File size: 19,399 Bytes
833376d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
"""Export paired CoQAR runs without model calls or silently dropping failures."""
from collections import Counter, defaultdict
from datetime import datetime, timezone
import hashlib
import json
import math
from pathlib import Path
import statistics

from scale_client import read_calls, read_cost_summary


def _hash(value):
    return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True,
                                     allow_nan=False).encode()).hexdigest()


def _save(path, value):
    temporary = path.with_suffix(path.suffix + ".tmp")
    temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False))
    temporary.replace(path)


def _call(identifier, by_id, story, question, stage, menu=None, selected_id=None):
    attempts = by_id.get(identifier, [])
    completed = [call for call in attempts if call.get("status") == "completed"]
    call = completed[0] if completed else None
    errors = ["multiple_completed_attempts"] if len(completed) > 1 else []
    if call:
        request = call["request"]
        if _hash(request) != call.get("request_sha256"):
            errors.append("request_hash_mismatch")
        try:
            prefix = "Input JSON:\n"
            if not request["input"].startswith(prefix):
                raise ValueError("Unexpected input prefix")
            payload = json.loads(request["input"][len(prefix):])
            if payload.get("story") != story or payload.get("question") != question:
                errors.append("input_story_or_question_mismatch")
            expected = {"story", "question"} | ({"menu", "selected_id"} if stage == "render"
                                                 else {"samples"} if stage == "audit" else set())
            if set(payload) != expected:
                errors.append("unexpected_model_visible_fields")
            if stage == "render" and (payload.get("menu") != menu
                                       or payload.get("selected_id") != selected_id):
                errors.append("render_menu_or_selection_mismatch")
        except (ValueError, TypeError, KeyError):
            errors.append("invalid_saved_input")
        try:
            if json.loads(call["text"]) != call.get("parsed"):
                errors.append("response_text_parsed_mismatch")
        except (ValueError, TypeError, KeyError):
            errors.append("invalid_saved_response_text")
        extracted = "".join(part.get("text", "") for item in call.get("response", {}).get("output", [])
                            if item.get("type") == "message" for part in item.get("content", [])
                            if part.get("type") == "output_text")
        if extracted != call.get("text"):
            errors.append("response_body_text_mismatch")
    return call, attempts, errors


def _menu_errors(menu):
    if not isinstance(menu, dict):
        return ["missing_menu"]
    errors = []
    items = menu.get("items", [])
    if not isinstance(items, list) or not 1 <= len(items) <= 5:
        return ["invalid_item_count"]
    if any(not isinstance(item, dict) for item in items):
        return ["invalid_item_type"]
    ids = [item.get("id") for item in items]
    if any(not isinstance(value, str) or not value for value in ids) or len(set(ids)) != len(ids):
        errors.append("invalid_item_ids")
    masses = [item.get("probability") for item in items]
    if any(type(p) not in (int, float) or not math.isfinite(p) or p < 0 for p in masses):
        errors.append("invalid_probabilities")
    elif not math.isclose(sum(masses), 1, abs_tol=0.02):
        errors.append("probabilities_do_not_sum_to_one")
    if menu.get("status") == "already_answerable":
        if not (menu.get("gap") == "" and menu.get("constraints") == []
                and len(items) == 1 and ids == ["unchanged"] and masses == [1]):
            errors.append("already_answerable_contract")
    elif menu.get("status") != "underspecified" or "unchanged" in ids:
        errors.append("underspecified_contract")
    return errors


def _audit_map(audit, expected):
    fields = {"sample_index": int, "answerable": bool, "answer": str, "answer_cluster": str,
              "contradiction": bool, "contradiction_evidence": str, "unrelated_addition": bool,
              "selected_state_compliant": bool, "evidence": str}
    items = audit.get("assessments", []) if isinstance(audit, dict) else []
    valid = (isinstance(items, list) and len(items) == expected and all(
        isinstance(item, dict) and set(item) == set(fields)
        and all(type(item[key]) is kind for key, kind in fields.items()) for item in items))
    if not valid or sorted(item["sample_index"] for item in items) != list(range(expected)):
        return {}, False
    return {item["sample_index"]: item for item in items}, True


def export_run(run_dir: Path, metadata: dict, subset: dict, config: dict) -> dict:
    """Include every planned example/draw and every saved network attempt."""
    run_dir = Path(run_dir)
    examples = subset["examples"]
    conditions = config.get("conditions", ["original", "modified"])
    expected = config.get("samples_per_example", 5)
    jobs = {}
    for condition in conditions:
        for example in examples:
            name = hashlib.sha256(example["id"].encode()).hexdigest()[:24] + ".json"
            path = run_dir / "examples" / condition / name
            jobs[condition, example["id"]] = json.loads(path.read_text()) if path.exists() else {}
    calls = read_calls(run_dir / "api.sqlite") if (run_dir / "api.sqlite").exists() else []
    by_id = defaultdict(list)
    for call in calls:
        by_id[call["id"]].append(call)
    temporary = run_dir / "requests.jsonl.tmp"
    with temporary.open("w") as handle:
        for call in calls:
            handle.write(json.dumps(call, ensure_ascii=False, allow_nan=False) + "\n")
    temporary.replace(run_dir / "requests.jsonl")
    source_path = Path(__file__).resolve().parent / config["source_path"]
    source = {row["id"]: row for row in json.loads(source_path.read_text())["data"]}
    summary = {"metadata": metadata, "exported_utc": datetime.now(timezone.utc).isoformat(),
               "configuration": config, "conditions": {}, "cost": read_cost_summary(run_dir / "api.sqlite")
               if calls else {}, "judgment_source": "Raw Luna audits; no human or Codex review",
               "limitations": ["Mechanical ablation does not guarantee unanswerability.",
                               "Repeated question turns from one story are statistically dependent.",
                               "Answer clusters, coherence, and state compliance are model judgments.",
                               "Diversity is conditional on audited valid samples and may reflect judge error."]}
    for condition in conditions:
        exported, counts, question_metrics, all_errors = {}, Counter(), [], []
        counts.update({key: 0 for key in (
            "samples_recorded", "samples_completed_calls", "samples_valid_format_and_provenance",
            "samples_exactly_unchanged", "samples_raw_empty_addition", "samples_expected_noop_contract",
            "samples_business_contract_errors", "samples_provenance_errors", "samples_audited",
            "raw_audit_complete_and_coherent", "raw_audit_contradictions", "raw_audit_state_compliant",
            "raw_audit_complete_and_state_compliant", "audit_answerable_evidence_not_exact_substring")})
        distinct, disagreement = [], []
        for example in examples:
            eid, question = example["id"], example["question"]
            story = example[condition + "_story"]
            job = jobs[condition, eid]
            prefix = f"{metadata['experiment_fingerprint'][:12]}/{condition}/{eid}"
            provenance = []
            raw = source.get(example["story_id"], {})
            raw_question = next((q for q in raw.get("questions", [])
                                 if q["turn_id"] == example["turn_id"]), {})
            if raw.get("story") != example["original_story"] or question not in raw_question.get("paraphrase", []):
                provenance.append("source_story_or_question_mismatch")
            if job and (job.get("id") != eid or job.get("input_story") != story
                        or job.get("question") != question or job.get("condition") != condition):
                provenance.append("job_input_mismatch")
            if job and job.get("metadata", {}).get("experiment_fingerprint") != metadata["experiment_fingerprint"]:
                provenance.append("job_experiment_mismatch")
            menu = job.get("menu")
            menu_call, menu_attempts, menu_check = _call(job.get("menu_call_id", prefix + "/menu"), by_id, story, question, "menu")
            menu_errors = _menu_errors(menu)
            if menu_call and menu_call.get("parsed") != menu:
                menu_check.append("menu_response_mismatch")
            counts["jobs_recorded"] += bool(job)
            counts["jobs_marked_complete"] += bool(job.get("complete"))
            counts["menus_completed"] += bool(menu_call)
            counts["menu_business_contract_valid"] += bool(menu_call and not menu_errors)
            counts["menus_already_answerable"] += bool(isinstance(menu, dict) and menu.get("status") == "already_answerable")
            counts["menus_already_answerable_contract_valid"] += bool(
                isinstance(menu, dict) and menu.get("status") == "already_answerable" and not menu_errors)
            audit_call, audit_attempts, audit_check = _call(job.get("audit_call_id", prefix + "/audit"), by_id, story, question, "audit")
            audit = job.get("audit")
            assessments, audit_valid = _audit_map(audit, expected)
            if audit_call and audit_call.get("parsed") != audit:
                audit_check.append("audit_response_mismatch")
            audit_valid = bool(audit_valid and audit_call and not audit_check)
            counts["audit_groups_valid_schema"] += audit_valid
            actual = {sample["sample_index"]: sample for sample in job.get("samples", [])}
            if len(actual) != len(job.get("samples", [])) or any(i not in range(expected) for i in actual):
                provenance.append("duplicate_or_invalid_sample_indices")
            clarifications, clusters, compliant_clusters, unchanged = [], [], [], 0
            for index in range(expected):
                sample = actual.get(index, {"sample_index": index, "missing": True})
                call, attempts, checks = _call(sample.get("api_call_id", prefix + f"/sample/{index}"), by_id, story, question,
                                              "render", menu, sample.get("selected_id"))
                raw_value = call.get("parsed") if call else None
                value = raw_value if isinstance(raw_value, dict) else {}
                addition = value.get("addition")
                business = []
                if call and (value.get("status") == "already_answerable" and addition != ""
                             or value.get("status") == "completed" and not str(addition or "").strip()):
                    business.append("render_status_addition_contract")
                if call and (not isinstance(menu, dict) or sample.get("selected_id") not in
                             [item.get("id") for item in menu.get("items", [])]):
                    checks.append("selected_item_missing")
                mismatch = (sample["raw_parsed"] != raw_value if "raw_parsed" in sample else
                            sample.get("addition") != addition or sample.get("status") != value.get("status"))
                if call and not sample.get("missing") and mismatch:
                    checks.append("sample_parsed_response_mismatch")
                shape = (set(value) == {"status", "addition", "justification"}
                         and value.get("status") in ("completed", "already_answerable")
                         and isinstance(addition, str) and isinstance(value.get("justification"), str))
                if shape and not sample.get("missing"):
                    reconstructed = story + ("\n\n" + addition.strip() if addition.strip() else "")
                    if sample.get("clarified_story") != reconstructed:
                        checks.append("clarified_story_reconstruction_mismatch")
                valid = bool(call and shape and sample.get("valid_format") and not checks and not provenance and not menu_check)
                exact = bool(valid and sample.get("clarified_story") == story)
                unchanged += exact
                counts["samples_recorded"] += not sample.get("missing", False)
                counts["samples_completed_calls"] += bool(call)
                counts["samples_valid_format_and_provenance"] += valid
                counts["samples_exactly_unchanged"] += exact
                counts["samples_raw_empty_addition"] += bool(call and addition == "")
                counts["samples_expected_noop_contract"] += bool(valid and exact and addition == ""
                                                                 and value.get("status") == "already_answerable")
                counts["samples_business_contract_errors"] += bool(business)
                counts["samples_provenance_errors"] += bool(checks or provenance)
                assessment = assessments.get(index) if audit_valid else None
                evidence_match = None
                if assessment:
                    counts["samples_audited"] += 1
                    complete = valid and assessment["answerable"] and not assessment["contradiction"]
                    counts["raw_audit_complete_and_coherent"] += complete
                    counts["raw_audit_contradictions"] += assessment["contradiction"]
                    counts["raw_audit_state_compliant"] += assessment["selected_state_compliant"]
                    counts["raw_audit_complete_and_state_compliant"] += complete and assessment["selected_state_compliant"]
                    evidence_match = bool(assessment["evidence"] and assessment["evidence"] in sample.get("clarified_story", ""))
                    counts["audit_answerable_evidence_not_exact_substring"] += assessment["answerable"] and not evidence_match
                    if complete:
                        clusters.append(assessment["answer_cluster"])
                        if assessment["selected_state_compliant"]:
                            compliant_clusters.append(assessment["answer_cluster"])
                clarifications.append({**sample, "generation_call": call, "generation_attempts": attempts,
                                       "provenance_errors": checks, "business_contract_errors": business,
                                       "audit_assessment": assessment, "audit_evidence_is_exact_substring": evidence_match})
            counts["questions_all_outputs_exactly_unchanged"] += unchanged == expected
            hist = Counter(clusters)
            distinct.append(len(hist))
            n = len(clusters)
            pair = 1 - sum(c * (c - 1) for c in hist.values()) / (n * (n - 1)) if n >= 2 else None
            if pair is not None:
                disagreement.append(pair)
            question_metrics.append({"id": eid, "raw_complete_answers": n, "answer_clusters": dict(hist),
                                     "pairwise_disagreement": pair, "complete_state_compliant": len(compliant_clusters)})
            errors = [*job.get("errors", []), *provenance, *menu_check, *audit_check]
            counts["groups_provenance_errors"] += bool(provenance or menu_check or audit_check)
            all_errors.extend({"id": eid, "error": error} for error in errors)
            exported[eid] = {"original_story": example["original_story"], "modified_story": example["modified_story"],
                             "input_story": story, "question": question, "removed_sentences": example["removed_sentences"],
                             "applied_removed_sentences": example["removed_sentences"] if condition == "modified" else [],
                             "flags": example["flags"], "missing": not bool(job),
                             "interpretation_stage": {"menu": menu, "call": menu_call, "attempts": menu_attempts,
                                                      "business_contract_errors": menu_errors},
                             "clarifications": clarifications, "audit": audit, "audit_call": audit_call,
                             "audit_attempts": audit_attempts, "errors": errors}
        planned = len(examples) * expected
        audit_planned = condition == "modified" and config.get("audit_damaged_outputs", True)
        summary["conditions"][condition] = {"expected_examples": len(examples), "expected_samples": planned,
            "counts": dict(counts), "missing_samples": planned - counts["samples_recorded"],
            "unaudited_samples": planned - counts["samples_audited"],
            "audit_planned": audit_planned,
            "raw_complete_fraction_of_planned": counts["raw_audit_complete_and_coherent"] / planned if audit_planned else None,
            "mean_distinct_raw_complete_answers": statistics.mean(distinct) if audit_planned else None,
            "mean_pairwise_disagreement": statistics.mean(disagreement) if disagreement else None,
            "questions_with_two_raw_complete_answers": len(disagreement), "per_question": question_metrics,
            "errors": all_errors}
        _save(run_dir / f"{condition}_validation.json", {"metadata": metadata, "condition": condition,
                                                       "samples": exported, "errors": all_errors})
    _save(run_dir / "summary.json", summary)
    lines = ["# CoQAR dev: paired two-step v2 run", "", "All planned examples and draws are retained, including missing or failed outputs.", "",
             "Judgments below are raw Luna audits, without human or Codex corrections. Exact unchanged counts are mechanical checks.", "",
             "| Condition | Planned draws | Recorded | Valid format + provenance | Exactly unchanged | Audited | Raw complete + coherent |", "|---|---:|---:|---:|---:|---:|---:|"]
    for condition, metrics in summary["conditions"].items():
        c = metrics["counts"]
        complete = c.get("raw_audit_complete_and_coherent", 0) if metrics["audit_planned"] else "not audited"
        lines.append(f"| {condition} | {metrics['expected_samples']} | {c.get('samples_recorded', 0)} | {c.get('samples_valid_format_and_provenance', 0)} | {c.get('samples_exactly_unchanged', 0)} | {c.get('samples_audited', 0)} | {complete} |")
    cost = summary["cost"]
    lines += ["", f"Known token cost: ${cost.get('known_cost_usd', 0):.6f}. Conservative accounted amount: ${cost.get('accounted_usd', 0):.6f}, including input premium and unresolved reservations.", "",
              "Input sentence deletion does not guarantee missing evidence. Completion and diversity judgments are exploratory model measurements. Unaudited samples contribute no successes to the planned-draw fraction; their outcomes remain unknown.", "",
              "[Original validation](original_validation.json) · [Damaged validation](modified_validation.json) · [Full metrics](summary.json) · [Every request attempt](requests.jsonl)"]
    path = run_dir / "report.md"
    path.write_text("\n".join(lines) + "\n")
    return summary