Skip to content

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

Closed
kalbasit wants to merge 1 commit into
release-0.9from
backport-975-to-release-0.9
Closed

kalbasit wants to merge 1 commit into
release-0.9from
backport-975-to-release-0.9

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

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

#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
kalbasit enabled auto-merge (squash) February 23, 2026 22:58
@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 introduces a crucial 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 robust mechanism to identify and optionally rectify discrepancies, ensuring that the system's data state remains healthy and reliable. The command operates with a cautious, multi-stage approach to minimize risks during operation, making it a powerful tool for system administrators.

Highlights

  • New fsck Command: Introduced a new ncps fsck command to perform integrity checks between the database and storage backends, ensuring data consistency.
  • Comprehensive Integrity Checks: The command checks for narinfos without linked nar_files, orphaned nar_files in the DB, nar_files missing from storage, and orphaned NAR files in storage. In CDC mode, it also checks for orphaned chunks in the DB, chunks missing from storage, and orphaned chunk files in storage.
  • Safe Double-Check Pattern: Implemented a double-check pattern (collect suspects -> re-verify -> report -> optionally repair) to safely handle in-flight operations and prevent accidental data loss without requiring exclusive locks.
  • Repair and Dry-Run Options: Added --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 Enhancements: Extended database queriers with new methods (GetAllNarFiles, GetNarInfosWithoutNarFiles, GetAllChunks) and storage interfaces (NarWalker, ChunkWalker) to support walking through NAR and chunk files for comprehensive checks.
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 retrieve 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 retrieve 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 retrieve 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 wrapper method for MySQL.
    • Implemented GetAllNarFiles wrapper method for MySQL.
    • Implemented GetNarInfosWithoutNarFiles wrapper method for MySQL.
  • pkg/database/generated_wrapper_postgres.go
    • Implemented GetAllChunks wrapper method for PostgreSQL.
    • Implemented GetAllNarFiles wrapper method for PostgreSQL.
    • Implemented GetNarInfosWithoutNarFiles wrapper method for PostgreSQL.
  • pkg/database/generated_wrapper_sqlite.go
    • Implemented GetAllChunks wrapper method for SQLite.
    • Implemented GetAllNarFiles wrapper method for SQLite.
    • Implemented GetNarInfosWithoutNarFiles wrapper method for SQLite.
  • pkg/database/mysqldb/querier.go
    • Updated Querier interface to include GetAllChunks, GetAllNarFiles, and GetNarInfosWithoutNarFiles.
  • pkg/database/mysqldb/query.mysql.sql.go
    • Generated Go code for GetAllChunks query.
    • Generated Go code for GetAllNarFiles query and its corresponding GetAllNarFilesRow struct.
    • Generated Go code for GetNarInfosWithoutNarFiles query.
  • pkg/database/postgresdb/querier.go
    • Updated Querier interface to include GetAllChunks, GetAllNarFiles, and GetNarInfosWithoutNarFiles.
  • pkg/database/postgresdb/query.postgres.sql.go
    • Generated Go code for GetAllChunks query.
    • Generated Go code for GetAllNarFiles query and its corresponding GetAllNarFilesRow struct.
    • Generated Go code for GetNarInfosWithoutNarFiles query.
  • pkg/database/sqlitedb/querier.go
    • Updated Querier interface to include GetAllChunks, GetAllNarFiles, and GetNarInfosWithoutNarFiles.
  • pkg/database/sqlitedb/query.sqlite.sql.go
    • Generated Go code for GetAllChunks query.
    • Generated Go code for GetAllNarFiles query and its corresponding GetAllNarFilesRow struct.
    • Generated Go code for GetNarInfosWithoutNarFiles query.
  • pkg/ncps/fsck.go
    • Added the fsckCommand implementation for checking and repairing database/storage inconsistencies.
    • Defined fsckResults struct to hold detected issues.
    • Implemented collectFsckSuspects to gather potential inconsistencies.
    • Implemented reVerifyFsckSuspects to double-check issues before reporting/repairing.
    • Implemented printFsckSummary to display the results.
    • Implemented repairFsckIssues to apply fixes for detected problems.
    • Added helper functions collectChunksMissingFromStorage, collectOrphanedChunksInStorage, and narFileRowToURL.
  • pkg/ncps/fsck_test.go
    • Added new test file for fsck command.
    • Implemented TestFsckBackends to run fsck tests across SQLite, PostgreSQL, and MySQL.
    • Included test cases for clean state, narinfos without nar_files, orphaned nar_files in DB, nar_files missing from storage, orphaned NARs in storage, repair functionality, and dry-run behavior.
  • pkg/ncps/migrate_nar_to_chunks.go
    • Updated CDC enabled flag check to use configValueTrue constant.
  • pkg/ncps/root.go
    • Registered the new fsckCommand to the main CLI application.
  • pkg/ncps/serve.go
    • Defined configValueTrue constant.
    • Updated loadCDCConfigFromDB to use configValueTrue for consistency checks.
  • pkg/storage/chunk/local.go
    • Imported io/fs package.
    • Implemented WalkChunks method for local chunk storage to iterate over all chunk files.
  • pkg/storage/chunk/s3.go
    • Implemented WalkChunks method for S3 chunk storage to list and process chunk objects.
  • pkg/storage/chunk/store.go
    • Added WalkChunks method to the Store interface for chunk storage.
  • pkg/storage/local/local.go
    • Implemented WalkNars method for local NAR storage to iterate over all NAR files.
  • pkg/storage/s3/s3.go
    • Implemented WalkNars method for S3 NAR storage to list and process NAR objects.
    • 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
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. ↩

@kalbasit

Copy link
Copy Markdown
Owner Author

dup of #976

@kalbasit kalbasit closed this Feb 23, 2026
auto-merge was automatically disabled February 23, 2026 22:59

Pull request was closed

@dosubot

dosubot Bot commented Feb 23, 2026

Copy link
Copy Markdown

Related Documentation

1 document(s) may need updating based on files changed in this PR:

kalbasit's Space

S3-Compatible Storage Backend
View Suggested Changes
@@ -258,6 +258,59 @@
 ### Security Considerations
 Store credentials securely (prefer environment variables or IAM roles for AWS). Use SSL/TLS in production. For AWS, restrict access with IAM policies and consider temporary credentials. Enable bucket versioning and set appropriate bucket policies for access control. [Source](https://github.com/kalbasit/ncps/blob/b7653d4303670bb88fd34b8bf82ed3aade09885d/pkg/storage/s3/README.md#L3-L183)
 
+### Maintenance and Troubleshooting
+The `ncps fsck` command performs integrity checks between the database and S3 storage backend, helping detect and repair inconsistencies that may arise from failed uploads, interrupted operations, or manual interventions.
+
+#### What It Detects
+The command identifies several types of inconsistencies:
+
+**NAR-related issues:**
+- Narinfos in the database with no linked `nar_file` records
+- Orphaned `nar_file` records in the database (not linked to any narinfo)
+- `Nar_file` records in the database whose physical file is missing from S3 storage
+- NAR files in S3 storage that have no corresponding database record
+
+**CDC (Content-Defined Chunking) issues** (when CDC mode is enabled):
+- Orphaned chunk records in the database (not linked to any `nar_file`)
+- Chunk records in the database whose physical file is missing from storage
+- Chunk files in S3 storage that have no corresponding database record
+
+#### Command Usage
+```bash
+# Run integrity checks and prompt for repair
+ncps fsck \
+  --cache-storage-s3-bucket=my-ncps-cache \
+  --cache-storage-s3-endpoint=s3.amazonaws.com \
+  --cache-storage-s3-region=us-east-1 \
+  --cache-storage-s3-access-key-id=AKIAIOSFODNN7EXAMPLE \
+  --cache-storage-s3-secret-access-key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY \
+  --cache-database-url=sqlite:/var/lib/ncps/db.sqlite
+
+# Preview issues without making any changes
+ncps fsck --dry-run \
+  --cache-storage-s3-bucket=my-ncps-cache \
+  --cache-storage-s3-endpoint=s3.amazonaws.com \
+  --cache-database-url=sqlite:/var/lib/ncps/db.sqlite
+
+# Automatically fix detected issues without prompting
+ncps fsck --repair \
+  --cache-storage-s3-bucket=my-ncps-cache \
+  --cache-storage-s3-endpoint=s3.amazonaws.com \
+  --cache-database-url=sqlite:/var/lib/ncps/db.sqlite
+```
+
+The command uses the same S3 configuration flags (`--cache-storage-s3-*`) and database flags (`--cache-database-url`) documented in the Configuration Options section above.
+
+#### How It Works
+The `fsck` command uses a double-check pattern to safely handle in-flight operations without requiring exclusive locks:
+
+1. **Collect suspects**: Scan the database and storage to identify potential issues
+2. **Re-verify**: Double-check each suspected issue to filter out false positives from in-flight operations
+3. **Report**: Display a summary of confirmed issues
+4. **Repair** (if requested): Fix confirmed issues by removing orphaned records and files
+
+This approach ensures that concurrent upload operations are not disrupted while maintaining data integrity.
+
 ---
 
 For further details, see the [S3 backend README](https://github.com/kalbasit/ncps/blob/b7653d4303670bb88fd34b8bf82ed3aade09885d/pkg/storage/s3/README.md#L3-L183) and [project documentation](https://github.com/kalbasit/ncps/blob/b7653d4303670bb88fd34b8bf82ed3aade09885d/README.md#L46-L782).

[Accept] [Decline]

Note: You must be authenticated to accept/decline updates.

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 to detect and repair inconsistencies between the database and storage, which is a valuable addition for maintaining data integrity. The implementation uses a robust three-phase approach (collect, verify, repair) to handle in-flight operations safely. The changes are comprehensive, including new database queries, storage walking capabilities, and the core command logic with associated tests. My feedback primarily focuses on opportunities to improve performance in the data collection phase and enhance code maintainability by ensuring consistency in data structures.

Comment thread db/query.mysql.sql

-- name: GetAllNarFiles :many
-- Returns all nar_files for storage existence verification.
SELECT id, hash, compression, `query`, file_size, total_chunks, chunking_started_at, created_at, updated_at, last_accessed_at

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.

medium

The order of columns in this SELECT statement causes sqlc to generate a new struct GetAllNarFilesRow instead of reusing the existing database.NarFile struct. The query and file_size columns are swapped compared to the NarFile struct definition.

By reordering the columns to match the NarFile struct, you can eliminate the GetAllNarFilesRow struct and the manual data conversion code in pkg/ncps/fsck.go. This change should be applied to the corresponding queries in query.postgres.sql and query.sqlite.sql as well for consistency.

SELECT id, hash, compression, file_size, `query`, total_chunks, chunking_started_at, created_at, updated_at, last_accessed_at

Comment thread db/query.postgres.sql

-- name: GetAllNarFiles :many
-- Returns all nar_files for storage existence verification.
SELECT id, hash, compression, query, file_size, total_chunks, chunking_started_at, created_at, updated_at, last_accessed_at

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.

medium

The order of columns in this SELECT statement causes sqlc to generate a new struct GetAllNarFilesRow instead of reusing the existing database.NarFile struct. The query and file_size columns are swapped compared to the NarFile struct definition.

By reordering the columns to match the NarFile struct, you can eliminate the GetAllNarFilesRow struct and the manual data conversion code in pkg/ncps/fsck.go. This change should be applied to the corresponding queries in query.mysql.sql and query.sqlite.sql as well for consistency.

SELECT id, hash, compression, file_size, query, total_chunks, chunking_started_at, created_at, updated_at, last_accessed_at

Comment thread db/query.sqlite.sql

-- name: GetAllNarFiles :many
-- Returns all nar_files for storage existence verification.
SELECT id, hash, compression, "query", file_size, total_chunks, chunking_started_at, created_at, updated_at, last_accessed_at

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.

medium

The order of columns in this SELECT statement causes sqlc to generate a new struct GetAllNarFilesRow instead of reusing the existing database.NarFile struct. The query and file_size columns are swapped compared to the NarFile struct definition.

By reordering the columns to match the NarFile struct, you can eliminate the GetAllNarFilesRow struct and the manual data conversion code in pkg/ncps/fsck.go. This change should be applied to the corresponding queries in query.mysql.sql and query.postgres.sql as well for consistency.

SELECT id, hash, compression, file_size, "query", total_chunks, chunking_started_at, created_at, updated_at, last_accessed_at

Comment thread pkg/ncps/fsck.go
Comment on lines +405 to +411
func collectFsckSuspects(
ctx context.Context,
db database.Querier,
narStore storage.NarStore,
chunkStore ChunkWalker,
cdcMode bool,
) (*fsckResults, error) {

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.

medium

The current implementation of collectFsckSuspects and its helpers (collectChunksMissingFromStorage, collectOrphanedChunksInStorage) uses a pattern that can lead to poor performance on large caches, often referred to as the N+1 query problem.

Specifically:

  • To find NAR files missing from storage, it iterates through all NAR files from the database and performs a separate check (HasNar) against the storage for each one.
  • To find orphaned NAR files in storage, it walks all files in storage and performs a separate database query for each one.
  • The same pattern is repeated for chunks.

This can result in thousands or millions of individual I/O operations (either filesystem stats or S3 API calls) and database queries, which will be very slow.

A more efficient approach would be to fetch all items from both the database and storage into memory at once, and then compute the differences. This would reduce the I/O to two bulk operations: one for the database and one for storage.

Here's a suggested high-level approach for NAR files (a similar logic applies to chunks):

  1. Fetch all NAR file records from the database using db.GetAllNarFiles(ctx). Store them in a map for efficient lookup, keyed by a canonical representation of the NAR URL.
  2. Fetch all NAR file paths from storage using narWalker.WalkNars(ctx, ...). Store them in a set (e.g., map[string]struct{}).
  3. Compare the two sets in memory:
    • Iterate through the database map. If a key is not in the storage set, it's a narFilesMissingInStorage issue.
    • Iterate through the storage set. If a key is not in the database map, it's an orphanedNarFilesInStorage issue.

This will significantly improve the performance of the fsck command on large instances.

@kalbasit
kalbasit deleted the backport-975-to-release-0.9 branch February 23, 2026 23:10
@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 (76b76e6) to head (0dc09c1).
⚠️ Report is 2 commits behind head on release-0.9.

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

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:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant