Skip to content

feat: add fsck command to detect and repair DB/storage inconsistencies - #975

Merged
kalbasit merged 3 commits into
mainfrom
worktree-hashed-enchanting-pond
Feb 23, 2026
Merged

kalbasit merged 3 commits into
mainfrom
worktree-hashed-enchanting-pond

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

Summary

  • Adds a new ncps fsck command that performs integrity checks between the database and storage backends
  • Uses a double-check pattern (collect suspects → re-verify → report → optionally repair) to safely handle in-flight operations without exclusive locks
  • Supports --dry-run (preview issues without changes) and --repair (fix without prompting)

Checks performed

  • Narinfos in DB with no linked nar_file entries
  • nar_files in DB not linked to any narinfo (orphaned)
  • nar_files in DB whose physical files are missing from storage
  • NAR files in storage with no corresponding DB record
  • (CDC mode) Orphaned chunks in DB, chunks missing from storage, orphaned chunk files in storage

Changes

  • New SQL queries (GetAllNarFiles, GetNarInfosWithoutNarFiles, GetAllChunks) added to all 3 DB backends and regenerated
  • WalkNars added to storage.NarStore interface with local + S3 implementations
  • WalkChunks added to chunk.Store interface with local + S3 implementations
  • New pkg/ncps/fsck.go command implementation
  • New pkg/ncps/fsck_test.go with 7 test cases (clean, narinfos-without-narfiles, orphaned-narfiles, missing-from-storage, orphaned-in-storage, repair, dry-run)

Test plan

  • go test -race ./pkg/ncps/... -run TestFsck -v — all subtests pass
  • ncps fsck --help shows correct flags
  • ncps fsck --dry-run ... reports issues without modifying anything
  • ncps fsck --repair ... fixes issues; second run shows 0 issues

🤖 Generated with Claude Code

Adds a new `ncps fsck` command that performs integrity checks between the
database and storage backends, detecting orphaned records and missing files.
Uses a double-check pattern (collect → re-verify → report → repair) to safely
handle in-flight operations without requiring exclusive locks.

Checks performed:
- Narinfos in DB with no linked nar_file entries
- Nar_files in DB not linked to any narinfo
- Nar_files in DB whose physical files are missing from storage
- NAR files in storage with no corresponding DB record
- (CDC mode) Orphaned chunks in DB, chunks missing from storage, orphaned chunk files

Flags: --dry-run (preview only), --repair (fix without prompting)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@dosubot dosubot Bot added size:XXL This PR changes 1000+ 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 delivers a critical new fsck command to the system, designed to maintain the integrity and consistency of data stored across the database and various storage backends. It provides a powerful tool for identifying and resolving discrepancies, ensuring that the system's data state is always reliable. The implementation prioritizes safety through a multi-stage verification process and offers both diagnostic and automated repair functionalities.

Highlights

  • New fsck Command: Introduced a new ncps fsck command to perform comprehensive integrity checks between the database and storage backends, ensuring data consistency.
  • Double-Check Pattern for Safety: Implemented a robust double-check pattern (collect suspects → re-verify → report → optionally repair) to safely handle in-flight operations and prevent accidental data corruption during consistency checks.
  • Comprehensive Issue Detection: The fsck command detects various inconsistencies, including narinfos without linked nar_files, orphaned nar_files in the DB, nar_files missing from storage, orphaned NAR files in storage, and, in CDC mode, orphaned chunks in DB, chunks missing from storage, and orphaned chunk files in storage.
  • Repair and Dry-Run Capabilities: The command supports --dry-run to preview issues without making changes and --repair to automatically fix detected inconsistencies, offering flexibility in managing data integrity.
  • Database and Storage Interface Extensions: New SQL queries and corresponding Go methods (GetAllNarFiles, GetNarInfosWithoutNarFiles, GetAllChunks) were added to all database backends, and WalkNars and WalkChunks interfaces were introduced and implemented for storage backends to facilitate comprehensive file system traversal.
Changelog
  • db/query.mysql.sql
    • Added GetAllNarFiles query to retrieve all nar_files for storage existence verification.
    • Added GetNarInfosWithoutNarFiles query to find narinfos not linked to any nar_file entries.
    • Added GetAllChunks query to fetch all chunks for storage existence verification in CDC mode.
  • db/query.postgres.sql
    • Added GetAllNarFiles query to retrieve all nar_files for storage existence verification.
    • Added GetNarInfosWithoutNarFiles query to find narinfos not linked to any nar_file entries.
    • Added GetAllChunks query to fetch all chunks for storage existence verification in CDC mode.
  • db/query.sqlite.sql
    • Added GetAllNarFiles query to retrieve all nar_files for storage existence verification.
    • Added GetNarInfosWithoutNarFiles query to find narinfos not linked to any nar_file entries.
    • Added GetAllChunks query to fetch all chunks for storage existence verification in CDC mode.
  • pkg/database/generated_models.go
    • Added GetAllNarFilesRow struct to represent the result of the GetAllNarFiles query.
  • pkg/database/generated_querier.go
    • Added GetAllChunks method to the Querier interface.
    • Added GetAllNarFiles method to the Querier interface.
    • Added GetNarInfosWithoutNarFiles method to the Querier interface.
  • pkg/database/generated_wrapper_mysql.go
    • Implemented GetAllChunks method for the MySQL database wrapper.
    • Implemented GetAllNarFiles method for the MySQL database wrapper.
    • Implemented GetNarInfosWithoutNarFiles method for the MySQL database wrapper.
  • pkg/database/generated_wrapper_postgres.go
    • Implemented GetAllChunks method for the PostgreSQL database wrapper.
    • Implemented GetAllNarFiles method for the PostgreSQL database wrapper.
    • Implemented GetNarInfosWithoutNarFiles method for the PostgreSQL database wrapper.
  • pkg/database/generated_wrapper_sqlite.go
    • Implemented GetAllChunks method for the SQLite database wrapper.
    • Implemented GetAllNarFiles method for the SQLite database wrapper.
    • Implemented GetNarInfosWithoutNarFiles method for the SQLite database wrapper.
  • pkg/database/mysqldb/querier.go
    • Added GetAllChunks method to the MySQL Querier interface.
    • Added GetAllNarFiles method to the MySQL Querier interface.
    • Added GetNarInfosWithoutNarFiles method to the MySQL Querier interface.
  • pkg/database/mysqldb/query.mysql.sql.go
    • Generated Go code for GetAllChunks query.
    • Generated Go code for GetAllNarFiles query.
    • Generated Go code for GetNarInfosWithoutNarFiles query.
  • pkg/database/postgresdb/querier.go
    • Added GetAllChunks method to the PostgreSQL Querier interface.
    • Added GetAllNarFiles method to the PostgreSQL Querier interface.
    • Added GetNarInfosWithoutNarFiles method to the PostgreSQL Querier interface.
  • pkg/database/postgresdb/query.postgres.sql.go
    • Generated Go code for GetAllChunks query.
    • Generated Go code for GetAllNarFiles query.
    • Generated Go code for GetNarInfosWithoutNarFiles query.
  • pkg/database/sqlitedb/querier.go
    • Added GetAllChunks method to the SQLite Querier interface.
    • Added GetAllNarFiles method to the SQLite Querier interface.
    • Added GetNarInfosWithoutNarFiles method to the SQLite Querier interface.
  • pkg/database/sqlitedb/query.sqlite.sql.go
    • Generated Go code for GetAllChunks query.
    • Generated Go code for GetAllNarFiles query.
    • Generated Go code for GetNarInfosWithoutNarFiles query.
  • pkg/ncps/fsck.go
    • Added new fsck command implementation for checking and repairing database and storage inconsistencies.
    • Defined fsckResults struct to hold consistency check outcomes.
    • Introduced NarWalker, ChunkWalker, hasChunker, and chunkDeleter interfaces for storage operations.
    • Implemented collectFsckSuspects to gather potential issues.
    • Implemented reVerifyFsckSuspects for double-checking issues to handle in-flight operations.
    • Implemented printFsckSummary to display the results of the consistency check.
    • Implemented repairFsckIssues to apply fixes for detected inconsistencies.
    • Added helper functions collectChunksMissingFromStorage, collectOrphanedChunksInStorage, and narFileRowToURL.
  • pkg/ncps/fsck_test.go
    • Added new test file for the fsck command.
    • Implemented TestFsckBackends to run tests across SQLite, PostgreSQL, and MySQL.
    • Included subtests for clean state, various inconsistency scenarios (narinfos without nar_files, orphaned nar_files in DB, missing from storage, orphaned in storage), and repair/dry-run functionalities.
    • Provided setup functions (setupFsckSQLite, setupFsckPostgres, setupFsckMySQL) for different database environments.
    • Added utility functions (writeFsckNar1ToStorage, getFsckNarInfo, parseFsckNarInfoText) for test data management.
  • pkg/ncps/migrate_nar_to_chunks.go
    • Updated CDC enabled check to use the configValueTrue constant.
  • pkg/ncps/root.go
    • Added the new fsckCommand to the root CLI command list.
  • pkg/ncps/serve.go
    • Added configValueTrue constant for consistent boolean string comparisons.
    • Updated CDC enabled check to use the configValueTrue constant.
  • pkg/storage/chunk/local.go
    • Added WalkChunks method to iterate over all chunk files in local storage.
  • pkg/storage/chunk/s3.go
    • Added WalkChunks method to iterate over all chunk files in S3 storage.
  • pkg/storage/chunk/store.go
    • Added WalkChunks method to the Store interface for chunk storage.
  • pkg/storage/local/local.go
    • Added WalkNars method to iterate over all NAR files in local storage.
  • pkg/storage/s3/s3.go
    • Added WalkNars method to iterate over all NAR files in S3 storage.
    • Added storeNarPrefix helper function to construct the S3 prefix for NAR files.
  • pkg/storage/store.go
    • Added WalkNars method to the NarStore interface for NAR storage.
Activity
  • The pull request introduces a new fsck command, detailing its purpose, the types of checks it performs, and the underlying changes to database queries and storage interfaces.
  • The author has provided a comprehensive test plan, including go test commands and CLI usage examples for fsck with --dry-run and --repair flags, indicating thorough testing has been considered.
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

Related Documentation

Checked 7 published document(s) in 1 knowledge base(s). No updates required.

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 new fsck command, which is a valuable addition for ensuring data integrity. The implementation is comprehensive, covering various types of inconsistencies between the database and storage, and includes a safe multi-phase approach for verification and repair. The code is well-structured and includes extensive tests.

My review focuses on a few key areas:

  • Adherence to repository rules: I've noted that some generated files were modified manually, which goes against the established contribution guidelines.
  • Performance: I've identified a couple of areas in the verification and repair logic that could be optimized to reduce the number of database queries, especially on large datasets.
  • Error Handling: I've pointed out a place where an error is ignored, which could mask underlying data integrity issues.

Overall, this is a solid contribution. Addressing these points will improve the maintainability and performance of the new command.

Comment thread pkg/database/generated_wrapper_mysql.go Resolved
Comment thread pkg/ncps/fsck.go Resolved
Comment thread pkg/ncps/fsck.go Resolved
Comment thread pkg/ncps/fsck.go Resolved
- Optimize reVerifyFsckSuspects: fetch orphaned chunks once, build a
  map, then iterate instead of calling GetOrphanedChunks per suspect
- Optimize repairFsckIssues: same pattern for orphaned chunk deletion
- Fix narFileRowToURL to return an error when url.ParseQuery fails
  and update all three callers to propagate the error

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@kalbasit

Copy link
Copy Markdown
Owner Author

/gemini review

@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 new fsck command to detect and repair inconsistencies between the database and storage backends. The implementation is robust, using a double-check pattern to handle in-flight operations safely. The changes include new SQL queries, storage interface extensions, and comprehensive test cases for the new command.

My main feedback is regarding the direct modification of auto-generated database wrapper files, which goes against the repository's contribution guidelines. These files should be updated by modifying the generator script instead. I've also pointed out a minor area for improvement in error handling for better code consistency.

Overall, this is a great feature addition that enhances the tool's reliability.

Comment thread pkg/database/generated_wrapper_mysql.go Resolved
Comment thread pkg/ncps/fsck.go Resolved
Comment thread pkg/ncps/fsck.go Resolved
…g from storage

When fsck repairs a nar_file that is missing from storage, deleting the
nar_file DB record cascades to remove the narinfo_nar_files join row but
leaves the parent narinfo as an orphan. This forced users to run fsck twice
to fully clean up a single missing storage file.

Fix: after deleting nar_files missing from storage, snapshot the newly
orphaned narinfos (by comparing GetNarInfosWithoutNarFiles before and after
the deletions) and delete them in the same repair pass.

Add TestFsckBackends/.../NarFileMissingInStorageCascadeRepair to verify
that a single --repair invocation leaves the database fully clean.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@kalbasit
kalbasit merged commit 7ef3479 into main Feb 23, 2026
14 checks passed
@kalbasit
kalbasit deleted the worktree-hashed-enchanting-pond branch February 23, 2026 22:55
@kalbasit kalbasit added backport release-0.9 Backport PR automatically labels Feb 23, 2026
kalbasit added a commit that referenced this pull request Feb 23, 2026
#975)

## Summary

- Adds a new `ncps fsck` command that performs integrity checks between
the database and storage backends
- Uses a double-check pattern (collect suspects → re-verify → report →
optionally repair) to safely handle in-flight operations without
exclusive locks
- Supports `--dry-run` (preview issues without changes) and `--repair`
(fix without prompting)

## Checks performed

- Narinfos in DB with no linked `nar_file` entries
- `nar_files` in DB not linked to any narinfo (orphaned)
- `nar_files` in DB whose physical files are missing from storage
- NAR files in storage with no corresponding DB record
- (CDC mode) Orphaned chunks in DB, chunks missing from storage,
orphaned chunk files in storage

## Changes

- New SQL queries (`GetAllNarFiles`, `GetNarInfosWithoutNarFiles`,
`GetAllChunks`) added to all 3 DB backends and regenerated
- `WalkNars` added to `storage.NarStore` interface with local + S3
implementations
- `WalkChunks` added to `chunk.Store` interface with local + S3
implementations
- New `pkg/ncps/fsck.go` command implementation
- New `pkg/ncps/fsck_test.go` with 7 test cases (clean,
narinfos-without-narfiles, orphaned-narfiles, missing-from-storage,
orphaned-in-storage, repair, dry-run)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
(cherry picked from commit 7ef3479)
@kalbasit

Copy link
Copy Markdown
Owner Author

Successfully created backport PR for release-0.9:

@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
…s [backport #975] (#976)

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

## Summary

- Adds a new `ncps fsck` command that performs integrity checks between
the database and storage backends
- Uses a double-check pattern (collect suspects → re-verify → report →
optionally repair) to safely handle in-flight operations without
exclusive locks
- Supports `--dry-run` (preview issues without changes) and `--repair`
(fix without prompting)

## Checks performed

- Narinfos in DB with no linked `nar_file` entries
- `nar_files` in DB not linked to any narinfo (orphaned)
- `nar_files` in DB whose physical files are missing from storage
- NAR files in storage with no corresponding DB record
- (CDC mode) Orphaned chunks in DB, chunks missing from storage,
orphaned chunk files in storage

## Changes

- New SQL queries (`GetAllNarFiles`, `GetNarInfosWithoutNarFiles`,
`GetAllChunks`) added to all 3 DB backends and regenerated
- `WalkNars` added to `storage.NarStore` interface with local + S3
implementations
- `WalkChunks` added to `chunk.Store` interface with local + S3
implementations
- New `pkg/ncps/fsck.go` command implementation
- New `pkg/ncps/fsck_test.go` with 7 test cases (clean,
narinfos-without-narfiles, orphaned-narfiles, missing-from-storage,
orphaned-in-storage, repair, dry-run)

## Test plan

- [ ] `go test -race ./pkg/ncps/... -run TestFsck -v` — all subtests
pass
- [ ] `ncps fsck --help` shows correct flags
- [ ] `ncps fsck --dry-run ...` reports issues without modifying
anything
- [ ] `ncps fsck --repair ...` fixes issues; second run shows 0 issues

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
@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 (5c3afeb) to head (96732c3).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@          Coverage Diff          @@
##            main    #975   +/-   ##
=====================================
  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 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:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant