Repository navigation
preserve fully-retracted history through full index rebuilds - #1624
Conversation
A predicate whose facts have all been retracted materializes no row in a rebuild, so leaflet segmentation never opened a partition for it and its transitions were filed under the next predicate's leaflet — where a predicate-keyed reader skips them by p_const and reports a silent zero at every historical t. The same absence hit a fully-retracted subject in SPOT, whose transitions fell outside the leaf's routing keys and so were never routed to at all. The leaf writer now emits a zero-row leaflet plus its own sidecar segment for each segment that ends without a row, and widens the leaf's routing keys to span committed history. This is the shape the incremental writer already preserves after a merge empties a leaflet, and the reader already replays it.
A leaf whose range stops at its last live record is never selected for a key that only history covers, so a fully-retracted subject stayed unreadable at a historical t even with its transitions in the sidecar. Widening is strict, so an entry sharing its own row's identity leaves that row as the routing key. Also adds the ignored rebuild-cost measurement for the preserved partitions.
…tion The preserved partition is the same zero-column-block shape the incremental writer produces via empty_encoded_leaflet_with_keys, so a later incremental routing novelty back into it depends on the row_count == 0 guard added in #1603. Reverting that guard turns the new indexer test red with "missing column block for SId", which is the failure #1603 fixed.
bplatz
left a comment
There was a problem hiding this comment.
Traced the writer paths against the format code. Three things I checked and can clear, so nobody re-derives them:
record_from_history'sg_id: 0/tare genuinely inert.write_ordered_key_v2writes only(s_id, p_id, o_type, o_key, o_i)in every order, andcmp_v2_*compares the same five columns. The doc comment is accurate.last_recordmonotonicity holds across the new call paths.flush_leafresetsleaf_first_recordbut notlast_record, so a leaf made up only of history-only leaflets compares against the previous leaf's last record — that's always smaller in build order, sowiden_leaf_boundsupdates correctly. See the inline note.- #1603 is on
main(merged 2026-08-10), so the stated dependency is satisfied here; it binds only for backports into any release line lacking it. Worth restating that way in the body.
One thing that isn't in the diff and I think should be: an operational note. The failure mode is "your existing indexes silently return empty at historical t, and reindexing is the remediation." That's exactly the kind of thing an operator needs to find in docs/troubleshooting/ or docs/operations/ rather than in a PR description — especially since nothing triggers the repair automatically. This PR touches no docs at all.
|
|
||
| /// Append one zero-row leaflet holding `entries` as its history segment. | ||
| fn emit_history_only_leaflet(&mut self, entries: &[HistEntryV2]) -> io::Result<()> { | ||
| debug_assert!( |
There was a problem hiding this comment.
This should be a hard assert! (or an io::Error), not a debug_assert!.
The invariant it guards is what keeps the sidecar segment index aligned with the leaflet directory index. If it's ever violated, every leaf written from that point has its history segments off by one — silently, and only visible as wrong history replay, which is precisely the bug class this PR exists to fix. It's also unrepairable except by another full rebuild.
CI runs debug so the assertion fires there, but index artifacts are written by release builds, where this compiles to nothing. The check is two boolean loads on a path that runs once per retracted segment — the cost argument for debug_assert! doesn't apply.
There was a problem hiding this comment.
Agreed, promoted to a hard assert!. Your framing is the deciding one: CI runs debug so the assertion fires there, but the artifacts that matter are written by release builds where it compiles to nothing, and an off-by-one between the sidecar segment index and the leaflet directory is both silent and unrepairable short of another rebuild — the exact failure mode this PR exists to remove.
I also widened what it guards. The invariant is now record_buf.is_empty() && !current_segment_started && leaflet_hist_min.is_none(), since the leaflet-key widening added a third piece of per-leaflet state that has to be clear before a history-only leaflet can be appended. It runs once per retracted segment, so the cost argument doesn't change.
| } | ||
| if self | ||
| .last_record | ||
| .is_none_or(|last| cmp(&rec, &last) == std::cmp::Ordering::Greater) |
There was a problem hiding this comment.
Correctness note rather than a defect — I convinced myself this is right, but it took a while, so it's worth making local.
flush_leaf() resets leaf_first_record = None but leaves last_record set. That was previously harmless: a leaf couldn't be flushed without records, and push_record overwrites last_record unconditionally. Now a leaf can consist solely of history-only leaflets, and its last_key comes from this widening compared against a value carried over from the previous leaf.
It works because build order is ascending, so the carried-over value is always smaller and the Greater branch fires. But that's a non-obvious cross-leaf dependency. Adding self.last_record = None; next to the leaf_first_record = None; reset in flush_leaf would make the invariant local instead of global.
There was a problem hiding this comment.
Taken — flush_leaf now resets last_record = None next to leaf_first_record = None. Your reasoning about why the old code was correct matches mine, and that's precisely the argument I'd rather not have to reconstruct again: it depended on build order being ascending across leaves, which is true but is a global property being used to justify a local read.
With the reset the next leaf's bounds derive only from its own contents. A leaf made up solely of history-only leaflets gets its bound from widen_leaf_bounds against None rather than against a carried-over value, so the Greater branch is no longer load-bearing. Comment at the reset says why.
bplatz
left a comment
There was a problem hiding this comment.
Left some feedback below to look at before merge
zonotope
left a comment
There was a problem hiding this comment.
Optimistically approving, but I've noted some improvements that would be nice to get in too.
| self.sidecar_builder.start_leaflet(); | ||
| self.current_segment_started = true; | ||
| } | ||
| self.widen_leaf_bounds(record_from_history(&entry)); |
There was a problem hiding this comment.
The widened bound here does not survive an incremental update. This is not a regression because this was broken unconditionally before this pr, but this pr only now fixes it for one mechanism and not the other.
This call grows only the leaf header's keys. When history is committed into an existing leaflet via commit_history_entry — SPOT always, and PSOT/POST when a fully-retracted subject sorts above the last live row — that leaflet's own dir keys still come from encode_leaflet(&records) and do not span the history.
That's fine for the freshly-rebuilt leaf, but the header keys are re-derived on the next incremental touch:
- incremental_leaf.rs:647-654 — build_leaf_from_group takes first_key from group.first() and last_key from group.last(), i.e. from the leaflet dir entries.
- incremental_branch.rs:444-450 — the branch entry is then read back out of that header.
- branch.rs:110 — find_leaves_in_range computes start by partition_point(|e| cmp(&e.last_key, min_key) == Less), so a narrowed last_key skips the leaf again.
So a full rebuild fixes the leaf, and the first update_leaf that touches it silently narrows the bound back and reintroduces the original symptom for that subject. trailing_fully_retracted_subject_is_not_dropped_in_spot asserts leaf.last_key.s_id == SubjectId(2) on the rebuild output only; test_update_into_rebuild_emitted_empty_partition does round-trip through update_leaf, but only for the history-only-leaflet case — whose leaflet keys do span its history, so it's the safe half.
Widening the leaflet's first_key/last_key alongside the leaf's would make the bound re-derivable, and would also make the leaflet_out_of_range prune at binary_cursor.rs:370 sound on its own rather than depending on the needs_history_replay guard.
There was a problem hiding this comment.
Confirmed, and it was the important one. I traced the chain you gave and it holds exactly: build_leaf_from_group takes first_key/last_key from group.first()/group.last() dir entries, update_branch reads the branch entry back out of that header, and find_leaves_in_range's partition_point on last_key then skips the leaf. I turned it into a failing test before fixing anything — a SPOT leaf with a trailing fully-retracted subject, round-tripped through update_leaf, came back with last_key.s_id == 100 instead of 200.
Fixed by widening the leaflet's own keys as you suggested, so the bound is re-derivable. One addition beyond your note: merge_and_encode_leaflet drops it the same way on the other side — it re-encodes each chunk from live rows via encode_leaflet while attaching history that sorts outside them, so the widening has to be reapplied there too or the very next incremental undoes it again. The merged.is_empty() branch already preserved the range via empty_encoded_leaflet_with_keys; this makes the still-has-rows branch honour the same contract. Widening stays inside the leaflet's routing interval (carried-forward history was already in it, novelty is sliced to it), so siblings can't overlap.
Coverage now: test_update_preserves_widened_bound_for_retracted_subject for the rebuild→update_leaf round trip, and time_travel_fully_retracted_subject_survives_later_incremental end-to-end — a deleted entity read at @t:1 after a later incremental. I checked both actually bite by disabling the incremental-side widening: the end-to-end one drops to 0 rows from 2.
| /// | ||
| /// Callers must have no buffered records and no open sidecar segment, so | ||
| /// the emitted leaflet and its segment stay index-aligned. | ||
| fn flush_history_only_segments(&mut self, next: Option<&RunRecordV2>) -> io::Result<()> { |
There was a problem hiding this comment.
This runs on every push_record. In the common case — all pending entries belong to next's segment — it still does mem::take, pushes every entry into a fresh retained, and assigns back (:409-433), then commit_all_pending immediately takes it again. That's a malloc + copy per record added to full-index rebuild.
Entries are sorted and next's segment sorts last, so inspecting pending_history[0] is sufficient for an O(1) early return before the take.
There was a problem hiding this comment.
Fixed. Inspecting pending_history[0] is sufficient exactly as you say — entries are sorted and next's segment sorts last, so if the first entry is already in next's segment then every entry is, and there is nothing to emit. That check now returns before the mem::take, so the common path on push_record costs one comparison instead of a take, a full copy into a fresh retained, and an assign-back that commit_all_pending immediately undoes.
| let homogeneous_o_type = entries | ||
| .iter() | ||
| .all(|e| e.o_type == first.o_type) | ||
| .then_some(first.o_type); |
There was a problem hiding this comment.
homogeneous_o_type scans all entries even under OPST, where the match arm discards it.
There was a problem hiding this comment.
Fixed — the scan moved inside the non-OPST match arm, so OPST takes Some(first.o_type) directly. It segments by type, so the constant is known without looking at the rest.
Widening the leaf header alone was not durable. build_leaf_from_group re-derives the header from the leaflet directory and update_branch republishes the branch entry from it, so the first incremental to touch a rebuilt leaf narrowed the bound back and the fully-retracted subject went missing at a historical t again. The re-encode in merge_and_encode_leaflet dropped it the same way, deriving keys from live rows while keeping history that sorts outside them. Both writers now span the retained history with the leaflet's own keys, which also makes the leaflet_out_of_range prune sound on its own terms instead of resting on the replay guard. Also from review: the leaflet-alignment check is a hard assert, since index artifacts are written by release builds and a misalignment is silent and unrepairable; last_record is reset with the leaf it belongs to, so a leaf of only history-only leaflets no longer derives its bound from the previous leaf; the pending-history scan takes an O(1) exit on the common push_record path; and OPST skips the o_type scan whose result it discards.
Existing indexes can return empty at a historical t for fully-retracted properties and deleted entities. Nothing repairs that automatically, so operators need the symptom and the remediation somewhere they can find it.
|
@bplatz — Thanks for clearing those three; I've left them as they are rather than re-deriving. On the third: I've restated the #1603 dependency in the body as satisfied on On the operational note — agreed, and it was a real gap. Added @zonotope — All five are in. The leaflet-keys one turned out to have a second half on the incremental side — details in the reply on |
The seeded plan reaches batched-subject probes that read base leaflets directly: latest-t only, with a novelty-overlay bail gate. Neither condition had a test — the existing coverage is all at head with no overlay, so a lane that is reachable but not correctly gated would pass. Both tests assert results, not plan shape: a lane that bails to a slower fallback is fine, one that returns the wrong rows is not. Each first asserts the query still plans as seeded, so the result assertions cannot quietly stop covering the lane they were written for. The historical case changes a value rather than retracting the predicate outright, so the predicate keeps live rows either side of the boundary and the test is a pure replay question — the fully-retracted shape depends on #1624, which is still open.
The shape the seeded plan actually changed the answer to: a predicate a later full rebuild leaves with no live rows is unreachable through PSOT/POST, and deferring used to route it through PropertyJoinOperator, whose replay-aware driver selection kept it correct by accident. Seeding takes it off that lane. #1624 preserves the SPOT history sidecars the probes need, so this is answerable now. Uses a full rebuild rather than an incremental build because that is the path that dropped the partition. The head assertion doubles as proof the predicate really is fully retracted.
A full rebuild materializes no row for a predicate whose facts have all been retracted, so leaflet segmentation never opened a partition for it — its transitions got filed under the next predicate's leaflet, where a predicate-keyed reader skips them by
p_const. The same absence hit fully-retracted subjects in SPOT: their transitions fell outside the leaf's routing keys, so no read ever routed to them. The visible effect was that after a full reindex, time-travel queries over a fully-retracted predicate or subject returned no rows at a historicalt(or, withOPTIONAL, rows with nulls where values existed), while incremental and novelty-only indexes answered the same queries correctly.The fix emits a zero-row leaflet plus its own history sidecar for each segment that ends without a live row, and grows routing keys to span history that sorts outside a leaflet's live rows. That's the same shape the incremental writer already preserves when a merge empties a leaflet, and the reader already replays it — this just makes the rebuild produce it too.
Those keys are widened on the leaflet, not only on the leaf header.
build_leaf_from_groupre-derives the header from the leaflet directory andupdate_branchrepublishes the branch entry from it, so a bound recorded only on the header is narrowed away by the first incremental that touches the leaf — reintroducing the original symptom for that subject.merge_and_encode_leafletneeded the same treatment, since it re-encodes from live rows while carrying history that sorts outside them. Both halves are pinned by round-trip tests throughupdate_leaf, and end-to-end by a deleted entity that stays readable at@t:1across a later incremental.On #1603: its
row_count == 0guard is what lets a later incremental merge into these zero-column-block partitions. It merged tomainon 2026-08-10, so the dependency is already satisfied here — it binds only for backports into any release line that lacks it. A test pins the seam (reverting the guard turns it red with the exact failure #1603 fixed).Verification: an 11-shape × 3-index-strategy matrix (the full-rebuild column was wrong in 8 of 11 cells before, all correct after; incremental and novelty pinned as controls), the existing pinned test extended with the plain single-triple variants, history-surface coverage, and a repeat-rebuild test showing an index built by a pre-fix binary is fully repaired by rebuilding again with this fix — the rebuild walks commits from genesis and reuses no leaves, so reindexing is the complete remediation for any already-affected index. Artifact cost measured at +0.69% bytes on a retraction-heavy fixture; rebuild time within noise.
Because nothing repairs an already-published index automatically, the symptom and the reindex remediation are documented for operators at
docs/troubleshooting/historical-results-missing.md.