Skip to content

feat(fsck): reclaim CDC chunked-NAR residue (grace-period mark-then-purge) - #1335

Merged
kalbasit merged 3 commits into
mainfrom
user/wnasreddine/fsck-reclaim-chunked-residue
Jun 7, 2026
Merged

kalbasit merged 3 commits into
mainfrom
user/wnasreddine/fsck-reclaim-chunked-residue

Conversation

@kalbasit

@kalbasit kalbasit commented Jun 5, 2026 •

Copy link
Copy Markdown
Owner

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:

  • Recoverable (a narinfo with a resolvable NarHash, inconsistent URL): relink + normalize the URL to none immediately (touches no chunks; safe in any CDC state).
  • Un-de-chunkable (no resolvable NarHash): mark with a persistent nar_file.dechunk_residue_flagged_at timestamp; 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_at column (forward-only additive migration, all three dialects), the two-tier reclaimer in pkg/ncps/fsck.go reusing PurgeChunkedNar and 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.

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Jun 5, 2026
@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR implements grace-window-based chunked NAR residue reclamation for fsck. It adds a persistent dechunk_residue_flagged_at timestamp field to track un-de-chunkable entries, along with database migrations, complete ORM codegen, cache layer helpers for URL normalization, fsck policy and orchestration logic, and comprehensive tests and specifications.

Changes

fsck Chunked NAR Residue Reclamation

Layer / File(s) Summary
Data model schema and ORM codegen
ent/schema/nar_file.go, ent/migration.go, ent/mutation.go, ent/narfile.go, ent/narfile/narfile.go, ent/narfile/where.go, ent/narfile_create.go, ent/narfile_update.go, ent/runtime.go
New nullable dechunk_residue_flagged_at timestamp field added to schema; full Ent codegen across mutation tracking, create/update builders, predicates, and ORM reflective APIs; runtime field descriptor index updated.
Database migrations
migrations/mysql/20260605211804_*, migrations/postgres/20260605211804_*, migrations/sqlite/20260605211804_*
Forward-only additive migrations across MySQL, PostgreSQL, and SQLite add nullable dechunk_residue_flagged_at column to nar_files with matching index recreation and rollback support.
Cache layer infrastructure
pkg/cache/cache.go
Exports CDCChunkingLockTTL() for in-flight-chunking detection, refactors linkedNarinfoNarHash logic into shared LinkedNarinfoNarHash() helper for external residue policy use, adds NormalizeChunkedNarInfoURL() to rewrite narinfos to Compression:none form and relink orphaned references.
Chunked NAR residue policy
pkg/ncps/fsck_chunked_residue.go
Implements two-tier residue decision function classifying each chunked NAR as skip (in-flight), normalize (recoverable with URL mismatch), clearFlag/setFlag (state change), or reclaim (aged un-de-chunkable); includes paginated residue scanner and URL inconsistency checker.
fsck orchestration and CLI
pkg/ncps/fsck.go
Adds --dechunk-residue-grace flag, phase 7b residue classification (read-only), repairChunkedResidue closure for mutating state, and wires reconciliation into both non-interactive --repair and interactive approval paths with duplicate-prevention guard; updates summary reporting.
Reconciliation and mutation
pkg/ncps/fsck_chunked_residue.go (continued)
reconcileChunkedResidue() applies mutations under fsck --repair: normalizes inconsistent URLs, clears stale flags, sets flags on first detection, purges aged un-de-chunkable rows; per-row error logging and migration-in-progress deferral.
Testing
pkg/ncps/fsck_chunked_residue_internal_test.go, pkg/ncps/fsck_chunked_residue_test.go
Unit test for decideChunkedResidue() decision logic with grace-window and in-flight-chunking scenarios; six e2e tests for recoverable normalization, first-run flagging, grace-window purging, recovery unflagging, in-flight protection; integration test across repeated fsck --repair runs and migrate-chunks-to-nar.
Specifications and design docs
openspec/changes/archive/2026-06-06-fsck-reclaim-chunked-residue/*, openspec/specs/data-model/spec.md, openspec/specs/fsck/spec.md
Proposal, design, and task checklist; data-model requirement for dechunk_residue_flagged_at with set/clear lifecycle and null defaults; fsck specifications for immediate recovery normalization, grace-window flagging/purging, in-flight-chunking guards, and validation scenarios.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • kalbasit/ncps#1316: Introduces purge primitives for migrate-chunks-to-nar hash/missing-chunk failures that are reused by this PR's reconcileChunkedResidue() via c.PurgeChunkedNar.
  • kalbasit/ncps#1333: Modifies linkedNarinfoNarHash fallback and fsck narinfo-join repair behavior; this PR refactors that logic into LinkedNarinfoNarHash() shared helper for residue recoverability checking.

Suggested labels

go, size:L, merge-stack

Poem

🐰 A timestamp now marks suspicious chunks,
grace windows guard against hasty purges,
recoverable NARs spring back to life,
fsck heals what the CDC left fragmented,
and residue finally fades away. 🌱

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: adding fsck functionality to reclaim CDC chunked-NAR residue using a grace-period mark-then-purge approach.
Docstring Coverage ✅ Passed Docstring coverage is 89.74% which is sufficient. The required threshold is 80.00%.
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.
Description check ✅ Passed The PR description clearly and specifically describes the changeset: adding a two-tier fsck safety net for CDC chunked-NAR residue with grace-period marking and purging logic, including schema changes and implementation details.

✏️ 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.

@dosubot dosubot Bot added documentation Improvements or additions to documentation enhancement New feature or request labels Jun 5, 2026

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

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between 28e52bf and 34f22d9.

📒 Files selected for processing (6)
  • openspec/changes/fsck-reclaim-chunked-residue/.openspec.yaml
  • openspec/changes/fsck-reclaim-chunked-residue/design.md
  • openspec/changes/fsck-reclaim-chunked-residue/proposal.md
  • openspec/changes/fsck-reclaim-chunked-residue/specs/data-model/spec.md
  • openspec/changes/fsck-reclaim-chunked-residue/specs/fsck/spec.md
  • openspec/changes/fsck-reclaim-chunked-residue/tasks.md

@kalbasit
kalbasit force-pushed the user/wnasreddine/self-completing-cdc-drain branch from 28e52bf to 8bfb770 Compare June 5, 2026 19:07
kalbasit added a commit that referenced this pull request Jun 5, 2026
- 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]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/fsck-reclaim-chunked-residue branch from 34f22d9 to 32b2fb8 Compare June 5, 2026 19:07
@kalbasit
kalbasit force-pushed the user/wnasreddine/self-completing-cdc-drain branch from 8bfb770 to eacc64a Compare June 5, 2026 19:08
kalbasit added a commit that referenced this pull request Jun 5, 2026
- 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]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/fsck-reclaim-chunked-residue branch from 32b2fb8 to d03b434 Compare June 5, 2026 19:08
@kalbasit
kalbasit force-pushed the user/wnasreddine/self-completing-cdc-drain branch from eacc64a to cf0e4f2 Compare June 5, 2026 19:15
kalbasit added a commit that referenced this pull request Jun 5, 2026
- 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]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/fsck-reclaim-chunked-residue branch from d03b434 to 121ed03 Compare June 5, 2026 19:15
@kalbasit
kalbasit force-pushed the user/wnasreddine/self-completing-cdc-drain branch from cf0e4f2 to 3803efc Compare June 5, 2026 19:23
kalbasit added a commit that referenced this pull request Jun 5, 2026
- 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]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/fsck-reclaim-chunked-residue branch from 121ed03 to 2184bb0 Compare June 5, 2026 19:23
@kalbasit
kalbasit force-pushed the user/wnasreddine/self-completing-cdc-drain branch from 3803efc to 1d97f02 Compare June 5, 2026 19:30
kalbasit added a commit that referenced this pull request Jun 5, 2026
- 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]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/fsck-reclaim-chunked-residue branch from 2184bb0 to 4bfd86c Compare June 5, 2026 19:30
Base automatically changed from user/wnasreddine/self-completing-cdc-drain to main June 5, 2026 21:00
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Jun 5, 2026
kalbasit and others added 3 commits June 6, 2026 18:43
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]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/fsck-reclaim-chunked-residue branch from 4bfd86c to c6f2a11 Compare June 7, 2026 01:47
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 7, 2026
@kalbasit
kalbasit enabled auto-merge (squash) June 7, 2026 01:50
@kalbasit
kalbasit merged commit a25ebef into main Jun 7, 2026
41 of 54 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/fsck-reclaim-chunked-residue branch June 7, 2026 01:53
@dosubot

dosubot Bot commented Jun 7, 2026

Copy link
Copy Markdown

Documentation Updates

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

Cache and Storage Configuration Flags
View 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 Streaming
View 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).
 

How did I do? Any feedback?  Join Discord

kalbasit added a commit to bryandph/ncps that referenced this pull request Jun 7, 2026
* 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation enhancement New feature or request size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant