Skip to content

fix(storage/local): don't wipe store/tmp on startup - #1313

Merged
kalbasit merged 2 commits into
mainfrom
user/wnasreddine/tmp-dir
Jun 2, 2026
Merged

kalbasit merged 2 commits into
mainfrom
user/wnasreddine/tmp-dir

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 2, 2026

Copy link
Copy Markdown
Owner

Summary

  • Remove os.RemoveAll(storeTMPPath()) from setupDirs() in pkg/storage/local
  • On a shared NFS PVC with two replicas, the incoming pod was deleting
    in-flight downloads owned by the outgoing pod during rolling updates,
    racing with active writes and crashing on startup
  • os.MkdirAll (called immediately after) already handles both the
    "dir exists" and "dir doesn't exist" cases idempotently — the RemoveAll
    was never necessary for correctness, only for a "clean slate" that is
    unsafe in a multi-pod topology
  • Leftover partial files are benign: the write path uses atomic
    tmp-then-rename and partials are never promoted to the NAR path

Test plan

  • task fmt — no changes
  • task lint — 0 issues
  • task test — all packages pass
  • TestSetupDirsIdempotent — calling New() twice on same dir succeeds
  • TestSetupDirsPreservesExistingTmpFiles — existing tmp files survive startup
  • TestNew/store/tmp_files_are_preserved_on_boot — updated to assert new behaviour

setupDirs() called os.RemoveAll(storeTMPPath()) on every boot,
intending a clean slate. On a shared NFS PVC with two replicas,
the incoming pod deleted in-flight downloads that the outgoing pod
still owned, racing with active writes and crashing the rolling
update.

The downstream os.MkdirAll call already handles both the
"dir exists" and "dir doesn't exist" cases idempotently, so
removing RemoveAll is sufficient. Leftover partial files are
benign because the write path uses an atomic tmp-then-rename
pattern and partial files are never promoted to the NAR path.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@kalbasit

kalbasit commented Jun 2, 2026 •

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. go Pull requests that update go code labels Jun 2, 2026
@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fa110a1a-ca27-49fd-aa78-96ad30d87d2b

📥 Commits

Reviewing files that changed from the base of the PR and between ab1dad6 and 69f5a87.

📒 Files selected for processing (1)
  • pkg/storage/local/local_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/storage/local/local_test.go

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Local storage initialization is now idempotent and safe to call multiple times across restarts.
    • Temporary files in the store/tmp directory are preserved during startup instead of being removed.
  • Tests

    • Added tests verifying repeated initialization and preservation of pre-existing tmp files.
  • Documentation

    • Added spec, design, proposal, and task docs defining and tracking the idempotent initialization change.

Walkthrough

This PR makes local storage directory initialization idempotent by removing the startup deletion of store/tmp. The change prevents rolling-update races on shared PVCs by allowing repeated setupDirs() calls to succeed without destroying existing partial download files. Documentation, implementation, and tests are all updated consistently.

Changes

Idempotent Local Store Directory Setup

Layer / File(s) Summary
Specifications and Requirements Documentation
openspec/changes/archive/2026-06-01-fix-store-tmp-mkdir-idempotent/.openspec.yaml, openspec/changes/archive/2026-06-01-fix-store-tmp-mkdir-idempotent/design.md, openspec/changes/archive/2026-06-01-fix-store-tmp-mkdir-idempotent/proposal.md, openspec/changes/archive/2026-06-01-fix-store-tmp-mkdir-idempotent/specs/local-store-initialization/spec.md, openspec/changes/archive/2026-06-01-fix-store-tmp-mkdir-idempotent/tasks.md, openspec/specs/local-store-initialization/spec.md
Documents the design, proposal, requirements, and task checklist for idempotent local store directory setup. Specifies that setupDirs() must succeed when directories already exist, must not delete existing partial tmp download files, and must be safe across pod restarts on shared PVCs.
Idempotent setupDirs() Implementation
pkg/storage/local/local.go
Removes the os.RemoveAll(s.storeTMPPath()) call from setupDirs() and adds store/tmp to the list of directories created with idempotent os.MkdirAll, while retaining the writability check via helper.EnsureDirWritable.
Idempotency and File Preservation Tests
pkg/storage/local/local_test.go
Updates TestNew boot-time expectation from "tmp removed" to "files preserved". Adds TestSetupDirsIdempotent to verify repeated initialization succeeds, and TestSetupDirsPreservesExistingTmpFiles to confirm partial files survive setupDirs().

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Suggested labels

size:L

Poem

🐰 A tmp directory stands proud and tall,
No longer wiped clean at each startup call,
Idempotent and safe through rolling tides,
Where NFS pods share the same tide,
Partial files dance where they now reside!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title 'fix(storage/local): don't wipe store/tmp on startup' directly matches the main objective of removing os.RemoveAll from setupDirs() to prevent deletions during rolling updates.
Description check ✅ Passed The PR description comprehensively details the removal of os.RemoveAll, the multi-pod racing issue on shared PVCs, why os.MkdirAll is sufficient, and how leftover files are benign—all directly related to the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request makes the local store directory initialization idempotent by removing the 'os.RemoveAll' call on the temporary directory in 'pkg/storage/local/local.go'. This change prevents rolling updates on shared persistent volumes from deleting active temporary files and causing crashloops. The test suite in 'pkg/storage/local/local_test.go' has been updated to assert that existing temporary files are preserved and that initialization can be safely run multiple times. There are no review comments to address, and I have no further feedback to provide.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@dosubot

dosubot Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Documentation Updates

1 document(s) were updated by changes in this PR:

NAR File Download and Streaming
View Changes
@@ -191,7 +191,7 @@
 
 When CDC is enabled and decompression is performed, the cleanup goroutine removes the uncompressed temporary file (`assetPath`) after all readers finish. The `compressedAssetPath` field is kept in the `downloadState` struct for backward compatibility but remains empty in the CDC pipeline since PR #1071 replaced the compressed temp file with an `io.Pipe`. This ensures that no temporary files persist after the NAR is stored.
 
-On startup, ncps cleans up any leftover temporary files from previous runs by removing the temp directory and recreating it. The server also validates that the temporary directory is writable during startup by creating and removing a test file. If the temporary directory is not writable, the server will fail to start immediately with an error, preventing silent failures that could occur later during NAR download operations. This boot-time validation ensures configuration issues are detected early, before the server begins accepting requests [source](https://github.com/kalbasit/ncps/blob/b7653d4303670bb88fd34b8bf82ed3aade09885d/pkg/storage/local/local.go#L305-L459).
+On startup, the temporary directory is created if it doesn't exist using `os.MkdirAll`, which is idempotent and will not modify the directory if it already exists. Any temporary files from previous runs are preserved rather than removed. This design supports shared storage scenarios (e.g., NFS PVC with multiple replicas) where removing the temp directory during startup could delete in-flight downloads owned by other pods, causing race conditions during rolling updates. Leftover partial files are harmless because the write path uses atomic tmp-then-rename, so they are never promoted to the NAR path. The server validates that the temporary directory is writable during startup by creating and removing a test file. If the temporary directory is not writable, the server will fail to start immediately with an error, preventing silent failures that could occur later during NAR download operations. This boot-time validation ensures configuration issues are detected early, before the server begins accepting requests [source](https://github.com/kalbasit/ncps/blob/b7653d4303670bb88fd34b8bf82ed3aade09885d/pkg/storage/local/local.go#L305-L459).
 
 ### Configuration of Temporary Download Paths
 The temporary directory for downloads is configurable via the `--cache-temp-path` flag or the `CACHE_TEMP_PATH` environment variable. By default, ncps uses the OS temporary directory. For local storage backends, a `tmp` subdirectory under the store path is used [source](https://github.com/kalbasit/ncps/blob/b7653d4303670bb88fd34b8bf82ed3aade09885d/cmd/serve.go#L176-L529).

How did I do? Any feedback?  Join Discord

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
pkg/storage/local/local_test.go (1)

127-133: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Close the temp file before asserting preservation.

os.CreateTemp leaves the descriptor open here, and this subtest never closes it. That leaks an FD and can make cleanup flaky on platforms that don't allow deleting open files.

Suggested fix
 		f, err := os.CreateTemp(filepath.Join(dir, "store", "tmp"), "hello")
 		require.NoError(t, err)
+		require.NoError(t, f.Close())

 		_, err = local.New(newContext(), dir)
 		require.NoError(t, err)

 		assert.FileExists(t, f.Name())
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pkg/storage/local/local_test.go` around lines 127 - 133, The temp file
created with os.CreateTemp (variable f) is left open; close it before proceeding
to avoid leaking file descriptors and flaky cleanup—call f.Close() (or defer
f.Close() immediately after creation) before invoking local.New(newContext(),
dir) and before asserting the file exists; update the test in
pkg/storage/local/local_test.go to close f so the descriptor is released prior
to the assertion.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@pkg/storage/local/local_test.go`:
- Around line 127-133: The temp file created with os.CreateTemp (variable f) is
left open; close it before proceeding to avoid leaking file descriptors and
flaky cleanup—call f.Close() (or defer f.Close() immediately after creation)
before invoking local.New(newContext(), dir) and before asserting the file
exists; update the test in pkg/storage/local/local_test.go to close f so the
descriptor is released prior to the assertion.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 03019660-24cc-4712-8cd5-013f9ca22587

📥 Commits

Reviewing files that changed from the base of the PR and between 95fc273 and ab1dad6.

📒 Files selected for processing (8)
  • openspec/changes/archive/2026-06-01-fix-store-tmp-mkdir-idempotent/.openspec.yaml
  • openspec/changes/archive/2026-06-01-fix-store-tmp-mkdir-idempotent/design.md
  • openspec/changes/archive/2026-06-01-fix-store-tmp-mkdir-idempotent/proposal.md
  • openspec/changes/archive/2026-06-01-fix-store-tmp-mkdir-idempotent/specs/local-store-initialization/spec.md
  • openspec/changes/archive/2026-06-01-fix-store-tmp-mkdir-idempotent/tasks.md
  • openspec/specs/local-store-initialization/spec.md
  • pkg/storage/local/local.go
  • pkg/storage/local/local_test.go
💤 Files with no reviewable changes (1)
  • pkg/storage/local/local.go

The "store/tmp files are preserved on boot" subtest left the
os.CreateTemp descriptor open, leaking an FD and risking flaky
cleanup on platforms that don't allow deleting open files.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@kalbasit
kalbasit enabled auto-merge (squash) June 2, 2026 04:23
@kalbasit
kalbasit merged commit 1c101ba into main Jun 2, 2026
59 of 61 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/tmp-dir branch June 2, 2026 04:32
kalbasit added a commit that referenced this pull request Jun 8, 2026
## Summary

The `[Unreleased]` section was populated in #1309 but skewed toward the
recent CDC-drain, in-flight-staging, and Ent-migration work, omitting
several user-facing features and fixes that also landed since v0.9.4.
This backfills the missing notable changes, each cross-referenced by PR.

**Added**
- `ncps fsck` command + Helm fsck CronJob (#975, #996, #998, #999,
#1000, #1004, #1006, #1176)
- Closure pinning HTTP endpoints `POST`/`DELETE /pin/{hash}.narinfo`,
`GET /pins` (#1108)
- pprof server via `--pprof-addr` (#1063)
- CDC lazy chunking as a feature + `--cache-cdc-lazy-cleanup-schedule` +
recovery cron (#1082, #1083, #1089, #1096)
- Helm: auto `GOMEMLIMIT` (#1061), configurable temp volume /
`volumeClaimTemplate` (#1074, #1077), SQLite `Recreate` strategy (#1012)
- Startup storage reporting + deprecated-narinfo warning (#959, #961)
- `docker-dev` image (#1097)

**Fixed**
- `store/tmp` no longer wiped on startup (#1313)
- `nix-hash` NAR verification (#1101)
- Prometheus counters primed at startup (#1337, #1343)
- 404 on un-reassemblable chunked NARs (#1319), purged narinfo no longer
500 (#1318), fail-fast tmp validation (#1086)
- Further CDC/cache reliability fixes (#1317, #1346, #1341, #1342,
#1331, #1347)

**Changed**
- CDC config now persisted in the DB config table (#971)

Dependency bumps, CI/test-only changes, and the internal Ent-conversion
PRs are intentionally excluded; the existing Ent-migration entry already
covers that work.

## Test plan

- [x] `nix fmt` reports no changes (docs-only edit)
- [x] CHANGELOG section structure intact
(Added/Fixed/Changed/Removed/Migration/CI)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go Pull requests that update go code size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant