Skip to content

refactor(cache): bulk-fetch chunks before insert - #1261

Merged
kalbasit merged 2 commits into
mainfrom
user/wnasreddine/fix-bulk-fetch-chunks
May 25, 2026
Merged

kalbasit merged 2 commits into
mainfrom
user/wnasreddine/fix-bulk-fetch-chunks

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

Summary

  • Pre-fetch all existing chunks for the current NAR in a single
    query before the per-chunk insert loop.
  • Use the fetched map to skip INSERT ... ON CONFLICT DO NOTHING
    for 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

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label May 25, 2026
@coderabbitai

coderabbitai Bot commented May 25, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@kalbasit, we couldn't start this review because you've used your available PR reviews for now.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8f582c8c-e327-49ed-bbf9-89ea27d3eac8

📥 Commits

Reviewing files that changed from the base of the PR and between d8d6ef9 and 02ddc93.

📒 Files selected for processing (1)
  • pkg/cache/cache.go
📝 Walkthrough

Walkthrough

The Cache.recordChunkBatch method is refactored to batch CDC chunk recording: it deduplicates hashes, preloads existing chunk IDs, bulk-inserts missing chunks with conflict-ignore, re-fetches to complete the hash→ID map (error on mismatch), and bulk-creates idempotent nar_file_chunks links.

Changes

Batch Chunk Recording

Layer / File(s) Summary
Sentinel error declaration
pkg/cache/cache.go
Adds errChunkIDFetchMismatch, a sentinel error returned when post-insert chunk-ID re-fetch returns an unexpected count.
Batch chunk recording with deduplication and conflict handling
pkg/cache/cache.go
Deduplicates incoming chunk hashes; bulk-selects existing chunk rows by hash to build a hash→ID map; bulk-inserts missing chunk rows with ON CONFLICT(hash) DO NOTHING; re-fetches inserted/race-won chunks and errors on count mismatch; bulk-creates nar_file_chunks links using resolved IDs with ON CONFLICT(nar_file_id, chunk_index) DO NOTHING.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • kalbasit/ncps#1205: Modifies pkg/cache/cache.go's recordChunkBatch to perform batch chunk/nar_file_chunks persistence, overlapping directly with this PR's changes.

Suggested labels

merge-stack

Poem

🐰 I hop through hashes, one by one no more,
I group and fetch what came before,
Insert the rest with a gentle nudge,
Re-query IDs that fate might judge,
Then link them all — bulk, tidy, and sure.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'refactor(cache): bulk-fetch chunks before insert' directly describes the main optimization: moving from per-chunk queries to bulk pre-fetching chunks, which is the primary change in the changeset.
Description check ✅ Passed The description clearly relates to the changeset, explaining the bulk pre-fetch optimization, the motivation (reducing 2×N round trips to 1 read + selective writes), and aligns with the summarized changes to recordChunkBatch.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

@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 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.

Comment thread pkg/cache/cache.go Resolved
@dosubot dosubot Bot added the go Pull requests that update go code label May 25, 2026
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-remove-25p02-rollback branch from 3d60e11 to ece75d8 Compare May 25, 2026 00:25
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-bulk-fetch-chunks branch from 78c71ae to a6560ed Compare May 25, 2026 00:25

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ddc12d7e-90a7-4687-8255-4987ab638ee6

📥 Commits

Reviewing files that changed from the base of the PR and between 3d60e11 and 78c71ae.

📒 Files selected for processing (1)
  • pkg/cache/cache.go

Comment thread pkg/cache/cache.go Resolved
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-remove-25p02-rollback branch from ece75d8 to 4ccda55 Compare May 25, 2026 01:02
kalbasit added a commit that referenced this pull request May 25, 2026
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]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-bulk-fetch-chunks branch from d8d6ef9 to 742e736 Compare May 25, 2026 01:02

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1764c61f-f8c0-4dde-97d2-0160529fe2ab

📥 Commits

Reviewing files that changed from the base of the PR and between 78c71ae and d8d6ef9.

📒 Files selected for processing (1)
  • pkg/cache/cache.go

Comment thread pkg/cache/cache.go

errMissingChunkEdge = errors.New("nar_file_chunk is missing eager-loaded chunk edge")

errChunkIDFetchMismatch = errors.New("chunk count mismatch after bulk insert")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 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.go

Repository: 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 40

Repository: 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.go

Repository: 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.

Suggested change
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.

Base automatically changed from user/wnasreddine/fix-remove-25p02-rollback to main May 25, 2026 01:18
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels May 25, 2026
kalbasit and others added 2 commits May 25, 2026 01:18
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]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-bulk-fetch-chunks branch from 742e736 to 02ddc93 Compare May 25, 2026 01:18
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 25, 2026
@kalbasit
kalbasit enabled auto-merge (squash) May 25, 2026 01:18
@kalbasit
kalbasit merged commit d6acdb0 into main May 25, 2026
21 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/fix-bulk-fetch-chunks branch May 25, 2026 01:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go Pull requests that update go code merge-stack size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant