Repository navigation
feat(fsck): reclaim CDC chunked-NAR residue (grace-period mark-then-purge) - #1335
Conversation
|
This change is part of the following stack:
Change managed by git-spice. |
📝 WalkthroughWalkthroughThis PR implements grace-window-based chunked NAR residue reclamation for fsck. It adds a persistent Changesfsck Chunked NAR Residue Reclamation
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
Comment |
There was a problem hiding this comment.
Code Review
This pull request introduces an OpenSpec proposal and specification to safely reclaim chunked NAR residue during routine fsck runs. It adds a nullable dechunk_residue_flagged_at timestamp to the nar_file schema to track un-de-chunkable rows, allowing them to be purged only after a configurable grace window (default ~24h) to protect transient states. Recoverable inconsistent rows are normalized immediately. The review feedback suggests clarifying that dry-runs (without --repair) should not report un-de-chunkable NARs as active consistency issues unless their residue flag has already aged past the grace window, preventing false positives during routine monitoring.
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.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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.
Inline comments:
In `@openspec/changes/fsck-reclaim-chunked-residue/specs/fsck/spec.md`:
- Around line 14-38: Add an explicit SHALL requirement and scenario to the fsck
spec: require that fsck --repair SHALL NOT set dechunk_residue_flagged_at or
purge a chunked nar_file whose chunking_started_at is within the chunking lock
TTL (i.e., indicates an in-flight chunking operation); add the scenario named "A
row with a recent chunking_started_at is not flagged or purged" that matches the
suggested GIVEN/WHEN/THEN (use the same symbols chunking_started_at,
dechunk_residue_flagged_at, and fsck --repair to locate where to insert it).
Ensure the new requirement is placed with the existing de-chunkable residue
requirement and the scenario is added alongside the other scenarios.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: b5f3720f-1f40-4678-96b9-53c2edd8dfae
📒 Files selected for processing (6)
openspec/changes/fsck-reclaim-chunked-residue/.openspec.yamlopenspec/changes/fsck-reclaim-chunked-residue/design.mdopenspec/changes/fsck-reclaim-chunked-residue/proposal.mdopenspec/changes/fsck-reclaim-chunked-residue/specs/data-model/spec.mdopenspec/changes/fsck-reclaim-chunked-residue/specs/fsck/spec.mdopenspec/changes/fsck-reclaim-chunked-residue/tasks.md
28e52bf to
8bfb770
Compare
- Add a SHALL requirement + scenario: fsck MUST NOT flag or purge a row with a recent chunking_started_at (actively being chunked) (thread Hc778). - Clarify that non-repair/dry-run runs MUST NOT report an un-de-chunkable chunked NAR as an active issue until flagged and past the grace window, to avoid false positives (thread Hc42Z). Co-Authored-By: Claude Opus 4.8 <[email protected]>
34f22d9 to
32b2fb8
Compare
8bfb770 to
eacc64a
Compare
- Add a SHALL requirement + scenario: fsck MUST NOT flag or purge a row with a recent chunking_started_at (actively being chunked) (thread Hc778). - Clarify that non-repair/dry-run runs MUST NOT report an un-de-chunkable chunked NAR as an active issue until flagged and past the grace window, to avoid false positives (thread Hc42Z). Co-Authored-By: Claude Opus 4.8 <[email protected]>
32b2fb8 to
d03b434
Compare
eacc64a to
cf0e4f2
Compare
- Add a SHALL requirement + scenario: fsck MUST NOT flag or purge a row with a recent chunking_started_at (actively being chunked) (thread Hc778). - Clarify that non-repair/dry-run runs MUST NOT report an un-de-chunkable chunked NAR as an active issue until flagged and past the grace window, to avoid false positives (thread Hc42Z). Co-Authored-By: Claude Opus 4.8 <[email protected]>
d03b434 to
121ed03
Compare
cf0e4f2 to
3803efc
Compare
- Add a SHALL requirement + scenario: fsck MUST NOT flag or purge a row with a recent chunking_started_at (actively being chunked) (thread Hc778). - Clarify that non-repair/dry-run runs MUST NOT report an un-de-chunkable chunked NAR as an active issue until flagged and past the grace window, to avoid false positives (thread Hc42Z). Co-Authored-By: Claude Opus 4.8 <[email protected]>
121ed03 to
2184bb0
Compare
3803efc to
1d97f02
Compare
- Add a SHALL requirement + scenario: fsck MUST NOT flag or purge a row with a recent chunking_started_at (actively being chunked) (thread Hc778). - Clarify that non-repair/dry-run runs MUST NOT report an un-de-chunkable chunked NAR as an active issue until flagged and past the grace window, to avoid false positives (thread Hc42Z). Co-Authored-By: Claude Opus 4.8 <[email protected]>
2184bb0 to
4bfd86c
Compare
A daily-janitor fsck reclaimer for CDC chunked-NAR residue: immediately normalize recoverable inconsistent narinfos; mark un-de-chunkable rows (new nullable nar_file.dechunk_residue_flagged_at column) and purge only on a later run after a ~24h grace window if still suspect. Never harms legitimately chunked NARs. Spec deltas for fsck and data-model. Co-Authored-By: Claude Opus 4.8 <[email protected]>
- Add a SHALL requirement + scenario: fsck MUST NOT flag or purge a row with a recent chunking_started_at (actively being chunked) (thread Hc778). - Clarify that non-repair/dry-run runs MUST NOT report an un-de-chunkable chunked NAR as an active issue until flagged and past the grace window, to avoid false positives (thread Hc42Z). Co-Authored-By: Claude Opus 4.8 <[email protected]>
fsck is the tool installations run routinely, so it should keep CDC chunked-NAR residue from accumulating between operator drains -- but without ever harming a legitimately chunked NAR during active CDC. Add a two-tier residue reclaimer to fsck --repair, keyed on a new nullable nar_file.dechunk_residue_flagged_at column (forward-only additive migration, all three dialects): - Recoverable (a narinfo carries a resolvable NarHash but advertises a non-none URL): relink + normalize the narinfo URL to Compression:none immediately via Cache.NormalizeChunkedNarInfoURL. Touches no chunks; safe in any CDC state. Clears any residue flag. - Un-de-chunkable (no narinfo with a resolvable NarHash): flag on first detection, never purge on sight. Purge via the existing PurgeChunkedNar only on a later run once the flag has aged past a configurable grace window (--dechunk-residue-grace, default 24h) and the row is still un-de-chunkable. A row that becomes recoverable or de-chunked is unflagged, never purged. Guard against in-flight chunking: a row whose chunking_started_at is within the chunking lock TTL is left untouched. Recoverability is decided by the shared de-chunk resolver (now package-level cache.LinkedNarinfoNarHash) so fsck and the drain agree on what is verifiable. The mutating reconcile runs under --repair (the routine janitor) and on interactive approval; non-repair/dry-run runs only report already-flagged, grace-elapsed residue so they raise no false positives on transient or legitimately chunked NARs. The residue scan is scoped to compression=none, the canonical chunked representation the resolver, purge, and normalize all look up by. Covered by a white-box policy matrix test, the five spec scenarios as CLI tests, and a CDC-lifecycle e2e exercising the reclaimer alongside the drain. Co-Authored-By: Claude Opus 4.8 <[email protected]>
4bfd86c to
c6f2a11
Compare
|
Documentation Updates 2 document(s) were updated by changes in this PR: Cache and Storage Configuration FlagsView Changes@@ -434,6 +434,44 @@
## Fsck (File System Check) Performance Optimization
The `fsck` command verifies the integrity of cache data by checking that NAR files and chunks exist in storage and are consistent with database records. For large caches, especially those using CDC, this can be time-consuming.
+
+### CDC Chunked-NAR Residue Reclamation
+
+The `--dechunk-residue-grace` flag controls the grace period before an un-de-chunkable chunked NAR (CDC residue) is reclaimed. fsck uses a two-tier, mark-then-purge approach to prevent premature reclamation of NARs that are mid-chunking or whose narinfo is written shortly after the NAR file.
+
+**Flag:** `--dechunk-residue-grace`
+
+**Environment variable:** `CACHE_FSCK_DECHUNK_RESIDUE_GRACE`
+
+**YAML key:** `cache.fsck.dechunk-residue-grace`
+
+**Default:** `24h`
+
+**Purpose:** Controls how long an un-de-chunkable chunked NAR must stay flagged before fsck `--repair` will reclaim it. This grace window (two daily fsck runs are a day apart) prevents purging transient states and protects legitimately chunked NARs.
+
+**Two-Tier Residue Reclamation:**
+
+When fsck finds a chunked nar_file, it applies a two-tier classification:
+
+1. **Recoverable inconsistent chunked NARs:** When fsck finds a chunked nar_file whose narinfo has a valid NarHash but advertises a non-Compression:none URL (e.g., `nar/<H>.nar.xz`), fsck `--repair` immediately normalizes the URL to Compression:none without touching chunks. This is safe regardless of CDC state.
+
+2. **Un-de-chunkable chunked NARs:** When fsck finds a chunked nar_file with no narinfo carrying a resolvable NarHash:
+ - **First detection:** fsck `--repair` sets the `dechunk_residue_flagged_at` timestamp but does NOT purge
+ - **Later runs:** fsck `--repair` purges the row only if it's still un-de-chunkable AND the flag has aged past the grace window (default 24h)
+ - **Recovery:** If the row becomes recoverable before the grace window elapses, fsck clears the flag and does NOT purge
+
+**Protection for in-flight chunking:** NARs actively being chunked (chunking_started_at within the chunking lock TTL) are never flagged or purged.
+
+**Non-repair behavior:** Non-repair fsck runs (`--dry-run` or monitoring) only report un-de-chunkable rows that are already flagged AND past the grace window, avoiding alert fatigue on transient states.
+
+**Example:**
+```bash
+# Use the default 24h grace window
+ncps fsck --cache-database-url postgres://... --cache-storage-local /var/lib/ncps --repair
+
+# Custom grace window (48 hours)
+ncps fsck --cache-database-url postgres://... --cache-storage-local /var/lib/ncps --repair --dechunk-residue-grace 48h
+```
### Verified Timestamp Optimization
@@ -504,6 +542,7 @@
| CDC lazy recovery batch size | `--cache-cdc-lazy-recovery-batch-size` | `cache.cdc.lazy-recovery-batch-size` | `config.cdc.lazyRecoveryBatchSize` | No (default: `100`) |
| CDC lazy cleanup schedule | `--cache-cdc-lazy-cleanup-schedule` | `cache.cdc.lazy-cleanup-schedule` | `config.cdc.lazyCleanupSchedule` | No (default: `@every 1h`) |
| CDC chunk wait timeout | `--cache-cdc-chunk-wait-timeout` | `cache.cdc.chunk-wait-timeout` | `cache.cdc.chunkWaitTimeout` | No (default: `30s`) |
+| Fsck dechunk residue grace | `--dechunk-residue-grace` | `cache.fsck.dechunk-residue-grace` | N/A | No (default: `24h`) |
* Either local or S3 storage must be configured, not both.
** Required for S3 storage.NAR File Download and StreamingView Changes@@ -119,6 +119,10 @@
- **Pending migration (lazy chunking)**: Records with `total_chunks = 0` and `chunking_started_at = NULL`. When lazy chunking is enabled, these records represent compressed NAR files stored without chunking that are awaiting background migration. Background workers asynchronously chunk these files using the `migrate-nar-to-chunks` infrastructure. If ncps is restarted before background chunking completes, these records can become "stuck" and will be recovered by the periodic recovery cron job (see "Recovery of Stuck NARs" in the lazy chunking section).
- **Placeholder/Failed**: Records with `total_chunks = 0` and `chunking_started_at = NULL` can also represent placeholder records created during narinfo storage (via `storeInDatabase`) to link the narinfo to its eventual NAR file. If the subsequent background NAR download fails (e.g., temporary directory missing), or if a chunking operation fails partway through (e.g., "no space left on device"), these placeholder records persist in the database without actual chunked data. When chunking fails due to most errors, the system automatically clears the `chunking_started_at` lock via the `ClearNarFileChunkingStarted` database operation to prevent subsequent requests from waiting indefinitely for chunks that will never arrive. However, when chunking fails specifically due to truncation detection (where the total bytes consumed do not match the expected `NarSize`), the system intentionally leaves `chunking_started_at` set and relies on the stale lock recovery mechanism (1-hour TTL cleanup) to handle it, rather than clearing the lock immediately.
+**CDC Residue Flag:**
+
+The `nar_file` table includes a nullable `dechunk_residue_flagged_at` timestamp column that records when fsck first observed a row to be un-de-chunkable CDC chunked-NAR residue (a chunked NAR with no narinfo carrying a resolvable NarHash). NULL means "not flagged". fsck sets it on first detection of un-de-chunkable state, clears it when the row becomes recoverable or is de-chunked, and uses its age against a configurable grace window (default 24h, controlled by `--dechunk-residue-grace`) to decide deferred reclamation. fsck only purges un-de-chunkable rows that have been flagged longer than the grace window. This field is independent of `verified_at`, `bytes_stored_at`, and `chunking_started_at`.
+
When determining whether to use CDC streaming for `GetNar` requests, the system first checks for active local download jobs using `hasActiveLocalJob`. If a local download is active, it uses the faster temp-file streaming path rather than progressive CDC streaming. Otherwise, the system checks both `total_chunks > 0` AND `chunking_started_at IS NOT NULL` to ensure the record represents actual chunked data rather than a placeholder or pending migration. The `prePullNar` function distinguishes these states to decide whether to serve from existing chunks, wait for progressive streaming, or trigger a fresh download from upstream.
Placeholder records with `chunking_started_at = NULL` do not cause the system to attempt serving from non-existent chunks. The progressive streaming mechanism in `streamProgressiveChunks` uses batch queries to fetch multiple available chunks at once (up to 256 chunks per query), eliminating per-chunk poll latency when chunks are already created. The system queries the NarFileChunk junction entity with eager-loaded Chunk edges, ordered by chunk index, to efficiently retrieve batches from the database. This batch approach only polls with a 200ms sleep when no new chunks are available yet, providing fast streaming when chunks are already written. The mechanism detects aborted chunking (when `total_chunks = 0` and `chunking_started_at = NULL`) and immediately fails fast with a "chunking was aborted" error instead of waiting for the timeout. The chunk wait timeout is configurable via `--cache-cdc-chunk-wait-timeout` (default: `30s`). This prevents clients from receiving truncated streams and ensures the cache recovers gracefully from failed NAR downloads. This behavior improvement ensures reliability when background downloads or chunking operations fail partway through the caching process.
@@ -144,6 +148,21 @@
**Handling Un-reassemblable Chunked NARs:**
The migration command purges un-reassemblable chunked NARs instead of aborting the entire run. When `migrate-chunks-to-nar` encounters a chunked NAR that cannot be reassembled—because its `nar_file_chunks` links are incomplete (fewer links than `total_chunks`) or because a referenced chunk's blob is absent from the chunk store—it purges that NAR and continues migrating the remaining NARs. The `PurgeChunkedNar` method deletes the `nar_file` record and chunk links while retaining the linked narinfo, allowing the NAR to be refetched from upstream on the next request. This makes HTTP 404 responses for incomplete chunked NARs self-healing rather than permanent failures.
+
+**fsck Chunked-NAR Residue Reclamation:**
+
+fsck implements a two-tier mark-then-purge reclamation strategy for CDC chunked-NAR residue, providing a safety net that complements the self-completing de-chunk migration. fsck classifies each chunked `nar_file` as either recoverable or un-de-chunkable:
+
+- **Recoverable** (a narinfo with a resolvable NarHash, inconsistent URL): fsck relinks and normalizes the narinfo URL to the Compression:none form immediately without purging. This repair touches no chunks and is safe in any CDC state. If the row previously carried a residue flag, fsck clears it.
+
+- **Un-de-chunkable** (no resolvable NarHash): fsck uses a grace-period mark-then-purge approach:
+ - On first detection: fsck sets the `dechunk_residue_flagged_at` timestamp but does not purge
+ - On a later fsck run: if the row is still un-de-chunkable and the flag has aged past the grace window (default 24h, configurable via `--dechunk-residue-grace`), fsck purges it
+ - If the row becomes recoverable or is de-chunked before the grace window elapses, fsck clears the flag and never purges it
+
+- NARs with `chunking_started_at` within the chunking lock TTL (1 hour) are actively being chunked and are never flagged or purged by fsck.
+
+The two-run grace window (roughly two daily fsck runs) prevents purging transient states (NARs mid-chunking, narinfos not yet written) and protects legitimately chunked NARs. Non-repair runs (e.g., `--dry-run` or monitoring checks) only report already-flagged, grace-elapsed residue, so they raise no false positives. This ensures orphaned CDC residue doesn't accumulate over time while avoiding spurious cleanup of valid data.
When lazy chunking is enabled (via `--cache-cdc-lazy-chunking-enabled=true`), compressed NAR files are stored without immediate chunking, and background workers automatically perform migration using the same infrastructure as the `migrate-nar-to-chunks` command. The background workers can be configured via `--cache-cdc-background-workers` (default: number of CPUs).
|
* origin/main: fix(cdc): heal orphaned mid-chunking NAR state via migration-lock liveness (kalbasit#1317) chore(deps): update codecov/codecov-action action to v7 (kalbasit#1340) feat(fsck): reclaim CDC chunked-NAR residue (grace-period mark-then-purge) (kalbasit#1335) fix(ent): stop sqlite phantom narinfos/nar_files rebuild (kalbasit#1339) chore: update flake.lock and run go mod tidy (kalbasit#1338) fix(deps): update module github.com/mattn/go-sqlite3 to v1.14.45 (kalbasit#1336) fix(cache,fsck): self-completing CDC drain (de-chunk never strands NARs) (kalbasit#1334) fix(cache,fsck): reconcile narinfo<->nar_file links (drain-mode unblock + prevention) (kalbasit#1333) fix(cache): close the CDC url=none/xz-NAR desync (prevention + repair) (kalbasit#1332) fix(cache): durable-bytes marker for /upload reference presence (kalbasit#1330) fix(cache): non-destructive narinfo purge on root path (kalbasit#1326) # Conflicts: # migrations/mysql/atlas.sum # migrations/postgres/atlas.sum # migrations/sqlite/atlas.sum # pkg/cache/cache.go
Summary
A routine-fsck safety net for CDC chunked-NAR residue, complementing the
self-completing de-chunk migration (#1334).
Two tiers, per chunked
nar_file:nar_file.dechunk_residue_flagged_attimestamp; purge only on a later fsck run once the flag has aged past a configurable ~24h grace window (--dechunk-residue-grace) and the row is still suspect. Becomes-recoverable/de-chunked → flag cleared, never purged. Rows mid-chunking are skipped.The grace window (two daily runs) prevents purging transient states and protects legitimately chunked NARs. Non-repair/dry-run runs only report already-flagged, grace-elapsed residue, so they raise no false positives.
Includes the OpenSpec proposal and the implementation: nullable
dechunk_residue_flagged_atcolumn (forward-only additive migration, all three dialects), the two-tier reclaimer inpkg/ncps/fsck.goreusingPurgeChunkedNarand the shared de-chunk resolver, a white-box policy test, the five spec scenarios as CLI tests, and a CDC-lifecycle e2e exercising the reclaimer alongside the drain.