#!/usr/bin/env python3 """Build deterministic, provenance-bound router training records without sealed-eval leakage.""" from __future__ import annotations import argparse from collections import defaultdict from datetime import datetime, timezone import hashlib import json from pathlib import Path from typing import Any ROOT = Path(__file__).resolve().parents[2] REASONING = ROOT / "downloads/datasets/_acquisition/fable-reasoning-440267f/Fable-5-Distill-5500x.jsonl" CODING = ROOT / "downloads/datasets/_acquisition/fable-agent-coding-c63e82a/data" TOKENIZER = ROOT / "downloads/models/_acquisition/lfm25-fable5-72d68fc/tokenizer.json" CONTRACT = ROOT / "config/benching/fable-router-curriculum.v2.json" def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for block in iter(lambda: handle.read(1024 * 1024), b""): digest.update(block) return digest.hexdigest() def identity(text: str) -> str: return hashlib.sha256(text.strip().encode("utf-8")).hexdigest() def stable_split(value: str) -> str: bucket = int(hashlib.sha256(value.encode("utf-8")).hexdigest()[:8], 16) % 1000 return "train" if bucket < 900 else "validation" if bucket < 950 else "test" def flattened_message_text(messages: list[dict[str, Any]]) -> str: chunks: list[str] = [] for message in messages: chunks.extend([str(message.get("role") or ""), str(message.get("reasoning_content") or ""), str(message.get("content") or "")]) for call in message.get("tool_calls") or []: function = call.get("function") or {} chunks.extend([str(function.get("name") or ""), str(function.get("arguments") or "")]) return "\n".join(chunks) def token_count(tokenizer: Any, text: str) -> int: return len(tokenizer.encode(text).ids) def choose_shortest(rows: list[dict[str, str]], tokenizer: Any, maximum: int) -> tuple[dict[str, str] | None, int]: candidates = [] for row in rows: if not all((row.get(key) or "").strip() for key in ("prompt", "reasoning", "answer")): continue count = token_count(tokenizer, "\n".join([row["prompt"], row["reasoning"], row["answer"]])) if count <= maximum: candidates.append((count, len(row["reasoning"]) + len(row["answer"]), row)) if not candidates: return None, 0 count, _, selected = min(candidates, key=lambda item: (item[0], item[1], identity(item[2]["answer"]))) return selected, count def target_message(row: dict[str, Any]) -> dict[str, Any]: messages = row.get("messages") or [] if not messages or messages[-1].get("role") != "assistant": raise ValueError("cumulative prefix does not end in an assistant target") return messages[-1] def has_tool_target(row: dict[str, Any]) -> bool: return bool(target_message(row).get("tool_calls")) def select_historical_prefixes(rows: list[dict[str, Any]]) -> list[dict[str, Any]]: ordered = sorted(rows, key=lambda row: (int(row["assistant_step"]), int(row["target_message_index"]))) selected = [] first_tool = next((row for row in ordered if has_tool_target(row)), None) if first_tool is not None: selected.append(first_tool) if not selected or selected[-1] is not ordered[-1]: selected.append(ordered[-1]) return selected def rejected_target(target: dict[str, Any]) -> tuple[str, dict[str, Any]] | None: calls = target.get("tool_calls") or [] if calls: rejected = dict(target) rejected["tool_calls"] = calls + calls return "duplicate_tool_call", rejected content = str(target.get("content") or "").strip() reasoning = str(target.get("reasoning_content") or "").strip() if not content and not reasoning: return None rejected = dict(target) if content: rejected["content"] = content + "\n\n" + content else: rejected["reasoning_content"] = reasoning + "\n\n" + reasoning return "repeated_completion", rejected def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: with path.open("w", encoding="utf-8", newline="\n") as handle: for row in rows: handle.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n") def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output-root", type=Path) parser.add_argument("--maximum-tokens-before-template", type=int, default=1900) args = parser.parse_args() if not 256 <= args.maximum_tokens_before_template <= 2048: raise SystemExit("maximum token count must be between 256 and 2048") from tokenizers import Tokenizer try: import polars as pl except ImportError as exc: raise SystemExit("polars is required") from exc tokenizer = Tokenizer.from_file(str(TOKENIZER)) stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") output = (args.output_root or ROOT / "downloads/audits" / f"fable-router-curriculum-data-{stamp}").resolve() output.mkdir(parents=True, exist_ok=False) sft: dict[str, list[dict[str, Any]]] = defaultdict(list) preferences: list[dict[str, Any]] = [] excluded = defaultdict(int) reasoning_groups: dict[str, list[dict[str, str]]] = defaultdict(list) with REASONING.open("r", encoding="utf-8") as handle: for line in handle: row = json.loads(line) reasoning_groups[identity(row.get("prompt") or "")].append(row) for prompt_id, rows in sorted(reasoning_groups.items()): chosen, tokens = choose_shortest(rows, tokenizer, args.maximum_tokens_before_template) if chosen is None: excluded["reasoning_empty_or_overflow"] += 1 continue split = stable_split(prompt_id) sft[split].append({ "schema": "AutonomaFableRouterRecord.v2", "id": f"reasoning:{prompt_id}", "split": split, "lane": "host_preservation", "routerEligibility": "preserve", "lossPolicyKey": "host_preservation", "messages": [{"role": "user", "content": chosen["prompt"]}, {"role": "assistant", "reasoning_content": chosen["reasoning"], "content": chosen["answer"]}], "tokensBeforeTemplate": tokens, "source": {"repo": "HelioAI/Claude-Fable-5-5500x", "revision": "440267fbdb1b00a40216e7233dbce25530a0ed09", "promptSha256": prompt_id, "duplicateCandidates": len(rows)} }) frames = [pl.read_parquet(path) for path in sorted(CODING.glob("*.parquet"))] grouped: dict[str, list[dict[str, Any]]] = defaultdict(list) for row in pl.concat(frames, how="vertical_relaxed").to_dicts(): grouped[str(row["source_trajectory_sha256"])].append(row) for trajectory_id, rows in sorted(grouped.items()): attested = [row for row in rows if row.get("model_attested") and str(row.get("verifier") or "").strip()] chosen_rows = sorted(attested, key=lambda row: int(row["assistant_step"])) if attested else select_historical_prefixes(rows) lane = "verified_expert" if attested else "interaction_pattern" eligibility = "expert" if attested else "conditional" for row in chosen_rows: messages = row.get("messages") or [] tokens = token_count(tokenizer, flattened_message_text(messages)) if tokens > args.maximum_tokens_before_template: excluded[f"{lane}_overflow"] += 1 continue split = stable_split(trajectory_id) record_id = f"agent:{trajectory_id}:{int(row['assistant_step'])}" sft[split].append({ "schema": "AutonomaFableRouterRecord.v2", "id": record_id, "split": split, "lane": lane, "routerEligibility": eligibility, "lossPolicyKey": lane, "messages": messages, "tokensBeforeTemplate": tokens, "target": {"assistantStep": int(row["assistant_step"]), "toolCall": has_tool_target(row), "terminal": not has_tool_target(row)}, "source": {"repo": "greghavens/fable-5-coding-and-debugging-traces", "revision": "c63e82adec30798edcbd6e1dcb0014d2b15de236", "trajectorySha256": trajectory_id, "task": row.get("task"), "verifier": row.get("verifier"), "modelAttested": bool(row.get("model_attested")), "derivation": row.get("derivation")} }) if split == "train": negative = rejected_target(target_message(row)) if negative: kind, rejected = negative preferences.append({ "schema": "AutonomaFableRouterPreference.v2", "id": record_id + ":" + kind, "split": "train", "lane": "loop_negative", "routerEligibility": eligibility, "lossPolicyKey": "loop_negative", "context": messages[:-1], "chosen": messages[-1], "rejected": rejected, "negativeType": kind, "sourceRecordId": record_id }) files = [] for split in ("train", "validation", "test"): rows = sorted(sft[split], key=lambda row: row["id"]) path = output / f"sft-{split}.jsonl" write_jsonl(path, rows) files.append({"path": path.name, "rows": len(rows), "bytes": path.stat().st_size, "sha256": sha256(path), "lanes": {lane: sum(row["lane"] == lane for row in rows) for lane in sorted({r["lane"] for r in rows})}}) preference_path = output / "preference-train.jsonl" write_jsonl(preference_path, sorted(preferences, key=lambda row: row["id"])) files.append({"path": preference_path.name, "rows": len(preferences), "bytes": preference_path.stat().st_size, "sha256": sha256(preference_path), "negativeTypes": {kind: sum(row["negativeType"] == kind for row in preferences) for kind in sorted({r["negativeType"] for r in preferences})}}) result = { "schema": "AutonomaFableRouterCurriculumBuild.v2", "status": "curriculum_built_nonrouting", "nonRouting": True, "trainingAuthorized": False, "createdAt": datetime.now(timezone.utc).isoformat(), "contract": {"path": str(CONTRACT), "sha256": sha256(CONTRACT)}, "sources": [{"path": str(REASONING), "sha256": sha256(REASONING)}, {"path": str(TOKENIZER), "sha256": sha256(TOKENIZER)}, {"path": str(CODING.parent / "dataset-manifest.json"), "sha256": sha256(CODING.parent / "dataset-manifest.json")}], "maximumTokensBeforeTemplate": args.maximum_tokens_before_template, "finalTrainerRetokenizationRequired": True, "files": files, "excluded": dict(sorted(excluded.items())), "frozenEvaluationRead": False } result_path = output / "result.json" result_path.write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") print(result_path) return 0 if __name__ == "__main__": raise SystemExit(main())