Repository navigation
fix(migrations): reliably sync identity sequences on existing DBs - #1258
Conversation
|
This change is part of the following stack:
Change managed by git-spice. |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthrough
ChangesChunk Recording and Transaction Robustness
Sequence Diagram(s)sequenceDiagram
participant Caller as Caller
participant Cache as Cache.recordChunkBatch
participant DB as Database
Caller->>Cache: submit chunk batch (hashes + indices)
Cache->>DB: SELECT chunks WHERE hash IN (batchHashes)
DB-->>Cache: existing chunk rows
Cache->>DB: INSERT missing chunks ON CONFLICT(hash) DO NOTHING
DB-->>Cache: insert result (races ignored)
Cache->>DB: SELECT chunks WHERE hash IN (batchHashes)
DB-->>Cache: chunk rows with IDs
Cache->>DB: INSERT INTO nar_file_chunks ON CONFLICT(nar_file_id, chunk_index) DO NOTHING
DB-->>Cache: confirmation
Cache-->>Caller: success (mapped chunk IDs)
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.
Actionable comments posted: 2
🤖 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_internal_test.go`:
- Around line 2262-2431: The new tests (TestRecordChunkBatch and helpers
testRecordChunkBatchNewChunk, testRecordChunkBatchPreExistingChunk,
testRecordChunkBatchDuplicateHashInBatch) are in the internal package; change
the test file to use the external test package by updating its package
declaration to "package cache_test" (or split into a new *_test.go file with
package cache_test), then import the cache package under test and adjust any
unexported references accordingly (ensure uses of types/functions from the cache
package are via the exported API), run `go test` to verify and fix any
compilation breaks caused by unexported identifiers.
In `@pkg/database/client.go`:
- Around line 143-152: The current pool-level rollback uses c.sdb.ExecContext
which can run on a different physical connection; bind the cleanup to the same
backend session that produced the aborted tx. Refactor transaction creation to
obtain a dedicated *sql.Conn (via c.sdb.Conn(ctx)) and call conn.BeginTx to
produce the *sql.Tx; on IsAbortedTransactionError(err) call
conn.ExecContext(context.Background(), "ROLLBACK") (or use
conn.Raw/driver-specific facility if you need lower-level access) and then
conn.Close to ensure the exact connection/session is cleaned up rather than
issuing ROLLBACK through c.sdb.ExecContext.
🪄 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: a1ad11f2-99cf-4037-bce4-8b4f3b0fa340
📒 Files selected for processing (4)
pkg/cache/cache.gopkg/cache/cache_internal_test.gopkg/database/client.gopkg/database/errors.go
There was a problem hiding this comment.
Code Review
This pull request updates the chunk recording logic to use an 'insert-ignore' strategy followed by a query to retrieve IDs, aimed at preventing primary key sequence desyncs. It also adds a recovery mechanism for aborted PostgreSQL transactions and introduces cross-backend tests for chunk batching. Feedback highlights that the new chunk recording implementation is inefficient due to 2N database round-trips and suggests a bulk-processing approach. Additionally, the transaction recovery logic is noted to be potentially unreachable or ineffective in its current placement.
b6e5901 to
4f09118
Compare
4f09118 to
b349700
Compare
59a27db to
4beaa0f
Compare
b349700 to
208d1ab
Compare
4beaa0f to
b2314a2
Compare
b2314a2 to
c61ff43
Compare
208d1ab to
2e3a801
Compare
c61ff43 to
b43c865
Compare
2e3a801 to
b510e31
Compare
b43c865 to
509b380
Compare
b510e31 to
2af8079
Compare
509b380 to
1a97db0
Compare
2af8079 to
72497d3
Compare
The previous BIGSERIAL→IDENTITY migration used setval via pg_get_serial_sequence and then DROP SEQUENCE IF EXISTS. Two failure modes were observed on production DB copies: 1. PostgreSQL reuses the old BIGSERIAL sequence object as the IDENTITY sequence — DROP then silently drops or fails to drop it, depending on the version, leaving the sequence at a low value after a transaction abort or retry. 2. setval targeted the old BIGSERIAL sequence (about to be dropped), leaving the new IDENTITY sequence at its initial value (1 or wherever the session left it). Fix: replace setval + DROP with ALTER COLUMN RESTART WITH inside a PL/pgSQL DO block. RESTART WITH always targets the IDENTITY column's own sequence regardless of its name. Wrap DROP SEQUENCE in an EXCEPTION WHEN dependent_objects_still_exist handler so it is silently skipped when PostgreSQL reused the old sequence for the identity (the RESTART above already synced it). Regenerated migrations/postgres/atlas.sum to match. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
72497d3 to
64e21bd
Compare
Summary
20260520212038_postgres_serial_to_identity.sqlmigration to use
ALTER TABLE ... ALTER COLUMN id RESTART WITH (MAX(id)+1)inside a DO block instead ofsetval(pg_get_serial_sequence(...))+DROP SEQUENCE IF EXISTS.sequence lookup could target the wrong sequence when PostgreSQL
reused the old BIGSERIAL sequence object for the IDENTITY column,
and the DROP could silently drop the identity sequence itself,
leaving it at its initial low value.
RESTART WITHvariant targets the identity sequence directlyregardless of its internal name, and wraps the DROP in an
EXCEPTION WHEN dependent_objects_still_existhandler so theidentity is preserved if PostgreSQL reused the old sequence.
migrations/postgres/atlas.sumto match.Why
On databases migrated from BIGSERIAL, the identity sequence was left
at its initial value (1) rather than at
MAX(id)+1. Subsequentauto-inserts generated primary-key values that collided with existing
rows, producing
duplicate key value violates unique constraint "narinfos_pkey"errors and HTTP 500 responses to Nix clients.🤖 Generated with Claude Code