Skip to content

fix(migrations): reliably sync identity sequences on existing DBs - #1258

Merged
kalbasit merged 1 commit into
mainfrom
user/wnasreddine/fix-500-error
May 25, 2026
Merged

kalbasit merged 1 commit into
mainfrom
user/wnasreddine/fix-500-error

Conversation

@kalbasit

@kalbasit kalbasit commented May 24, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Rewrite the 20260520212038_postgres_serial_to_identity.sql
    migration to use ALTER TABLE ... ALTER COLUMN id RESTART WITH (MAX(id)+1) inside a DO block instead of
    setval(pg_get_serial_sequence(...)) + DROP SEQUENCE IF EXISTS.
  • The old approach had two failure modes on existing databases: the
    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.
  • The RESTART WITH variant targets the identity sequence directly
    regardless of its internal name, and wraps the DROP in an
    EXCEPTION WHEN dependent_objects_still_exist handler so the
    identity is preserved if PostgreSQL reused the old sequence.
  • Regenerated migrations/postgres/atlas.sum to match.

Why

On databases migrated from BIGSERIAL, the identity sequence was left
at its initial value (1) rather than at MAX(id)+1. Subsequent
auto-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

@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 24, 2026
@coderabbitai

coderabbitai Bot commented May 24, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

recordChunkBatch now deduplicates hashes, bulk-selects existing chunks, bulk-inserts missing chunks with conflict-ignore, re-fetches chunk IDs, and bulk-creates idempotent nar_file_chunk links. upsertNarInfoFromParsed uses insert-ignore plus unconditioned re-SELECT and fills raced stub rows. New backend-agnostic tests and a Postgres aborted-transaction detector were added; Postgres migration SQL was updated to restart identity sequences and guard legacy-sequence drops.

Changes

Chunk Recording and Transaction Robustness

Layer / File(s) Summary
Aborted transaction error detection
pkg/database/errors.go
New IsAbortedTransactionError helper checks for PostgreSQL SQLSTATE 25P02 via pgconn.PgError or falls back to string matching for "current transaction is aborted".
Chunk batch recording with bulk insert-ignore
pkg/cache/cache.go
recordChunkBatch collects unique chunk hashes, bulk-fetches existing chunks into a hash->ID map, bulk-inserts only missing chunks with OnConflict(hash).Ignore(), re-fetches new/race-won chunks to obtain IDs, then bulk-creates nar_file_chunk junction rows using idempotent OnConflict(nar_file_id, chunk_index).Ignore().
NarInfo insert path change
pkg/cache/cache.go
upsertNarInfoFromParsed replaces constraint-error fallback with an explicit OnConflict(hash).Ignore().Exec(ctx) insert followed by an unconditional re-SELECT to fetch the narinfo row; fills raced stub rows by updating empty-URL rows.
Chunk batch recording test suite
pkg/cache/cache_internal_test.go
Adds TestRecordChunkBatch and helpers to validate NewChunk, PreExistingChunk, and DuplicateHashInBatch across configured DB backends; adds entchunk, entnarfilechunk, and chunker imports used by tests.
Postgres serial->identity migration
migrations/postgres/20260520212038_postgres_serial_to_identity.sql
Replaces setval(pg_get_serial_sequence(...)) with ALTER TABLE ... ALTER COLUMN id RESTART WITH <max(id)+1> and wraps legacy <table>_id_seq drops in exception-silencing blocks to avoid failures when dependent objects still exist (applied to narinfos, config, nar_files, chunks, pinned_closures).

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)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • kalbasit/ncps#1205: Similar changes to pkg/cache/cache.go's recordChunkBatch handling and bulk insert-ignore semantics.
  • kalbasit/ncps#1203: Related NarInfo persistence refactor that interacts with upsertNarInfoFromParsed semantics.

Suggested labels

size:M, merge-stack

Poem

🐇 I hop through hashes, one batch at a time,
Ignore collisions — I leave no crime.
I re-select the winners, stitch links with care,
Tests run on many backends, race bugs beware. 🌱

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 87.50% 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.
Title check ✅ Passed The title accurately describes the main change: fixing reliable synchronization of identity sequences in PostgreSQL migrations on existing databases.
Description check ✅ Passed The description is directly related to the changeset, explaining the problem (sequence desynchronization), the solution (ALTER TABLE RESTART WITH approach), and why the change was needed.

✏️ 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: 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

📥 Commits

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

📒 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/cache/cache_internal_test.go Resolved
Comment thread pkg/database/client.go Resolved

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

Comment thread pkg/cache/cache.go Resolved
Comment thread pkg/database/client.go Resolved
@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 24, 2026

@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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 764893fe-0d22-4e89-8e80-882c4fc1e4e1

📥 Commits

Reviewing files that changed from the base of the PR and between 17d3124 and f6bd6a7.

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

Comment thread pkg/cache/cache.go Resolved
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-500-error branch from b6e5901 to 4f09118 Compare May 25, 2026 00:19
@kalbasit kalbasit changed the title fix: use DO NOTHING for chunk inserts, add 25P02 recovery fix(migrations): reliably sync identity sequences on existing DBs May 25, 2026
@kalbasit
kalbasit changed the base branch from main to user/wnasreddine/fix-stub-narinfo-race May 25, 2026 00:20
@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 force-pushed the user/wnasreddine/fix-500-error branch from 4f09118 to b349700 Compare May 25, 2026 00:25
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-stub-narinfo-race branch from 59a27db to 4beaa0f Compare May 25, 2026 00:25
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-500-error branch from b349700 to 208d1ab Compare May 25, 2026 01:00
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-stub-narinfo-race branch from 4beaa0f to b2314a2 Compare May 25, 2026 01:00
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-stub-narinfo-race branch from b2314a2 to c61ff43 Compare May 25, 2026 01:03
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-500-error branch from 208d1ab to 2e3a801 Compare May 25, 2026 01:03
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-stub-narinfo-race branch from c61ff43 to b43c865 Compare May 25, 2026 01:18
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-500-error branch from 2e3a801 to b510e31 Compare May 25, 2026 01:18
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-stub-narinfo-race branch from b43c865 to 509b380 Compare May 25, 2026 01:35
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-500-error branch from b510e31 to 2af8079 Compare May 25, 2026 01:35
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-stub-narinfo-race branch from 509b380 to 1a97db0 Compare May 25, 2026 02:10
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-500-error branch from 2af8079 to 72497d3 Compare May 25, 2026 02:10
Base automatically changed from user/wnasreddine/fix-stub-narinfo-race to main May 25, 2026 02:37
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]>
@kalbasit
kalbasit force-pushed the user/wnasreddine/fix-500-error branch from 72497d3 to 64e21bd Compare May 25, 2026 02:37
@kalbasit
kalbasit enabled auto-merge (squash) May 25, 2026 02:37
@kalbasit
kalbasit merged commit 1a56b2f into main May 25, 2026
19 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/fix-500-error branch May 25, 2026 02:53
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: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