Skip to content

test(dev-scripts): add e2e migration test orchestrator - #1233

Merged
kalbasit merged 3 commits into
mainfrom
test-dev-scripts-add-e2e
May 23, 2026
Merged

kalbasit merged 3 commits into
mainfrom
test-dev-scripts-add-e2e

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

dev-scripts/test-migration-e2e.py drives a main→current-branch
migration test across 12 scenarios (3 DBs × 2 CDC modes × 2 storage
backends). For each scenario it:

  1. Resets var/ncps + drops dev DBs + recreates the S3 bucket.
  2. Detaches HEAD at main, starts ncps via dev-scripts/run.py.
  3. Seeds the cache via dev-scripts/nix-isolated-build.py with two
    small Nix packages.
  4. Snapshots tables + narinfo hashes + pubkey.
  5. Switches back to the migration branch and runs
    go run . migrate up --dry-run then migrate up then
    --dry-run again, asserting idempotency.
  6. Snapshots again and verifies every pre-migration narinfo hash
    is still present.
  7. Restarts ncps on the migration branch and verifies the cache
    still serves a pre-existing entry (cache-hit) AND can accept a
    new write (write-path).

The detached-HEAD checkout avoids conflicting with the main worktree
in this repo. Per-scenario nix temp stores are routed onto the real
disk via TMPDIR=var/ncps/nix-tmp so a tmpfs /tmp can't exhaust the
test run after a handful of scenarios. Result logs land under
.e2e-results// which is now in .gitignore.

This was referenced May 22, 2026
@kalbasit
kalbasit force-pushed the test-dev-scripts-add-e2e branch from 679154c to 3c4ec51 Compare May 23, 2026 04:47
@kalbasit
kalbasit force-pushed the fix-dev-scripts-use-ncps-migrate branch from 01d7799 to 63c059d Compare May 23, 2026 04:49
@kalbasit
kalbasit force-pushed the test-dev-scripts-add-e2e branch from 3c4ec51 to c07f76f Compare May 23, 2026 04:49
@kalbasit
kalbasit force-pushed the fix-dev-scripts-use-ncps-migrate branch from 63c059d to 4e7fa24 Compare May 23, 2026 05:25
@kalbasit
kalbasit force-pushed the test-dev-scripts-add-e2e branch from c07f76f to e5e314f Compare May 23, 2026 05:25
@kalbasit
kalbasit force-pushed the fix-dev-scripts-use-ncps-migrate branch from 4e7fa24 to 574f4cf Compare May 23, 2026 05:29
@kalbasit
kalbasit force-pushed the test-dev-scripts-add-e2e branch from e5e314f to 4c76679 Compare May 23, 2026 05:29
@kalbasit
kalbasit force-pushed the fix-dev-scripts-use-ncps-migrate branch from 574f4cf to 77f5f1e Compare May 23, 2026 05:41
@kalbasit
kalbasit force-pushed the test-dev-scripts-add-e2e branch from 4c76679 to f8ce520 Compare May 23, 2026 05:41
@kalbasit
kalbasit force-pushed the fix-dev-scripts-use-ncps-migrate branch from 77f5f1e to 0aaee14 Compare May 23, 2026 05:53
@kalbasit
kalbasit force-pushed the test-dev-scripts-add-e2e branch from f8ce520 to 4529cae Compare May 23, 2026 05:53
@kalbasit
kalbasit force-pushed the fix-dev-scripts-use-ncps-migrate branch from 0aaee14 to efb1962 Compare May 23, 2026 06:06
@kalbasit

Copy link
Copy Markdown
Owner Author

Automated stack merge failed during the rebase step. The merge-stack label has been removed from all PRs in the stack. Please resolve conflicts locally, push, and re-apply the label on the top-most PR to retry. Run: https://github.com/kalbasit/ncps/actions/runs/26326665317

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 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 `@dev-scripts/test-migration-e2e.py`:
- Line 25: Update the module docstring that currently states "Results are
written to var/ncps/e2e-results/<timestamp>/." to reflect the real output
location ".e2e-results/<timestamp>/"; locate the top-level module docstring in
dev-scripts/test-migration-e2e.py (the file-level string) and change the path
text so it matches the actual directory used when the script writes results.
- Around line 488-501: The idempotency check currently logs a warning when the
dry-run output in dry2 (set by migrate_up with dry_run=True and stored to
result["stages"]["dry_run_after"]) lacks the "pending versions: N" line; change
this to fail closed by raising an exception instead of calling log when
re.search(r"pending versions:\s*(\d+)", dry2) returns None, so the harness
errors out (e.g., RuntimeError with a clear message referencing dry2) and
preserves the existing check that raises when int(m.group(1)) != 0.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0396fd32-2cb3-4191-b5ff-b65aa85563a5

📥 Commits

Reviewing files that changed from the base of the PR and between 4327e65 and 9c93d44.

📒 Files selected for processing (2)
  • .gitignore
  • dev-scripts/test-migration-e2e.py

Comment thread dev-scripts/test-migration-e2e.py Resolved
Comment thread dev-scripts/test-migration-e2e.py Resolved
Comment thread dev-scripts/test-migration-e2e.py Resolved
Comment thread dev-scripts/test-migration-e2e.py Resolved
kalbasit added 3 commits May 23, 2026 19:05
dev-scripts/test-migration-e2e.py drives a main→current-branch
migration test across 12 scenarios (3 DBs × 2 CDC modes × 2 storage
backends). For each scenario it:

  1. Resets var/ncps + drops dev DBs + recreates the S3 bucket.
  2. Detaches HEAD at main, starts ncps via dev-scripts/run.py.
  3. Seeds the cache via dev-scripts/nix-isolated-build.py with two
     small Nix packages.
  4. Snapshots tables + narinfo hashes + pubkey.
  5. Switches back to the migration branch and runs
     `go run . migrate up --dry-run` then `migrate up` then
     `--dry-run` again, asserting idempotency.
  6. Snapshots again and verifies every pre-migration narinfo hash
     is still present.
  7. Restarts ncps on the migration branch and verifies the cache
     still serves a pre-existing entry (cache-hit) AND can accept a
     new write (write-path).

The detached-HEAD checkout avoids conflicting with the main worktree
in this repo. Per-scenario nix temp stores are routed onto the real
disk via TMPDIR=var/ncps/nix-tmp so a tmpfs /tmp can't exhaust the
test run after a handful of scenarios. Result logs land under
.e2e-results/<timestamp>/ which is now in .gitignore.
The snapshot_db helpers swallowed sqlite3.Error / psycopg2.Error /
pymysql.MySQLError and returned partial data, which could mask
unreachable databases or schema problems and surface as a misleading
pass. Drop the broad excepts so a real DB error aborts the scenario,
and gate the narinfos lookup on the table existing in the discovered
table list — the only condition we genuinely want to tolerate is the
table not being present yet (e.g. baseline before migrations).
When the orchestrator detaches HEAD at main's commit, main's run.py
invokes bare `dbmate --no-dump-schema --url <url> up` (no
--migrations-dir flag). dbmate then defaults to ./db/migrations/,
but main's repo only holds per-dialect sub-dirs there
(db/migrations/{sqlite,postgres,mysql}/) — the historical
dbmate-wrapper used to inject the right one based on the URL scheme
and was deleted in 80c4a15 ("chore: delete sqlc + dbmate filesystem
and Nix references"). Without that wrapper, the bare `pkgs.dbmate`
restored to the dev shell errors with `no migration files found`
and run.py exits non-zero, failing the scenario before ncps even
starts.

start_ncps() now sets DBMATE_MIGRATIONS_DIR=<repo>/db/migrations/
<scenario.db> in the subprocess env. The variable matches dbmate's
own env-var name, so dbmate picks it up directly. The dialect names
align (sqlite/postgres/mysql), so the path is just
`scenario["db"]` joined into the sub-dir.

The env var is silently ignored when run.py-on-fix invokes
`ncps migrate up` instead of dbmate, so setting it unconditionally
in start_ncps is safe and keeps the helper straightforward.
Comment thread dev-scripts/test-migration-e2e.py Dismissed
Comment thread dev-scripts/test-migration-e2e.py Dismissed
Comment thread dev-scripts/test-migration-e2e.py Dismissed
Comment thread dev-scripts/test-migration-e2e.py Dismissed
Comment thread dev-scripts/test-migration-e2e.py Resolved
Comment thread dev-scripts/test-migration-e2e.py Resolved
Comment thread dev-scripts/test-migration-e2e.py Dismissed
Comment thread dev-scripts/test-migration-e2e.py Dismissed

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (3)
dev-scripts/test-migration-e2e.py (3)

488-501: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Make the idempotency assertion fail closed.

If the second dry-run stops emitting pending versions: N, this scenario can still pass without actually proving the post-migration invariant. That should be an error, not a warning.

Suggested fix
         import re
         m = re.search(r"pending versions:\s*(\d+)", dry2)
         if m is None:
-            log(f"WARN: dry-run output did not contain 'pending versions: N': {dry2!r}", Y)
+            raise RuntimeError(
+                "idempotency check failed: could not parse "
+                "'pending versions: N' from dry-run output"
+            )
         elif int(m.group(1)) != 0:
             raise RuntimeError(
                 f"idempotency check failed: {m.group(1)} migration(s) still "
                 f"pending after migrate up"
             )
🤖 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 `@dev-scripts/test-migration-e2e.py` around lines 488 - 501, The idempotency
check currently warns when the dry-run output (dry2, produced by migrate_up and
stored in result["stages"]["dry_run_after"]) does not contain the "pending
versions: N" line; change this to fail closed by raising an exception instead.
Locate the regex search (m = re.search(r"pending versions:\s*(\d+)", dry2)) and
replace the log warning branch (if m is None) with a RuntimeError (or similar)
that includes the dry-run output for diagnostics, keeping the existing behavior
that raises if int(m.group(1)) != 0.

136-183: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't let reset failures silently contaminate the next scenario.

These cleanup steps currently treat failed rmtree, dbmate, mc, and redis-cli calls as success. That can leave state behind and make the migration result for the next scenario meaningless. Fail closed here and only special-case the expected "already absent" cases.

🤖 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 `@dev-scripts/test-migration-e2e.py` around lines 136 - 183, The
reset_everything function currently ignores failures from shutil.rmtree and all
subprocess.run calls, allowing partial cleanup to silently pass; update
reset_everything to fail-fast: check shutil.rmtree result or use
os.path.exists(VAR_NCPS) -> try rmtree and on exception re-raise (except for
FileNotFoundError), and for each subprocess.run invocation (the dbmate calls
using DB_URLS[...], the mc rb/mb calls referencing S3 and parsed, and the
redis-cli flushall) set check=True or inspect returncode and raise a
RuntimeError unless the stderr/stdout indicates an expected "already absent"
condition (e.g., database/bucket not found); ensure error messages include the
command context (engine name, DB_URLS key, S3['bucket']) so reset_everything
fails loudly on real errors instead of contaminating the next scenario.

230-246: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Raise if shutdown never releases port 8501.

Right now a stuck listener only gets logged, so the next stage can talk to the old server or fail for the wrong reason.

Suggested fix
 def stop_ncps(p, f):
     if p.poll() is None:
         try:
             os.killpg(os.getpgid(p.pid), signal.SIGTERM)
@@
             except ProcessLookupError:
                 pass
             p.wait(timeout=5)
     f.close()
-    wait_port_close(PORT, timeout=15)
+    if not wait_port_close(PORT, timeout=15):
+        raise RuntimeError(f"ncps did not release port {PORT} after shutdown")
🤖 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 `@dev-scripts/test-migration-e2e.py` around lines 230 - 246, In stop_ncps,
after attempting SIGTERM then SIGKILL and calling wait_port_close(PORT,
timeout=15), detect if the port is still open and raise an exception instead of
only logging so the caller fails fast; update the stop_ncps function to call
wait_port_close and if it returns False (or port still open) raise a
RuntimeError (include PORT and process pid/context) so downstream stages cannot
accidentally talk to the old listener.
🤖 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 `@dev-scripts/test-migration-e2e.py`:
- Around line 249-261: The wait_ready function currently waits the full timeout
even if the spawned run.py process has already exited; update wait_ready to, on
each loop iteration, check the child process object used to start run.py (e.g.,
proc) for liveness/returncode and if it has exited, immediately log the child's
stderr/stdout or exit code and return False (or raise) so the test fails fast
with the real server log; modify wait_ready (and the other similar loops around
lines referenced) to accept or capture the child process object and use
proc.poll() / proc.returncode to detect early exit and surface logs instead of
sleeping until timeout.

---

Duplicate comments:
In `@dev-scripts/test-migration-e2e.py`:
- Around line 488-501: The idempotency check currently warns when the dry-run
output (dry2, produced by migrate_up and stored in
result["stages"]["dry_run_after"]) does not contain the "pending versions: N"
line; change this to fail closed by raising an exception instead. Locate the
regex search (m = re.search(r"pending versions:\s*(\d+)", dry2)) and replace the
log warning branch (if m is None) with a RuntimeError (or similar) that includes
the dry-run output for diagnostics, keeping the existing behavior that raises if
int(m.group(1)) != 0.
- Around line 136-183: The reset_everything function currently ignores failures
from shutil.rmtree and all subprocess.run calls, allowing partial cleanup to
silently pass; update reset_everything to fail-fast: check shutil.rmtree result
or use os.path.exists(VAR_NCPS) -> try rmtree and on exception re-raise (except
for FileNotFoundError), and for each subprocess.run invocation (the dbmate calls
using DB_URLS[...], the mc rb/mb calls referencing S3 and parsed, and the
redis-cli flushall) set check=True or inspect returncode and raise a
RuntimeError unless the stderr/stdout indicates an expected "already absent"
condition (e.g., database/bucket not found); ensure error messages include the
command context (engine name, DB_URLS key, S3['bucket']) so reset_everything
fails loudly on real errors instead of contaminating the next scenario.
- Around line 230-246: In stop_ncps, after attempting SIGTERM then SIGKILL and
calling wait_port_close(PORT, timeout=15), detect if the port is still open and
raise an exception instead of only logging so the caller fails fast; update the
stop_ncps function to call wait_port_close and if it returns False (or port
still open) raise a RuntimeError (include PORT and process pid/context) so
downstream stages cannot accidentally talk to the old listener.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 86854606-fc96-4c93-8759-9aa2d30492c9

📥 Commits

Reviewing files that changed from the base of the PR and between 9c93d44 and 8a67648.

📒 Files selected for processing (2)
  • .gitignore
  • dev-scripts/test-migration-e2e.py
✅ Files skipped from review due to trivial changes (1)
  • .gitignore

Comment thread dev-scripts/test-migration-e2e.py Resolved
@codecov

codecov Bot commented May 23, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 5.50%. Comparing base (2b8a6e2) to head (8a67648).

Additional details and impacted files
@@          Coverage Diff          @@
##            main   #1233   +/-   ##
=====================================
  Coverage   5.50%   5.50%           
=====================================
  Files          6       6           
  Lines        400     400           
=====================================
  Hits          22      22           
  Misses       374     374           
  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.

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

Labels

go Pull requests that update go code merge-stack size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants