Repository navigation
feat(migrations): ent_baseline bridge + schema-equivalence test - #1187
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces baseline migrations for SQLite, MySQL, and PostgreSQL to align existing database schemas with the structures expected by Ent. The migration generation tool in cmd/generate-migrations has been enhanced with a --skip flag and an ensureAtlasSum helper to automatically maintain integrity files. A new test suite, TestSchemaEquivalence, is added to verify that the migration history correctly reproduces the Ent schema across all dialects. Review feedback suggests refactoring the MySQL DSN construction to use mysqldriver.NewConfig for better robustness and ensuring that parent directories are created when copying migrations in tests.
edb1683 to
5634b25
Compare
db4c896 to
119e303
Compare
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.
5634b25 to
79d3a6b
Compare
119e303 to
47fcbfa
Compare
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.
79d3a6b to
4501ffa
Compare
47fcbfa to
e10a4eb
Compare
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.
📝 WalkthroughWalkthroughThis PR implements schema baseline migrations across SQLite, Postgres, and MySQL dialects, adds a comprehensive schema equivalence test that validates replay of migrations against fresh databases, enhances the migration generation tooling with a ChangesSchema Baseline Migrations and Equivalence Testing
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
4501ffa to
1239e34
Compare
e10a4eb to
e828bc8
Compare
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.
Implements §8 of the migrate-to-ent-and-atlas change. Closes the gap
between the §7 translated dbmate-era migrations and Ent's expected
schema (§4) with a per-dialect bridge migration, and gates the
equivalence permanently via a CI-runnable test.
Bridge migrations (one per dialect, all sorted after the last
dbmate-era file):
- migrations/sqlite/20260520212039_ent_baseline.sql (Atlas-auto):
the SQLite-canonical "recreate via temp table" pattern. Adds
surrogate id PKs on weak entities (D10b), renames indexes to Ents
naming convention (e.g. idx_narinfos_hash -> narinfo_hash), and
adds Ent's named CHECK constraints.
- migrations/mysql/20260520212039_ent_baseline.sql (Atlas-auto):
ALTER TABLE ADD COLUMN id BIGINT AUTO_INCREMENT, DROP PRIMARY KEY,
ADD PRIMARY KEY (id), ADD UNIQUE INDEX on weak entities. Plus
MODIFY COLUMN to varchar(255) for hashes, bigint for chunk sizes
(signed; previously bigint unsigned), and FK constraint renames.
- migrations/postgres/ — split into two files because Atlas's diff
engine refuses to compute the BIGSERIAL/IDENTITY reverse direction:
- 20260520212038_postgres_serial_to_identity.sql (hand-written):
DROP DEFAULT + ADD GENERATED BY DEFAULT AS IDENTITY for each of
the five existing id-bearing tables, setval the new IDENTITY
sequence past max(id), drop the orphaned BIGSERIAL sequences.
The BIGSERIAL -> IDENTITY modernization is bundled here per
design D6 so v1 lands with modern Postgres conventions and
v1.x doesnt need a separate disruptive migration.
- 20260520213017_ent_baseline.sql (Atlas-auto, after the IDENTITY
conversion file is in place so Atlas can compute the rest):
surrogate ids on weak entities, text -> varchar, integer ->
bigint, timestamp -> timestamptz, FK and CHECK constraint
renames.
Tooling:
- cmd/generate-migrations extends §6 with two improvements:
1. ensureAtlasSum: computes and writes atlas.sum after creating
a GooseDir, so the first run on a hand-translated directory
(per §7) bootstraps the integrity file. atlas.sum is committed
for all three dialects.
2. --skip flag: comma-separated dialects to skip
(sqlite,postgres,mysql), an escape hatch for the
two-file Postgres bridge approach.
Test:
- migrations/equivalence_test.go::TestSchemaEquivalence is the
load-bearing guarantee. Per dialect:
1. Copies migrations/<dialect>/*.sql to a temp dir.
2. Bootstraps atlas.sum in that temp dir.
3. Opens a fresh empty database — in-memory SQLite, or an
ephemeral PostgreSQL / MySQL database via testhelper-style
ephemeral-DB helpers added to the test file.
4. Runs Atlas's schema.NewMigrate with ModeReplay +
GooseFormatter, calls NamedDiff against migrate.Tables into
the temp dir.
5. Asserts no new .sql file appeared (zero diff between the
replayed-from-migrations schema and Ents expected schema).
All three dialects pass.
Note for §13/CI: the Postgres test requires create_test_db function
to be installed in the dev test-db. The function is part of
nix/process-compose/postgres-dblink-create-drop-functions.sql which
runs as part of nix run .#deps init. If a deps instance is missing
the function (rare; happened once during this work after a deps
restart didnt complete init), re-run the SQL file as the postgres
superuser.
Tasks 8.1-8.5 of the migrate-to-ent-and-atlas change. 8.6
(TestSchemaCreateMatchesAppliedMigrations) and 8.7 (CI wiring)
remain for §9 and §13 respectively.
sqlfluff (via nix fmt) reformatted the ent_baseline migration: uppercased the PRAGMA value and broke the long INSERT...SELECT across lines for readability. Regenerated migrations/sqlite/atlas.sum with the project-pinned ariga.io/atlas library so the directory checksum matches the new file content (CI's atlas-sum-check would otherwise fail).
e828bc8 to
2cccdbf
Compare
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.
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 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 `@cmd/generate-migrations/main.go`:
- Around line 166-172: The sql-only code path returns before refreshing Atlas
checksum, leaving atlas.sum stale; update the handler that branches on the
--sql-only flag (the sqlOnly branch in the migration generation flow) to call
ensureAtlasSum(gdir) after writing the .sql file (or before returning) and
propagate/log any error (same pattern as the schema-diff path), using the
existing ensureAtlasSum function to refresh atlas.sum so integrity metadata
stays in sync.
- Around line 112-123: The parseSkip function should validate and normalize the
comma-separated --skip values instead of silently ignoring typos: update
parseSkip to convert each part to lower-case, trim whitespace, check against a
canonical set of allowed dialect identifiers (e.g., a const/var like
validDialects or a hard-coded map containing "mysql","postgres","sqlite", etc.),
and if any unknown token is encountered return an error (or propagate one)
rather than omitting it; keep the returned type as a set of normalized strings
(map[string]struct{}) but change the signature to return (map[string]struct{},
error) and make callers handle the error so the program fails fast on typos like
"myslq".
In `@migrations/equivalence_test.go`:
- Around line 109-118: Replace the manual failure check that uses t.Fatalf when
diffFiles has entries with a testify assertion: import
"github.com/stretchr/testify/assert" and change the t.Fatalf(...) call to
assert.Emptyf(t, diffFiles, "schema drift detected for %s: Atlas produced new
migration file(s): %v", tc.dialect, diffFiles); keep the existing diffFiles :=
setDiff(after, before) loop and logging, ensuring the new import is added to the
test file imports.
In `@migrations/mysql/20260520212039_ent_baseline.sql`:
- Around line 5-19: This migration narrows several text/longer varchar columns
to varchar(255) (config.value, nar_files.query, narinfos.ca, narinfos.deriver,
narinfos.url, narinfos.store_path) without safety checks; before running each
MODIFY COLUMN, add a preflight step that queries MAX(CHAR_LENGTH(column)) for
those columns and either aborts the migration with a clear error if any rows
exceed 255, or performs a controlled cleanup step (e.g., UPDATE ... SET column =
LEFT(column,255) or move/backup offending rows to a staging table) and re-checks
length, then proceed with ALTER TABLE; update the migration SQL to include these
SELECT + conditional UPDATE/VERIFY steps and ensure the migration fails fast
with a clear message if automatic trimming is not desired.
In `@migrations/postgres/20260520213017_ent_baseline.sql`:
- Line 3: The ALTER on table "chunks" currently changes "created_at" to
timestamptz with an implicit cast that depends on the session timezone; update
the ALTER TABLE "chunks" ALTER COLUMN "created_at" TYPE timestamptz statement to
include an explicit USING clause (e.g. USING created_at AT TIME ZONE 'UTC') so
the conversion is deterministic, and mirror the symmetric explicit USING clause
in the Down migration when converting back to timestamp without time zone (e.g.
USING created_at AT TIME ZONE 'UTC' to produce the target type) to avoid
session-dependent behavior.
In `@migrations/sqlite/20260520212039_ent_baseline.sql`:
- Around line 170-220: The migration's -- +goose Down section incorrectly
contains DROP INDEX/DROP TABLE statements that reference the temporary new_*
objects (e.g., DROP TABLE `new_pinned_closures`, DROP TABLE `new_chunks`, DROP
TABLE `new_narinfos`) which will fail if run; replace the entire -- +goose Down
block with an intentionally empty forward-only stub (leave a comment or a no-op
like "-- +goose Down\n-- no-op: forward-only migration") so the migration is
explicitly marked as non-reversible and does not attempt to drop the new_*
tables/indexes.
🪄 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: defaults
Review profile: CHILL
Plan: Pro
Run ID: 0d2631ce-fb95-45c8-b33f-6d2e4c2a478f
⛔ Files ignored due to path filters (3)
migrations/mysql/atlas.sumis excluded by!**/*.summigrations/postgres/atlas.sumis excluded by!**/*.summigrations/sqlite/atlas.sumis excluded by!**/*.sum
📒 Files selected for processing (7)
cmd/generate-migrations/main.gomigrations/equivalence_test.gomigrations/mysql/20260520212039_ent_baseline.sqlmigrations/postgres/20260520212038_postgres_serial_to_identity.sqlmigrations/postgres/20260520213017_ent_baseline.sqlmigrations/sqlite/20260520212039_ent_baseline.sqlopenspec/changes/migrate-to-ent-and-atlas/tasks.md
| // Ensure atlas.sum exists and is current before Atlas validates the | ||
| // directory during replay. This bootstraps the integrity file on the | ||
| // first run after a migration tree is hand-edited (notably the §7 | ||
| // translation) and refreshes it on every subsequent generation. | ||
| if err := ensureAtlasSum(gdir); err != nil { | ||
| return fmt.Errorf("ensureAtlasSum: %w", err) | ||
| } |
There was a problem hiding this comment.
--sql-only can leave atlas.sum stale.
ensureAtlasSum only runs in schema-diff mode; sql-only writes a new .sql file and returns before checksum refresh. That can leave migration integrity metadata out of sync.
Suggested fix
if sqlOnly {
path := filepath.Join(dir, fname)
stub := "-- +goose Up\n\n-- +goose Down\n"
if err := os.WriteFile(path, []byte(stub), 0o600); err != nil {
return fmt.Errorf("write stub: %w", err)
}
+
+ gdir, err := sqltool.NewGooseDir(dir)
+ if err != nil {
+ return fmt.Errorf("NewGooseDir(%s): %w", dir, err)
+ }
+ if err := ensureAtlasSum(gdir); err != nil {
+ return fmt.Errorf("ensureAtlasSum: %w", err)
+ }
fmt.Println(path)
return nil
}🤖 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 `@cmd/generate-migrations/main.go` around lines 166 - 172, The sql-only code
path returns before refreshing Atlas checksum, leaving atlas.sum stale; update
the handler that branches on the --sql-only flag (the sqlOnly branch in the
migration generation flow) to call ensureAtlasSum(gdir) after writing the .sql
file (or before returning) and propagate/log any error (same pattern as the
schema-diff path), using the existing ensureAtlasSum function to refresh
atlas.sum so integrity metadata stays in sync.
| diffFiles := setDiff(after, before) | ||
| if len(diffFiles) > 0 { | ||
| for _, f := range diffFiles { | ||
| body, _ := os.ReadFile(filepath.Join(tmpDir, f)) | ||
| t.Logf("=== diff file %s ===\n%s", f, string(body)) | ||
| } | ||
|
|
||
| t.Fatalf("schema drift detected for %s: Atlas produced new migration file(s): %v", | ||
| tc.dialect, diffFiles) | ||
| } |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify this file still uses raw fatal assertions and whether assert is imported.
rg -n 't\.Fatalf\(' migrations/equivalence_test.go
rg -n '"github.com/stretchr/testify/assert"' migrations/equivalence_test.goRepository: kalbasit/ncps
Length of output: 148
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="migrations/equivalence_test.go"
# Show imports block
echo "---- imports ----"
sed -n '1,120p' "$FILE" | nl -ba | sed -n '1,120p'
# Show the drift-check block around the referenced lines
echo "---- drift block ----"
nl -ba "$FILE" | sed -n '90,140p'
# Confirm whether testify assert is imported anywhere
echo "---- assert import check ----"
rg -n 'github\.com/stretchr/testify/assert' "$FILE" || trueRepository: kalbasit/ncps
Length of output: 136
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="migrations/equivalence_test.go"
test -f "$FILE" || { echo "Missing $FILE"; exit 1; }
echo "---- file size ----"
wc -l "$FILE"
echo "---- imports (top) ----"
sed -n '1,140p' "$FILE" | cat -n | sed -n '1,140p'
echo "---- drift block (around 100-130) ----"
cat -n "$FILE" | sed -n '90,130p'
echo "---- t.Fatalf usage ----"
rg -n 't\.Fatalf\(' "$FILE" || true
echo "---- testify assert import ----"
rg -n 'github\.com/stretchr/testify/assert' "$FILE" || trueRepository: kalbasit/ncps
Length of output: 6791
🏁 Script executed:
rg -n 't\.Fatalf\(' migrations/equivalence_test.go
rg -n 'github\.com/stretchr/testify/assert' migrations/equivalence_test.goRepository: kalbasit/ncps
Length of output: 148
🏁 Script executed:
rg -n 't\.Fatalf\(' migrations/equivalence_test.go
rg -n 'github\.com/stretchr/testify/assert' migrations/equivalence_test.goRepository: kalbasit/ncps
Length of output: 148
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="migrations/equivalence_test.go"
echo "---- t.Fatal / t.Fatalf occurrences ----"
rg -n 't\.Fatalf?\(' "$FILE" || true
rg -n 't\.FailNow\(' "$FILE" || true
echo "---- testify assert usage ----"
rg -n 'testify/assert|github\.com/stretchr/testify/assert|\bassert\.' "$FILE" || trueRepository: kalbasit/ncps
Length of output: 220
Use testify assert for the non-error schema drift check
migrations/equivalence_test.go still uses t.Fatalf when len(diffFiles) > 0, and github.com/stretchr/testify/assert isn’t imported. Replace that t.Fatalf(...) with a testify assert (e.g., assert.Emptyf(t, diffFiles, ...)) and add the assert import.
🤖 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 `@migrations/equivalence_test.go` around lines 109 - 118, Replace the manual
failure check that uses t.Fatalf when diffFiles has entries with a testify
assertion: import "github.com/stretchr/testify/assert" and change the
t.Fatalf(...) call to assert.Emptyf(t, diffFiles, "schema drift detected for %s:
Atlas produced new migration file(s): %v", tc.dialect, diffFiles); keep the
existing diffFiles := setDiff(after, before) loop and logging, ensuring the new
import is added to the test file imports.
| ALTER TABLE `config` COLLATE utf8mb4_bin, MODIFY COLUMN `key` varchar(255) NOT NULL, MODIFY COLUMN `value` varchar(255) NOT NULL, MODIFY COLUMN `created_at` timestamp NULL DEFAULT (current_timestamp()), ADD UNIQUE INDEX `configentry_key` (`key`); | ||
| -- modify "pinned_closures" table | ||
| ALTER TABLE `pinned_closures` COLLATE utf8mb4_bin, MODIFY COLUMN `hash` varchar(255) NOT NULL, MODIFY COLUMN `created_at` timestamp NULL DEFAULT (current_timestamp()), ADD UNIQUE INDEX `pinnedclosure_hash` (`hash`); | ||
| -- modify "nar_files" table | ||
| ALTER TABLE `nar_files` COLLATE utf8mb4_bin, MODIFY COLUMN `hash` varchar(255) NOT NULL, MODIFY COLUMN `compression` varchar(255) NOT NULL DEFAULT '', MODIFY COLUMN `query` varchar(255) NOT NULL DEFAULT '', MODIFY COLUMN `created_at` timestamp NULL DEFAULT (current_timestamp()), MODIFY COLUMN `last_accessed_at` timestamp NULL, ADD UNIQUE INDEX `narfile_hash_compression_query` (`hash`, `compression`, `query`), ADD INDEX `narfile_last_accessed_at` (`last_accessed_at`); | ||
| -- modify "nar_file_chunks" table | ||
| ALTER TABLE `nar_file_chunks` COLLATE utf8mb4_bin, ADD COLUMN `id` bigint NOT NULL AUTO_INCREMENT, DROP PRIMARY KEY, ADD PRIMARY KEY (`id`), ADD INDEX `narfilechunk_chunk_id` (`chunk_id`), ADD UNIQUE INDEX `narfilechunk_nar_file_id_chunk_index` (`nar_file_id`, `chunk_index`), DROP FOREIGN KEY `nar_file_chunks_ibfk_1`, DROP FOREIGN KEY `nar_file_chunks_ibfk_2`, ADD CONSTRAINT `nar_file_chunks_chunks_nar_file_links` FOREIGN KEY (`chunk_id`) REFERENCES `chunks` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE, ADD CONSTRAINT `nar_file_chunks_nar_files_chunk_links` FOREIGN KEY (`nar_file_id`) REFERENCES `nar_files` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE; | ||
| -- modify "narinfos" table | ||
| ALTER TABLE `narinfos` COLLATE utf8mb4_bin, ADD CONSTRAINT `narinfos_file_size_nonneg` CHECK (`file_size` >= 0), ADD CONSTRAINT `narinfos_nar_size_nonneg` CHECK (`nar_size` >= 0), MODIFY COLUMN `hash` varchar(255) NOT NULL, MODIFY COLUMN `created_at` timestamp NULL DEFAULT (current_timestamp()), MODIFY COLUMN `last_accessed_at` timestamp NULL, MODIFY COLUMN `store_path` varchar(255) NULL, MODIFY COLUMN `url` varchar(255) NULL, MODIFY COLUMN `compression` varchar(255) NULL, MODIFY COLUMN `file_hash` varchar(255) NULL, MODIFY COLUMN `file_size` bigint NULL, MODIFY COLUMN `nar_hash` varchar(255) NULL, MODIFY COLUMN `nar_size` bigint NULL, MODIFY COLUMN `deriver` varchar(255) NULL, MODIFY COLUMN `system` varchar(255) NULL, MODIFY COLUMN `ca` varchar(255) NULL, ADD UNIQUE INDEX `narinfo_hash` (`hash`), ADD INDEX `narinfo_last_accessed_at` (`last_accessed_at`); | ||
| -- modify "narinfo_nar_files" table | ||
| ALTER TABLE `narinfo_nar_files` COLLATE utf8mb4_bin, ADD COLUMN `id` bigint NOT NULL AUTO_INCREMENT, DROP PRIMARY KEY, ADD PRIMARY KEY (`id`), ADD INDEX `narinfonarfile_narinfo_id` (`narinfo_id`), ADD UNIQUE INDEX `narinfonarfile_narinfo_id_nar_file_id` (`narinfo_id`, `nar_file_id`), ADD INDEX `narinfonarfile_nar_file_id` (`nar_file_id`), DROP FOREIGN KEY `fk_narinfo_nar_files_nar_file`, DROP FOREIGN KEY `fk_narinfo_nar_files_narinfo`, ADD CONSTRAINT `narinfo_nar_files_nar_files_nar_info_nar_files` FOREIGN KEY (`nar_file_id`) REFERENCES `nar_files` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE, ADD CONSTRAINT `narinfo_nar_files_narinfos_nar_info_nar_files` FOREIGN KEY (`narinfo_id`) REFERENCES `narinfos` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE; | ||
| -- modify "narinfo_references" table | ||
| ALTER TABLE `narinfo_references` COLLATE utf8mb4_bin, MODIFY COLUMN `reference` varchar(255) NOT NULL, ADD COLUMN `id` bigint NOT NULL AUTO_INCREMENT, DROP PRIMARY KEY, ADD PRIMARY KEY (`id`), ADD UNIQUE INDEX `narinforeference_narinfo_id_reference` (`narinfo_id`, `reference`), ADD INDEX `narinforeference_reference` (`reference`), DROP FOREIGN KEY `fk_narinfo_references_narinfo_id`, ADD CONSTRAINT `narinfo_references_narinfos_references` FOREIGN KEY (`narinfo_id`) REFERENCES `narinfos` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE; | ||
| -- modify "narinfo_signatures" table | ||
| ALTER TABLE `narinfo_signatures` COLLATE utf8mb4_bin, MODIFY COLUMN `signature` varchar(255) NOT NULL, ADD COLUMN `id` bigint NOT NULL AUTO_INCREMENT, DROP PRIMARY KEY, ADD PRIMARY KEY (`id`), ADD UNIQUE INDEX `narinfosignature_narinfo_id_signature` (`narinfo_id`, `signature`), ADD INDEX `narinfosignature_signature` (`signature`), DROP FOREIGN KEY `fk_narinfo_signatures_narinfo_id`, ADD CONSTRAINT `narinfo_signatures_narinfos_signatures` FOREIGN KEY (`narinfo_id`) REFERENCES `narinfos` (`id`) ON UPDATE RESTRICT ON DELETE CASCADE; |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="migrations/mysql/20260520212039_ent_baseline.sql"
if [ ! -f "$FILE" ]; then
echo "Missing $FILE" >&2
exit 1
fi
echo "== File head =="
head -n 60 "$FILE" | cat -n
echo "== File tail =="
tail -n 80 "$FILE" | cat -n
echo "== Extract Up/Down sections =="
# Try to locate markers commonly used by migration tools
rg -n "BEGIN|-- ?\(?Down\)?|-- ?\(?Up\)?|\bDown\b|\bUp\b|downgrade|upgrade|ROLLBACK|COMMIT" "$FILE" || true
# Print ALTER TABLE statements around the snippet lines
echo "== Narrowing ALTER TABLE statements =="
rg -n "ALTER TABLE" "$FILE" || true
echo "== Check for any preflight/cleanup logic =="
rg -n "(check|length|max|update|delete|trim|cleanup|sql_mode|strict|truncate)" "$FILE" || true
echo "== Check Down section types mentioned =="
# Grab relevant down casts/types if present
rg -n "varchar\\(255\\)|varchar\\(512\\)|\\btext\\b|store_path|nar_files|narinfos|config" "$FILE" || trueRepository: kalbasit/ncps
Length of output: 39746
Add data-length safety when narrowing column types in this migration
config.value:text→varchar(255)nar_files.query:varchar(512)→varchar(255)narinfos.ca,narinfos.deriver,narinfos.url,narinfos.store_path:text→varchar(255)
This migration performsALTER TABLE ... MODIFY COLUMN ...for these without any preflight length checks or cleanup, so it can truncate or fail on existing rows.
🤖 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 `@migrations/mysql/20260520212039_ent_baseline.sql` around lines 5 - 19, This
migration narrows several text/longer varchar columns to varchar(255)
(config.value, nar_files.query, narinfos.ca, narinfos.deriver, narinfos.url,
narinfos.store_path) without safety checks; before running each MODIFY COLUMN,
add a preflight step that queries MAX(CHAR_LENGTH(column)) for those columns and
either aborts the migration with a clear error if any rows exceed 255, or
performs a controlled cleanup step (e.g., UPDATE ... SET column =
LEFT(column,255) or move/backup offending rows to a staging table) and re-checks
length, then proceed with ALTER TABLE; update the migration SQL to include these
SELECT + conditional UPDATE/VERIFY steps and ensure the migration fails fast
with a clear message if automatic trimming is not desired.
| @@ -0,0 +1,103 @@ | |||
| -- +goose Up | |||
| -- modify "chunks" table | |||
| ALTER TABLE "chunks" ALTER COLUMN "hash" TYPE character varying, ALTER COLUMN "size" TYPE bigint, ALTER COLUMN "compressed_size" TYPE bigint, ALTER COLUMN "created_at" TYPE timestamptz; | |||
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
repo_root="$(pwd)"
echo "Repo root: $repo_root"
ls -la migrations/postgres | head
sed -n '1,120p' migrations/postgres/20260520213017_ent_baseline.sql
wc -l migrations/postgres/20260520213017_ent_baseline.sql
nl -ba migrations/postgres/20260520213017_ent_baseline.sql | sed -n '1,80p'Repository: kalbasit/ncps
Length of output: 11976
Make chunks.created_at conversions timezone-safe.
Line 3 changes chunks.created_at with an implicit timestamp → timestamptz cast, which depends on the session timezone; make it explicit with a USING clause. Mirror the same approach in the Down section to avoid the reverse conversion being session-dependent.
Suggested change
-ALTER TABLE "chunks" ALTER COLUMN "hash" TYPE character varying, ALTER COLUMN "size" TYPE bigint, ALTER COLUMN "compressed_size" TYPE bigint, ALTER COLUMN "created_at" TYPE timestamptz;
+ALTER TABLE "chunks"
+ ALTER COLUMN "hash" TYPE character varying,
+ ALTER COLUMN "size" TYPE bigint,
+ ALTER COLUMN "compressed_size" TYPE bigint,
+ ALTER COLUMN "created_at" TYPE timestamptz
+ USING "created_at" AT TIME ZONE 'UTC';🤖 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 `@migrations/postgres/20260520213017_ent_baseline.sql` at line 3, The ALTER on
table "chunks" currently changes "created_at" to timestamptz with an implicit
cast that depends on the session timezone; update the ALTER TABLE "chunks" ALTER
COLUMN "created_at" TYPE timestamptz statement to include an explicit USING
clause (e.g. USING created_at AT TIME ZONE 'UTC') so the conversion is
deterministic, and mirror the symmetric explicit USING clause in the Down
migration when converting back to timestamp without time zone (e.g. USING
created_at AT TIME ZONE 'UTC' to produce the target type) to avoid
session-dependent behavior.
| -- +goose Down | ||
| -- reverse: create index "pinnedclosure_hash" to table: "pinned_closures" | ||
| DROP INDEX `pinnedclosure_hash`; | ||
| -- reverse: create "new_pinned_closures" table | ||
| DROP TABLE `new_pinned_closures`; | ||
| -- reverse: create index "narfilechunk_chunk_id" to table: "nar_file_chunks" | ||
| DROP INDEX `narfilechunk_chunk_id`; | ||
| -- reverse: create index "narfilechunk_nar_file_id_chunk_index" to table: "nar_file_chunks" | ||
| DROP INDEX `narfilechunk_nar_file_id_chunk_index`; | ||
| -- reverse: create "new_nar_file_chunks" table | ||
| DROP TABLE `new_nar_file_chunks`; | ||
| -- reverse: create index "chunk_hash" to table: "chunks" | ||
| DROP INDEX `chunk_hash`; | ||
| -- reverse: create "new_chunks" table | ||
| DROP TABLE `new_chunks`; | ||
| -- reverse: create index "narfile_last_accessed_at" to table: "nar_files" | ||
| DROP INDEX `narfile_last_accessed_at`; | ||
| -- reverse: create index "narfile_hash_compression_query" to table: "nar_files" | ||
| DROP INDEX `narfile_hash_compression_query`; | ||
| -- reverse: create "new_nar_files" table | ||
| DROP TABLE `new_nar_files`; | ||
| -- reverse: create index "narinfosignature_signature" to table: "narinfo_signatures" | ||
| DROP INDEX `narinfosignature_signature`; | ||
| -- reverse: create index "narinfosignature_narinfo_id_signature" to table: "narinfo_signatures" | ||
| DROP INDEX `narinfosignature_narinfo_id_signature`; | ||
| -- reverse: create "new_narinfo_signatures" table | ||
| DROP TABLE `new_narinfo_signatures`; | ||
| -- reverse: create index "narinforeference_reference" to table: "narinfo_references" | ||
| DROP INDEX `narinforeference_reference`; | ||
| -- reverse: create index "narinforeference_narinfo_id_reference" to table: "narinfo_references" | ||
| DROP INDEX `narinforeference_narinfo_id_reference`; | ||
| -- reverse: create "new_narinfo_references" table | ||
| DROP TABLE `new_narinfo_references`; | ||
| -- reverse: create index "narinfonarfile_nar_file_id" to table: "narinfo_nar_files" | ||
| DROP INDEX `narinfonarfile_nar_file_id`; | ||
| -- reverse: create index "narinfonarfile_narinfo_id" to table: "narinfo_nar_files" | ||
| DROP INDEX `narinfonarfile_narinfo_id`; | ||
| -- reverse: create index "narinfonarfile_narinfo_id_nar_file_id" to table: "narinfo_nar_files" | ||
| DROP INDEX `narinfonarfile_narinfo_id_nar_file_id`; | ||
| -- reverse: create "new_narinfo_nar_files" table | ||
| DROP TABLE `new_narinfo_nar_files`; | ||
| -- reverse: create index "configentry_key" to table: "config" | ||
| DROP INDEX `configentry_key`; | ||
| -- reverse: create "new_config" table | ||
| DROP TABLE `new_config`; | ||
| -- reverse: create index "narinfo_last_accessed_at" to table: "narinfos" | ||
| DROP INDEX `narinfo_last_accessed_at`; | ||
| -- reverse: create index "narinfo_hash" to table: "narinfos" | ||
| DROP INDEX `narinfo_hash`; | ||
| -- reverse: create "new_narinfos" table | ||
| DROP TABLE `new_narinfos`; |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="migrations/sqlite/20260520212039_ent_baseline.sql"
if [ ! -f "$FILE" ]; then
echo "Missing file: $FILE" >&2
exit 1
fi
echo "== File: $FILE =="
echo "-- +goose Up context --"
sed -n '1,120p' "$FILE" | nl -ba | sed -n '1,120p'
echo
echo "-- +goose Down context --"
# Find the start of Down section and print a window through the end (or at least >220 lines)
LINE_DOWN=$(rg -n --fixed-string "-- +goose Down" "$FILE" | head -n1 | cut -d: -f1 || true)
if [ -z "${LINE_DOWN:-}" ]; then
echo "No '-- +goose Down' marker found" >&2
exit 1
fi
START=$((LINE_DOWN-20))
END=$((LINE_DOWN+220))
sed -n "${START},${END}p" "$FILE" | nl -ba | sed -n '1,260p'
echo
echo "== Sanity checks for new_* rename/drop usage in Down =="
# show rename statements in Up
echo "-- RENAME TO '...' occurrences --"
rg -n "RENAME TO" "$FILE"
# show any DROP TABLE 'new_*' in Down
echo "-- DROP TABLE `new_*` occurrences --"
rg -n "DROP TABLE `new_" "$FILE" || true
# show any DROP INDEX on canonical tables in Down
echo "-- DROP INDEX occurrences --"
rg -n "DROP INDEX" "$FILE"Repository: kalbasit/ncps
Length of output: 205
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="migrations/sqlite/20260520212039_ent_baseline.sql"
[ -f "$FILE" ] || { echo "Missing file: $FILE" >&2; exit 1; }
print_numbered() {
local start="$1" end="$2"
awk -v s="$start" -v e="$end" '{if(NR>=s && NR<=e) printf "%6d\t%s\n", NR, $0}' "$FILE"
}
echo "== File: $FILE =="
echo "-- +goose Up context --"
print_numbered 1 160
echo
echo "-- +goose Down context --"
LINE_DOWN=$(rg -n --fixed-string "-- +goose Down" "$FILE" | head -n1 | cut -d: -f1 || true)
[ -n "${LINE_DOWN:-}" ] || { echo "No '-- +goose Down' marker found" >&2; exit 1; }
START=$((LINE_DOWN-30))
END=$((LINE_DOWN+220))
print_numbered "$START" "$END"
echo
echo "== Sanity checks for new_* rename/drop usage in Down =="
echo "-- RENAME TO occurrences --"
rg -n "RENAME TO" "$FILE" || true
echo
echo "-- DROP TABLE `new_` occurrences --"
rg -n "DROP TABLE `new_" "$FILE" || true
echo
echo "-- Within Down: DROP TABLE or DROP INDEX on new_* --"
awk '
$0 ~ /-- \+goose Down/ {in_down=1}
in_down {
if($0 ~ /DROP (TABLE|INDEX) `new_/) print NR "\t" $0
if($0 ~ /-- \+goose Up/) in_down=0
}
' "$FILE" || trueRepository: kalbasit/ncps
Length of output: 12047
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="migrations/sqlite/20260520212039_ent_baseline.sql"
[ -f "$FILE" ] || { echo "Missing file: $FILE" >&2; exit 1; }
echo "== markers =="
rg -n --fixed-strings "-- +goose Down" "$FILE" || true
rg -n --fixed-strings "-- +goose Up" "$FILE" || true
echo
echo "== tail around provided range (160-260) =="
awk 'NR>=160 && NR<=260 {printf "%6d\t%s\n", NR, $0}' "$FILE"
echo
echo "== locate DOWN section boundaries =="
DOWN_START=$(rg -n --fixed-strings "-- +goose Down" "$FILE" | head -n1 | cut -d: -f1)
UP_START=$(rg -n --fixed-strings "-- +goose Up" "$FILE" | head -n1 | cut -d: -f1)
echo "UP_START=$UP_START"
echo "DOWN_START=$DOWN_START"
echo
echo "== Down content (from marker to end-of-file or 220 lines further) =="
awk -v s="$DOWN_START" 'NR>=s && NR<=s+220 {printf "%6d\t%s\n", NR, $0}' "$FILE"
echo
echo "== within Down: DROP TABLE new_* / DROP INDEX on canonical tables =="
awk '
$0 ~ /-- \+goose Down/ {in_down=1}
in_down {
if($0 ~ /DROP TABLE `new_/ || $0 ~ /DROP INDEX `.*`/ ) print NR "\t" $0
}
' "$FILE" || trueRepository: kalbasit/ncps
Length of output: 4923
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== Search for forward-only/down unsupported policy =="
rg -n "forward[- ]only|no down|Down.*intentionally|intentionally forward|migrate down|goose.*down" . || true
echo
echo "== Search for goose usage (migrate up/down) =="
rg -n "goose.*(up|down)|migrate.*(up|down)" . || true
echo
echo "== Search for goose configuration in CI/scripts =="
rg -n "GOOSE|goose" .github . 2>/dev/null | head -n 200 || trueRepository: kalbasit/ncps
Length of output: 46015
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== Search for forward-only/down unsupported policy =="
rg -n "forward[- ]only|no down|Down.*intentionally|intentionally forward|migrate down|goose.*down" . || true
echo
echo "== Search for goose usage (migrate up/down) =="
rg -n "goose.*(up|down)|migrate.*(up|down)" . || true
echo
echo "== Search for goose configuration in CI/scripts =="
rg -n "GOOSE|goose" .github . 2>/dev/null | head -n 200 || trueRepository: kalbasit/ncps
Length of output: 46015
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="migrations/postgres/20260520212038_postgres_serial_to_identity.sql"
[ -f "$FILE" ] || { echo "Missing file: $FILE" >&2; exit 1; }
echo "== tail around +goose Down =="
DOWN=$(awk '/-- \+goose Down/ {print NR; exit}' "$FILE" || true)
[ -n "${DOWN:-}" ] || { echo "No +goose Down marker found" >&2; exit 1; }
START=$((DOWN-20))
END=$((DOWN+40))
awk -v s="$START" -v e="$END" '{if(NR>=s && NR<=e) printf "%6d\t%s\n", NR, $0}' "$FILE"Repository: kalbasit/ncps
Length of output: 1593
Fix -- +goose Down in migrations/sqlite/20260520212039_ent_baseline.sql to be intentionally empty (forward-only)
-- +goose Uprenamesnew_*tables to canonical names, but-- +goose Downstill attempts to dropnew_*tables/indexes (e.g.,DROP TABLE \new_pinned_closures`,DROP TABLE `new_chunks`,DROP TABLE `new_narinfos``), so it would fail if ever executed.- Per design D10 (
ncps migrate downunsupported), thisDownsection should be replaced with an intentionally empty forward-only stub like other migrations.
🤖 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 `@migrations/sqlite/20260520212039_ent_baseline.sql` around lines 170 - 220,
The migration's -- +goose Down section incorrectly contains DROP INDEX/DROP
TABLE statements that reference the temporary new_* objects (e.g., DROP TABLE
`new_pinned_closures`, DROP TABLE `new_chunks`, DROP TABLE `new_narinfos`) which
will fail if run; replace the entire -- +goose Down block with an intentionally
empty forward-only stub (leave a comment or a no-op like "-- +goose Down\n--
no-op: forward-only migration") so the migration is explicitly marked as
non-reversible and does not attempt to drop the new_* tables/indexes.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1187 +/- ##
========================================
- Coverage 6.38% 5.04% -1.34%
========================================
Files 6 6
Lines 329 436 +107
========================================
+ Hits 21 22 +1
- Misses 304 410 +106
Partials 4 4 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
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.
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.
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 #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.
- parseSkip validates and normalises each dialect token, returning an error on unknown values (e.g. "myslq") instead of silently skipping nothing and running the dialect anyway. - --sql-only path now calls ensureAtlasSum after writing the stub so atlas.sum stays in sync when only empty stubs are generated. - Replace non-fatal assert.Len with require.Len in TestSQLOnlyEmitsThreeDialects so the test fails cleanly before indexing stamps[0..2] when fewer than 3 files are produced. - Wrap the one-time go build in a 60-second context instead of context.Background() to prevent an indefinite hang. Addresses PR #1187 (PRRT_kwDONV6tZs6EK6w5), PR #1185, PR #1241 (PRRT_kwDONV6tZs6EVhVP). Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…1251) ## Summary Consolidation branch addressing unresolved reviewer threads left open across merged PRs #1179–#1246. Each fix has its own atomic commit referencing the source PR and thread ID; all threads are resolved on GitHub after each change. ### Bug fixes - **cache:** touch `nar_file` by fetched row ID, not by narURL fields — `getNarFileFromDB` can return a `compression=none` fallback whose key differs from `narURL`, causing stale `last_accessed_at` and LRU regressions (#1206) - **cache:** fail fast on `nil` eager-loaded chunk edges in `streamCompleteChunks` and `streamProgressiveChunks` instead of silently `continue`-ing, which caused count mismatches or infinite re-streaming (#1207) - **cache:** include `narURLsToRemove` in the LRU early-return guard so orphaned `NarFile` blobs are passed to `parallelDeleteFromStores` instead of being silently leaked in storage (#1215) - **cache:** log a warning when LRU candidate fetch hits the `maxFetchRows` cap so operators know eviction scanned only a partial window (#1206) - **cache/relink:** lower `relinkBatchSize` from 500 → 499 to stay under SQLite's 999-placeholder limit (500 rows × 2 binds = 1000 > 999) (#1208) - **database:** close `*sql.DB` in `Open()` when `NewClient` fails (#1208) - **migrate/adopt:** use `ErrUnknownState` (not `ErrUnknownDialect`) for unrecognised `State` values — fixes false-positive `errors.Is` checks (#1188) - **generate-migrations:** `parseSkip` validates dialect names, returning an error on unknown values like `"myslq"` instead of silently skipping them (#1187) - **generate-migrations:** `--sql-only` path now calls `ensureAtlasSum` after writing the stub so `atlas.sum` stays in sync (#1187) - **generate-migrations:** `runDialect` now returns the generated file path and prints it to stdout; `main()` warns when a second boundary falls between dialect runs so callers know to re-run for a consistent timestamp set (#1215) - **generate-migrations:** add `"empty"` to `validateName` reject list (#1185) - **nix/ent-lint-check:** add `set -o pipefail` so `ent-lint | tee` propagates a non-zero exit through the pipeline (#1221) - **e2e:** fix docstring path (`var/ncps/e2e-results/` → `.e2e-results/`); `mc mb` and `redis-cli flushall` now use `check=True` so reset failures abort the test immediately (#1233) - **e2e:** `stop_ncps` now verifies the port closes within timeout; `wait_ready` exits early if the child process dies before becoming ready (#1233) - **run.py:** guard `dbmate` usage with a `shutil.which` check so a missing binary fails fast with a clear message instead of an obscure error (#1234) - **CI:** pin all external GitHub Action refs to immutable commit SHAs to prevent supply-chain mutation (#1223) - **CI:** remove `release-*` from pull_request/push triggers; add `go.mod` and `go.sum` to the ent paths-filter (#1235) - **docs:** replace distroless-incompatible `wget` healthcheck in Docker Compose example with `garage status` (#1223) ### Test fixes - Replace non-fatal `assert.Len` → `require.Len` before indexing `stamps[0..2]` in `generate-migrations` tests (#1185) - Add 60 s timeout to the one-time `go build` in the test setup (#1241) - Fix `cache_prefetch_test.go` to look up `nar_file` by `(hash, compression, query)` instead of hard-coded `id=1` (#1218) - Apply `NarSize` fallback when `FileSize == 0` in `testhelper/sqlite.go` to avoid impossible `file_size=0` fixture rows for `compression=none` narinfos (#1218) - Increase `chunkingDelay` from 500 ms → 1 s in `cdc_test.go` to reduce flakiness on slow CI machines (#1217) - Replace `Lock`-with-timeout with `TryLock` in `cache_distributed_test.go` to avoid spurious failures when the lock-hold window is tight (#1217) ### Docs / skills - Quote PostgreSQL DSNs in shell-command examples to prevent `?`-glob expansion by shells (#1234) - `migrate-new/SKILL.md`: ent-lint checks A1, A2, A4 — not all five invariants as previously stated (#1225) - `migrate-down/SKILL.md`: clarify that `DROP COLUMN` is sensitive/forbidden DDL per the migration spec and is only permissible as the terminal expand-contract step; add the missing "deploy code that always writes non-null" step to the NOT NULL recipe (#1225) - `openspec/changes/archive/2026-05-23-less-tests/`: fix stale paths, add `bash` fence tag, replace "branch coverage" with "statement/block coverage" (#1245) - `openspec/specs/test-suite-efficiency/spec.md`: same coverage terminology fix (#1245) - `openspec/changes/archive/2026-05-21-migrate-to-ent-and-atlas/design.md`: add language tag to decision-tree fence block; fix grammar (#1186) - `openspec/changes/archive/2026-05-21-migrate-to-ent-and-atlas/tasks.md`: update §10.1/§11.1 notes to reflect that `*database.Client` threading was completed in §11, not deferred (#1191, #1192) ## Test plan - [x] `nix flake check` (includes all unit + integration tests, lint, ent-lint, atlas-sum, helm-unittest, schema-equivalence) - [x] `go test -race ./...` locally with `eval "$(enable-integration-tests)"` - [x] Verify all referenced GitHub threads are marked resolved 🤖 Generated with [Claude Code](https://claude.ai/claude-code) --------- Co-authored-by: Claude Sonnet 4.6 <[email protected]>
Implements §8 of the migrate-to-ent-and-atlas change. Closes the gap
between the §7 translated dbmate-era migrations and Ent's expected
schema (§4) with a per-dialect bridge migration, and gates the
equivalence permanently via a CI-runnable test.
Bridge migrations (one per dialect, all sorted after the last
dbmate-era file):
migrations/sqlite/20260520212039_ent_baseline.sql (Atlas-auto):
the SQLite-canonical "recreate via temp table" pattern. Adds
surrogate id PKs on weak entities (D10b), renames indexes to Ents
naming convention (e.g. idx_narinfos_hash -> narinfo_hash), and
adds Ent's named CHECK constraints.
migrations/mysql/20260520212039_ent_baseline.sql (Atlas-auto):
ALTER TABLE ADD COLUMN id BIGINT AUTO_INCREMENT, DROP PRIMARY KEY,
ADD PRIMARY KEY (id), ADD UNIQUE INDEX on weak entities. Plus
MODIFY COLUMN to varchar(255) for hashes, bigint for chunk sizes
(signed; previously bigint unsigned), and FK constraint renames.
migrations/postgres/ — split into two files because Atlas's diff
engine refuses to compute the BIGSERIAL/IDENTITY reverse direction:
DROP DEFAULT + ADD GENERATED BY DEFAULT AS IDENTITY for each of
the five existing id-bearing tables, setval the new IDENTITY
sequence past max(id), drop the orphaned BIGSERIAL sequences.
The BIGSERIAL -> IDENTITY modernization is bundled here per
design D6 so v1 lands with modern Postgres conventions and
v1.x doesnt need a separate disruptive migration.
conversion file is in place so Atlas can compute the rest):
surrogate ids on weak entities, text -> varchar, integer ->
bigint, timestamp -> timestamptz, FK and CHECK constraint
renames.
Tooling:
a GooseDir, so the first run on a hand-translated directory
(per §7) bootstraps the integrity file. atlas.sum is committed
for all three dialects.
(sqlite,postgres,mysql), an escape hatch for the
two-file Postgres bridge approach.
Test:
load-bearing guarantee. Per dialect:
ephemeral PostgreSQL / MySQL database via testhelper-style
ephemeral-DB helpers added to the test file.
GooseFormatter, calls NamedDiff against migrate.Tables into
the temp dir.
replayed-from-migrations schema and Ents expected schema).
All three dialects pass.
Note for §13/CI: the Postgres test requires create_test_db function
to be installed in the dev test-db. The function is part of
nix/process-compose/postgres-dblink-create-drop-functions.sql which
runs as part of nix run .#deps init. If a deps instance is missing
the function (rare; happened once during this work after a deps
restart didnt complete init), re-run the SQL file as the postgres
superuser.
Tasks 8.1-8.5 of the migrate-to-ent-and-atlas change. 8.6
(TestSchemaCreateMatchesAppliedMigrations) and 8.7 (CI wiring)
remain for §9 and §13 respectively.
Summary by CodeRabbit
Release Notes
New Features
--skipflag to migration generation for excluding specific database dialects.Bug Fixes
Tests