Repository navigation
fix(core): constant IRIs match unindexed data once the namespace table is full - #2413
Conversation
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.
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
left a comment
There was a problem hiding this comment.
@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:
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'sa8eedba58(stats keyed by longest prefix, read by canonical split).encode_registeredis 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) andlookup_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, theencode_iri_strictdoc comment atdb.rs:511, which #2214 also edited (keep both sentences). On that treeit_overflow_iri_bound_lookupsand the three new unit tests pass on a box. So this could land onmainahead of the stack. git merge-treeagainst my #2419 and #2201 is clean. Onto #2422 the only textual conflict iscypher_procedures.rsdisplay_name(keep next'sis_rdf_reifiesguard and this PR'sdecode_sid), then thetable_fullfield 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_registeredinto the one IRI → Sid rule every read-side encoder shares; the stats re-key reusesdecode_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.
| /// 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
…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.
Addressed in 0c0d6af (novelty and indexed; it fails with the old strict encoding). The PR body's entry is reworded.
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
Addressed in fc45bb2, and noted in the PR body under "When merging into next". |
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.
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_elseinbuild_reverse_graphis still unreachable, sinceencode_irialways returnsSome.What was wrong
Sid(OVERFLOW, iri).Sid(EMPTY, iri)for the same IRI.(EMPTY, iri)never met(OVERFLOW, iri). That covered constant subjects, predicates, objects, datatypes and graphs, in SPARQL and JSON-LD alike.InvalidGraph("flake references unknown graph Sid"): the graph map was keyed by the EMPTY form.Changes
ns_encoding::encode_registeredtakes the table's fullness. An IRI whose prefix has no code encodes asSid(OVERFLOW, iri)on a full table and asSid(EMPTY, iri)otherwise, which is unchanged. While the table has room, no stored IRI has such a prefix.LedgerSnapshot::encode_iri;BinaryIndexStore::encode_iri;StatsIriEncoder;NamespaceRegistry'sIriEncoder;ns_encoding::table_full,NamespaceCodes::is_full).encode_iri_strictreturns the overflow Sid as well: on a full table every IRI has a known encoding. A constant therefore lowers to aSid, not anIri, 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:(EMPTY, iri). A rebuild or an incremental index splits it at the longest registered prefix.rev:revieweris such a predicate, Q7 and Q8 planned a full scan of it first and went from tens of milliseconds to seconds.Changes:
LedgerSnapshotre-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.LedgerSnapshot::decode_sid, which knows the full-IRI codes. It replaces five copies that looked the code up in the namespace table: two inStatsView, two in GraphQL, one in the Cypher procedures. Those copies drop a Sid under the overflow code. Class keys already use that code, soCALL 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, soDESCRIBE ?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. AsSid(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.Behavior changes (full table only)
Each follows from
encode_iri_strictno longer returningNonefor 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.f:policyClasspolicies apply.default-allowgoverns.IRI("…")constant counts as known.Nothing changes for a table with room.
Tests
it_overflow_iri_bound_lookups(new):VALUES, s+p, s+p+oASK, p+o, s+o, a join on?p,VALUES-driven existence probes, JSON-LD twins, and aDELETE DATAof the novel facts.BinaryIndexStore::encode_iri, or the store's datatype Sids) fails a check.it_overflow_iri_bound_lookups::an_overflow_identity_has_its_policies_applied(new): an identity stored underOVERFLOW, with anf:policyClassthat 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_indexnow 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_lookupsalso checks the stats. Each check fails without its change: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
NamespaceRegistry::lookup_sid_for_iristill returnsNonefor an IRI with no code on a full table. Its callers treat such an IRI as unknown:uniquePropertiesvalidation;Changing it would make the
uniquePropertiestypo check silent on a full table, so it needs its own decision.The indexer and the importer still key predicates (the root's predicate Sids and the stats) by a longest-prefix match with a
(0, iri)fallback. No query sees those keys: the store looks predicates up by IRI, and stats are re-keyed at load. Writing the overflow form into a root would change the index format.What overflow placement costs, and how the table is allocated: Measure namespace overflow costs near the 16-bit limit before choosing wider ids or better overflow handling #2135, Bulk import assigns namespace codes nondeterministically; once the table fills this changes overflow placement and query time #2134.
When merging into next
StatsIriEncoder::from_namespace_codesmust build the encoder withtable_full: false. It keys an index root's predicate table, which never storesOVERFLOW; taking fullness from the codes writesOVERFLOWpredicate Sids the store refuses to load.cypher_procedures.rsdisplay_name: keep next'sis_rdf_reifiesguard and this PR'sdecode_sid.