Repository navigation
refactor(cache): bulk-fetch chunks before insert - #1261
Conversation
|
Warning Review limit reached
Your plan includes 5 reviews of capacity. Refill in 1 minute and 13 seconds. Your organization has run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After more review capacity refills, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than trial, open-source, and free plans. In all cases, review capacity refills continuously over time. Please see our FAQ for further information. 📝 WalkthroughWalkthroughThe ChangesBatch Chunk Recording
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
Code Review
This pull request refactors the recordChunkBatch function in pkg/cache/cache.go to utilize bulk database operations for fetching and inserting chunks, which improves performance and avoids primary key sequence desynchronization. The reviewer suggested adding a validation step to ensure that all expected chunk IDs are retrieved after a bulk insert, preventing potential foreign key violations if any IDs are missing.
3d60e11 to
ece75d8
Compare
78c71ae to
a6560ed
Compare
|
This change is part of the following stack:
Change managed by git-spice. |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@pkg/cache/cache.go`:
- Around line 2475-2510: In recordChunkBatch, guard against missing chunk PKs in
idByHash before using them to create nar_file_chunks: after building idByHash
(and before creating bulk nar_file_chunks with tx.NarFileChunk.Create), check
for each batch entry (cm.Hash) that id, ok := idByHash[cm.Hash] is present; if
not, return a clear error (including the missing hash and context like
narFileID) instead of using zero and causing an FK violation. This change should
live in the recordChunkBatch flow that runs inside
Client.WithTransaction/withEntTransactionRetry and prevents silent insertion of
chunk_id=0 by failing fast (optionally you may log the missing hashes) so
callers can surface/retry appropriately.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ece75d8 to
4ccda55
Compare
After bulk-inserting new chunks with ON CONFLICT DO NOTHING and then re-fetching them by hash, guard against the narrow window where a chunk row could be absent (e.g. FK violation from a 0-ID link). If the SELECT returns fewer rows than expected, return a wrapped errChunkIDFetchMismatch error rather than silently building links with zero IDs. Addresses PR #1261 review comment (thread PRRT_kwDONV6tZs6EblBM). Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
d8d6ef9 to
742e736
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@pkg/cache/cache.go`:
- Line 150: Cache.recordChunkBatch can return the sentinel
errChunkIDFetchMismatch when the post-insert refetch count is wrong, but
withEntTransactionRetry currently only retries on deadlock/duplicate-key errors;
update withEntTransactionRetry to treat errChunkIDFetchMismatch as retryable by
checking errors.Is(err, errChunkIDFetchMismatch) (or equivalent) in its retry
condition so the transaction closure (used by Cache.recordChunkBatch) is retried
on this transient race; reference errChunkIDFetchMismatch,
withEntTransactionRetry, and Cache.recordChunkBatch when making the change.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
|
|
||
| errMissingChunkEdge = errors.New("nar_file_chunk is missing eager-loaded chunk edge") | ||
|
|
||
| errChunkIDFetchMismatch = errors.New("chunk count mismatch after bulk insert") |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== Sentinel definition and call sites =="
rg -n -C2 'errChunkIDFetchMismatch' pkg/cache/cache.go
echo
echo "== Current retry predicate =="
sed -n '5550,5558p' pkg/cache/cache.goRepository: kalbasit/ncps
Length of output: 991
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== Locate withEntTransactionRetry =="
rg -n "withEntTransactionRetry" -S pkg/cache/cache.go
echo
echo "== Inspect withEntTransactionRetry body (retry predicate) =="
# Print a wider window around the predicate we saw earlier
sed -n '5500,5595p' pkg/cache/cache.go
echo
echo "== Inspect mismatch sentinel raise site context =="
sed -n '2460,2535p' pkg/cache/cache.go
echo
echo "== Run golangci-lint run --fix (required) =="
golangci-lint run --fix ./...
echo
echo "== Run go test -race ./... (required) =="
go test -race ./...Repository: kalbasit/ncps
Length of output: 6268
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== cache.go import block =="
rg -n "^import \\(" -n pkg/cache/cache.go && true
# Print a small window after the import block start
start=$(rg -n "^import \\(" pkg/cache/cache.go | head -n1 | cut -d: -f1)
# show ~30 lines from that point
sed -n "$start,$((start+40))p" pkg/cache/cache.go
echo
echo "== Quick check: does go test also fail typecheck in same place? =="
go test -race ./... 2>&1 | head -n 40Repository: kalbasit/ncps
Length of output: 1443
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== Locate Cache.recordChunkBatch =="
rg -n "func \\(c \\*Cache\\) recordChunkBatch" -n pkg/cache/cache.go
echo
# show from definition start through the withEntTransactionRetry call area
# (use sed around the known bulk/link section near 2425-2530)
sed -n '2380,2485p' pkg/cache/cache.go
echo
# show the withEntTransactionRetry call wrapper line nearby
sed -n '2440,2520p' pkg/cache/cache.goRepository: kalbasit/ncps
Length of output: 6166
Make errChunkIDFetchMismatch retryable in withEntTransactionRetry
Cache.recordChunkBatch returns a wrapped errChunkIDFetchMismatch when the post-INSERT ... DO NOTHING refetch count doesn’t match expected IDs, but withEntTransactionRetry retries only deadlock and duplicate-key errors—so this transient race becomes a terminal failure instead of rerunning the transaction closure.
♻️ Proposed fix
diff --git a/pkg/cache/cache.go b/pkg/cache/cache.go
@@
- retryable := database.IsDeadlockError(err) || database.IsDuplicateKeyError(err)
+ retryable := database.IsDeadlockError(err) ||
+ database.IsDuplicateKeyError(err) ||
+ errors.Is(err, errChunkIDFetchMismatch)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| errChunkIDFetchMismatch = errors.New("chunk count mismatch after bulk insert") | |
| retryable := database.IsDeadlockError(err) || | |
| database.IsDuplicateKeyError(err) || | |
| errors.Is(err, errChunkIDFetchMismatch) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@pkg/cache/cache.go` at line 150, Cache.recordChunkBatch can return the
sentinel errChunkIDFetchMismatch when the post-insert refetch count is wrong,
but withEntTransactionRetry currently only retries on deadlock/duplicate-key
errors; update withEntTransactionRetry to treat errChunkIDFetchMismatch as
retryable by checking errors.Is(err, errChunkIDFetchMismatch) (or equivalent) in
its retry condition so the transaction closure (used by Cache.recordChunkBatch)
is retried on this transient race; reference errChunkIDFetchMismatch,
withEntTransactionRetry, and Cache.recordChunkBatch when making the change.
Replace the 2N SELECT+INSERT loop in recordChunkBatch with a 3-query bulk approach: 1. SELECT all chunk hashes present in this batch (one query). 2. Bulk-INSERT only genuinely absent hashes with DO NOTHING for the narrow race window between steps 1 and 2. 3. Re-SELECT newly inserted hashes to populate the id→hash map. 4. Bulk-INSERT nar_file_chunks links as before. This eliminates per-chunk sequence PK generation for pre-existing chunks entirely. The previous DO NOTHING + per-chunk SELECT pattern still advanced the auto-increment sequence for every INSERT attempt (even ones that resolved to DO NOTHING after PK generation), so a desynced sequence could still cause chunks_pkey violations for new chunks. With bulk-fetch first, pre-existing chunks are never INSERTed at all, and only truly new chunks go through INSERT. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
After bulk-inserting new chunks with ON CONFLICT DO NOTHING and then re-fetching them by hash, guard against the narrow window where a chunk row could be absent (e.g. FK violation from a 0-ID link). If the SELECT returns fewer rows than expected, return a wrapped errChunkIDFetchMismatch error rather than silently building links with zero IDs. Addresses PR #1261 review comment (thread PRRT_kwDONV6tZs6EblBM). Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
742e736 to
02ddc93
Compare
Summary
query before the per-chunk insert loop.
INSERT ... ON CONFLICT DO NOTHINGfor chunks that are already in the DB, avoiding unnecessary round
trips to the database.
Why
The per-chunk query-after-insert pattern introduced in the previous
commit works correctly but issues N×2 round trips per NAR. Bulk
pre-fetching reduces this to 1 read + (new chunks only) writes,
improving throughput for NARs with many chunks.
🤖 Generated with Claude Code