Skip to content

docs(openspec): address PR #1178 review comments - #1190

Merged
kalbasit merged 9 commits into
mainfrom
gs-comments-1178-1188
May 22, 2026
Merged

kalbasit merged 9 commits into
mainfrom
gs-comments-1178-1188

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

docs(openspec): address PR #1178 review comments

Three review comments on design.md, all valid:

  • Tracking-table name inconsistency (PRRT_kwDONV6tZs6DokBc): D5
    said ncps_schema_versions while D6 and the database-migrations
    spec said schema_migrations. The latter is the intended choice
    (preserves dbmate-era name for operator continuity). Updated D5.

  • tstamp NULL → NOT NULL on the SQLite/Postgres adoption block
    (PRRT_kwDONV6tZs6DokBp): goose's actual Postgres dialect emits
    NOT NULL. Updated the design doc + adopt.go's adoptPostgresSteps
    to match.

  • tstamp NULL → NOT NULL on the MySQL S3 adoption documentation
    (PRRT_kwDONV6tZs6DokBt): in modern MySQL (with
    explicit_defaults_for_timestamp=ON) the column is effectively
    NOT NULL anyway, so make the spec stricter and consistent.
    No impl change needed — createMySQLSchemaMigrations already uses
    NULL DEFAULT which functions identically.

All migrate-package tests pass under -race against all three
engines after the Postgres NOT NULL change.

fix(Taskfile): quote NAME variable to prevent shell injection

Two review comments on PR #1179 (PRRT_kwDONV6tZs6DolmP and
PRRT_kwDONV6tZs6DolmV): the {{.NAME}} template variable was
expanded unquoted into the shell command. Whitespace or shell
metacharacters in NAME would either misparse or open a small shell
injection surface. Wrap in double quotes.

The third comment on this PR (PRRT_kwDONV6tZs6DolmN: goose missing
from go.mod) was correct at the time of the commit but has since
been organically fixed — once §7's apply_test.go imported goose,
go mod tidy pulled it in as a direct dep. Resolved without code
change.

test(schema-parity): lowercase introspected names consistently

Two review comments on PR #1181:

  • PRRT_kwDONV6tZs6DokIU (mustListTables): the MySQL/Postgres queries
    return table names in their stored case, which can drift from the
    lowercase expectedTables list under some MySQL configs. Lowercase
    on read, matching the column-introspection pattern.

  • PRRT_kwDONV6tZs6DokIX (mustListColumns / SQLite branch): SQLite's
    PRAGMA table_info returns column names as-declared; the
    MySQL/Postgres branches already lowercase. Lowercase the SQLite
    branch too for consistency.

The third comment (PRRT_kwDONV6tZs6DokIM: use assert.ElementsMatch
for strict column-set equality instead of Contains) is rejected
with rationale: the same expectedColumns fixture is consumed by
TestSchemaParity (dbmate schema, exact match would work) AND
TestEntSchemaParity (Ent schema, which legitimately adds the
surrogate id columns on weak entities per design D10b). Strict
ElementsMatch would fail on TestEntSchemaParity for legitimate
reasons. Contains correctly models "the documented columns must
exist; extras are allowed".

fix(ent-schema): use Nillable for all optional time fields

Two review comments on PR #1182 (PRRT_kwDONV6tZs6DomHI,
PRRT_kwDONV6tZs6DomHL): nullable time fields in the generated Ent
structs were inconsistent — NarFile.ChunkingStartedAt used
sql.NullTime (which marshals as a JSON object), NarFile.LastAccessedAt
and NarInfo.LastAccessedAt used time.Time (which can't distinguish
NULL from the zero value).

Updated the schema source (ent/schema/nar_file.go,
ent/schema/narinfo.go) to chain .Nillable() on all three fields and
removed the now-unused GoType(sql.NullTime{}) override. Regenerated
the ent client.

All three nullable time fields now use *time.Time consistently, both
for JSON-correctness and for distinguishing NULL from zero. The
sqlc.yaml override that originally forced sql.NullTime is no longer
needed (sqlc tree is removed in §12 cleanup).

Tests pass across all three engines under -race.

fix(ent-lint): skip top-level helpers and unparseable edge targets

Four review comments on PR #1183 (PRRT_kwDONV6tZs6Dont7,
PRRT_kwDONV6tZs6DonuJ, PRRT_kwDONV6tZs6DonuN, PRRT_kwDONV6tZs6DonuR):

Three of them point out that checkA1, checkA2, and checkA4 iterate
methods named Fields/Edges but don't verify the function has a
receiver. If a future ent/schema/ file ever contains a top-level
helper function with one of those names, the linter would
incorrectly attribute its body to a non-existent schema. Skip
methods whose receiverTypeName is empty.

The fourth points out that checkA4 was constructing edgeTo entries
even when typeRefName returned "" (the edge target isn't a simple
T.Type expression — e.g. a more complex Ent invocation we don't
model). The resulting empty-target entry would produce confusing
failure messages downstream. Skip the edge in that case.

ent-lint passes against the live ent/schema/ tree; the fixture-based
unit tests pass under -race.

fix(migrations): goose-correct SQLite PRAGMA + MySQL InnoDB defaults

Three review comments on PR #1184:

  • PRRT_kwDONV6tZs6DojlB (HIGH): the translated SQLite migration
    20260127223000_allow_multiple_nar_representations.sql uses the
    PRAGMA foreign_keys = OFF / DROP TABLE / RENAME pattern to swap
    the nar_files table. SQLite ignores PRAGMA foreign_keys inside a
    transaction, and goose wraps migrations in a transaction by
    default — so against any data already in narinfo_nar_files, the
    DROP TABLE would fail. Added -- +goose NO TRANSACTION plus a
    comment explaining why. Same fix applied to the ent_baseline
    bridge migration (20260520212039_ent_baseline.sql) which also
    uses PRAGMA + table swaps.

  • PRRT_kwDONV6tZs6DojlH: 20260131021850_add_chunks.sql for MySQL
    was missing the ENGINE/CHARSET/COLLATE clauses that
    20260101000000_init_schema.sql sets. Without them the tables
    would inherit server defaults that may not be InnoDB +
    utf8mb4_unicode_ci. Added the clauses to both CREATE TABLE
    statements.

  • PRRT_kwDONV6tZs6DojlK: the SQLite Down migration in
    20260301000000_add_verified_at_to_nar_files.sql used a fragile
    full-table-swap pattern that required manually maintaining the
    column list. Replaced with the much simpler
    ALTER TABLE nar_files DROP COLUMN verified_at (supported by the
    project's go-sqlite3 v1.14.x). This also removes another
    PRAGMA-inside-transaction usage. Down migrations aren't supported
    per design D10, but the cleanup keeps the file honest.

atlas.sum regenerated for all three dialects. All tests pass under
-race across SQLite, PostgreSQL, and MySQL.

Note: the Postgres create_test_db helper function disappeared again
during the test run (this is the third time this session); reinstalled
manually before re-running. May want to investigate why the deps
init isn't sticky between runs.

fix(generate-migrations): use migrate.Tables as source of truth

Review comment on PR #1185 (PRRT_kwDONV6tZs6DonIx): the resetDevDB
helper hardcoded the list of ncps tables to drop before each
migration-generation run. If a future entity is added to ent/schema/
the hardcoded list would silently drift, leaving stale tables in
the dev DB and corrupting the diff.

Switched to enumerating migrate.Tables (already imported in this
file) and appending schema_migrations explicitly. Also restructured
the dialect switch to handle "postgres" explicitly and error on
unknown dialects, so adding a new engine to the loop won't silently
fall through to no-op behavior.

cmd/generate-migrations tests pass; the smoke test verifies the
generator still produces zero diff against the current
schemas/migrations state.

docs(openspec): address PR #1186 review comments

Five comments on the Option E docs PR:

  • PRRT_kwDONV6tZs6DolgE (HIGH): the renamed D6 section introduced a
    contradiction — the legacy adoption sub-sections still said
    "Table doesn't exist → fresh install. Goose creates
    schema_migrations and runs all translated migrations from scratch"
    but Option E handles fresh installs via Schema.Create. Removed
    the contradictory "Table doesn't exist" branches from the
    SQLite/Postgres and MySQL adoption sub-sections and clarified
    that those sub-sections describe the table-conversion mechanic
    for the dbmate-shape branch only; the empty-DB case is handled
    by the higher-level Schema.Create path.

  • PRRT_kwDONV6tZs6DolgG (HIGH): the BIGSERIAL → IDENTITY conversion
    on Postgres needs sequence sync (setval past max(id)) or the new
    IDENTITY starts at 1 and the first post-bridge INSERT collides.
    The actual hand-written
    20260520212038_postgres_serial_to_identity.sql already does this
    — the doc was just incomplete. Added the explanation.

  • PRRT_kwDONV6tZs6DolgM / PRRT_kwDONV6tZs6DolgS: replaced bare
    references to NOW() with "the dialect-appropriate function or a
    Go-side time.Now() value" since SQLite uses CURRENT_TIMESTAMP not
    NOW().

  • PRRT_kwDONV6tZs6DolgZ: noted the partial-fresh crash recovery
    scenario in tasks.md as a known edge case deferred to follow-up.
    Currently if Schema.Create succeeds but version seeding crashes,
    Detect returns ErrCorruptState. Adding a StatePartialFresh would
    improve robustness but the same DB shape can arise from genuine
    corruption / manual operator actions; auto-recovery would mask
    those. For v1, refusing to adopt is the safer default.

test(migrate): robust mysql DSN + MkdirAll in copyMigrations

Two review comments on PR #1187:

  • PRRT_kwDONV6tZs6DooEC: the hand-rolled mysqlURLToDSN concatenated
    user/password/host/db into a DSN string, which breaks if the
    password contains : or @. Switched both copies of the helper
    (migrations/equivalence_test.go and
    pkg/database/migrate/migrate_test.go) to use
    mysqldriver.NewConfig, which handles escaping correctly. Also
    promotes parseTime / loc / multiStatements to proper Config
    fields when they're not already set in the URL params.

  • PRRT_kwDONV6tZs6DooEF: copyMigrations in equivalence_test.go used
    os.Create directly, which would fail if a future migrations
    layout introduced subdirectories. Added MkdirAll on the target
    file's parent directory. Today the layout is flat so this is a
    no-op, but the helper is now robust to a future refactor.

Migrations + migrate-package tests pass under -race.

fix(migrate): idiomatic rollback + dynamic appTables + io.Writer plan

Six review comments on PR #1188, all valid:

  • PRRT_kwDONV6tZs6DonwL (adopt.go): replace manual rollback() calls
    on every error path with a single defer tx.Rollback(). The
    deferred call is a no-op after a successful Commit, and the
    pattern is robust to future early-return paths.

  • PRRT_kwDONV6tZs6DonwR + PRRT_kwDONV6tZs6DonwW (state.go): the
    hardcoded appTables list would drift from the Ent schema as
    entities are added. Switched to populating it at init() from
    entmigrate.Tables, matching the same approach we applied to
    cmd/generate-migrations in PR feat(cmd): add generate-migrations with atlas-as-library #1185's fix.

  • PRRT_kwDONV6tZs6Donwa + PRRT_kwDONV6tZs6Donwc +
    PRRT_kwDONV6tZs6Donwd (ncps/migrate.go): printPlan hardcoded
    os.Stdout. Updated to take an io.Writer (testable + respects
    the cli.Command's configured Writer) and the caller passes
    cmd.Writer (falling back to os.Stdout if unset).

All migrate-package + ncps tests pass under -race across all three
engines.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. documentation Improvements or additions to documentation go Pull requests that update go code labels May 21, 2026
@kalbasit

kalbasit commented May 21, 2026 •

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

This was referenced May 21, 2026
@coderabbitai

coderabbitai Bot commented May 22, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes

    • Improved lint checks to better validate schema definitions and edge configurations.
    • Fixed timestamp field handling to properly support nullable values in database records.
    • Enhanced database migration state detection to reduce false corruption errors.
    • Corrected transaction handling in SQLite migrations to ensure foreign key constraints work as intended.
  • Documentation

    • Updated migration adoption design specifications for clarity on recovery scenarios and fresh installs.

Walkthrough

This PR unifies nullable timestamp handling across the Ent ORM layer by replacing sql.NullTime with *time.Time, refactors migration state management to use generated table metadata, hardens SQLite transaction handling, and improves test infrastructure robustness for DSN construction and schema parity testing.

Changes

Nullable Timestamp Unification and Migration Infrastructure Refactoring

Layer / File(s) Summary
Schema definition updates for nullable timestamps
ent/schema/nar_file.go, ent/schema/narinfo.go
Ent schemas remove database/sql imports and update chunking_started_at and last_accessed_at to use Optional().Nillable() instead of custom sql.NullTime mappings.
Model struct types and database value assignment
ent/narfile.go, ent/narinfo.go, ent/narinfo_create.go
Entity types NarFile and NarInfo change timestamp fields to nullable pointers. Assignment logic allocates pointers when column values are valid; string formatting conditionally includes these fields only when non-nil.
Mutation setter and getter APIs
ent/mutation.go
Mutation methods for timestamps (SetChunkingStartedAt, OldChunkingStartedAt, OldLastAccessedAt) updated to use time.Time/*time.Time instead of sql.NullTime.
Create and update builder APIs
ent/narfile_create.go, ent/narfile_update.go
Builder signatures updated to use time.Time/*time.Time parameters; internal createSpec methods corrected to store pointer values for nullable timestamp fields.
Query predicate and where clause builders
ent/narfile/where.go
All chunking_started_at predicate helpers updated to accept time.Time instead of sql.NullTime.
Ent-lint schema method validation
cmd/ent-lint/main.go
Lint checks tightened to skip non-schema-method Fields/Edges functions and validate edge.To targets conform to simple T.Type form, reducing false positives.
Dynamic migration state tracking and table reset refactoring
cmd/generate-migrations/main.go, pkg/database/migrate/state.go
resetDevDB constructs table drop lists from migrate.Tables instead of hardcoded values with dialect-specific switch branches; appTables is dynamically initialized at runtime from Ent migration metadata.
Adoption transaction refactoring and schema_migrations constraints
pkg/database/migrate/adopt.go
adoptTransactional uses deferred rollback; PostgreSQL schema adoption DDL defines schema_migrations.tstamp as NOT NULL DEFAULT now().
SQLite migration transaction directives
migrations/sqlite/*
Migrations marked with NO TRANSACTION to ensure PRAGMA foreign_keys changes take effect; includes explanatory comments.
MySQL storage engine and charset specifications
migrations/mysql/20260131021850_add_chunks.sql
Tables created with explicit ENGINE = InnoDB and DEFAULT CHARSET utf8mb4.
Test DSN parsing and migration copy robustness
migrations/equivalence_test.go, pkg/database/migrate/migrate_test.go
MySQL DSN helpers replace manual concatenation with go-sql-driver/mysql config-based parsing; copyMigrations hardened with os.MkdirAll.
Schema parity test case normalization
pkg/database/schema_parity_test.go
Introspected table and column names normalized to lowercase for SQLite, aligning with existing Postgres/MySQL behavior.
Dry-run output writer refactoring
pkg/ncps/migrate.go
Dry-run plan printing refactored to accept io.Writer and route to cmd.Writer (with os.Stdout fallback).
Migration design and specification updates
openspec/changes/migrate-to-ent-and-atlas/*
Design documentation specifies schema_migrations as canonical tracking table, clarifies PostgreSQL IDENTITY sequence advancement, refines adoption flow ordering, and defines tstamp as non-nullable.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • kalbasit/ncps#1185: The main PR's refactor of cmd/generate-migrations/main.go (notably resetDevDB dropping tables based on migrate.Tables, plus dialect-specific behavior) directly builds on/adjusts the new cmd/generate-migrations tool introduced in this PR.
  • kalbasit/ncps#1186: The main PR includes follow-up edits to the same openspec/changes/migrate-to-ent-and-atlas/* "Option E" migration/adoption design/spec docs that this PR expands, refining the schema_migrations/tstamp and decision-tree details in overlapping sections.
  • kalbasit/ncps#1187: The main PR further updates the migrations/equivalence_test.go helpers (mysqlURLToDSN DSN parsing and copyMigrations directory creation) used by TestSchemaEquivalence.

Suggested labels

size:L

Poem

🐰 With timestamps now nullable and pointers so fine,
Migrations march forward with schema in line,
SQLite transactions no longer confined,
Infrastructure hardened—a masterpiece designed! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The PR title 'docs(openspec): address PR #1178 review comments' is vague and does not clearly summarize the main scope of changes, which encompasses fixes across docs, migrations, schema, linting, and testing beyond just openspec documentation. Consider a more specific title that captures the breadth of changes, such as 'fix: address review comments across migrations, schema, and tooling' to better represent the comprehensive nature of this PR.
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed The PR description thoroughly documents all changes across multiple areas (docs, migrations, schema, ent-lint, tests, and tooling) with detailed explanations of review comments addressed and rationales for decisions made, making it clearly related to the changeset.
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.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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

@kalbasit
kalbasit force-pushed the feat-migrate-ncps-migrate-up branch from 3ea9c61 to a667980 Compare May 22, 2026 16:02
@kalbasit
kalbasit force-pushed the gs-comments-1178-1188 branch from 96c0213 to d2afd47 Compare May 22, 2026 16:02
@kalbasit
kalbasit force-pushed the feat-migrate-ncps-migrate-up branch from a667980 to 11cfef3 Compare May 22, 2026 16:15
@kalbasit
kalbasit force-pushed the gs-comments-1178-1188 branch from d2afd47 to cf004cf Compare May 22, 2026 16:15
@kalbasit
kalbasit force-pushed the feat-migrate-ncps-migrate-up branch from 11cfef3 to 2764dfb Compare May 22, 2026 16:27
@kalbasit
kalbasit force-pushed the gs-comments-1178-1188 branch from cf004cf to 96afbbf Compare May 22, 2026 16:27
Base automatically changed from feat-migrate-ncps-migrate-up to main May 22, 2026 16:42
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 22, 2026
kalbasit added 9 commits May 22, 2026 16:42
Three review comments on design.md, all valid:

- Tracking-table name inconsistency (PRRT_kwDONV6tZs6DokBc): D5
  said `ncps_schema_versions` while D6 and the database-migrations
  spec said `schema_migrations`. The latter is the intended choice
  (preserves dbmate-era name for operator continuity). Updated D5.

- tstamp NULL → NOT NULL on the SQLite/Postgres adoption block
  (PRRT_kwDONV6tZs6DokBp): goose's actual Postgres dialect emits
  NOT NULL. Updated the design doc + adopt.go's adoptPostgresSteps
  to match.

- tstamp NULL → NOT NULL on the MySQL S3 adoption documentation
  (PRRT_kwDONV6tZs6DokBt): in modern MySQL (with
  explicit_defaults_for_timestamp=ON) the column is effectively
  NOT NULL anyway, so make the spec stricter and consistent.
  No impl change needed — createMySQLSchemaMigrations already uses
  NULL DEFAULT which functions identically.

All migrate-package tests pass under -race against all three
engines after the Postgres NOT NULL change.
Two review comments on PR #1181:

- PRRT_kwDONV6tZs6DokIU (mustListTables): the MySQL/Postgres queries
  return table names in their stored case, which can drift from the
  lowercase expectedTables list under some MySQL configs. Lowercase
  on read, matching the column-introspection pattern.

- PRRT_kwDONV6tZs6DokIX (mustListColumns / SQLite branch): SQLite's
  PRAGMA table_info returns column names as-declared; the
  MySQL/Postgres branches already lowercase. Lowercase the SQLite
  branch too for consistency.

The third comment (PRRT_kwDONV6tZs6DokIM: use assert.ElementsMatch
for strict column-set equality instead of Contains) is rejected
with rationale: the same expectedColumns fixture is consumed by
TestSchemaParity (dbmate schema, exact match would work) AND
TestEntSchemaParity (Ent schema, which legitimately adds the
surrogate `id` columns on weak entities per design D10b). Strict
ElementsMatch would fail on TestEntSchemaParity for legitimate
reasons. Contains correctly models "the documented columns must
exist; extras are allowed".
Two review comments on PR #1182 (PRRT_kwDONV6tZs6DomHI,
PRRT_kwDONV6tZs6DomHL): nullable time fields in the generated Ent
structs were inconsistent — NarFile.ChunkingStartedAt used
sql.NullTime (which marshals as a JSON object), NarFile.LastAccessedAt
and NarInfo.LastAccessedAt used time.Time (which can't distinguish
NULL from the zero value).

Updated the schema source (ent/schema/nar_file.go,
ent/schema/narinfo.go) to chain .Nillable() on all three fields and
removed the now-unused GoType(sql.NullTime{}) override. Regenerated
the ent client.

All three nullable time fields now use *time.Time consistently, both
for JSON-correctness and for distinguishing NULL from zero. The
sqlc.yaml override that originally forced sql.NullTime is no longer
needed (sqlc tree is removed in §12 cleanup).

Tests pass across all three engines under -race.
Four review comments on PR #1183 (PRRT_kwDONV6tZs6Dont7,
PRRT_kwDONV6tZs6DonuJ, PRRT_kwDONV6tZs6DonuN, PRRT_kwDONV6tZs6DonuR):

Three of them point out that checkA1, checkA2, and checkA4 iterate
methods named Fields/Edges but don't verify the function has a
receiver. If a future ent/schema/ file ever contains a top-level
helper function with one of those names, the linter would
incorrectly attribute its body to a non-existent schema. Skip
methods whose receiverTypeName is empty.

The fourth points out that checkA4 was constructing edgeTo entries
even when typeRefName returned "" (the edge target isn't a simple
T.Type expression — e.g. a more complex Ent invocation we don't
model). The resulting empty-target entry would produce confusing
failure messages downstream. Skip the edge in that case.

ent-lint passes against the live ent/schema/ tree; the fixture-based
unit tests pass under -race.
Three review comments on PR #1184:

- PRRT_kwDONV6tZs6DojlB (HIGH): the translated SQLite migration
  20260127223000_allow_multiple_nar_representations.sql uses the
  PRAGMA foreign_keys = OFF / DROP TABLE / RENAME pattern to swap
  the nar_files table. SQLite ignores PRAGMA foreign_keys inside a
  transaction, and goose wraps migrations in a transaction by
  default — so against any data already in narinfo_nar_files, the
  DROP TABLE would fail. Added `-- +goose NO TRANSACTION` plus a
  comment explaining why. Same fix applied to the ent_baseline
  bridge migration (20260520212039_ent_baseline.sql) which also
  uses PRAGMA + table swaps.

- PRRT_kwDONV6tZs6DojlH: 20260131021850_add_chunks.sql for MySQL
  was missing the ENGINE/CHARSET/COLLATE clauses that
  20260101000000_init_schema.sql sets. Without them the tables
  would inherit server defaults that may not be InnoDB +
  utf8mb4_unicode_ci. Added the clauses to both CREATE TABLE
  statements.

- PRRT_kwDONV6tZs6DojlK: the SQLite Down migration in
  20260301000000_add_verified_at_to_nar_files.sql used a fragile
  full-table-swap pattern that required manually maintaining the
  column list. Replaced with the much simpler
  `ALTER TABLE nar_files DROP COLUMN verified_at` (supported by the
  project's go-sqlite3 v1.14.x). This also removes another
  PRAGMA-inside-transaction usage. Down migrations aren't supported
  per design D10, but the cleanup keeps the file honest.

atlas.sum regenerated for all three dialects. All tests pass under
-race across SQLite, PostgreSQL, and MySQL.

Note: the Postgres create_test_db helper function disappeared again
during the test run (this is the third time this session); reinstalled
manually before re-running. May want to investigate why the deps
init isn't sticky between runs.
Review comment on PR #1185 (PRRT_kwDONV6tZs6DonIx): the resetDevDB
helper hardcoded the list of ncps tables to drop before each
migration-generation run. If a future entity is added to ent/schema/
the hardcoded list would silently drift, leaving stale tables in
the dev DB and corrupting the diff.

Switched to enumerating migrate.Tables (already imported in this
file) and appending schema_migrations explicitly. Also restructured
the dialect switch to handle "postgres" explicitly and error on
unknown dialects, so adding a new engine to the loop won't silently
fall through to no-op behavior.

cmd/generate-migrations tests pass; the smoke test verifies the
generator still produces zero diff against the current
schemas/migrations state.
Five comments on the Option E docs PR:

- PRRT_kwDONV6tZs6DolgE (HIGH): the renamed D6 section introduced a
  contradiction — the legacy adoption sub-sections still said
  "Table doesn't exist → fresh install. Goose creates
  schema_migrations and runs all translated migrations from scratch"
  but Option E handles fresh installs via Schema.Create. Removed
  the contradictory "Table doesn't exist" branches from the
  SQLite/Postgres and MySQL adoption sub-sections and clarified
  that those sub-sections describe the *table-conversion mechanic*
  for the dbmate-shape branch only; the empty-DB case is handled
  by the higher-level Schema.Create path.

- PRRT_kwDONV6tZs6DolgG (HIGH): the BIGSERIAL → IDENTITY conversion
  on Postgres needs sequence sync (setval past max(id)) or the new
  IDENTITY starts at 1 and the first post-bridge INSERT collides.
  The actual hand-written
  20260520212038_postgres_serial_to_identity.sql already does this
  — the doc was just incomplete. Added the explanation.

- PRRT_kwDONV6tZs6DolgM / PRRT_kwDONV6tZs6DolgS: replaced bare
  references to `NOW()` with "the dialect-appropriate function or a
  Go-side time.Now() value" since SQLite uses CURRENT_TIMESTAMP not
  NOW().

- PRRT_kwDONV6tZs6DolgZ: noted the partial-fresh crash recovery
  scenario in tasks.md as a known edge case deferred to follow-up.
  Currently if Schema.Create succeeds but version seeding crashes,
  Detect returns ErrCorruptState. Adding a StatePartialFresh would
  improve robustness but the same DB shape can arise from genuine
  corruption / manual operator actions; auto-recovery would mask
  those. For v1, refusing to adopt is the safer default.
Two review comments on PR #1187:

- PRRT_kwDONV6tZs6DooEC: the hand-rolled mysqlURLToDSN concatenated
  user/password/host/db into a DSN string, which breaks if the
  password contains `:` or `@`. Switched both copies of the helper
  (migrations/equivalence_test.go and
  pkg/database/migrate/migrate_test.go) to use
  mysqldriver.NewConfig, which handles escaping correctly. Also
  promotes parseTime / loc / multiStatements to proper Config
  fields when they're not already set in the URL params.

- PRRT_kwDONV6tZs6DooEF: copyMigrations in equivalence_test.go used
  os.Create directly, which would fail if a future migrations
  layout introduced subdirectories. Added MkdirAll on the target
  file's parent directory. Today the layout is flat so this is a
  no-op, but the helper is now robust to a future refactor.

Migrations + migrate-package tests pass under -race.
Six review comments on PR #1188, all valid:

- PRRT_kwDONV6tZs6DonwL (adopt.go): replace manual `rollback()` calls
  on every error path with a single `defer tx.Rollback()`. The
  deferred call is a no-op after a successful Commit, and the
  pattern is robust to future early-return paths.

- PRRT_kwDONV6tZs6DonwR + PRRT_kwDONV6tZs6DonwW (state.go): the
  hardcoded `appTables` list would drift from the Ent schema as
  entities are added. Switched to populating it at init() from
  `entmigrate.Tables`, matching the same approach we applied to
  cmd/generate-migrations in PR #1185's fix.

- PRRT_kwDONV6tZs6Donwa + PRRT_kwDONV6tZs6Donwc +
  PRRT_kwDONV6tZs6Donwd (ncps/migrate.go): `printPlan` hardcoded
  `os.Stdout`. Updated to take an `io.Writer` (testable + respects
  the cli.Command's configured Writer) and the caller passes
  `cmd.Writer` (falling back to `os.Stdout` if unset).

All migrate-package + ncps tests pass under -race across all three
engines.
@kalbasit
kalbasit force-pushed the gs-comments-1178-1188 branch from 96afbbf to ef67ddd Compare May 22, 2026 16:42
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels May 22, 2026
@kalbasit
kalbasit enabled auto-merge (squash) May 22, 2026 16:42

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

🧹 Nitpick comments (1)
openspec/changes/migrate-to-ent-and-atlas/specs/database-migrations/spec.md (1)

86-99: ⚡ Quick win

Consider making PostgreSQL sequence synchronization an explicit requirement.

The bridge migration requirement mentions converting BIGSERIAL to IDENTITY for PostgreSQL, but doesn't explicitly require synchronizing the new IDENTITY sequence past MAX(id). Without this sync, the first post-migration INSERT will fail with a primary key collision (the sequence starts at 1 while existing rows occupy 1..N).

design.md line 98 documents this correctly, but it's critical enough to warrant an explicit SHALL in the spec.

📝 Suggested addition to the PostgreSQL bridge bullet
-- For PostgreSQL only: conversion of every `BIGSERIAL` PK column to `BIGINT GENERATED BY DEFAULT AS IDENTITY` (modern Postgres best practice).
+- For PostgreSQL only: conversion of every `BIGSERIAL` PK column to `BIGINT GENERATED BY DEFAULT AS IDENTITY` (modern Postgres best practice). The conversion SHALL synchronize each new IDENTITY sequence past the table's current `MAX(id)` to prevent primary key collisions on subsequent inserts.
🤖 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 `@openspec/changes/migrate-to-ent-and-atlas/specs/database-migrations/spec.md`
around lines 86 - 99, Add an explicit SHALL to the PostgreSQL bridge migration
requirement requiring the new IDENTITY sequences to be advanced beyond existing
values: when converting every BIGSERIAL PK to BIGINT GENERATED BY DEFAULT AS
IDENTITY in the migrations/<dialect>/<timestamp>_ent_baseline.sql bridge, ensure
the migration also sets each table’s identity/sequence to at least MAX(id)+1 (so
subsequent INSERTs won’t collide with existing rows for tables like
narinfo_references, narinfo_signatures, narinfo_nar_files, nar_file_chunks) and
document that the post-bridge schema must match Schema.Create and have updated
sequences.
🤖 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.

Nitpick comments:
In `@openspec/changes/migrate-to-ent-and-atlas/specs/database-migrations/spec.md`:
- Around line 86-99: Add an explicit SHALL to the PostgreSQL bridge migration
requirement requiring the new IDENTITY sequences to be advanced beyond existing
values: when converting every BIGSERIAL PK to BIGINT GENERATED BY DEFAULT AS
IDENTITY in the migrations/<dialect>/<timestamp>_ent_baseline.sql bridge, ensure
the migration also sets each table’s identity/sequence to at least MAX(id)+1 (so
subsequent INSERTs won’t collide with existing rows for tables like
narinfo_references, narinfo_signatures, narinfo_nar_files, nar_file_chunks) and
document that the post-bridge schema must match Schema.Create and have updated
sequences.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4a20e4e8-970e-4cad-94d2-6cd22b867d02

📥 Commits

Reviewing files that changed from the base of the PR and between 81dffd6 and ef67ddd.

⛔ Files ignored due to path filters (2)
  • migrations/mysql/atlas.sum is excluded by !**/*.sum
  • migrations/sqlite/atlas.sum is excluded by !**/*.sum
📒 Files selected for processing (24)
  • cmd/ent-lint/main.go
  • cmd/generate-migrations/main.go
  • ent/mutation.go
  • ent/narfile.go
  • ent/narfile/where.go
  • ent/narfile_create.go
  • ent/narfile_update.go
  • ent/narinfo.go
  • ent/narinfo_create.go
  • ent/schema/nar_file.go
  • ent/schema/narinfo.go
  • migrations/equivalence_test.go
  • migrations/mysql/20260131021850_add_chunks.sql
  • migrations/sqlite/20260127223000_allow_multiple_nar_representations.sql
  • migrations/sqlite/20260301000000_add_verified_at_to_nar_files.sql
  • migrations/sqlite/20260520212039_ent_baseline.sql
  • openspec/changes/migrate-to-ent-and-atlas/design.md
  • openspec/changes/migrate-to-ent-and-atlas/specs/database-migrations/spec.md
  • openspec/changes/migrate-to-ent-and-atlas/tasks.md
  • pkg/database/migrate/adopt.go
  • pkg/database/migrate/migrate_test.go
  • pkg/database/migrate/state.go
  • pkg/database/schema_parity_test.go
  • pkg/ncps/migrate.go

@codecov

codecov Bot commented May 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 5.04%. Comparing base (81dffd6) to head (ef67ddd).

Additional details and impacted files
@@          Coverage Diff          @@
##            main   #1190   +/-   ##
=====================================
  Coverage   5.04%   5.04%           
=====================================
  Files          6       6           
  Lines        436     436           
=====================================
  Hits          22      22           
  Misses       410     410           
  Partials       4       4           

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

@kalbasit
kalbasit merged commit 40afcbb into main May 22, 2026
18 checks passed
@kalbasit
kalbasit deleted the gs-comments-1178-1188 branch May 22, 2026 16:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation 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