From c3bbfc2a326855161f42408728275c9f56c8ac81 Mon Sep 17 00:00:00 2001 From: njord Date: Wed, 25 Nov 2026 09:09:19 -0600 Subject: [PATCH] Analyze explicit failed-sample retry lineages without double counting --- docs/claude-credit-campaign.md | 10 ++ src/synthbench/campaign_analysis.py | 144 ++++++++++++++++++++-- tests/test_campaign_analysis.py | 183 ++++++++++++++++++++++++++++ 3 files changed, 328 insertions(+), 9 deletions(-) diff --git a/docs/claude-credit-campaign.md b/docs/claude-credit-campaign.md index febd390..d09c200 100644 --- a/docs/claude-credit-campaign.md +++ b/docs/claude-credit-campaign.md @@ -52,6 +52,16 @@ again. Runtime, pricing, and question-input fingerprints prevent incompatible replays. A changed collector/runtime requires a new journal and a budget that subtracts prior spending. Keep a separate campaign-wide total across journals. +To repair an infrastructure failure, create a new task id with `retry_of` set +to the failed task id. Preserve its configuration, question, replicate, sample +index, and sample count. Keep the original manifest and journal unchanged and +pass all original and repair manifests/journals to the analyzer. Retry chains +must be linear, and every parent must have an observed final `error` record. +A completed answer, model refusal, or parse failure cannot be retried this way. +The terminal retry fills one logical sample slot; ancestor errors, charges, +and explicit recovery history remain in the analysis. Apply a separate repair +budget and include it in the campaign-wide total. + The request reserve uses UTF-8 bytes, framing allowance, output ceilings, and a cache-write premium. This is a conservative estimate, not a formal provider token-count guarantee. An observed overrun stops collection for reconciliation. diff --git a/src/synthbench/campaign_analysis.py b/src/synthbench/campaign_analysis.py index 4f00bf3..3992c5d 100644 --- a/src/synthbench/campaign_analysis.py +++ b/src/synthbench/campaign_analysis.py @@ -38,6 +38,55 @@ def _config_key(task): return json.dumps(_configuration(task), sort_keys=True) +def _retry_lineage(tasks, finals): + """Validate linear, explicit retries of final errors in the same sample slot.""" + parents, children = {}, {} + for task_id, task in tasks.items(): + if "retry_of" not in task: + continue + parent_id = task["retry_of"] + if not isinstance(parent_id, str) or parent_id not in tasks: + raise ValueError("Retry references an unknown parent task") + parent = tasks[parent_id] + if ( + _configuration(task) != _configuration(parent) + or task["question_key"] != parent["question_key"] + or task.get("replicate", 0) != parent.get("replicate", 0) + or task.get("sample_index", 0) != parent.get("sample_index", 0) + or ( + "_question_hash" in task + and "_question_hash" in parent + and task["_question_hash"] != parent["_question_hash"] + ) + ): + raise ValueError("Retry parent and child must describe the same sample") + if parent_id in children: + raise ValueError("Retry lineage must be linear; branching retries rejected") + parents[task_id], children[parent_id] = parent_id, task_id + + roots = {} + for task_id in tasks: + path, visited = [], set() + current = task_id + while current not in roots: + if current in visited: + raise ValueError("Retry lineage contains a cycle") + visited.add(current) + path.append(current) + if current not in parents: + break + current = parents[current] + root = roots.get(current, current) + for member in path: + roots[member] = root + for parent_id in parents.values(): + if finals.get(parent_id, {}).get("status") != "error": + raise ValueError( + "Retry parent must have a final error, never a completed response" + ) + return roots, children + + def _number(value): if value is None: return None @@ -299,16 +348,29 @@ def analyze_campaign( for line in Path(path).read_text().splitlines(): if line.strip(): task = json.loads(line) + recorded = tasks.get(task["id"], {}) existing = { key: value - for key, value in tasks.get(task["id"], {}).items() + for key, value in recorded.items() if key != "_question_hash" } - if existing and existing != task: + manifest = { + key: value for key, value in task.items() if key != "_question_hash" + } + if existing and ( + existing != manifest + or ( + "_question_hash" in recorded + and "_question_hash" in task + and recorded["_question_hash"] != task["_question_hash"] + ) + ): raise ValueError("Task manifest conflicts with journal") - tasks[task["id"]] = task + # Collector-added question hashes remain available for lineage checks. + tasks[task["id"]] = {**recorded, **task} if attempts.keys() - reservations.keys(): raise ValueError("Attempt has no reservation") + roots, children = _retry_lineage(tasks, finals) if split is not None and selection is None: raise ValueError("--split requires --selection") if selection: @@ -345,7 +407,7 @@ def analyze_campaign( row["key"]: row for row in (raw["questions"] if isinstance(raw, dict) else raw) } - cells = defaultdict(dict) + cells = defaultdict(lambda: defaultdict(list)) for task, final in members: key = (task["question_key"], task.get("replicate", 0)) sample = task.get("sample_index", 0) @@ -358,11 +420,49 @@ def analyze_campaign( or not 0 <= sample < expected ): raise ValueError("Invalid sample index or expected sample count") - if sample in cells[key]: - raise ValueError("Duplicate logical sample across task ids") - cells[key][sample] = final + cells[key][sample].append((task, final)) output_cells = [] - for (question_key, replicate), by_sample in sorted(cells.items()): + for (question_key, replicate), sample_tasks in sorted(cells.items()): + by_sample, retry_history = {}, [] + for sample, records in sorted(sample_tasks.items()): + if len({roots[task["id"]] for task, _ in records}) != 1: + raise ValueError( + "Duplicate logical sample across task ids without retry lineage" + ) + terminal = [ + (task, final) + for task, final in records + if task["id"] not in children + ] + if len(terminal) != 1: + raise ValueError( + "Logical sample must have exactly one terminal retry" + ) + leaf, final = terminal[0] + by_sample[sample] = final + if len(records) > 1: + root = roots[leaf["id"]] + chain = [root] + while chain[-1] in children: + chain.append(children[chain[-1]]) + retry_history.append( + { + "sample_index": sample, + "root_task_id": root, + "task_ids": chain, + "statuses": [ + finals.get(task_id, {}).get("status", "pending") + for task_id in chain + ], + "errors": [ + finals.get(task_id, {}).get("error") + for task_id in chain + ], + "selected_task_id": leaf["id"], + "recovered": final is not None + and final["status"] == "completed", + } + ) q = lookup[question_key] question = Question( key=question_key, @@ -385,9 +485,15 @@ def analyze_campaign( "n_completed": len(complete_rows), "missing_sample_indices": missing, "n_errors": sum( + row is not None and row["status"] == "error" + for records in sample_tasks.values() + for _, row in records + ), + "n_unresolved_error_samples": sum( row is not None and row["status"] == "error" for row in by_sample.values() ), + "retry_history": retry_history, "scores": None, } if not missing: @@ -432,12 +538,32 @@ def analyze_campaign( for rep in sorted({cell["replicate"] for cell in output_cells}) }, "questions": output_cells, + "retry_coverage": { + "retried_samples": sum( + len(cell["retry_history"]) for cell in output_cells + ), + "retry_tasks": sum( + len(history["task_ids"]) - 1 + for cell in output_cells + for history in cell["retry_history"] + ), + "recovered_samples": sum( + history["recovered"] + for cell in output_cells + for history in cell["retry_history"] + ), + "unresolved_retried_samples": sum( + not history["recovered"] + for cell in output_cells + for history in cell["retry_history"] + ), + }, "billing": _billing(relevant_reservations, relevant_attempts), "response_latency": _latencies( [ _number(row.get("elapsed_seconds")) for _, row in members - if row is not None + if row is not None and row["status"] == "completed" ] ), "settings_counts": dict( diff --git a/tests/test_campaign_analysis.py b/tests/test_campaign_analysis.py index 8a4908f..298fa24 100644 --- a/tests/test_campaign_analysis.py +++ b/tests/test_campaign_analysis.py @@ -345,3 +345,186 @@ def test_conflicting_logical_samples_and_split_overlap_fail_closed(files): directory, selection={"fixture": {"development": ["q0"], "evaluation": ["q0"]}}, ) + + +def _repair(task, suffix="repair", **overrides): + return {**task, "id": f"{task['id']}-{suffix}", "retry_of": task["id"], **overrides} + + +def _charge(task, amount, elapsed): + return [ + { + "kind": "reservation", + "attempt_id": task["id"], + "task_id": task["id"], + "reserved_usd": amount, + }, + { + "kind": "attempt", + "attempt_id": task["id"], + "task_id": task["id"], + "accounted_usd": amount, + "cost_source": "provider-reported-max-gateway-upstream", + "usage": {"cost": amount}, + "elapsed_seconds": elapsed, + }, + ] + + +def test_explicit_repair_fills_one_slot_and_retains_error_cost_and_history(files): + directory, write = files + original = {**_task(n=1), "_question_hash": "snapshot-v1"} + repair = _repair(original) + failed = {**_final(original, status="error"), "elapsed_seconds": 10} + completed = _final(repair) + original_path = write([*_charge(original, "0.1", 10), failed], "original.jsonl") + repair_path = write([*_charge(repair, "0.2", 2), completed], "repair.jsonl") + # Ordering input files does not change the declared causal lineage. + result = analyze_campaign([repair_path, original_path], directory) + config = result["configurations"][0] + cell = config["questions"][0] + assert cell["complete"] and cell["n_completed"] == 1 + assert cell["n_errors"] == 1 + assert cell["n_unresolved_error_samples"] == 0 + assert cell["retry_history"] == [ + { + "sample_index": 0, + "root_task_id": original["id"], + "task_ids": [original["id"], repair["id"]], + "statuses": ["error", "completed"], + "errors": ["TransportError", None], + "selected_task_id": repair["id"], + "recovered": True, + } + ] + assert config["retry_coverage"] == { + "retried_samples": 1, + "retry_tasks": 1, + "recovered_samples": 1, + "unresolved_retried_samples": 0, + } + assert config["billing"]["accounted_usd"] == pytest.approx(0.3) + assert result["all_journal_billing"]["accounted_usd"] == pytest.approx(0.3) + assert config["billing"]["attempt_latency"]["mean_seconds"] == 6 + assert config["response_latency"]["count"] == 1 + assert config["response_latency"]["mean_seconds"] == 2 + assert config["errors"] == {"TransportError": 1} + + +@pytest.mark.parametrize( + ("option", "refusal"), [("A", False), (None, False), (None, True)] +) +def test_retry_of_completed_answer_parse_failure_or_refusal_is_rejected( + files, option, refusal +): + directory, write = files + original = _task(n=1) + repair = _repair(original) + path = write([_final(original, option=option, refusal=refusal), _final(repair)]) + with pytest.raises(ValueError, match="final error"): + analyze_campaign([path], directory) + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("dataset", "other"), + ("question_key", "q1"), + ("model", "other"), + ("provider", "openrouter"), + ("elicitation", "structured"), + ("persona_pack", "global-respondents"), + ("replicate", 1), + ("sample_index", 1), + ("samples_per_question", 6), + ("_question_hash", "changed-snapshot"), + ], +) +def test_retry_cannot_change_sample_scope_or_question_snapshot(files, field, value): + directory, write = files + original = {**_task(), "_question_hash": "original-snapshot"} + repair = _repair(original, **{field: value}) + path = write([_final(original, status="error"), _final(repair)]) + with pytest.raises(ValueError, match="same sample"): + analyze_campaign([path], directory) + + +def test_retry_unknown_parent_cycle_and_branch_fail_closed(files): + directory, write = files + original = _task(n=1) + repair = _repair(original) + with pytest.raises(ValueError, match="unknown parent"): + analyze_campaign([write([_final(repair)])], directory) + cyclic_original = {**original, "retry_of": repair["id"]} + with pytest.raises(ValueError, match="cycle"): + analyze_campaign( + [ + write( + [ + _final(cyclic_original, status="error"), + _final(repair, status="error"), + ] + ) + ], + directory, + ) + alternate = _repair(original, suffix="alternate") + with pytest.raises(ValueError, match="branching"): + analyze_campaign( + [ + write( + [ + _final(original, status="error"), + _final(repair), + _final(alternate), + ] + ) + ], + directory, + ) + + +def test_failed_to_failed_to_completed_retry_chain_and_pending_terminal(files): + directory, write = files + original = _task(n=1) + first = _repair(original) + second = _repair(first) + rows = [ + _final(original, status="error"), + _final(first, status="error"), + _final(second), + ] + result = analyze_campaign([write(rows)], directory) + cell = result["configurations"][0]["questions"][0] + assert cell["n_completed"] == 1 and cell["n_errors"] == 2 + assert cell["retry_history"][0]["task_ids"] == [ + original["id"], + first["id"], + second["id"], + ] + assert cell["retry_history"][0]["statuses"] == ["error", "error", "completed"] + manifest = write([original, first, second], "tasks.jsonl") + result = analyze_campaign([write(rows[:2])], directory, task_files=[manifest]) + config = result["configurations"][0] + assert config["questions"][0]["missing_sample_indices"] == [0] + assert config["questions"][0]["retry_history"][0]["statuses"] == [ + "error", + "error", + "pending", + ] + assert config["retry_coverage"]["unresolved_retried_samples"] == 1 + + +def test_retry_parent_requires_observed_error_final_and_preserves_journal_hash(files): + directory, write = files + original = _task(n=1) + repair = _repair(original) + manifest = write([original, repair], "tasks.jsonl") + with pytest.raises(ValueError, match="final error"): + analyze_campaign([write([_final(repair)])], directory, task_files=[manifest]) + original_row = _final({**original, "_question_hash": "old"}, status="error") + repair_row = _final({**repair, "_question_hash": "new"}) + with pytest.raises(ValueError, match="same sample"): + analyze_campaign( + [write([original_row, repair_row])], directory, task_files=[manifest] + )