about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorAlexander_Kabui <alexanderkabui@proton.me>2026-10-14 07:28:47 +0300
committerAlexander_Kabui <alexanderkabui@proton.me>2026-10-14 07:28:47 +0300
commit82f1e85a4c011b18aca476dca66a335981b05e4f (patch)
treea7be75fbb666e4fb28bbf3608bb106c55c568989 /src
parentd607e8faa7692f28f7e6cf3d0517a69a44557a27 (diff)
downloadgenenetwork4-82f1e85a4c011b18aca476dca66a335981b05e4f.tar.gz
indexer delta: fall back to FULL on a case-only dataset rename
* src/indexer/delta.rs (scan): enumerate dataset labels under COLLATE
  utf8mb4_bin so a case-only rename's old and new labels both enter scope;
  route to FULL when a case-variant label pair is in the affected scope.
* src/indexer/run.rs (run_delta): seed the duplicate-check map with manifest
  labels not in scope; route to FULL when a manifest carries an unknown
  versioning flavour.
* scripts/gn-indexer-lag.sh: honour the table-prefix seam only with the
  explicit test opt-in; treat a literal NULL MAX as no change; guard an
  empty lag value.
* scripts/gn-indexer-run.sh: --index=PATH-aware argument scan.
Diffstat (limited to 'src')
-rw-r--r--src/indexer/delta.rs89
-rw-r--r--src/indexer/run.rs83
2 files changed, 146 insertions, 26 deletions
diff --git a/src/indexer/delta.rs b/src/indexer/delta.rs
index e0843f8..68fd2ff 100644
--- a/src/indexer/delta.rs
+++ b/src/indexer/delta.rs
@@ -29,7 +29,7 @@ pub const FLAVOUR: &str = "timestamp6";
 /// supplies the prefix and the second explicit opt-in required to honour
 /// it (a debug build also enables it).
 pub const PREFIX_ENV: &str = "GN4_INDEXER_DELTA_TABLE_PREFIX";
-/// Second explicit opt-in for the table-prefix seam (A6): the prefix is
+/// Second explicit opt-in for the table-prefix seam (test seam): the prefix is
 /// ignored unless this is `1` or the binary is a debug build.
 pub const TEST_ENV: &str = "GN4_INDEXER_DELTA_TEST";
 
@@ -241,7 +241,8 @@ pub enum Startup {
 /// versioning absent, marker NULL/unparseable, marker in the future,
 /// marker not strictly monotonic (log "retry next tick" on the rare
 /// equal-microsecond case), and history purged (oldest resolvable version
-/// newer than the marker).
+/// newer than the marker, or no resolvable history at all with a valid
+/// previous marker).
 ///
 /// The caller must probe versioning presence **before** computing
 /// `oldest_history` (a `FOR SYSTEM_TIME ALL` query errors on an
@@ -267,10 +268,17 @@ pub fn decide(
             "marker not monotonic (equal timestamp; retry next tick)".to_string(),
         );
     }
-    if let Some(oldest) = oldest_history {
-        if *oldest > prev {
+    // A NULL `oldest_history` (no resolvable version at all) with a valid
+    // previous marker means the window's lower bound cannot be resolved,
+    // so it is as unsafe as a purge: route to FULL (advisory A2).
+    match oldest_history {
+        Some(oldest) if *oldest > prev => {
             return Startup::Full("history purged".to_string());
         }
+        None => {
+            return Startup::Full("history purged".to_string());
+        }
+        _ => {}
     }
     let floor = window_floor(&prev, overlap_seconds());
     Startup::Delta {
@@ -281,7 +289,7 @@ pub fn decide(
 }
 
 // ---------------------------------------------------------------------------
-// Table-name resolver (the test-only prefix seam, A6)
+// Table-name resolver (the test-only prefix seam, test seam)
 // ---------------------------------------------------------------------------
 
 /// Resolve the effective table prefix from raw inputs. Kept pure so the
@@ -308,8 +316,32 @@ thread_local! {
         const { std::cell::RefCell::new(None) };
 }
 
+/// The first pair of case-variant labels in a set (two labels that differ
+/// only by case), or `None`. `identity_term` lowercases the whole
+/// `name:dataset`, so two such labels map their documents into the *same*
+/// identity-term space; a delta cannot tell their shards apart (deleting
+/// the old label's terms would delete the new label's documents), so the
+/// caller falls back to FULL, exactly as FULL/INCREMENTAL treat a live
+/// case-variant pair as a hard error.
+pub fn case_collision(labels: &BTreeSet<String>) -> Option<(String, String)> {
+    let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
+    for label in labels {
+        let key = label.to_lowercase();
+        match seen.get(&key) {
+            Some(existing) if existing != label => {
+                return Some((existing.clone(), label.clone()));
+            }
+            None => {
+                seen.insert(key, label.clone());
+            }
+            _ => {}
+        }
+    }
+    None
+}
+
 /// The effective table prefix. Honoured only when the explicit test env
-/// (or a debug build) is present (A6); otherwise the prefix env is ignored
+/// (or a debug build) is present (test seam); otherwise the prefix env is ignored
 /// and a warning is expected from the run entry point.
 pub fn table_prefix() -> String {
     #[cfg(test)]
@@ -342,7 +374,7 @@ pub fn table_name(base: &str) -> String {
     format!("{}{}", table_prefix(), base)
 }
 
-/// Emit the seam warning once at a run's entry point (A6/R6).
+/// Emit the seam warning once at a run's entry point (test seam).
 pub fn log_prefix_warning() {
     let raw = std::env::var(PREFIX_ENV).unwrap_or_default();
     if raw.is_empty() {
@@ -594,7 +626,7 @@ pub fn scan(
     let freeze_names = query_strings(
         conn,
         &format!(
-            "SELECT DISTINCT Name FROM {pubfreeze} WHERE {}",
+            "SELECT DISTINCT Name COLLATE utf8mb4_bin FROM {pubfreeze} WHERE {}",
             int_in_clause("InbredSetId", &inbred_sets)
         ),
     )?;
@@ -622,7 +654,7 @@ pub fn scan(
     for name in query_strings(
         conn,
         &format!(
-            "SELECT DISTINCT Name FROM {pubfreeze} FOR SYSTEM_TIME ALL WHERE {}",
+            "SELECT DISTINCT Name COLLATE utf8mb4_bin FROM {pubfreeze} FOR SYSTEM_TIME ALL WHERE {}",
             int_in_clause("Id", &freeze_ids)
         ),
     )? {
@@ -663,7 +695,7 @@ pub fn scan(
     let gene_freeze_names = query_strings(
         conn,
         &format!(
-            "SELECT DISTINCT Name FROM {probefreeze} WHERE {}",
+            "SELECT DISTINCT Name COLLATE utf8mb4_bin FROM {probefreeze} WHERE {}",
             int_in_clause("Id", &probe_freeze_ids)
         ),
     )?;
@@ -673,7 +705,7 @@ pub fn scan(
     let probe_names = query_strings(
         conn,
         &format!(
-            "SELECT DISTINCT Name FROM {probeset} WHERE {}",
+            "SELECT DISTINCT Name COLLATE utf8mb4_bin FROM {probeset} WHERE {}",
             int_in_clause("Id", &probe_ids)
         ),
     )?;
@@ -695,7 +727,7 @@ pub fn scan(
     for name in query_strings(
         conn,
         &format!(
-            "SELECT DISTINCT Name FROM {probefreeze} FOR SYSTEM_TIME ALL WHERE {}",
+            "SELECT DISTINCT Name COLLATE utf8mb4_bin FROM {probefreeze} FOR SYSTEM_TIME ALL WHERE {}",
             int_in_clause("Id", &rows_ids)
         ),
     )? {
@@ -713,7 +745,7 @@ pub fn scan(
     for name in query_strings(
         conn,
         &format!(
-            "SELECT DISTINCT f.Name FROM {probefreeze} f \
+            "SELECT DISTINCT f.Name COLLATE utf8mb4_bin FROM {probefreeze} f \
              JOIN {probexref} x ON x.ProbeSetFreezeId = f.Id \
              WHERE {}",
             int_in_clause("x.ProbeSetId", &probeset_ids)
@@ -734,7 +766,7 @@ pub fn scan(
     for name in query_strings(
         conn,
         &format!(
-            "SELECT DISTINCT Name FROM {pubfreeze} WHERE {}",
+            "SELECT DISTINCT Name COLLATE utf8mb4_bin FROM {pubfreeze} WHERE {}",
             int_in_clause("InbredSetId", &group_ids)
         ),
     )? {
@@ -743,7 +775,7 @@ pub fn scan(
     for name in query_strings(
         conn,
         &format!(
-            "SELECT DISTINCT f.Name FROM {probefreeze} f \
+            "SELECT DISTINCT f.Name COLLATE utf8mb4_bin FROM {probefreeze} f \
              JOIN ProbeFreeze pr ON pr.Id = f.ProbeFreezeId \
              WHERE {}",
             int_in_clause("pr.InbredSetId", &group_ids)
@@ -764,7 +796,7 @@ pub fn scan(
     for name in query_strings(
         conn,
         &format!(
-            "SELECT DISTINCT pf.Name FROM {pubfreeze} pf \
+            "SELECT DISTINCT pf.Name COLLATE utf8mb4_bin FROM {pubfreeze} pf \
              JOIN {inbredset} i ON i.Id = pf.InbredSetId \
              WHERE {}",
             int_in_clause("i.SpeciesId", &species_ids)
@@ -775,7 +807,7 @@ pub fn scan(
     for name in query_strings(
         conn,
         &format!(
-            "SELECT DISTINCT f.Name FROM {probefreeze} f \
+            "SELECT DISTINCT f.Name COLLATE utf8mb4_bin FROM {probefreeze} f \
              JOIN ProbeFreeze pr ON pr.Id = f.ProbeFreezeId \
              JOIN {inbredset} i2 ON i2.Id = pr.InbredSetId \
              WHERE {}",
@@ -966,6 +998,12 @@ mod tests {
             ),
             Startup::Full("history purged".to_string())
         );
+        // Rule 6b (advisory A2): NO resolvable history at all with a valid
+        // previous marker is as unsafe as a purge -> FULL.
+        assert_eq!(
+            decide(Some(prev.as_str()), &new, true, None),
+            Startup::Full("history purged".to_string())
+        );
         // Healthy: prev < new and oldest <= prev -> delta at the overlap floor.
         match decide(
             Some(prev.as_str()),
@@ -981,6 +1019,23 @@ mod tests {
     }
 
     #[test]
+    fn case_collision_detects_case_variant_pairs() {
+        let labels: BTreeSet<String> = ["bxd", "BXD", "other"]
+            .into_iter()
+            .map(String::from)
+            .collect();
+        let (a, b) = case_collision(&labels).expect("case-variant pair");
+        assert!(a.eq_ignore_ascii_case(&b) && a != b, "{a} vs {b}");
+        // Identical labels cannot occur in a set; distinct non-case-variant
+        // labels do not collide.
+        let none: BTreeSet<String> = ["Alpha", "beta", "Gamma"]
+            .into_iter()
+            .map(String::from)
+            .collect();
+        assert!(case_collision(&none).is_none());
+    }
+
+    #[test]
     fn prefix_resolver_requires_the_second_opt_in() {
         // Prefix set, but no opt-in and a release build: ignored.
         assert_eq!(resolve_prefix(Some("vdelta_"), None, false), None);
diff --git a/src/indexer/run.rs b/src/indexer/run.rs
index 30335f2..6475009 100644
--- a/src/indexer/run.rs
+++ b/src/indexer/run.rs
@@ -305,11 +305,11 @@ fn duplicate_prepass(sql_uri: &str, filtered: bool) -> Result<(Vec<String>, usiz
 
 /// The scoped duplicate pre-pass (B1): stream only `datasets` through the
 /// [`DuplicateSink`], with its cross-dataset label map PRE-SEEDED from
-/// every existing label (`seed_labels`, typically all manifest shard
-/// keys). This catches a case-variant collision between an affected label
-/// and an out-of-scope shard, and (via the per-dataset set) a
-/// within-dataset identity-term collision. `datasets = None` is the
-/// unscoped FULL/INCREMENTAL pass.
+/// `seed_labels` (the manifest labels that are NOT in scope, advisory A1). This
+/// catches a case-variant collision between an affected label and an
+/// out-of-scope shard, and (via the per-dataset set) a within-dataset
+/// identity-term collision. `datasets = None` is the unscoped
+/// FULL/INCREMENTAL pass.
 fn duplicate_prepass_scoped<I: IntoIterator<Item = String>>(
     sql_uri: &str,
     filtered: bool,
@@ -322,6 +322,21 @@ fn duplicate_prepass_scoped<I: IntoIterator<Item = String>>(
     Ok((sink.duplicates, sink.max_terms))
 }
 
+/// The B1 seed set: the existing labels that are NOT already in scope
+/// (advisory A1). In-scope labels are checked by the scoped crawl's own map, so
+/// seeding them would false-positive on a case-only dataset rename (the
+/// manifest keeps the old case, the crawl yields the new one). Pure so the
+/// exclusion is directly testable.
+fn seed_labels_excluding_scope<'a, I>(labels: I, scope: &BTreeSet<String>) -> Vec<String>
+where
+    I: Iterator<Item = &'a String>,
+{
+    labels
+        .filter(|label| !scope.contains(*label))
+        .cloned()
+        .collect()
+}
+
 // ---------------------------------------------------------------------------
 // Chunked-commit pacer with a per-chunk memory probe.
 // ---------------------------------------------------------------------------
@@ -1199,6 +1214,18 @@ pub fn run_delta(config: &RunConfig) -> Result<Stats, String> {
         Pre::Full(reason) => return run_full_with_reason(config, Some(reason)),
     };
 
+    // advisory A4: a manifest carrying an unknown timestamp flavour must not run
+    // the delta (a future flavour's window semantics are not known). A
+    // marker-less v3 manifest is the adoption state and is fine.
+    if let Some(flavour) = manifest.versioning_flavour.as_deref() {
+        if flavour != delta::FLAVOUR {
+            return run_full_with_reason(
+                config,
+                Some(format!("unknown versioning flavour {flavour:?}")),
+            );
+        }
+    }
+
     // Probe versioning presence BEFORE any `FOR SYSTEM_TIME` query (A1):
     // an unversioned table would error `Unknown column 'ROW_START'`.
     let mut conn = delta::connect(&config.sql_uri)?;
@@ -1263,19 +1290,39 @@ pub fn run_delta(config: &RunConfig) -> Result<Stats, String> {
         });
     }
 
+    // A case-only dataset rename (or any two affected labels that differ
+    // only by case) collapses in `identity_term` (which lowercases
+    // `name:dataset`): the old label's shard terms are identical to the new
+    // label's, so the leftover-delete path would delete the documents the
+    // scoped crawl just wrote. FULL/INCREMENTAL treat such a pair as a hard
+    // duplicate error; the delta must not silently diverge from FULL, so it
+    // detects the collision and falls back to FULL (case-collision fallback).
+    if let Some((a, b)) = delta::case_collision(&candidates.datasets) {
+        return run_full_with_reason(
+            config,
+            Some(format!(
+                "case-variant dataset labels in affected scope ({a:?} vs {b:?})"
+            )),
+        );
+    }
+
     let caches = RdfCaches::load(&config.rdf_cache)?;
 
     // B1: run the duplicate check, SCOPED, with the cross-dataset label map
-    // PRE-SEEDED from ALL manifest labels (so a case-variant collision
-    // against an out-of-scope shard is still caught). This is the only
-    // guard against within-dataset identity-term collisions and
+    // PRE-SEEDED from the manifest labels that are NOT already in scope
+    // (advisory A1). In-scope labels are covered by the crawl's own map (the
+    // scoped crawl yields them and their per-dataset sets are checked);
+    // seeding them too would false-positive on a case-only dataset rename
+    // (the seed holds the old case, the crawl yields the new one). The seed
+    // still catches an in-scope x out-of-scope case-variant collision. This
+    // is the only guard against within-dataset identity-term collisions and
     // cross-dataset case-variant labels; skipping it would let the delta
     // diverge from a fresh FULL.
     let (duplicates, max_dataset_terms) = duplicate_prepass_scoped(
         &config.sql_uri,
         config.publish_filter,
         Some(&candidates.datasets),
-        manifest.shards.keys().cloned(),
+        seed_labels_excluding_scope(manifest.shards.keys(), &candidates.datasets),
     )?;
     if !duplicates.is_empty() {
         return Err(format!(
@@ -1482,6 +1529,24 @@ mod tests {
         assert!(sink.duplicates.is_empty(), "{:?}", sink.duplicates);
     }
 
+    /// advisory A1: the duplicate-check seed excludes already-in-scope labels,
+    /// so a case-only rename (manifest old case, crawl new case) does not
+    /// false-positive; out-of-scope labels are still seeded.
+    #[test]
+    fn seed_excludes_in_scope_labels() {
+        let manifest: BTreeSet<String> = ["bxd", "KeepOut", "gone"]
+            .into_iter()
+            .map(String::from)
+            .collect();
+        let scope: BTreeSet<String> = ["bxd", "BXD", "gone"]
+            .into_iter()
+            .map(String::from)
+            .collect();
+        let mut seed = seed_labels_excluding_scope(manifest.iter(), &scope);
+        seed.sort();
+        assert_eq!(seed, vec!["KeepOut"]);
+    }
+
     /// The DELTA leftover path may only name in-scope datasets; without a
     /// scope it is the full INCREMENTAL leftover set.
     #[test]