about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorAlexander_Kabui <alexanderkabua@gmail.com>2026-10-08 10:45:58 +0300
committerAlexander_Kabui <alexanderkabua@gmail.com>2026-10-08 10:45:58 +0300
commita0c2c7d4bd9d7524103377afe2b18d38c9b8041d (patch)
tree26463c170562ffe4b7f026d3edb0e66fe548b11e /src
parent7a61c8d956cf4ef6ee69a5e0a06c74451079cc28 (diff)
parent54f138802bed2040531b3da3df0b30895d881bc8 (diff)
downloadgenenetwork4-a0c2c7d4bd9d7524103377afe2b18d38c9b8041d.tar.gz
Merge origin/main (54f1388): page, publish annotations, publications route.
Composes the new main above the search engine seam:

* src/routes/search.rs (page): parsed and threaded through the seam;
  the gn3 forwarder passes page to gn3 unsorted (sorted fetches the
  wide first page), the native engine takes the mset window. Ranked
  pages slice the sorted list, as before.
* src/routes/search.rs (add_publish_annotations): enrichment now
  fills locus and abbreviation in one PublishXRef/Phenotype lookup.
* src/search/mod.rs (Engine::search): page parameter; SearchHit
  gains abbreviation and pubmed_id (gn3's future fields flow via
  extra, as before).
* src/db.rs (LRS_PER_LOD): 4.604 — lod shifts accordingly everywhere.

All 34 test binaries green; parity replay and shape gates pass
against the dev index with the new lod constant (grading compares
identifier sets, not lod); page disjointness, abbreviation and locus
verified live (native engine, dev index, SQL_URI set).
Diffstat (limited to 'src')
-rw-r--r--src/db.rs187
-rw-r--r--src/lib.rs1
-rw-r--r--src/routes/groups.rs69
-rw-r--r--src/routes/mod.rs1
-rw-r--r--src/routes/publications.rs130
-rw-r--r--src/routes/search.rs70
-rw-r--r--src/routes/traits.rs2
-rw-r--r--src/search/gn3.rs2
-rw-r--r--src/search/mod.rs18
-rw-r--r--src/search/native.rs21
10 files changed, 400 insertions, 101 deletions
diff --git a/src/db.rs b/src/db.rs
index edc96e0..dca7c29 100644
--- a/src/db.rs
+++ b/src/db.rs
@@ -37,11 +37,11 @@ fn pool() -> Result<Pool, mysql::Error> {
     Ok(new_pool)
 }
 
-/// GeneNetwork stores LRS (likelihood ratio statistic); LOD = LRS / 4.61
-/// (4.61 ~ 2 ln 10). Every `lod` the API reports is derived with this one
-/// constant -- in SQL for rows read from the database, via `lod` for
+/// GeneNetwork stores LRS (likelihood ratio statistic); LOD = LRS / 4.604
+/// (the divisor GeneNetwork's RDF data uses; 2 ln 10 is 4.605). Every
+/// `lod` the API reports is derived with this one constant -- in SQL for rows read from the database, via `lod` for
 /// values that arrive as LRS (gn3 search hits).
-pub const LRS_PER_LOD: f64 = 4.61;
+pub const LRS_PER_LOD: f64 = 4.604;
 
 /// LOD score for an LRS value; see LRS_PER_LOD.
 pub fn lod(lrs: f64) -> f64 {
@@ -157,17 +157,25 @@ pub struct Group {
     pub public: Option<u8>,
     pub mapping_method_id: Option<String>,
     pub genetic_type: Option<String>,
+    /// The population category, e.g. "Reference Populations (replicate
+    /// average, SE, N)".
+    pub family: Option<String>,
+    /// The species' short name, e.g. "mouse" (as listed by /species).
+    pub species: Option<String>,
 }
 
-/// Mirrors GeneNetwork2's wqflask.api.router.get_groups_list (no
-/// species filter yet).
+/// Mirrors GeneNetwork2's wqflask.api.router.get_groups_list, plus the
+/// family and species name (filtering is done by the handler).
 pub fn get_all_groups() -> Result<Vec<Group>, mysql::Error> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.query_map(
-        "SELECT InbredSetId, SpeciesId, InbredSetName, Name, FullName, \
-                public, MappingMethodId, GeneticType \
-         FROM InbredSet ORDER BY Name ASC",
+        "SELECT InbredSet.InbredSetId, InbredSet.SpeciesId, InbredSet.InbredSetName, \
+                InbredSet.Name, InbredSet.FullName, InbredSet.public, \
+                InbredSet.MappingMethodId, InbredSet.GeneticType, InbredSet.Family, \
+                Species.Name \
+         FROM InbredSet LEFT JOIN Species ON Species.Id = InbredSet.SpeciesId \
+         ORDER BY InbredSet.Name ASC",
         |(
             id,
             species_id,
@@ -177,6 +185,8 @@ pub fn get_all_groups() -> Result<Vec<Group>, mysql::Error> {
             public,
             mapping_method_id,
             genetic_type,
+            family,
+            species,
         )| {
             Group {
                 id,
@@ -187,6 +197,8 @@ pub fn get_all_groups() -> Result<Vec<Group>, mysql::Error> {
                 public,
                 mapping_method_id,
                 genetic_type,
+                family,
+                species,
             }
         },
     )
@@ -353,20 +365,29 @@ pub struct TraitInfo {
     pub pages: Option<String>,
     pub month: Option<String>,
     pub year: Option<String>,
+    /// The PublishFreeze this trait belongs to, e.g. "BXDPublish".
+    pub dataset: Option<String>,
+    /// The trait's short name (Phenotype.Post_publication_abbreviation,
+    /// else Pre_publication_abbreviation), e.g. "5HT_MB_M".
+    pub abbreviation: Option<String>,
+    /// The trait's page on GeneNetwork's website.
+    pub url: Option<String>,
 }
 
-/// Fetch one published trait's metadata (see TraitInfo) within a
-/// group. Like get_group_trait_values, PublishXRef.Id alone isn't
-/// unique across groups, so group_id is required.
-pub fn get_group_trait_info(
-    group_id: u16,
-    trait_id: u32,
-) -> Result<Option<TraitInfo>, mysql::Error> {
-    let pool = pool()?;
-    let mut conn = pool.get_conn()?;
-    conn.exec_first(
-        format!(
-            "SELECT PublishXRef.Id AS Id, PublishXRef.PhenotypeId AS PhenotypeId, \
+/// Where GeneNetwork's website shows one trait; see TraitInfo::url.
+const GN_SHOW_TRAIT_URL: &str = "https://genenetwork.org/show_trait";
+
+/// A published trait's short name; shared by every query that reports
+/// or filters on it.
+const ABBREVIATION_SQL: &str =
+    "COALESCE(NULLIF(Phenotype.Post_publication_abbreviation, ''), Phenotype.Pre_publication_abbreviation)";
+
+/// The SELECT behind every TraitInfo row; callers add the WHERE
+/// `filter` and the ORDER BY. PublishFreeze is joined on InbredSetId,
+/// i.e. one dataset per group, as everywhere else in this API.
+fn trait_info_sql(filter: &str, order_by: &str) -> String {
+    format!(
+        "SELECT PublishXRef.Id AS Id, PublishXRef.PhenotypeId AS PhenotypeId, \
                 PublishXRef.PublicationId AS PublicationId, PublishXRef.mean AS Mean, \
                 PublishXRef.Locus AS Locus, PublishXRef.LRS AS Lrs, \
                 PublishXRef.LRS / {LRS_PER_LOD} AS Lod, \
@@ -378,11 +399,33 @@ pub fn get_group_trait_info(
                 Publication.PubMed_ID AS PubmedId, Publication.Title AS Title, \
                 Publication.Authors AS Authors, Publication.Journal AS Journal, \
                 Publication.Volume AS Volume, Publication.Pages AS Pages, \
-                Publication.Month AS Month, Publication.Year AS Year \
+                Publication.Month AS Month, Publication.Year AS Year, \
+                PublishFreeze.Name AS Dataset, \
+                {ABBREVIATION_SQL} AS Abbreviation, \
+                CONCAT('{GN_SHOW_TRAIT_URL}?trait_id=', PublishXRef.Id, '&dataset=', \
+                       PublishFreeze.Name) AS Url \
          FROM PublishXRef \
          LEFT JOIN Phenotype ON Phenotype.Id = PublishXRef.PhenotypeId \
          LEFT JOIN Publication ON Publication.Id = PublishXRef.PublicationId \
-         WHERE PublishXRef.InbredSetId = :group_id AND PublishXRef.Id = :trait_id"
+         LEFT JOIN PublishFreeze ON PublishFreeze.InbredSetId = PublishXRef.InbredSetId \
+         WHERE {filter} \
+         ORDER BY {order_by}"
+    )
+}
+
+/// Fetch one published trait's metadata (see TraitInfo) within a
+/// group. Like get_group_trait_values, PublishXRef.Id alone isn't
+/// unique across groups, so group_id is required.
+pub fn get_group_trait_info(
+    group_id: u16,
+    trait_id: u32,
+) -> Result<Option<TraitInfo>, mysql::Error> {
+    let pool = pool()?;
+    let mut conn = pool.get_conn()?;
+    conn.exec_first(
+        trait_info_sql(
+            "PublishXRef.InbredSetId = :group_id AND PublishXRef.Id = :trait_id",
+            "PublishXRef.Id",
         ),
         mysql::params! { "group_id" => group_id, "trait_id" => trait_id },
     )
@@ -394,46 +437,76 @@ pub fn get_group_traits(group_id: u16) -> Result<Vec<TraitInfo>, mysql::Error> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec(
-        format!(
-            "SELECT PublishXRef.Id AS Id, PublishXRef.PhenotypeId AS PhenotypeId, \
-                PublishXRef.PublicationId AS PublicationId, PublishXRef.mean AS Mean, \
-                PublishXRef.Locus AS Locus, PublishXRef.LRS AS Lrs, \
-                PublishXRef.LRS / {LRS_PER_LOD} AS Lod, \
-                PublishXRef.additive AS Additive, PublishXRef.NSamples AS Nsamples, \
-                Phenotype.Pre_publication_description AS PrePublicationDescription, \
-                Phenotype.Post_publication_description AS PostPublicationDescription, \
-                Phenotype.Original_description AS OriginalDescription, \
-                Phenotype.Units AS Units, \
-                Publication.PubMed_ID AS PubmedId, Publication.Title AS Title, \
-                Publication.Authors AS Authors, Publication.Journal AS Journal, \
-                Publication.Volume AS Volume, Publication.Pages AS Pages, \
-                Publication.Month AS Month, Publication.Year AS Year \
-         FROM PublishXRef \
-         LEFT JOIN Phenotype ON Phenotype.Id = PublishXRef.PhenotypeId \
-         LEFT JOIN Publication ON Publication.Id = PublishXRef.PublicationId \
-         WHERE PublishXRef.InbredSetId = :group_id \
-         ORDER BY PublishXRef.Id"
-        ),
+        trait_info_sql("PublishXRef.InbredSetId = :group_id", "PublishXRef.Id"),
         mysql::params! { "group_id" => group_id },
     )
 }
 
-/// Peak marker names for published traits, keyed by (dataset name,
-/// PublishXRef.Id), in one query. Traits with no recorded Locus are
-/// absent from the result.
-pub fn get_publish_loci(
+/// The traits of a group whose short name (either the post- or the
+/// pre-publication abbreviation) is `abbreviation`.
+pub fn get_group_traits_by_abbreviation(
+    group_id: u16,
+    abbreviation: &str,
+) -> Result<Vec<TraitInfo>, mysql::Error> {
+    let pool = pool()?;
+    let mut conn = pool.get_conn()?;
+    conn.exec(
+        trait_info_sql(
+            "PublishXRef.InbredSetId = :group_id \
+             AND (Phenotype.Post_publication_abbreviation = :abbreviation \
+                  OR Phenotype.Pre_publication_abbreviation = :abbreviation)",
+            "PublishXRef.Id",
+        ),
+        mysql::params! { "group_id" => group_id, "abbreviation" => abbreviation },
+    )
+}
+
+/// Every published trait (across groups) reported in the publication
+/// with this PubMed id, or None when no such publication exists.
+pub fn get_publication_traits(pubmed_id: u32) -> Result<Option<Vec<TraitInfo>>, mysql::Error> {
+    let pool = pool()?;
+    let mut conn = pool.get_conn()?;
+    let exists: Option<u32> = conn.exec_first(
+        "SELECT Id FROM Publication WHERE PubMed_ID = :pubmed_id LIMIT 1",
+        mysql::params! { "pubmed_id" => pubmed_id },
+    )?;
+    if exists.is_none() {
+        return Ok(None);
+    }
+    conn.exec(
+        trait_info_sql(
+            "Publication.PubMed_ID = :pubmed_id",
+            "PublishFreeze.Name, PublishXRef.Id",
+        ),
+        mysql::params! { "pubmed_id" => pubmed_id },
+    )
+    .map(Some)
+}
+
+/// What search hits are annotated with from PublishXRef/Phenotype
+/// (gn3's hits carry neither).
+#[derive(Default, Clone)]
+pub struct PublishAnnotation {
+    pub locus: Option<String>,
+    pub abbreviation: Option<String>,
+}
+
+/// Peak marker names and short names for published traits, keyed by
+/// (dataset name, PublishXRef.Id), in one query. Traits that don't
+/// exist are absent from the result.
+pub fn get_publish_annotations(
     keys: &[(String, u32)],
-) -> Result<std::collections::HashMap<(String, u32), String>, mysql::Error> {
+) -> Result<std::collections::HashMap<(String, u32), PublishAnnotation>, mysql::Error> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     let pairs = vec!["(?, ?)"; keys.len()].join(", ");
-    let rows: Vec<(String, u32, String)> = conn.exec(
+    let rows: Vec<(String, u32, Option<String>, Option<String>)> = conn.exec(
         format!(
-            "SELECT PublishFreeze.Name, PublishXRef.Id, PublishXRef.Locus \
+            "SELECT PublishFreeze.Name, PublishXRef.Id, PublishXRef.Locus, {ABBREVIATION_SQL} \
              FROM PublishXRef \
              JOIN PublishFreeze ON PublishFreeze.InbredSetId = PublishXRef.InbredSetId \
-             WHERE PublishXRef.Locus IS NOT NULL \
-               AND (PublishFreeze.Name, PublishXRef.Id) IN ({pairs})"
+             LEFT JOIN Phenotype ON Phenotype.Id = PublishXRef.PhenotypeId \
+             WHERE (PublishFreeze.Name, PublishXRef.Id) IN ({pairs})"
         ),
         keys.iter()
             .flat_map(|(dataset, id)| [mysql::Value::from(dataset), mysql::Value::from(*id)])
@@ -441,7 +514,15 @@ pub fn get_publish_loci(
     )?;
     Ok(rows
         .into_iter()
-        .map(|(dataset, id, locus)| ((dataset, id), locus))
+        .map(|(dataset, id, locus, abbreviation)| {
+            (
+                (dataset, id),
+                PublishAnnotation {
+                    locus,
+                    abbreviation,
+                },
+            )
+        })
         .collect())
 }
 
diff --git a/src/lib.rs b/src/lib.rs
index 672708d..84e3b37 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -72,6 +72,7 @@ pub fn app() -> Router {
         .routes(routes!(routes::traits::traits))
         .routes(routes!(routes::traits::trait_info))
         .routes(routes!(routes::traits::trait_values))
+        .routes(routes!(routes::publications::publication_traits))
         .routes(routes!(routes::search::search))
         .routes(routes!(routes::correlation::correlation));
     // Only registered -- so only ever reachable, and only ever
diff --git a/src/routes/groups.rs b/src/routes/groups.rs
index 12652ec..90e22f7 100644
--- a/src/routes/groups.rs
+++ b/src/routes/groups.rs
@@ -4,6 +4,7 @@
 use axum::Json;
 use axum::extract::{Extension, Path, Query};
 use axum::http::StatusCode;
+use serde::Deserialize;
 use tower_http::request_id::RequestId;
 
 use crate::auth::AuthToken;
@@ -11,14 +12,35 @@ use crate::db;
 use crate::error::{ApiError, Unauthorized};
 use crate::request_id_string;
 
-#[utoipa::path(get, path = "/groups", summary = "List all groups (populations; InbredSet rows)", responses(
-    (status = 200, description = "All groups (InbredSet rows) in the database", body = Vec<db::Group>),
+/// Query parameters for `GET /groups`; all optional, combined with AND.
+#[derive(Deserialize, utoipa::IntoParams)]
+pub struct GroupsParams {
+    /// Keep groups whose family contains this text, case-insensitively,
+    /// e.g. "Reference Populations".
+    pub family: Option<String>,
+    /// Keep groups of this species, by the short name /species lists
+    /// (case-insensitive), e.g. "mouse".
+    pub species: Option<String>,
+    /// Keep groups whose name, display name or full name contains this
+    /// text, case-insensitively, e.g. "alzheimer".
+    pub q: Option<String>,
+}
+
+fn contains_ci(field: &Option<String>, needle: &str) -> bool {
+    field
+        .as_deref()
+        .is_some_and(|f| f.to_lowercase().contains(&needle.to_lowercase()))
+}
+
+#[utoipa::path(get, path = "/groups", summary = "List all groups (populations; InbredSet rows), optionally filtered", params(GroupsParams), responses(
+    (status = 200, description = "The groups (InbredSet rows), with family and species name", body = Vec<db::Group>),
     Unauthorized,
     (status = 500, description = "Database error", body = ApiError)
 ))]
 pub async fn groups(
     Extension(request_id): Extension<RequestId>,
     _token: AuthToken,
+    Query(params): Query<GroupsParams>,
 ) -> Result<Json<Vec<db::Group>>, ApiError> {
     let rid = request_id_string(&request_id);
     tokio::task::spawn_blocking(db::get_all_groups)
@@ -33,7 +55,27 @@ pub async fn groups(
             )
             .with_request_id(rid.clone())
         })?
-        .map(Json)
+        .map(|groups| {
+            Json(
+                groups
+                    .into_iter()
+                    .filter(|g| params.family.as_ref().is_none_or(|f| contains_ci(&g.family, f)))
+                    .filter(|g| {
+                        params
+                            .species
+                            .as_ref()
+                            .is_none_or(|s| g.species.as_deref().is_some_and(|n| n.eq_ignore_ascii_case(s)))
+                    })
+                    .filter(|g| {
+                        params.q.as_ref().is_none_or(|q| {
+                            contains_ci(&Some(g.name.clone()), q)
+                                || contains_ci(&g.display_name, q)
+                                || contains_ci(&g.full_name, q)
+                        })
+                    })
+                    .collect(),
+            )
+        })
         .map_err(|e| {
             ApiError::new(
                 StatusCode::INTERNAL_SERVER_ERROR,
@@ -320,8 +362,17 @@ pub async fn group_trait_info(
         })
 }
 
+/// Query parameters for `GET /groups/{group}/traits`.
+#[derive(Deserialize, utoipa::IntoParams)]
+pub struct GroupTraitsParams {
+    /// Only the traits with this short name (abbreviation), e.g.
+    /// "5HT_MB_M" or "3NP_Tox".
+    pub abbreviation: Option<String>,
+}
+
 #[utoipa::path(get, path = "/groups/{group}/traits", summary = "List the published (phenotype) traits belonging to a group", params(
-    ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id")
+    ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id"),
+    GroupTraitsParams
 ), responses(
     (status = 200, description = "The published traits belonging to the group", body = Vec<db::TraitInfo>),
     Unauthorized,
@@ -332,13 +383,17 @@ pub async fn group_traits(
     Extension(request_id): Extension<RequestId>,
     Path(group): Path<String>,
     _token: AuthToken,
+    Query(params): Query<GroupTraitsParams>,
 ) -> Result<Json<Vec<db::TraitInfo>>, ApiError> {
     let rid = request_id_string(&request_id);
     let not_found_name = group.clone();
     tokio::task::spawn_blocking(move || {
-        db::get_group_by_name(&group).and_then(|group| match group {
-            Some(group) => db::get_group_traits(group.id).map(Some),
-            None => Ok(None),
+        db::get_group_by_name(&group).and_then(|group| match (group, params.abbreviation) {
+            (Some(group), Some(abbreviation)) => {
+                db::get_group_traits_by_abbreviation(group.id, &abbreviation).map(Some)
+            }
+            (Some(group), None) => db::get_group_traits(group.id).map(Some),
+            (None, _) => Ok(None),
         })
     })
     .await
diff --git a/src/routes/mod.rs b/src/routes/mod.rs
index fd1ef4a..0362206 100644
--- a/src/routes/mod.rs
+++ b/src/routes/mod.rs
@@ -7,6 +7,7 @@ pub mod correlation;
 pub mod datasets;
 pub mod dev;
 pub mod groups;
+pub mod publications;
 pub mod search;
 pub mod species;
 pub mod traits;
diff --git a/src/routes/publications.rs b/src/routes/publications.rs
new file mode 100644
index 0000000..2f6fab4
--- /dev/null
+++ b/src/routes/publications.rs
@@ -0,0 +1,130 @@
+//! Publications domain endpoint: which traits a paper reports.
+
+use axum::Json;
+use axum::extract::{Extension, Path};
+use axum::http::StatusCode;
+use std::collections::HashMap;
+use tower_http::request_id::RequestId;
+
+use crate::auth::AuthToken;
+use crate::config::Config;
+use crate::db;
+use crate::error::{ApiError, Unauthorized};
+use crate::request_id_string;
+use crate::routes::traits::is_authorised;
+
+enum PublicationTraits {
+    NotFound,
+    Found(Vec<db::TraitInfo>),
+}
+
+enum LookupError {
+    Db(mysql::Error),
+    Auth(String),
+}
+
+impl From<mysql::Error> for LookupError {
+    fn from(e: mysql::Error) -> Self {
+        LookupError::Db(e)
+    }
+}
+
+/// The publication's traits, minus those of datasets the caller may
+/// not view (each dataset is checked once, as in GET /traits/{dataset}).
+fn get_publication_traits_result(
+    pubmed_id: u32,
+    auth_server_url: &str,
+    token: &AuthToken,
+) -> Result<PublicationTraits, LookupError> {
+    let Some(traits) = db::get_publication_traits(pubmed_id)? else {
+        return Ok(PublicationTraits::NotFound);
+    };
+    let mut readable: HashMap<String, bool> = HashMap::new();
+    let mut visible = Vec::new();
+    for info in traits {
+        let Some(dataset) = info.dataset.clone() else {
+            continue;
+        };
+        if !readable.contains_key(&dataset) {
+            let allowed = match db::get_publish_freeze_by_name(&dataset)? {
+                Some(pf) => is_authorised(
+                    auth_server_url,
+                    token,
+                    &pf.name,
+                    None,
+                    pf.public,
+                    pf.confidentiality,
+                    &pf.create_time,
+                )
+                .map_err(LookupError::Auth)?,
+                None => false,
+            };
+            readable.insert(dataset.clone(), allowed);
+        }
+        if readable[&dataset] {
+            visible.push(info);
+        }
+    }
+    Ok(PublicationTraits::Found(visible))
+}
+
+#[utoipa::path(get, path = "/publications/{pubmed_id}/traits", summary = "List the published traits a publication reports", description = "Every published (phenotype) trait, across groups and datasets, whose publication has this PubMed id. Traits of datasets the caller isn't authorized to view are left out.", params(
+    ("pubmed_id" = u32, Path, description = "The publication's PubMed id, e.g. 31634382")
+), responses(
+    (status = 200, description = "The publication's traits (possibly none)", body = Vec<db::TraitInfo>),
+    Unauthorized,
+    (status = 404, description = "No publication with this PubMed id", body = ApiError),
+    (status = 500, description = "Database error", body = ApiError),
+    (status = 502, description = "Could not reach gn-auth to check authorization", body = ApiError)
+))]
+pub async fn publication_traits(
+    Extension(request_id): Extension<RequestId>,
+    Path(pubmed_id): Path<u32>,
+    token: AuthToken,
+) -> Result<Json<Vec<db::TraitInfo>>, ApiError> {
+    let rid = request_id_string(&request_id);
+    let auth_server_url = Config::load().auth_server_url.clone();
+    tokio::task::spawn_blocking(move || {
+        get_publication_traits_result(pubmed_id, &auth_server_url, &token)
+    })
+    .await
+    .map_err(|e| {
+        ApiError::new(
+            StatusCode::INTERNAL_SERVER_ERROR,
+            "internal_error",
+            "Internal error",
+            e.to_string(),
+            "publication_traits",
+        )
+        .with_request_id(rid.clone())
+    })?
+    .map_err(|e| match e {
+        LookupError::Db(e) => ApiError::new(
+            StatusCode::INTERNAL_SERVER_ERROR,
+            "database_error",
+            "Database error",
+            e.to_string(),
+            "publication_traits",
+        )
+        .with_request_id(rid.clone()),
+        LookupError::Auth(e) => ApiError::new(
+            StatusCode::BAD_GATEWAY,
+            "auth_server_error",
+            "Could not check authorization",
+            e,
+            "publication_traits",
+        )
+        .with_request_id(rid.clone()),
+    })
+    .and_then(|lookup| match lookup {
+        PublicationTraits::Found(traits) => Ok(Json(traits)),
+        PublicationTraits::NotFound => Err(ApiError::new(
+            StatusCode::NOT_FOUND,
+            "publication_not_found",
+            "Publication not found",
+            format!("No publication with PubMed id {pubmed_id}."),
+            "publication_traits",
+        )
+        .with_request_id(rid)),
+    })
+}
diff --git a/src/routes/search.rs b/src/routes/search.rs
index fa2a853..7dbaaa9 100644
--- a/src/routes/search.rs
+++ b/src/routes/search.rs
@@ -3,9 +3,10 @@
 //! Phase A (gn4-api-foundation.gmi "Pilot: search"): proxies gn3's
 //! /api/search (xapian-backed) and re-wraps the hits in the
 //! descriptive envelope. gn3's hit objects pass through untouched;
-//! gn4 contributes boundary validation and the contract, plus three
-//! additions gn3's hits lack: `lod` (derived from `lrs`), `locus` (the
-//! peak marker's name, looked up in PublishXRef) and `sort`/`order`.
+//! gn4 contributes boundary validation and the contract, plus what
+//! gn3's hits lack: `lod` (derived from `lrs`), `locus` and
+//! `abbreviation` (looked up in PublishXRef/Phenotype), and
+//! `sort`/`order`/`page`.
 //!
 //! The backend itself lives behind the search engine seam (see
 //! `crate::search`); this handler validates parameters, delegates to
@@ -45,6 +46,10 @@ pub struct SearchParams {
     pub sort: Option<String>,
     /// "desc" (default) or "asc"; only meaningful with `sort`.
     pub order: Option<String>,
+    /// Which page of `limit` hits to return (default 1). With `sort`,
+    /// pages are taken from the ranked list, so they reach past the
+    /// first `limit` best hits (up to the first 1000 matches).
+    pub page: Option<u64>,
 }
 
 /// Map a [`SearchError`] onto the `/search` error contract: one
@@ -117,35 +122,30 @@ fn sort_by_lrs(hits: &mut [SearchHit], ascending: bool) {
     });
 }
 
-/// Fills in `locus` for phenotype hits from one PublishXRef lookup.
-/// A database failure leaves `locus` null rather than failing the
-/// search: the hits are still correct, and the marker is also on
+/// Fills in `locus` and `abbreviation` for phenotype hits from one
+/// PublishXRef lookup. A database failure leaves them null rather than
+/// failing the search: the hits are still correct, and both are also on
 /// GET /traits/{dataset}/{trait}.
-async fn add_loci(hits: &mut [SearchHit]) {
-    let keys: Vec<(String, u32)> = hits
-        .iter()
-        .filter_map(|hit| {
-            let dataset = hit.dataset.as_deref().filter(|d| d.ends_with("Publish"))?;
-            Some((dataset.to_string(), hit.name.as_deref()?.parse().ok()?))
-        })
-        .collect();
+async fn add_publish_annotations(hits: &mut [SearchHit]) {
+    let key = |hit: &SearchHit| -> Option<(String, u32)> {
+        let dataset = hit.dataset.as_deref().filter(|d| d.ends_with("Publish"))?;
+        Some((dataset.to_string(), hit.name.as_deref()?.parse().ok()?))
+    };
+    let keys: Vec<(String, u32)> = hits.iter().filter_map(key).collect();
     if keys.is_empty() {
         return;
     }
-    let loci: HashMap<(String, u32), String> =
-        match tokio::task::spawn_blocking(move || db::get_publish_loci(&keys)).await {
-            Ok(Ok(loci)) => loci,
+    let annotations: HashMap<(String, u32), db::PublishAnnotation> =
+        match tokio::task::spawn_blocking(move || db::get_publish_annotations(&keys)).await {
+            Ok(Ok(annotations)) => annotations,
             _ => return,
         };
     for hit in hits {
-        let key = (
-            hit.dataset.clone().unwrap_or_default(),
-            hit.name
-                .as_deref()
-                .and_then(|n| n.parse().ok())
-                .unwrap_or(0),
-        );
-        hit.locus = loci.get(&key).cloned();
+        let annotation = key(hit)
+            .and_then(|key| annotations.get(&key).cloned())
+            .unwrap_or_default();
+        hit.locus = annotation.locus;
+        hit.abbreviation = annotation.abbreviation;
     }
 }
 
@@ -201,13 +201,19 @@ pub async fn search(
         Some("asc") => true,
         Some(_) => return Err(bad_request("order must be \"asc\" or \"desc\"")),
     };
-    let fetch_limit = if params.sort.is_some() {
-        SORT_FETCH_LIMIT
+    let page = params.page.unwrap_or(1);
+    if page < 1 {
+        return Err(bad_request("page must be at least 1"));
+    }
+    // Unsorted: gn3 pages for us. Sorted: gn3 is asked for one wide
+    // first page and the pages are taken from the ranked list.
+    let (fetch_limit, gn3_page) = if params.sort.is_some() {
+        (SORT_FETCH_LIMIT, 1)
     } else {
-        limit
+        (limit, page)
     };
 
-    let mut hits = search::search(q, search_type, fetch_limit)
+    let mut hits = search::search(q, search_type, fetch_limit, gn3_page)
         .await
         .map_err(|e| engine_error(e, rid))?;
     for hit in &mut hits {
@@ -215,9 +221,13 @@ pub async fn search(
     }
     if params.sort.is_some() {
         sort_by_lrs(&mut hits, ascending);
+        hits = hits
+            .into_iter()
+            .skip((page - 1).saturating_mul(limit) as usize)
+            .collect();
     }
     hits.truncate(limit as usize);
-    add_loci(&mut hits).await;
+    add_publish_annotations(&mut hits).await;
 
     Ok(Json(Envelope::of(hits)))
 }
diff --git a/src/routes/traits.rs b/src/routes/traits.rs
index fea6eb3..97dfbf5 100644
--- a/src/routes/traits.rs
+++ b/src/routes/traits.rs
@@ -59,7 +59,7 @@ impl From<mysql::Error> for TraitAuthError {
 /// Shared by all three handlers below so the ProbeSet and Publish
 /// branches of each only differ in which db:: functions they call, not
 /// in how they're gated.
-fn is_authorised(
+pub(crate) fn is_authorised(
     auth_server_url: &str,
     token: &AuthToken,
     dataset_name: &str,
diff --git a/src/search/gn3.rs b/src/search/gn3.rs
index 7ab3f5d..58655cb 100644
--- a/src/search/gn3.rs
+++ b/src/search/gn3.rs
@@ -93,6 +93,7 @@ impl Engine for Gn3 {
         q: &str,
         type_: &str,
         limit: u64,
+        page: u64,
     ) -> Result<Vec<SearchHit>, SearchError> {
         let gn3_url = crate::config::Config::load().gn3_url;
         let url = url::Url::parse_with_params(
@@ -101,6 +102,7 @@ impl Engine for Gn3 {
                 ("query", q),
                 ("type", type_),
                 ("per_page", &limit.to_string()),
+                ("page", &page.to_string()),
             ],
         )
         .map_err(|e| {
diff --git a/src/search/mod.rs b/src/search/mod.rs
index 223b5a3..addd7ac 100644
--- a/src/search/mod.rs
+++ b/src/search/mod.rs
@@ -96,10 +96,15 @@ pub mod native;
 /// default, the native xapian engine when `SEARCH_ENGINE=native`
 /// (PORT-DESIGN §6 wiring). Selecting the engine is a config change,
 /// so flipping back never needs a rebuild or a redeploy.
-pub async fn search(q: &str, type_: &str, limit: u64) -> Result<Vec<SearchHit>, SearchError> {
+pub async fn search(
+    q: &str,
+    type_: &str,
+    limit: u64,
+    page: u64,
+) -> Result<Vec<SearchHit>, SearchError> {
     match crate::config::Config::load().search_engine.as_str() {
-        "native" => native::Native.search(q, type_, limit).await,
-        _ => gn3::Gn3.search(q, type_, limit).await,
+        "native" => native::Native.search(q, type_, limit, page).await,
+        _ => gn3::Gn3.search(q, type_, limit, page).await,
     }
 }
 
@@ -122,15 +127,19 @@ pub struct SearchHit {
     pub mean: Option<f64>,
     pub additive: Option<f64>,
     pub lrs: Option<f64>,
-    /// LOD score, LRS / 4.61; the route computes it from `lrs`.
+    /// LOD score, LRS / `db::LRS_PER_LOD` (4.604); the route computes
+    /// it from `lrs`.
     pub lod: Option<f64>,
     /// Name of the peak marker (a Geno.Name such as "rsm10000012461"),
     /// looked up in PublishXRef for phenotype hits; null for other
     /// hits, or when the database is unavailable.
     pub locus: Option<String>,
+    /// The trait's short name (e.g. "5HT_MB_M"), looked up like `locus`.
+    pub abbreviation: Option<String>,
     pub geno_chr: Option<String>,
     pub geno_mb: Option<f64>,
     pub inbredsetcode: Option<String>,
+    pub pubmed_id: Option<u32>,
     #[serde(flatten)]
     #[schema(value_type = Option<std::collections::BTreeMap<String, String>>)]
     pub extra: std::collections::BTreeMap<String, serde_json::Value>,
@@ -187,5 +196,6 @@ pub trait Engine {
         q: &str,
         type_: &str,
         limit: u64,
+        page: u64,
     ) -> impl Future<Output = Result<Vec<SearchHit>, SearchError>> + Send;
 }
diff --git a/src/search/native.rs b/src/search/native.rs
index 6e5dab4..4bfe60b 100644
--- a/src/search/native.rs
+++ b/src/search/native.rs
@@ -407,20 +407,26 @@ impl Engine for Native {
         q: &str,
         type_: &str,
         limit: u64,
+        page: u64,
     ) -> Result<Vec<SearchHit>, SearchError> {
         // xapian calls are synchronous C++ work: keep them off the
         // async runtime's workers (the house pattern for blocking
         // calls, cf. every spawn_blocking handler in src/routes).
         let query = q.to_string();
         let search_type = type_.to_string();
-        tokio::task::spawn_blocking(move || search_blocking(&query, &search_type, limit))
+        tokio::task::spawn_blocking(move || search_blocking(&query, &search_type, limit, page))
             .await
             .map_err(|e| SearchError::Internal(format!("native search task failed to join: {e}")))?
     }
 }
 
 /// The synchronous search path: parse, open, filter, retrieve, map.
-fn search_blocking(q: &str, type_: &str, limit: u64) -> Result<Vec<SearchHit>, SearchError> {
+fn search_blocking(
+    q: &str,
+    type_: &str,
+    limit: u64,
+    page: u64,
+) -> Result<Vec<SearchHit>, SearchError> {
     // 1. Parse first (search.py:291 parses before :296 opens the
     //    index), through the checked-parse API: a malformed query is a
     //    typed error, not a panic (the fork's parse_query_checked).
@@ -480,11 +486,14 @@ fn search_blocking(q: &str, type_: &str, limit: u64) -> Result<Vec<SearchHit>, S
     );
 
     // 5. Retrieve the full match set — the forwarded `limit` is
-    //    deliberately not applied here (per-page invariant, §5).
-    let _ = limit;
+    //    deliberately not applied to the fetch size (per-page
+    //    invariant, §5); `page` shifts the retrieval window for
+    //    unsorted paging, exactly as gn3's per_page/page pair does.
+    //    Sorted calls pass page=1 (the route ranks and slices).
+    let first_item = (page.saturating_sub(1).saturating_mul(limit)).min(u32::MAX as u64) as u32;
     let mut enquire = Enquire::new(&db);
     enquire.set_query(&filtered, None);
-    let mset = enquire.mset(0, FULL_MATCH_SET_MAX_ITEMS, None, None);
+    let mset = enquire.mset(first_item, FULL_MATCH_SET_MAX_ITEMS, None, None);
 
     // 6. Map each hit's stored doc data (the indexer's JSON, the
     //    schema gn3 serves verbatim: json.loads(document.get_data()),
@@ -933,7 +942,7 @@ mod tests {
         let rt = tokio::runtime::Builder::new_current_thread()
             .build()
             .expect("guard test runtime");
-        rt.block_on(Native.search(query, "phenotype", 5))
+        rt.block_on(Native.search(query, "phenotype", 5, 1))
     }
 
     /// The index-open guards, without touching a real index.