Repository navigation
Conversation
The non-lazy CDC path was slow because the CDC chunker used fileAvailableReader which blocks on a condition variable waiting for decompression to signal each write. This created a sequential dependency: decompression writes bytes -> CDC reads bytes. Changes: - Add directFileReader that reads directly from the growing file without blocking on condition variable. The OS handles blocking when reading past EOF, enabling true pipelining between decompression (writing to file) and CDC chunking. - Reduce batch delays: cdcFirstBatchDelay 100ms -> 10ms, cdcSubsequentBatchDelay 500ms -> 50ms for faster chunk recording.
|
This change is part of the following stack: Change managed by git-spice. |
Summary of ChangesHello, 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 significantly enhances the performance of the non-lazy Change Data Capture (CDC) download process by addressing a critical sequential dependency. By introducing a new file reading mechanism that allows the operating system to manage read blocking, it enables parallel execution of decompression and CDC chunking. Additionally, the adjustments to batch processing delays contribute to faster data ingestion and improved system responsiveness. 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
|
|
Related Documentation 1 document(s) may need updating based on files changed in this PR: kalbasit's Space NAR File Download and StreamingView Suggested Changes@@ -93,8 +93,8 @@
The download and CDC chunking processes work concurrently with two goroutines:
1. **Download goroutine**: The HTTP response body is piped through a decompressor (`nar.DecompressReader`), and the decompressed output is written to the temp file at `assetPath` using `streamReaderToFile`. This happens inline within the download goroutine.
-2. **CDC goroutine**: Starts immediately and reads from `assetPath` using a `fileAvailableReader`, which blocks until bytes become available. The goroutine chunks the data concurrently and creates the `nar_file` database record within milliseconds.
-3. Multiple concurrent clients requesting the uncompressed version share the same decompressed stream via `fileAvailableReader`, which blocks until bytes become available in `assetPath`.
+2. **CDC goroutine**: Starts immediately and reads from `assetPath` using a `directFileReader`, which reads directly from the growing file without blocking on a condition variable. The goroutine chunks the data concurrently and creates the `nar_file` database record within milliseconds. The `directFileReader` lets the OS handle blocking when reading past EOF, enabling true pipelining between decompression (writing to file) and CDC chunking (reading from file).
+3. Multiple concurrent clients requesting the uncompressed version share the same decompressed stream via `fileAvailableReader`, which blocks on a condition variable until bytes become available in `assetPath`.
4. Clients begin receiving uncompressed data as soon as the decompressor produces bytes, without waiting for the full download to complete.
This approach prevents the excessive memory usage and resource contention that would occur if multiple clients simultaneously attempted to decompress the same large NAR file. By eliminating the compressed temp file and using an `io.Pipe`, the system reduces disk I/O—only the decompressed data is written to disk, not the compressed data. The concurrent CDC chunking ensures that the database record with `chunking_started_at` is visible to other HA instances immediately, rather than waiting for full decompression to complete first. The single-decompression mechanism significantly reduces memory pressure and disk usage under concurrent load and improves system reliability for CDC-enabled deployments.
@@ -301,7 +301,15 @@
#### Concurrent CDC Chunking (Lazy Chunking Disabled)
-When lazy chunking is disabled, the chunking process runs concurrently with decompression during download. As soon as the download starts, a CDC goroutine begins reading from the temporary file using a `fileAvailableReader` that blocks until bytes become available (written by the decompression stream). This concurrent execution ensures the `nar_file` database record with `chunking_started_at` is created within milliseconds of download start, allowing other high-availability (HA) instances to immediately detect the active chunking operation instead of polling for up to 30 seconds. The HTTP response completes as soon as the download finishes, without waiting for CDC chunking to complete. This concurrent design significantly reduces TTFB in HA deployments by approximately 30 seconds for large compressed NARs.
+When lazy chunking is disabled, the chunking process runs concurrently with decompression during download. As soon as the download starts, a CDC goroutine begins reading from the temporary file using a `directFileReader`, which reads directly from the growing file without blocking on a condition variable. Unlike the previous `fileAvailableReader` approach that blocked on a condition variable waiting for decompression to signal each write, the `directFileReader` lets the OS handle blocking when reading past EOF. This enables true pipelining between decompression (writing to file) and CDC chunking (reading from file), eliminating the sequential dependency that made the non-lazy CDC path slow.
+
+This concurrent execution ensures the `nar_file` database record with `chunking_started_at` is created within milliseconds of download start, allowing other high-availability (HA) instances to immediately detect the active chunking operation instead of polling for up to 30 seconds. The HTTP response completes as soon as the download finishes, without waiting for CDC chunking to complete.
+
+Performance improvements include:
+- **Reduced batch delays**: The `cdcFirstBatchDelay` has been reduced from 100ms to 10ms, and `cdcSubsequentBatchDelay` from 500ms to 50ms, enabling faster chunk recording and batch processing.
+- **Eliminated sequential blocking**: The `directFileReader` eliminates the sequential blocking that occurred with `fileAvailableReader`, where CDC chunking had to wait for explicit signals from the decompression goroutine.
+
+This concurrent design with pipelined processing significantly reduces TTFB in HA deployments by approximately 30 seconds for large compressed NARs.
For CDC-enabled first pulls where no local download is active, the system optimizes TTFB by preferring the original compressed NAR URL from upstream (e.g., xz) rather than requesting an uncompressed version. When a client requests `compression=none`, the server looks up the narinfo hash in the database and fetches the narinfo from upstream to find the original compressed URL. The `lookupPreferredUpstreamURL` function returns both the preferred compressed `*nar.URL` and the `*narinfo.NarInfo`, which is passed through to `pullNarIntoStore` for use in the single-decompression flow. The compressed file is downloaded and decompressed once using the single-decompression mechanism, with the decompressed data written to a temporary file that all concurrent clients share. This approach reduces TTFB significantly because upstream serves pre-compressed files directly from disk rather than decompressing on-the-fly [source](https://github.com/kalbasit/ncps/blob/b7653d4303670bb88fd34b8bf82ed3aade09885d/pkg/cache/cache.go#L94-L677).
@@ -358,7 +366,7 @@
CacheServer->>CacheServer: Decompress inline in download goroutine
CacheServer->>TempFile: Write decompressed data to temp file
par Concurrent Operations
- CDCGoroutine->>TempFile: Read from temp file (blocks until available)
+ CDCGoroutine->>TempFile: Read from temp file (directFileReader)
CDCGoroutine->>CDCGoroutine: Chunk data and store in DB
and
CacheServer->>Client: Stream decompressed data
@@ -367,9 +375,10 @@
Upstream-->>CacheServer: Next compressed chunk via pipe
CacheServer->>CacheServer: Decompress chunk
CacheServer->>TempFile: Write decompressed chunk
- CDCGoroutine->>TempFile: Read and chunk concurrently
+ CDCGoroutine->>TempFile: Read and chunk concurrently (pipelined)
CacheServer->>Client: Stream chunk
end
+ Note over CDCGoroutine: directFileReader enables pipelining without condition variable
Note over CDCGoroutine: Creates nar_file DB record within milliseconds
Note over CacheServer,Client: HTTP response completes when download finishes
Note over CDCGoroutine: Continues chunking in backgroundNote: You must be authenticated to accept/decline updates. |
There was a problem hiding this comment.
Code Review
This pull request improves the performance of the non-lazy CDC download path by replacing the fileAvailableReader, which uses a condition variable, with a new directFileReader that polls a growing file. This change aims to create a better pipeline between decompression and CDC chunking. The PR also reduces batch delays for faster chunk recording. My review focuses on the implementation of the new directFileReader. I've identified a potential infinite loop and an unused field.
| func (r *directFileReader) Read(p []byte) (int, error) { | ||
| for { | ||
| // Try to read directly from the file | ||
| n, readErr := r.f.ReadAt(p, r.offset) | ||
|
|
||
| if n > 0 { | ||
| r.offset += int64(n) | ||
|
|
||
| return n, readErr | ||
| } | ||
|
|
||
| // No bytes read - check why | ||
| r.ds.mu.Lock() | ||
| finalSize := r.ds.finalSize | ||
| downloadErr := r.ds.downloadError | ||
| r.ds.mu.Unlock() | ||
|
|
||
| // Check for download error | ||
| if downloadErr != nil { | ||
| return 0, downloadErr | ||
| } | ||
|
|
||
| // Check if download is complete | ||
| if finalSize > 0 && r.offset >= finalSize { | ||
| return 0, io.EOF | ||
| } | ||
|
|
||
| // Download is still in progress but no bytes available yet | ||
| // Sleep briefly to avoid busy looping, then retry | ||
| // This is better than blocking on a condition variable because | ||
| // it allows the decompressor to write at its own pace | ||
| time.Sleep(10 * time.Millisecond) | ||
| } | ||
| } |
There was a problem hiding this comment.
The Read method has a couple of areas for improvement:
- Unhandled Errors: If
r.f.ReadAtreturnsn=0and an error other thanio.EOF(e.g.,os.ErrClosed), the error is ignored. This can lead to an infinite loop where the code continuously retries a failingReadAtcall. You should check for and return unexpected errors. - Magic Number: The sleep duration
10 * time.Millisecondis a magic number. It's better to define this as a constant (e.g.,directFileReaderPollInterval) for readability and maintainability. You could add this to theconstblock at the top of the file, or define it locally within the function as shown in the suggestion.
The suggestion below addresses both points.
func (r *directFileReader) Read(p []byte) (int, error) {
const directFileReaderPollInterval = 10 * time.Millisecond
for {
// Try to read directly from the file
n, readErr := r.f.ReadAt(p, r.offset)
if n > 0 {
r.offset += int64(n)
return n, readErr
}
// If we read no bytes, but there was an error other than EOF, return it.
if readErr != nil && readErr != io.EOF {
return 0, readErr
}
// No bytes read - check why
r.ds.mu.Lock()
finalSize := r.ds.finalSize
downloadErr := r.ds.downloadError
r.ds.mu.Unlock()
// Check for download error
if downloadErr != nil {
return 0, downloadErr
}
// Check if download is complete
if finalSize > 0 && r.offset >= finalSize {
return 0, io.EOF
}
// Download is still in progress but no bytes available yet
// Sleep briefly to avoid busy looping, then retry
// This is better than blocking on a condition variable because
// it allows the decompressor to write at its own pace
time.Sleep(directFileReaderPollInterval)
}
}| type directFileReader struct { | ||
| f *os.File | ||
| ds *downloadState | ||
| offset int64 | ||
| readBufSize int | ||
| } | ||
|
|
||
| // newDirectFileReader creates a reader that reads directly from the growing file. | ||
| func newDirectFileReader(f *os.File, ds *downloadState) *directFileReader { | ||
| return &directFileReader{ | ||
| f: f, | ||
| ds: ds, | ||
| offset: 0, | ||
| readBufSize: 64 * 1024, // 64KB read buffer for efficient chunking | ||
| } | ||
| } |
There was a problem hiding this comment.
The field readBufSize is initialized in newDirectFileReader but it's never used in the Read method or anywhere else in directFileReader. This field should be removed to avoid confusion and dead code.
type directFileReader struct {
f *os.File
ds *downloadState
offset int64
}
// newDirectFileReader creates a reader that reads directly from the growing file.
func newDirectFileReader(f *os.File, ds *downloadState) *directFileReader {
return &directFileReader{
f: f,
ds: ds,
offset: 0,
}
}
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1100 +/- ##
=====================================
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:
|
|
fixed in #1102 instead... |
The non-lazy CDC path was slow because the CDC chunker used
fileAvailableReader which blocks on a condition variable waiting for
decompression to signal each write. This created a sequential
dependency: decompression writes bytes -> CDC reads bytes.
Changes:
blocking on condition variable. The OS handles blocking when reading
past EOF, enabling true pipelining between decompression (writing to
file) and CDC chunking.
cdcSubsequentBatchDelay 500ms -> 50ms for faster chunk recording.