about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorAlexander_Kabui <alexanderkabua@gmail.com>2026-10-07 21:01:40 +0300
committerAlexander_Kabui <alexanderkabua@gmail.com>2026-10-07 21:01:40 +0300
commit85b63abcfdbae235d292a6de4bd47ffe6ba6dafd (patch)
tree8b39f26fad90eaa27751fd061ab1cbc91ae95b08 /src
parentb68531c40d91cadfd868e4b65ff92989ffd4fb27 (diff)
parente912c87deaf220fd5fce1299d669e8fa992b5338 (diff)
downloadgenenetwork4-85b63abcfdbae235d292a6de4bd47ffe6ba6dafd.tar.gz
Merge origin/main (e912c87: /search gains lod, locus, sort/order) into
native-search-engine.

Resolution: his route-level additions compose above the engine seam —
the handler now validates sort/order, asks the engine for
SORT_FETCH_LIMIT (1000) when ranking, maps SearchError via the seam's
engine_error, then computes lod, sorts, truncates to limit and fills
loci; lod/locus join SearchHit in src/search/mod.rs. His tests pass
through the seam.

KNOWN at this commit: the parity floor is BLOCKED (36 shapes) — the
route's new truncate(limit) exposes that route-level full-set grading
was a calibration-stub artifact (real gn3 caps at per_page; the stub
ignored it). Harness fix queued: set-equality moves to engine level,
status + top-10 stay route level. Landed together with that fix.
Diffstat (limited to 'src')
-rw-r--r--src/db.rs189
-rw-r--r--src/lib.rs1
-rw-r--r--src/routes/groups.rs56
-rw-r--r--src/routes/search.rs106
-rw-r--r--src/search/mod.rs6
5 files changed, 344 insertions, 14 deletions
diff --git a/src/db.rs b/src/db.rs
index afc8f82..edc96e0 100644
--- a/src/db.rs
+++ b/src/db.rs
@@ -37,6 +37,17 @@ 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
+/// values that arrive as LRS (gn3 search hits).
+pub const LRS_PER_LOD: f64 = 4.61;
+
+/// LOD score for an LRS value; see LRS_PER_LOD.
+pub fn lod(lrs: f64) -> f64 {
+    lrs / LRS_PER_LOD
+}
+
 #[derive(Serialize, utoipa::ToSchema)]
 pub struct Species {
     pub name: String,
@@ -327,6 +338,7 @@ pub struct TraitInfo {
     pub mean: Option<f64>,
     pub locus: Option<String>,
     pub lrs: Option<f64>,
+    pub lod: Option<f64>,
     pub additive: Option<f64>,
     pub nsamples: Option<i32>,
     pub pre_publication_description: Option<String>,
@@ -353,9 +365,11 @@ pub fn get_group_trait_info(
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec_first(
-        "SELECT PublishXRef.Id AS Id, PublishXRef.PhenotypeId AS PhenotypeId, \
+        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, \
@@ -368,7 +382,8 @@ pub fn get_group_trait_info(
          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",
+         WHERE PublishXRef.InbredSetId = :group_id AND PublishXRef.Id = :trait_id"
+        ),
         mysql::params! { "group_id" => group_id, "trait_id" => trait_id },
     )
 }
@@ -379,9 +394,11 @@ pub fn get_group_traits(group_id: u16) -> Result<Vec<TraitInfo>, mysql::Error> {
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec(
-        "SELECT PublishXRef.Id AS Id, PublishXRef.PhenotypeId AS PhenotypeId, \
+        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, \
@@ -395,11 +412,39 @@ pub fn get_group_traits(group_id: u16) -> Result<Vec<TraitInfo>, mysql::Error> {
          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",
+         ORDER BY 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(
+    keys: &[(String, u32)],
+) -> Result<std::collections::HashMap<(String, u32), String>, 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(
+        format!(
+            "SELECT PublishFreeze.Name, PublishXRef.Id, PublishXRef.Locus \
+             FROM PublishXRef \
+             JOIN PublishFreeze ON PublishFreeze.InbredSetId = PublishXRef.InbredSetId \
+             WHERE PublishXRef.Locus IS NOT NULL \
+               AND (PublishFreeze.Name, PublishXRef.Id) IN ({pairs})"
+        ),
+        keys.iter()
+            .flat_map(|(dataset, id)| [mysql::Value::from(dataset), mysql::Value::from(*id)])
+            .collect::<Vec<_>>(),
+    )?;
+    Ok(rows
+        .into_iter()
+        .map(|(dataset, id, locus)| ((dataset, id), locus))
+        .collect())
+}
+
 /// One expression (ProbeSet) dataset: a ProbeSetFreeze row, matching
 /// the shape of GeneNetwork2's GET /api/v_pre1/datasets/<group_name>
 /// response (field names there: Id, ProbeFreezeId, AvgID,
@@ -466,6 +511,104 @@ pub fn get_group_datasets(group_id: u16) -> Result<Vec<Dataset>, mysql::Error> {
     )
 }
 
+/// One strain's case-attribute values within a group: extra per-strain
+/// metadata (e.g. age, sex, treatment) beyond genotype/phenotype data,
+/// matching GeneNetwork3's gn3.api.case_attributes (genenetwork4's own
+/// read-only equivalent of its /case-attribute/{id}/values -- the only
+/// place this concept exists; neither GeneNetwork2 nor gn-guile expose
+/// it). Keyed by attribute name rather than a fixed field set, since
+/// which attributes exist is itself per-group data (see CaseAttribute
+/// below).
+#[derive(Serialize, utoipa::ToSchema)]
+pub struct StrainCaseAttributes {
+    pub strain: String,
+    pub case_attributes: std::collections::HashMap<String, String>,
+}
+
+/// A group's case attributes: every attribute name defined for it
+/// (`CaseAttribute.Name`) and, for each strain that has at least one
+/// value set, that strain's values -- combined into one response
+/// rather than GN3's separate .../names and .../values endpoints,
+/// since neither list is large enough on its own to need splitting.
+#[derive(Serialize, utoipa::ToSchema)]
+pub struct CaseAttributes {
+    pub names: Vec<String>,
+    pub values: Vec<StrainCaseAttributes>,
+}
+
+/// Fetch every case-attribute name defined for a group, matching
+/// GeneNetwork3's gn3.api.case_attributes.__case_attribute_labels_by_inbred_set__
+/// (trimmed to just the name -- Description isn't used by genenetwork4
+/// yet, and CaseAttributeId/InbredSetId are already implied by this
+/// being scoped to one group).
+fn get_group_case_attribute_names(group_id: u16) -> Result<Vec<String>, mysql::Error> {
+    let pool = pool()?;
+    let mut conn = pool.get_conn()?;
+    conn.exec(
+        "SELECT Name FROM CaseAttribute WHERE InbredSetId = :group_id ORDER BY Name",
+        mysql::params! { "group_id" => group_id },
+    )
+}
+
+/// Fetch every strain's case-attribute values for a group, based on
+/// GeneNetwork3's gn3.api.case_attributes.__case_attribute_values_by_inbred_set__,
+/// fixed to also join on InbredSetId: `CaseAttributeId` alone is not
+/// unique across groups (it's a shared vocabulary -- e.g. id 37 means
+/// "Epoch" for dozens of unrelated groups at once; the table's real
+/// key is the pair `(InbredSetId, CaseAttributeId)`), so GN3's version
+/// of this join -- `ON ca.CaseAttributeId=caxrn.CaseAttributeId`,
+/// `WHERE caxrn.InbredSetId=...` with no matching condition on `ca`'s
+/// own InbredSetId -- pulls in every other group's attribute that
+/// happens to share a `CaseAttributeId` number, not just this group's.
+/// Confirmed against this database: without the extra join condition
+/// below, BXD's (group 1) result included a spurious "Strain" = "Live"
+/// attribute that belongs to a different, unrelated group entirely.
+/// Rows come back one (strain, attribute, value) triple at a time,
+/// ordered by strain name, so adjacent rows for the same strain are
+/// folded into one `StrainCaseAttributes` as they're read rather than
+/// grouped afterwards.
+fn get_group_case_attribute_values(group_id: u16) -> Result<Vec<StrainCaseAttributes>, mysql::Error> {
+    let pool = pool()?;
+    let mut conn = pool.get_conn()?;
+    let rows: Vec<(String, String, String)> = conn.exec(
+        "SELECT s.Name, ca.Name, caxrn.Value \
+         FROM CaseAttribute AS ca \
+         JOIN CaseAttributeXRefNew AS caxrn \
+                ON ca.CaseAttributeId = caxrn.CaseAttributeId \
+                AND ca.InbredSetId = caxrn.InbredSetId \
+         JOIN Strain AS s ON caxrn.StrainId = s.Id \
+         WHERE caxrn.InbredSetId = :group_id \
+         ORDER BY s.Name",
+        mysql::params! { "group_id" => group_id },
+    )?;
+    let mut values: Vec<StrainCaseAttributes> = Vec::new();
+    for (strain, attribute_name, attribute_value) in rows {
+        match values.last_mut() {
+            Some(last) if last.strain == strain => {
+                last.case_attributes.insert(attribute_name, attribute_value);
+            }
+            _ => {
+                let mut case_attributes = std::collections::HashMap::new();
+                case_attributes.insert(attribute_name, attribute_value);
+                values.push(StrainCaseAttributes {
+                    strain,
+                    case_attributes,
+                });
+            }
+        }
+    }
+    Ok(values)
+}
+
+/// Fetch a group's case attributes: every attribute name defined for
+/// it, and every strain's values for them. See `CaseAttributes`.
+pub fn get_group_case_attributes(group_id: u16) -> Result<CaseAttributes, mysql::Error> {
+    Ok(CaseAttributes {
+        names: get_group_case_attribute_names(group_id)?,
+        values: get_group_case_attribute_values(group_id)?,
+    })
+}
+
 /// Fetch the expression datasets belonging to a species (across all of
 /// its groups), the species-scoped equivalent of get_group_datasets.
 /// GeneNetwork2's own species-scoped variant of
@@ -656,6 +799,7 @@ pub struct ProbeSetInfo {
     pub mean: Option<f64>,
     pub locus: Option<String>,
     pub lrs: Option<f64>,
+    pub lod: Option<f64>,
     pub p_value: Option<f64>,
     pub additive: Option<f64>,
 }
@@ -673,6 +817,7 @@ type ProbeSetInfoRow = (
     Option<f64>,
     Option<f64>,
     Option<f64>,
+    Option<f64>,
 );
 
 /// Fetch one expression trait's metadata (see ProbeSetInfo) within a
@@ -687,12 +832,15 @@ pub fn get_dataset_probeset_info(
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec_first(
-        "SELECT ProbeSet.Id, ProbeSet.Name, ProbeSet.Symbol, ProbeSet.description, \
+        format!(
+            "SELECT ProbeSet.Id, ProbeSet.Name, ProbeSet.Symbol, ProbeSet.description, \
                 ProbeSet.Chr, ProbeSet.Mb, ProbeSetXRef.mean, ProbeSetXRef.Locus, \
-                ProbeSetXRef.LRS, ProbeSetXRef.pValue, ProbeSetXRef.additive \
+                ProbeSetXRef.LRS, ProbeSetXRef.LRS / {LRS_PER_LOD}, ProbeSetXRef.pValue, \
+                ProbeSetXRef.additive \
          FROM ProbeSet \
          JOIN ProbeSetXRef ON ProbeSetXRef.ProbeSetId = ProbeSet.Id \
-         WHERE ProbeSetXRef.ProbeSetFreezeId = :dataset_id AND ProbeSet.Name = :probeset_name",
+         WHERE ProbeSetXRef.ProbeSetFreezeId = :dataset_id AND ProbeSet.Name = :probeset_name"
+        ),
         mysql::params! { "dataset_id" => dataset_id, "probeset_name" => probeset_name },
     )
     .map(|row: Option<ProbeSetInfoRow>| {
@@ -707,6 +855,7 @@ pub fn get_dataset_probeset_info(
                 mean,
                 locus,
                 lrs,
+                lod,
                 p_value,
                 additive,
             )| {
@@ -720,6 +869,7 @@ pub fn get_dataset_probeset_info(
                     mean,
                     locus,
                     lrs,
+                    lod,
                     p_value,
                     additive,
                 }
@@ -735,15 +885,31 @@ pub fn get_dataset_probesets(dataset_id: u16) -> Result<Vec<ProbeSetInfo>, mysql
     let pool = pool()?;
     let mut conn = pool.get_conn()?;
     conn.exec_map(
-        "SELECT ProbeSet.Id, ProbeSet.Name, ProbeSet.Symbol, ProbeSet.description, \
+        format!(
+            "SELECT ProbeSet.Id, ProbeSet.Name, ProbeSet.Symbol, ProbeSet.description, \
                 ProbeSet.Chr, ProbeSet.Mb, ProbeSetXRef.mean, ProbeSetXRef.Locus, \
-                ProbeSetXRef.LRS, ProbeSetXRef.pValue, ProbeSetXRef.additive \
+                ProbeSetXRef.LRS, ProbeSetXRef.LRS / {LRS_PER_LOD}, ProbeSetXRef.pValue, \
+                ProbeSetXRef.additive \
          FROM ProbeSet \
          JOIN ProbeSetXRef ON ProbeSetXRef.ProbeSetId = ProbeSet.Id \
          WHERE ProbeSetXRef.ProbeSetFreezeId = :dataset_id \
-         ORDER BY ProbeSet.Id",
+         ORDER BY ProbeSet.Id"
+        ),
         mysql::params! { "dataset_id" => dataset_id },
-        |(probeset_id, name, symbol, description, chr, mb, mean, locus, lrs, p_value, additive)| {
+        |(
+            probeset_id,
+            name,
+            symbol,
+            description,
+            chr,
+            mb,
+            mean,
+            locus,
+            lrs,
+            lod,
+            p_value,
+            additive,
+        )| {
             ProbeSetInfo {
                 probeset_id,
                 name,
@@ -754,6 +920,7 @@ pub fn get_dataset_probesets(dataset_id: u16) -> Result<Vec<ProbeSetInfo>, mysql
                 mean,
                 locus,
                 lrs,
+                lod,
                 p_value,
                 additive,
             }
diff --git a/src/lib.rs b/src/lib.rs
index 3882818..672708d 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -64,6 +64,7 @@ pub fn app() -> Router {
         .routes(routes!(routes::groups::group_trait_info))
         .routes(routes!(routes::groups::group_traits))
         .routes(routes!(routes::groups::group_datasets))
+        .routes(routes!(routes::groups::group_case_attributes))
         .routes(routes!(routes::datasets::dataset_by_name))
         .routes(routes!(routes::datasets::dataset_probesets))
         .routes(routes!(routes::datasets::dataset_probeset_info))
diff --git a/src/routes/groups.rs b/src/routes/groups.rs
index 51f12cc..12652ec 100644
--- a/src/routes/groups.rs
+++ b/src/routes/groups.rs
@@ -376,6 +376,62 @@ pub async fn group_traits(
     })
 }
 
+#[utoipa::path(get, path = "/groups/{group}/case-attributes", summary = "Get a group's case attributes: defined attribute names and every strain's values", params(
+    ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id")
+), responses(
+    (status = 200, description = "The group's case-attribute names and per-strain values", body = db::CaseAttributes),
+    Unauthorized,
+    (status = 404, description = "No matching group", body = ApiError),
+    (status = 500, description = "Database error", body = ApiError)
+))]
+pub async fn group_case_attributes(
+    Extension(request_id): Extension<RequestId>,
+    Path(group): Path<String>,
+    _token: AuthToken,
+) -> Result<Json<db::CaseAttributes>, 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_case_attributes(group.id).map(Some),
+            None => Ok(None),
+        })
+    })
+    .await
+    .map_err(|e| {
+        ApiError::new(
+            StatusCode::INTERNAL_SERVER_ERROR,
+            "internal_error",
+            "Internal error",
+            e.to_string(),
+            "group_case_attributes",
+        )
+        .with_request_id(rid.clone())
+    })?
+    .map_err(|e| {
+        ApiError::new(
+            StatusCode::INTERNAL_SERVER_ERROR,
+            "database_error",
+            "Database error",
+            e.to_string(),
+            "group_case_attributes",
+        )
+        .with_request_id(rid.clone())
+    })?
+    .map(Json)
+    .ok_or_else(|| {
+        ApiError::new(
+            StatusCode::NOT_FOUND,
+            "group_not_found",
+            "Group not found",
+            format!("No group matching '{not_found_name}'."),
+            "group_case_attributes",
+        )
+        .with_request_id(rid)
+        .with_next("/groups")
+    })
+}
+
 #[utoipa::path(get, path = "/groups/{group}/datasets", summary = "List the expression (ProbeSet) datasets belonging to a group", params(
     ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id")
 ), responses(
diff --git a/src/routes/search.rs b/src/routes/search.rs
index a10f431..6921d40 100644
--- a/src/routes/search.rs
+++ b/src/routes/search.rs
@@ -3,7 +3,9 @@
 //! 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.
+//! 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`.
 //!
 //! The backend itself lives behind the search engine seam (see
 //! `crate::search`); this handler validates parameters, delegates to
@@ -14,9 +16,11 @@ use axum::Json;
 use axum::extract::{Extension, Query};
 use axum::http::StatusCode;
 use serde::Deserialize;
+use std::collections::HashMap;
 use tower_http::request_id::RequestId;
 
 use crate::auth::AuthToken;
+use crate::db;
 use crate::error::{ApiError, Unauthorized};
 use crate::request_id_string;
 use crate::response::Envelope;
@@ -35,6 +39,12 @@ pub struct SearchParams {
     pub r#type: Option<String>,
     /// Maximum hits to return (default 20, capped at 100).
     pub limit: Option<u64>,
+    /// Rank hits by "lrs" or "lod" (the same order) instead of
+    /// relevance; hits without a value come last. The ranking covers
+    /// the first 1000 relevance-ranked matches, then `limit` applies.
+    pub sort: Option<String>,
+    /// "desc" (default) or "asc"; only meaningful with `sort`.
+    pub order: Option<String>,
 }
 
 /// Map a [`SearchError`] onto the `/search` error contract: one
@@ -77,6 +87,52 @@ fn engine_error(error: SearchError, rid: Option<String>) -> ApiError {
     }
 }
 
+/// With `sort`, the engine is asked for this many hits (not just
+/// `limit`) so the ranking spans more than one page of relevance-
+/// ordered results.
+const SORT_FETCH_LIMIT: u64 = 1000;
+
+/// Orders hits by `lrs` (which orders LOD identically), descending
+/// unless `ascending`; hits with no `lrs` always come last.
+fn sort_by_lrs(hits: &mut [SearchHit], ascending: bool) {
+    hits.sort_by(|a, b| match (a.lrs, b.lrs) {
+        (Some(x), Some(y)) if ascending => x.total_cmp(&y),
+        (Some(x), Some(y)) => y.total_cmp(&x),
+        (Some(_), None) => std::cmp::Ordering::Less,
+        (None, Some(_)) => std::cmp::Ordering::Greater,
+        (None, None) => std::cmp::Ordering::Equal,
+    });
+}
+
+/// 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
+/// 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();
+    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,
+            _ => 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();
+    }
+}
+
 #[utoipa::path(get, path = "/search",
     summary = "Search traits across GN datasets",
     description = "Search traits across GN datasets. Runs through the \
@@ -121,10 +177,31 @@ pub async fn search(
         ));
     }
     let limit = params.limit.unwrap_or(20).min(100);
+    if !matches!(params.sort.as_deref(), None | Some("lrs") | Some("lod")) {
+        return Err(bad_request("sort must be \"lrs\" or \"lod\""));
+    }
+    let ascending = match params.order.as_deref() {
+        None | Some("desc") => false,
+        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
+    } else {
+        limit
+    };
 
-    let hits = search::search(q, search_type, limit)
+    let mut hits = search::search(q, search_type, fetch_limit)
         .await
         .map_err(|e| engine_error(e, rid))?;
+    for hit in &mut hits {
+        hit.lod = hit.lrs.map(db::lod);
+    }
+    if params.sort.is_some() {
+        sort_by_lrs(&mut hits, ascending);
+    }
+    hits.truncate(limit as usize);
+    add_loci(&mut hits).await;
 
     Ok(Json(Envelope::of(hits)))
 }
@@ -132,7 +209,6 @@ pub async fn search(
 #[cfg(test)]
 mod tests {
     use super::*;
-
     /// Each `SearchError` class keeps its existing status/code/title,
     /// carrying the engine's diagnostic as `detail`, with the request
     /// id threaded through.
@@ -182,4 +258,28 @@ mod tests {
             assert_eq!(api_error.request_id.as_deref(), Some("req-1"));
         }
     }
+
+    use serde_json::json;
+
+    fn hit(lrs: Option<f64>) -> SearchHit {
+        serde_json::from_value(json!({ "lrs": lrs })).unwrap()
+    }
+
+    fn lrs_of(hits: &[SearchHit]) -> Vec<Option<f64>> {
+        hits.iter().map(|h| h.lrs).collect()
+    }
+
+    #[test]
+    fn sort_by_lrs_descending_puts_missing_values_last() {
+        let mut hits = vec![hit(Some(2.0)), hit(None), hit(Some(9.0)), hit(Some(5.0))];
+        sort_by_lrs(&mut hits, false);
+        assert_eq!(lrs_of(&hits), [Some(9.0), Some(5.0), Some(2.0), None]);
+    }
+
+    #[test]
+    fn sort_by_lrs_ascending_still_puts_missing_values_last() {
+        let mut hits = vec![hit(Some(2.0)), hit(None), hit(Some(9.0)), hit(Some(5.0))];
+        sort_by_lrs(&mut hits, true);
+        assert_eq!(lrs_of(&hits), [Some(2.0), Some(5.0), Some(9.0), None]);
+    }
 }
diff --git a/src/search/mod.rs b/src/search/mod.rs
index 936c977..cb76f60 100644
--- a/src/search/mod.rs
+++ b/src/search/mod.rs
@@ -122,6 +122,12 @@ 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`.
+    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>,
     pub geno_chr: Option<String>,
     pub geno_mb: Option<f64>,
     pub inbredsetcode: Option<String>,