Skip to content

feat: add CDC lazy chunking recovery cron job - #1089

Merged
kalbasit merged 4 commits into
mainfrom
feat-add-cdc-lazy-chunking
Mar 15, 2026
Merged

kalbasit merged 4 commits into
mainfrom
feat-add-cdc-lazy-chunking

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

This implements a cron job that periodically scans for stuck NARs and
triggers background chunking for them. When CDC lazy chunking is enabled
and ncps is restarted before background chunking completes, NARs can
become stuck in a state with total_chunks=0 and
chunking_started_at=NULL.

The recovery job:

  • Runs on a configurable schedule (default: every 5 minutes)
  • Processes up to 100 stuck NARs per run (configurable)
  • Uses the interval between runs as the age cutoff to identify genuinely
    stuck NARs
  • Uses distributed locking to prevent duplicate processing across
    instances

New CLI flags:

  • --cache-cdc-lazy-recovery-schedule (default: @every 5m)
  • --cache-cdc-lazy-recovery-batch-size (default: 100)

New Helm values:

  • config.cdc.lazyRecoverySchedule
  • config.cdc.lazyRecoveryBatchSize

@kalbasit

kalbasit commented Mar 14, 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:XL This PR changes 500-999 lines, ignoring generated files. enhancement New feature or request go Pull requests that update go code helm labels Mar 14, 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 introduces a robust recovery mechanism for the CDC lazy chunking feature. It addresses a critical issue where NAR files could become permanently stuck if the system restarted before their background chunking completed. By adding a scheduled cron job, the system can now automatically detect and re-initiate chunking for these stalled files, significantly improving the reliability and resilience of the CDC process. The solution is designed with configurability and distributed environments in mind, ensuring efficient and safe operation.

Highlights

  • Automated CDC Lazy Chunking Recovery: Introduced a new cron job that periodically scans for NARs (Nix Archive files) that are stuck in a non-chunked state due to system restarts or other issues during CDC lazy chunking.
  • Stuck NAR Identification and Remediation: The recovery job identifies stuck NARs by checking for total_chunks = 0 and chunking_started_at = NULL and then triggers background chunking for them to complete the process.
  • Configurable Schedule and Batch Processing: The recovery process is highly configurable, allowing users to set the cron schedule (default: every 5 minutes) and the maximum number of stuck NARs to process per run (default: 100).
  • Distributed Locking for Concurrency Control: Implemented distributed locking to ensure that only one instance of the recovery job runs at a time across multiple deployments, preventing duplicate processing and resource contention.
  • New Configuration Options: Added new CLI flags (--cache-cdc-lazy-recovery-schedule, --cache-cdc-lazy-recovery-batch-size) and corresponding Helm chart values (config.cdc.lazyRecoverySchedule, config.cdc.lazyRecoveryBatchSize) for managing the recovery cron job.
Changelog
  • charts/ncps/templates/configmap.yaml
    • Added lazy-recovery-schedule and lazy-recovery-batch-size configuration options to the Helm chart's configmap template.
  • charts/ncps/values.yaml
    • Defined default values for lazyRecoverySchedule and lazyRecoveryBatchSize in the Helm chart's values.yaml.
  • db/query.mysql.sql
    • Added a new SQL query GetStuckNarFiles to retrieve NAR files that are stuck in the chunking process for MySQL.
  • db/query.postgres.sql
    • Added a new SQL query GetStuckNarFiles to retrieve NAR files that are stuck in the chunking process for PostgreSQL.
  • db/query.sqlite.sql
    • Added a new SQL query GetStuckNarFiles to retrieve NAR files that are stuck in the chunking process for SQLite.
  • pkg/cache/cache.go
    • Imported the math package.
    • Added AddCDCLazyRecoveryCronJob function to schedule the new recovery cron job.
    • Implemented runCDCLazyRecovery function containing the core logic for identifying and recovering stuck NAR files, including distributed locking.
  • pkg/database/generated_models.go
    • Defined GetStuckNarFilesParams and GetStuckNarFilesRow structs for the new database query.
  • pkg/database/generated_querier.go
    • Extended the Querier interface with the GetStuckNarFiles method.
  • pkg/database/generated_wrapper_mysql.go
    • Implemented the GetStuckNarFiles method for the MySQL database wrapper.
  • pkg/database/generated_wrapper_postgres.go
    • Implemented the GetStuckNarFiles method for the PostgreSQL database wrapper.
  • pkg/database/generated_wrapper_sqlite.go
    • Implemented the GetStuckNarFiles method for the SQLite database wrapper.
  • pkg/database/mysqldb/querier.go
    • Added GetStuckNarFiles to the MySQL-specific Querier interface.
  • pkg/database/mysqldb/query.mysql.sql.go
    • Generated Go code for the GetStuckNarFiles SQL query for MySQL, including its parameters and return types.
  • pkg/database/postgresdb/querier.go
    • Added GetStuckNarFiles to the PostgreSQL-specific Querier interface.
  • pkg/database/postgresdb/query.postgres.sql.go
    • Generated Go code for the GetStuckNarFiles SQL query for PostgreSQL, including its parameters and return types.
  • pkg/database/sqlitedb/querier.go
    • Added GetStuckNarFiles to the SQLite-specific Querier interface.
  • pkg/database/sqlitedb/query.sqlite.sql.go
    • Generated Go code for the GetStuckNarFiles SQL query for SQLite, including its parameters and return types.
  • pkg/ncps/serve.go
    • Added new CLI flags --cache-cdc-lazy-recovery-schedule and --cache-cdc-lazy-recovery-batch-size.
    • Integrated the CDC lazy recovery cron job into the cache creation process, parsing its schedule and batch size from CLI flags.
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 14, 2026 •

Copy link
Copy Markdown

Documentation Updates

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

Cache and Storage Configuration Flags
View Changes
@@ -209,6 +209,18 @@
   - 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.
 
+- `--cache-cdc-lazy-recovery-schedule` (string): Cron schedule for recovering stuck NARs in lazy chunking mode. Default: `@every 5m`
+  - Environment variable: `CACHE_CDC_LAZY_RECOVERY_SCHEDULE`
+  - YAML key: `cache.cdc.lazy-recovery-schedule`
+  - Helm value: `config.cdc.lazyRecoverySchedule`
+  - Purpose: Controls the schedule for a background recovery mechanism that automatically re-triggers chunking for NARs that became stuck when ncps restarted before background chunking completed. Accepts `@every X` format (e.g., `@every 5m`, `@every 10m`) or standard cron expressions. This job uses distributed locking to prevent duplicate processing across instances.
+
+- `--cache-cdc-lazy-recovery-batch-size` (integer): Maximum number of stuck NARs to process per recovery cron run. Default: `100`
+  - Environment variable: `CACHE_CDC_LAZY_RECOVERY_BATCH_SIZE`
+  - YAML key: `cache.cdc.lazy-recovery-batch-size`
+  - Helm value: `config.cdc.lazyRecoveryBatchSize`
+  - Purpose: Limits the number of stuck NARs that will be recovered in each run to avoid overloading the system. NARs are identified as stuck if they have `total_chunks = 0`, `chunking_started_at = NULL`, and are older than the recovery interval.
+
 **Behavior:**
 
 When lazy chunking is enabled (the default), NAR files are stored in their original compressed format first, then chunked in the background. When a new NAR is added to the cache:
@@ -277,6 +289,8 @@
     lazy-chunking-enabled: true
     background-workers: 4
     delete-delay: 48h
+    lazy-recovery-schedule: "@every 10m"
+    lazy-recovery-batch-size: 50
 ```
 
 **Note:** The existing `migrate-nar-to-chunks` CLI command can still be used for manual chunking of stored NAR files.
@@ -427,17 +441,19 @@
 This allows fsck to focus resources on files that haven't been verified recently, while maintaining confidence that all files are periodically checked. The optimization is especially beneficial for large caches with many chunked NARs, where chunk-level verification can be time-consuming.
 
 ## Summary Table of Storage Flags
-| Purpose         | CLI Flag                              | YAML Key                       | Required |
-|-----------------|--------------------------------------|-------------------------------|----------|
-| Local storage   | `--cache-storage-local`               | `cache.storage.local`         | Yes*     |
-| Temp directory  | `--cache-temp-path`                   | `cache.temp-path`             | No       |
-| S3 bucket       | `--cache-storage-s3-bucket`           | `cache.storage.s3.bucket`     | Yes*     |
-| S3 endpoint     | `--cache-storage-s3-endpoint` (must include scheme) | `cache.storage.s3.endpoint`   | Yes**    |
-| S3 region       | `--cache-storage-s3-region`           | `cache.storage.s3.region`     | No       |
-| S3 access key   | `--cache-storage-s3-access-key-id`    | `cache.storage.s3.access-key-id` | Yes** |
-| S3 secret key   | `--cache-storage-s3-secret-access-key`| `cache.storage.s3.secret-access-key` | Yes** |
-| S3 force path style | `--cache-storage-s3-force-path-style` | `cache.storage.s3.force-path-style` | No       |
-| LRU schedule timezone | `--cache-lru-schedule-timezone` | `cache.lru.schedule.timezone` | No       |
+| Purpose         | CLI Flag                              | YAML Key                       | Helm Value | Required |
+|-----------------|--------------------------------------|-------------------------------|------------|----------|
+| Local storage   | `--cache-storage-local`               | `cache.storage.local`         | N/A | Yes*     |
+| Temp directory  | `--cache-temp-path`                   | `cache.temp-path`             | N/A | No       |
+| S3 bucket       | `--cache-storage-s3-bucket`           | `cache.storage.s3.bucket`     | N/A | Yes*     |
+| S3 endpoint     | `--cache-storage-s3-endpoint` (must include scheme) | `cache.storage.s3.endpoint`   | N/A | Yes**    |
+| S3 region       | `--cache-storage-s3-region`           | `cache.storage.s3.region`     | N/A | No       |
+| S3 access key   | `--cache-storage-s3-access-key-id`    | `cache.storage.s3.access-key-id` | N/A | Yes** |
+| S3 secret key   | `--cache-storage-s3-secret-access-key`| `cache.storage.s3.secret-access-key` | N/A | Yes** |
+| S3 force path style | `--cache-storage-s3-force-path-style` | `cache.storage.s3.force-path-style` | N/A | No       |
+| LRU schedule timezone | `--cache-lru-schedule-timezone` | `cache.lru.schedule.timezone` | N/A | No       |
+| CDC lazy recovery schedule | `--cache-cdc-lazy-recovery-schedule` | `cache.cdc.lazy-recovery-schedule` | `config.cdc.lazyRecoverySchedule` | No (default: `@every 5m`) |
+| CDC lazy recovery batch size | `--cache-cdc-lazy-recovery-batch-size` | `cache.cdc.lazy-recovery-batch-size` | `config.cdc.lazyRecoveryBatchSize` | No (default: `100`) |
 
 * Either local or S3 storage must be configured, not both.  
 ** Required for S3 storage.
NAR File Download and Streaming
View Changes
@@ -114,7 +114,7 @@
 
 - **Fully chunked**: Records with `total_chunks > 0` and `chunking_started_at` set. These records represent NAR files that have been successfully chunked and are ready for CDC streaming.
 - **Actively chunking**: Records with `chunking_started_at` set but `total_chunks = 0`. These records indicate that chunking is in progress. When lazy chunking is disabled, the `chunking_started_at` timestamp is set within milliseconds of download start (before decompression completes), allowing other HA instances to immediately detect active chunking operations and use progressive streaming. The system uses progressive streaming to serve these NARs while chunking completes.
-- **Pending migration (lazy chunking)**: Records with `total_chunks = 0` and `chunking_started_at = NULL`. When lazy chunking is enabled (the default), 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.
+- **Pending migration (lazy chunking)**: Records with `total_chunks = 0` and `chunking_started_at = NULL`. When lazy chunking is enabled (the default), 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, 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.
 
 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.
@@ -279,6 +279,19 @@
 - 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
+
+**Recovery of Stuck NARs:**
+
+When lazy chunking is enabled and ncps is restarted before background chunking completes, NARs can become stuck in a state with `total_chunks = 0` and `chunking_started_at = NULL`. To recover from this scenario, the system implements a recovery cron job (via `AddCDCLazyRecoveryCronJob`) that periodically scans for and recovers these stuck NAR files.
+
+The recovery job:
+
+- Runs on a configurable schedule (default: every 5 minutes via `--cache-cdc-lazy-recovery-schedule`)
+- Uses the interval between runs as the age cutoff to identify genuinely stuck NARs (e.g., if it runs every 5 minutes, it only processes NARs older than 5 minutes)
+- Processes up to a configurable number of stuck NARs per run (default: 100 via `--cache-cdc-lazy-recovery-batch-size`)
+- Uses distributed locking to prevent duplicate processing across multiple ncps instances
+
+The `--cache-cdc-lazy-recovery-schedule` flag accepts either `@every X` format (e.g., `@every 5m`, `@every 10m`) or standard cron expressions. The corresponding Helm chart values are `config.cdc.lazyRecoverySchedule` and `config.cdc.lazyRecoveryBatchSize`.
 
 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.
 

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 a cron job to recover stuck NARs in CDC lazy chunking mode. The implementation is mostly solid, but I've found a significant issue with how the recovery interval is calculated, which could lead to the job not functioning as intended. I've proposed a set of changes across pkg/ncps/serve.go and pkg/cache/cache.go to calculate this interval dynamically and make the feature more robust. I also have a couple of minor suggestions for improving code clarity and consistency.

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/ncps/serve.go Resolved
Comment thread charts/ncps/values.yaml Resolved
Comment thread pkg/cache/cache.go Resolved
@codecov

codecov Bot commented Mar 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 5.04%. Comparing base (1b8a9f2) to head (a256c09).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@          Coverage Diff          @@
##            main   #1089   +/-   ##
=====================================
  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.

This implements a cron job that periodically scans for stuck NARs and
triggers background chunking for them. When CDC lazy chunking is enabled
and ncps is restarted before background chunking completes, NARs can
become stuck in a state with total_chunks=0 and
chunking_started_at=NULL.

The recovery job:
- Runs on a configurable schedule (default: every 5 minutes)
- Processes up to 100 stuck NARs per run (configurable)
- Uses the interval between runs as the age cutoff to identify genuinely
  stuck NARs
- Uses distributed locking to prevent duplicate processing across
  instances

New CLI flags:
- --cache-cdc-lazy-recovery-schedule (default: @every 5m)
- --cache-cdc-lazy-recovery-batch-size (default: 100)

New Helm values:
- config.cdc.lazyRecoverySchedule
- config.cdc.lazyRecoveryBatchSize
@kalbasit
kalbasit force-pushed the feat-add-cdc-lazy-chunking branch from 09aca89 to a256c09 Compare March 15, 2026 23:13
@kalbasit
kalbasit enabled auto-merge (squash) March 15, 2026 23:17
@kalbasit
kalbasit merged commit 37a5647 into main Mar 15, 2026
18 of 25 checks passed
@kalbasit
kalbasit deleted the feat-add-cdc-lazy-chunking branch March 15, 2026 23:26
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 helm 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