#!/usr/bin/env python3 """Stages D and E: the claim registry, the synthetic-question targets, and the synthetic questions with their injection. banks axis 3-8 question banks from the discovered candidates registry --init|--show|--check the injection registry (batches, atoms, claims) claims register every question of the bank as a claim targets per-axis synthetic-question need (count and mechanism) -> synthetic_targets.json short-axes the synthetic-capable axes that need synthetic questions generate --axes A --model M synthetic question+atom pairs -> synthetic_pairs.json wire append synthetic questions to their banks -> injection_plan.json batches register one batch per synthetic axis of the plan apply inject the linted plan into event_chain.jsonl and evidence_chain.jsonl All injections are planned before any is applied, and dialogues are generated once afterwards. Claims list, per question, the entities its gold tracks and the entities its gold asserts absent; the generators receive both as a forbidden list. """ from __future__ import annotations import argparse import glob import json import os import re import shutil import sys from collections import Counter, defaultdict from pipeline.common import BASE, PER_AXIS_MINIMUM, Progress, patient_id from pipeline.llm import ChatClient from pipeline.questions import axis3, axis5, axis6, axis7 PATIENT = patient_id() REGISTRY = BASE / "injection_registry.json" def load() -> dict: if REGISTRY.exists(): return json.loads(REGISTRY.read_text()) return {"patient_id": PATIENT, "batches": [], "atoms": [], "claims": []} def save(r: dict) -> None: tmp = REGISTRY.with_suffix(".tmp") tmp.write_text(json.dumps(r, ensure_ascii=False, indent=1)) os.replace(tmp, REGISTRY) def add_batch(r, batch_id, axis, purpose): if any(b["batch_id"] == batch_id for b in r["batches"]): raise SystemExit(f"batch {batch_id} already exists; batches are append-only") r["batches"].append({"batch_id": batch_id, "axis": axis, "purpose": purpose, "applied": False}) return r def add_claim(r, qid, axis, grounding, gold_entities, absence_entities, depends_on_atoms): """Register a question's dependency surface; `grounding` must be record or synthetic:.""" if not grounding: raise SystemExit(f"{qid}: grounding must be 'record' or 'synthetic:'") r["claims"] = [c for c in r["claims"] if c["qid"] != qid] + [{ "qid": qid, "axis": axis, "grounding": grounding, "gold_entities": gold_entities, "absence_entities": absence_entities, "depends_on_atoms": depends_on_atoms, }] return r def norm(s): return " ".join(re.sub(r"[^a-z0-9 ]", " ", str(s).lower()).split()) def gold_entities(r) -> dict: """entity -> [qid] for every entity a live gold tracks (forbidden to the generators).""" out = {} for c in r["claims"]: for e in c.get("gold_entities") or []: out.setdefault(norm(e), []).append(c["qid"]) return out def absence_entities(r) -> dict: """entity -> [qid] for every entity a gold asserts absent (forbidden to the generators).""" out = {} for c in r["claims"]: for e in c.get("absence_entities") or []: out.setdefault(norm(e), []).append(c["qid"]) return out def atoms_of(r, batch_id): return [a for a in r["atoms"] if a["batch_id"] == batch_id] def check(r) -> list: errs = [] ids = [a["atom_id"] for a in r["atoms"]] if len(ids) != len(set(ids)): errs.append("duplicate atom_id") bids = [b["batch_id"] for b in r["batches"]] if len(bids) != len(set(bids)): errs.append("duplicate batch_id") known = set(ids) for c in r["claims"]: for a in c.get("depends_on_atoms") or []: if a not in known: errs.append(f"{c['qid']} depends on unknown atom {a}") g = str(c.get("grounding") or "") if g.startswith("synthetic:"): b = g.split(":", 1)[1] if b not in bids: errs.append(f"{c['qid']} claims synthetic batch {b} which is not registered") if not (c.get("depends_on_atoms") or []): errs.append(f"{c['qid']} is synthetic but depends on no injected atom") elif g == "record": if c.get("depends_on_atoms"): errs.append(f"{c['qid']} is grounding=record but depends on injected atoms {c['depends_on_atoms']}") else: errs.append(f"{c['qid']} has grounding={g!r}; it must be 'record' or 'synthetic:'") for a in r["atoms"]: b = next((x for x in r["batches"] if x["batch_id"] == a["batch_id"]), None) if a["applied"] and b and not b["applied"]: errs.append(f"atom {a['atom_id']} applied but its batch {a['batch_id']} is not") ge, ae = set(gold_entities(r)), set(absence_entities(r)) for e in ge & ae: errs.append(f"entity {e!r} is both a gold entity and an absence entity") return errs def registry(a) -> None: """--init an empty registry, --show it, or --check its invariants.""" r = load() if a.init: if REGISTRY.exists(): sys.exit(f"{REGISTRY} already exists; refusing to overwrite (the registry is append-only)") r["patient_id"] = PATIENT save(r) print(f"initialised empty registry -> {REGISTRY}") return if a.show or not (a.check): print(f"registry: {REGISTRY} patient={r['patient_id']}") print(f" batches: {len(r['batches'])} atoms: {len(r['atoms'])} claims: {len(r['claims'])}") for b in r["batches"]: n = len(atoms_of(r, b["batch_id"])) dep = sum(1 for c in r["claims"] if str(c.get("grounding")) == f"synthetic:{b['batch_id']}") print(f" [{'applied' if b['applied'] else 'PLANNED'}] {b['batch_id']:<18} axis={b['axis']} " f"atoms={n:<3} questions={dep:<3} {b['purpose']}") ge, ae = gold_entities(r), absence_entities(r) print(f" gold entities (no injection may mention): {len(ge)}") print(f" absence entities (no injection may make present): {len(ae)}") for e, q in list(ae.items())[:6]: print(f" ABSENT {e!r} <- {q}") if a.check: errs = check(r) print(f"invariant check: {'PASS' if not errs else f'{len(errs)} FAILURES'}") for e in errs: print(" ", e) sys.exit(1 if errs else 0) def _gold_of(q: dict) -> tuple[str | None, str]: """Return (answer, answer_type) across the gold fields the axis modules write.""" at = q.get("answer_type") or "" if "answer" in q and q["answer"] is not None: return q["answer"], at or "open_exact" if q.get("options"): correct = [o for o in q["options"] if o.get("is_correct")] if correct: return "; ".join(o.get("content", o.get("label", "")) for o in correct), at or "multiple_choice" return None, at def entities_of(q: dict, axis: int): """-> (gold_entities, absence_entities, unresolved_reason|None)""" op = (q.get("derivation") or {}).get("operands") or {} ax = q.get("axis_specific") or {} g, a = [], [] if axis == 5: for k in ("absent_entity", "absent_entity_bare"): if op.get(k) or ax.get(k): a.append(op.get(k) or ax.get(k)) for k in ("anchor_entity",): if op.get(k) or ax.get(k): g.append(op.get(k) or ax.get(k)) return g, a, None if a else "axis5 question without an absent_entity" for k in ("entity", "series_entity", "measure_label", "absent_entity"): v = op.get(k) or ax.get(k) if v: (a if k == "absent_entity" else g).append(v) if g or a: return g, a, None gold, _ = _gold_of(q) if not gold: gold = (q.get("derivation") or {}).get("gold") if gold: ents = [str(gold)[:80]] for o in q.get("options") or []: if o.get("is_correct") and o.get("content"): ents.append(str(o["content"])[:80]) return ents, [], f"axis{axis}: no entity field; the gold text is used" return [], [], f"axis{axis}: no entity and no gold" def claims() -> None: """Register every question of the bank as a registry claim (gold and absence entities per question, extracted per axis from the generators' fields); unresolved extractions are reported.""" reg = load() n, unres = 0, [] for axis in range(1, 9): p = BASE / f"questions_axis{axis}.jsonl" if not p.exists(): continue rows = [json.loads(l) for l in open(p, encoding="utf-8") if l.strip()] for i, q in enumerate(rows): qid = q.get("qid") or f"{PATIENT}/axis{axis}/{i:03d}" gr = q.get("grounding") if not gr: unres.append(f"{qid}: no grounding; not registered") continue ge, ae, why = entities_of(q, axis) if why: unres.append(f"{qid}: {why}") add_claim(reg, qid, str(axis), gr, ge, ae, (q.get("axis_specific") or {}).get("depends_on_atoms") or []) n += 1 save(reg) print(f"registered {n} claims -> {REGISTRY}") ge, ae = gold_entities(reg), absence_entities(reg) print(f" gold entities: {len(ge)}") print(f" absence entities: {len(ae)}") for e, q in list(ae.items())[:8]: print(f" ABSENT {e[:64]!r} <- {q}") if unres: print(f"\n {len(unres)} unresolved:") for u in unres[:8]: print(f" {u}") errs = check(reg) print(f"\ninvariants: {'PASS' if not errs else f'{len(errs)} FAIL'}") for e in errs[:5]: print(" ", e) MECHANISMS = { 6: {"space": ["steadily increased", "steadily decreased", "increased then decreased", "decreased then increased", "remained essentially unchanged"], "read": lambda c: (c.get("derivation", {}).get("operands", {}) or {}).get("shape_class") or (c.get("axis_specific", {}) or {}).get("shape_class")}, } SYNTHETIC_AXES = (3, 5, 6, 7) def targets() -> None: """Synthetic-question need of each axis with a generator: the count of record questions below PER_AXIS_MINIMUM plus one question for every mechanism of the axis without a record candidate. Writes synthetic_targets.json.""" rows, out = [], {} for ax in SYNTHETIC_AXES: p = BASE / f"questions_axis{ax}.jsonl" if not p.exists(): continue cs = [q for q in (json.loads(l) for l in open(p, encoding="utf-8") if l.strip()) if "synthetic" not in str(q.get("grounding", ""))] n_record = len(cs) minimum = PER_AXIS_MINIMUM[ax] count_gap = max(0, minimum - n_record) mech_gap, seen, space = [], Counter(), [] if ax in MECHANISMS: space = MECHANISMS[ax]["space"] read = MECHANISMS[ax]["read"] for c in cs: m = read(c) if m: seen[m] += 1 mech_gap = [m for m in space if seen.get(m, 0) == 0] need = count_gap + len(mech_gap) out[str(ax)] = { "axis": ax, "n_record": n_record, "minimum": minimum, "count_gap": count_gap, "mechanism_space": space, "mechanism_seen": dict(seen), "mechanism_gap": mech_gap, "inject": need, "reason": ("count" if count_gap and not mech_gap else "mechanism" if mech_gap and not count_gap else "count+mechanism" if mech_gap else "none"), } rows.append(out[str(ax)]) (BASE / "synthetic_targets.json").write_text(json.dumps( {"patient_id": PATIENT, "axes": out, "total_inject": sum(r["inject"] for r in rows)}, ensure_ascii=False, indent=1)) print(f"synthetic-question targets, patient {PATIENT}\n") print(f"{'axis':<5}{'record':>7}{'min':>6}{'count':>7}{'mech gap':>26}{'inject':>7} reason") print("-" * 76) for r in rows: mg = ",".join(r["mechanism_gap"])[:24] or "-" print(f"{r['axis']:<5}{r['n_record']:>7}{r['minimum']:>6}{r['count_gap']:>7}{mg:>26}{r['inject']:>7} " f"{r['reason']}") print("-" * 76) print(f"{'TOTAL':<5}{sum(r['n_record'] for r in rows):>7}{'':>6}{sum(r['count_gap'] for r in rows):>7}" f"{'':>26}{sum(r['inject'] for r in rows):>7}") for r in rows: if r["mechanism_gap"] and not r["count_gap"]: print(f"\n NOTE axis-{r['axis']}: {r['n_record']}/{r['minimum']} by count but " f"{len(r['mechanism_seen'])}/{len(r['mechanism_space'])} by mechanism " f"({dict(r['mechanism_seen'])}).") print(f"\n-> {BASE/'synthetic_targets.json'}") def generate(a) -> None: """Author synthetic question+atom pairs for the axes below their target -> synthetic_pairs.json. The operands are authored (by LLM where needed) and the atom and its question are emitted together; golds use the same templates and formulas as the discovered questions. Grounding is synthetic:.""" for stale in ("synthetic_pairs.json", "injection_plan.json"): (BASE / stale).unlink(missing_ok=True) reg = load() forbidden = sorted(set(gold_entities(reg)) | set(absence_entities(reg))) chain = [json.loads(l) for l in open(BASE / "event_chain.jsonl", encoding="utf-8") if l.strip()] by_v = {r["visit_number"]: r for r in chain} need_by_axis = json.loads((BASE / "synthetic_targets.json").read_text())["axes"] cli = _SkipFailedCalls(ChatClient(model=a.model, reasoning_effort="medium", max_completion_tokens=4000)) made = [] for ax in [int(x) for x in a.axes.split(",")]: need = need_by_axis.get(str(ax), {}).get("inject", 0) if not need: continue batch = f"synthetic-axis{ax}" print(f"axis{ax}: authoring {need} synthetic question+atom pairs", flush=True) with Progress(f"synth axis{ax}", total=need, out=str(BASE / f"progress_synth{ax}.json")) as pg: fn = {3: axis3.synthesize, 5: axis5.synthesize, 6: axis6.synthesize, 7: axis7.synthesize}.get(ax) if not fn: print(f" no synthetic generator for axis{ax}; skipped") continue try: if ax == 6: ex = [json.loads(l).get("entity", "") for l in open(BASE / "evidence_chain.jsonl", encoding="utf-8") if json.loads(l).get("aspect") == "test_result"] items = fn(cli, chain, by_v, forbidden, need, batch, ex) else: items = fn(cli, chain, by_v, forbidden, need, batch) for item in items: made.append(item) pg.tick(ok=True) except Exception as e: print(f" FAILED: {str(e)[:200]}") pg.tick(ok=False) if made: (BASE / "synthetic_pairs.json").write_text(json.dumps( {"patient_id": PATIENT, "n": len(made), "pairs": made}, ensure_ascii=False, indent=1)) print(f"\n{len(made)} pairs -> {BASE/'synthetic_pairs.json'}") for x in made[:3]: print(f" Q: {x['q']['question'][:100]}") print(f" A: {x['q']['answer'][:100]}") print(f" atom: {x['atom']['text'][:70]}\n") else: print("nothing generated") if cli.failed: sys.exit(f"{cli.failed} model calls failed; their items were skipped") class _SkipFailedCalls: """Wraps a client: a call that still fails after the client's retries is reported and returns {}, so the synthesizer drops that item and keeps the others.""" def __init__(self, cli): self.cli, self.failed = cli, 0 def complete_json(self, *args, **kwargs): try: return self.cli.complete_json(*args, **kwargs) except Exception as e: self.failed += 1 print(f" call failed: {str(e)[:200]}") return {} def _question_entity(q, ax): """The entity a synthetic question stores itself (axis 6 series, axis 5 anchor), as a list.""" ops = (q.get("derivation") or {}).get("operands") or {} if ax == "6": v = ops.get("series_entity") elif ax == "5": v = (q.get("axis_specific") or {}).get("anchor_entity") or ops.get("anchor_entity") else: v = None return [v] if v else [] def _plan_atom_ids(q): """The injection-plan atom ids of a synthetic question: one per evidence entry with a visit.""" batch = f"synthetic-axis{q['qid'].split('/axis')[1][0]}" return [f"{batch}/{q['qid'].split('/')[-1]}_{i}" for i, e in enumerate((q.get("derivation") or {}).get("evidence") or []) if e.get("visit") is not None] def wire() -> None: """Append each synthetic question to its axis bank and build injection_plan.json from the evidence atoms of every synthetic question, with the entities and topic their generator gave, so those atoms enter the chain before dialogues are generated.""" pairs_f = BASE / "synthetic_pairs.json" pairs = json.loads(pairs_f.read_text())["pairs"] if pairs_f.exists() else [] by_ax = defaultdict(list) for p in pairs: by_ax[p["q"]["qid"].split("/axis")[1][0]].append(p["q"]) added = Counter() for bank in sorted(BASE.glob("questions_axis*.jsonl")): ax = bank.stem.split("axis")[1] kept = [l for l in open(bank, encoding="utf-8") if l.strip() and "synthetic" not in str(json.loads(l).get("grounding", ""))] with open(bank, "w", encoding="utf-8") as fh: fh.writelines(kept) for q in by_ax.get(ax, []): q.setdefault("axis_specific", {})["depends_on_atoms"] = _plan_atom_ids(q) fh.write(json.dumps(q, ensure_ascii=False) + "\n") added[ax] += 1 dept_of = {r["visit_number"]: r.get("department") for r in (json.loads(l) for l in open(BASE / "event_chain.jsonl", encoding="utf-8") if l.strip())} authored = {} for p in pairs: for x in (p.get("atom"), p.get("atom2"), *(p.get("atoms") or [])): if x: authored[(p["q"]["qid"], int(x["visit_number"]), norm(x["text"]))] = x plan = [] for f in sorted(glob.glob(str(BASE / "questions_axis*.jsonl"))): for l in open(f): q = json.loads(l) if "synthetic" not in str(q.get("grounding", "")): continue ax = q["qid"].split("/axis")[1][0] batch = f"synthetic-axis{ax}" for i, e in enumerate((q.get("derivation") or {}).get("evidence") or []): if e.get("visit") is None: continue src = authored.get((q["qid"], int(e["visit"]), norm(e.get("atom"))), {}) ents = list(src.get("entities") or []) or _question_entity(q, ax) plan.append({ "atom_id": f"{batch}/{q['qid'].split('/')[-1]}_{i}", "batch_id": batch, "axis": ax, "visit_number": e.get("visit"), "date": e.get("date"), "department": dept_of.get(e.get("visit")), "field": e.get("field") or "doctor_extra_notes", "text": e.get("atom"), "entities": ents, "topic": src.get("topic"), "anchors_axis": ax, "anchors_on": []}) (BASE / "injection_plan.json").write_text(json.dumps( {"patient_id": PATIENT, "n": len(plan), "atoms": plan}, ensure_ascii=False, indent=1)) print(f"wired synthetic questions, patient {PATIENT}") print(f" questions appended: {dict(added)}") print(f" injection plan: {len(plan)} atoms {dict(Counter(a['batch_id'] for a in plan))}") print(f"-> {BASE/'injection_plan.json'}") def banks() -> None: """Write the axis 3-8 question banks from the discovered candidates.""" for n in (3, 4, 5, 6, 7, 8): cs = json.load(open(f"{BASE}/_discover_axis{n}.json"))["candidates"] with open(f"{BASE}/questions_axis{n}.jsonl", "w", encoding="utf-8") as fh: for c in cs: fh.write(json.dumps(c, ensure_ascii=False) + "\n") def short_axes() -> None: """Print the comma-separated synthetic-capable axes that need synthetic questions.""" d = json.load(open(BASE / "synthetic_targets.json"))["axes"] print(",".join(str(a) for a in SYNTHETIC_AXES if d.get(str(a), {}).get("inject", 0) > 0)) def batches() -> None: """Register one batch per synthetic axis of the injection plan.""" reg = load() plan = json.load(open(BASE / "injection_plan.json"))["atoms"] for b in sorted({a["batch_id"] for a in plan}): if not any(x["batch_id"] == b for x in reg["batches"]): add_batch(reg, b, b.split("axis")[-1], f"synthetic questions {b}") save(reg) def apply() -> None: """Apply the linted injection plan once: snapshot the chain, then write each synthetic atom into its host visit in event_chain.jsonl and a one-segment timeline into evidence_chain.jsonl. Idempotent by atom text.""" plan_p, rep_p = BASE / "injection_plan.json", BASE / "lint_report.json" if not plan_p.exists(): sys.exit(f"no {plan_p}; run the wire step first") plan = json.loads(plan_p.read_text())["atoms"] if not rep_p.exists(): sys.exit(f"no {rep_p}; run the lint gate before injecting") rep = json.loads(rep_p.read_text()) if not rep.get("pass"): sys.exit("lint_report.json says FAIL; refusing to inject (correct the plan, re-lint, then apply)") if rep.get("n_planned") != len(plan): sys.exit(f"lint_report covers {rep.get('n_planned')} atoms but the plan has {len(plan)}; " f"re-run python -m pipeline.gates lint") reg = load() ec = BASE / "event_chain.jsonl" evc = BASE / "evidence_chain.jsonl" snap = BASE / "event_chain.preinject.jsonl" if not snap.exists(): shutil.copy2(ec, snap) print(f" snapshot -> {snap}") chain = [json.loads(l) for l in open(ec, encoding="utf-8") if l.strip()] by_v = {r["visit_number"]: r for r in chain} tl = [json.loads(l) for l in open(evc, encoding="utf-8") if l.strip()] added, skipped = 0, 0 for a in plan: v = by_v.get(a["visit_number"]) if v is None: sys.exit(f"atom {a['atom_id']} targets missing visit {a['visit_number']}") bucket = v.setdefault(a["field"], []) if any(norm(x) == norm(a["text"]) for x in bucket): skipped += 1 continue bucket.append(a["text"]) ent = next((x for x in (a.get("entities") or []) if x), None) or a.get("topic") or a["text"] tl.append({ "entity": ent, "aspect": "constraint_or_safety" if a["axis"] == "3" else "other", "source_field": a["field"], "current_status": a["text"], "segments": [{"value": a["text"], "valid_from": {"date": a["date"], "visit_number": a["visit_number"]}, "valid_until": "current", "status": "current", "supporting_visits": [a["visit_number"]], "superseded_by": None}], "department": a["department"] or v.get("department"), "batch_id": a["batch_id"], }) added += 1 with open(ec, "w", encoding="utf-8") as fh: for r in chain: fh.write(json.dumps(r, ensure_ascii=False) + "\n") with open(evc, "w", encoding="utf-8") as fh: for t in tl: fh.write(json.dumps(t, ensure_ascii=False) + "\n") for a in plan: if not any(x["atom_id"] == a["atom_id"] for x in reg["atoms"]): reg["atoms"].append({**{k: a[k] for k in ("atom_id", "batch_id", "axis", "visit_number", "date", "department", "field", "text", "entities", "topic", "anchors_axis")}, "applied": True}) for b in reg["batches"]: b["applied"] = True save(reg) print(f"applied: {added} atoms injected, {skipped} already present") print(f" event_chain.jsonl: {len(chain)} visits") print(f" evidence_chain.jsonl: {len(tl)} timelines (+{added})") print(f" registry: {len(reg['atoms'])} atoms, all batches applied") def main(): ap = argparse.ArgumentParser(description="Stages D and E: registry, targets, synthetic questions, injection.") sp = ap.add_subparsers(dest="cmd", required=True) r = sp.add_parser("registry") for flag in ("--init", "--show", "--check"): r.add_argument(flag, action="store_true") sp.add_parser("claims") sp.add_parser("targets") g = sp.add_parser("generate") g.add_argument("--model", required=True) g.add_argument("--axes", required=True) for name in ("banks", "short-axes", "wire", "batches", "apply"): sp.add_parser(name) a = ap.parse_args() {"registry": lambda: registry(a), "claims": claims, "targets": targets, "banks": banks, "short-axes": short_axes, "generate": lambda: generate(a), "wire": wire, "batches": batches, "apply": apply}[a.cmd]() if __name__ == "__main__": main()