about summary refs log tree commit diff
path: root/src/indexer/rows.rs
diff options
context:
space:
mode:
authorAlexander_Kabui <alexanderkabui@proton.me>2026-10-13 15:11:33 +0300
committerAlexander_Kabui <alexanderkabui@proton.me>2026-10-14 07:27:03 +0300
commit53c3f26ec2fdf209876a8a8eab561acc6fd755d4 (patch)
tree25fc2be0d09e37da759be90fc3590f1496afaa89 /src/indexer/rows.rs
parenta6003ffbfe40aadaa1d9548bdc3294987b97d304 (diff)
downloadgenenetwork4-53c3f26ec2fdf209876a8a8eab561acc6fd755d4.tar.gz
* src/indexer/sidecar.rs (sharding): one sidecar shard per dataset.
A monolithic sidecar rewrote and re-read the whole identity map each run;
sharding it by dataset under <index>.sidecar.json plus <index>.sidecar.d/
lets a run load and rewrite only the shards it touches and keeps resident
memory at O(largest dataset).
* src/indexer/run.rs: crawl the SQL sources one dataset at a time through a
sink and commit every 5000 documents instead of buffering the whole crawl;
a bounded-channel variant was tried and reverted (several times slower).
* src/indexer/rows.rs: order and group the crawl streams by dataset.
* src/bin/gn-indexer.rs: follow the sharded sink wiring.
Diffstat (limited to 'src/indexer/rows.rs')
-rw-r--r--src/indexer/rows.rs284
1 files changed, 222 insertions, 62 deletions
diff --git a/src/indexer/rows.rs b/src/indexer/rows.rs
index b8669e1..69b94cc 100644
--- a/src/indexer/rows.rs
+++ b/src/indexer/rows.rs
@@ -1,5 +1,5 @@
 //! The crawl: the SQL queries and typed row structs the document
-//! builder consumes.
+//! builder consumes, streamed and grouped by dataset.
 //!
 //! The queries and joins are the indexer's own (`genes_query` and
 //! `phenotypes_query` in index-genenetwork), rendered by its
@@ -12,6 +12,18 @@
 //! PublishFreezes (e.g. BXDPublish and GITrMetPublish) each index every
 //! trait under their own dataset label. This cross-product is INTENTIONAL
 //! reference semantics and is reproduced, not "cleaned up".
+//!
+//! # Streaming, dataset-grouped crawl
+//!
+//! [`stream_dataset_groups`] never materialises the crawl. Each query is
+//! executed in its own producer thread with `ORDER BY dataset`; the merge
+//! consumes the two sorted streams and hands the caller **one dataset at
+//! a time** through a [`DatasetSink`], whose `begin_dataset` / `row` /
+//! `end_dataset` callbacks see rows one at a time. The only per-dataset
+//! state the caller keeps is bounded by the largest dataset, not by the
+//! whole crawl.
+
+use std::sync::mpsc::{Receiver, Sender};
 
 use mysql::prelude::Queryable;
 use mysql::{Conn, Opts, OptsBuilder, Row};
@@ -74,6 +86,34 @@ pub struct PhenotypeRow {
     pub geno_mb: Option<f64>,
 }
 
+/// One crawled row, tagged with its document type. The dataset label is
+/// the row's dataset column — never parsed back out of the identity
+/// term, whose `name` part may itself contain a colon.
+pub enum CrawlRow {
+    Gene(GeneRow),
+    Phenotype(PhenotypeRow),
+}
+
+impl CrawlRow {
+    /// The row's dataset label (the shard key).
+    pub fn dataset(&self) -> Option<&str> {
+        match self {
+            CrawlRow::Gene(row) => row.dataset.as_deref(),
+            CrawlRow::Phenotype(row) => row.dataset.as_deref(),
+        }
+    }
+}
+
+/// Receive one dataset group at a time from [`stream_dataset_groups`].
+pub trait DatasetSink {
+    /// Called once when a dataset group starts, before any of its rows.
+    fn begin_dataset(&mut self, label: &str) -> Result<(), String>;
+    /// Called for each row of the current dataset, in arrival order.
+    fn row(&mut self, row: CrawlRow) -> Result<(), String>;
+    /// Called once after the last row of the dataset.
+    fn end_dataset(&mut self, label: &str) -> Result<(), String>;
+}
+
 fn connect(sql_uri: &str) -> Result<Conn, String> {
     let opts = Opts::from_url(sql_uri).map_err(|e| format!("bad SQL_URI: {e}"))?;
     Conn::new(OptsBuilder::from_opts(opts)).map_err(|e| format!("cannot connect: {e}"))
@@ -122,7 +162,8 @@ fn genes_sql() -> String {
          INNER JOIN ProbeSetXRef ON ProbeSetXRef.ProbeSetFreezeId = ProbeSetFreeze.Id \
          INNER JOIN ProbeSet ON ProbeSet.Id = ProbeSetXRef.ProbeSetId \
          LEFT JOIN Geno ON ProbeSetXRef.Locus = Geno.Name AND Geno.SpeciesId = Species.Id \
-         WHERE {GENE_PUBLIC_FILTER}"
+         WHERE {GENE_PUBLIC_FILTER} \
+         ORDER BY dataset"
     )
 }
 
@@ -155,75 +196,194 @@ fn phenotypes_sql(filtered: bool) -> String {
          INNER JOIN Phenotype ON PublishXRef.PhenotypeId = Phenotype.Id \
          INNER JOIN Publication ON PublishXRef.PublicationId = Publication.Id \
          LEFT JOIN Geno ON PublishXRef.Locus = Geno.Name AND Geno.SpeciesId = Species.Id\
-         {where_clause}"
+         {where_clause} \
+         ORDER BY dataset"
     )
 }
 
-/// Crawl every public, non-confidential expression record.
-pub fn crawl_genes(sql_uri: &str) -> Result<Vec<GeneRow>, String> {
+type Item = Result<(String, CrawlRow), String>;
+
+/// Producer thread for the gene crawl: stream rows ordered by dataset and
+/// send each as `(dataset, CrawlRow)`. Rows with no dataset produce no
+/// document and are skipped.
+fn produce_genes(sql_uri: &str, tx: &Sender<Item>) -> Result<(), String> {
     let mut conn = connect(sql_uri)?;
-    let rows: Vec<Row> = conn
-        .query(genes_sql())
+    let result = conn
+        .query_iter(genes_sql())
         .map_err(|e| format!("gene crawl failed: {e}"))?;
-    let mut out = Vec::with_capacity(rows.len());
-    for row in &rows {
-        out.push(GeneRow {
-            name: text(row, "name")?,
-            symbol: text(row, "symbol")?,
-            description: text(row, "description")?,
-            chr: text(row, "chr")?,
-            mb: float(row, "mb")?,
-            alias: text(row, "alias")?,
-            genbankid: text(row, "genbankid")?,
-            unigeneid: text(row, "unigeneid")?,
-            probe_target_description: text(row, "probe_target_description")?,
-            dataset: text(row, "dataset")?,
-            dataset_fullname: text(row, "dataset_fullname")?,
-            species: text(row, "species")?,
-            group: text(row, "group")?,
-            tissue: text(row, "tissue")?,
-            mean: float(row, "mean")?,
-            lrs: float(row, "lrs")?,
-            additive: float(row, "additive")?,
-            geno_chr: text(row, "geno_chr")?,
-            geno_mb: float(row, "geno_mb")?,
-        });
+    for row in result {
+        let row = row.map_err(|e| format!("gene crawl failed: {e}"))?;
+        let Some(dataset) = text(&row, "dataset")? else {
+            continue;
+        };
+        let row = GeneRow {
+            name: text(&row, "name")?,
+            symbol: text(&row, "symbol")?,
+            description: text(&row, "description")?,
+            chr: text(&row, "chr")?,
+            mb: float(&row, "mb")?,
+            alias: text(&row, "alias")?,
+            genbankid: text(&row, "genbankid")?,
+            unigeneid: text(&row, "unigeneid")?,
+            probe_target_description: text(&row, "probe_target_description")?,
+            dataset: Some(dataset.clone()),
+            dataset_fullname: text(&row, "dataset_fullname")?,
+            species: text(&row, "species")?,
+            group: text(&row, "group")?,
+            tissue: text(&row, "tissue")?,
+            mean: float(&row, "mean")?,
+            lrs: float(&row, "lrs")?,
+            additive: float(&row, "additive")?,
+            geno_chr: text(&row, "geno_chr")?,
+            geno_mb: float(&row, "geno_mb")?,
+        };
+        if tx.send(Ok((dataset, CrawlRow::Gene(row)))).is_err() {
+            return Ok(());
+        }
     }
-    Ok(out)
+    Ok(())
 }
 
-/// Crawl published phenotype records. `filtered=false` drops the
-/// public/confidentiality predicate: that is the leak control, used
-/// only by the gate-4 RED run.
-pub fn crawl_phenotypes(sql_uri: &str, filtered: bool) -> Result<Vec<PhenotypeRow>, String> {
+/// Producer thread for the phenotype crawl.
+fn produce_phenotypes(sql_uri: &str, filtered: bool, tx: &Sender<Item>) -> Result<(), String> {
     let mut conn = connect(sql_uri)?;
-    let rows: Vec<Row> = conn
-        .query(phenotypes_sql(filtered))
+    let result = conn
+        .query_iter(phenotypes_sql(filtered))
         .map_err(|e| format!("phenotype crawl failed: {e}"))?;
-    let mut out = Vec::with_capacity(rows.len());
-    for row in &rows {
-        out.push(PhenotypeRow {
-            species: text(row, "species")?,
-            group: text(row, "group")?,
-            dataset: text(row, "dataset")?,
-            dataset_fullname: text(row, "dataset_fullname")?,
-            name: integer(row, "name")?,
-            abbreviation: text(row, "abbreviation")?,
-            description: text(row, "description")?,
-            lab_code: text(row, "Lab_code")?,
-            abstract_: text(row, "Abstract")?,
-            title: text(row, "Title")?,
-            authors: text(row, "authors")?,
-            year: integer(row, "year")?,
-            pubmed_id: integer(row, "pubmed_id")?,
-            lrs: float(row, "lrs")?,
-            additive: float(row, "additive")?,
-            inbredsetcode: text(row, "inbredsetcode")?,
-            mean: float(row, "mean")?,
-            nsamples: integer(row, "nsamples")?,
-            geno_chr: text(row, "geno_chr")?,
-            geno_mb: float(row, "geno_mb")?,
-        });
+    for row in result {
+        let row = row.map_err(|e| format!("phenotype crawl failed: {e}"))?;
+        let Some(dataset) = text(&row, "dataset")? else {
+            continue;
+        };
+        let row = PhenotypeRow {
+            species: text(&row, "species")?,
+            group: text(&row, "group")?,
+            dataset: Some(dataset.clone()),
+            dataset_fullname: text(&row, "dataset_fullname")?,
+            name: integer(&row, "name")?,
+            abbreviation: text(&row, "abbreviation")?,
+            description: text(&row, "description")?,
+            lab_code: text(&row, "Lab_code")?,
+            abstract_: text(&row, "Abstract")?,
+            title: text(&row, "Title")?,
+            authors: text(&row, "authors")?,
+            year: integer(&row, "year")?,
+            pubmed_id: integer(&row, "pubmed_id")?,
+            lrs: float(&row, "lrs")?,
+            additive: float(&row, "additive")?,
+            inbredsetcode: text(&row, "inbredsetcode")?,
+            mean: float(&row, "mean")?,
+            nsamples: integer(&row, "nsamples")?,
+            geno_chr: text(&row, "geno_chr")?,
+            geno_mb: float(&row, "geno_mb")?,
+        };
+        if tx.send(Ok((dataset, CrawlRow::Phenotype(row)))).is_err() {
+            return Ok(());
+        }
+    }
+    Ok(())
+}
+
+fn spawn_producer<F>(tx: Sender<Item>, body: F) -> std::thread::JoinHandle<()>
+where
+    F: FnOnce(&Sender<Item>) -> Result<(), String> + Send + 'static,
+{
+    std::thread::spawn(move || {
+        if let Err(error) = body(&tx) {
+            let _ = tx.send(Err(error));
+        }
+    })
+}
+
+/// The dataset label at the head of a channel, propagating a producer
+/// error. `Ok(None)` means the channel is exhausted.
+fn head_label(head: &Option<Item>) -> Result<Option<&str>, String> {
+    match head {
+        None => Ok(None),
+        Some(Ok((label, _))) => Ok(Some(label.as_str())),
+        Some(Err(error)) => Err(error.clone()),
+    }
+}
+
+/// Stream the crawl as dataset groups. Two producer threads (genes and
+/// phenotypes) each return rows ordered by dataset; this merge consumes
+/// them in dataset order and invokes `sink` once per dataset. No whole-
+/// crawl buffer exists: at most one pending row per source is held.
+pub fn stream_dataset_groups(
+    sql_uri: &str,
+    filtered: bool,
+    sink: &mut dyn DatasetSink,
+) -> Result<(), String> {
+    // Unbounded channels: the producers stream the two SQL result sets in
+    // their own threads and the merge consumes them; this is the fast
+    // path (a bounded channel was tried and made the scaled run several
+    // times slower, so it was reverted).
+    let (gene_tx, gene_rx) = std::sync::mpsc::channel::<Item>();
+    let (phen_tx, phen_rx) = std::sync::mpsc::channel::<Item>();
+    let gene_uri = sql_uri.to_string();
+    let phen_uri = sql_uri.to_string();
+    let genes = spawn_producer(gene_tx, move |tx| produce_genes(&gene_uri, tx));
+    let phenotypes = spawn_producer(phen_tx, move |tx| {
+        produce_phenotypes(&phen_uri, filtered, tx)
+    });
+
+    let outcome = merge_streams(&gene_rx, &phen_rx, sink);
+
+    // Producers end when the receivers drop, but join for a clean exit.
+    let _ = genes.join();
+    let _ = phenotypes.join();
+    outcome
+}
+
+fn merge_streams(
+    gene_rx: &Receiver<Item>,
+    phen_rx: &Receiver<Item>,
+    sink: &mut dyn DatasetSink,
+) -> Result<(), String> {
+    let mut gene_head = gene_rx.recv().ok();
+    let mut phen_head = phen_rx.recv().ok();
+    loop {
+        let gene_label = head_label(&gene_head)?;
+        let phen_label = head_label(&phen_head)?;
+        let label = match (gene_label, phen_label) {
+            (None, None) => break,
+            (Some(label), None) => label.to_string(),
+            (None, Some(label)) => label.to_string(),
+            (Some(gene), Some(phen)) => {
+                if gene <= phen {
+                    gene.to_string()
+                } else {
+                    phen.to_string()
+                }
+            }
+        };
+        sink.begin_dataset(&label)?;
+        drain_label(&mut gene_head, gene_rx, &label, sink)?;
+        drain_label(&mut phen_head, phen_rx, &label, sink)?;
+        sink.end_dataset(&label)?;
+    }
+    Ok(())
+}
+
+/// Consume every head row whose dataset equals `label`, advancing the
+/// channel. Rows for later datasets stay as the new head.
+fn drain_label(
+    head: &mut Option<Item>,
+    rx: &Receiver<Item>,
+    label: &str,
+    sink: &mut dyn DatasetSink,
+) -> Result<(), String> {
+    loop {
+        match head {
+            Some(Ok((row_label, _))) if row_label == label => {
+                let Some(Ok((_, row))) = head.take() else {
+                    unreachable!("head was checked Some(Ok)")
+                };
+                sink.row(row)?;
+                *head = rx.recv().ok();
+            }
+            Some(Err(error)) => return Err(error.clone()),
+            _ => return Ok(()),
+        }
     }
-    Ok(out)
 }