Skip to content

fix(indexer): remove rebuild session directories on every exit - #1917

Merged
bplatz merged 2 commits into
mainfrom
fix/index-build-staging-guard
Sep 25, 2026
Merged

bplatz merged 2 commits into
mainfrom
fix/index-build-staging-guard

Conversation

@bplatz

@bplatz bplatz commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A full index rebuild stages plaintext ledger content — sorted commit runs, dictionaries, leaves — under per-session directories that default to the system temp directory. Cleanup ran only on the success path, so any of the pipeline's early ? exits left the staging tree behind. This ties removal to a drop guard so every exit clears it.

Change

  • SessionDirs in fluree-db-indexer/src/build/rebuild.rs owns the tmp_import/{session} and index/{session} directories and removes both on drop. It is created inside the spawn_blocking task, not the caller's future, so a cancelled caller cannot delete directories the still-running task is writing to. A directory that was never created is not an error.
  • The explicit success-path cleanup is gone; the guard covers it.
  • When the commit store reports permits_plaintext_cache() == false (encrypted storage) and IndexerConfig::data_dir is unset, the rebuild logs a warning that staging is going to $TMPDIR.
  • docs/security/encryption.md gains an "Index build staging" section: what is staged, that every exit removes it, that only a killed process leaves directories behind, and that encrypted deployments should point data_dir at an encrypted volume.

Not covered here: bulk import. Its session directory ($TMPDIR/fluree-import or FLUREE_IMPORT_DIR, not data_dir) is removed on success and failure alike when cleanup_local_files is on. But the removal is a plain statement after an .await, so a panic or a cancelled caller skips it, the same hole this PR closes for rebuild. The guard is not a drop-in there: import's spawn_blocking sort-write tasks keep writing after the caller is cancelled, so a guard owned by the async function would remove the directory under them. That needs its own design; the docs name the gap.

Follow-up: #1950

Tests

fluree-db-api/tests/it_rebuild_staging_cleanup.rs:

  • A rebuild whose first envelope range read fails (after the session directories exist) leaves nothing under data_dir.
  • A successful rebuild leaves nothing under data_dir.

Both fail with the guard's body disabled, so neither passes by accident.

Review follow-ups

Verification

Indexer unit suite, API grp_index, the new test target and it_rebuild_fetch_counts pass. Clippy and fmt clean on the indexer and api crates.

@bplatz bplatz added bug Something isn't working as expected area:storage Storage backends, nameservice, ledger lifecycle, index storage, caches labels Sep 24, 2026
@bplatz
bplatz requested review from aaj3f and zonotope September 24, 2026 10:01
@bplatz
bplatz added this pull request to stack #1918 September 24, 2026 10:23

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

@bplatz this looks good and seems great both from the perspective of the tmp file cleanup and the leak guardrail. Full review below:


This is a tight, well-aimed fix and the part I'd have most expected to see done wrong is done right: the guard is constructed inside the spawn_blocking task rather than in the caller's future, so a cancelled caller can't delete directories the still-running task is writing into, and the comment says so. I checked the panic leg you claim in the commit body (no panic = "abort" in any root profile, so the unwind really does run Drop) and that nothing in the pipeline spawns detached work that could race the removal — both hold. RangeReadsFail failing only get_range is a nicely chosen seam, and I confirmed your non-vacuity claim rather than taking it: disabling the guard's body turns both new tests red naming the leftover session paths.

One thing I'd like corrected even though it doesn't change the code here. The body's reason for leaving the bulk-import path alone — that cleanup_local_files "keeps the directory on failure for debugging" — doesn't match import.rs:3734-3745, which cleans up on both success and failure by default and says so in its own comment; the "keeps on failure" wording is coming from a stale doc comment on derive_session_dir (import.rs:7186-7188). The real difference is that import's cleanup is a sequential statement a panic or a cancellation skips, which is the same hole you just closed here, on a path that stages more plaintext into $TMPDIR/fluree-import and ignores data_dir entirely — so the new "point data_dir at an encrypted volume" guidance doesn't reach it. Happy for the import guard itself to be a separate change; the stale doc comment I'd just fix.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ A drop guard is the right mechanism, placed at the right scope, and the explicit cleanup it replaces is fully removed rather than left alongside.
  • Performance (speed first, memory second): ✔ Same two remove_dir_all calls on the success path, moved into Drop; one extra removal on the error path, which is the work that should have happened. Nothing per-blob or per-row. No performance-degradation risk.
  • Testing: ✔ Both new tests are in their own [[test]] target (fluree-db-api/Cargo.toml:488), run under the green test job on this exact head, and are non-vacuous under mutation. Only the panic leg is untested.
  • Conventions: ✔ Multi-line commit body carrying the real rationale, clippy/fmt green at 470b2f494, docs updated alongside and honest about what they don't cover.

Verified locally at 470b2f494: cargo test -p fluree-db-api --test it_rebuild_staging_cleanup → 2 passed / 0 failed with both tests named; short-circuiting SessionDirs::drop turns both red (0 passed / 2 failed, leftover paths named); gh api .../commits/470b2f494/check-runs confirms a real pull_request CI run on the head despite the base being #1916's branch.

Approving so you can merge when ready — this one's clean. Just worth getting the derive_session_dir doc comment right on the way past, since it's what made the import-path justification read as true.

})
}

/// The rebuild's session directories, removed when dropped.

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.

Optional — fluree-db-api/src/import.rs:3735: the reason given for leaving the bulk-import path alone doesn't match what that path actually does, and I think the real difference makes it a candidate for the same guard.

The PR body says the import path "has its own session directory with an explicit cleanup_local_files option that keeps the directory on failure for debugging. That is a documented knob rather than an omission." Reading import.rs:3734-3745, cleanup runs on both success and failure whenever cleanup_local_files is true (the default), and the comment immediately above it says exactly that — "Cleanup session dir on both success and failure to avoid accumulating hundreds of GB of orphaned temp files from failed imports." cleanup_local_files = false turns cleanup off on both paths; it isn't a keep-on-failure switch. I think the "keeps on failure" wording came from the stale doc comment on derive_session_dir at import.rs:7186-7188, which still says "The cleanup phase removes this directory on success; on failure it is kept for debugging."

Which means the real difference between the two paths is the one this PR is about: import's cleanup is a sequential statement after an .await, so a panic in run_pipeline_phases or a cancelled caller skips it, exactly as rebuild's used to. And it stages more — its own comment says hundreds of GB — into $TMPDIR/fluree-import (or FLUREE_IMPORT_DIR), which ignores data_dir entirely, so the new "point data_dir at an encrypted volume" guidance in docs/security/encryption.md doesn't reach it. The SessionDirs type you just wrote drops straight in:

let _session = SessionDirs { run_dir: session_dir.clone(), index_dir: PathBuf::new() };

I recognize this is scope creep on a tight PR, and I'd take "not here" as an answer. But the stale derive_session_dir doc comment is worth fixing wherever this lands, because it's what made the body's justification read as true — if you agree, I'd rather see that one-line doc fix folded in now than lost in the backlog.

Commenting here because fluree-db-api/src/import.rs is not in this diff; this is the guard it would reuse.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, and thanks for tracing where it came from. Fixed in db82de8: derive_session_dir's doc now says cleanup runs on success and failure unless cleanup_local_files is off. The call-site comment was stale too: it claimed the directory derives from storage's data directory, and storage isn't consulted. The PR body now gives the real reason.

I left the import guard out of this PR on purpose, filed as #1950. It isn't quite a drop-in: run_pipeline_phases hands work to spawn_blocking sort-write tasks that keep running after the caller is cancelled. A SessionDirs owned by the async function would be dropped on cancellation and remove the directory while they're still writing, which is the hazard this PR avoided by building its guard inside the blocking task. Import needs an owner that outlives its last writer.

The docs now say import stages under $TMPDIR/fluree-import or FLUREE_IMPORT_DIR, not data_dir, that encrypted deployments should point that at an encrypted volume too, and that a panicked or cancelled import leaves its directory behind (#1950).

/// Both trees hold plaintext ledger content — sorted commit runs, dictionaries,
/// staged leaves — and default to the system temp directory. Tying their
/// removal to a drop rather than to the success path means every exit clears
/// them: an early `?`, a panic unwinding the blocking task, or the normal

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.

Optional — the commit body claims the panic path is covered and I believe it is, but nothing pins it.

"an early error, a panic unwinding the task, and the normal return" — the first and third have tests. I checked the third leg by hand (no panic = "abort" in any root profile, so Drop runs on unwind), which is the right answer, but it's the kind of thing a future panic = "abort" in a release profile would silently take away. A third test that injects a panic through the same RangeReadsFail seam — say a PanicsOnRangeRead wrapper — would pin it for about fifteen lines, and would fail loudly if the profile ever changed. More of a question than a suggestion: is the panic leg worth a test, or is it enough that the profile is what it is?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd leave it untested. The risk it would pin is a future panic = "abort" in a release profile, and Cargo ignores the panic setting when building tests: the test harness always unwinds. So that test would stay green while the change it guards against turned the cleanup off in production. Today the only panic = "abort" in the repo is in wasm-probe, which doesn't rebuild indexes.

// Owned by the blocking task, not the caller's future: the task runs to
// completion even when the caller is cancelled, so the directories are
// removed only after the last write to them.
let _session_dirs = SessionDirs {

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.

Praise — constructing the guard inside the spawn_blocking closure rather than in the caller's future, with the comment saying why, is the part of this that's easy to get backwards and expensive when you do.

"the task runs to completion even when the caller is cancelled, so the directories are removed only after the last write to them" — that's the failure this shape exists to avoid. Same for declaring it after parent_span.enter() so the drop's warn! still lands in the span.


/// Wraps a content store and fails every envelope range read, which is the
/// first read the rebuild issues after creating its session directories.
#[derive(Clone, Debug)]

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.

Praise — RangeReadsFail failing only get_range is a well-chosen injection point.

It guarantees the session directories exist before the failure, so the empty-directory assertion can't pass because nothing ever ran. That's the difference between a test and a test that means something, and it's why the mutation run turns it red rather than leaving it green.

artifacts it just built. With encryption enabled that cache is bypassed
entirely: no decrypted leaf, branch, dictionary or vector shard is written
outside the encrypted storage, and nothing already in the cache directory is
consulted. Fetched artifacts are served from memory instead.

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.

Praise — "Only a killed process leaves its session directories behind; nothing removes those automatically, so clear tmp_import after a crash" is the honest version.

Docs that name their own residual gap are worth more than docs that claim closure.

Base automatically changed from fix/encryption-at-rest-coverage to main September 25, 2026 23:14
A full rebuild stages sorted commit runs, dictionaries and leaves in
plaintext under per-session directories that default to the system temp
directory. Cleanup ran only on the success path, after every `?` in the
pipeline, so a rebuild that failed part-way left its staging tree behind.

The two directories are now owned by a drop guard created inside the
blocking task, so an early error, a panic unwinding the task, and the
normal return all remove them, and only after the task's last write.

When the commit store forbids a plaintext cache (encrypted storage) and
IndexerConfig::data_dir is unset, the rebuild logs a warning that staging
is going to the system temp directory. Docs describe the staging tree,
the guard's coverage, and the data_dir guidance for encrypted deployments.

Regression tests: a rebuild whose first range read fails, and a successful
rebuild, both leave no session directory under data_dir. Both fail with the
guard's body disabled.
- RangeReadsFail answers permits_plaintext_cache by delegating; the method
  became required on main, and the test target no longer compiled.
- docs/security/encryption.md: the rebase put "Index build staging" in the
  middle of the "What Stays Plaintext" list, stranding the cache upgrade
  note and the proxy-peer bullet under it. The list is whole again and the
  staging section follows it. The section also says that bulk import
  stages under $TMPDIR/fluree-import or FLUREE_IMPORT_DIR rather than
  data_dir, and that an import which panics or is cancelled leaves its
  session directory behind (#1950).
- import.rs: derive_session_dir's doc said a failed import keeps its
  directory for debugging; cleanup runs on success and failure alike
  unless cleanup_local_files is off. The call-site comment said the
  directory derives from storage's data directory; storage is not
  consulted.
- rebuild_index_from_commits' doc comment gains its missing summary line.
@bplatz

bplatz commented Sep 25, 2026

Copy link
Copy Markdown
Contributor Author

@aaj3f heads-up, since you approved 470b2f494 and the diff has changed since. Rebasing onto main after #1916 merged broke two things, both fixed in db82de8:

Otherwise db82de8 is the comment fixes and #1950 from your review threads. Only the docs section needs a fresh look.

@bplatz
bplatz merged commit ad56d59 into main Sep 25, 2026
16 checks passed
@bplatz
bplatz deleted the fix/index-build-staging-guard branch September 25, 2026 23:28
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