Skip to content

feat: persist CDC configuration in database config table - #971

Merged
kalbasit merged 4 commits into
mainfrom
worktree-compiled-petting-pudding
Feb 23, 2026
Merged

kalbasit merged 4 commits into
mainfrom
worktree-compiled-petting-pudding

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

Implement boot-time CDC configuration validation and persistence:

  • Add CDC config keys (cdc_enabled, cdc_min, cdc_avg, cdc_max) to database
  • Enforce immutable CDC configuration: once enabled, cannot be disabled or changed
  • Store CDC settings on first boot with CDC enabled
  • Validate on subsequent boots to prevent accidental configuration changes
  • Provide detailed error messages when configuration mismatches occur

Boot behavior:

  1. CDC disabled, no config → no-op (nothing stored)
  2. CDC enabled, no config → store all 4 values
  3. CDC enabled, config exists, same values → proceed normally
  4. CDC enabled, config exists, different values → fail boot with error
  5. CDC disabled, config exists (was enabled) → fail boot with error

Implementation:

  • Add sentinel errors: ErrCDCDisabledAfterEnabled, ErrCDCConfigMismatch
  • Implement ValidateOrStoreCDCConfig() with helper methods for clarity
  • Call validation in createCache() before SetCDCConfiguration()
  • Add 7 comprehensive test scenarios covering all boot rules
  • Support all database backends (SQLite, PostgreSQL, MySQL)

All tests pass, code passes linting, no migrations needed (uses existing config table).

Implement boot-time CDC configuration validation and persistence:
- Add CDC config keys (cdc_enabled, cdc_min, cdc_avg, cdc_max) to database
- Enforce immutable CDC configuration: once enabled, cannot be disabled or changed
- Store CDC settings on first boot with CDC enabled
- Validate on subsequent boots to prevent accidental configuration changes
- Provide detailed error messages when configuration mismatches occur

Boot behavior:
1. CDC disabled, no config → no-op (nothing stored)
2. CDC enabled, no config → store all 4 values
3. CDC enabled, config exists, same values → proceed normally
4. CDC enabled, config exists, different values → fail boot with error
5. CDC disabled, config exists (was enabled) → fail boot with error

Implementation:
- Add sentinel errors: ErrCDCDisabledAfterEnabled, ErrCDCConfigMismatch
- Implement ValidateOrStoreCDCConfig() with helper methods for clarity
- Call validation in createCache() before SetCDCConfiguration()
- Add 7 comprehensive test scenarios covering all boot rules
- Support all database backends (SQLite, PostgreSQL, MySQL)

All tests pass, code passes linting, no migrations needed (uses existing config table).

Co-Authored-By: Claude Haiku 4.5 <[email protected]>
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. enhancement New feature or request go Pull requests that update go code labels Feb 23, 2026
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @kalbasit, 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 mechanism to manage Change Data Capture (CDC) configuration by persisting its settings in the database. This ensures that once CDC is enabled and configured, its parameters remain consistent across application restarts, safeguarding data integrity and preventing accidental misconfigurations that could lead to inaccessible data chunks. The system now validates these settings at boot time, providing clear error messages for any discrepancies, thereby enhancing the reliability and stability of CDC operations.

Highlights

  • CDC Configuration Persistence: Implemented persistence for Change Data Capture (CDC) configuration parameters (enabled status, min, avg, max chunk sizes) in the database's configuration table.
  • Immutable CDC Configuration: Enforced immutability for CDC settings: once enabled, it cannot be disabled or have its parameters changed on subsequent boots, preventing data inconsistency.
  • Boot-time Validation: Added boot-time validation to check current CDC configuration against stored values, failing startup with detailed error messages if mismatches or attempts to disable occur.
  • New Error Types: Introduced two new sentinel errors, ErrCDCDisabledAfterEnabled and ErrCDCConfigMismatch, to provide specific feedback on configuration violations.
  • Comprehensive Testing: Added seven new test scenarios covering all defined boot behaviors and validation rules across SQLite, PostgreSQL, and MySQL database backends.
Changelog
  • pkg/config/config.go
    • Imported the 'strings' package for string manipulation in error messages.
    • Defined new constants for CDC configuration keys: KeyCDCEnabled, KeyCDCMin, KeyCDCAvg, and KeyCDCMax.
    • Added new error variables: ErrCDCDisabledAfterEnabled and ErrCDCConfigMismatch with descriptive messages.
    • Implemented getter and setter methods for each new CDC configuration key (e.g., GetCDCEnabled, SetCDCEnabled).
    • Introduced ValidateOrStoreCDCConfig function to handle the core logic of validating or persisting CDC settings based on boot state.
    • Added helper functions storeCDCConfig and validateCDCConfig to encapsulate the logic for storing and comparing CDC parameters respectively.
  • pkg/config/config_test.go
    • Added TestValidateOrStoreCDCConfigBackends to execute CDC configuration tests across different database types.
    • Implemented runValidateOrStoreCDCConfigTestSuite to structure and run various CDC validation test cases.
    • Created testValidateCDCFirstBootDisabled to verify that no CDC config is stored if CDC is disabled on first boot.
    • Developed testValidateCDCFirstBootEnabled to confirm that all CDC config values are stored correctly on first boot when enabled.
    • Added testValidateCDCSameFlags to ensure successful boot when CDC configuration matches stored values.
    • Included testValidateCDCChangedMin, testValidateCDCChangedAvg, and testValidateCDCChangedMax to test failure scenarios when individual CDC parameters are changed on subsequent boots.
    • Implemented testValidateCDCDisableAfterEnabled to confirm that disabling CDC after it was previously enabled results in an error.
  • pkg/ncps/serve.go
    • Extracted CDC configuration parameters (cdcEnabled, cdcMin, cdcAvg, cdcMax) into local variables.
    • Integrated a call to config.ValidateOrStoreCDCConfig to perform boot-time validation or persistence of CDC settings.
    • Added error handling for the ValidateOrStoreCDCConfig call, returning a formatted error if validation fails.
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 Feb 23, 2026 •

Copy link
Copy Markdown

Documentation Updates

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

NAR File Download and Streaming
View Changes
@@ -57,24 +57,31 @@
 
 The `migrate-nar-to-chunks` command requires CDC to be enabled via the `--cache-cdc-enabled` flag. If CDC is disabled, the command will return an error: "migrate-nar-to-chunks command requires CDC to be enabled". This ensures that the migration infrastructure is properly configured before attempting to migrate existing NAR files to the chunked storage format.
 
-> **⚠️ Warning: CDC Configuration is Immutable**
+> **⚠️ CDC Configuration Enforcement**
 >
-> CDC configuration is a **one-way operation** that becomes permanent once enabled. Before enabling CDC for the first time, carefully plan your configuration:
+> CDC configuration is validated and enforced at server startup. Once CDC is enabled, the configuration becomes immutable to prevent data inconsistency. Before enabling CDC for the first time, carefully plan your configuration:
 >
-> - **Cannot Disable CDC**: Once CDC is enabled (`--cache-cdc-enabled=true`) and NAR data has been chunked, you cannot later disable it. Attempting to start the server with `--cache-cdc-enabled=false` after CDC has been enabled will cause a boot failure with the error: "CDC was previously enabled and cannot be disabled; existing chunks would become inaccessible".
+> **Boot-Time Validation:**
 >
-> - **Cannot Change Chunk Sizes**: The CDC chunk size parameters (`--cache-cdc-min`, `--cache-cdc-avg`, `--cache-cdc-max`) are permanently stored in the database on first boot with CDC enabled. Changing any of these values on subsequent boots will cause a boot failure with the error: "CDC configuration mismatch; existing chunks would be inaccessible if values change".
+> The server validates CDC configuration using `ValidateOrStoreCDCConfig()` during startup. CDC settings are persisted to the database `config` table with keys: `cdc_enabled`, `cdc_min`, `cdc_avg`, and `cdc_max`. If validation fails, the server will refuse to start.
 >
-> - **Boot-Time Validation**: On every boot, the server validates that the current CDC configuration matches the stored configuration. If any values differ (enabled flag or chunk sizes), the server will fail to start with a detailed error message indicating which values differ (e.g., "cdc_min: stored=65536, current=32768").
+> **Configuration Errors That Prevent Startup:**
 >
-> - **Planning Guidance**: Choose your CDC configuration carefully before enabling it for the first time, as it becomes permanent for that deployment. If different CDC parameters are needed later, a new deployment with fresh storage would be required.
+> - **Disabling CDC After Enabled**: Attempting to disable CDC after it was previously enabled will fail with: `"CDC cannot be disabled after being enabled; existing chunked NARs would not be reconstructed"`. This prevents the server from running in a state where existing chunked NAR files cannot be properly reconstructed.
 >
-> **Configuration Persistence Behavior:**
-> 1. **CDC disabled, no stored config**: No configuration is stored (no-op).
-> 2. **CDC enabled, no stored config**: All 4 values (enabled flag, min, avg, max) are stored in the database.
-> 3. **CDC enabled, config exists, same values**: Server boots normally.
-> 4. **CDC enabled, config exists, different values**: Server fails to boot with detailed mismatch error.
-> 5. **CDC disabled, config exists (was previously enabled)**: Server fails to boot with error.
+> - **Changing CDC Parameters**: Modifying any CDC chunk size parameter (`--cache-cdc-min`, `--cache-cdc-avg`, `--cache-cdc-max`) after initial configuration will fail with: `"CDC config changed; different chunk sizes create new chunks without reusing old ones, causing storage duplication"`. The error includes specific parameter mismatches (e.g., `"cdc_min: stored=65536, current=32768"`). Changing chunk sizes would create new chunks without reusing existing ones, leading to storage duplication and preventing proper NAR reconstruction.
+>
+> **Boot Scenarios:**
+>
+> 1. **CDC disabled, no stored config**: No configuration is stored (no-op). Server starts normally.
+> 2. **CDC enabled, no stored config**: All 4 configuration values are persisted to the database. Server starts normally.
+> 3. **CDC enabled, config exists, same values**: Configuration validation passes. Server starts normally.
+> 4. **CDC enabled, config exists, different values**: Configuration validation fails with detailed mismatch errors. Server refuses to start.
+> 5. **CDC disabled, config exists (was previously enabled)**: Configuration validation fails. Server refuses to start.
+>
+> **Planning Guidance:**
+>
+> Choose your CDC configuration carefully before enabling it for the first time, as it becomes permanent for that deployment. If different CDC parameters are needed later, a new deployment with fresh storage would be required.
 
 ### Error Propagation
 Errors encountered during download (e.g., upstream failures, disk write errors) are stored in the `downloadError` field of `downloadState`. Waiting goroutines are signaled via the condition variable, and clients receive the error immediately if it occurs. This ensures that failures are communicated promptly and that resources are cleaned up appropriately [source](https://github.com/kalbasit/ncps/blob/b7653d4303670bb88fd34b8bf82ed3aade09885d/pkg/cache/cache.go#L94-L677).

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 robust mechanism for persisting and validating CDC configuration in the database, ensuring that once CDC is enabled, its parameters are immutable. The implementation is well-structured, with clear separation of concerns between storing and validating the configuration. The addition of comprehensive, multi-backend tests is excellent and covers all the defined boot-time behaviors.

My review includes a couple of suggestions to simplify the code by removing an unused function parameter and a redundant validation check. Overall, this is a solid feature addition that improves the reliability of the CDC configuration.

Comment thread pkg/config/config.go Resolved
Comment thread pkg/config/config.go Resolved
Comment thread pkg/config/config.go Resolved
kalbasit and others added 3 commits February 22, 2026 23:52
Update error messages to accurately describe the issues:
- CDC config mismatch: chunks won't be reused, causing storage duplication
- CDC disabled after enabled: chunked NARs won't be reconstructed properly

Update test assertions to match new error messages.

Co-Authored-By: Claude Haiku 4.5 <[email protected]>

Copy link
Copy Markdown
Owner Author

This stack of pull requests is managed by Graphite. Learn more about stacking.

@kalbasit
kalbasit enabled auto-merge (squash) February 23, 2026 08:05
@codecov

codecov Bot commented Feb 23, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@          Coverage Diff          @@
##            main    #971   +/-   ##
=====================================
  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 3ba9750 into main Feb 23, 2026
16 checks passed
@kalbasit
kalbasit deleted the worktree-compiled-petting-pudding branch February 23, 2026 08:14
@kalbasit kalbasit added the backport release-0.9 Backport PR automatically label Feb 23, 2026
kalbasit added a commit that referenced this pull request Feb 23, 2026
Implement boot-time CDC configuration validation and persistence:
- Add CDC config keys (cdc_enabled, cdc_min, cdc_avg, cdc_max) to
  database
- Enforce immutable CDC configuration: once enabled, cannot be disabled
  or changed
- Store CDC settings on first boot with CDC enabled
- Validate on subsequent boots to prevent accidental configuration
  changes
- Provide detailed error messages when configuration mismatches occur

Boot behavior:
1. CDC disabled, no config → no-op (nothing stored)
2. CDC enabled, no config → store all 4 values
3. CDC enabled, config exists, same values → proceed normally
4. CDC enabled, config exists, different values → fail boot with error
5. CDC disabled, config exists (was enabled) → fail boot with error

Implementation:
- Add sentinel errors: ErrCDCDisabledAfterEnabled, ErrCDCConfigMismatch
- Implement ValidateOrStoreCDCConfig() with helper methods for clarity
- Call validation in createCache() before SetCDCConfiguration()
- Add 7 comprehensive test scenarios covering all boot rules
- Support all database backends (SQLite, PostgreSQL, MySQL)

All tests pass, code passes linting, no migrations needed (uses existing
config table).

---------

Co-authored-by: Claude Haiku 4.5 <[email protected]>
(cherry picked from commit 3ba9750)
@kalbasit

Copy link
Copy Markdown
Owner Author

Successfully created backport PR for release-0.9:

kalbasit added a commit that referenced this pull request Feb 23, 2026
…] (#972)

Bot-based backport to `release-0.9`, triggered by a label in #971.

Implement boot-time CDC configuration validation and persistence:
- Add CDC config keys (cdc_enabled, cdc_min, cdc_avg, cdc_max) to
database
- Enforce immutable CDC configuration: once enabled, cannot be disabled
or changed
- Store CDC settings on first boot with CDC enabled
- Validate on subsequent boots to prevent accidental configuration
changes
- Provide detailed error messages when configuration mismatches occur

Boot behavior:
1. CDC disabled, no config → no-op (nothing stored)
2. CDC enabled, no config → store all 4 values
3. CDC enabled, config exists, same values → proceed normally
4. CDC enabled, config exists, different values → fail boot with error
5. CDC disabled, config exists (was enabled) → fail boot with error

Implementation:
- Add sentinel errors: ErrCDCDisabledAfterEnabled, ErrCDCConfigMismatch
- Implement ValidateOrStoreCDCConfig() with helper methods for clarity
- Call validation in createCache() before SetCDCConfiguration()
- Add 7 comprehensive test scenarios covering all boot rules
- Support all database backends (SQLite, PostgreSQL, MySQL)

All tests pass, code passes linting, no migrations needed (uses existing
config table).

Co-authored-by: Claude Haiku 4.5 <[email protected]>
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

backport release-0.9 Backport PR automatically enhancement New feature or request go Pull requests that update go code size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant