Skip to content

fix(core): constant IRIs match unindexed data once the namespace table is full - #2413

Merged
bplatz merged 6 commits into
mainfrom
fix/overflow-iri-encoding
Nov 18, 2026
Merged

bplatz merged 6 commits into
mainfrom
fix/overflow-iri-encoding

Conversation

@bplatz

@bplatz bplatz commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Once a ledger's namespace table is full, a query with a constant IRI whose prefix has no code misses every fact about it that is not yet indexed. After the next index the facts reappear. On BSBM 100M, whose import always fills the table (#2135), every live write that introduced a new prefix hit this: the values were invisible to subject- and predicate-bound reads until a reindex.

Fixes #1842
Partially addresses #1891: graph Sids now take the overflow form, so a write into a named graph with such an IRI is accepted. The ok_or_else in build_reverse_graph is still unreachable, since encode_iri always returns Some.

What was wrong

  • Once every user code (13–65533) is taken, the write path stores an IRI whose canonical prefix has no code whole, as Sid(OVERFLOW, iri).
  • The read-side encoders fell back to Sid(EMPTY, iri) for the same IRI.
  • Persisted data still matched, because the subject dictionary is looked up by IRI and tries both codes. Novelty compares Sids, so (EMPTY, iri) never met (OVERFLOW, iri). That covered constant subjects, predicates, objects, datatypes and graphs, in SPARQL and JSON-LD alike.
  • A write into a named graph with such an IRI failed with InvalidGraph("flake references unknown graph Sid"): the graph map was keyed by the EMPTY form.

Changes

  • ns_encoding::encode_registered takes the table's fullness. An IRI whose prefix has no code encodes as Sid(OVERFLOW, iri) on a full table and as Sid(EMPTY, iri) otherwise, which is unchanged. While the table has room, no stored IRI has such a prefix.
  • Every read-side encoder goes through it:
    • LedgerSnapshot::encode_iri;
    • BinaryIndexStore::encode_iri;
    • the store's datatype Sids at load;
    • StatsIriEncoder;
    • the staged NamespaceRegistry's IriEncoder;
    • commit transfer's txn-meta graph Sid.
  • Fullness has one definition: the table holds the last user code (ns_encoding::table_full, NamespaceCodes::is_full).
  • encode_iri_strict returns the overflow Sid as well: on a full table every IRI has a known encoding. A constant therefore lowers to a Sid, not an Iri, so it keeps the planner's Sid-only lanes.

Index stats

Lowering an uncoded predicate to Sid(OVERFLOW, iri) exposed a mismatch with the index stats, which never key it that way:

  • Bulk import keys it (EMPTY, iri). A rebuild or an incremental index splits it at the longest registered prefix.
  • The planner's Sid lookup missed, read the miss as a predicate known to be absent, and estimated it at 0 rows. On BSBM 100M, where rev:reviewer is such a predicate, Q7 and Q8 planned a full scan of it first and went from tens of milliseconds to seconds.
  • Novelty's counts for the predicate, keyed by the write's Sid, landed in a second entry beside the index's.

Changes:

  • LedgerSnapshot re-keys each predicate in its stats by the Sid its IRI encodes to, as the stats enter the snapshot (new_meta, set_index_root_stats). That covers the property table and the class usages, ledger-wide and per graph.
    • Indexes from all three builders are covered without a reindex.
    • Stats already keyed that way are shared, not copied.
    • The key map comes from the property table, so the cost is per predicate, once per index load.
  • Stats Sids decode to IRIs through LedgerSnapshot::decode_sid, which knows the full-IRI codes. It replaces five copies that looked the code up in the namespace table: two in StatsView, two in GraphQL, one in the Cypher procedures. Those copies drop a Sid under the overflow code. Class keys already use that code, so CALL db.labels() and the GraphQL schema left out overflow classes.

BIND of a store id

BIND(?x AS ?y) evaluated ?x: a store id decoded to its IRI and came back as a Sid, which DISTINCT, joins and GROUP BY then looked up in the subject dictionary again, once per row. DESCRIBE binds its target that way, so DESCRIBE ?x WHERE { … } paid one reverse lookup per output triple, on any ledger.

On a full table this used to be free for an overflow IRI: it came back as Sid(EMPTY, iri), a key that sorts before the whole dictionary, so each lookup returned without reading a leaf. As Sid(OVERFLOW, iri) each one read the leaf, and BSBM Q9 (DESCRIBE ?x WHERE { <Review> rev:reviewer ?x }) went from 1.7 ms to about 21 ms.

  • The BIND operator copies a store id from a bare variable, dropping history metadata as evaluating does. Q9 makes 3 dictionary lookups instead of 9; a DESCRIBE over registered prefixes, 3 instead of 7.
  • Eager callers (datalog rule heads), which want decoded terms, still evaluate it.

Behavior changes (full table only)

Each follows from encode_iri_strict no longer returning None for an IRI with no code. Only the identity entry has a test of its own.

  • IRI() results bind as Sids, so they join with stored overflow subjects.
  • A typed literal whose datatype IRI has no code no longer fails with "Unknown datatype IRI".
  • Fix: an identity IRI with no code now resolves to the identity's subject, so its f:policyClass policies apply.
  • A policy-class IRI with no code resolves instead of failing with "Failed to resolve IRI". A stored class's policies load; a class no stored policy has loads none, as a misspelled class under a prefix with a code does, and default-allow governs.
  • A datalog rule's IRI("…") constant counts as known.
  • SHACL class checks and cross-ledger hydration look such IRIs up instead of skipping them.

Nothing changes for a table with room.

Tests

  • it_overflow_iri_bound_lookups (new):
    • Fills the table, indexes one subject, then commits a new subject and a new value on the indexed one.
    • Checks constant IRIs in subject, predicate, object, datatype and named-graph position: VALUES, s+p, s+p+o ASK, p+o, s+o, a join on ?p, VALUES-driven existence probes, JSON-LD twins, and a DELETE DATA of the novel facts.
    • Without the fix the named-graph insert is refused, and with that step skipped 18 checks miss.
    • Reverting either store-side change alone (BinaryIndexStore::encode_iri, or the store's datatype Sids) fails a check.
    • The stats encoder change only steers plan choice; no test pins it.
  • it_overflow_iri_bound_lookups::an_overflow_identity_has_its_policies_applied (new): an identity stored under OVERFLOW, with an f:policyClass that restricts what it sees, sees only what its policy allows, while it is only in novelty and once it is indexed. It fails without this PR's strict encoding.
  • it_overflow_iri_delete_index now also checks the bound reads while the deletes are pending, which Bound-IRI lookups miss overflow-namespace subjects in novelty #1842 had kept out. Those checks fail without the fix.
  • it_overflow_iri_bound_lookups also checks the stats. Each check fails without its change:
    • explain's estimate for an overflow predicate is its indexed count (0 without the re-key);
    • the merged stats count it once, novelty included (1 without);
    • db.labels(), db.propertyKeys() and the GraphQL schema list an overflow class and predicates (dropped without the decoder change).
  • db::tests::stats_key_each_predicate_as_its_iri_encodes: import- and rebuild-style keys are re-keyed in the property table and both class tables, and stats on a table with room are shared unchanged.
  • bind::tests::bind_of_a_var_holding_a_store_id_copies_the_id: the copy, without history metadata, and evaluation for an eager caller. Each half fails without its change.
  • namespace::tests::a_full_table_reads_an_uncoded_prefix_as_a_write_stores_it: the write path, the snapshot and the staged registry give the same Sid on a full table, and the EMPTY fallback while it has room.

Not in this PR

When merging into next

Once every user namespace code is taken, a write stores an IRI whose
canonical prefix has no code whole, as Sid(OVERFLOW, iri). The read-side
encoders fell back to Sid(EMPTY, iri) instead. Persisted data still
matched, because the subject dictionary is looked up by IRI, but novelty
compares Sids, so a constant IRI bound in a query missed every fact not
yet indexed: subject, predicate, object, datatype or graph. A write into
a named graph with such an IRI was refused as naming an unknown graph.

`ns_encoding::encode_registered` now takes the table's fullness and gives
the OVERFLOW form when the prefix has no code and the table is full. The
snapshot, the index store, the store's datatype Sids, the stats encoder,
the staged registry's IriEncoder and commit transfer all encode through
it, and test fullness through one definition (`table_full`,
`NamespaceCodes::is_full`): the table holds the last user code.
`encode_iri_strict` gives that Sid too, since on a full table every IRI
has a known encoding.
@bplatz bplatz added the bug Something isn't working as expected label Nov 16, 2026
Index builders key a predicate whose prefix has no code under a shorter
registered prefix (rebuild, incremental) or whole under EMPTY (import).
Once such a constant lowered to Sid(OVERFLOW, iri), the planner's stats
lookup missed and read the miss as a predicate known to be absent,
estimating it at 0 rows: BSBM Q7 and Q8 scanned rev:reviewer in full
first. Novelty's counts for the predicate, keyed by the write's Sid,
landed in a second entry beside the index's.

The snapshot re-keys its stats as they enter it (`new_meta`,
`set_index_root_stats`): the property table and the class usages,
ledger-wide and per graph, by the Sid each predicate's IRI encodes to.
No reindex is needed, and stats already keyed that way are shared.

Stats Sids decode through `LedgerSnapshot::decode_sid` instead of five
copies that looked the code up in the namespace table and so dropped a
Sid under the overflow code. Class keys already use it, so
`db.labels()` and the GraphQL schema left out overflow classes.
`BIND(?x AS ?y)` evaluated `?x`: a store id decoded to its IRI and came
back as a Sid, which DISTINCT, joins and GROUP BY then looked up in the
subject dictionary again, once per row. DESCRIBE binds its target that
way, so `DESCRIBE ?x WHERE { ... }` paid one reverse lookup per output
triple, on any ledger.

On a full namespace table an overflow IRI used to come back as
Sid(EMPTY, iri), a key that sorts before the whole dictionary, so those
lookups returned without reading a leaf. As Sid(OVERFLOW, iri) each one
read the leaf, and BSBM Q9 went from 1.7 ms to about 21 ms.

The BIND operator now copies a store id from a bare variable, dropping
history metadata as evaluating does. An eager caller, which wants
decoded terms, still evaluates it.

@aaj3f aaj3f left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bplatz this is the right altitude for #1842: one encoder that knows the table is full, every read-side site through it, and stats re-keyed at load to match. Approving to unblock.

The one must is a regression test for the identity-policy path on a full table, with the Behavior-changes entry worded as a fix rather than "resolve instead of failing"; I'll send details directly.

Relatedly, a policy-class naming no stored policy on a full table now falls to default-allow instead of refusing, as a coded-prefix typo already does. I think that's right, but wanted to confirm it's intended.

Merge note for main→next: #2422's StatsIriEncoder::from_namespace_codes needs table_full: false; otherwise the builders write OVERFLOW predicate Sids the store refuses to load (Claude tried it).

Full review below:


✅ Approving to unblock: please get a regression test for the identity-policy path on a full table in before merging. The encoder, the load-time re-key and the BIND copy each do what they claim. Claude checked the miss and the fix on a box across constants, a two-ledger dataset and all three index builders, and found BIND's answers unchanged under DISTINCT, GROUP BY, joins and history. The one must is a test plus some wording.

Before merging:

  1. fluree-db-core/src/db.rs:511: add a regression test for the identity-policy path on a full table, and word the Behavior-changes entry as a fix rather than "resolve instead of failing" (details sent directly).

Notes:

  • This is the read-side fix for a class we've hit several times: "an IRI encoded by a second encoder that disagrees with the one the write path stored it under". Instances: #2142 (4c32809e0, 3323124d4), #1842 and #1891 here, and #2422's a8eedba58 (stats keyed by longest prefix, read by canonical split). encode_registered is now the chokepoint for the snapshot, the store, the datatype Sids, the stats encoder, the staged registry and commit transfer. The sites still outside it are the index-root writers (import.rs:7138, rebuild.rs:1006, :1091, incremental.rs:5154) and lookup_sid_for_iri, as the body says, and the end state ("a root stores what the write path stores") needs the reader to accept OVERFLOW predicate Sids, which is #2135 territory. Not this PR: the point fixes are right here.
  • Stack altitude: none of this PR's 14 files overlap #2403–#2409. Its three commits apply to current main (with #2214 and #2227 merged) with one conflict, the encode_iri_strict doc comment at db.rs:511, which #2214 also edited (keep both sentences). On that tree it_overflow_iri_bound_lookups and the three new unit tests pass on a box. So this could land on main ahead of the stack.
  • git merge-tree against my #2419 and #2201 is clean. Onto #2422 the only textual conflict is cypher_procedures.rs display_name (keep next's is_rdf_reifies guard and this PR's decode_sid), then the table_full field above.
  • #2415 stacks on this, and its DESCRIBE path relies on the third commit's BIND copy.
Adherence: Patterns ✔ · Performance ✔ · Deployment ✔ · Testing ⚠️ · Conventions ✔ · verification
  • Patterns/abstractions: ✔ extends encode_registered into the one IRI → Sid rule every read-side encoder shares; the stats re-key reuses decode_sid, and five hand-rolled prefix lookups go away. Shared IR, so SPARQL and JSON-LD get it alike (the new test covers both).
  • Performance (speed first, memory second): ✔ the fullness test runs only on a prefix miss; the re-key runs once per index load and shares the stats when no key changes (Claude timed it in a release build: about 7 µs for 50 predicates, 1.44–1.46 ms for 10,000, 4.21–4.23 ms when all 10,000 re-key); the BIND copy removes a decode and a downstream per-row dictionary lookup. No performance-degradation risk.
  • Deployment targets: ✔ shared code every host runs, with no background work, no process-lifetime state and nothing a wasm32 build or a short-lived embedder forbids; the re-key is per snapshot.
  • Testing: ⚠️ the new integration and unit tests are wired (grp_query_sparql, grp_transact, crate unit tests) and cover the encoder sites and the stats; the five full-table behavior changes have no tests of their own, and the identity-policy one needs one before merging.
  • Conventions: ✔ multi-line bodies on all three commits; the Behavior-changes entry should word the identity-policy change as a fix.

Verified at b231f31d6: CI has not run on this head (release-workflow checks only), so Claude ran CI's jobs at it: all green, and nextest's three non-passes didn't reproduce on rerun (the localstack suite 9 of 9, the grp_index warm-reads test 200 of 200). On a c7i.4xlarge, Claude ran base/head probes for class policies, a two-ledger constant, stats after import/incremental/rebuild, and fourteen BIND shapes (identical answers); applied the commits to main and to #2422's head (E0063; table_full: false passes, fullness-from-codes fails at index load); and git merge-tree against #2419, #2201, #2422 and main.

Approving so you can merge once that test is in, but maybe worth folding in the stats_view.rs comment while you're there.

Comment thread fluree-db-core/src/db.rs Outdated
/// the EMPTY namespace for unknown IRIs. Use this when the caller needs
/// to distinguish between known and unknown namespaces (e.g., validating
/// user-supplied IRIs in BIND expressions or policy identity resolution).
/// Once the table is full, every IRI has a known encoding: its prefix's

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking (test needed).

The identity-policy path changes behavior on a full table here, and nothing pins it.

The body's Behavior-changes entry describes it as "resolve instead of failing with 'Failed to resolve IRI'". That's accurate for policy-class, but for identity it undersells the change: on a full table this is a fix, and reverting any one of the read-side encoders this PR routes through encode_registered would undo it without a test noticing.

Before merging, please add a regression test for the identity-policy path on a full table, novelty and indexed (the table-filling fixture from it_overflow_iri_bound_lookups covers the setup), and word the Behavior-changes entry as a fix rather than "resolve instead of failing". I'll send details directly. Three comments in policy_builder.rs also still describe the old strict behavior (:623, :1612-1622, :1625-1633) and are worth updating alongside. Commenting here because fluree-db-api/src/policy_builder.rs is not in this diff.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 0c0d6af. The Behavior-changes entry is reworded as a fix in the PR body.

/// IRI prefix -> namespace code, shared with the snapshot.
reverse: Arc<HashMap<String, u16>>,
split_mode: NsSplitMode,
table_full: bool,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional (merge note).

When main meets next, #2422's StatsIriEncoder::from_namespace_codes needs table_full: false, and a comment here would make that hard to get wrong.

git merges this file cleanly with #2422, but #2422's constructor builds Self { reverse, split_mode }, so the merged tree fails with error[E0063]: missing field 'table_full' (Claude built #2413's commits on #2422's head). Under #2422 the full and incremental builders encode the root's predicate_sids through that constructor. Take fullness from the codes and they write (OVERFLOW, iri), which build_dictionary_set (fluree-db-binary-index/src/read/binary_index_store.rs:3748-3754) refuses. On the box, it_overflow_iri_bound_lookups then fails at reload with failed to load binary index: predicate[4]: unknown ns_code 65534. With table_full: false it passes, and this PR's load-time re-key covers the planner.

Maybe a line on this field along the lines of "a snapshot's encoder only: an index root's predicate table never stores OVERFLOW, so the indexer's encoder keeps this false"? This is minor and non-blocking, but if you agree it's right, I'd rather see it folded in now than rediscovered in the merge.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in fc45bb2. The merge note is also in the PR body, under "When merging into next".

/// `OVERFLOW` once `table_full`. While the table has room, a prefix without a
/// code belongs to no stored IRI, and the result is `Sid(EMPTY, iri)`.
#[inline]
pub fn encode_registered(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Praise. Making encode_registered the one place every read-side encoder asks, with the fullness test run only on a miss, is the right chokepoint. table_full as "holds LAST_USER_CODE" is exactly the write path's overflow test, since next_code is max_code + 1 (:557, :592), so the two can't drift even with gaps in the table.

Base automatically changed from fix/query-peers-shared-storage to main November 18, 2026 22:20
…ding

# Conflicts:
#	fluree-db-core/src/db.rs
Once the namespace table is full, an identity whose IRI has a prefix
with no code is stored whole, under OVERFLOW. Its policies are found
only if the identity's IRI encodes the same way when a query names it
in `opts.identity`. The new test stores such an identity with an
`f:policyClass` that restricts what it sees, and checks the
restriction holds with the identity only in novelty and again once it
is indexed. The table-filling subjects move into a helper both tests
share.

The policy builder's comments described the strict resolvers as
refusing any IRI without a registered prefix. They now say what holds:
only an IRI the ledger cannot hold is refused, and on a full table an
identity or a policy class encodes as the write path stored it. A
class that no stored policy has then loads none, as a misspelled class
under a coded prefix does.
The stats encoder takes the namespace table's fullness so that, like
the snapshot's encoder, it keys an uncoded IRI under OVERFLOW on a full
table. An encoder that keys an index root's predicate table must not:
a root never stores OVERFLOW predicate Sids, and the store refuses to
load one. The field's comment now says so, for any constructor that
builds the encoder from a root's codes.
@bplatz

bplatz commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

The one must is a regression test for the identity-policy path on a full table, with the Behavior-changes entry worded as a fix

Addressed in 0c0d6af (novelty and indexed; it fails with the old strict encoding). The PR body's entry is reworded.

a policy-class naming no stored policy on a full table now falls to default-allow instead of refusing … wanted to confirm it's intended

Yes, intended. The refusal guarded against an encoding that could never match a stored class; on a full table the overflow encoding does match one, so its policies load. A class no stored policy has now behaves as a misspelled class under a prefix with a code already does. The comment on resolve_policy_class_iri_to_sid says so (0c0d6af), and so does the PR body.

Merge note for main→next: #2422's StatsIriEncoder::from_namespace_codes needs table_full: false

Addressed in fc45bb2, and noted in the PR body under "When merging into next".

@bplatz
bplatz merged commit 4e572f7 into main Nov 18, 2026
21 checks passed
@bplatz
bplatz deleted the fix/overflow-iri-encoding branch November 18, 2026 23:29
bplatz added a commit that referenced this pull request Nov 18, 2026
Brings #2413.

`display_name` in the Cypher procedures keeps next's `rdf:reifies`
guard and takes main's `decode_sid`, so the catalogs name an overflow
class or predicate on next too. next has no other hand-rolled Sid
decoders beyond the ones main replaced.

`StatsIriEncoder` has only the snapshot constructor on next. #2422,
still open against next, adds one for an index root's predicate
table; that constructor must set `table_full: false`, since a root
never stores OVERFLOW predicate Sids and the store refuses to load
one.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bound-IRI lookups miss overflow-namespace subjects in novelty

2 participants