Skip to content

perf: optimize fsck with verified_at timestamp [backport #998] - #1001

Merged
kalbasit merged 1 commit into
release-0.9from
backport-998-to-release-0.9
Mar 1, 2026
Merged

kalbasit merged 1 commit into
release-0.9from
backport-998-to-release-0.9

Conversation

@kalbasit

@kalbasit kalbasit commented Mar 1, 2026

Copy link
Copy Markdown
Owner

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

This change introduces a verified_at timestamp to the nar_files table and a new --verified-since flag to the fsck command. This allows the tool to skip NARs that have been verified recently, significantly reducing the time required for subsequent fsck runs, especially for large chunked NARs.

How:

  1. Created database migrations for SQLite, PostgreSQL, and MySQL to add the verified_at column.
  2. Updated SQL queries and regenerated Go code to support the new column.
  3. Added a shouldCheckNar helper and updated fsck logic to skip NARs verified within the specified duration.
  4. Updated fsck to update verified_at whenever a successful check is performed.
  5. Added a new test case TestFsckBackends/.../VerifiedSince to verify the optimization works as expected.

This change introduces a verified_at timestamp to the nar_files table
and a new --verified-since flag to the fsck command. This allows the
tool to skip NARs that have been verified recently, significantly
reducing the time required for subsequent fsck runs, especially for
large chunked NARs.

How:
1. Created database migrations for SQLite, PostgreSQL, and MySQL to add
   the verified_at column.
2. Updated SQL queries and regenerated Go code to support the new
   column.
3. Added a shouldCheckNar helper and updated fsck logic to skip NARs
   verified within the specified duration.
4. Updated fsck to update verified_at whenever a successful check is
   performed.
5. Added a new test case TestFsckBackends/.../VerifiedSince to verify
   the optimization works as expected.

(cherry picked from commit fb770a8)
@kalbasit
kalbasit enabled auto-merge (squash) March 1, 2026 06:20
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. enhancement New feature or request go Pull requests that update go code labels Mar 1, 2026
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, 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 implements a crucial performance enhancement for the fsck command by introducing a mechanism to skip re-verifying NAR files that have been recently checked. By adding a verified_at timestamp to the nar_files table and a --verified-since flag, the system can intelligently bypass redundant checks, leading to faster and more efficient integrity verification processes, particularly for large datasets. This change directly addresses the need for optimized maintenance operations without compromising data integrity.

Highlights

  • Performance Optimization for fsck: Introduced a verified_at timestamp to the nar_files database table across SQLite, PostgreSQL, and MySQL to track when a NAR (Nix Archive) file was last successfully verified.
  • New fsck Flag: Added a --verified-since flag to the fsck command, allowing users to specify a duration within which recently verified NARs should be skipped during subsequent checks.
  • Reduced fsck Runtime: Modified the fsck logic to leverage the verified_at timestamp and the new flag, significantly reducing the time required for fsck runs by avoiding re-verification of recently checked NARs, especially beneficial for large chunked NARs.
  • Automated Timestamp Updates: Ensured that the verified_at timestamp is automatically updated in the database whenever a NAR file undergoes a successful fsck verification.
  • Comprehensive Testing: Added a new test case, TestFsckBackends/.../VerifiedSince, to thoroughly verify the functionality and effectiveness of the new optimization.
Changelog
  • db/migrations/mysql/20260301000000_add_verified_at_to_nar_files.sql
    • Added a new migration to add the verified_at column to the nar_files table in MySQL.
  • db/migrations/postgres/20260301000000_add_verified_at_to_nar_files.sql
    • Added a new migration to add the verified_at column to the nar_files table in PostgreSQL.
  • db/migrations/sqlite/20260301000000_add_verified_at_to_nar_files.sql
    • Added a new migration to add the verified_at column to the nar_files table in SQLite, including a full table rebuild for DROP COLUMN support.
  • db/query.mysql.sql
    • Updated SELECT queries to include the new verified_at column.
    • Added a new UPDATE query, UpdateNarFileVerifiedAt, to set the verified_at timestamp.
  • db/query.postgres.sql
    • Updated SELECT queries to include the new verified_at column.
    • Added a new UPDATE query, UpdateNarFileVerifiedAt, to set the verified_at timestamp.
  • db/query.sqlite.sql
    • Updated SELECT queries to include the new verified_at column.
    • Added a new UPDATE query, UpdateNarFileVerifiedAt, to set the verified_at timestamp.
  • db/schema/mysql.sql
    • Added the verified_at column to the nar_files table definition.
    • Added the new migration version to the schema_migrations table.
  • db/schema/postgres.sql
    • Added the verified_at column to the nar_files table definition.
    • Added the new migration version to the schema_migrations table.
  • db/schema/sqlite.sql
    • Added the verified_at column to the nar_files table definition.
    • Added the new migration version to the schema_migrations table.
  • pkg/database/generated_models.go
    • Updated the GetAllNarFilesRow and NarFile Go structs to include the VerifiedAt field.
  • pkg/database/generated_querier.go
    • Updated the Querier interface to reflect the inclusion of verified_at in various SELECT statements.
    • Added the UpdateNarFileVerifiedAt method to the Querier interface.
  • pkg/database/generated_wrapper_mysql.go
    • Updated the MySQL database wrapper to handle the VerifiedAt field in NarFile and GetAllNarFilesRow conversions.
    • Implemented the UpdateNarFileVerifiedAt method for MySQL.
  • pkg/database/generated_wrapper_postgres.go
    • Updated the PostgreSQL database wrapper to handle the VerifiedAt field in NarFile and GetAllNarFilesRow conversions.
    • Implemented the UpdateNarFileVerifiedAt method for PostgreSQL.
  • pkg/database/generated_wrapper_sqlite.go
    • Updated the SQLite database wrapper to handle the VerifiedAt field in NarFile and GetAllNarFilesRow conversions.
    • Implemented the UpdateNarFileVerifiedAt method for SQLite.
  • pkg/database/mysqldb/models.go
    • Updated the NarFile struct to include the VerifiedAt field.
  • pkg/database/mysqldb/querier.go
    • Updated the Querier interface to include verified_at in SELECT statements and added UpdateNarFileVerifiedAt.
  • pkg/database/mysqldb/query.mysql.sql.go
    • Updated generated Go code for MySQL queries to include verified_at in SELECT statements.
    • Added generated Go code for the UpdateNarFileVerifiedAt query.
  • pkg/database/postgresdb/models.go
    • Updated the NarFile struct to include the VerifiedAt field.
  • pkg/database/postgresdb/querier.go
    • Updated the Querier interface to include verified_at in SELECT statements and added UpdateNarFileVerifiedAt.
  • pkg/database/postgresdb/query.postgres.sql.go
    • Updated generated Go code for PostgreSQL queries to include verified_at in SELECT statements.
    • Added generated Go code for the UpdateNarFileVerifiedAt query.
  • pkg/database/sqlitedb/models.go
    • Updated the NarFile struct to include the VerifiedAt field.
  • pkg/database/sqlitedb/querier.go
    • Updated the Querier interface to include verified_at in SELECT statements and added UpdateNarFileVerifiedAt.
  • pkg/database/sqlitedb/query.sqlite.sql.go
    • Updated generated Go code for SQLite queries to include verified_at in SELECT statements.
    • Added generated Go code for the UpdateNarFileVerifiedAt query.
  • pkg/ncps/fsck.go
    • Added a new cli.DurationFlag named --verified-since to the fsck command.
    • Modified collectFsckSuspects to accept and utilize the verifiedSince duration.
    • Introduced a skipped counter for progress logging in fsck.
    • Implemented shouldCheckNar helper function to determine if a NAR should be skipped based on verified_at and verifiedSince.
    • Added logic to update verified_at for successfully checked NAR files.
  • pkg/ncps/fsck_test.go
    • Imported the time package.
    • Added a new test suite testFsckVerifiedSince to validate the --verified-since flag's functionality.
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 Mar 1, 2026

Copy link
Copy Markdown

Related Documentation

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

kalbasit's Space

Cache and Storage Configuration Flags
View Suggested Changes
@@ -288,6 +288,19 @@
 ```
 
 **Note:** The `verified_at` timestamp is only updated when a NAR passes verification. Failed checks do not update the timestamp, ensuring problematic NARs will continue to be checked on subsequent runs.
+
+### Implementation Details
+
+**Database Schema:** A `verified_at` TIMESTAMP column has been added to the `nar_files` table. Database migrations are provided for SQLite, PostgreSQL, and MySQL to add this column to existing installations.
+
+**Update Mechanism:** When fsck successfully verifies a NAR file (whether non-chunked or CDC-chunked), it calls the `UpdateNarFileVerifiedAt` database function to set the `verified_at` timestamp to the current time. This update is skipped if the verification fails, ensuring that problematic files will be checked again on the next run.
+
+**Filtering Logic:** When `--verified-since` is specified, fsck uses the `shouldCheckNar` helper function to determine whether to verify each NAR file. The filtering query checks:
+- If `verified_at` IS NULL (never verified), the NAR is checked
+- If `verified_at < (NOW() - specified duration)`, the NAR is checked
+- Otherwise, the NAR is skipped
+
+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 |

[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 performance optimization for the fsck command by adding a verified_at timestamp to nar_files. This allows skipping recently verified NARs, which is a great improvement for large repositories. The implementation is well-rounded, covering database migrations for all supported backends, updating queries, and adding a new command-line flag with corresponding logic. The new test case for verified-since is also well-written and covers the main scenarios. My main concern is with the down migration for SQLite, which could lead to broken foreign key constraints.

Comment on lines +4 to +40
-- migrate:down
CREATE TABLE nar_files_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
hash TEXT NOT NULL,
compression TEXT NOT NULL DEFAULT '',
file_size INTEGER NOT NULL,
"query" TEXT NOT NULL DEFAULT '',
total_chunks BIGINT NOT NULL DEFAULT 0,
chunking_started_at TIMESTAMP NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,
updated_at TIMESTAMP,
last_accessed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE (hash, compression, "query")
);

INSERT INTO nar_files_new (
id, hash, compression, file_size, "query", total_chunks, chunking_started_at, created_at, updated_at, last_accessed_at
)
SELECT
id,
hash,
compression,
file_size,
"query",
total_chunks,
chunking_started_at,
created_at,
updated_at,
last_accessed_at
FROM nar_files;

PRAGMA foreign_keys = OFF;
DROP TABLE nar_files;
ALTER TABLE nar_files_new RENAME TO nar_files;
PRAGMA foreign_keys = ON;

CREATE INDEX idx_nar_files_last_accessed_at ON nar_files (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.

high

The down migration for SQLite is implemented by recreating the nar_files table without the verified_at column. While this is a standard approach for dropping a column in older SQLite versions, it has a significant side effect here. The nar_files table is referenced by foreign keys in narinfo_nar_files and nar_file_chunks. When nar_files is dropped (even with PRAGMA foreign_keys=OFF), these foreign key constraints are broken and are not automatically re-established when a new nar_files table is created.

This can lead to a loss of data integrity, as the relationships will no longer be enforced by the database for existing data.

To fix this, the down migration should also recreate the tables that reference nar_files (narinfo_nar_files and nar_file_chunks) after recreating nar_files. This would involve:

  1. Saving data from narinfo_nar_files and nar_file_chunks to temporary tables.
  2. Dropping narinfo_nar_files and nar_file_chunks.
  3. Performing the existing down migration for nar_files.
  4. Recreating narinfo_nar_files and nar_file_chunks with their foreign key constraints.
  5. Restoring data into the newly created narinfo_nar_files and nar_file_chunks.

Given the complexity, and since down migrations are not as common, an alternative is to accept this limitation but add a prominent comment in the migration file warning users about the consequences of running it.

References
  1. To maintain consistency, schema changes (like adding ON DELETE CASCADE) should be applied across all supported database backends (e.g., SQLite and PostgreSQL) in a coordinated manner, potentially through a new, separate migration. This comment highlights a specific challenge in SQLite migrations that needs careful handling to ensure data integrity, aligning with the need for coordinated and robust schema changes across backends.

@codecov

codecov Bot commented Mar 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 5.04%. Comparing base (e7719e1) to head (cc75b6a).
⚠️ Report is 1 commits behind head on release-0.9.

Additional details and impacted files
@@             Coverage Diff             @@
##           release-0.9   #1001   +/-   ##
===========================================
  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 9513b23 into release-0.9 Mar 1, 2026
13 checks passed
@kalbasit
kalbasit deleted the backport-998-to-release-0.9 branch March 1, 2026 06:33
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:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant