"""Read-only package inventory; rebuild SQLite and four CSV tables after each batch.""" import argparse import csv import io import json from pathlib import Path import sqlite3 from np.batch_stats import expected_versions ROOT = Path(__file__).resolve().parents[1] SCHEMA = { 'batches': 'batch TEXT PRIMARY KEY, code TEXT, planned INTEGER, complete INTEGER, questions INTEGER, zero_versions TEXT, wall_s REAL, warm_s REAL, generate_s REAL, questions_s REAL, audit_s REAL, rc INTEGER, audit_json TEXT', 'segments': 'id TEXT, batch TEXT REFERENCES batches(batch), house TEXT REFERENCES houses(house), scene TEXT, humans_requested INTEGER, humans_actual INTEGER, observers INTEGER, duration_s REAL, tier TEXT, arrangement TEXT, seed INTEGER, complete INTEGER, refusal TEXT, questions INTEGER, rc INTEGER, refill INTEGER, generate_s REAL, questions_s REAL, stage_wall_json TEXT, record_json TEXT, manifest_source TEXT, movers INTEGER, movers_humanoid INTEGER, movers_quadruped INTEGER, observers_embodied INTEGER, observer_bodies TEXT, PRIMARY KEY(batch,id)', 'entities': 'batch TEXT, segment TEXT, role TEXT, entity TEXT, kind TEXT, body TEXT, category TEXT, appearance TEXT, PRIMARY KEY(batch,segment,role,entity), FOREIGN KEY(batch,segment) REFERENCES segments(batch,id)', 'questions': 'id INTEGER PRIMARY KEY, batch TEXT, segment TEXT, candidate_id TEXT, version_id TEXT REFERENCES versions(id), ability TEXT, unit TEXT, wp TEXT, side TEXT, answer_type TEXT, source TEXT, FOREIGN KEY(batch,segment) REFERENCES segments(batch,id)', 'houses': 'house TEXT PRIMARY KEY, scene TEXT', 'version_status': 'batch TEXT, segment TEXT, version_id TEXT REFERENCES versions(id), questions INTEGER, reject_reasons TEXT, audit_zero INTEGER, stats_json TEXT, PRIMARY KEY(batch,segment,version_id), FOREIGN KEY(batch,segment) REFERENCES segments(batch,id)', 'groups': 'batch TEXT, segment TEXT, unit TEXT, group_id TEXT, forms TEXT, sets TEXT, conditions TEXT, summary_json TEXT, PRIMARY KEY(batch,segment,unit,group_id), FOREIGN KEY(batch,segment) REFERENCES segments(batch,id)', 'group_members': 'question_rowid INTEGER REFERENCES questions(id), batch TEXT, segment TEXT, unit TEXT, group_id TEXT, set_id INTEGER, kind INTEGER, anchor TEXT, form TEXT, scaffold TEXT, has_scaffold INTEGER, version_id TEXT REFERENCES versions(id), slots TEXT, presentation_json TEXT, group_json TEXT, FOREIGN KEY(batch,segment,unit,group_id) REFERENCES groups(batch,segment,unit,group_id)', 'versions': 'id TEXT PRIMARY KEY, active INTEGER, ability TEXT, unit TEXT, wp TEXT, side TEXT, answer_type TEXT', } def bodies(cfg): '''Who is in the segment, from its config: (role, id, kind, body, category, appearance) per observer and mover; category is the body's appearance category (humanoid, quadruped) or virtual for a camera body, observer body defaulting as the generator does.''' from embodied_pipeline.gen import config rows = [] for o in cfg.get('observers') or []: body = o.get('body', config.OBS_KINDS.get(o.get('kind'), 'camera')) category = config.BODIES.get(body, {}).get('appearance_category') or ('virtual' if body == 'camera' else body.split('_')[0]) rows.append(('observer', o.get('id'), o.get('kind'), body, category, o.get('appearance'))) for c in cfg.get('cast') or []: rows.append(('mover', c.get('id'), c.get('kind'), c.get('kind'), c.get('kind'), c.get('appearance'))) return rows def summary_of(who): movers = [r for r in who if r[0] == 'mover']; observers = [r for r in who if r[0] == 'observer'] return [len(movers), sum(r[4] == 'humanoid' for r in movers), sum(r[4] == 'quadruped' for r in movers), sum(r[2] == 'embodied' for r in observers), ','.join(r[4] for r in observers)] def load(path): return json.loads(path.read_text()) if path.is_file() else {} def text(value): return json.dumps(value, ensure_ascii=False, sort_keys=True) if isinstance(value, (dict, list)) else value def number(value): return int(value) if value not in ('', None) else None def insert(db, table, values): db.execute(f'INSERT INTO {table} VALUES ({",".join("?" for _ in values)})', tuple(map(text, values))) def build(package, out, work=None, batch=None): """Use TSV as the batch/segment manifest; reconcile actual JSONL before publishing.""" package, out = Path(package).resolve(), Path(out).resolve() if out == package or package in out.parents: raise ValueError("output must be outside the read-only package") snapshots = {name: (package / name).read_text() for name in ('per-batch.tsv', 'per-seg.tsv')} manifests = {name: list(csv.DictReader(io.StringIO(data), delimiter='\t')) for name, data in snapshots.items()} batches = [b for b in manifests['per-batch.tsv'] if batch is None or b['batch'] == batch] if not batches: raise ValueError('no batches in manifest') contract = load(ROOT / 'embodied_pipeline/prover/wp_target.json')['versions'] targets = {vid: v for v in contract for vid in [v['id'], *v.get('impl', [])]} forms = load(ROOT / 'spec/questions/catalog.json')['forms'] metadata = {v['id']: (f['id'].split('.')[0], f.get('answer', {}).get('type')) for f in forms for v in f['versions']} active = expected_versions(ROOT / 'spec/questions/catalog.json') active_set = set(active) # Build in memory so a malformed/live input cannot replace the last good inventory. db = sqlite3.connect(':memory:') db.execute('PRAGMA foreign_keys=ON') for table, definition in SCHEMA.items(): db.execute(f'CREATE TABLE {table} ({definition})') db.execute('CREATE INDEX questions_segment ON questions(batch,segment,version_id)') for vid in active: target = targets.get(vid, {}) ability, answer = metadata[vid] insert(db, 'versions', [vid, 1, ability, target.get('unit'), target.get('wp'), target.get('side'), answer]) for b in batches: name = b['batch'] base = package / 'batches' / name audits = [load(p) for p in sorted((base / 'report').glob('audit-*.json'))] audit = next((a for a in audits if a.get('code') == b.get('code')), {}) insert(db, 'batches', [name, b.get('code'), number(b['denominator']), number(b['complete']), number(b['questions']), b.get('zero_versions'), *[b.get(k) or audit.get(k) for k in ('wall_s', 'warm_s', 'generate_s', 'questions_s', 'audit_s')], audit.get('rc'), audit]) configs = {c['id']: c for c in load(base / 'batch.json').get('selected_configs', [])} rows = [dict(s, manifest_source='per-seg.tsv') for s in manifests['per-seg.tsv'] if s['batch'] == name] seen = {s['id'] for s in rows} rows += [dict(s, manifest_source='audit.records') for s in audit.get('records', []) if s['id'] not in seen] packages = {} for s in rows: sid = s['id'] script = load(base / 'segs' / sid / 'script.json') cfg_path = Path(work) / name / 'cfg' / f'{sid}.json' if work else Path(s.get('config_path') or '/nonexistent') cfg = load(cfg_path) or configs.get(sid) or script.get('generator', {}).get('config', {}) duration = cfg.get('duration_s') tier = s.get('tier') or (('short' if duration <= 60 else 'medium' if duration <= 125 else 'long') if duration else None) db.execute('INSERT OR IGNORE INTO houses VALUES (?,?)', (s.get('house'), cfg.get('scene') or script.get('world_id'))) record_path = Path(work) / name / 'state/seg' / f'{sid}.json' if work else Path(s.get('record_path') or '/nonexistent') record = load(record_path) vout = base / 'vout' / sid report = load(vout / 'summary.json') walls = dict(generate_s=record.get('wall_s'), questions_s=report.get('seconds')) refill = int((Path(work) / name / 'refill.json').is_file()) if work else None who = bodies(cfg) insert(db, 'segments', [sid, name, s.get('house'), cfg.get('scene') or script.get('world_id'), number(s.get('humans_requested')), number(s.get('humans_actual')), len(cfg['observers']) if 'observers' in cfg else None, duration, tier, s.get('arrangement'), cfg.get('seed'), int(str(s['complete']).lower() == 'true'), s.get('refusal'), number(s['questions']), number(s.get('rc')), refill, walls['generate_s'], walls['questions_s'], walls, record, s['manifest_source'], *(summary_of(who) if who else [None]*5)]) for row in who: insert(db, 'entities', [name, sid, *row]) count = 0 for filename in ('groups.jsonl', 'questions.jsonl'): path = vout / filename if not path.is_file(): continue with path.open() as stream: for line in stream: if not line.strip(): continue q = json.loads(line) vid = q['public']['version_id'] if vid not in active_set: raise ValueError(f'{path}: non-active version {vid}') t = targets.get(vid, {}) unit = (q.get('scope', {}).get('group') or {}).get('unit') or t.get('unit') ability, answer = metadata[vid] insert(db, 'questions', [None, name, sid, q.get('candidate_id'), vid, ability, unit, t.get('wp'), t.get('side'), answer, filename]) question_rowid = db.execute('SELECT last_insert_rowid()').fetchone()[0] g = (q.get('scope') or {}).get('group') if g: key = (name, sid, str(g['unit']), str(g['id'])) if key not in packages: packages[key] = dict(forms=set(), sets=set(), conditions=[]) insert(db, 'groups', [*key, '[]', '[]', '[]', report.get('groups', {}).get(g['unit'], {})]) item = packages[key] item['forms'].add(g.get('form')) item['sets'].add(g.get('set')) item['conditions'].append(g) scaffold = q['public'].get('scaffold', []) insert(db, 'group_members', [question_rowid, *key, g.get('set'), g.get('kind'), text(g.get('anchor')), g.get('form'), scaffold, int(bool(scaffold)), vid, q['public'].get('slots'), q.get('presentation'), g]) count += 1 audit_zeros = json.loads(b.get('zero_versions') or '[]') for vid in active: stats = report.get('versions', {}).get(vid, {}) supplied = db.execute('SELECT count(*) FROM questions WHERE batch=? AND segment=? AND version_id=?', (name, sid, vid)).fetchone()[0] insert(db, 'version_status', [name, sid, vid, supplied, stats.get('reject_reasons', {}), int(vid in audit_zeros), stats]) if count != number(s['questions']): raise ValueError(f'{name}/{sid}: JSONL questions={count}, TSV={s["questions"]}') for key, info in packages.items(): db.execute('UPDATE groups SET forms=?,sets=?,conditions=? WHERE batch=? AND segment=? AND unit=? AND group_id=?', (text(sorted(info['forms'], key=str)), text(sorted(info['sets'], key=str)), text(info['conditions']), *key)) actual = db.execute('SELECT count(*), coalesce(sum(complete),0), coalesce(sum(questions),0) FROM segments WHERE batch=?', (name,)).fetchone() expected = tuple(number(b[k]) for k in ('rows', 'complete', 'questions')) if actual != expected: raise ValueError(f'{name}: segments/complete/questions={actual}, TSV={expected}') if any((package / name).read_text() != data for name, data in snapshots.items()): raise ValueError('package manifests changed during build; rebuild after batch completes') db.execute('CREATE VIEW question_dimensions AS SELECT q.id question_rowid,q.*,s.house,s.scene,s.humans_requested,s.humans_actual,s.observers,s.duration_s,s.tier,s.arrangement,s.seed,s.complete,s.refill,s.movers,s.movers_humanoid,s.movers_quadruped,s.observers_embodied,s.observer_bodies FROM questions q JOIN segments s ON s.batch=q.batch AND s.id=q.segment') db.commit() out.mkdir(parents=True, exist_ok=True) temporary = out / 'bench.sqlite.tmp' with sqlite3.connect(temporary) as dest: db.backup(dest) temporary.replace(out / 'bench.sqlite') for table in SCHEMA: result = db.execute(f'SELECT * FROM {table}') with (out / f'{table}.csv').open('w', newline='') as stream: writer = csv.writer(stream) writer.writerow([c[0] for c in result.description]) writer.writerows(result) db.close() return out / 'bench.sqlite' def readonly(path): db = sqlite3.connect(Path(path).resolve().as_uri() + '?mode=ro', uri=True) db.execute('PRAGMA query_only=ON') return db def summary(db): """Return JSON-compatible distributions; NULL means source metadata was absent.""" def rows(sql): cursor = db.execute(sql) return [dict(zip([c[0] for c in cursor.description], row)) for row in cursor] result = rows('SELECT count(DISTINCT house) houses, count(*) segments, coalesce(sum(complete),0) complete FROM segments')[0] result['questions'] = db.execute('SELECT count(*) FROM questions').fetchone()[0] for dimension in ('tier', 'duration_s', 'humans_requested', 'humans_actual', 'observers', 'arrangement', 'batch', 'movers', 'movers_quadruped', 'observer_bodies'): result[dimension] = rows(f'SELECT {dimension}, count(*) segments, sum(complete) complete, sum(questions) questions FROM segments GROUP BY {dimension} ORDER BY {dimension}') result['abilities'] = rows('SELECT ability, count(*) questions FROM questions GROUP BY ability ORDER BY ability') result['units'] = rows('SELECT ability, unit, count(*) questions FROM questions GROUP BY ability,unit ORDER BY ability,unit') result['versions'] = rows('SELECT ability, unit, version_id, count(*) questions FROM questions GROUP BY ability,unit,version_id ORDER BY ability,unit,version_id') result['zero_versions'] = rows('SELECT * FROM versions WHERE id NOT IN (SELECT version_id FROM questions) ORDER BY id') for version in result['zero_versions']: version['reject_reasons'] = rows("SELECT batch,segment,reject_reasons,audit_zero FROM version_status WHERE version_id='"+version['id'].replace("'", "''")+"' AND (reject_reasons!='{}' OR audit_zero=1)") result['group_counts'] = rows('SELECT unit,count(*) packages FROM groups GROUP BY unit ORDER BY unit') result['group_member_counts'] = rows('SELECT members,count(*) packages FROM (SELECT count(*) members FROM group_members GROUP BY batch,segment,unit,group_id) GROUP BY members') result['member_kinds'] = rows('SELECT kind,scaffold,count(*) members FROM group_members GROUP BY kind,scaffold ORDER BY kind,scaffold') result['batches'] = rows('SELECT batch,code,planned,complete,questions,zero_versions,wall_s,warm_s,generate_s,questions_s,audit_s,rc FROM batches ORDER BY batch') return result def main(): parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest='command', required=True) p = commands.add_parser('build') p.add_argument('package', type=Path) p.add_argument('--work', type=Path) p.add_argument('--out', type=Path, required=True) p.add_argument('--batch', help='restrict validation to one batch') for command in ('summary', 'query'): p = commands.add_parser(command) p.add_argument('--db', type=Path, required=True) if command == 'query': p.add_argument('sql') args = parser.parse_args() if args.command == 'build': print(build(args.package, args.out, args.work, args.batch)) else: with readonly(args.db) as db: if args.command == 'summary': print(json.dumps(summary(db), ensure_ascii=False, indent=2)) else: cursor = db.execute(args.sql) writer = csv.writer(__import__('sys').stdout) writer.writerow([c[0] for c in cursor.description]) writer.writerows(cursor) if __name__ == '__main__': main()