Skip to content

Multi-ledger datasets: datatype-constraint Sid is never re-encoded per graph, so cross-ledger custom-datatype matches silently drop #1771

Closed

Description

@aaj3f

Raised by @bplatz in review of #1746 (read off the code there); confirmed by fixture below. Not introduced by that PR — the underlying gap predates it — but #1746 changed one failure mode from wrong-rows to silently-empty, so this is the natural home for both.

Problem

In a multi-ledger dataset query, the datatype-constraint Sid on a triple pattern (pattern.dtc) is resolved once, against the primary (lowering) ledger's snapshot, and never re-encoded into the per-graph snapshots the way subject/predicate/object Sids are. query_dataset lowers against primary.snapshot (fluree-db-api/src/view/dataset_query.rs:141-165 — the first default graph), and per-graph execution re-encodes s/p/o through context::reencode_sid (fluree-db-query/src/binary_scan.rs:1777-1836, build_match_val_for_snapshot) — but dtc reaches every dt_compatible comparison as the primary encoded it:

  • fluree-db-query/src/binary_scan.rs:846 — range-fallback flake filter
  • fluree-db-query/src/binary_scan.rs:1286 — matches_datatype_constraint, the binary-store cursor lane (resolves the flake's dt from the per-graph store's dictionary, then compares against the primary-space dtc)
  • fluree-db-core/src/range.rs:289 — flake_matches_range_eq

dt_compatible is exact Sid equality outside the XSD numeric families, and namespace codes are assigned per ledger in first-use order, so any custom datatype whose namespace isn't registered on the primary — or is registered under a different code than on the graph being scanned — constrains against a Sid no flake in that graph carries.

Two concrete shapes:

  1. Datatype registered only on a non-primary ledger. The primary can't encode it. Before fix: fail closed on unencodable datatype IRIs; keep the membership-join lane join-equivalent on list rows #1746 the lowering fell back to xsd:string, so the pattern matched the primary's plain-string rows (wrong rows); after fix: fail closed on unencodable datatype IRIs; keep the membership-join lane join-equivalent on list rows #1746 it lowers to the EMPTY-namespace full-IRI Sid, so it matches nothing (silently drops the real matches on the other ledger). Both wrong; fail-closed is the better interim, but the real rows are still unreachable.
  2. Datatype registered on both ledgers under divergent codes. Pre-existing and unchanged by fix: fail closed on unencodable datatype IRIs; keep the membership-join lane join-equivalent on list rows #1746: the constraint carries the primary's code, the other graph's flakes carry theirs, exact equality fails, and the non-primary rows silently drop.

Fixture (executed at #1746 head 3d415d583 and with origin/main's xsd:string fallback swapped back in)

Two memory ledgers per case, composed with DataSetDb::new().with_default(...), queried through the public fluree.query_dataset(...) surface. ct: = http://custom-types.test/.

  • V1: ledger A (primary) holds ex:s1 ex:p "a" (plain string; ct: unregistered). Ledger B holds ex:s2 ex:p "a"^^ct:T (ct: registered, code 14). Query: SELECT ?s WHERE { ?s ex:p "a"^^ct:T }. Correct answer: [s2].
  • V2: ledger C (primary) pads its namespace table first, then registers ct: (code 15) with a row ex:c1 ex:p "z"^^ct:T; ledger D registers ct: unpadded (code 14) with ex:d1 ex:p "b"^^ct:T. Query: SELECT ?s WHERE { ?s ex:p "b"^^ct:T }. Correct answer: [d1].
Probe Correct main (xsd:string fallback) #1746 head (fail-closed)
V1 — ct: only on B [s2] [s1] — the primary's plain-string row, i.e. the wrong row [] — silent drop
V1 control — B queried alone (B primary) [s2] [s2] [s2]
V2 — codes 15 vs 14 [d1] [] []
V2 control — primary's own "z"^^ct:T row [c1] [c1] [c1]

The controls pin that the constraint machinery works whenever the Sid spaces align, so the empty results are the cross-graph encoding mismatch and nothing else.

Full probe test (drop into fluree-db-api/tests/ with a [[test]] target, required-features = ["native"])
//! PROBE: does the datatype-constraint Sid survive a multi-ledger dataset
//! query when the datatype's namespace is not registered on the primary
//! (lowering) ledger — or registered under a different code?

#![cfg(feature = "native")]

mod support;
use crate::support::genesis_ledger;
use fluree_db_api::{DataSetDb, FlureeBuilder, GraphDb};
use serde_json::{json, Value};

const P: &str = "PREFIX ex: <http://example.org/ns/>\nPREFIX ct: <http://custom-types.test/>\n";

async fn run(
    fluree: &fluree_db_api::Fluree,
    dataset: &DataSetDb,
    body: &str,
) -> Result<Value, String> {
    let sparql = format!("{P}{body}");
    let result = fluree
        .query_dataset(dataset, sparql.as_str())
        .await
        .map_err(|e| e.to_string())?;
    let primary = dataset.primary().expect("primary");
    result
        .to_jsonld(primary.snapshot.as_ref())
        .map_err(|e| e.to_string())
}

fn ns_code(snapshot: &fluree_db_core::LedgerSnapshot, iri: &str) -> String {
    match snapshot.encode_iri(iri) {
        Some(sid) => format!("Sid(ns={}, name={:?})", sid.namespace_code, sid.name),
        None => "UNREGISTERED".to_string(),
    }
}

/// V1 — custom datatype registered ONLY in ledger B (non-primary).
/// Correct answer: ex:s2 (the B row).
#[tokio::test]
async fn v1_dtc_unregistered_in_primary() {
    let fluree = FlureeBuilder::memory().build_memory();

    let a0 = genesis_ledger(&fluree, "probe/a:main");
    let a = fluree
        .insert(
            a0,
            &json!({
                "@context": {"ex": "http://example.org/ns/"},
                "@id": "ex:s1", "ex:p": "a"
            }),
        )
        .await
        .expect("insert a")
        .ledger;

    let b0 = genesis_ledger(&fluree, "probe/b:main");
    let b = fluree
        .insert(
            b0,
            &json!({
                "@context": {"ex": "http://example.org/ns/", "ct": "http://custom-types.test/"},
                "@id": "ex:s2", "ex:p": {"@value": "a", "@type": "ct:T"}
            }),
        )
        .await
        .expect("insert b")
        .ledger;

    eprintln!(
        "V1 ct:T in A: {} | in B: {}",
        ns_code(&a.snapshot, "http://custom-types.test/T"),
        ns_code(&b.snapshot, "http://custom-types.test/T"),
    );

    let dataset = DataSetDb::new()
        .with_default(GraphDb::from_ledger_state(&a))
        .with_default(GraphDb::from_ledger_state(&b));

    // Control: the union reaches both rows at all.
    let all = run(&fluree, &dataset, "SELECT ?s ?o WHERE { ?s ex:p ?o }").await;
    eprintln!("V1 control (all rows): {all:?}");

    // Sanity: B queried alone finds its own row by the constraint.
    let b_only = DataSetDb::new().with_default(GraphDb::from_ledger_state(&b));
    let b_alone = run(&fluree, &b_only, r#"SELECT ?s WHERE { ?s ex:p "a"^^ct:T }"#).await;
    eprintln!("V1 B-alone (B primary, should be s2): {b_alone:?}");

    // THE PROBE: constrain on the datatype registered only in B, lowered
    // against A. Correct answer: [["ex:s2"]].
    let probe = run(&fluree, &dataset, r#"SELECT ?s WHERE { ?s ex:p "a"^^ct:T }"#).await;
    eprintln!("V1 PROBE (correct = s2): {probe:?}");
}

/// V2 — datatype registered in BOTH ledgers but under DIFFERENT namespace
/// codes. Correct answer for the probe: ex:d1 (the D row).
#[tokio::test]
async fn v2_dtc_divergent_codes() {
    let fluree = FlureeBuilder::memory().build_memory();

    // Ledger C (primary): pad the namespace table first so ct: lands on a
    // different code than in D.
    let c0 = genesis_ledger(&fluree, "probe/c:main");
    let c1 = fluree
        .insert(
            c0,
            &json!({
                "@context": {"ex": "http://example.org/ns/", "other": "http://other.test/"},
                "@id": "ex:c0", "other:q": "x"
            }),
        )
        .await
        .expect("insert c pad")
        .ledger;
    let c = fluree
        .insert(
            c1,
            &json!({
                "@context": {"ex": "http://example.org/ns/", "ct": "http://custom-types.test/"},
                "@id": "ex:c1", "ex:p": {"@value": "z", "@type": "ct:T"}
            }),
        )
        .await
        .expect("insert c")
        .ledger;

    // Ledger D: ct: registered without the pad.
    let d0 = genesis_ledger(&fluree, "probe/d:main");
    let d = fluree
        .insert(
            d0,
            &json!({
                "@context": {"ex": "http://example.org/ns/", "ct": "http://custom-types.test/"},
                "@id": "ex:d1", "ex:p": {"@value": "b", "@type": "ct:T"}
            }),
        )
        .await
        .expect("insert d")
        .ledger;

    eprintln!(
        "V2 ct:T in C: {} | in D: {}",
        ns_code(&c.snapshot, "http://custom-types.test/T"),
        ns_code(&d.snapshot, "http://custom-types.test/T"),
    );

    let dataset = DataSetDb::new()
        .with_default(GraphDb::from_ledger_state(&c))
        .with_default(GraphDb::from_ledger_state(&d));

    // Control: union sees both typed rows.
    let all = run(&fluree, &dataset, "SELECT ?s ?o WHERE { ?s ex:p ?o }").await;
    eprintln!("V2 control (all rows): {all:?}");

    // Self-match control: the constraint mechanism works for the primary's own
    // row (codes trivially align). Correct: [["ex:c1"]].
    let self_match = run(&fluree, &dataset, r#"SELECT ?s WHERE { ?s ex:p "z"^^ct:T }"#).await;
    eprintln!("V2 self-match (correct = c1): {self_match:?}");

    // THE PROBE: the matching row lives only in D, whose ct: code differs.
    // Correct answer: [["ex:d1"]].
    let probe = run(&fluree, &dataset, r#"SELECT ?s WHERE { ?s ex:p "b"^^ct:T }"#).await;
    eprintln!("V2 PROBE (correct = d1): {probe:?}");
}

Verbatim output at #1746 head:

V1 ct:T in A: Sid(ns=0, name="http://custom-types.test/T") | in B: Sid(ns=14, name="T")
V2 ct:T in C: Sid(ns=15, name="T") | in D: Sid(ns=14, name="T")
V1 B-alone (B primary, should be s2): Ok(Array [Array [String("ex:s2")]])
V1 PROBE (correct = s2): Ok(Array [])
V2 self-match (correct = c1): Ok(Array [Array [String("ex:c1")]])
V2 PROBE (correct = d1): Ok(Array [])

With origin/main's encode_iri_strict(...).unwrap_or(xsd:string) fallback swapped back into datatype_sid, V1's probe returns [["ex:s1"]] — the wrong row — and everything else is identical.

Suggested fix

Re-encode dtc into the per-graph snapshot the same way s/p/o are — decode against ctx.original_snapshot, encode against the active graph's snapshot (context::reencode_sid), computed once per scan open rather than per flake. That one move fixes both shapes:

The sites are the three dt_compatible consumers above; probably a per-open "effective dtc" on the scan rather than three call-site translations, so the per-flake loops stay untouched. The lang-tag half of DatatypeConstraint needs nothing (tags are strings, not Sids). Worth checking while in there whether binding-carried datatype Sids (VALUES rows, per-row join probes) can cross graph boundaries the same way — I traced the constraint path only.

Adjacent observation (same seam, probably out of scope here)

The fixture also shows the formatting side of the seam on the same public surface: result.to_jsonld(primary.snapshot) on the V1 union query fails with Unknown namespace code: 14 (B's Sid reaching the primary's decoder), and in V2 it silently decodes D's ct:T as http://other.test/T — the primary's namespace at code 14, i.e. the wrong IRI with no error. That's the #1639 family (SERVICE IRIs decoded against the requesting ledger's table) showing up on the dataset surface. Noting it here so it isn't lost; if it isn't already covered by #1639 it likely deserves its own issue rather than scope-creep on this one.

References

Activity

  1. added
    P2
    area:query
    on Sep 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2area:query

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions