Skip to content

feat: implement progressive chunk streaming for CDC concurrent downloads - #743

Merged
kalbasit merged 2 commits into
mainfrom
02-04-feat_implement_progressive_chunk_streaming_for_cdc_concurrent_downloads
Feb 5, 2026
Merged

kalbasit merged 2 commits into
mainfrom
02-04-feat_implement_progressive_chunk_streaming_for_cdc_concurrent_downloads

Conversation

@kalbasit

@kalbasit kalbasit commented Feb 5, 2026

Copy link
Copy Markdown
Owner

This change fixes a race condition where multiple cache instances requesting
the same NAR file during CDC chunking would receive partial data because
HasNarInChunks() returned true as soon as any chunk existed.

The solution adds a total_chunks field to the nar_files table to track CDC
operation status (NULL=legacy data, 0=in-progress, >0=complete). The
HasNarInChunks function now only returns true when total_chunks > 0,
preventing premature reads.

The getNarFromChunks function has been rewritten to support two streaming
paths:

  • Fast path: Loads all chunk hashes at once when chunking is complete
  • Progressive path: Polls and streams chunks one-by-one as they appear
    during in-progress chunking operations (200ms polling interval, 30s
    per-chunk timeout)

This enables multiple instances to successfully stream chunks while another
instance is still performing CDC chunking, eliminating the partial data
issue. The CDC distributed test has been re-enabled and now passes with all
3 instances successfully retrieving the complete 12MB NAR file.

Database migrations have been added for all three engines (SQLite,
PostgreSQL, MySQL) to add the total_chunks column, and new SQL queries
support chunk-by-index retrieval and completion status updates.

Part of #322

@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 5, 2026

kalbasit commented Feb 5, 2026 •

Copy link
Copy Markdown
Owner Author

@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 significant enhancement to the Content-Defined Chunking (CDC) download process by enabling progressive streaming. Previously, concurrent requests for a NAR file undergoing CDC chunking could result in partial data being served due to a race condition. The core of this change involves a database schema modification to track the chunking status more precisely and a refactoring of the NAR retrieval logic to support both immediate and progressive streaming. This ensures that multiple clients can reliably access NAR files, even when they are still being processed, thereby improving the robustness and concurrency of the caching system.

Highlights

  • Progressive Chunk Streaming: Implemented a progressive streaming mechanism for Content-Defined Chunking (CDC) downloads, allowing multiple cache instances to stream a NAR file concurrently even while another instance is still actively chunking it. This prevents premature reads of partial data.
  • Database Schema Update: Added a new total_chunks column to the nar_files table across MySQL, PostgreSQL, and SQLite databases. This column tracks the CDC operation status: NULL for legacy data, 0 for in-progress chunking, and a positive integer for completed chunking (representing the total number of chunks).
  • Refined NAR File Status Logic: Updated the HasNarInChunks function to return true only when total_chunks > 0, accurately indicating that chunking is complete. A new HasNarFileRecord function was introduced to check for the existence of a NAR file record regardless of its chunking completion status, facilitating the progressive streaming path.
  • Enhanced getNarFromChunks Functionality: The getNarFromChunks function was rewritten to support two distinct streaming paths: a 'fast path' for completed chunking operations where all chunk hashes are loaded at once, and a 'progressive path' that polls for and streams chunks one-by-one with a 200ms interval and a 30s per-chunk timeout during in-progress chunking.
  • Distributed Test Re-enabled: The CDC distributed test, which previously highlighted a race condition, has been re-enabled and now passes successfully, confirming that all three instances can retrieve a complete 12MB NAR file without issues.
Changelog
  • db/migrations/mysql/20260205063659_add_total_chunks_to_nar_files.sql
    • Added a new migration to introduce the total_chunks INTEGER column to the nar_files table for MySQL.
  • db/migrations/postgres/20260205063658_add_total_chunks_to_nar_files.sql
    • Added a new migration to introduce the total_chunks INTEGER column to the nar_files table for PostgreSQL.
  • db/migrations/sqlite/20260205063651_add_total_chunks_to_nar_files.sql
    • Added a new migration to introduce the total_chunks INTEGER column to the nar_files table for SQLite.
  • db/query.mysql.sql
    • Updated GetNarFileByHashAndCompressionAndQuery and GetNarFileByID to select the new total_chunks column.
    • Modified CreateNarFile to include total_chunks in the insert statement.
    • Added new SQL queries: GetChunkByNarFileIDAndIndex for retrieving chunks by NAR file ID and index, and UpdateNarFileTotalChunks for updating the total_chunks value.
  • db/query.postgres.sql
    • Updated GetNarFileByHashAndCompressionAndQuery and GetNarFileByID to select the new total_chunks column.
    • Modified CreateNarFile to include total_chunks in the insert statement and return value.
    • Added new SQL queries: GetChunkByNarFileIDAndIndex for retrieving chunks by NAR file ID and index, and UpdateNarFileTotalChunks for updating the total_chunks value.
  • db/query.sqlite.sql
    • Updated GetNarFileByHashAndCompressionAndQuery and GetNarFileByID to select the new total_chunks column.
    • Modified CreateNarFile to include total_chunks in the insert statement and return value.
    • Added new SQL queries: GetChunkByNarFileIDAndIndex for retrieving chunks by NAR file ID and index, and UpdateNarFileTotalChunks for updating the total_chunks value.
  • db/schema/mysql.sql
    • Added total_chunks column definition to the nar_files table schema.
    • Updated the schema migration version to include the new migration.
  • db/schema/postgres.sql
    • Added total_chunks column definition to the nar_files table schema.
    • Updated the schema migration version to include the new migration.
  • db/schema/sqlite.sql
    • Added total_chunks column definition to the nar_files table schema.
    • Updated the schema migration version to include the new migration.
  • pkg/cache/cache.go
    • Modified GetNar to use HasNarFileRecord for initial checks, allowing progressive streaming to start earlier.
    • Updated storeNarWithCDC to initialize total_chunks to 0 (in-progress) and update it to the final chunk count upon completion.
    • Added benign error handling for io.ErrClosedPipe in serveNarFromStorageViaPipe to prevent unnecessary error logging when clients disconnect early.
    • Adjusted prePullNar to utilize HasNarFileRecord for determining if a NAR file record exists.
    • Refactored HasNarInChunks to check the total_chunks column for completion status (total_chunks > 0).
    • Introduced HasNarFileRecord function to check for the mere existence of a NAR file record, irrespective of chunking completion.
    • Rewrote getNarFromChunks to implement both a 'fast path' for fully chunked NARs and a 'progressive path' for in-progress chunking, using polling and timeouts.
    • Added streamCompleteChunks and streamProgressiveChunks helper functions to encapsulate the streaming logic for each path.
  • pkg/cache/cache_distributed_test.go
    • Added a new distributed test CDCProgressiveStreamingDuringChunking to validate the progressive streaming functionality.
    • Re-enabled the CDC_Enabled scenario in LargeNARConcurrentDownload and increased the request timeout to accommodate progressive streaming.
  • pkg/cache/cache_test.go
    • Added testHasNarFileRecord to verify the behavior of the new HasNarFileRecord function under different total_chunks states.
  • pkg/database/generated_models.go
    • Updated CreateNarFileParams and NarFile structs to include the TotalChunks field.
    • Added new parameter and row structs for GetChunkByNarFileIDAndIndex, GetLeastUsedNarFilesRow, GetNarFileByNarInfoIDRow, GetOrphanedNarFilesRow, and UpdateNarFileTotalChunksParams.
  • pkg/database/generated_querier.go
    • Updated method signatures for CreateNarFile, GetLeastUsedNarFiles, GetNarFileByHashAndCompressionAndQuery, GetNarFileByID, GetNarFileByNarInfoID, and GetOrphanedNarFiles to reflect the new total_chunks field and new return types.
    • Added new methods GetChunkByNarFileIDAndIndex and UpdateNarFileTotalChunks to the Querier interface.
  • pkg/database/generated_wrapper_mysql.go
    • Updated the MySQL database wrapper to handle the new total_chunks column in CreateNarFile and other NarFile related operations.
    • Implemented the new GetChunkByNarFileIDAndIndex and UpdateNarFileTotalChunks methods.
  • pkg/database/generated_wrapper_postgres.go
    • Updated the PostgreSQL database wrapper to handle the new total_chunks column in CreateNarFile and other NarFile related operations.
    • Implemented the new GetChunkByNarFileIDAndIndex and UpdateNarFileTotalChunks methods.
  • pkg/database/generated_wrapper_sqlite.go
    • Updated the SQLite database wrapper to handle the new total_chunks column in CreateNarFile and other NarFile related operations.
    • Implemented the new GetChunkByNarFileIDAndIndex and UpdateNarFileTotalChunks methods.
  • pkg/database/mysqldb/models.go
    • Added TotalChunks field to the NarFile struct.
  • pkg/database/mysqldb/querier.go
    • Updated method signatures for CreateNarFile, GetNarFileByHashAndCompressionAndQuery, and GetNarFileByID to include total_chunks.
    • Added new methods GetChunkByNarFileIDAndIndex and UpdateNarFileTotalChunks to the MySQL querier interface.
  • pkg/database/mysqldb/query.mysql.sql.go
    • Updated generated Go code for MySQL queries to reflect changes in CreateNarFile, GetNarFileByHashAndCompressionAndQuery, GetNarFileByID.
    • Added generated Go code for GetChunkByNarFileIDAndIndex and UpdateNarFileTotalChunks.
  • pkg/database/postgresdb/models.go
    • Added TotalChunks field to the NarFile struct.
  • pkg/database/postgresdb/querier.go
    • Updated method signatures for CreateNarFile, GetNarFileByHashAndCompressionAndQuery, and GetNarFileByID to include total_chunks.
    • Added new methods GetChunkByNarFileIDAndIndex and UpdateNarFileTotalChunks to the PostgreSQL querier interface.
  • pkg/database/postgresdb/query.postgres.sql.go
    • Updated generated Go code for PostgreSQL queries to reflect changes in CreateNarFile, GetNarFileByHashAndCompressionAndQuery, GetNarFileByID.
    • Added generated Go code for GetChunkByNarFileIDAndIndex and UpdateNarFileTotalChunks.
  • pkg/database/sqlitedb/models.go
    • Added TotalChunks field to the NarFile struct.
  • pkg/database/sqlitedb/querier.go
    • Updated method signatures for CreateNarFile, GetNarFileByHashAndCompressionAndQuery, and GetNarFileByID to include total_chunks.
    • Added new methods GetChunkByNarFileIDAndIndex and UpdateNarFileTotalChunks to the SQLite querier interface.
  • pkg/database/sqlitedb/query.sqlite.sql.go
    • Updated generated Go code for SQLite queries to reflect changes in CreateNarFile, GetNarFileByHashAndCompressionAndQuery, GetNarFileByID.
    • Added generated Go code for GetChunkByNarFileIDAndIndex and UpdateNarFileTotalChunks.
Activity
  • The pull request introduces a new feature to enable progressive chunk streaming for CDC concurrent downloads.
  • It addresses a race condition where multiple cache instances could receive partial data during CDC chunking.
  • Database schema changes were implemented across MySQL, PostgreSQL, and SQLite to add a total_chunks column to the nar_files table.
  • Existing database queries were updated, and new queries were added to support the new total_chunks field and chunk-by-index retrieval.
  • Core cache logic in pkg/cache/cache.go was significantly refactored to implement the progressive streaming and update NAR file status handling.
  • New test cases were added (CDCProgressiveStreamingDuringChunking, testHasNarFileRecord), and an existing distributed test was re-enabled and now passes, validating the fix and new 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. ↩

@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 is an excellent pull request that addresses a tricky race condition in concurrent downloads with a robust and well-designed solution. The introduction of the total_chunks field to manage the state of CDC operations is a great approach. The new progressive streaming logic in getNarFromChunks is well-implemented, with thoughtful handling of polling, timeouts, and fast/slow paths. It's particularly impressive that this is backed by a re-enabled distributed test that now passes, which gives high confidence in the fix. The database migrations and query updates are clean and consistent across all supported engines. I have a couple of minor suggestions for code cleanup, but overall, this is a high-quality contribution.

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
@kalbasit
kalbasit changed the base branch from 02-04-refactor_improve_test_code_quality_in_distributed_cache_tests to graphite-base/743 February 5, 2026 08:31
@kalbasit
kalbasit force-pushed the 02-04-feat_implement_progressive_chunk_streaming_for_cdc_concurrent_downloads branch from e9b9e0b to 8b1ce64 Compare February 5, 2026 08:31
@kalbasit
kalbasit changed the base branch from graphite-base/743 to 02-05-fix_handle_sql.null_types_correctly_in_database_wrapper_generator February 5, 2026 08:31
@kalbasit
kalbasit force-pushed the 02-04-feat_implement_progressive_chunk_streaming_for_cdc_concurrent_downloads branch from 8b1ce64 to e423cb3 Compare February 5, 2026 08:50
@kalbasit
kalbasit force-pushed the 02-05-fix_handle_sql.null_types_correctly_in_database_wrapper_generator branch 2 times, most recently from efed176 to 56ab810 Compare February 5, 2026 09:06
@kalbasit
kalbasit force-pushed the 02-04-feat_implement_progressive_chunk_streaming_for_cdc_concurrent_downloads branch 3 times, most recently from ba1e37b to 3581de3 Compare February 5, 2026 09:20
@kalbasit
kalbasit changed the base branch from 02-05-fix_handle_sql.null_types_correctly_in_database_wrapper_generator to graphite-base/743 February 5, 2026 09:48
@kalbasit
kalbasit force-pushed the 02-04-feat_implement_progressive_chunk_streaming_for_cdc_concurrent_downloads branch from 3581de3 to ca05c7e Compare February 5, 2026 09:56
@kalbasit
kalbasit changed the base branch from graphite-base/743 to 02-05-fix_handle_sql.null_types_correctly_in_database_wrapper_generator February 5, 2026 09:56
@kalbasit

kalbasit commented Feb 5, 2026

Copy link
Copy Markdown
Owner Author

/gemini review

Base automatically changed from 02-05-fix_handle_sql.null_types_correctly_in_database_wrapper_generator to main February 5, 2026 10:01

@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 total_chunks column to the nar_files table across all database types to enable progressive streaming of NAR files during content-defined chunking (CDC). Database schemas, migrations, and generated query code were updated to support this new column and associated operations, including GetChunkByNarFileIDAndIndex and UpdateNarFileTotalChunks. The application logic was refactored to initialize total_chunks to 0 when a NAR file record is created and update it upon chunking completion. A new HasNarFileRecord function was added to check for a NAR file's existence regardless of chunking status, allowing concurrent requests to start streaming progressively via streamProgressiveChunks while another instance is still chunking. The HasNarInChunks function was updated to specifically indicate chunking completion. Tests were added and modified to verify this progressive streaming behavior and the new HasNarFileRecord functionality. Review comments suggest optimizing the HasNarFileRecord function by removing unnecessary transaction management for read-only queries and removing an unused narURL parameter from the streamProgressiveChunks function signature and its call site.

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
This change fixes a race condition where multiple cache instances requesting
the same NAR file during CDC chunking would receive partial data because
HasNarInChunks() returned true as soon as any chunk existed.

The solution adds a total_chunks field to the nar_files table to track CDC
operation status (NULL=legacy data, 0=in-progress, >0=complete). The
HasNarInChunks function now only returns true when total_chunks > 0,
preventing premature reads.

The getNarFromChunks function has been rewritten to support two streaming
paths:
- Fast path: Loads all chunk hashes at once when chunking is complete
- Progressive path: Polls and streams chunks one-by-one as they appear
  during in-progress chunking operations (200ms polling interval, 30s
  per-chunk timeout)

This enables multiple instances to successfully stream chunks while another
instance is still performing CDC chunking, eliminating the partial data
issue. The CDC distributed test has been re-enabled and now passes with all
3 instances successfully retrieving the complete 12MB NAR file.

Database migrations have been added for all three engines (SQLite,
PostgreSQL, MySQL) to add the total_chunks column, and new SQL queries
support chunk-by-index retrieval and completion status updates.

Part of #322
@kalbasit
kalbasit force-pushed the 02-04-feat_implement_progressive_chunk_streaming_for_cdc_concurrent_downloads branch from ca05c7e to 104111f Compare February 5, 2026 10:11
@kalbasit

kalbasit commented Feb 5, 2026

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 robust solution for a race condition in concurrent CDC chunk downloads by adding a total_chunks field to track chunking status. The implementation of progressive chunk streaming is a significant improvement, allowing clients to stream NARs while they are still being chunked. The database migrations and new SQL queries are well-integrated, and the addition of comprehensive distributed tests validates the fix effectively. My review includes a couple of suggestions for performance optimization and code clarity, including documenting an accepted risk related to integer overflow as per repository guidelines.

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/cache/cache.go Resolved
@codecov

codecov Bot commented Feb 5, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #743   +/-   ##
=======================================
  Coverage   85.41%   85.41%           
=======================================
  Files           2        2           
  Lines         480      480           
=======================================
  Hits          410      410           
  Misses         65       65           
  Partials        5        5           

☔ 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 enabled auto-merge (squash) February 5, 2026 10:24
@kalbasit
kalbasit merged commit 7ec4318 into main Feb 5, 2026
14 checks passed
@kalbasit
kalbasit deleted the 02-04-feat_implement_progressive_chunk_streaming_for_cdc_concurrent_downloads branch February 5, 2026 10:36
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