diff --git a/ops/restack-verify/SPEC-REVIEW-EVIDENCE.md b/ops/restack-verify/SPEC-REVIEW-EVIDENCE.md new file mode 100644 index 000000000..5a5d212fe --- /dev/null +++ b/ops/restack-verify/SPEC-REVIEW-EVIDENCE.md @@ -0,0 +1,34 @@ +# PR #230 local verification + +Run from this PR checkout. Temporary-fixture checks, not deployed workload or independent signoff. + +The follow-up retains table-loss refusal because coherent lineage cannot prove +a removed table intentional. The diagnostic calls for semantic verification +rather than asserting every drop is a stale snapshot. No bypass was added. + +```text +$ python3 ops/restack-verify/test_checks.py +test_bindings_inapplicable_skips (__main__.RestackChecks) ... ok +test_bindings_missing_config_fails (__main__.RestackChecks) ... ok +test_bindings_missing_script_fails (__main__.RestackChecks) ... ok +test_bindings_passes_config_argument (__main__.RestackChecks) ... ok +test_bindings_propagates_checker_failure (__main__.RestackChecks) ... ok +test_broken_snapshot_chain_fails (__main__.RestackChecks) ... ok +test_clean_tracked_file_ignores_untracked_markers (__main__.RestackChecks) ... ok +test_empty_journal_passes (__main__.RestackChecks) ... ok +test_equal_or_out_of_order_timestamps_fail (__main__.RestackChecks) ... ok +test_git_error_fails (__main__.RestackChecks) ... ok +test_lockfile_conflicts_fail (__main__.RestackChecks) ... ok +test_missing_entries_fails (__main__.RestackChecks) ... ok +test_missing_sql_fails (__main__.RestackChecks) ... ok +test_orphan_sql_fails (__main__.RestackChecks) ... ok +test_table_loss_requires_semantic_verification (__main__.RestackChecks) ... ok +test_valid_lineage_passes (__main__.RestackChecks) ... ok + +---------------------------------------------------------------------- +Ran 16 tests in 0.421s + +OK + +exit_code=0 +``` diff --git a/ops/restack-verify/migration-journal.sh b/ops/restack-verify/migration-journal.sh new file mode 100755 index 000000000..6ec067f9d --- /dev/null +++ b/ops/restack-verify/migration-journal.sh @@ -0,0 +1,115 @@ +#!/bin/sh +# Verify a drizzle migration journal is internally coherent after a merge. +# +# Skips cleanly when the repo has no such journal — this flow is meant to be +# runnable in any checkout, and "not applicable" must not read as "failed". +set -eu +JOURNAL="packages/web/drizzle/meta/_journal.json" +if [ ! -f "$JOURNAL" ]; then + echo "RESTACK_VERIFY migration-journal: SKIPPED (no $JOURNAL)" + exit 0 +fi +python3 - "$JOURNAL" <<'PY' +import json, os, sys +p = sys.argv[1] +d = os.path.dirname(p) +sqldir = os.path.dirname(d) +j = json.load(open(p)) +if not isinstance(j, dict) or not isinstance(j.get("entries"), list): + print("RESTACK_VERIFY migration-journal: FAILED (entries must be a list)") + raise SystemExit(1) +entries = j["entries"] +tags = [e["tag"] for e in entries] +problems = [] + +dupes = sorted({t for t in tags if tags.count(t) > 1}) +if dupes: + problems.append(f"duplicate journal tags: {dupes}") + +missing = [t for t in tags if not os.path.exists(os.path.join(sqldir, f"{t}.sql"))] +if missing: + problems.append(f"journal entries with no .sql file: {missing}") + +on_disk = {f[:-4] for f in os.listdir(sqldir) if f.endswith(".sql")} +orphans = sorted(on_disk - set(tags)) +if orphans: + problems.append(f".sql files with no journal entry: {orphans}") + +# The tail must sort last. A renumbered migration whose `when` was not raised +# above the new base is the exact defect this catches -- drizzle selects by +# timestamp, never by filename. +whens = [e["when"] for e in entries] +if any(a >= b for a, b in zip(whens, whens[1:])): + problems.append("journal timestamps must be strictly increasing in entry order") + +# Validate lineage, then compare snapshot payloads. Lineage alone cannot tell a +# stale snapshot from an intentional drop, so the content comparison is what +# gives this gate teeth: drizzle snapshots are cumulative, so anything present +# in a predecessor and absent from its successor is either a deliberate removal +# or a snapshot that was rebuilt from the wrong base. Columns are compared as +# well as tables — the defect this gate was written for was a snapshot missing +# a single jsonb column, which a table-name comparison alone would have passed. +# +# A removal that is deliberate is recorded once in ACK_PATH, one +# `:` or `:
.` per line. +# Without that escape hatch a single legitimate DROP TABLE — or a RENAME, which +# drizzle snapshots as a drop plus a create — fails this gate on every future +# run forever, and a permanently red gate gets deleted rather than fixed. +ACK_PATH = "ops/restack-verify/intentional-drops.txt" +acknowledged = set() +if os.path.exists(ACK_PATH): + for raw in open(ACK_PATH): + line = raw.split("#", 1)[0].strip() + if line: + acknowledged.add(line) + +snaps = sorted(f for f in os.listdir(d) if f.endswith("_snapshot.json")) +previous = "00000000-0000-0000-0000-000000000000" +seen = set() +previous_tables = None +previous_columns = {} +for name in snaps: + snapshot = json.load(open(os.path.join(d, name))) + ident = snapshot.get("id") + if not isinstance(ident, str) or not ident or ident in seen: + problems.append(f"{name}: missing or duplicate snapshot id") + if snapshot.get("prevId") != previous: + problems.append(f"{name}: prevId does not match predecessor {previous}") + if isinstance(ident, str): + seen.add(ident) + previous = ident + tables = snapshot.get("tables") + if not isinstance(tables, dict): + problems.append(f"{name}: tables must be an object") + continue + columns = {} + for tname, tbody in tables.items(): + cols = tbody.get("columns") if isinstance(tbody, dict) else None + columns[tname] = set(cols) if isinstance(cols, dict) else set() + + if previous_tables is not None: + lost = [t for t in sorted(previous_tables - set(tables)) + if f"{name}:{t}" not in acknowledged] + if lost: + problems.append( + f"{name}: removed tables require semantic schema verification " + f"(intentional drop or stale snapshot): {lost}" + ) + for tname in sorted(set(tables) & previous_tables): + lost_cols = [c for c in sorted(previous_columns.get(tname, set()) - columns[tname]) + if f"{name}:{tname}.{c}" not in acknowledged] + if lost_cols: + problems.append( + f"{name}: table {tname} lost columns present in its predecessor " + f"(intentional drop or stale snapshot): {lost_cols}" + ) + previous_tables = set(tables) + previous_columns = columns + +if problems: + print("RESTACK_VERIFY migration-journal: FAILED") + for x in problems: + print(f" - {x}") + raise SystemExit(1) +print(f"RESTACK_VERIFY migration-journal: PASSED ({len(entries)} entries, tail {tags[-1] if tags else 'none'})") +PY diff --git a/ops/restack-verify/no-conflict-markers.sh b/ops/restack-verify/no-conflict-markers.sh new file mode 100755 index 000000000..c81d71cf5 --- /dev/null +++ b/ops/restack-verify/no-conflict-markers.sh @@ -0,0 +1,20 @@ +#!/bin/sh +# Check all tracked files, including lockfiles; untracked scratch is irrelevant. +set -eu +markers=$(mktemp) +trap 'rm -f "$markers"' EXIT HUP INT TERM +status=0 +git grep -n -e '^<<<<<<< ' -e '^>>>>>>> ' -- >"$markers" || status=$? +case "$status" in + 0) + echo "RESTACK_VERIFY no-conflict-markers: FAILED" + echo "tracked files still contain conflict markers:" + cat "$markers" + exit 1 + ;; + 1) echo "RESTACK_VERIFY no-conflict-markers: PASSED" ;; + *) + echo "RESTACK_VERIFY no-conflict-markers: FAILED (git grep exit $status)" >&2 + exit 1 + ;; +esac diff --git a/ops/restack-verify/test_checks.py b/ops/restack-verify/test_checks.py new file mode 100644 index 000000000..c7d863ed7 --- /dev/null +++ b/ops/restack-verify/test_checks.py @@ -0,0 +1,130 @@ +"""Black-box checks over temporary repositories; no cloud checkout required.""" +import json +from pathlib import Path +import subprocess +import tempfile +import unittest + +SCRIPTS = Path(__file__).resolve().parent +ZERO = '00000000-0000-0000-0000-000000000000' + + +class RestackChecks(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + + def write(self, path, content): + target = self.root / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content) + + def git(self, *args): + subprocess.run(['git', *args], cwd=self.root, check=True, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + + def check(self, script, code, text): + result = subprocess.run(['sh', str(SCRIPTS / (script + '.sh'))], + cwd=self.root, text=True, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + self.assertEqual(result.returncode, code, result.stdout) + self.assertIn(text, result.stdout) + + def journal(self, whens=(1, 2)): + entries = [dict(idx=i, tag=f'{i:04}_change', when=w) + for i, w in enumerate(whens)] + self.write('packages/web/drizzle/meta/_journal.json', + json.dumps(dict(entries=entries))) + for entry in entries: + self.write(f'packages/web/drizzle/{entry["tag"]}.sql', '-- migration\n') + return entries + + def snapshot(self, index, ident, previous, tables): + self.write(f'packages/web/drizzle/meta/{index:04}_snapshot.json', + json.dumps(dict(id=ident, prevId=previous, tables=tables))) + + def test_git_error_fails(self): + self.check('no-conflict-markers', 1, 'git grep exit 128') + + def test_clean_tracked_file_ignores_untracked_markers(self): + self.git('init', '-q') + self.write('source.txt', 'clean\n') + self.git('add', 'source.txt') + self.write('scratch.txt', '<<<<<<< scratch\n') + self.check('no-conflict-markers', 0, 'PASSED') + + def test_lockfile_conflicts_fail(self): + self.git('init', '-q') + self.write('package-lock.json', '<<<<<<< HEAD\n') + self.git('add', 'package-lock.json') + self.check('no-conflict-markers', 1, 'package-lock.json:1:') + + def test_missing_entries_fails(self): + self.write('packages/web/drizzle/meta/_journal.json', '{}') + self.check('migration-journal', 1, 'entries must be a list') + + def test_empty_journal_passes(self): + self.journal(()) + self.check('migration-journal', 0, 'PASSED (0 entries') + + def test_broken_snapshot_chain_fails(self): + self.journal() + self.snapshot(0, 'a', ZERO, {'users': {}}) + self.snapshot(1, 'b', 'wrong', {'users': {}}) + self.check('migration-journal', 1, 'prevId does not match predecessor a') + + def test_table_loss_requires_semantic_verification(self): + self.journal() + self.snapshot(0, 'a', ZERO, {'users': {}, 'old': {}}) + self.snapshot(1, 'b', 'a', {'users': {}}) + self.check('migration-journal', 1, 'intentional drop or stale snapshot') + + def test_valid_lineage_passes(self): + self.journal() + self.snapshot(0, 'a', ZERO, {'users': {}}) + self.snapshot(1, 'b', 'a', {'users': {}, 'new': {}}) + self.check('migration-journal', 0, 'PASSED') + + def test_equal_or_out_of_order_timestamps_fail(self): + for whens in [(1, 1), (2, 1, 3)]: + with self.subTest(whens=whens): + self.journal(whens) + self.check('migration-journal', 1, 'strictly increasing') + + def test_missing_sql_fails(self): + self.journal() + (self.root / 'packages/web/drizzle/0001_change.sql').unlink() + self.check('migration-journal', 1, 'no .sql file') + + def test_orphan_sql_fails(self): + self.journal() + self.write('packages/web/drizzle/orphan.sql', '-- orphan\n') + self.check('migration-journal', 1, 'no journal entry') + + def test_bindings_inapplicable_skips(self): + self.check('worker-bindings', 0, 'SKIPPED') + + def test_bindings_missing_config_fails(self): + self.write('scripts/verify-fast-path-bindings.mjs', 'process.exit(0)') + self.check('worker-bindings', 1, 'missing packages/web/wrangler.production.toml') + + def test_bindings_missing_script_fails(self): + self.write('packages/web/wrangler.production.toml', '') + self.check('worker-bindings', 1, 'missing scripts/verify-fast-path-bindings.mjs') + + def test_bindings_propagates_checker_failure(self): + self.write('packages/web/wrangler.production.toml', '') + self.write('scripts/verify-fast-path-bindings.mjs', 'process.exit(1)') + self.check('worker-bindings', 1, 'FAILED') + + def test_bindings_passes_config_argument(self): + self.write('packages/web/wrangler.production.toml', '') + self.write('scripts/verify-fast-path-bindings.mjs', + 'process.exit(process.argv.slice(2).join(" ") === ' + '"--wrangler-config packages/web/wrangler.production.toml" ? 0 : 1)') + self.check('worker-bindings', 0, 'PASSED') + + +if __name__ == '__main__': + unittest.main(verbosity=2) diff --git a/ops/restack-verify/worker-bindings.sh b/ops/restack-verify/worker-bindings.sh new file mode 100755 index 000000000..1b2ac9bf4 --- /dev/null +++ b/ops/restack-verify/worker-bindings.sh @@ -0,0 +1,25 @@ +#!/bin/sh +# Run the repo's own worker-binding gate, if it has one. +# +# Does not reimplement the check. The point of a restack gate is to re-run the +# checks the repo already trusts, because a merge can invalidate them without +# producing a conflict. +set -eu +SCRIPT="scripts/verify-fast-path-bindings.mjs" +CONFIG="packages/web/wrangler.production.toml" +if [ ! -f "$SCRIPT" ] && [ ! -f "$CONFIG" ]; then + echo "RESTACK_VERIFY worker-bindings: SKIPPED (no $SCRIPT or $CONFIG)" + exit 0 +fi +for required in "$SCRIPT" "$CONFIG"; do + if [ ! -f "$required" ]; then + echo "RESTACK_VERIFY worker-bindings: FAILED (missing $required)" >&2 + exit 1 + fi +done +if node "$SCRIPT" --wrangler-config "$CONFIG"; then + echo "RESTACK_VERIFY worker-bindings: PASSED" +else + echo "RESTACK_VERIFY worker-bindings: FAILED" + exit 1 +fi diff --git a/workflows/restack-verify.yaml b/workflows/restack-verify.yaml new file mode 100644 index 000000000..5fc8a535e --- /dev/null +++ b/workflows/restack-verify.yaml @@ -0,0 +1,66 @@ +# Restack-verify — the deterministic gate that runs after merging the base +# branch into a long-lived feature branch. +# +# Provenance: on 2026-09-07 this exact sequence was hand-driven EIGHT times +# against cloud#3270 across a single evening. Every step below is a check that +# was typed out by hand, repeatedly, and three of the defects found that night +# were introduced BY a restack and existed in neither parent: +# +# - a renumbered migration whose cumulative snapshot still described its old +# position (87 tables where the base had 90) +# - a policy file whose emptied exemption list was silently re-populated from +# the stale side of the merge +# - a test from the base branch meeting a guard from the feature branch, so +# that neither side was wrong and the combination was +# +# None of those produce a conflict marker. That is the point of this flow: a +# clean `git merge` is not evidence, and the checks that catch these are +# mechanical, so a human should not be running them from memory eight times. +# +# Usage from a repo checkout, after merging your base branch: +# +# flows run workflows/restack-verify.yaml +# +# Exit 0 = these structural checks passed or were inapplicable. +# Table loss fails pending semantic schema verification; this does not prove +# SQL/schema equivalence or run the target repo test suites. +# Non-zero = one named check failed. +# +# Gate: exit_code == 0 is implicit for deterministic steps; each runner exits +# non-zero on its own failure. No output_contains gate is layered on top — +# a substring match on a diff-derived body is fail-open, per the reasoning +# already recorded in workflows/preswarm-check.yaml. + +version: '0.1.0' +name: restack-verify +description: > + Verify a just-merged base branch did not silently break the feature branch: + no leftover conflict markers, migration journal still coherent, worker env + bindings still accounted for. Run the target repo test suites separately. + +steps: + - id: no-conflict-markers + type: deterministic + dependsOn: [] + timeoutMs: 120000 + # Cheapest possible check, and it must run first: every later result is + # meaningless if a marker is sitting in a tracked file. + command: "sh ops/restack-verify/no-conflict-markers.sh" + + - id: migration-journal + type: deterministic + dependsOn: [no-conflict-markers] + timeoutMs: 300000 + # Checks duplicate tags, orphaned .sql files, snapshot lineage, and + # strictly increasing migration timestamps. Table loss blocks until semantic + # verification distinguishes an intentional drop from a stale snapshot. + command: "sh ops/restack-verify/migration-journal.sh" + + - id: worker-bindings + type: deterministic + dependsOn: [no-conflict-markers] + timeoutMs: 300000 + # Catches the class where the merge adds an env binding that the + # deploy-time config does not declare. Skips cleanly in repos that have no + # such gate rather than failing them. + command: "sh ops/restack-verify/worker-bindings.sh"