Skip to content

feat: implement lazy CDC chunking with delayed compressed NAR deletion - #1082

Merged
kalbasit merged 1 commit into
mainfrom
feat-implement-lazy-cdc-chunking-2
Mar 13, 2026
Merged

kalbasit merged 1 commit into
mainfrom
feat-implement-lazy-cdc-chunking-2

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

feat: implement lazy CDC chunking with delayed compressed NAR deletion

This fixes a bug in lazy CDC chunking where narinfo compression was
incorrectly normalized to 'none' even when lazy chunking was enabled and
the NAR hadn't been chunked yet. The original compression (e.g., xz) and
FileSize are now preserved until chunking completes.

Changes:

  • Fix pullNarInfo to skip normalization when lazy chunking is enabled
  • Add --cache-cdc-delete-delay flag (default: 24h) to control delayed
    deletion
  • Modify migrateNarToChunksCleanup to skip immediate deletion in lazy
    mode
  • Add background cleanup job that runs hourly to delete old compressed
    NARs after delay
  • Add GetOldCompressedNarFiles and DeleteNarFileByID database queries

add some logs

@kalbasit

kalbasit commented Mar 13, 2026 •

Copy link
Copy Markdown
Owner Author

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. enhancement New feature or request go Pull requests that update go code labels Mar 13, 2026
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the lazy CDC (Content-Defined Chunking) functionality by addressing a critical bug that led to premature normalization of narinfo compression. The core improvement involves delaying the deletion of original compressed NAR files until a configurable period after they have been chunked. This ensures data integrity and provides a grace period for clients to transition to chunked references, preventing potential data unavailability. A new background cleanup job automates the removal of these old files, streamlining cache management and optimizing storage utilization.

Highlights

  • Lazy CDC Chunking Bug Fix: Resolved an issue where narinfo compression was incorrectly normalized to 'none' even when lazy chunking was enabled and the NAR had not yet been chunked. Original compression and FileSize are now preserved until chunking is complete.
  • Delayed Compressed NAR Deletion: Implemented a mechanism to delay the deletion of original compressed NAR files after they have been successfully chunked. This allows clients sufficient time to update their cache references before the old files are removed.
  • Configurable Deletion Delay: Added a new command-line flag, --cache-cdc-delete-delay, allowing users to configure the duration for which compressed NAR files are retained before deletion, with a default of 24 hours.
  • Background Cleanup Job: Introduced a new hourly cron job responsible for identifying and deleting old compressed NAR files that have been replaced by chunked versions and have passed their configured deletion delay.
  • New Database Queries: Added DeleteNarFileByID and GetOldCompressedNarFiles database queries to support the delayed deletion and cleanup process across MySQL, PostgreSQL, and SQLite.
  • Enhanced Logging: Integrated additional debug and error logging throughout the cache operations, particularly around NAR file record management and transaction execution, to improve observability.
Changelog
  • db/query.mysql.sql
    • Added DeleteNarFileByID query to allow deletion of NAR files by their unique ID.
    • Introduced GetOldCompressedNarFiles query to retrieve compressed NAR files that are eligible for delayed cleanup.
  • db/query.postgres.sql
    • Added DeleteNarFileByID query for PostgreSQL.
    • Introduced GetOldCompressedNarFiles query for PostgreSQL.
  • db/query.sqlite.sql
    • Added DeleteNarFileByID query for SQLite.
    • Introduced GetOldCompressedNarFiles query for SQLite.
  • pkg/cache/cache.go
    • Added cdcDeleteDelay field and associated getter/setter methods to manage the delayed deletion duration.
    • Introduced AddCDCDeletedCleanupCronJob to schedule the periodic cleanup of old compressed NAR files.
    • Modified pullNarInfo to skip narinfo compression normalization when lazy chunking is enabled, preserving original compression.
    • Updated storeNarWithCDCFromReader to conditionally skip immediate deletion of old compressed NARs based on lazy chunking status.
    • Added debug logging to ensureNarFileRecord, findOrCreateNarFileForCDC, and createOrUpdateNarFile for better transaction and NAR file record visibility.
    • Implemented runCDCDeletedCleanup function to execute the background job for deleting old compressed NARs after the delay.
  • pkg/cache/cdc_test.go
    • Added testCDCLazyChunkingPreservesOldNarFile to verify that lazy chunking correctly preserves old NAR file records until cleanup.
  • pkg/database/generated_models.go
    • Added GetOldCompressedNarFilesRow struct to represent the data returned by the new cleanup query.
  • pkg/database/generated_querier.go
    • Updated the Querier interface to include DeleteNarFileByID and GetOldCompressedNarFiles methods.
  • pkg/database/generated_wrapper_mysql.go
    • Implemented DeleteNarFileByID and GetOldCompressedNarFiles methods in the MySQL database wrapper.
  • pkg/database/generated_wrapper_postgres.go
    • Implemented DeleteNarFileByID and GetOldCompressedNarFiles methods in the PostgreSQL database wrapper.
  • pkg/database/generated_wrapper_sqlite.go
    • Implemented DeleteNarFileByID and GetOldCompressedNarFiles methods in the SQLite database wrapper.
  • pkg/database/mysqldb/querier.go
    • Updated the MySQL Querier interface to include DeleteNarFileByID and GetOldCompressedNarFiles.
  • pkg/database/mysqldb/query.mysql.sql.go
    • Generated Go code for DeleteNarFileByID and GetOldCompressedNarFiles MySQL queries.
  • pkg/database/postgresdb/querier.go
    • Updated the PostgreSQL Querier interface to include DeleteNarFileByID and GetOldCompressedNarFiles.
  • pkg/database/postgresdb/query.postgres.sql.go
    • Generated Go code for DeleteNarFileByID and GetOldCompressedNarFiles PostgreSQL queries.
  • pkg/database/sqlitedb/querier.go
    • Updated the SQLite Querier interface to include DeleteNarFileByID and GetOldCompressedNarFiles.
  • pkg/database/sqlitedb/query.sqlite.sql.go
    • Generated Go code for DeleteNarFileByID and GetOldCompressedNarFiles SQLite queries.
  • pkg/ncps/serve.go
    • Added a new cli.DurationFlag named --cache-cdc-delete-delay to configure the deletion delay.
    • Configured the cdcDeleteDelay in the cache instance based on the new flag.
    • Added logic to schedule the AddCDCDeletedCleanupCronJob when lazy chunking is enabled.
Activity
  • No human activity (comments, reviews) was provided in the context for this pull request.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@dosubot

dosubot Bot commented Mar 13, 2026 •

Copy link
Copy Markdown

Documentation Updates

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

Cache and Storage Configuration Flags
View Changes
@@ -202,6 +202,11 @@
   - Environment variable: `CACHE_CDC_BACKGROUND_WORKERS`
   - YAML key: `cache.cdc.background-workers`
 
+- `--cache-cdc-delete-delay` (duration): Delay before deleting compressed NAR files after chunking completes. Default: `24h`
+  - Environment variable: `CACHE_CDC_DELETE_DELAY`
+  - YAML key: `cache.cdc.delete-delay`
+  - Purpose: Controls how long to wait before deleting original compressed NAR files after CDC chunking completes. When lazy chunking is enabled, this delay ensures that compressed NAR files remain available during the transition period, allowing graceful fallback while chunks are being generated in the background. A background cleanup job runs hourly to delete compressed files that have been replaced by chunks and exceed this delay.
+
 **Behavior:**
 
 When lazy chunking is enabled (the default), NAR files are:
@@ -231,6 +236,13 @@
   --cache-cdc-background-workers 4
 ```
 
+**CLI Example (custom delete delay):**
+```bash
+ncps serve \
+  --cache-cdc-enabled \
+  --cache-cdc-delete-delay 48h
+```
+
 **YAML Example (using defaults):**
 ```yaml
 cache:
@@ -238,6 +250,7 @@
     enabled: true
     # lazy-chunking-enabled defaults to true
     # background-workers defaults to CPU count
+    # delete-delay defaults to 24h
 ```
 
 **YAML Example (disabling lazy chunking):**
@@ -255,6 +268,7 @@
     enabled: true
     lazy-chunking-enabled: true
     background-workers: 4
+    delete-delay: 48h
 ```
 
 **Note:** The existing `migrate-nar-to-chunks` CLI command can still be used for manual chunking of stored NAR files.
NAR File Download and Streaming
View Changes
@@ -252,6 +252,7 @@
 **Configuration:**
 - `--cache-cdc-lazy-chunking-enabled` (default: `true`): Enable lazy chunking for optimal TTFB
 - `--cache-cdc-background-workers` (default: CPU count): Number of background workers for asynchronous chunking
+- `--cache-cdc-delete-delay` (default: `24h`): Delay before deleting compressed NAR files after chunking completes
 
 **Serving Logic:**
 
@@ -259,7 +260,25 @@
 - If `total_chunks > 0`: Serve from CDC chunks for optimal performance and deduplication
 - If `total_chunks = 0`: Serve the raw compressed NAR from storage while background workers perform chunking
 
-This dual-path serving ensures clients receive data immediately while chunking happens asynchronously, maintaining the deduplication benefits of CDC without impacting TTFB.
+**Compression Preservation:**
+
+When lazy chunking is enabled and a NAR file has not yet been chunked (`total_chunks = 0`), the system preserves the original compression format (e.g., xz) and FileSize from the upstream cache in the narinfo response. This ensures clients receive accurate metadata during the chunking transition period. The `pullNarInfo` function skips the compression normalization step that would otherwise convert all CDC-enabled narinfos to `compression=none` immediately, allowing the original compressed NAR to be served until chunking completes.
+
+**Delayed Deletion:**
+
+When lazy chunking is enabled, the system implements delayed deletion of compressed NAR files after chunking completes. Rather than immediately deleting the original compressed NAR when the chunked version becomes available, the system preserves it for a configurable grace period (controlled by `--cache-cdc-delete-delay`, default: 24 hours). This provides:
+
+- A grace period for clients to update their cached narinfo records
+- Graceful degradation if the chunked version encounters issues
+- Reduced risk of cache misses during the transition
+
+A background cleanup job runs hourly (via `AddCDCDeletedCleanupCronJob`) to identify and delete old compressed NAR files that meet all these criteria:
+
+- The compressed NAR has been replaced by a chunked version (`compression != 'none'` and matching hash has `compression = 'none'` with `total_chunks > 0`)
+- The deletion delay has passed since the compressed NAR was created
+- The database record is deleted first, followed by the storage file
+
+This dual-path serving and lifecycle management ensures clients receive data immediately while chunking happens asynchronously, maintaining the deduplication benefits of CDC without impacting TTFB.
 
 To restore the previous behavior where chunking happens synchronously during download, set `--cache-cdc-lazy-chunking-enabled=false`.
 

How did I do? Any feedback?  Join Discord

@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 lazy CDC chunking with delayed deletion of compressed NARs, which correctly fixes a bug related to premature narinfo normalization. The implementation includes a new configuration flag for the deletion delay and a background cron job for cleanup, which is a solid approach. The changes are well-supported by a new test case. I've provided two suggestions: one to improve the robustness of the cleanup logic and another to address the manual modification of generated files, which should be handled by the generator script as per repository rules.

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/database/generated_wrapper_mysql.go Resolved
Base automatically changed from feat-implement-lazy-cdc-chunking to main March 13, 2026 00:37
@kalbasit
kalbasit force-pushed the feat-implement-lazy-cdc-chunking-2 branch from 8cefa7f to 28d9595 Compare March 13, 2026 00:37
@kalbasit
kalbasit enabled auto-merge (squash) March 13, 2026 00:44
This fixes a bug in lazy CDC chunking where narinfo compression was
incorrectly normalized to 'none' even when lazy chunking was enabled and
the NAR hadn't been chunked yet. The original compression (e.g., xz) and
FileSize are now preserved until chunking completes.

Changes:
- Fix pullNarInfo to skip normalization when lazy chunking is enabled
- Add --cache-cdc-delete-delay flag (default: 24h) to control delayed
  deletion
- Modify migrateNarToChunksCleanup to skip immediate deletion in lazy
  mode
- Add background cleanup job that runs hourly to delete old compressed
  NARs after delay
- Add GetOldCompressedNarFiles and DeleteNarFileByID database queries
@kalbasit
kalbasit force-pushed the feat-implement-lazy-cdc-chunking-2 branch from 28d9595 to 91037f0 Compare March 13, 2026 01:00
@codecov

codecov Bot commented Mar 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 5.04%. Comparing base (405ce06) to head (91037f0).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@          Coverage Diff          @@
##            main   #1082   +/-   ##
=====================================
  Coverage   5.04%   5.04%           
=====================================
  Files          6       6           
  Lines        436     436           
=====================================
  Hits          22      22           
  Misses       410     410           
  Partials       4       4           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@kalbasit
kalbasit merged commit 22e60a8 into main Mar 13, 2026
21 of 28 checks passed
@kalbasit
kalbasit deleted the feat-implement-lazy-cdc-chunking-2 branch March 13, 2026 01:14
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

enhancement New feature or request go Pull requests that update go code 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