Skip to content

fix(core): disk cache byte accounting is exact around its scans - #2183

Merged
aaj3f merged 8 commits into
mainfrom
fix/disk-cache-scan-race
Nov 2, 2026
Merged

aaj3f merged 8 commits into
mainfrom
fix/disk-cache-scan-race

Conversation

@aaj3f

@aaj3f aaj3f commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

The disk cache's byte total could drift from what its directory actually holds. The cache sizes the directory with a walk that runs outside the state lock: the first sizing on a background thread (since #2022), and evict_until's rescan inline. Meanwhile writes and evictions account their bytes after their file operation. A scan that landed between the two miscounted:

  • a write whose file the walk had already seen was added again;
  • an eviction the walk had missed was subtracted again;
  • evict_until's total overwrote anything that landed during its rescan, so that write or eviction was lost.

Two writes of one entry at once (a seed and a fetch of the same object) could also both rename and both count. The first of these is what made disk_cache::tests::tracked_bytes_updated_on_write fail about 1 run in 40 (400 for 300).

Each slip moved the total by one entry's size, and only while a scan was walking (the first write's sizing, or an eviction pass). The next evict_until rescanned and reset it, so it was bounded and self-correcting. An over-count evicted a little early; an under-count let the directory run past its budget until the next pass.

Now the total is exact. Writes and evictions, including evict_until's own removals, register before their file operation (at most one per path) and account after it. Both kinds of scan land through one reconciliation:

  • a path an operation changed while the scan walked counts as what that operation left;
  • an operation still under way corrects the total by what it leaves when it lands.

Two small things came along. An eviction that finds a write of the same entry under way now leaves it to that write; evict_cached_cid's doc says so. And a disk-full write no longer leaves its partial temporary file behind: scans skip those, so it took space that nothing counted and nothing evicted.

Tests. Test-only pause points drive each window deterministically:

  • a size scan landing inside a write, and inside an eviction;
  • a write and an eviction landing inside a rescan;
  • a rescan landing inside a write;
  • an entry removed around the cache during a rescan;
  • two writes of one entry.

Each fails with its piece of the mechanism taken out. On main, a scan landing between a write's rename and its accounting counts a 100-byte write as 200, every time. The flaky test now passes 40/40 run alone.

Cost. A write takes the same two lock acquisitions as before (the registration rides in the lock that reads the size), plus one path allocation and a scan of the in-flight list, which holds one entry per concurrent write or eviction. Reads take no lock, as before. Evicting an entry that exists takes one more lock; evicting one that doesn't (the usual case for a released object) takes none. evict_until takes two locks per removal and now builds a path-to-size map of its rescan (one entry per cached file) to land it, which it didn't before; the background sizing builds the same map outside the lock instead of under it. On its own, a write's accounting goes from about 4 ns to about 21 ns, most of it the path allocation, against roughly 120 µs for a 1 KiB write itself on this machine's disk. Since review, a write first checks whether its entry is already on disk and returns if so: about 1 µs more for a write that creates its entry, and a write of an entry that's already cached now costs that one stat instead of the locks, the allocation and any rescan.

Review follow-ups (in this PR):

  • A write of an entry already on disk returns before it registers, so it can't hold the path against a concurrent eviction (8b906c741).
  • A scan is a guard that closes on drop, so a scan that fails or panics no longer leaves the scan count raised or the sizing flag stuck (498e74282).
  • A walk skips an entry that's removed between the listing and its stat (2d94b338b).
  • The pause-point tests fail at once on a failing assertion instead of hanging, and every wait has a 10 s limit (34f4fa31f).
  • evict_until totals its walk once (8dff87670).

Each of the first four has a test that fails without it.

Gates (all --all-features):

  • cargo fmt --all -- --check, clippy -D warnings on fluree-db-core, the CI wasm32 clippy step, and cargo check --workspace --all-targets: pass.
  • cargo test -p fluree-db-core: 1,089 passed at the head (1,078 lib, 3 util_bytes, 8 doc); the disk-cache suite 20 of 20 runs.
  • At 3e65938db, before the review follow-ups (which touch only disk_cache.rs): binary-index and iceberg lib tests (the remote-store cache paths), 765 passed; and the api tests that go through the remote-storage cache: 56 passed (disk-cache locality, residency retry, encrypted storage, store-load failure, rebuild fetch counts and staging cleanup, indexing stats, memory-storage reads, reindex pre-build).
  • tracked_bytes_updated_on_write alone, 40 runs: 40 passed.

The cache sizes its directory with a walk that runs outside the state lock
(off-thread for the first sizing since #2022, inline in evict_until), and
writes and evictions account their bytes after their file operation. A
scan landing between the two counted the operation twice or not at all:
a write whose file the walk saw was added again by its note_write, an
eviction the walk missed was subtracted again, and evict_until's total
overwrote whatever landed during its rescan. Two writes of one entry could
also both rename and both count. Each miss drifted the total by one entry
until the next evict_until rescanned.

Writes and evictions, evict_until's own removals included, now register
before their file operation, at most one per path, and account after it.
Every scan lands through one reconciliation: a path an operation changed
while the scan walked holds what that operation left, and an operation
still under way corrects the total by what it leaves when it lands. A
write registers in the lock it already took to read the size, so it takes
no extra lock; reads take none.

A disk-full write no longer leaves its partial temporary file behind,
where no accounting saw it and no eviction removed it.
@aaj3f aaj3f added bug Something isn't working as expected area:storage Storage backends, nameservice, ledger lifecycle, index storage, caches labels Oct 26, 2026
@aaj3f
aaj3f requested a review from bplatz October 26, 2026 19:37
@bplatz

bplatz commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

Heads-up on next. next has reworked disk_cache.rs a good deal since this PR's base (CachedContentStore, fill, the shared flights — +685/−534), but it still carries the same scanning / pending / note_write accounting, so the race this fixes is there too. The main→next merge won't take this cleanly; it'll need a hand port onto next's structure. While porting: CachedContentStore::evict's doc on next has the same "a fetch already in flight may still write the entry" wording this PR updates on evict_cached_cid.

One fix worth making here: a no-op write blocks an eviction. best_effort_write registers the path (L769) before anything checks whether the entry already exists — that check is in write_atomic (L728). So a write of an entry that's already on disk still holds the path for its whole in-flight window, which includes ensure_capacity and possibly a full evict_until rescan. An evict_entry for that path in the window finds it registered and returns, and the entry survives though nothing is replacing it. Before this PR the eviction would have removed it.

seed_disk_cache reaches this, since it writes without checking the cache first. The window is narrow (the same CID seeded and released at once), and evict_cached_cid's doc already tells consumers to tolerate a surviving entry, so it isn't urgent — but the fix is cheap. At the top of best_effort_write:

if self.budget_bytes == 0 || target.exists() {
    return;
}

keeping write_atomic's own check for the race. Only writes that will create the entry register, and duplicate writes skip two lock acquisitions and the path allocation. a_second_write_of_an_entry_under_way_is_left_to_the_first still covers the collision, since the first write pauses before its file exists.

@bplatz

bplatz commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

Smaller items, none blocking:

  • ScanTicket has no drop guard. Landing is RAII so a panic can't leave a path registered, but a scan isn't: a panic between begin_scan and land_scan/end_scan leaves scans > 0 for good. After that every write and eviction appends to landed without bound, and if it was the sizing scan, sizing sticks and the budget is never enforced. Nothing in that span panics today, so this is hardening — a guard that calls end_scan on drop unless landed, or at least #[must_use].
  • A walk fails when an entry vanishes mid-walk (pre-existing). scan_cache_entries does child.metadata()? (L421); an entry removed between read_dir listing it and the stat fails the whole walk with NotFound. Through ensure_capacity that skips the write with a warn, and a release loop evicting while a writer rescans can hit it repeatedly. Same family of race as this PR; treating NotFound there as continue is a one-liner, here or as a follow-up.
  • A failing pause-point test hangs instead of failing. The go senders live outside thread::scope. If anything in the scope panics — e.g. wait_for_sizing's 10 s deadline — scope joins the spawned thread first, which is parked in pause_at on go.recv() with its sender still alive, so the test hangs rather than reporting. Moving the senders into the scope closure (they drop on unwind) or a recv_timeout in pause_at turns a regression into a failure.
  • Nits:
    • evict_until totals the walk twice; let (_, walked) = walked_sizes(&entries) (L706) discards the second.
    • In evict_until's NotFound arm, when a concurrent in-cache eviction removed the entry, tracked_bytes is decremented twice until the rescan lands and corrects it. Transient, and only a writer's budget check in that window sees it — fine as is, noting it only because I checked.
    • Concurrent over-budget writers each run their own evict_until (pre-existing, no single-flight), and each now also builds a path→size map of the directory, so a burst costs N walks and N maps. Fine given eviction drains to 80%; worth knowing if it shows up in a profile.

@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 reconciliation holds across the interleavings I traced — operations landing before, during and after a walk, operations spanning a land, overlapping sizing and evict_until scans, and NotFound from an in-cache vs an outside removal — since each land sets tracked_bytes and every in-flight counted together.

Some feedback in the comments above: a note on porting this to next, one suggested fix (a no-op write blocking an eviction), and smaller items. None blocking.

aaj3f added 7 commits October 30, 2026 13:54
A paused operation waited on its release for good, and a test waited for
an operation to reach a pause for good. A test that failed in between
left the scope joining a parked thread. Both sides now time out, the
release can make the operation panic, and the pauses are armed inside
the scope so a failing test drops them and fails the parked thread at
once.
It summed the walk for its eviction loop, then summed it again building
the path map it lands with, and dropped the second total.
A scan opened under the state lock and closed only on its landing or
error paths. A panic between the two left it open for good: every later
write and eviction was recorded for it without bound, and if it was the
background sizing, the size never landed and the budget was never
enforced again. Nothing in that span panics today.

A scan is now a guard that closes on drop, and ends the sizing when it
is the sizing scan. The background sizing opens its scan on its own
thread, just before the walk: anything that lands before then is on disk
for the walk to see, so it needs no record.
A write registered its path before anything checked whether the entry
was already on disk, so a write that would change nothing still held
the path through its budget check and any rescan, and an eviction of
that entry in the window left it in place. Seeding writes without
checking the cache first, so it could do this.

A write of an entry already on disk now returns before registering. One
that races another write to create the entry is still caught by
write_atomic's own check.
The walk read each listed entry's size with a ? on the stat, so an entry
removed between the listing and the stat, by the cache's own eviction or
from outside it, failed the whole walk with NotFound. A rescan for the
budget then skipped the write it was making room for, and a release loop
evicting while a writer rescanned could hit this repeatedly. Such an
entry is gone, and the walk now passes over it.
@aaj3f

aaj3f commented Oct 30, 2026

Copy link
Copy Markdown
Contributor Author

Folded all of these into this PR (head c353b60ab); replies per point below.

One fix worth making here: a no-op write blocks an eviction

Thanks for tracing this one. You're right, and it reproduced exactly as you described: with
the entry already on disk, a write parked just after it registered (before ensure_capacity)
made a concurrent evict_entry find the path held and return, and the entry survived the
eviction.

Folded in as 8b906c7, with your check at the top of best_effort_write
(self.budget_bytes == 0 || target.exists()), and write_atomic's own check stays for the race.
The new test, a_write_of_an_entry_on_disk_leaves_it_to_an_eviction, parks a write of a cached
entry at a new test-only registered pause point and evicts underneath it. It fails without the
check ("the write kept the entry from the eviction") and passes with it.
a_second_write_of_an_entry_under_way_is_left_to_the_first still covers the collision, as you
said, since the first write parks before its file exists.

One thing I want to be honest about: this narrows the window rather than closing it. A write
whose exists() runs just before another write of the same entry lands will still register,
and it holds the path until write_atomic sees the file. That needs two writes of one CID
landing within a stat of each other plus an eviction of that CID right then, and
evict_cached_cid's doc already covers a surviving entry, so I don't think it's worth more
machinery here. Happy to talk it through if you see it differently.

On cost: a write that creates its entry now pays one extra stat (I measured about 1 µs
for exists() on a missing path on this box) against roughly 120–175 µs for the 1 KiB write
itself. It never touches the read path, since best_effort_write only runs after a miss
and its remote fetch, or when seeding. Duplicate writes get cheaper: one stat instead of
a stat, two lock acquisitions, the path allocation and possibly a rescan.

ScanTicket has no drop guard

Agreed, and I went with the guard rather than #[must_use] alone (it's both now). I could
reproduce both halves of what you described by making a scan panic mid-walk through the test
pause: a rescan that panicked left scans at 1, and a size scan that panicked left sizing
stuck, so the size never landed and the budget was never enforced again.

498e742 replaces ScanTicket with a Scan guard that closes on drop, and ends the sizing
too when it's the sizing scan. So the error paths in walk_and_land, evict_until and the
failed-spawn branch no longer close it by hand. One small structural change came with it:
the background sizing now opens its scan on its own thread, just before the walk, instead of
under the writer's lock. Anything that lands before the scan opens is already on disk for the
walk to see, so it doesn't need a record, and the guard can borrow the state instead of
carrying an Arc. a_rescan_that_panics_is_closed and a_size_scan_that_panics_is_closed
fail without the guard (scans left at 1; "size scan never landed") and pass with it.

A walk fails when an entry vanishes mid-walk

Same family as this PR, so I folded it in here rather than a follow-up: 2d94b33. Removing a
listed entry before the walk stats it (through a test-only per-entry hook) failed
scan_cache_entries with NotFound, as you said; now the walk passes over it.
scan_skips_an_entry_removed_mid_walk fails without the change and passes with it. I applied
the same NotFound arm to child.file_type() too, since that falls back to an lstat on
filesystems that don't report d_type, though the test only exercises the metadata() arm
(APFS reports d_type). The reconciliation already handles a skipped entry: an in-cache eviction
that removed it is in landed or still in flight, so it counts as gone either way.
(c353b60 is just a type alias on the test hook to keep clippy happy.)

A failing pause-point test hangs instead of failing

Yep, confirmed. I injected a failing assert into
a_size_scan_landing_inside_a_write_counts_it_once and the test sat there until I killed it
at 90 s. I fixed it on both sides in 34f4fa3, because there was a second hang behind the one
you named: the test's own recv() on the "reached" signal would also block forever if a
regression meant no operation ever got to the pause. So the pause is now a small Pause
handle that's armed inside the scope (a failing test drops it, which fails the parked thread
at once), and both the parked operation and the test's wait use a 10 s recv_timeout as a
backstop. With the same injected assert, the test now fails in 0.01 s with the assert's
message. Pause can also make the parked operation panic, which is what R2's tests use.

Nit: evict_until totals the walk twice

Good catch, thank you. The second total came from walked_sizes returning both. 8dff876
splits it into walked_bytes and walked_paths, so each pass is done once.

Heads-up on next

Thanks for flagging it. I checked next (f92a3d499), and I think the port of the
accounting itself is mechanical. The state struct, known_bytes, note_write,
evict_entry, evict_until, ensure_capacity and best_effort_write there are still
essentially main's pre-PR code; CachedContentStore, fill and the shared Flights
reach the cache only through best_effort_write and evict_entry, so they don't need to
change. A few places do need care:

  • next's write_atomic treats an empty entry as crash debris and replaces it
    (metadata.len() > 0), so the R1 pre-check there has to be that same test, not
    exists(); otherwise a debris entry would never get repaired.
  • best_effort_write on next also returns early on empty bytes, and ensure_capacity
    calls known_bytes itself, so the registration moves into the write's first lock the
    way it does here.
  • The tests use next's scan_hold hook rather than the pause points, so they need
    re-plumbing onto Pause rather than a straight copy.
  • CachedContentStore::evict's doc gets the same wording change as evict_cached_cid.

Happy to take the port onto next once this lands.

The two notes that need no change

Both check out, and I agree neither needs a change.

On the double decrement in evict_until's NotFound arm: right. That arm can't tell an
in-cache eviction (already subtracted when it landed) from a removal outside the cache (never
counted), and -entry.bytes is the answer that's right for the second. land_scan then
replaces the total from landed, where the last delta for that path is a removal, so it comes
out exact by the end of the same evict_until call. Recording 0 there instead would turn an
outside removal into an over-count that lasts until the next rescan, which seems worse than a
transient under-count that only a budget check inside that call can see.

On N walks for N concurrent over-budget writers: also right, and it's pre-existing. Each walk
now builds a path map too, but that's one hash insert per entry against an lstat per entry
for the walk itself, so the walks are still what a burst costs (I didn't time the map on its
own). If it ever shows up in a profile, I'd single-flight evict_until so concurrent callers
share one rescan, but nothing here suggests it's needed now.

@aaj3f
aaj3f merged commit db8c191 into main Nov 2, 2026
29 of 30 checks passed
@aaj3f
aaj3f deleted the fix/disk-cache-scan-race branch November 2, 2026 20:43
aaj3f added a commit that referenced this pull request Nov 3, 2026
…out-mapping

Brings in #2193, #2200, #2183, #2187 and #2198. The one conflict is
it_iceberg_local_fs.rs, where this branch's unmapped-source tests and
#2198's BigQuery and merge-on-read tests were appended at the same
place; both are kept.
bplatz added a commit that referenced this pull request Nov 4, 2026
Brings #2247, #2232, #2246, #2248, #2245, #2230, #2205, #2231, #2255,
#2219, #2209, #2207, #2190, #2216, #2186, #2215, #2213, #2184, #2210,
#2206, #2198, #2187, #2183, #2200, #2193, #2199, #2196 and #2145 into next.

Resolutions:
- Novelty: main's fact-state trim (a cutoff plus a bounded sweep) and the
  dictionary's coverage watermark sit on next's graph slots and per-graph
  OrdMaps. A commit's reification links count toward coverage. Planner
  stats from segment sums decline under annotations, whose link deltas
  only the walk counts, and otherwise carry the indexed link counts.
- Stats-view identity: the index root's id reaches the snapshot through
  next's root decoder (`decode` takes the id, as `take_snapshot_metadata`
  does). `LedgerState::load_record` has a decoding-root form beside
  `load_decoding_root`.
- Transact: #2184's parallel-relationship check runs in next's link
  cascade, counting the `rdf:reifies` links on the retracted edge that the
  transaction does not retract itself. Main's bundle `edge_reifiers` is
  dropped, and `subjects_with_prior_rows` and
  `enforce_single_target_reifiers` stay deleted. The upsert pre-check
  takes main's dictionary probe and bounded seek.
- Query: geo search resolves the graph's POST tree once at open (pooled
  graphs keep their filter), an empty manifest when there is none.
  `branch_or_none` reads the dedicated branch, and the batched joins keep
  next's pooled lanes. The stats-view key hashes the root id.
- Indexer: `apply_dict_novelty` and `compact_forward_streams` take the
  cycle's compaction budget, so the term dictionary keeps its reserved
  share. `Prefetched` holds `ContentBytes`. `relocalize_sorted_commit`
  rewrites next's 20-byte types records.
- Disk cache: main's in-flight write registration, with an empty entry
  still read as crash debris that a write replaces. The process-wide
  eviction walk stays removed.
- Graph import (#2232): fenced CAS and publishes, the seed carries the
  record's namespace and fence, 32-bit graph ids and next's loaders. An
  import into a graph of an existing ledger refuses triple terms and edge
  annotations: the splice merges no triple-term dictionary yet.
- Iceberg: `create_iceberg_graph_source` goes with main (a source needs a
  mapping); the R2RML path keeps next's `model_instance`.
- CLI: main's shared import flags without the leaflet flags; `graph
  import` routes through next's process-wide server routing, and
  `upload_source_import` serves next's `Destination`. Doc sources read a
  ledger through the command's open instance.
- Tests: sibling ledger ids become distinct names, `genesis_ledger` is
  awaited, Cypher state dumps include each relationship's `rdf:reifies`
  link, and the graph-import arena test checks the refusal instead.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:storage Storage backends, nameservice, ledger lifecycle, index storage, caches bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants