Skip to content

fix: use DO NOTHING for chunk inserts, add 25P02 recovery - #1259

Merged
kalbasit merged 2 commits into
mainfrom
user/wnasreddine/fix-chunk-do-nothing
May 25, 2026
Merged

kalbasit merged 2 commits into
mainfrom
user/wnasreddine/fix-chunk-do-nothing

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

Summary

  • Replace per-chunk UpsertOne(...).Update(...) with
    Create().OnConflictColumns(hash).Ignore().Exec() so that a
    duplicate-hash conflict leaves the transaction alive instead of
    aborting it with SQLSTATE 25P02.
  • After each INSERT, query the chunk ID by hash for the
    nar_file_chunks link — DO NOTHING returns no rows so an
    explicit SELECT is required.
  • Add database.IsAbortedTransactionError (SQLSTATE 25P02 detector)
    and a best-effort bare ROLLBACK in WithTransaction to recover
    connections that entered the aborted state before this fix was
    deployed.
  • Regression coverage via three new testRecordChunkBatch_* subtests.

Why

A duplicate chunk hash caused the DB engine to abort the whole
transaction. Every subsequent statement on that connection failed
with "current transaction is aborted, commands ignored until end of
transaction block", which surfaced as HTTP 500 to Nix clients.

🤖 Generated with Claude Code

recordChunkBatch used ON CONFLICT(hash) DO UPDATE SET updated_at which
fails with a chunks_pkey violation when the PostgreSQL sequence is
desynced: the INSERT hits the auto-increment PK conflict before the
hash conflict clause can fire. After 5 retries the error propagates and
leaves a connection in SQLSTATE 25P02 (in_failed_sql_transaction),
causing a subsequent narinfo query to return HTTP 500.

Fix 1 — recordChunkBatch: replace the upsert with DO NOTHING + a
separate SELECT WHERE hash = ... to retrieve the chunk ID. Chunks are
content-addressed immutable blobs; an existing row never needs updating.
DO NOTHING skips the PK path entirely when the row pre-exists.

Fix 2 — WithTransaction: add IsAbortedTransactionError (25P02) and
issue a best-effort ROLLBACK via the raw pool after any transaction
failure carrying that state, ensuring the connection is clean before
it is returned for reuse.

Three regression tests cover: new chunk, pre-existing chunk, and
duplicate hash within the same batch.
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. bug Something isn't working go Pull requests that update go code labels 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 6 minutes and 3 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: 0dff1011-3bc0-49c5-a51d-1f97063f23c4

📥 Commits

Reviewing files that changed from the base of the PR and between eb7a95c and 5aabdf8.

📒 Files selected for processing (6)
  • openspec/changes/archive/2026-05-24-fix-postgres-aborted-transaction-500/.openspec.yaml
  • openspec/changes/archive/2026-05-24-fix-postgres-aborted-transaction-500/design.md
  • openspec/changes/archive/2026-05-24-fix-postgres-aborted-transaction-500/proposal.md
  • openspec/changes/archive/2026-05-24-fix-postgres-aborted-transaction-500/specs/cdc-chunking/spec.md
  • openspec/changes/archive/2026-05-24-fix-postgres-aborted-transaction-500/tasks.md
  • openspec/specs/cdc-chunking/spec.md
📝 Walkthrough

Walkthrough

Chunk record insertion logic switches from upsert-with-touch to insert-or-ignore-then-query, PostgreSQL aborted-transaction errors are classified and trigger explicit connection cleanup, and chunk batch recording behavior is tested across new, existing, and duplicate-hash scenarios.

Changes

CDC Chunking and Transaction Resilience

Layer / File(s) Summary
Aborted Transaction Error Detection
pkg/database/errors.go
New exported IsAbortedTransactionError helper detects PostgreSQL SQLSTATE 25P02 via pgconn.PgError unwrapping or fallback string match for "current transaction is aborted".
Transaction Cleanup on Abort
pkg/database/client.go
WithTransaction now performs best-effort explicit ROLLBACK on the underlying sql.DB after detecting an aborted-transaction error, clearing pooled connections before reuse.
Chunk Batch Persistence Refactoring
pkg/cache/cache.go
recordChunkBatch replaces upsert-with-touch behavior using insert with OnConflictColumns(entchunk.FieldHash).Ignore() followed by hash-based query to fetch chunk ID for bulk junction record creation.
Chunk Batch Recording Tests
pkg/cache/cache_internal_test.go
Backend-parameterized TestRecordChunkBatch with three subtests: (1) new chunk insertion creates single chunk row and correct nar_file_chunks link with ChunkIndex: 0, (2) pre-existing chunk reuse avoids duplication and links to original chunk ID, (3) duplicate hashes in one batch create single chunk row with multiple junction links at distinct indices.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • kalbasit/ncps#1205: Both PRs modify recordChunkBatch CDC logic for chunk insertion and nar_file_chunks junction handling; this PR refactors upsert-to-insert-or-ignore-then-query while the related PR introduces the Ent-based conflict handling.

Suggested labels

go, size:M

Poem

🐰 Hopping through transactions with care,
Chunks now insert without a touch to spare,
When connections abort mid-flight,
We roll them back and set things right,
Tests dance through every batch case with flair!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically summarizes the main changes: replacing the chunk insert logic with DO NOTHING and adding SQLSTATE 25P02 recovery.
Description check ✅ Passed The description provides relevant context directly related to the changeset, explaining both the technical changes and the rationale for them.
Docstring Coverage ✅ Passed Docstring coverage is 85.71% which is sufficient. The required threshold is 80.00%.
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.

@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/database/client.go`:
- Around line 150-152: The best-effort ROLLBACK call currently uses
context.Background() and can hang; when handling IsAbortedTransactionError(err)
replace the unbounded ExecContext call with one using a short
context.WithTimeout (e.g., few seconds), call c.sdb.ExecContext with that ctx,
and defer cancel() so the cleanup is bounded; update the branch around
IsAbortedTransactionError to create the timeout context, execute ROLLBACK with
that context, and ignore/handle the returned error as before.
🪄 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: 6703dcf2-f3c3-4f4a-b43e-0c351fedc943

📥 Commits

Reviewing files that changed from the base of the PR and between 77a1484 and eb7a95c.

📒 Files selected for processing (4)
  • pkg/cache/cache.go
  • pkg/cache/cache_internal_test.go
  • pkg/database/client.go
  • pkg/database/errors.go

Comment thread pkg/database/client.go Resolved
Archive the completed change and sync the two new requirements into
the canonical CDC chunking spec:

- CDC chunk insert MUST use ON CONFLICT DO NOTHING (not upsert),
  followed by SELECT to retrieve the chunk ID for the link table.
- Transaction failure MUST NOT leave PostgreSQL connections in the
  aborted state (25P02); an explicit ROLLBACK must be issued before
  returning the connection to the pool.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@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

@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 modifies the chunk recording logic to use an ignore-on-conflict strategy followed by a separate query to retrieve IDs, which prevents primary key sequence desynchronization. It also adds a mechanism to handle aborted PostgreSQL transactions and introduces comprehensive tests for chunk batch recording across SQLite, PostgreSQL, and MySQL. Feedback identifies a performance regression in the chunk recording loop, suggesting that the per-chunk database round-trips be optimized into bulk operations. Additionally, the effectiveness of issuing a manual rollback on the connection pool was questioned, as it may not target the specific failed connection and could be better handled via driver-level settings.

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/database/client.go Resolved
@kalbasit
kalbasit merged commit ae88bf8 into main May 25, 2026
23 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/fix-chunk-do-nothing branch May 25, 2026 01:02
@codecov

codecov Bot commented May 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 0.00%. Comparing base (77a1484) to head (5aabdf8).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@     Coverage Diff      @@
##   main   #1259   +/-   ##
============================
============================

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code merge-stack size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant