Files
absdev-deployment/evidence/combined-qualification/migration-test.py

485 lines
26 KiB
Python

import hashlib
import json
import os
import signal
import shutil
import subprocess
import sys
import time
from datetime import datetime,timedelta,timezone
import secrets
from pathlib import Path
ROOT=Path.cwd()
REPO=ROOT/"framework"
sys.path.insert(0,str(REPO))
import db_tools as fixture
from db_tools import cmd, good, record, require, DOCKER, PASSWORDS
from core.approval import issue_approval
from core.backup import BackupEngine
from core.compatibility import canonical_hash
from core.database import get_adapter
from core.database_identity import DatabaseIdentityProbe
from core.deployment import DeploymentController, DeploymentError
from core.dev3.operations import SiteOperations
from core.execution import CommandRunner
from core.locking import LockError
from core.migration import MigrationCoordinator, MigrationError
from core.migration_recovery import MigrationRecovery, MigrationRecoveryError
from core.migration_archive import MigrationArchive
from core.trusted_rehearsal import TrustedRehearsal
from core.operator_approval import OperatorApprovalPolicy, OperatorGrant
from core.releases import ReleaseManager
from core.transactions import TransactionError, TransactionJournal
REVISION="84a7a5b23796b15cab830034aae256b9414e9693"
fixture.EXPECTED=REVISION
fixture.REPO=REPO
MIGRATION="2026_11_28_000001_recovery_probe"
BASE="2026_01_01_000000_create_fixture"
SITE="absdev-migration-lab"
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def write(name,data):
(ROOT/name).write_text(json.dumps(data,indent=2,sort_keys=True)+"\n")
def exercise(name):
fixture.ready("postgres",name,"postgres")
admin=fixture.connect("postgres",name,"admin","postgres")
good(admin,"CREATE DATABASE fixture;")
database=fixture.connect("postgres",name,"admin")
for account in ("migration_user","backup_user"):
good(database,f"CREATE ROLE {account} LOGIN PASSWORD '{PASSWORDS[account]}';")
good(database,f"""
REVOKE CONNECT, TEMPORARY ON DATABASE fixture FROM PUBLIC;
GRANT CONNECT ON DATABASE fixture TO migration_user,backup_user;
CREATE SCHEMA work AUTHORIZATION migration_user;
GRANT USAGE ON SCHEMA work TO backup_user;
ALTER DEFAULT PRIVILEGES FOR ROLE migration_user IN SCHEMA work GRANT SELECT ON TABLES TO backup_user;
REVOKE ALL ON FUNCTION pg_catalog.pg_control_system() FROM PUBLIC;
GRANT EXECUTE ON FUNCTION pg_catalog.pg_control_system() TO backup_user,migration_user;
""")
migration=fixture.connect("postgres",name,"migration_user")
good(migration,f"""
CREATE TABLE work.migrations(name TEXT PRIMARY KEY);
INSERT INTO work.migrations VALUES ('{BASE}');
CREATE TABLE work.items(id INT PRIMARY KEY, label TEXT);
INSERT INTO work.items VALUES (1,'original');
""")
server=good(database,"SELECT system_identifier FROM pg_control_system();")
pgpass="".join(f"127.0.0.1:5432:fixture:{role}:{PASSWORDS[role]}\n"
for role in ("backup_user","migration_user"))
good((*DOCKER,"exec","-i",name,"sh","-c","umask 077; mkdir -p /run/secrets; cat >/run/secrets/absdev-pgpass"),pgpass)
config=json.loads((REPO/"config/site.example.json").read_text())
config["database"].update(driver="pgsql",container=name,host="127.0.0.1",port=5432,name="fixture",username="backup_user")
backup_adapter=get_adapter(config)
config["database"]["username"]="migration_user"
migration_adapter=get_adapter(config)
commands=[backup_adapter.live_identity_command(),backup_adapter.backup_command(),migration_adapter.live_identity_command()]
runner=CommandRunner([["sudo","-n",*args] for args in commands],timeout=50)
def run(args,out):
runner(["sudo","-n",*args],out)
backup_probe=DatabaseIdentityProbe(backup_adapter,run,server_id=server)
identity=DatabaseIdentityProbe(migration_adapter,run,server_id=server)
db_identity=canonical_hash(identity.observe())
backup_dir=ROOT/"backups"
backup_dir.mkdir()
backup=BackupEngine(backup_adapter,backup_dir,run,live_identity=backup_probe)
artifact=backup.create()
manifest=backup.verify(artifact)
require(backup_probe(),"Backup identity not verified")
write("backup-manifest.json",manifest)
record("postgres","real transactionally consistent PostgreSQL backup verified","PASS",manifest["sha256"])
scratch="isolated_restore_migration_ci"
rehearsal_id=canonical_hash({"database":scratch,"cluster":server})
app=ROOT/"app"
versions={}
for version in ("1","2","3"):
p=app/"releases"/version
(p/"vendor").mkdir(parents=True)
(p/"public/build").mkdir(parents=True)
(p/"vendor/autoload.php").write_text("<?php\n")
(p/"public/build/manifest.json").write_text("{}\n")
(p/"public/index.php").write_text("release="+version+"\n")
rev=hashlib.sha1(("fixture release "+version).encode()).hexdigest()
(p/"REVISION").write_text(rev+"\n")
versions[version]={"revision":rev,"fingerprint":digest(p/"public/index.php")}
releases=ReleaseManager(app)
releases.activate("2")
now=lambda:datetime.now(timezone.utc)
grants=[OperatorGrant(os.geteuid(),"ci-fixture-operator",operation,SITE,
versions["3"]["revision"],now()+timedelta(hours=1))
for operation in ("issue","execute","reconcile")]
policy=OperatorApprovalPolicy(grants,sealing_key=secrets.token_bytes(32))
def trusted_runner(context):
require(context["revision"]==versions["3"]["revision"],"Unapproved rehearsal revision")
good(admin,"CREATE DATABASE "+scratch+";")
# Database dump and rehearsal are confined to this one disposable cluster.
result=subprocess.run((*DOCKER,"exec","-i",name,"pg_restore","-U","postgres","-d",scratch,
"--no-owner","--no-privileges","--exit-on-error","--single-transaction"),
input=(artifact/"database.dump").read_bytes(),capture_output=True,timeout=60)
require(result.returncode==0,"Disposable rehearsal restore failed")
rehearsed=fixture.connect("postgres",name,"admin",scratch)
require(good(rehearsed,"SELECT label FROM work.items;")=="original","Restored data invalid")
good(rehearsed,f"""
BEGIN;
CREATE TABLE work.committed_prefix(id INT);
CREATE TABLE work.interrupted_step(id INT);
INSERT INTO work.migrations VALUES ('{MIGRATION}');
COMMIT;
""")
require(good(rehearsed,"SELECT name FROM work.migrations ORDER BY name;").splitlines()==[BASE,MIGRATION],
"Rehearsal migration history not verified")
good(admin,"DROP DATABASE "+scratch+";")
require(not good(admin,f"SELECT 1 FROM pg_database WHERE datname='{scratch}';"),"Rehearsal cleanup failed")
record("postgres","restored backup to a separate disposable database and rehearsed both migration steps","PASS")
return {"driver":"postgresql","source_database":"fixture","target_database":scratch,
"target_identity":rehearsal_id,"applied_migrations":[MIGRATION],
"checks":{key:True for key in ("isolation_verified","backup_restored","migration_succeeded",
"migration_history_verified","application_verified","cleanup_verified")}}
trusted=TrustedRehearsal("absdev-ci-reconciliation",trusted_runner,key=secrets.token_bytes(32),clock=now)
ops=SiteOperations(ROOT,operator_policy=lambda:policy,trusted_rehearsal=trusted)
ordinary=ops.journal.create(site=SITE,previous="1",candidate="2",
revision=versions["2"]["revision"],provenance=versions["2"]["fingerprint"],
previous_revision=versions["1"]["revision"],previous_provenance=versions["1"]["fingerprint"])
ordinary_bytes=ops.journal.path.read_bytes()
ordinary_hash=digest(ops.journal.path)
(ROOT/"ordinary-before.json").write_bytes(ordinary_bytes)
active_before=(os.readlink(app/"current"),digest(app/"current/public/index.php"))
def history():
return good(migration,"SELECT name FROM work.migrations ORDER BY name;").splitlines()
def base_context():
candidate=versions["3"]
return {"site":SITE,"release":"3","revision":candidate["revision"],
"provenance":candidate["fingerprint"],"compatibility":canonical_hash({"fixture":"additive"}),
"database_identity":canonical_hash(identity.observe()),"backup_sha256":backup.verify(artifact)["sha256"],
"pending_migrations":[MIGRATION]}
base=base_context()
require(base["database_identity"]==db_identity,"Live identity changed")
rehearsal=trusted.run(base)
ctx=trusted.approval_context(rehearsal,base,now=now())
approval=issue_approval(ctx,approver="ci-fixture-operator",now=now())
identifier=approval["approval_id"]
ops.approvals.save(approval,ctx,rehearsal=rehearsal,confirmation=approval["confirmation"],now=now())
write("rehearsal.json",rehearsal)
gate=ROOT/"containment.closed"
def contain():
with gate.open("w") as handle:
handle.write("maintenance\n")
handle.flush()
os.fsync(handle.fileno())
return True
def contained():
return gate.is_file()
backup_ok=lambda:backup.verify(artifact)["sha256"]==manifest["sha256"]
appname="absdev_fixture_interruption"
def interrupted_migration(pending):
require(pending==(MIGRATION,),"Unexpected inventory")
db=list(migration)
e=db.index("exec")+2
db[e:e]=["-e","PGAPPNAME="+appname]
return cmd(tuple(db),f"""
CREATE TABLE work.committed_prefix(id INT);
BEGIN;
CREATE TABLE work.interrupted_step(id INT);
INSERT INTO work.migrations VALUES ('{MIGRATION}');
SELECT pg_sleep(120);
COMMIT;
""",timeout=135).returncode
def original_probe():
current=releases.current()
return {"release":current,**versions[current]}
coordinator=MigrationCoordinator(store=ops.approvals,lock_path=ops.lock_path,journal=ops.journal,
original_release_probe=original_probe,context_probe=base_context,
contain=contain,containment_probe=contained,backup_probe=backup_ok,history_probe=history,
migration_runner=interrupted_migration,application_probe=lambda:False,clock=now)
child=os.fork()
if child==0:
try:
coordinator.execute(identifier,rehearsal,confirmation=approval["confirmation"])
finally:
os._exit(91)
backend=None
try:
for _ in range(80):
backend=good(database,f"SELECT pid FROM pg_stat_activity WHERE application_name='{appname}' AND wait_event='PgSleep';")
if backend.isdigit():
break
time.sleep(.25)
require(backend and backend.isdigit(),"The migration did not reach the in-flight transaction")
require(good(database,"SELECT to_regclass('work.committed_prefix');")=="work.committed_prefix",
"First migration step did not commit")
require(ops.approvals.consumed_path(identifier).exists() and coordinator.intent_path(identifier).exists(),
"Approval/intent was not durable before execution")
try:
with ops.lock():
raise RuntimeError("Ordinary operation acquired the migration lock")
except LockError:
record("framework","live migration excluded a competing site operation","PASS")
os.kill(child,signal.SIGKILL)
_,status=os.waitpid(child,0)
child=None
require(os.waitstatus_to_exitcode(status)==-signal.SIGKILL,"Coordinator did not exit abruptly")
require(good(database,f"SELECT pg_terminate_backend({int(backend)});")=="t","Backend termination failed")
record("postgres","abruptly stopped coordinator and interrupted an in-flight PostgreSQL transaction","PASS")
finally:
if child is not None:
try:
os.kill(child,signal.SIGKILL)
except ProcessLookupError:
pass
os.waitpid(child,0)
require(history()==[BASE] and good(database,"SELECT to_regclass('work.interrupted_step');")=="" and
good(database,"SELECT to_regclass('work.committed_prefix');")=="work.committed_prefix",
"Unexpected committed or transactional state after interruption")
require(not coordinator.result_path(identifier).exists() and contained(),
"Interrupted migration did not stay contained without a result")
record("postgres","interrupted transaction rolled back, committed prefix survives, migration history unchanged","PASS")
activation_calls=[]
def forbid(*args):
activation_calls.append(str(args))
raise RuntimeError("Unexpected activation or reopening")
def reviewed_probe(context, intent, history_after):
prefix=good(database,"SELECT 'work.committed_prefix'::regclass::oid;")
suffix=good(database,"SELECT 'work.interrupted_step'::regclass::oid;")
require(prefix.isdigit() and suffix.isdigit() and good(database,"SELECT label FROM work.items;")=="original",
"Reconciled fixture schema and source data not verified")
return canonical_hash({"prefix":prefix,"suffix":suffix,"history":history_after,
"revision":context["revision"],"intent":intent["checksum"]})
recovery=MigrationRecovery(reconciliation_probe=reviewed_probe,site=SITE,store=ops.approvals,lock_path=ops.lock_path,
identity_probe=lambda:canonical_hash(identity.observe()),history_probe=history,
provenance_probe=lambda release:versions[release],backup_probe=backup_ok,contain=contain,
containment_probe=contained,current_probe=releases.current,activate=forbid,refresh=forbid,
readiness_probe=forbid,release_containment=forbid,writes_enabled_probe=forbid,health_probe=forbid)
for action in (lambda:recovery.inspect(identifier),
lambda:recovery.execute(identifier,confirmation="ACTIVATE-"+identifier,fingerprint="0"*64)):
try:
action()
except MigrationRecoveryError:
pass
else:
raise RuntimeError("Interrupted migration allowed forward activation")
require(not activation_calls,"Recovery touched release or runtime")
record("framework","restart inspection and activation refuse incomplete migration evidence","PASS")
try:
coordinator.execute(identifier,rehearsal,confirmation=approval["confirmation"])
except MigrationError:
pass
else:
raise RuntimeError("Consumed migration replayed")
record("framework","interrupted migration approval could not be replayed","PASS")
controller=DeploymentController(**ops.common(),site=SITE,releases=releases,provenance=None,
backup=None,services=None,health=None,runtime_check=forbid,stopped_check=contained,
operation_guard=ops.guard)
try:
controller.deploy("3")
except DeploymentError:
pass
else:
raise RuntimeError("Ordinary deployment escaped unfinished migration guard")
require(not activation_calls and ops.guard.inspect()["status"]=="BLOCKED","Ordinary guard failed")
(ROOT/"ordinary-after.json").write_bytes(ops.journal.path.read_bytes())
require(ops.journal.path.read_bytes()==ordinary_bytes and digest(ops.journal.path)==ordinary_hash,
"Standard interrupted migration flow changed the ordinary journal")
require((os.readlink(app/"current"),digest(app/"current/public/index.php"))==active_before,
"Standard interrupted migration flow changed the original release")
record("framework","standard paths left original release and ordinary journal byte-for-byte intact","PASS",
{"release":releases.current(),"journal_sha256":ordinary_hash})
for label,path in (("migration-intent.json",coordinator.intent_path(identifier)),
("approval-consumed.json",ops.approvals.consumed_path(identifier))):
(ROOT/label).write_bytes(path.read_bytes())
reopened=TransactionJournal(ops.journal.directory)
try:
reopened.transition(ordinary["transaction_id"],"PREPARED","FAILED")
except TransactionError as error:
require("blocked by migration" in str(error),"Unexpected journal error")
else:
raise RuntimeError("Direct ordinary journal writer bypassed the guard")
require(reopened.path.read_bytes()==ordinary_bytes,"Direct writer changed original journal")
(ROOT/"direct-writer-probe.json").write_bytes(reopened.path.read_bytes())
record("framework","reopened ordinary journal denies direct transition during unfinished migration","PASS")
fresh=ROOT/"empty-ordinary-site"
fresh.mkdir()
independent=SiteOperations(fresh)
shutil.copyfile(coordinator.intent_path(identifier),independent.approvals.directory/"interrupted.json")
try:
TransactionJournal(independent.journal.directory).create(
SITE,"1","2",versions["2"]["revision"],versions["2"]["fingerprint"])
except TransactionError as error:
require("blocked by migration" in str(error),"Unexpected journal creation error")
else:
raise RuntimeError("Direct creation bypassed unfinished migration guard")
require(not independent.journal.path.exists(),"Rejected creation published journal data")
record("framework","bound journal also rejects direct creation while migration is unfinished","PASS")
intent=json.loads((ROOT/"migration-intent.json").read_text())
bound={"release":intent["original_release"],"revision":intent["original_revision"],
"fingerprint":intent["original_provenance"]}
require(bound=={"release":"2",**versions["2"]} and original_probe()==bound,
"Durable migration intent failed original release checks")
require(intent["checksum"]==canonical_hash({k:v for k,v in intent.items() if k!="checksum"}),
"Original release binding is outside the intent checksum")
record("framework","durable migration intent binds original release, revision and provenance","PASS",bound)
def observed_state():
return {"active_release":releases.current(),"history":history(),
"prefix_oid":good(database,"SELECT 'work.committed_prefix'::regclass::oid;"),
"suffix_exists":bool(good(database,"SELECT to_regclass('work.interrupted_step');")),
"journal_sha256":digest(ops.journal.path),
"contained":contained()}
operator="ci-fixture-operator"
try:
recovery.plan_reconciliation(identifier,operator=operator)
except MigrationRecoveryError:
pass
else:
raise RuntimeError("Incomplete database allowed reconciliation")
record("framework","incomplete history cannot produce a reconciliation proposal","PASS")
before=observed_state()
require(before["active_release"]=="2" and before["history"]==[BASE]
and not before["suffix_exists"] and before["contained"],"Unexpected review input")
plan={"operation":"complete only interrupted suffix in disposable fixture",
"intent_checksum":intent["checksum"],"before":before}
confirmation=canonical_hash(plan)
with ops.lock():
require(canonical_hash(plan)==confirmation and observed_state()==before
and backup_ok() and canonical_hash(identity.observe())==db_identity,
"Reconciliation review no longer matches live state")
good(migration,f"""
BEGIN;
CREATE TABLE work.interrupted_step(id INT);
INSERT INTO work.migrations VALUES ('{MIGRATION}');
COMMIT;
""")
after=observed_state()
require(after==dict(before,history=[BASE,MIGRATION],suffix_exists=True),
"Reconciliation replayed prefix or changed protected state")
record("postgres","review drill completed only the rolled-back suffix; prefix identity and journal stayed unchanged","PASS")
for action,error_type in ((lambda:coordinator.execute(identifier,rehearsal,confirmation=approval["confirmation"]),MigrationError),
(lambda:recovery.inspect(identifier),MigrationRecoveryError)):
try:
action()
except error_type:
pass
else:
raise RuntimeError("Framework bypassed incomplete evidence after manual SQL")
require(ops.guard.inspect()["status"]=="BLOCKED" and observed_state()==after and not activation_calls,
"Manual SQL unexpectedly cleared containment or changed runtime")
record("framework","manual SQL did not authorise replay, activation or containment release","PASS")
try:
recovery.plan_reconciliation(identifier,operator="ungranted")
except MigrationRecoveryError:
pass
else:
raise RuntimeError("Unauthorised reconciler obtained a plan")
plan_review=recovery.plan_reconciliation(identifier,operator=operator)
try:
recovery.record_reconciliation(identifier,operator=operator,
confirmation=plan_review["confirmation"],fingerprint="0"*64)
except MigrationRecoveryError:
pass
else:
raise RuntimeError("Incorrect reconciliation fingerprint accepted")
require(not coordinator.result_path(identifier).exists(),"Rejected review wrote a migration result")
record("framework","ungranted operator and incorrect plan fingerprint denied with no result","PASS")
recorded=recovery.record_reconciliation(identifier,operator=operator,
confirmation=plan_review["confirmation"],fingerprint=plan_review["plan_fingerprint"])
require(recorded["reconciliation"]["operator"]==operator
and recorded["reconciliation"]["plan_fingerprint"]==plan_review["plan_fingerprint"],
"Durable result was not bound to review")
result_bytes=coordinator.result_path(identifier).read_bytes()
try:
recovery.record_reconciliation(identifier,operator=operator,
confirmation=plan_review["confirmation"],fingerprint=plan_review["plan_fingerprint"])
except MigrationRecoveryError:
pass
else:
raise RuntimeError("Reconciliation replay succeeded")
require(result_bytes==coordinator.result_path(identifier).read_bytes()
and observed_state()==after and not activation_calls
and ops.guard.inspect()["status"]=="BLOCKED",
"Reconciliation disturbed protected state")
forward=recovery.inspect(identifier)
require(forward["status"]=="FORWARD_ACTIVATION_READY" and forward["migration_reexecution_allowed"] is False,
"Reconciliation did not produce a guarded forward plan")
record("framework","authorised review persisted once; separate forward confirmation still required","PASS")
write("reconciliation-result.json",recorded)
# Continue using the real release manager and disposable database. The
# service probes below model containment and readiness in this fixture.
def activate(target):
require(contained(),"Fixture activation escaped containment")
releases.activate(target)
return True
def reopen():
require(contained() and releases.current()=="3" and history()==[BASE,MIGRATION],
"Fixture reopening happened before candidate and history verification")
gate.unlink()
return True
health=lambda release:{"healthy":not contained() and releases.current()==release,"release":release}
recovery.activate=activate
recovery.refresh=lambda:contained()
recovery.readiness_probe=lambda:contained() and releases.current()=="3"
recovery.release_containment=reopen
recovery.writes_enabled_probe=lambda:not contained()
recovery.health_probe=health
activation=recovery.execute(identifier,confirmation=forward["confirmation"],
fingerprint=forward["plan_fingerprint"])
require(activation["status"]=="VERIFIED" and releases.current()=="3" and not contained()
and history()==[BASE,MIGRATION] and not activation["migration_reexecuted"]
and digest(ops.journal.path)==ordinary_hash,"Forward activation disturbed recovered state")
record("framework","separate forward confirmation activated the fixture without rerunning migration","PASS")
archive=MigrationArchive(site=SITE,store=ops.approvals,lock_path=ops.lock_path,
identity_probe=lambda:canonical_hash(identity.observe()),history_probe=history,
provenance_probe=lambda release:versions[release],backup_probe=backup_ok,
current_probe=releases.current,health_probe=health,writes_enabled_probe=lambda:not contained())
archive_plan=archive.plan(identifier)
archive.execute(identifier,confirmation=archive_plan["confirmation"],fingerprint=archive_plan["fingerprint"])
require(ops.guard.inspect()["status"]=="CLEAR" and digest(ops.journal.path)==ordinary_hash,
"Verified archive did not release only the migration guard")
record("framework","verified archival cleared the migration guard without rewriting ordinary journal","PASS")
write("forward-activation.json",activation)
write("manual-reconciliation.json",{"plan":plan,"plan_fingerprint":confirmation,"after":after,
"scope":"Fixture repair followed by framework-recorded reconciliation"})
write("observed.json",{"active_release":"2","candidate_release":"3","history":history(),
"committed_prefix_survived":True,"unfinished_step_rolled_back":True,"containment_retained":True,
"ordinary_journal_before_and_after_sha256":ordinary_hash,"rollback_attempted":False})
def main():
os.umask(0o077)
require(good(("hostname","-s"))=="absdev-ci","Wrong host")
fixture.capability("before")
try:
exercise(fixture.start("postgres"))
finally:
for container in fixture.containers:
good((*DOCKER,"rm","-f","-v",container))
require(not good((*DOCKER,"ps","-aq","--filter","label=absdev.qualification="+fixture.RUN)),
"Disposable resources remained")
record("framework","disposable PostgreSQL container and anonymous data volume removed","PASS")
fixture.capability("after")
checks=fixture.events
write("summary.json",{"revision":REVISION,"host":"ABSDEV-CI",
"production_execution_enabled":False,"production_ready":False,
"passed":sum(r["result"]=="PASS" for r in checks),
"open_gates":[r["check"] for r in checks if r["result"]=="GAP"]})
if __name__=="__main__":
try:
main()
except Exception as error:
print(fixture.safe(str(error)),file=sys.stderr)
sys.exit(1)