diff --git a/scripts/recovery/import_config_sources.py b/scripts/recovery/import_config_sources.py new file mode 100644 index 0000000000..6a15154c1f --- /dev/null +++ b/scripts/recovery/import_config_sources.py @@ -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() diff --git a/scripts/recovery/import_platform_missing.py b/scripts/recovery/import_platform_missing.py new file mode 100644 index 0000000000..eb876e2047 --- /dev/null +++ b/scripts/recovery/import_platform_missing.py @@ -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]