Repository navigation
feat: add CDC lazy chunking recovery cron job - #1089
Conversation
|
This change is part of the following stack: Change managed by git-spice. |
Summary of ChangesHello, 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
Changelog
Using Gemini Code AssistThe 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
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 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
|
|
Documentation Updates 2 document(s) were updated by changes in this PR: Cache and Storage Configuration FlagsView 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 StreamingView 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.
|
There was a problem hiding this comment.
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.
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
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
09aca89 to
a256c09
Compare
## 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)
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:
stuck NARs
instances
New CLI flags:
New Helm values: