Files
aigc-home/e2e/hel732-migration.py
T

98 lines
5.3 KiB
Python

"""Executable isolated backup / migration / old-code read / exact restore exercise.
No service, user database or production configuration is opened.
"""
from __future__ import annotations
import asyncio
import hashlib
import json
import os
from pathlib import Path
import sqlite3
import subprocess
import tarfile
BASE='8d7e58645c9e63bb9b9e6a4ae8dfb031bf5960fb'
ROOT=Path(__file__).resolve().parents[1]
OUT=ROOT/'e2e/shots/hel732/migration'
OUT.mkdir(parents=True,exist_ok=True)
OLD=OUT/'old-code';OLD.mkdir(exist_ok=True)
archive=subprocess.run(['git','archive',BASE,'calliope-backend/src'],cwd=ROOT,check=True,stdout=subprocess.PIPE).stdout
(OUT/'old-code.tar').write_bytes(archive)
with tarfile.open(OUT/'old-code.tar') as tf:tf.extractall(OLD,filter='data')
DB=OUT/'isolated.db'
if DB.exists():DB.rename(OUT/f'previous-{__import__("time").time_ns()}.db')
checks=[]
def old_run(mode):
code='''import asyncio,json,sys
from pathlib import Path
from calliope import config
from calliope.db import migrate_db,get_db
config.settings.data_dir=Path(sys.argv[1]).parent
config.settings.db_name=Path(sys.argv[1]).name
config.settings.assets_dir=Path(sys.argv[1]).parent/'assets'
config.settings.dry_run=True
config.Settings.save_config_file=lambda self:None
if sys.argv[2]=='create':
asyncio.run(migrate_db(config.settings.db_path))
c=get_db(config.settings.db_path)
p=c.execute("INSERT INTO projects(title,status) VALUES ('B3 isolated legacy','draft')").lastrowid
c.execute("INSERT INTO agent_sessions(project_id,title,status) VALUES (?,'Legacy session','idle')",(p,))
c.execute("INSERT INTO agent_messages(session_id,role,content) VALUES (1,'user','Existing legacy message')")
c.execute("INSERT INTO jobs(project_id,kind,status,payload_json,output_paths_json) VALUES (1,'image','done',?,'[]')",(json.dumps({'legacy':True}),))
content=json.dumps({'text':'Legacy confirmed story text, sufficiently long to preserve the old confirmation behavior.'})
c.execute("INSERT INTO project_stages(project_id,stage_key,status,content_json,confirmed_content_json) VALUES (?,'script','confirmed',?,?)",(p,content,content))
c.commit();c.close()
else:
from calliope.main import create_app
from fastapi.testclient import TestClient
with TestClient(create_app()) as client:
s=client.get('/api/agent/sessions/1');assert s.status_code==200,s.text
assert any(m['content']=='Existing legacy message' for m in s.json()['messages'])
jobs=client.get('/api/jobs?project_id=1');assert jobs.status_code==200,jobs.text
assert jobs.json()[0]['status']=='done' and jobs.json()[0]['payload']['legacy'] is True
w=client.get('/api/workbench/projects/1');assert w.status_code==200,w.text
stage=w.json()['stages'][0];assert stage['status']=='confirmed'
assert stage['content']==stage['confirmed_content']
print(json.dumps({'session':s.json()['title'],'stage':stage['status'],'message_count':len(s.json()['messages'])}))
'''
env=os.environ.copy();env['PYTHONPATH']=str(OLD/'calliope-backend/src')
result=subprocess.run([__import__('sys').executable,'-c',code,str(DB),mode],cwd=OUT,env=env,text=True,capture_output=True,check=True)
(OUT/f'old-{mode}.log').write_text(result.stdout+result.stderr)
checks.append('old code '+mode+' succeeded')
old_run('create')
def backup(src,dst):
a=sqlite3.connect(src);b=sqlite3.connect(dst);a.backup(b);b.close();a.close()
backup(DB,OUT/'pre-b4-backup.db')
def dump(path):
c=sqlite3.connect(path);rows={name:c.execute(f'SELECT * FROM {name}').fetchall() for name in ['projects','agent_sessions','agent_messages','project_stages','jobs']};c.close();return rows
before=dump(DB)
from calliope.db import migrate_db,get_db
asyncio.run(migrate_db(DB));asyncio.run(migrate_db(DB))
c=get_db(DB)
for table,rows in before.items():
current=c.execute(f'SELECT * FROM {table}').fetchall()
# New columns are appended; every pre-existing field is equal.
assert [tuple(r)[:len(rows[0])] for r in current]==rows
assert c.execute('PRAGMA integrity_check').fetchone()[0]=='ok'
assert c.execute('PRAGMA foreign_key_check').fetchall()==[]
cols=[r[1] for r in c.execute('PRAGMA table_info(agent_sessions)')]
assert cols.count('task_summary')==1 and cols.count('task_status')==1
c.close();checks+=['migrate twice; no duplicate columns/tables','all original rows/fields preserved','integrity_check and foreign_key_check passed']
old_run('read')
# New-only payload survives an old-code read and startup.
c=get_db(DB)
c.execute("INSERT INTO agent_deliverables(session_id,source_message_id,project_id,stage_key,title,content) VALUES (1,1,1,'script','B4 isolated','New isolated deliverable')")
c.commit();c.close()
backup(DB,OUT/'post-b4-export.db')
# Exact rollback to an offline copy of the old backup; never overwrite a live DB.
backup(OUT/'pre-b4-backup.db',OUT/'restored.db')
assert dump(OUT/'restored.db')==before
c=sqlite3.connect(OUT/'restored.db')
assert 'task_summary' not in [r[1] for r in c.execute('PRAGMA table_info(agent_sessions)')]
assert c.execute("SELECT COUNT(*) FROM sqlite_master WHERE name='agent_deliverables'").fetchone()[0]==0
c.close();checks.append('exact pre-migration backup restored: old rows and old schema equal')
manifest={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in OUT.glob('*.db')}
(OUT/'report.json').write_text(json.dumps({'base':BASE,'checks':checks,'sha256':manifest},indent=2))
print(json.dumps({'checks':checks,'sha256':manifest},indent=2))