Repository navigation
fix(query): time travel loses retracted facts of a type their leaflet no longer holds - #2373
Conversation
A POST/PSOT leaflet's `o_type_const` is taken over its rows alone, while the history sidecar keeps retracted facts under their own types. Once every ref of a predicate is retracted and indexed, the leaflet reports the type of the literals left behind, and a read at the earlier `t` went wrong in two ways: - the cursor skipped the leaflet by that constant, so a bound-object pattern (`?x ex:tag ex:bob`, or a bound integer) returned no rows and COUNT returned 0; - the batched subject-join and probe lanes labelled replayed rows with it, so the retracted ref came back as a string. `LeafletDirEntryV3::o_type_const_for` gives a reader no constant when it also takes rows from the sidecar, and `replays_history` replaces the five hand-written copies of the predicate that decides that.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz nice find, and I think reader-side is the right altitude here. Making the writer clear the constant whenever the sidecar holds another type would only reach existing indexes after a reindex. It would also cost every head read that leans on the constant (the IRI-only and single-type fast paths), for any predicate that ever held a second type.
Two headline notes:
(1) This is the third round of "a directory fact computed over live rows, trusted below the index t" (#1223, #1624, now this). The five loops aren't the only readers, though. Claude found two more that still read the raw o_type_const at a past t: the FILTER(?v = k) integer-seek proof and the #1652 composite-count gate. Both reproduced on a box with a fix using your new helpers (inline below), and I'd like those in this PR. A third, the list census built from HAS_O_I, is a store-level cache. Since none of the three sit in the five loops #2375 targets, I'd lean toward its "simpler alternative" (the raw field behind an at-t accessor, and the same for HAS_O_I) as the part that turns the next one into a compile error.
(2) #2374 conflicts with this in for_each_object_probe_match, mechanically. I'd land this first and have #2374 pick up replays_history when it rebases.
Full review below:
✅ Approving to unblock: please get the two blocking fixes below in before merging.
This is carefully built, @bplatz. The two helpers replace five hand-written copies of the replay predicate, and the cursor skip and all three labelling lanes go through them. Nothing on disk changes, so every existing index reads correctly under it. The test stamps the batched lanes, so no shape can pass through the cursor by accident. Both blockers are pre-existing, not introduced here. But they are this PR's bug on two more paths (a read below the index trusting a type constant taken over live rows), and each is about six lines with your new helpers. So I'd rather they land with this than wait on #2375.
Adherence to repo commitments:
- Patterns/abstractions:
⚠️ The fix extendsLeafletDirEntryV3with the shared predicate instead of adding a sixth copy. But two readers outside the five loops still read the raw field below the index (the two blockers). - Performance (speed first, memory second): ✔ No per-row work is added at head, and the per-leaflet check is the same predicate computed a few lines earlier. Claude ran a box A/B, main vs this head, on 8 join and bound-object lanes at head and below the index plus
query_hot_bsbm/query_hot_optional. Every row is within ±4% (one noisy bench aside, which swung 30% between main's own runs), and every regression-direction move is inside main's own run-to-run spread or within 0.6%. No performance-degradation risk. - Deployment targets: ✔ n/a. This is pure read-path computation in
fluree-db-binary-index/fluree-db-query, reached the same way by every host (embeddedfluree-db-api,fluree-db-server, wasm32). It adds no I/O, threads, clocks or caches. - Testing: ✔ Three index strategies, SPARQL plus a JSON-LD twin, head and history-range controls, and lane stamps. CI ran
retracted_type_shapes_*by name on this head.⚠️ The two blockers each want a shape in the new test. - Conventions: ✔ The commit has a multi-line body. fmt and clippy are green in CI. There's no format or docs change to make.
Verified at branch HEAD: CI is green on c353574e4 (run 43351488196: test with 15,859 passed, clippy, fmt, testsuite-sparql, wasm32, wasm-smoke). On a box, Claude ran:
- the new tests: they pass;
- four single-site mutations: all red;
- the star-SPOT mutation: green, as expected;
- 20 extra time-travel shapes against three index strategies;
- both sibling fixes: verified, with their regression suites.
Approving so you can merge once those two are in.
| /// literals left behind. A reader that also takes rows from the sidecar | ||
| /// (`reads_history`) therefore has no constant to skip or label by. | ||
| #[inline] | ||
| pub fn o_type_const_for(&self, reads_history: bool) -> Option<u16> { |
There was a problem hiding this comment.
Blocking. One more reader trusts o_type_const at a past t, outside the five loops this helper replaced: predicate_otype_uniform (fluree-db-query/src/binary_scan.rs:351, the check at :371). It's the proof behind the integer point seek for FILTER(?v = k) (called at :2561).
It walks the predicate's POST directory and engages the integer-only seek when every non-empty leaflet's o_type_const is the integer type. Unlike its decimal sibling prove_decimal_only (gated to current reads at :2237), it runs below the index too. A leaflet whose last xsd:double was retracted reports the integer type, so the proof passes. The cursor then seeks the integer slice only, and the double that replay would have restored is dropped. It's the "type its leaflet no longer holds" bug this PR fixes, on the planner side. It predates this PR (#1448, 7cc856533), but it's this PR's title on another path.
Claude reproduced it on a box at this head. The data: at t=1, ns:a ns:num 7 and ns:b ns:num "7"^^xsd:double (plus 8 and 9 on other subjects); t=2 retracts the double; then index. At t=1, SELECT ?x WHERE { ?x ns:num ?v FILTER(?v = 7) } returns [ns:a] on both full-rebuild and incremental indexes, where novelty-only returns [ns:a, ns:b]. COUNT(*) of the same pattern gives 1 against 2. Head is right.
The fix uses your new helpers. Claude verified it on the box: both shapes then match novelty-only, and retracted_type_shapes_*, the rest of it_query_time_travel_bgp and cypher_equality_seek_correct_under_predicate_novelty stay green. Reverting it turns the shapes red again:
// Below the index, a leaflet's history can hold a type its rows do not.
let replay_to = (ctx.to_t < store.max_t()).then_some(ctx.to_t);
// ... in the directory loop:
let replays = entry.replays_history(replay_to);
if (entry.row_count == 0 && !replays) || entry.p_const != Some(p_id) {
continue;
}
if entry.o_type_const_for(replays) != Some(ot16) {
return Ok(false);
}A FILTER(?v = 7) shape with a retracted double in retracted_type_shapes would pin it.
Commenting here because fluree-db-query/src/binary_scan.rs is not in this diff.
| /// Such a read cannot go by what the directory says of the rows alone: | ||
| /// their count, their key range, or their type constant. | ||
| #[inline] | ||
| pub fn replays_history(&self, replay_to: Option<i64>) -> bool { |
There was a problem hiding this comment.
Blocking. A second reader outside the five loops: predicate_unsafe_for_cross_predicate_o_key_join (fluree-db-query/src/fast_path_common.rs:452). It's the #1652 gate for the composite-key count COUNT { ?s <p1> ?o . ?s <p2> ?o }.
The gate decides from HAS_O_I and o_type_const (:467, :470) that neither predicate holds a list row or an arena-keyed decimal. CompositeJoinPairCount is overlay-supported (count_plan_exec.rs:181), so count_plan runs it at a past t too, calling the gate at :3715. Below the index, those flags describe live rows only. A decimal retracted after t passes the gate, and the merge-join then compares per-predicate arena handles that never compare equal.
Claude reproduced it on the box at this head. The data: at t=1, ns:zz ns:p1 1.5 and ns:zz ns:p2 1.5 as xsd:decimal, two more p1 decimals so the handles differ, and ns:c ns:p1 3 / ns:c ns:p2 3; t=2 retracts the decimals; then index. At t=1, SELECT (COUNT(*) AS ?c) WHERE { ?s ns:p1 ?o . ?s ns:p2 ?o } returns 1 on both index strategies, against 2 novelty-only. The same pattern selecting rows returns both rows everywhere, so only the count lane is wrong.
Suggested fix: thread replay_to into the gate and treat a leaflet with newer history as unsafe. Claude verified it on the box: the count is 2 on both strategies, and it_fastpath_1652_regression, grp_query, grp_query_sparql, the fluree-db-query lib tests and the time-travel suite stay green.
let replays = entry.replays_history(replay_to);
if (entry.row_count == 0 && !replays) || entry.p_const != Some(p_id) {
continue;
}
// The flags and the type constant describe live rows; history
// newer than the read can hold list rows or arena handles.
if replays {
return Ok(true);
}The caller passes (ec.ctx.to_t < ec.store.max_t()).then_some(ec.ctx.to_t). A composite-count shape in the new test would pin this one too.
Commenting here because fluree-db-query/src/fast_path_common.rs and count_plan_exec.rs are not in this diff.
| /// read at the index's own `t`, which replays nothing. | ||
| /// | ||
| /// Such a read cannot go by what the directory says of the rows alone: | ||
| /// their count, their key range, or their type constant. |
There was a problem hiding this comment.
Optional, and more a note for #2375 than an ask for this PR. HAS_O_I belongs on this comment's list of things the directory only says of live rows.
The list census caches are built from it:
list_predicate_ids(binary_index_store.rs:2643) andleaf_list_subjects(:2781) skip every leaflet without the flag.ListView::for_db(list_view.rs:86) trusts the resulting set.
So below the index, a predicate whose lists were all retracted later isn't a list predicate anymore.
Claude reproduced it on the box. A CONSTRUCT { ns:alice ns:items ?o } WHERE { ns:alice ns:items ?o } at t=1 returns "ns:items": ["x","y","z"] once the list was retracted at t=3 and indexed. Novelty-only returns {"@list": ["x","y","z"]}. Forcing for_db to "any predicate may hold lists" made both index strategies match, so that gate is the cause.
The reach is narrower than the two above: CONSTRUCT templates that restate list entries, and the opt-in RDF list view. The fix is also a different layer: a store-level cache with no notion of t. So this is the one place I'd say the class issue is the right home rather than this PR. Could we add a HAS_O_I row to #2375's table, and maybe name the flag in this comment too?
| /// Which lane a shape must answer through on an indexed ledger, so it cannot | ||
| /// pass by way of a reader the shape was not written for. | ||
| #[derive(Clone, Copy)] | ||
| enum Lane { |
There was a problem hiding this comment.
Praise. Really nice to see the batched lanes stamped, so the subject-join and OPTIONAL shapes can't pass by falling through to the cursor. Claude reverted each fix site alone on a box, and each went red on its matching shape:
- the cursor skip and the helper itself: bound ref
[]; scan_matches: subject join"bob";- the subject probe: OPTIONAL
"bob".
The star-SPOT site stays green, as the body says.
…t below the index
The integer-only proof behind the FILTER(?v = k) point seek and the
composite-count gate for COUNT { ?s p1 ?o . ?s p2 ?o } read o_type_const
and HAS_O_I at a past t, where both describe live rows only. A retracted
double of the same value was never read by the seek, and a retracted
decimal pair was counted as two arena handles. A leaflet the read replays
now declines the proof and fails the gate; reads at the index's t are
unchanged.
Brings #2296, #2309, #2313, #2315, #2316, #2317, #2367, #2368, #2369, #2373, #2374, #2378 and #2379. Ports onto next: - #2374 (bound-object probe reads POST): main's POST walk and per-type flush replace next's OPST walk. The lane keys (o_type, o_key), so next's triple-term handles are one more covered type (object_probe_covers takes TripleTermDict) rather than a flush per type; a term's matches are read whole, as a ref's are. The wildcard cursor still keys refs only. Pooled graphs decline through dedicated_branch(Post); o_i is 64-bit. Next's pair join keys its subject through the shared LaneKey. - #2373 (leaflet type constant under replay): replays_history and o_type_const_for beside next's may_hold_keys; the row-labelling lanes take main's const-unless-replaying form over next's always-read-column. - #2368: the cyclic join decodes for eager callers with next's list index sentinel; both reasoning tests kept (cyclic operator and pair lane). - #2317 (GRAPH streams): main's work queue and InnerStream with next's pooled-graph pruning before each enumerated graph. - #2315: list predicates are an ordered set in next's multi-ledger view; the annotation edge probe stays deleted (no bundle lane on next). - #2296 (rebase reads its new line): ported onto next's fenced resets, erasure checks and peer sync (follow_record keeps next's unchanged-head arm); a non-fast-forward rebase moves head and index in one fenced reset. - Main's new tests: async genesis_ledger, graph_source_store for mapping writes, leaf_rows for leaflets-per-leaf, storage lock off for two file instances. New pattern/function matches cover TermComponents and the triple-term functions; AnnotationTarget arms dropped.
Problem
A query at an earlier
tcan miss, or mis-type, a fact that was later retracted, once the ledger is reindexed.Take a predicate holding two refs among six strings at t=1, with both refs retracted at t=2 and the index built at t=2. At t=1:
SELECT ?x WHERE { ?x ex:tag ex:bob }returns no rows (expectedex:d1), andCOUNT(*)returns 0.?x ex:val 7.ex:alice ex:reads ?d . ?d ex:tag ?oreturns the retracted ref as the string"bob"instead ofex:bob. The same happens throughOPTIONAL { ?d ex:tag ?o }.The unbound form
?x ex:tag ?o FILTER(isIRI(?o))returns the right rows. Full-rebuild and incremental indexes behave the same, and so doesFLUREE_DISABLE_QUERY_FAST_PATHS=1, because the defect is in the plan both lanes share.Root cause
A POST/PSOT leaflet's
o_type_constis computed over its rows alone. The history sidecar keeps retracted facts under their own types, so after the retraction the leaflet reports the type of the literals left behind. Two kinds of reader trusted that constant while replaying history:BinaryCursor::next_batchskipped the leaflet by it before replay could restore the rows.join.rslabelled every replayed row with it.predicate_otype_uniformproved a predicate integer-only and engaged the integer point seek forFILTER(?v = 7), so a retracted double of the same value was never read.predicate_unsafe_for_cross_predicate_o_key_joincleared both predicates of the composite countCOUNT { ?s p1 ?o . ?s p2 ?o }of arena-keyed decimals and list rows from the flags and the constant, so a retracted decimal pair compared as two per-predicate arena handles and was not counted.p_constand the OPST constant are not affected: the writer segments by them and gives a fully retracted segment its own zero-row leaflet.Fix
Two helpers on
LeafletDirEntryV3:replays_history(replay_to): whether a read at thatttakes rows from the leaflet's sidecar. It replaces five hand-written copies of the same predicate (the cursor and four join lanes).o_type_const_for(reads_history): the constant a reader may apply, which is none when it also reads history.The cursor's skip and the three row-labelling lanes go through them. A leaflet with no history newer than
to_tis skipped and labelled exactly as before.The two proofs take the read's
tas well. A leaflet the read replays has no constant to prove by, so the integer-only proof declines, and the composite-count gate treats the leaflet as unsafe (its flags, like its constant, describe live rows). Reads at the index's owntprove exactly what they did before.Tests
retracted_type_shapes_{full_rebuild,incremental,novelty_only}init_query_time_travel_bgp.rscover the shapes above on SPARQL, with a JSON-LD twin for the bound ref, a head-tcontrol, and a history-range control. The subject-join and OPTIONAL shapes are stamped to their batched lanes so they cannot pass through the cursor. Two more shapes read the fixture's other predicates:?x ns:num ?v FILTER(?v = 7)with a retracted double of the same value, and the compositeCOUNTover a retracted decimal pair, each with its t=2 control.Each fix site was reverted on its own and the matching shape failed: the cursor skip (no rows), the subject join (
"bob"), the probe lane ("bob"under OPTIONAL), the integer-only proof (ns:d3missing), and the composite-count gate (1 against 2).Not verified
to_tand were previously skipped by type, and the integer point seek and composite-count fast path declining a past-tread whose leaflets replay.HAS_O_Ihas the same live-rows-only meaning for the list census caches, a store-level layer with no notion oft; it is recorded on One leaflet-at-t reader for the cursor and the batched join lanes #2375 rather than changed here.Follow-up: #2375