Repository navigation
Conversation
#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)
Summary of ChangesHello @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 Highlights
Changelog
Activity
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
|
|
dup of #976 |
Pull request was closed
|
Related Documentation 1 document(s) may need updating based on files changed in this PR: kalbasit's Space S3-Compatible Storage BackendView 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).Note: You must be authenticated to accept/decline updates. |
There was a problem hiding this comment.
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.
|
|
||
| -- 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 |
There was a problem hiding this comment.
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|
|
||
| -- 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 |
There was a problem hiding this comment.
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|
|
||
| -- 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 |
There was a problem hiding this comment.
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| func collectFsckSuspects( | ||
| ctx context.Context, | ||
| db database.Querier, | ||
| narStore storage.NarStore, | ||
| chunkStore ChunkWalker, | ||
| cdcMode bool, | ||
| ) (*fsckResults, error) { |
There was a problem hiding this comment.
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):
- 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. - Fetch all NAR file paths from storage using
narWalker.WalkNars(ctx, ...). Store them in a set (e.g.,map[string]struct{}). - Compare the two sets in memory:
- Iterate through the database map. If a key is not in the storage set, it's a
narFilesMissingInStorageissue. - Iterate through the storage set. If a key is not in the database map, it's an
orphanedNarFilesInStorageissue.
- Iterate through the database map. If a key is not in the storage set, it's a
This will significantly improve the performance of the fsck command on large instances.
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
Bot-based backport to
release-0.9, triggered by a label in #975.Summary
ncps fsckcommand that performs integrity checks between the database and storage backends--dry-run(preview issues without changes) and--repair(fix without prompting)Checks performed
nar_fileentriesnar_filesin DB not linked to any narinfo (orphaned)nar_filesin DB whose physical files are missing from storageChanges
GetAllNarFiles,GetNarInfosWithoutNarFiles,GetAllChunks) added to all 3 DB backends and regeneratedWalkNarsadded tostorage.NarStoreinterface with local + S3 implementationsWalkChunksadded tochunk.Storeinterface with local + S3 implementationspkg/ncps/fsck.gocommand implementationpkg/ncps/fsck_test.gowith 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 passncps fsck --helpshows correct flagsncps fsck --dry-run ...reports issues without modifying anythingncps fsck --repair ...fixes issues; second run shows 0 issues🤖 Generated with Claude Code