#!/usr/bin/env python3
"""Supplement measurement.py: offline malformed-write check, then real server recovery sweep.
Usage: verify-malformed.py CHECKOUT MEASUREMENT_DIRECTORY PORT
"""
import sys,os,json,time,sqlite3,subprocess,urllib.request
from pathlib import Path
checkout=Path(sys.argv[1]);out=Path(sys.argv[2]);port=int(sys.argv[3]);home=out/'home';db=home/'userdata/statev2.sqlite';trace=home/'userdata/logs/server.trace.ndjson'
c=sqlite3.connect(db)
# The same exact predicate as the app under test, read from its source.
c.execute("DELETE FROM orchestration_v2_projection_turn_items WHERE turn_item_id='malformed-fixture'"); c.commit()
source=(checkout/'apps/server/src/orchestration-v2/ProjectionStore.ts').read_text()
start=source.index('SELECT failure.thread_id FROM orchestration_v2_projection_turn_items failure')
end=source.index('\n            )',start)
predicate='\n'.join(line for line in source[start:end].splitlines() if not line.strip().startswith('--'))
plan=json.loads(subprocess.check_output(['node','--input-type=module','-e',"import {DatabaseSync} from 'node:sqlite';import fs from 'node:fs';const db=new DatabaseSync(process.argv[1],{readOnly:true});console.log(JSON.stringify(db.prepare('EXPLAIN QUERY PLAN '+fs.readFileSync(0,'utf8')).all().map(x=>x.detail)));db.close();",str(db)],input=predicate,text=True))
rowsBefore=sorted(set(r[0] for r in c.execute(predicate)))
# Insert an extra historical error on a thread with no usage-limit record.
c.execute("INSERT INTO orchestration_v2_projection_turn_items(turn_item_id,thread_id,run_id,node_id,ordinal,type,status,updated_at,payload_json) VALUES('malformed-fixture','fixture-thread-3999','fixture-thread-3999-run-15','fixture-thread-3999-run-15-root',99,'error','failed','2026-01-01T00:00:00.000Z','{broken')")
c.commit()
c.execute("UPDATE orchestration_v2_projection_turn_items SET payload_json='{still-broken' WHERE turn_item_id='malformed-fixture'");c.commit()
prefilterError=None
try: rowsAfter=sorted(set(r[0] for r in c.execute(predicate)))
except sqlite3.Error as error: rowsAfter=None;prefilterError=str(error)
c.close()
def spans():
 result=[]
 for line in trace.read_text().splitlines():
  try:r=json.loads(line)
  except ValueError:continue
  if r.get('name')=='ProjectionStore.getLimitRecoveryCandidates':result.append(r)
 return result
before=len(spans());log=open(out/'private-malformed-server.log','w')
p=subprocess.Popen(['node','apps/server/src/bin.ts','serve','--host','127.0.0.1','--port',str(port),'--base-dir',str(home),'--no-browser'],cwd=checkout,env={**os.environ,'T3CODE_DEV_SEED':'0','T3CODE_TRACE_MAX_BYTES':'100000000'},stdout=log,stderr=log)
try:
 deadline=time.monotonic()+90
 while time.monotonic()<deadline:
  current=spans()
  if len(current)>before:break
  if p.poll() is not None:raise RuntimeError('Server stopped')
  time.sleep(.2)
 else:raise RuntimeError('No recovery sweep')
 r=current[-1];success=r['exit']['_tag']=='Success'
 c=sqlite3.connect(db);armed=[r[0] for r in c.execute("SELECT thread_id FROM orchestration_v2_projection_threads WHERE json_extract(payload_json,'$.limitRecovery.autoResume')=1 ORDER BY thread_id")];c.close()
 report=dict(commit=subprocess.check_output(['git','rev-parse','HEAD'],cwd=checkout,text=True).strip(),malformedInsertSucceeded=True,malformedUpdateSucceeded=True,malformedExcludedFromPrefilter=rowsAfter is not None and 'fixture-thread-3999' not in rowsAfter,prefilterThreadIdsUnchanged=rowsBefore==rowsAfter,prefilterDistinctThreads=None if rowsAfter is None else len(rowsAfter),prefilterError=prefilterError,planSqliteVersion=subprocess.check_output(['node','-p','process.versions.sqlite'],text=True).strip(),plan=plan,realServerRecoverySweepSucceeded=success,realServerRecoverySweepMs=r['durationMs'],armedThreadIds=armed)
 (out/'malformed-and-plan.json').write_text(json.dumps(report,indent=2));print(json.dumps(report,indent=2))
finally:
 p.terminate()
 try:p.wait(timeout=15)
 except subprocess.TimeoutExpired:p.kill();p.wait()
 log.close()
 c=sqlite3.connect(db);c.execute("DELETE FROM orchestration_v2_projection_turn_items WHERE turn_item_id='malformed-fixture'");c.commit();c.close()
