Skip to content

fix(query): novelty-only-predicate retractions were invisible to the crawl read path - #1698

Merged
aaj3f merged 9 commits into
mainfrom
fix/list-retraction-indexed-novelty
Aug 27, 2026
Merged

aaj3f merged 9 commits into
mainfrom
fix/list-retraction-indexed-novelty

Conversation

@aaj3f

@aaj3f aaj3f commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Fixes the P0 from #1683, folds in the two deferrals that were sequenced behind it, and closes two pre-existing defects of the same class that surfaced while fixing it.

The bug is bigger and simpler than the issue title

#1683 reported this as a @list problem: a filtered DELETE of one list entry commits with receipt.flake_count = 1 and the entry stays readable. The narrowing in the issue was right that staging is not at fault — hydrate_list_index_meta_for_retractions hands the commit a retraction with the correct m = { i: 1 }, and I confirmed that again here: novelty at t=3 holds s=ex:nov1 p=ex:items o="b" i=Some(1) op=false, exactly as it should.

The write path was fine. The read path was dropping the retraction on the floor.

fluree-db-query/src/binary_range.rs — binary_range_eq_v3 bails to overlay_only_flakes whenever a bound component of the pattern has no persisted id (a novelty-only subject, predicate, or object) or the requested order has no branch manifest. overlay_only_flakes served that by filtering the walk to if !flake.op { return; } — assert-only, no lifecycle resolution at all. But the overlay is a log, not a current-state view: the assert at t=2 and its retraction at t=3 both sit in novelty. Filtering to asserts resurrects every fact whose assert and retract live there.

Consequence: any workload that writes a fact under a brand-new predicate and then deletes it before the next index build is told the flake was retracted and can still read the value. Silent, and shaped like data loss in the opposite direction.

Two things about the shape are worth stating plainly, because both change how the issue reads.

Nothing about it is list-specific. I added a plain-valued leg to the repro on a second novelty-only predicate — ex:tags: ["p", "q"], delete "p" — and got ["p", "q"] back at the pin. @list is just how the bug was found: a brand-new predicate carrying a collection is a very natural way to land a fact wholly in novelty.

Reload does not heal it. That was the open remediation question from the sweep, and the answer is no. I ran the reload leg against the unfixed code specifically to answer it: a fresh handle replays the same commit chain into novelty and reads it the same wrong way, so an affected ledger stays wrong across a restart. It heals on the next index build (the fact leaves novelty and the cursor path resolves it correctly), not on reload. The regression pin has a reload leg so that stays honest.

That also explains the sweep's puzzle about the CLI probes not reproducing: the BGP path (select ["?s","?o"]) resolves the overlay correctly and always did — it takes the cursor path. Only the subject-crawl (select {"?s": ["ex:items"]}) goes through fetch_subject_predicate_pair, binds both s and p, fails to resolve the novelty-only p, and lands in overlay_only_flakes. The maintainer probe in the thread used the crawl; the CLI probes used a BGP. Same ledger, two answers.

The fix

Keep both ops through the walk, run the matching set through resolve_latest_ops_keep_asserts (newest op per fact identity wins, retracted keys drop out), then apply object bounds / offset / limit to the resolved state. That is the same rule the cursor path already gets from resolve_overlay_ops, and the same thing the bounded twin overlay_only_flakes_bounded twenty lines up was already doing — this function was simply the odd one out.

The early exit at limit had to go with it: the retraction that cancels an already-collected assert can arrive after the limit is reached. Worth noting it was never buying much — for_each_overlay_flake walks the graph's whole overlay either way, so the exit only saved clones of matching flakes. (There's a measured argument about restoring it further down.)

Regression pin lives with its siblings in fluree-db-api/tests/it_filtered_delete_list_meta.rs (novelty_only_predicate_retraction_takes_effect): novelty-only predicate over an indexed base, live handle across the background-index swap, list leg + plain leg + reload leg, plus a BGP assertion so the two read paths stay in agreement. It fails at the merge base with the reported ["a","b","c"] vs ["a","c"].

Two more instances of the same defect — #1703 and #1704

Both were already broken before this branch, and the overlay_only_flakes fix does not, on its own, close either. Both live in code this branch already holds, and both are the same "the overlay is a log" defect #1683 is about, so they land here rather than as deferred follow-ups. Filed as #1703 and #1704 so the history is honest about them being pre-existing.

#1703 — the helper I delegate to had the same bug for values that repeat under different metadata

resolve_latest_ops_keep_asserts cut resolution groups on full fact identity (s, p, o, dt, m) by run adjacency. But every comparator orders … t, op, m, with t before m (fluree-db-core/src/comparator.rs:161-207), so siblings sharing (s, p, o, dt) interleave by t: a sibling's assert lands between a fact's own assert and its retraction, the run closes early, and the retracted assert is emitted live. ["a", "b", "a"] deleting position 0 returned both "a" entries; "hello"@en + "hello"@fr deleting the @en returned both. Deleting the last position passes, so it only fails when the retracted entry's metadata sorts below a surviving sibling's — about a coin flip on any list that repeats a value.

Runs are now cut on the four fields all four comparators do order before t, with the winner picked per distinct m inside the run. I verified non-vacuity by putting m back into the run key and re-running: exactly the two reported outputs come back, and the last-position case stays green — so both directions are pinned.

The per-m grouping inside the run needs its own comparator, and this is the part that is easiest to "simplify" wrongly. FlakeMeta::cmp (fluree-db-core/src/flake.rs:110-129) compares only i when both sides carry a list index — lang is never consulted — while PartialEq is derived over both fields. So {lang: en, i: 0} and {lang: fr, i: 0} compare Equal without being equal: Ord is not consistent with Eq for that type. Sorting by that relation and then cutting groups on m == m is sorting by one relation and grouping by a stricter one — structurally the same mistake as #1703 itself, one level down. One list position under two language tags lets the sibling's assert separate a fact from its own retraction, and the retracted value survives. Grouping therefore sorts with a local meta_group_cmp that compares i then lang, so Equal means equal in fact and the sort agrees with the == the groups are cut on.

Two things here are load-bearing and shouldn't be simplified away. Runs are not cut by moving m ahead of t in the comparators, which would change index ordering semantics repo-wide. And FlakeMeta::Ord itself is left alone deliberately — every comparator's cmp_meta tiebreak reads it, so repairing the type moves index ordering semantics repo-wide too. That's #1711's job, not something to smuggle in here.

Three tests cover the combination specifically, because the residual lives there and not in either half: tests covering list positions and language tags separately all pass. Both tag orders of the combined shape, plus one that asserts the invariant directly — meta_group_cmp returns Equal exactly when the metas are equal, across the eight interesting (lang, i) combinations, plus the en@0/fr@0 pair that is Ord-equal and Eq-unequal. Verified non-vacuous by putting FlakeMeta::cmp back as the sort key: both new cases fail with the reported output while the other eleven stay green.

One thing I found trying to write the end-to-end leg, which is worth carrying into #1711. The combined shape can't currently be built through the write path at all. Asserting a second language tag at an occupied list position commits — the receipt reports one flake at its own t — but it never reaches the live view: novelty keys the fact by that same inconsistent ordering and folds it onto the first tag. So the write side collapses the shape before the read side can be asked about it. That means the Ord/Eq disagreement is silently dropping a legitimately distinct write, not just mis-resolving a read, which I think widens #1711's blast radius beyond how it's currently scoped. I left a note in it_filtered_delete_list_meta.rs naming that test as the one to grow an end-to-end leg once the type is fixed, rather than contriving a fixture that can't exist today.

#1704 — a third assert-only overlay path

batched_refs_overlay_only was still filtering to asserts with no resolution, the odd one out among the three paths of binary_lookup_subject_predicate_refs_batched_v3 — which serves policy rdf:type lookups. On a graph with no PSOT branch, a class asserted and revoked inside one novelty window kept granting class-based policy access until the first index build. It now hands the merged set to apply_raw_overlay_deltas_to_batched_refs, the same rule its two sibling paths already use, rather than a third variant of it. The guard test drives the real provider entry point on a named graph that lives only in novelty; I confirmed it reaches the intended path, and that restoring the assert-only filter makes it fail with ["Admin", "Person"].

Beyond those, the test additions here cover the duplicate-valued list and language-tag shapes end to end, and an offset/limit pin — the fix moved when paging applies relative to resolution, and nothing held that ordering down.

#1685 — has_list_meta on bulk-import roots

import.rs:6837 left the flag None, so the stage.rs:1623 skip (snapshot.has_list_meta == Some(false) && !novelty.has_list_meta) could never fire for bulk-imported ledgers — which are the large ones, i.e. exactly where the O(novelty) walk costs something.

Implemented as the issue proposed, which does match the numbig_pool / vector_pool / ns_alloc precedent: a sticky Arc<AtomicBool> on SpoolConfig, a plain bool on SpoolContext OR'd in write_record, one relaxed store per chunk at finish / finish_buffered, read once at root assembly after the workers join. No per-record atomic traffic.

One deliberate detail: the OR gates on the mapped i != LIST_INDEX_NONE, not on list_index.is_some(). An out-of-range index coerces to the sentinel a few lines above and is not a list row in the index, so gating on the option would let a Some(true) root claim a list that the index doesn't actually carry. Cheap insurance in the safe direction, but the safe direction here is not the obvious one — a wrongly-false root is the dangerous case, which is why import_with_list_records_has_list_meta_true_and_still_retracts asserts the flag and then runs the filtered DELETE it protects.

The import_sink.rs:253 comment is also corrected: it claimed every SpoolContext reaches a finish path, which isn't true (there's a ? on the parse and on into_parts() between construction and finish). The flag is still safe, but the invariant is "a context that doesn't finish means no root", not "every context finishes" — the old wording would let a future change that tolerates per-chunk failures look correct. And same_fact_key now carries the note about g being absent because every caller scopes to one g_id.

#1684 — transact_filtered_delete bench

Two scenarios over a bulk-imported, novelty-heavy ledger, covering both sides of the stage.rs:1623 gate with the same deleted predicate so the delta is the hydration path and nothing else. The no_lists branch is only reachable this cheaply because of the #1685 work above — before it, that branch needed a full rebuild inside the fixture.

Each scenario asserts its gate state during setup rather than trusting the fixture; a fixture that drifts off its branch fails the bench instead of quietly reporting a plausible number for the wrong path.

On the honesty front: at Small both scenarios read ~39 ms, because the WHERE and the commit dominate — the curves only separate from Medium up (69 ms vs 127 ms at 20k groups on my box). I've said that in the module doc so nobody reads a flat Tiny/Small pair as "the gate is free". Either scale still catches what the bench exists for, since a regression back to retractions × novelty turns tens of milliseconds into seconds.

Wired into fluree-db-api/Cargo.toml and regression-budget.json; workspace_reconcile passes.

The read-side bench, and why the limit early exit stays gone

transact_filtered_delete guards the write side; nothing covered the read side this PR actually changes. query_overlay_only_range does, with two scenarios that separate the candidate cost drivers. Quick profile on my box: narrow_subject (one matched fact) is 13.6 µs at 2k novelty subjects and 13.8 µs at 10k — flat across a 5× increase in overlay size — while wide_subject goes 31.8 µs at 200 matched values to 95.9 µs at 1k, about 80 ns per matched row. So the cost is bounded by the matched fact set, not by novelty.

Restoring the early exit by streaming the resolution is the obvious alternative — for_each_overlay_flake is contractually comparator-ordered, so it's available. I don't think it's the right trade here.

The caller trace says the exposure is small. Every caller that sets a limit and can reach this function: policy_builder.rs:603 and cypher_write.rs:900 are subject-bound with flake_limit(1); ledger_view.rs:331 is predicate+object-bound with flake_limit(16); time_resolve.rs:342 and ledger_view.rs:235 go through range_bounded_with_overlay, i.e. the bounded twin, which already collected everything before this PR. The one that is not subject-bound is probe_timestamp_axis (time_resolve.rs:154), which issues RangeMatch::predicate(..) — predicate only, no subject, no object — with flake_limit(1), and adds object_bounds when resolving after: Some. Its matched set is one flake per commit in the txn-meta graph, so it scales with commits-in-novelty rather than with a bound subject's fact count, and it's doubly exposed because those object bounds now prune after resolution instead of inside the walk. It only takes this path when txn-meta has no POST branch, it reads a system graph, and at ~80 ns per matched row the absolute cost is small — but it is the shape neither bench scenario models, so rather than a third scenario, query_overlay_only_range's doc names the site, its exact bind pattern, the object_bounds interaction, and the fact that it's where to measure first if this path ever needs the bound back.

Against that small cost, streaming would trade the helper's internal sort — which today self-heals if any overlay provider ever violates the ordering contract — for a hard dependency on that contract, in the fallback path that exists precisely to be defensive. A few hundred nanoseconds of clone on bound patterns isn't worth that. The bench is in the tree, so the day someone does add a limit-setting caller on an unbound pattern, we'll see it. Happy to be talked back into the restructure if the balance reads differently to someone else.

Gates

  • cargo test -p fluree-db-api — 3250 passed, 0 failed
  • cargo test -p fluree-db-query — 1494 passed (1434 lib, incl. 13 resolver unit tests)
  • cargo test -p fluree-db-transact / -p fluree-db-policy / -p fluree-db-sparql / -p fluree-db-cypher — all green
  • cargo test -p fluree-bench-support --test workspace_reconcile — green
  • cargo clippy -p fluree-db-query -p fluree-db-transact -p fluree-db-api --all-targets --no-deps — clean
  • cargo fmt --all — clean (run last)
  • cargo bench -p fluree-db-api --bench transact_filtered_delete --bench query_overlay_only_range -- --test — all four scenarios green

Two things I did not do, flagging rather than hiding them. The W3C SPARQL suite didn't run — its rdf-tests submodule isn't populated in this worktree, and that suite runs on memory ledgers, which don't reach binary_range_eq_v3 at all, so I don't think it exercises the changed line. And --all-features won't build in my environment (cxx build script fails), which is pre-existing and unrelated; everything above is default features.

I'd also note for the record that #1683's title and labels understate it now — it isn't an @list bug, it's "novelty-only-predicate retractions are invisible to the crawl read path". Happy to retitle the issue if that's useful, or leave it and let this PR body carry the correction.

Fixes #1683
Fixes #1685
Closes #1684
Fixes #1703
Fixes #1704

Follow-up: #1711

aaj3f added 3 commits August 26, 2026 10:37
…dropping retracts

A filtered DELETE of a value under a predicate that exists only in novelty
committed with `flake_count = 1` and left the value readable. No error, no
warning — the caller was told the flake was retracted and the entry stayed.

`binary_range_eq_v3` serves a pattern straight from the overlay whenever a
bound component has no persisted id (a novelty-only subject, predicate, or
object) or the requested order has no branch manifest. `overlay_only_flakes`
did that by filtering the walk to `op == true`. But the overlay is a LOG,
not a current-state view: the assert at `t=2` and its retraction at `t=3`
both sit in novelty, so dropping retracts resurrected every fact whose
assert AND retract lived there — durably, since a reload replays the same
novelty and reads it the same way.

Keep both ops through the walk, run `resolve_latest_ops_keep_asserts` over
the matching set, then apply object bounds / offset / limit to the resolved
state. Same rule the cursor path gets from `resolve_overlay_ops` and the
bounded twin (`overlay_only_flakes_bounded`) already applied.

The early exit at `limit` goes with it: the retraction that cancels an
already-collected assert can arrive after the limit is reached.
`for_each_overlay_flake` walks the graph's whole overlay either way, so the
exit only ever saved clones of matching flakes.

`@list` retraction is the shape it was reported as, because a brand-new
predicate carrying a list is a common way to land a fact wholly in novelty —
but nothing here is list-specific, and the regression pin covers both.
`IndexRoot.has_list_meta` gates the filtered-DELETE hydration skip:
staging skips the list-meta lookup only when the root says `Some(false)`
AND novelty's sticky bit is clear. Bulk import left the flag `None` —
correct but conservative, so the skip never fired for bulk-imported
ledgers, which are exactly the ones large enough for the O(novelty) walk
to cost anything.

The signal was already in hand and thrown away: `write_record` maps each
record's `list_index` to `i` per chunk and nothing accumulated it. Carry
it the way the other shared import state travels — a sticky
`Arc<AtomicBool>` on `SpoolConfig`, alongside `numbig_pool` /
`vector_pool` / `ns_alloc`:

- a plain `bool` on `SpoolContext`, OR'd in `write_record` only on the
  `i != LIST_INDEX_NONE` branch, so the per-record path takes no atomic
  traffic;
- one relaxed store per chunk at `finish` / `finish_buffered` (every
  context ends at one of them);
- read once at root assembly, after the parse workers have joined, into
  `has_list_meta: Some(saw_list_meta)`.

Gate on the mapped `i`, not on `list_index.is_some()`: an out-of-range
index coerces to the sentinel and is not a list row in the index. The
txn-meta records assembled outside the spool hard-code `LIST_INDEX_NONE`
and are never list rows, so the spool bit is the whole picture.

Tests: a unit test that the bit is per-import and sticky across chunks,
plus the two the flag needs end-to-end — an import with no collections
recording `Some(false)`, and one collection recording `Some(true)`. The
second also runs the filtered DELETE it protects, since a wrongly-`false`
root would skip hydration and drop the retraction silently.
Nothing benched WHERE/DELETE staging. `transact_commit.rs` measures
insert-shaped commits only, which is how a `retractions × novelty` shape
in `hydrate_list_index_meta_for_retractions` sat unnoticed until a
40k-subject delete stopped finishing. That shape is fixed; nothing
guarded the win.

`transact_filtered_delete` deletes every fact under one predicate on a
bulk-imported ledger that has since accumulated novelty, in two
scenarios covering both sides of the hydration-skip gate:

- `no_lists`  — root `Some(false)`, clean novelty: hydration skipped.
- `with_lists` — one RDF collection in the import flips the root to
  `Some(true)`: every retraction group pays the overlay walk plus a
  base-only seek. Same deleted predicate in both, so the delta is the
  hydration path and nothing else.

The `no_lists` branch is only reachable this cheaply because bulk-import
roots now record the flag; it previously needed a full rebuild in the
fixture.

Each scenario asserts its gate state during setup rather than trusting
the fixture: a fixture that drifts off its branch fails the bench instead
of reporting a plausible number for the wrong path.

Observed at quick profile: the curves separate from Medium up (69 ms vs
127 ms at 20k groups) and read flat at Small (~39 ms each), where the
WHERE and the commit dominate. Either scale still catches a regression
back to the quadratic shape, which turns tens of milliseconds into
seconds — the module doc says so, so a flat Tiny pair is not misread as
"the gate is free".

Wired into fluree-db-api/Cargo.toml and regression-budget.json;
`cargo test -p fluree-bench-support --test workspace_reconcile` passes.
aaj3f added 4 commits August 26, 2026 15:54
…rd assert-only overlay path

Two pre-existing defects of the same class as #1683, found reviewing the fix
for it. Both are in code this PR already touches, so they land here rather
than as deferred follow-ups.

Fixes #1703 — `resolve_latest_ops_keep_asserts` dropped retractions when two
flakes shared `(s, p, o, dt)` and differed only in `m`.

A fact's identity is `(s, p, o, dt, m)`: two `@list` entries holding the same
value at different positions, and one lexical form under two language tags,
are distinct facts. The helper cut resolution groups on that full identity by
run adjacency — but every comparator orders `… t, op, m`, with `t` BEFORE
`m`. So siblings interleave by `t`, a sibling's assert lands between a fact's
own assert and its retraction, the run closes early, and the retracted assert
is emitted as live. `["a", "b", "a"]` deleting position 0 returned both "a"s;
`"hello"@en` + `"hello"@fr` deleting the `@en` returned both. Deleting the
LAST position passed, so it only fails when the retracted entry's metadata
sorts below a surviving sibling's — roughly a coin flip on any list that
repeats a value.

Runs are now cut on `same_fact_key` — the four fields all four comparators do
order before `t`, so those runs are contiguous — and the winner is picked per
distinct `m` inside the run. Not by reordering the comparators to put `m`
ahead of `t`: that would change index ordering semantics repo-wide.

Winners come out of a run in first-appearance (`t`) order, which for a run
with more than one survivor need not be the comparator's order, so the result
is re-sorted. Callers take this as a range result and expect index order; the
single-winner-per-group predecessor gave them that for free.

Fixes #1704 — `batched_refs_overlay_only` was still filtering its walk to
asserts with no resolution anywhere, the odd one out among the three paths of
`binary_lookup_subject_predicate_refs_batched_v3`. That function serves policy
`rdf:type` lookups, so on a graph with no PSOT branch a class asserted and
revoked inside one novelty window kept granting class-based policy access
until the first index build. It now keeps retractions and hands the merged set
to `apply_raw_overlay_deltas_to_batched_refs` — the same latest-op-wins rule
its two sibling paths already use, not a third variant of it.

Tests: eight unit tests on the resolver covering both metadata shapes in the
failing direction, the mirror direction that passed even with the bug, a
re-assert after retraction, equal-`t` precedence, datatype siblings, and
output ordering. Verified non-vacuous by putting `m` back in the run key:
exactly the two reported outputs come back. The delegated batched-ref rule
gets its own unit test, and an integration test drives the real provider entry
point on a named graph with no PSOT branch — verified to reach the intended
path and to fail with `["Admin", "Person"]` when the assert-only filter is
restored.
…ses end to end

The unit tests on the resolver pin the rule; these pin it through the real
read path, where the shapes are the ones a user actually writes.

- `novelty_only_predicate_resolves_metadata_siblings` — a `@list` repeating a
  value and one lexical form under two language tags, both on a novelty-only
  predicate over an indexed base. Both legs delete the entry whose metadata
  sorts FIRST, which is the failing direction; deleting the last position
  passes even with the grouping bug, so a pin covering only that would be
  vacuous.
- `novelty_only_predicate_paging_applies_after_resolution` — the fix moved
  when `offset`/`limit` apply relative to resolution and nothing pinned the
  order. Ten values with the two that sort first retracted, then a LIMIT
  smaller than the retracted prefix: paging the log instead of the resolved
  state would put a retracted value in the page.
- `it_batched_refs_overlay_lifecycle` — drives
  `lookup_subject_predicate_refs_batched` on a named graph that lives only in
  novelty (so it has no PSOT branch) over an indexed default graph (so
  `rdf:type` has a persisted id and the lookup gets far enough to reach the
  overlay fallback). Grants two classes, revokes one, and asserts the revoked
  one is not reported — the policy-visible consequence.
Review point: `transact_filtered_delete` guards the write and staging path,
but nothing measured the read path the fix actually touches — and
`fluree-db-query` is the crate this repo scrutinizes hardest. The specific
open question was whether removing the `limit` early exit, which made the
intermediate grow from `offset + limit` to the whole match-gated set, costs
anything worth a restructure.

`query_overlay_only_range` crawls a novelty-only predicate over an indexed
base — the #1683 shape — in two scenarios that separate the two candidate
cost drivers: `narrow_subject` matches one fact against a large overlay,
`wide_subject` matches many (half of them retracted, so resolution has real
lifecycle work). The fixture asserts the crawl returns the resolved set, so a
future change that stops taking this path fails the bench instead of quietly
measuring something else.

Quick profile, author's box: narrow_subject is 13.6 µs at 2k novelty subjects
and 13.8 µs at 10k — flat across a 5× increase in overlay size — while
wide_subject goes 31.8 µs at 200 matched values to 95.9 µs at 1k, about 80 ns
per matched row. So the cost this path took on is bounded by the matched fact
set, not by novelty.

Also corrects the `publish_list_meta` comment, which claimed every
`SpoolContext` reaches a finish path. It doesn't: every call site has a `?` on
the parse and on `into_parts()` between construction and finish, and either
drops the sink with the context inside it. The flag is still safe, but the
invariant that makes it safe is "a context that doesn't finish means no root"
— both errors abort the import — not "every context finishes". Said that
instead, so a future change that tolerates per-chunk failures can't read the
old wording as permission.
… a winners list

Self-review of the #1703 fix: picking the winner per distinct `m` with a
linear "have I seen this `m`" probe over a winners list is O(k²) in the
number of distinct metadata values inside one `(s, p, o, dt)` run.

That run is exactly where a list holding ONE value at k positions lands —
every entry shares the run key and carries its own `m` — so the shape that
motivated the grouping fix is also its worst case. Shipping a quadratic into
this path while fixing a quadratic in the same area is not a trade worth
making, however unlikely a 10k-element list of a repeated value is.

Group by a stable sort keyed on `m` alone instead: O(k log k), and stability
leaves the comparator's `t, op` order intact inside each group so the winner
scan still sees candidates in ascending `t` and applies the same rule. A
one-flake run — overwhelmingly the common case — short-circuits before any of
it.

Guard test resolves 4k positions of one repeated value with every third
retracted, asserting the surviving set, its order, and a wall-clock ceiling
two orders of magnitude above the real runtime, so a reintroduced quadratic
fails it without flaking on a slow box.
…ality

Delta re-review caught the previous commit reintroducing its own defect one
level down, and it was right.

`FlakeMeta::cmp` (`fluree-db-core/src/flake.rs:110-129`) compares ONLY `i`
when both sides carry a list index — `lang` is never consulted — while
`PartialEq` is derived over both fields. So `{lang: en, i: 0}` and
`{lang: fr, i: 0}` compare `Equal` without being equal: `Ord` is not
consistent with `Eq` for that type.

The run grouping sorted `idxs` by that relation and then cut groups on
`m == m` — sorting by one relation and grouping by a stricter one, which is
structurally the same mistake as the #1703 fix it was part of. One list
position under two language tags therefore let the sibling's assert separate
a fact from its own retraction, and the retracted value survived: assert
`"x"@en` at position 0 (t=2), assert `"x"@fr` at position 0 (t=3), retract
the `@en` (t=4), and both came back.

Grouping now sorts with a local `meta_group_cmp` that compares `i` then
`lang`, so `Equal` means equal in fact and the sort agrees with the `==` the
groups are cut on. Left `FlakeMeta::Ord` alone deliberately: every
comparator's `cmp_meta` tiebreak reads it, so repairing the type moves index
ordering semantics repo-wide. Follow-up: #1711.

Three tests: both tag orders of the combined shape, and one asserting the
invariant directly — that `meta_group_cmp` returns `Equal` exactly when the
metas are equal, across the eight interesting `(lang, i)` combinations, plus
the `en@0` / `fr@0` pair that is `Ord`-equal and `Eq`-unequal. The ten
existing tests covered list positions and language tags only separately,
which is exactly where the residual lived. Verified non-vacuous by putting
`FlakeMeta::cmp` back as the sort key: both new cases fail with the reported
output, the other eleven stay green.

The end-to-end leg is deliberately absent, with a note in
`it_filtered_delete_list_meta.rs` saying why: the shape cannot currently be
built through the write path. Asserting a second language tag at an occupied
list position commits (receipt reports one flake at its own `t`) but never
reaches the live view — novelty keys the fact by the same inconsistent
ordering and folds it onto the first tag. So the write side collapses the
shape before the read side can be asked about it. That is more evidence for
#1711, and the note names this test as the one to grow an end-to-end leg once
the type is fixed.

@bplatz bplatz 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.

Approving — the core fix is right, well-diagnosed, and properly pinned. I mutation-checked both halves: restoring the assert-only filter in overlay_only_flakes reddens three e2e tests (["a","b","c"] vs ["a","c"]), and restoring it in batched_refs_overlay_only reddens the policy test with ["Admin", "Person"]. The has_list_meta work also checks out — root assembly is base_t: 0 / prev_index: None, so there's no prior root a Some(false) could clobber, and import.rs:5412 really is the only non-spool RunRecord producer.

Five inline comments, all worth a look before merge. The two I care about most are the equal-t tie rules: resolution rules disagreeing across paths that are documented to agree is the same class of defect this PR exists to close.

Minor, not inline: #1685 and #1684 are independent of the read-path fix, so a revert of the fix drags them along. And a footnote for #1711 — Double(NaN) has the same Ord/Eq disagreement one level further down (comparator calls two NaNs equal via to_bits, == doesn't), so a NaN retraction can't cancel its assert. Unreachable in practice, but it belongs in the same ledger.

Comment thread fluree-db-query/src/binary_range.rs Outdated
let cand = &flakes[idxs[h]];
let cur = &flakes[best];
// Newest op wins; at equal `t` a retraction beats an assert,
// matching `resolve_current_flakes`.

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.

This says the tie rule matches resolve_current_flakes, but it's the opposite. I ran it: resolve_current_flakes(vec![assert@t2, retract@t2]) returns 1 survivor, while retraction_wins_at_equal_t asserts 0.

Mechanism: remove_stale_flakes reverse-scans a comparator-sorted vec, and the comparator orders op ascending (false < true), so reversing puts the assert first. And resolve_current_flakes's own doc says it exists so callers "get identical results to range_with_overlay" — these two are meant to agree.

Either the comment is wrong or one implementation is; right now the divergence reads as deliberate consistency.

);

let mut out: HashMap<Sid, Vec<Sid>> = HashMap::new();
apply_raw_overlay_deltas_to_batched_refs(&mut out, &raw_overlay, predicate, effective_to_t);

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.

Two things about routing through this helper:

Third tie rule, failing open. It uses if flake.t > t0 — strictly greater — so at equal t whichever flake the walk yields first wins. Verified: an assert + retract of the same class at the same t leaves ["Admin"]. That's the fail-open direction on the lane that decides class-based policy grants. Pre-existing, but this PR newly routes the overlay-only path through it and adds a unit test pinning its semantics without covering the tie. flake.t > t0 || (flake.t == t0 && !flake.op).

New behavior diff. out.entry(subj).or_default() now leaves an empty-vec entry for a subject whose only overlay flakes are retractions (verified: contains_key true, len 0). lookup_subject_classes documents "Subjects with no rdf:type assertions will not be present in the map" and its own fallback enforces that with if !classes.is_empty(). Benign today, but one line to fix in the loop below.

Comment thread fluree-db-query/src/binary_range.rs Outdated

if flakes[best].op {
out.push(flakes[best].clone());
// Group the run by `m`. Sorting rather than scanning a winners list

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.

Was a hash considered here? fluree_db_core::range::remove_stale_flakes already solves exactly this — a HashSet on the full (s, p, o, dt, m) identity, reverse-scanned over the sorted vec. Being a hash, it has no dependency on run adjacency, none on FlakeMeta::Ord, no meta_group_cmp, and no final out.sort_by(cmp). FlakeMeta derives Hash/Eq consistently and FlakeValue's Hash is already documented to agree with its cross-numeric Eq.

That's ~110 lines and the whole Ord-vs-Eq hazard, replaced by a sibling that already exists. There is a defensible reason to prefer the sort — hashing BigDecimal/Double objects isn't free, hash_decimal_canonical allocates — but the doc presents the two-level grouping as forced rather than chosen. Worth an answer even if the code stays.

(Separately: out.sort_by(cmp) at the end runs unconditionally, including the common all-runs-of-size-1 case where out is already sorted. A bool set when a run emits >1 survivor skips it.)

Comment thread fluree-db-query/src/binary_range.rs Outdated
Ok(flakes)
let mut resolved = resolve_latest_ops_keep_asserts(flakes, index);

// Options apply to the resolved current state, not to the log.

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.

object_bounds can go back in the walk. A retraction that can cancel an assert has the same o by construction — same_fact_key requires it — so bounds.matches is true for both or false for both, and filtering in the walk is provably equivalent to filtering survivors.

Moving it back shrinks the collected vector, the clone count, and both sorts. For probe_timestamp_axis's after: Some(target) leg it's the difference between collecting every commit in novelty and collecting only those past the target — i.e. it retires the "doubly exposed" caveat the bench doc calls out.

Unlike restoring the limit early exit — where I agree with the reasoning; trading the internal sort for a hard dependency on the walk-order contract is a bad deal in a defensive fallback — this one costs nothing.

/// Overlay-only results when the persisted index cannot contribute a row.
///
/// Reached whenever a bound component of `match_val` has no persisted id
/// (a novelty-only subject, predicate, or object), or no branch manifest

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.

"genesis / pre-first-index" may be understating this. branch_for_order is keyed per (g_id, order), so a graph with some orders built and not others lands here too — and in that case this function silently drops persisted rows, which is a bigger hole than the one being fixed.

If all four orders are always built per graph, worth saying so here. If not, worth its own issue rather than a comment that reads as exhaustive.

Review of the equal-`t` tie rules found three implementations that were
documented to agree and did not. Settled by picking the rule that already had
a written rationale and making the other two match it.

`resolve_overlay_ops` (the cursor path) resolves an equal-`t` assert+retract
to ABSENT, and says why: it matches the per-commit apply path, and the
segment-aware assembly merges runs across segments so the tie has to be
deterministic rather than sort-position dependent. `remove_stale_flakes`
disagreed — it reverse-scanned a comparator-sorted vec, and the comparator
orders `op` ascending, so reversing put the assert first and the fact
survived. That contradicted `resolve_current_flakes`'s own promise of
"identical results to `range_with_overlay`".

- `remove_stale_flakes` now picks the winner explicitly (newest `t`, retract
  wins the tie) instead of taking the first hit of a reverse scan, so the
  answer no longer depends on where the comparator happened to sort the ops.
- `apply_raw_overlay_deltas_to_batched_refs` used `t > t0`, letting walk
  order decide the tie — and on the lane that decides class-based policy
  grants it failed OPEN: a same-`t` assert+retract left the class granted.

Then the bigger simplification behind it. `remove_stale_flakes` already
hashes the full `(s, p, o, dt, m)` identity, which is exactly what the
two-level run grouping in `binary_range` was reinventing — and it does it
without depending on run adjacency, on `FlakeMeta::Ord`, or on the local
`meta_group_cmp` that the last round had to introduce because that `Ord`
disagrees with `Eq` (#1711). `Hash`/`Eq` are derived together and agree.

So `resolve_latest_ops_keep_asserts`, `same_fact_key` and `meta_group_cmp`
are deleted and the four call sites go straight to
`resolve_current_flakes`. That is ~144 lines and the entire `Ord`-vs-`Eq`
hazard removed, replaced by a sibling that was already there, and it drops
the final `out.sort_by(cmp)` the grouping needed along with the
superlinearity question that came with it. The resolution tests move to
`fluree-db-core` next to the implementation they pin, and grow the cases the
query-side copy didn't have.

Also, per review:

- `object_bounds` moves back INTO the overlay-only walk. A retraction that
  can cancel an assert carries the same `o` by construction, so the bound is
  true for both halves or false for both — pruning early is equivalent and
  collects and clones less. It restores `probe_timestamp_axis`'s
  `after: Some` leg to collecting only the commits past its target. The
  `offset`/`limit` pair stays out: those count survivors, and the cancelling
  retraction can arrive after the count is reached.
- `batched_refs_overlay_only` no longer leaves an empty vector for a subject
  whose overlay flakes are all retractions. `lookup_subject_classes`
  documents that such subjects are absent from the map and its per-subject
  fallback enforces that; this path was diverging from both.
- The overlay-only doc no longer describes its second trigger as
  "genesis / pre-first-index". `branch_for_order` is keyed per (graph,
  order), and bulk import emits SPOT unconditionally while skipping the
  other three orders when they produced no run files — so a zero-row graph
  lands here for three of four orders. The fallback is still correct
  (missing orders are exactly the zero-row ones, so no persisted rows are
  dropped), but the doc now says that rather than reading as exhaustive, and
  records that the converse is unsafe: SPOT can be `Some` with an empty
  branch, so no caller may read "this order resolved" as "this graph is
  indexed".
@aaj3f

aaj3f commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @bplatz — all five are addressed, and the hash question changed the shape of the PR for the better.

The tie rule (:903) — you were right, and there's a third implementation that settles which one was wrong. resolve_overlay_ops on the cursor path already resolves an equal-t assert+retract to absent, with a written rationale: it matches the per-commit apply path, and the segment-aware assembly merges runs across segments so the tie has to be deterministic. That makes remove_stale_flakes the outlier — and it was contradicting resolve_current_flakes's own "identical results to range_with_overlay" promise, exactly as you read it. Fixed there rather than in the comment: the winner is now chosen explicitly instead of falling out of which end a reverse scan happens to reach first. Restoring the original body makes the new tie test fail as you described.

The third tie rule (:1254) — took your fix verbatim, flake.t > t0 || (flake.t == t0 && !flake.op). And the empty-vec entry was mine, not pre-existing; lookup_subject_classes documents absence and its own fallback enforces it, so leaving or_default() behind was a real behavior diff. Both now covered by a test that runs assert-first and retract-first orderings plus a retraction-only subject.

The hash (:873) — you're right, and I took it. remove_stale_flakes hashes the full (s, p, o, dt, m) identity, which is precisely what the two-level grouping was reinventing less safely. resolve_latest_ops_keep_asserts, same_fact_key and meta_group_cmp are gone (−144 lines), the four call sites now go through resolve_current_flakes, and with them go the Ord-vs-Eq hazard, the unconditional final out.sort_by(cmp), and the superlinearity question you raised in the parenthetical. The resolution tests moved to core beside the implementation, with cases the query-side copy didn't have — net −100 lines and more coverage. The doc no longer presents the grouping as forced, because it isn't there.

On your performance caveat: I couldn't resolve it here and I'd rather say so than quote a number. The box is at load 26 against an idle floor near 5.7, and run-to-run spread on narrow_subject was 14.9 vs 20.5 µs against a hash-vs-sort delta around 1 µs — the noise is twenty times the signal. Hashing is O(n) against the sort's O(n log n) so it shouldn't be asymptotically worse, and the CI bench gate against the committed baseline is the honest arbiter rather than anything I measure on this machine.

object_bounds back in the walk (:1687) — done. Your equivalence argument holds: same_fact_key requires the same o, so a cancelling retraction matches the bounds exactly when its assert does, and filtering in the walk is equivalent to filtering survivors. offset/limit stay out, since those count survivors rather than candidates. That retires the "doubly exposed" caveat in the bench doc, which was the right thing to chase — thank you.

branch_for_order (:1612) — you're right that it wasn't exhaustive, and the investigation says no issue is needed. Not all four orders are built per graph: bulk import emits SPOT unconditionally, even for zero rows with an empty branch, while PSOT/POST/OPST are skipped when the order produced no run files. But the fallback stays correct, because the missing orders are exactly the zero-row ones — there are no persisted rows to drop. The comment now says that, plus the converse that actually is unsafe: SPOT can be Some over an empty branch, so nothing should read "this order resolved" as "this graph is indexed."

On the NaN footnote — I don't think it holds, and I checked by execution rather than reading:

bits n1=0x7ff8000000000000  n2=0x7ff8000000000001
same-bits   cmp=Equal  eq=true   hash_eq=true
diff-bits   cmp=Less   eq=false  hash_eq=true

Ord and Eq agree in both directions. The reason is that PartialEq routes numerics through numeric_cmp (value.rs:401-405), which carries the same to_bits fallback the comparator's same_type_cmp does (value.rs:504) — so identical-bit NaNs are equal under both relations and differing-bit NaNs are unequal under both. So it doesn't belong in #1711's ledger, and I've recorded the negative result there so nobody re-derives it. The hash_eq=true on differing bits is just a hash collision, which the contract permits and Eq disambiguates — worth noting only because the resolver now hashes that identity.

On the topology note — fair, and a deliberate call rather than an oversight: #1685 and #1684 do ride along with a revert of the read-path fix. Consolidated PRs are the house preference and this one's already reviewed and green, so I'd rather not split it now.

@aaj3f
aaj3f merged commit fd78564 into main Aug 27, 2026
14 checks passed
@aaj3f
aaj3f deleted the fix/list-retraction-indexed-novelty branch August 27, 2026 18:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment