Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions scripts/recovery/import_config_sources.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Usage: import_config_sources.py CANDIDATE [--apply --expect-sha256 SHA]
[--target fleet-platform|fleet-platform-reconcile-stage-20261118]. Default read-only.
Creates only four missing sources tables, inserts five recovered records; D1 untouched.
"""
import argparse,json,subprocess
from pathlib import Path
from import_runtime import Client,quote,filehash
from import_platform_missing import canonical_time
TABLES={'automation_sources':2,'finance_sources':1,'home_sources':1,'research_sources':1}
COLS=['id','name','kind','drive_file_id','drive_modified_at','import_batch','imported_at','note']
def ddl(table):
if table not in TABLES:raise ValueError('table not approved')
return 'CREATE TABLE '+quote(table)+" (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, kind TEXT NOT NULL, drive_file_id TEXT, drive_modified_at TEXT, import_batch TEXT NOT NULL, imported_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')), note TEXT)"
def validate(data):
if set(data)!=set(TABLES):raise ValueError('wrong tables')
for table,rows in data.items():
if len(rows)!=TABLES[table] or len({r[0] for r in rows})!=len(rows):raise ValueError('wrong count/duplicate ID')
for r in rows:
if len(r)!=8 or type(r[0]) is not int or any(v is not None and not isinstance(v,str) for v in r[1:]):raise ValueError('row type')
if any(r[i] is None for i in [1,2,5,6]):raise ValueError('required field')
canonical_time(r[6])
if r[4] is not None:canonical_time(r[4])
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('candidate',type=Path);p.add_argument('--apply',action='store_true');p.add_argument('--expect-sha256');p.add_argument('--target',choices=['fleet-platform','fleet-platform-reconcile-stage-20261118'],default='fleet-platform');a=p.parse_args();digest=filehash(a.candidate)
if a.apply and digest!=a.expect_sha256:p.error('reviewed candidate SHA required')
data=json.loads(a.candidate.read_text());validate(data);cmd=['fleet','secrets','get','turso.fleet-platform-rw-token'] if a.target=='fleet-platform' else ['turso','db','tokens','create',a.target,'--expiration','1d'];token=subprocess.run(cmd,capture_output=True,text=True,check=True,timeout=60).stdout.strip().splitlines()[-1];c=Client(token,a.target);begun=False;attempted=False
try:
if a.apply:c.execute('BEGIN IMMEDIATE');begun=True
existing={r[0] for r in c.execute('SELECT name FROM sqlite_master')}
if set(data)&existing:raise ValueError('target already exists; refuse duplicate/partial import')
print('apply' if a.apply else 'dry-run','four new tables, five rows',digest,flush=True)
if not a.apply:return
for table,rows in data.items():
c.execute(ddl(table))
for row in rows:c.execute('INSERT INTO '+quote(table)+' ('+','.join(quote(v) for v in COLS)+') VALUES (?,?,?,?,?,?,?,?)',row)
if int(c.execute('SELECT count(*) FROM '+quote(table))[0][0])!=len(rows):raise ValueError('count mismatch')
if filehash(a.candidate)!=digest:raise ValueError('candidate changed')
attempted=True;c.execute('COMMIT');begun=False;print('COMMIT acknowledged',flush=True)
except Exception:
if begun and not attempted:
try:c.execute('ROLLBACK');print('ROLLBACK acknowledged',flush=True)
except Exception:print('ROLLBACK uncertain',flush=True)
elif attempted:print('COMMIT uncertain; inspect before retry',flush=True)
raise
finally:
try:c.close()
except Exception:pass
if __name__=='__main__':main()
79 changes: 79 additions & 0 deletions scripts/recovery/import_platform_missing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Read-only by default. Usage: import_platform_missing.py CANDIDATE
[--apply --expect-sha256 SHA] [--target fleet-platform|fleet-platform-reconcile-stage-20261118].
Strictly INSERT-only historical recovery into 17 allowlisted existing tables.
No credential values or row contents printed. No retry after ambiguous COMMIT.
"""
import argparse,json,sqlite3,subprocess,hashlib,math,datetime
from pathlib import Path
from import_runtime import Client,quote,batches,filehash
TABLES={'agent_mirror_'+s for s in ('agent_agents','compaction_stats_daily','conversation_stats_daily','distincts_daily','goals_updates','histograms_daily','message_token_stats_daily','run_stats_daily','scheduler_job_runs','scheduler_jobs','session_activity_hourly','session_stats_daily','sessions','token_usage_daily','token_usage_hourly')}|{'agent_quota_records','ci_events'}
def canonical_time(v):
if not isinstance(v,str):raise ValueError('temporal key must be text')
dt=datetime.datetime.fromisoformat(v.replace('Z','+00:00'))
if dt.tzinfo is None:raise ValueError('temporal key requires timezone')
return dt.astimezone(datetime.timezone.utc).isoformat().replace('+00:00','Z')
def validate(data):
if not data or set(data)-TABLES:raise ValueError('unexpected table')
for table,x in data.items():
cols=x['columns'];keys=x['keys']
if not cols or len(set(cols))!=len(cols) or not keys or not set(keys)<=set(cols) or not set(x['temporal_keys'])<=set(keys):raise ValueError('invalid columns/keys')
if not isinstance(x['initial_count'],int) or x['initial_count']<0:raise ValueError('invalid count')
seen=set()
for row in x['rows']:
if len(row)!=len(cols) or any(not isinstance(v,(str,int,float,type(None))) or isinstance(v,float) and not math.isfinite(v) for v in row):raise ValueError('invalid row')
key=tuple(canonical_time(row[cols.index(k)]) if k in x['temporal_keys'] else row[cols.index(k)] for k in keys)
if any(v is None for v in key) or key in seen:raise ValueError('null/duplicate key')
seen.add(key)
if any(s[0]=='trigger' for s in x['schema']):raise ValueError('target triggers not allowed')
def check_absent(c,table,x):
cols=x['columns'];keys=x['keys'];positions=[cols.index(k) for k in keys]
lhs=[("julianday(CASE WHEN substr("+quote(k)+",-3)='+00' THEN substr("+quote(k)+",1,length("+quote(k)+")-3)||'Z' ELSE "+quote(k)+" END)" if k in x['temporal_keys'] else quote(k)) for k in keys]
rhs=[('julianday(?)' if k in x['temporal_keys'] else '?') for k in keys]
for start in range(0,len(x['rows']),100):
rows=x['rows'][start:start+100];args=[canonical_time(row[i]) if k in x['temporal_keys'] else row[i] for row in rows for k,i in zip(keys,positions)]
left='('+','.join(lhs)+')' if len(keys)>1 else lhs[0]
item='('+','.join(rhs)+')' if len(keys)>1 else rhs[0]
if c.execute('SELECT 1 FROM '+quote(table)+' WHERE '+left+' IN ('+','.join(item for row in rows)+') LIMIT 1',args):raise ValueError('candidate key exists or timestamp-equivalent collision')
def preflight(c,data):
counts={}
for table,x in data.items():
if c.execute('SELECT type,name,tbl_name,sql FROM sqlite_master WHERE tbl_name=? ORDER BY type,name',[table])!=x['schema']:raise ValueError('schema changed')
if [v[1] for v in c.execute('PRAGMA table_info('+quote(table)+')')]!=x['columns']:raise ValueError('column order changed')
counts[table]=int(c.execute('SELECT count(*) FROM '+quote(table))[0][0])
if counts[table]<x['initial_count']:raise ValueError('count decreased')
check_absent(c,table,x)
return counts
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('candidate',type=Path);p.add_argument('--apply',action='store_true');p.add_argument('--expect-sha256');p.add_argument('--target',choices=['fleet-platform','fleet-platform-reconcile-stage-20261118'],default='fleet-platform');a=p.parse_args()
digest=filehash(a.candidate)
if a.apply and digest!=a.expect_sha256:p.error('reviewed candidate SHA required')
data=json.loads(a.candidate.read_text());validate(data)
cmd=['fleet','secrets','get','turso.fleet-platform-rw-token'] if a.target=='fleet-platform' else ['turso','db','tokens','create',a.target,'--expiration','1d']
token=subprocess.run(cmd,capture_output=True,text=True,check=True,timeout=60).stdout.strip().splitlines()[-1];c=Client(token,a.target);begun=False;commit_attempted=False
try:
if a.apply:
c.execute('PRAGMA foreign_keys=ON');assert c.execute('PRAGMA foreign_keys')==[['1']]
c.execute('BEGIN IMMEDIATE');begun=True
initial_counts=preflight(c,data);print(json.dumps({'mode':'apply' if a.apply else 'dry-run','candidate_sha256':digest,'tables':len(data),'initial_counts':initial_counts,'rows':sum(len(v['rows']) for v in data.values())}),flush=True)
if not a.apply:return
for table,x in data.items():
cols=x['columns']
for batch in batches(x['rows']):
sql='INSERT INTO '+quote(table)+' ('+','.join(quote(v) for v in cols)+') VALUES '+','.join('('+','.join('?' for _ in cols)+')' for row in batch)
c.execute(sql,[v for row in batch for v in row])
assert int(c.execute('SELECT count(*) FROM '+quote(table))[0][0])==initial_counts[table]+len(x['rows'])
print(table,len(x['rows']),'inserted',flush=True)
if c.execute('PRAGMA foreign_key_check'):raise ValueError('foreign key violation')
if filehash(a.candidate)!=digest:raise ValueError('candidate changed')
commit_attempted=True;c.execute('COMMIT');begun=False;print('COMMIT acknowledged',flush=True)
except Exception:
if begun and not commit_attempted:
try:c.execute('ROLLBACK');print('ROLLBACK acknowledged',flush=True)
except Exception:print('ROLLBACK uncertain; inspect before retry',flush=True)
elif commit_attempted:print('COMMIT uncertain; inspect before retry',flush=True)
raise
finally:
try:c.close()
except Exception:pass
if __name__=='__main__':main()
16 changes: 16 additions & 0 deletions scripts/recovery/test_import_config_sources.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""Oracle: SQLite constraint/default behavior and fixed table/count contract."""
import unittest,sqlite3
from import_config_sources import TABLES,ddl,validate
class Tests(unittest.TestCase):
def data(self):return {t:[[i,'name','kind',None,None,'batch','2026-11-01T00:00:00Z',None] for i in range(n)] for t,n in TABLES.items()}
def test_valid(self):validate(self.data())
def test_wrong_table(self):
d=self.data();d['external_comms']=d.pop('home_sources')
with self.assertRaises(ValueError):validate(d)
def test_required(self):
d=self.data();d['home_sources'][0][6]=None
with self.assertRaises(ValueError):validate(d)
def test_ddl(self):
c=sqlite3.connect(':memory:');c.execute(ddl('home_sources'));c.execute("INSERT INTO home_sources(name,kind,import_batch) VALUES ('a','b','c')");r=c.execute('SELECT id,imported_at FROM home_sources').fetchone();self.assertEqual(r[0],1);self.assertTrue(r[1].endswith('Z'))
with self.assertRaises(sqlite3.IntegrityError):c.execute("INSERT INTO home_sources(id,name,kind,import_batch) VALUES (1,'a','b','c')")
if __name__=='__main__':unittest.main()
45 changes: 45 additions & 0 deletions scripts/recovery/test_import_platform_missing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
"""Oracle: SQLite state, exact key/temporal equivalence, rejected invalid input."""
import unittest,sqlite3,copy
from import_platform_missing import validate,check_absent,preflight
class C:
def __init__(self):self.db=sqlite3.connect(':memory:');self.db.execute('CREATE TABLE agent_quota_records(source TEXT,id TEXT,ts TEXT,PRIMARY KEY(source,id,ts))')
def execute(self,s,args=()):return [[str(v) if isinstance(v,int) else v for v in r] for r in self.db.execute(s,args)]
class Tests(unittest.TestCase):
def setUp(self):
self.c=C();self.t='agent_quota_records';self.x={'columns':['source','id','ts'],'keys':['source','id','ts'],'temporal_keys':['ts'],'rows':[['a','b','2026-11-01T00:00:00Z']],'schema':self.c.execute('SELECT type,name,tbl_name,sql FROM sqlite_master WHERE tbl_name=? ORDER BY type,name',[self.t]),'initial_count':0}
def test_missing(self):validate({self.t:self.x});preflight(self.c,{self.t:self.x})
def test_temporal_collision(self):
self.c.db.execute("INSERT INTO agent_quota_records VALUES ('a','b','2026-11-01 00:00:00+00')")
with self.assertRaises(ValueError):check_absent(self.c,self.t,self.x)
def test_forbidden(self):
with self.assertRaises(ValueError):validate({'agent_external_comms':self.x})
def test_duplicate(self):
self.x['rows']*=2
with self.assertRaises(ValueError):validate({self.t:self.x})
def test_null_key(self):
self.x['rows'][0][0]=None
with self.assertRaises(ValueError):validate({self.t:self.x})
def test_count_drift(self):
self.x['initial_count']=1
with self.assertRaises(ValueError):preflight(self.c,{self.t:self.x})
def test_preserves_live_additions(self):
self.c.db.execute("INSERT INTO agent_quota_records VALUES ('other','x','2026-01-01T00:00:00Z')")
self.assertEqual(preflight(self.c,{self.t:self.x})[self.t],1)
def test_schema_drift(self):
self.x['schema']=[]
with self.assertRaises(ValueError):preflight(self.c,{self.t:self.x})
def test_trigger_refusal(self):
self.x['schema'].append(['trigger','x',self.t,'x'])
with self.assertRaises(ValueError):validate({self.t:self.x})
def test_invalid_time(self):
self.x['rows'][0][2]='not-time'
with self.assertRaises(ValueError):validate({self.t:self.x})
def test_naive_time(self):
self.x['rows'][0][2]='2026-11-01T00:00:00'
with self.assertRaises(ValueError):validate({self.t:self.x})
def test_equivalent_duplicate(self):
self.x['rows'].append(['a','b','2026-11-01 00:00:00+00'])
with self.assertRaises(ValueError):validate({self.t:self.x})
def test_many_keys(self):
self.x['rows']=[['a',str(i),'2026-11-01T00:00:00Z'] for i in range(1200)];check_absent(self.c,self.t,self.x)
if __name__=='__main__':unittest.main()