diff --git a/.dockerignore b/.dockerignore index 2e3eabcc..378e5ec4 100644 --- a/.dockerignore +++ b/.dockerignore @@ -6,7 +6,10 @@ **/__pycache__ **/*.pyc examples/**/data +# deco_hallu_explore copies these frozen case manifests (276 KB) into its image. +!examples/m1_m5/deco_hallu/data/cases examples/**/outputs examples/**/outputs.* examples/**/*.zip **/.env +**/node_modules diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 04e188c5..10770ed4 100755 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,7 +46,7 @@ jobs: strategy: fail-fast: false matrix: - python-version: ["3.10", "3.11", "3.12"] + python-version: ["3.11", "3.12"] steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 @@ -89,6 +89,15 @@ jobs: # is a field the frontend cannot see, which is the drift the contract # exists to catch -- so catch it on the commit that causes it. run: python -m evalrx.contract.export --out docs/contract --check + - name: Type-check + # Once is enough: [tool.mypy] pins the target to Python 3.11. It runs + # here, not in the lint job, because it needs the installed extras to + # see the real types of torch, pydantic, fastapi, ... + # Pinned so a new mypy release cannot turn CI red on unchanged code. + if: matrix.python-version == '3.11' + run: | + pip install "mypy==2.4.1" + mypy evalrx - name: Run fast unit tests run: pytest -m "not gpu and not network" --cov=evalrx --cov-report=xml -q - name: Upload coverage diff --git a/CHANGELOG.md b/CHANGELOG.md index 80b3c9ae..c6e2528a 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,366 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Added — typed judge calls + +`evalrx.agent_runtime.judge_call.ask_judge(judge, prompt, OutputModel, role=...)` +asks a judge for one pydantic object. PydanticAI runs the exchange: the +reply's first JSON value is validated, an invalid reply goes back to the +judge with the validation errors, and when the retry budget runs out +`JudgeOutputError` is raised (`JudgeCallError` when the judge itself fails). +Both carry every exchange for the log. Stages move onto it one by one and +drop their own parsers. + +### Changed — Python 3.11 and two new core dependencies + +`pydantic>=2.12` and `pydantic-ai-slim>=2.71,<3` are core dependencies, and +the package needs Python 3.11 (pydantic-ai does; Python 3.10 left upstream +support in October 2026). CI no longer tests 3.10. + +### Changed — the agentic loop's decision is a typed answer + +`decide` asks through `ask_judge` with an output model whose `tool` field only +admits registered tool names. Removed: `parse_action`, `ActionParseError`, +`ACTION_SCHEMA`, the `validate_json_shape` re-export from +`evalrx.eval_agent.agentic`, `ACTION_REPAIR_PROMPT`, and `decide(max_repairs=)` +(now `retries=`). Every decision exchange is logged with role `agent_decision` +and its attempt number; there is no separate `agent_decision_repair` role. + +### Changed — M3 asks for typed hypotheses and a typed review + +`DiagnosisAgent` asks for a `Proposal` (`hypotheses`: `hypothesis`, +`plain_statement`, `failure_mode` as a snake_case tag, `test`, +`expected_association`) and the critic for a `Review` (one keep/reject +decision per numbered hypothesis). The Markdown label parser and its +regexes, the format re-ask and the separate plain-language repair call are +gone: an invalid answer, or a plain statement that fails the jargon check, +goes back to the judge once with the reason. An empty proposal means "no +problem found" (was `NO_ISSUE`). + +A proposal that is still invalid after its retry now raises `JudgeOutputError` +instead of being replaced by template hypotheses; the loop logs every +exchange and retries M3 or stops. The report marks such a run's M3 stage `failed`, with +the reason (`stage_detail.m3.error`), on the loop figure and the M3 page. A critic with no usable answer keeps the +hypotheses with `review_unavailable`, as a failed critic call did before. +All proposer attempts are logged as role `diagnosis_judge`; the +`diagnosis_format_repair` and `diagnosis_plain_language_repair` roles are gone. + +### Changed — the remaining structured judge calls go through `ask_judge` + +M5 fix proposals (`FixAgent`), failure-mode cluster naming and error signals +(`cluster_failures`), and held-out grading (`holdout_confirm`) ask through +`ask_judge`, so a reply in prose or code fences is read, and an invalid one is +sent back with the errors instead of being repeated blind or dropped. A +held-out judge that gives no valid answer now records `verdict="not_judged"` +with `judge_error`, not `not_testable`. Every fix-judge attempt is logged +(`FixRecorder.judge_exchanges`). + +### Changed — M2 and case labeling ask for typed answers + +`StatsAnalysisAgent`'s written analysis is a typed answer (`conclusion`, +`evidence_chain`, `qualitative`) instead of `CONCLUSION:`/`EVIDENCE_CHAIN:` +sections, and its tool selection only accepts catalog names (the free-text +scan for any tool name in the reply is gone). An analysis that is still +invalid after one retry keeps the deterministic report, with the reason in +`llm_fallback_reason` and the judge's last answer in `llm_raw`. +`CaseDiscoveryAgent`'s judge label is typed (`PASS`/`FAIL`/`UNKNOWN`, any +case); a judge with no valid label falls back to the expected-answer +rubric, as an `UNKNOWN` label did, instead of keyword-scanning the reply. + +### Changed — `evalrx explore` hypotheses are a typed answer + +`HypothesisAgent` (the hypotheses after `explore()`) asks through `ask_judge` +for `hypotheses` (`hypothesis`, `plain_statement`, `basis`, `test`); the +`HYPOTHESIS:`/`PLAIN:` parser, its trajectory de-duplication and +`PLAIN_REPAIR_PROMPT` are gone, and a jargon-laden plain statement goes back +once through the same retry. With a CLI coding agent as the backend, the +agent now writes its answer to `answer.json` (new +`evalrx.agent_runtime.judges.cli_agent.CliAgentJudge`) instead of the +hypotheses being scraped from its whole tool-call trajectory, where a draft +could be read as the answer. + +### Changed — one way to run a CLI judge + +`ClaudeModel`, `CodexModel` and `AgyModel` run through the providers' +`SubprocessRunner`: a timeout kills the CLI's whole process group (its worker +processes outlived a plain `subprocess.run` timeout), Claude runs in a +throwaway directory instead of the caller's, and a limit notice printed as an +answer raises for every provider, not only Claude. +A coding agent (`claude_code`, `codex`, ...) that ends its session on a +limit notice and writes no files now reports `error="account limit reached: ..."` +instead of no error and no files. + +### Changed — one diagnosis loop; the judge-decided mode is a policy + +`AgenticDiagnoseLoop` is gone. Pass `policy=JudgePolicy(judge, max_actions=..., +time_budget_sec=..., registry_factory=...)` to `VLDiagnoseLoop` for the same +judge-decided run; the loop's own `explorer` becomes the `explore_data` tool. +`run_start` records the loop as `JudgePolicy`. A custom `registry_factory` +still receives `(loop, run_state)`; the decision judge is `run_state.judge` +(was `loop.judge`). + +The fixed M1→M4 cycle is a policy too, `FixedOrderPolicy`, and the default: +`loop.policy` is never `None`. A policy is any object with +`run(loop, data, timings) -> AutoDiagnoseReport`; `VLDiagnoseLoop.run` resets +the token count, calls it and logs `loop_end`. Both policies keep their +bookkeeping in one `evalrx.eval_agent.policy.RunState` (the agentic +`_RunState` is gone), and the `stopped_by` values are constants in +`loop_reports` (`STOPPED_BY_*`). + +### Removed + +- `create_sandbox`, `SandboxFactoryConfig`, `SandboxConfig` + (`evalrx.agent_runtime.factory`): nothing called them, and the `docker` mode + silently returned the subprocess sandbox. Use `ExperimentSandbox(workdir)`. +- `evalrx.agent_runtime.json_shape.validate_json_shape`: output models + validate with pydantic. + +## [0.2.0] — 2026-11-14 + +### Changed — the run logger and its readers lose their "V2" names + +There has been one run logger since 0.1.2, so its names no longer carry a +version. The old names are gone, with nothing forwarding to the new ones: + +| was | is | +|---|---| +| `evalrx.eval_agent.run_logger_v2` | `evalrx.eval_agent.run_logger` | +| `RunLoggerV2` | `RunLogger` | +| `read_v2_events` | `read_run_events` | +| `write_v2_bundle` | `write_run_bundle` | +| `resolve_v2_root` | `resolve_run_root` | +| `evalrx/eval_agent/RUN_LOGGER_V2.md` | `RUN_LOGGER.md`, rewritten to describe the current design | + +The Langfuse delivery queue's temp directory is `evalrx-outbox-`. + +### Changed — `run_logger.py` split by what each part does + +`RunLogger` keeps routing, stamping and atomic writes. What each event +records moved to `run_log_entries` (one pure function per event), what lands +on disk beside the JSON to `run_log_files`, and the Langfuse mirror of each +event to `run_log_tracing`. The `log_*` methods, their signatures, the files +they write and the tracer calls they make are unchanged. + +### Removed — reading runs written by earlier log versions + +A run is read from its log: `run.json` and `M1..M5/log.json`, as the current +logger writes them. The readers for what earlier versions kept in files +beside the log are gone: + +- `artifacts/c_.result.json`, `fixes/*/result.json` and + `outputs.jsonl`, `report/hypotheses.json`, `report/m4_results.json`, + `prompts/`, `tools/`, `manifest.json`, and an `explore/` directory beside + the logs of a loop run. +- The join against a benchmark data manifest that supplied case text for + runs whose log did not carry the cases. With it go `--example-dir` on + `evalrx report` / `evalrx publish-report` and the `example_dir` argument of + `build_report_data`, `publish_report`, `export_static_report`, + `RunContext.publish_report` and `VLDiagnoseLoop.publish_report`. + +- What the report inferred for logs that did not record it: the partition + of untagged case records (from the record order), a finished run from + `loop_end` (a run is finished when it logged `run_end`), the repair + numbering of contract payloads written before `ref`, and case text from + `report/discovery_cases.json`. +- Layouts published before two renderer changes: the `OutcomeCard` component + is no longer accepted, and elements without `props` are no longer patched + on load. +- Events without the envelope the logger stamps. Events are ordered by + `event_seq` (a log without it is not readable), and a `surgery` / `fix` + event is told apart by its own `module`. +- M3's `agent_response` and `unparsed_proposals` in `stage_detail` (and the + `UnparsedProposal` contract model): they were filled from a `prompts/` + directory. The aggregate M4 example shown when a log kept no validation + case, and M1 examples rebuilt for logs that recorded none, are gone too. +- The contract no longer maps the spellings `ebh` / `bh` (correction method) + or `env` / `critic` (trajectory step role) onto the current ones. + +A run logged by an earlier version is refused with a message that says so. +Re-run it to open it with this version. + +### Fixed — report fields that still looked for files no run writes + +- The Case Studio and M5's worked example show what the repair answered on + each case again. They read `outputs.jsonl` from a trial folder that is gone + by the time a run finishes; the fix event carries the same answers, and the + report reads them from there. +- The header names the agent that drove the run ("Claude Code · + claude-opus-5"). It looked for a `manifest.json` beside the log; the + `run_start` event records it. +- M2's rate comparison (failure rate with and without a signal) draws again: + the two rates are on the analysis event, not in an `artifacts/` file. +- The case study's example case shows its gold answer and the model's + baseline answer, read from the case record instead of + `report/discovery_cases.json`. +- Each M4 verdict card shows its own test statistics. With several + hypotheses, every card borrowed the last verdict's interval. +- A case with more than one media slot shows each file in its own slot. The + report paired a case's inputs with the copies the logger made by position, + in a different slot order than the logger wrote them, so an image-and-audio + case had the two swapped. They are paired by file name. +- The Case Studio lists a multiple-choice case's options (`metadata.options`, + else `metadata.choices`); the block was always empty. A case's label is its + `metadata.category`, else the task kind, so it is no longer blank on + datasets without categories. + +Report data is version 23. + +### Fixed — the pinned-M1 examples ran no analyzer on an audio model + +`mmau_qwen2_audio`, `audiocaps_hallucination_qwen2_audio`, +`musicavqa_videollama2` and the three VLM examples keyed their pinned +analyzer list on `vlm` / `agent` / `llm` only. An audio model is routed as +`alm` or `avlm`, so it was handed an empty list and M1 ran nothing. They key +the list on every `ModelKind`. + +### Changed — the explore agent's record shows for loop runs too + +M2's full record now carries the explore agent's code, output and audit for a +diagnosis run as well, read from the files the logger inlines on the explore +event. It was filled only for standalone explore outputs. + +### Removed — the first M2 tool layer; run log schema 8 + +`StatsToolAgent` (`evalrx.analysis.stats_tool_agent`: `scalar_summary` and +`per_case_signal_label_association`) ran beside the statistical tool layer +only to fill two report fields, `stats_tool_results` and `visualizations`. +Nothing read them: the M2 judge, M3, M4, the contract and the report all use +`stats_results` and `figures`. + +- `StatsToolAgent`, `StatsAnalysisAgent(stats_tool_agent=...)`, and + `StatsAnalysisReport.stats_tool_results` / `.visualizations` are removed. + `enable_stats_tools` is unchanged: it gates the statistical tool layer. +- The `analysis` event no longer carries `stats_tool_results` or + `visualizations`, so `RUN_LOG_SCHEMA_VERSION` is 8. + +### Removed — names and code paths kept from earlier iterations + +Each of these had a current replacement and stayed only so older code kept +working. They are gone, with no forwarding name left behind. + +- `QwenLLM()` / `QwenVL()`: use `evalrx.load("")` or a version + factory such as `qwen2_5_7b_instruct()`. +- The model aliases `"qwen"` and `"qwen2.5-7b"` and `resolve_spec_key`: name a + spec key (`evalrx.list_specs()`). An unknown key raises `KeyError`. +- `registry.models` and `register_model`: model identity lives in + `evalrx.specs`. +- `PureQADataset` and `evalrx.datasets.pure_qa`: use `LLMQADataset`. +- `evalrx.stats.sample_subset` (use `stratified_subset`) and `ab_test` (use + `compare`). +- A leading `call_` on `analysis:` in a config file is no longer stripped. +- `VLDiagnoseReport` (use `AutoDiagnoseReport`, the same class) and the + report's `all_hypotheses` property (use `final_hypotheses`). +- `evalrx.reporting.langfuse_exporter`: import `export_to_langfuse_bundle` / + `sync_to_langfuse_live` from `evalrx.observability`, or run + `evalrx export-langfuse`. +- `evalrx.cli.serve_report` and the hidden `evalrx serve --no-audio` flag, + which did nothing. +- The pre-0.1.2 module paths (`evalrx.models.backends.hf_local`, + `.jax_local`, `.openai_compat`, `.gemini_compat`, + `evalrx.models.blackbox.gemini`, `evalrx.models._discover`, + `evalrx.models.inference`, `evalrx.models.jax*`): import from + `evalrx.models.backends.{hf,jax,api}`. +- `AutoDiagnoseReport.final_results` (always empty) and `final_analysis` + (a mirror of `final_stats_report`). +- `Trial.write_record` / `Trial.write_result`, `RUN_LOGGER_V2_VERSION`, + `HFLocalModel._vcd_next_token_logits`, and the `_resolve_image` / + `_resolve_audio` names in `backends.hf.model` (use + `evalrx.models._media`): nothing called them. +- The held-out M4 probe no longer retries without `analyzers=` when a probe + agent raises `TypeError`. +- The report server no longer looks for case media in a `data/` folder beside + the run. The logger copies each case's media into the run's `media/`, and + the report serves that copy. +- `run_fix` calls its fix agent with `FixAgent`'s signature. It used to + inspect the agent and pass only the keywords it accepted, skip `recommend` + and `no_fix_recommendation` when they were missing, and hand back whatever + object `propose_and_validate` returned. A replacement agent now needs the + members listed under "A replacement fix agent" in `docs/stage_io.md` and + must return a `FixOutcome`; one that does not fails at the call instead of + running a tier ladder that ignores the tier. +- `DiagnosisAgent.diagnose` takes the M2 report only. It no longer wraps a + bare `{analyzer: Result}` dict, and its `model_name` argument (used only for + that dict) is gone: pass `AnalysisModule().analyze(results, model_name)`. +- `RunLogger.inline_text_artifacts` and `.preserve_full_model_io`. Both were + always true: they let a producer ask which logger it had, and there is one. + With them go the branches for the other answer, in which a model call's + text was cut at 8000 characters and a coded repair's prompt and code were + written as files in its trial folder, and the checks for whether the + logger has `log_model_exchange`. A stage records its model calls whenever + it has a run logger. +- `rejected_tools` in the multiplicity report (`fdr_correct`, + `StatsAnalysisReport.corrected_rejections`, `FusedReport.adjudication`): + read `rejected_result_keys`. A tool name stood for every result of that + tool, so one surviving signal marked all of `signal_label_assoc` as + surviving. M2's evidence chain, which M3 reads, now lists the surviving + results by key and names the correction that was applied (BH, e-BH or + mixed) instead of always saying e-BH. +- `evalrx.analysis.default_plan` and `AnalysisPlanItem.as_legacy_tuple`: call + `plan_stats_input`, which returns the `AnalysisPlanItem`s (`.tool`, + `.config`, `.rationale`) the tuples were made from. +- `compile_diagnostic_report` with `DiagnosticReport`, `Claim`, `Evidence` + and `ReportStep` (exported from `evalrx.reporting` and `evalrx.analysis`), + `evalrx.reporting.stages` (`STAGE_SPECS`, `StageSpec`, + `stage_specs_as_dicts`), `evalrx.viz.prompts` and `evalrx.viz.schema`: they + fed the dashboard server this release removes, and nothing else read them. + The report's opening summary (`compile_reader_report`) is unchanged. +- `evalrx.eval_agent.iter_log_errors` (it validated a `run_log.jsonl`, which + no logger writes; use `validate_event` per event), and the schema entries + for fields only the flat logger wrote: `judge_io`, `model_calls_path`, + `code_paths`, `output_paths`, `record`. + +### Added — follow a run while it is written + +`evalrx serve` on a run still in progress follows it: the top bar says "run in +progress" and the report on screen is replaced in place each time the run logs +something (server-sent events on `/api/runs/{id}/live`), until the run ends. +A run that goes quiet without ending says so, with how long it has been quiet, +instead of "report complete". The report carries `setting.finished` and +`setting.last_event_at`, so an export of an unfinished run says the same. + +### Changed — the run log records when a run ends: `run_end` + +`RunLogger.close()` writes a `run_end` event, the run-level completion +signal. `loop_end` ends M1–M4 only (M5 and the fix step log after it), which +is why it could not serve. A run whose log has no `run_end` is read as +unfinished. The new event type made the log schema 7; the removal of two +`analysis` fields (above) makes it 8. + +### Added — compare two runs in `evalrx serve` + +**Compare** in the report's top bar opens the run beside another one the +server lists (`#/compare/`): metrics and stage outcomes side by side, and +the shared cases (joined by id) that passed in one run and failed in the +other, each linking into the case studio. + +### Changed — the package type-checks, and CI enforces it + +`mypy evalrx` reports no errors (it reported 672) and now runs in CI. Most of +the work was declarations: analyzers declare the hyper-parameters +`Analyzer.__init__` stores with `setattr`, the HF backend mixins declare the +host attributes they use, and stages type their judge as the new +`evalrx.core.model.Judge` protocol (`capabilities` + `generate`), which every +`Model` and the CLI judges in `agent_runtime.judges` satisfy. Two real bugs it +found are listed under Fixed. `CapabilityError.missing` accepts any set. + +### Fixed — Docker-routed analyzers crashed on cases without a label + +`ProbeAgent(use_docker=True)` rebuilt each case inside the container with +`label=None` when the case had no usable label, so anything that serialised +the case (`FailureCase.to_dict()`) raised `AttributeError`. Such cases are +now `Label.UNKNOWN`, the field's own default. + +### Fixed — `ReportData.repairs` carried the per-case repair outcomes + +`build_report_data` reused the name `repairs` for M5's per-case outcomes, so +the report's `repairs` list (`[{id, fixed, title, effect, fixed_cases, +broken_cases}]`) was replaced by a `case id → outcome` dict, and the loop +figure, which reads `repairs[0]`, never showed the repair. The list is back; +the per-case outcomes still reach each case as `case.repair`. Its counts now +come from the same M5 result as the "Cases repaired" tile (the confirmation, +or the strongest scored candidate when none was certified); read from the fix +event alone they said "0 fixed" beside a tile of 3. + ### Added — validation report for the published weight edit on Qwen3.5-0.8B `docs/validation/astra_p50c_20261115.md` records the structure read-out, the @@ -108,8 +468,7 @@ with everything only they used: - `evalrx.eval_agent.orchestrator` (`EvalOrchestrator`) and what only it used: `ab_runner` (`ABRunner`, `ABResult`), `preregister` (`DataSplit`, `Split`, `PreregisteredHypothesis`, `PreregistrationLog`) and `report` - (`DiagnosticReport` — `evalrx.reporting.DiagnosticReport` is a different, - kept class). For a paired comparison use `evalrx.stats.compare`. + (`DiagnosticReport`). For a paired comparison use `evalrx.stats.compare`. - `evalrx.eval_agent._tools`, whose one live function `SurgeryAgent`'s parameter sweep now calls directly. @@ -127,20 +486,33 @@ from `evalrx.agent_runtime.providers.`; `SkillInstaller` / `evalrx.eval_agent` still exports `CliAgentConfig`, `CliAgentResult` and `create_cli_agent`. -### Removed — the `dashboard` report server (breaking) +### Removed — the `dashboard` report server and the legacy static report (breaking) Run reports have one UI: the React report (`evalrx serve` / `evalrx report` / -`evalrx publish-report`). +`evalrx publish-report`), for loop runs and explore outputs alike. - `evalrx dashboard` and `evalrx.analysis.dashboard` are removed: the standard-library server that served the legacy static `report.html`, and the `load_run` / `load_case_studies` / `load_loop_story` loaders, which nothing outside their tests used. Use `evalrx serve ` for a run. -- `evalrx explore`, `evalrx run-codebase` and `evalrx-explore`: an explore - output is not an M1–M5 run, and the React report cannot render one (all five - stages read "not run"), so these keep writing the legacy static - `report.html` (`evalrx.reporting.html_report`, now used only for this). - `--serve-report` opens that file in a browser instead of starting a server; +- `evalrx.reporting.html_report` (`build_html_report`, `generate_html_report`, + `embed_figures`, `embed_media`, and the `evalrx.reporting.build_html_report` + export) is removed. An explore output (`evalrx explore`, `evalrx + run-codebase`, a fused run) is now read as its own report: M2 and M3 show + as completed, the question and data come from its `exploratory_report.json` + (or `fused_report.json`), and the header counts patterns, charts and + proposed causes instead of cases. M2's full record carries what the legacy + page showed of the explore agent, for loop runs too: the analysis code it + ran, what it printed, its audit, and its trajectory (cut at 200 000 + characters; the run directory keeps the whole file). `evalrx serve ` works on it, + and the `report.html` these commands write is the React report's portable + export (`evalrx.reporting.static_export.write_report`). A source checkout + must build the renderer (`npm run build` in `evalrx/reporting/web`) for that + file; without it the run finishes and says why the file was not written. + The example images that run an explore step build the renderer in a Node + stage, and no longer ask for the `dashboard` extra, which no longer exists. +- `evalrx explore`, `evalrx run-codebase` and `evalrx-explore`: + `--serve-report` opens the written `report.html` in a browser instead of starting a server; the deprecated `--dashboard` alias and `--port` are removed (`evalrx-explore` had `--dashboard`, now `--serve-report`). The `run_explore` / `run_codebase_cli` keywords `dashboard` / `dashboard_port` become @@ -224,13 +596,14 @@ log lines now come from the `evalrx.eval_agent.loop_fix` logger. ### Changed — the run reader moved to `evalrx.reporting.run_data` -`extract_run_data` (and the run-layout helpers and analyzer glossary it uses) -moved from `evalrx.reporting.html_report` to `evalrx.reporting.run_data`. It -is the reader behind the dynamic report, the Langfuse bundle export and the -legacy static page, and no longer lives inside the legacy renderer. -`html_report` keeps the static page (`build_html_report`, -`generate_html_report`, `embed_figures`, `embed_media`). Import -`extract_run_data` from `evalrx.reporting.run_data`. +`extract_run_data` (and the run-layout helpers it uses) moved from +`evalrx.reporting.html_report` to `evalrx.reporting.run_data`. It is the +reader behind the report and the Langfuse bundle export. Import +`extract_run_data` from `evalrx.reporting.run_data`; `html_report` itself is +gone (see the removal above). + +The reader is one function per stage now, and the analyzer glossary and the +M1 results live in `evalrx.reporting.run_probes`. ### Changed — FixAgent split into the `stages/fix/` package @@ -275,17 +648,13 @@ unchanged. Visible differences: - After `run_fix(max_tier=...)` or an `auto_escalate` run, the agent keeps its configured `max_tier`; it used to keep the requested or last-tried tier, which leaked into the next `run_fix` call. -- A custom fix agent whose `propose_and_validate` cannot take - `max_tier`/`min_tier` now raises `TypeError` under `auto_escalate` or an - explicit `max_tier`, instead of running every rung at its own tier. -- A custom fix agent whose `propose_and_validate` does not take `record` - is no longer silenced during the search (the loop used to set its - `run_logger` to `None`); it logs whatever it logs per round. -- Under `auto_escalate` without a held-out split, a custom agent's opaque - (non-`FixOutcome`) result is returned as-is, as the held-out ladder - already did, instead of raising `AttributeError`. - -### Fixed — RunLoggerV2 outbox on multi-user hosts +- A replacement fix agent is called with these keywords and must return a + `FixOutcome`: see "A replacement fix agent" in `docs/stage_io.md`. One + whose `propose_and_validate` cannot take `max_tier` / `min_tier` / + `record` raises `TypeError` at the call, instead of running every rung at + its own tier. + +### Fixed — the Langfuse outbox on multi-user hosts The Langfuse outbox lived in a single shared `/tmp/evalrx-v2-outbox`, owned by whichever user created it first; every other user's run then failed with diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7c11cc26..ed76d656 100755 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -49,7 +49,7 @@ provides an inventory command. Generated files are preserved locally. ```bash ruff check . -mypy evalrx --ignore-missing-imports +mypy evalrx # settings in pyproject.toml; CI runs it too ``` ## Adding a model @@ -77,8 +77,7 @@ The new analyzer is instantly discoverable via `registry.analyzers.names_compati ## Pull requests - Keep PRs focused: one analyzer, one model, or one infrastructure change per PR. -- All configured CI checks must pass: Ruff, the frontend format/lint/tests/build, contract export, - documentation build, and the non-GPU/non-network test suite. Mypy is an - additional local check, not currently a CI gate. +- All configured CI checks must pass: Ruff, mypy, the frontend format/lint/tests/build, + contract export, documentation build, and the non-GPU/non-network test suite. - Add or update the relevant entry in `CHANGELOG.md` under `[Unreleased]`. - Include paper citations (arXiv link + BibTeX key) for any method from the literature. diff --git a/docs/architecture.md b/docs/architecture.md index 51212135..61c65b13 100755 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -193,7 +193,9 @@ VLDiagnoseLoop (loop.py — protocol-guided, stops on verified hypothesis) │ M5 · SurgeryAgent called once post-loop on the best verified hypothesis -AgenticDiagnoseLoop (agentic/loop.py — judge-decided, same M1-M4 stages) +The cycle above is the default policy, FixedOrderPolicy (policy.py). + +VLDiagnoseLoop(policy=JudgePolicy(judge)) (agentic/policy.py — judge-decided, same M1-M4 stages) A CLI judge picks the next tool (run_probe / run_stats / explore_data / cluster_failures / search_probes / propose_hypotheses / test_hypothesis / run_surgery / run_fix / stop) each turn from an EvidenceBoard, instead of a @@ -207,8 +209,7 @@ The agent touches models only through the `Model` protocol and stores all evidence in a `Store`. `.run()` on both loops returns the same class, `AutoDiagnoseReport` -(`loop_reports.py`; `VLDiagnoseReport` is a back-compat alias for the -identical class). Each loop populates only the fields relevant to what it +(`loop_reports.py`). Each loop populates only the fields relevant to what it ran — see [Stage Input/Output Reference](stage_io.md#loop-level-output) for the full field table. @@ -218,13 +219,16 @@ the full field table. eval_agent/ ├── loop.py VLDiagnoseLoop (current) ├── loop_fix.py run_fix orchestration: fix targets, tier ladder, EXPLORE→CONFIRM -├── loop_reports.py AutoDiagnoseReport (VLDiagnoseReport is an alias — all -│ both loops return this one unified report class) +├── loop_reports.py AutoDiagnoseReport — the one report class both policies return +├── policy.py FixedOrderPolicy (default M1→M4 cycles) + RunState, shared by both policies ├── run_metadata.py shared run-provenance + logging-wiring helpers -├── agentic/ AgenticDiagnoseLoop — judge-decided M1-M4 (see below) +├── agentic/ JudgePolicy — judge-decided M1-M4 (see below) ├── run_context.py RunContext, Trial — single owner of a run's output directory -├── run_logger_v2.py RunLoggerV2 — run.json + per-stage M/log.json event log -├── log_schema.py published event JSON Schema +├── run_logger.py RunLogger — run.json + per-stage M/log.json event log +├── run_log_entries.py what each logged event records, one pure function per event +├── run_log_files.py atomic JSON writes, inlined sandbox workspaces, saved artifacts +├── run_log_tracing.py each logged event mirrored into Langfuse +├── log_schema.py published event JSON Schema ├── hypothesis.py Hypothesis, HypothesisStatus — shared across M3/M4/M5 ├── store.py Store / InMemoryStore / JsonlStore └── stages/ ← M1, M3, M4, M5 stage implementations (M2 lives in evalrx.analysis) @@ -234,6 +238,7 @@ eval_agent/ ├── diagnosis.py M3 DiagnosisAgent, DiagnosisResult ├── surgery.py M5 SurgeryAgent, InterventionResult ├── experiment_writer.py M5 ExperimentWriter + ├── experiment_code.py M5 reading + static checks of the code it writes ├── fix/ M5 (post-loop) tiered repair │ ├── agent.py FixAgent — orchestrates the modules below │ ├── types.py FixCandidate, FixValidation, FixOutcome, FixContext @@ -421,8 +426,7 @@ Key properties: not timed out), preserving failure artefacts for debugging. `SandboxProtocol` is a structural type allowing transparent substitution of subprocess, -Docker, SSH, or other backends. `create_sandbox(SandboxFactoryConfig, workdir)` selects -the backend from a `mode` string (`"subprocess"` default, `"docker"` with graceful fallback). +Docker, SSH, or other backends; `ExperimentSandbox` is the one implementation shipped. ### Persistent store — `JsonlStore` @@ -470,7 +474,7 @@ result.image_overlays(fig_dir, stem_prefix) # -> list[Path] lazy `Inputs.image` paths/URLs the same way the model's forward pass did (`transformers.image_utils.load_image`), so the overlay matches what was actually fed to the model. `image_overlays()` is a duck-typed hook: -`RunLoggerV2` calls it on any `Result` that defines it and saves the PNGs +`RunLogger` calls it on any `Result` that defines it and saves the PNGs into `M1/artifacts/` alongside the bare heatmaps, so overlays flow into the same artifact list a multimodal judge already receives — no per-analyzer wiring required. @@ -481,7 +485,7 @@ wiring required. files, a logger buried under a `logs/` subdir, hand-built figure-dir paths, and M5 sandboxes living in ephemeral temp dirs deleted on success. One `RunContext` owns the whole run root and hands every producer its -subdirectory, always through `RunLoggerV2` (`evalrx/eval_agent/RUN_LOGGER_V2.md`) — +subdirectory, always through `RunLogger` (`evalrx/eval_agent/RUN_LOGGER.md`) — there is no other logger to select: ```text @@ -512,19 +516,18 @@ run provenance — `model`, `judge`, `git_commit` (falls back to the the example Docker images), `data_fingerprint` (an order-independent hash of the case batch, so two runs can be confirmed to use the same data) and `label_distribution` (the base PASS/FAIL/UNKNOWN counts the diagnosis is -conditioned on). Nothing is externalized the way V1's `{"path", "n_items", -"bytes"}` payload placeholder was — `stats_results`, `findings`, and every -other per-event field are inlined verbatim in the stage's JSON document. -`evalrx/reporting/run_events.py`'s `read_v2_events(root)` flattens `run.json` +conditioned on). Nothing is externalized — `stats_results`, `findings`, and +every other per-event field are inlined verbatim in the stage's JSON document. +`evalrx/reporting/run_events.py`'s `read_run_events(root)` flattens `run.json` + every `M/log.json` back into one ordered, flat event list (the same shape every downstream reader — dynamic report, HTML export, dashboard, Langfuse backfill — consumes), so most code never has to know about the per-stage bucketing directly: ```python -from evalrx.reporting.run_events import read_v2_events +from evalrx.reporting.run_events import read_run_events -events = read_v2_events("run_dir") # run_dir or run_dir/logs +events = read_run_events("run_dir") # run_dir or run_dir/logs diagnoses = [e for e in events if e["event"] == "diagnosis"] # all judge outputs probes = [e for e in events if e["event"] == "probe"] # M1 findings ``` @@ -551,7 +554,7 @@ from evalrx.eval_agent import validate_event validate_event(event) # raises jsonschema.ValidationError on a violation ``` -Set `EVALRX_VALIDATE_LOG=1` to have `RunLoggerV2` self-check every event it +Set `EVALRX_VALIDATE_LOG=1` to have `RunLogger` self-check every event it writes against the schema and warn (never raise) on a violation — a CI/dev aid to catch a producer drifting from the contract. Both paths need the optional `jsonschema` dependency (`pip install evalrx[dev]`). @@ -584,8 +587,8 @@ on first write, so a candidate discarded before producing anything (e.g. a deduped proposal) leaves no empty folder — a gap in the numbering honestly means "proposed, then discarded," not a missing record. `ctx.new_workdir(label)` is the non-trial equivalent for sandboxes that don't belong to a numbered -attempt (e.g. M1/M2 tool codegen). Under V2 there are no persisted trial -folders at all — a trial's generated code/output is inlined into its stage's +attempt (e.g. M1/M2 tool codegen). There are no persisted trial +folders — a trial's generated code/output is inlined into its stage's JSON, and the sandbox it ran in lives under an ephemeral `ctx.runtime_root` tempdir that's deleted at `finalize()`, not `fixes/`/`experiments/`. @@ -661,7 +664,7 @@ evalrx.FailureCase evalrx.Result # Diagnosis stages and logging -from evalrx.eval_agent import DiagnosisAgent, RunLoggerV2, StrategyProbe, SurgeryAgent +from evalrx.eval_agent import DiagnosisAgent, RunLogger, StrategyProbe, SurgeryAgent # Protocol-guided diagnosis — VLDiagnoseLoop (M1→M2→M3→M4, M5 post-loop) from evalrx.eval_agent import ( diff --git a/docs/cli.md b/docs/cli.md index f7539eff..b2728468 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -114,7 +114,7 @@ set. | `--model` (`--coder-model`) | backend default | Model name passed to the coding agent. | | `--max-rows` / `--max-files` | `2000` / `200` | Sampling caps for large inputs. | | `--timeout-sec` / `--max-attempts` | `120` / `2` | Per-attempt timeout and repair-retry budget. | -| `--serve-report` | off | Open the run's static `report.html` in a browser when it finishes. | +| `--serve-report` | off | Open the run's `report.html` in a browser when it finishes. | | `--skill DIR` (repeatable) | — | Agent-Skill directory to style agent-authored figures. Implies `--allow-skills`. | | `--no-skills` | off | Skip the package's bundled skills (e.g. `nature-figure`). | | `--no-hypotheses` | off | Skip M3 — stop after M2's takeaways. | @@ -124,9 +124,11 @@ set. | `--no-narrate` | off | Don't print live per-stage terminal narration (see above). | | `--progress-path PATH` | — | Also append durable JSONL progress events to `PATH`, for a separate workbench UI — independent of narration; both can run together. | -An explore output is not an M1–M5 run, so `serve` has nothing to show for it; -its report is the static `report.html` (`evalrx/reporting/html_report.py`) -written into `--out`, which opens from disk. +An explore output renders in the same report as a full run, with M2 and M3 +filled in and the other stages marked not run: `--out` gets a portable +`report.html` that opens from disk, and `evalrx serve ` shows it live. +A source checkout writes that file only once the renderer is built +(`npm run build` in `evalrx/reporting/web`); an installed package carries it. ## `evalrx run-codebase` @@ -171,6 +173,20 @@ evalrx serve --runs-root outputs/ # runs panel over every run under outputs/ | `--trace-id` | — | Langfuse trace id (required with `--source langfuse`). | | `--runs-root` | `run_dir`'s parent | Where the in-page runs panel looks for other experiments. | +A run still being written is followed live: the top bar reads "run in +progress", and the page swaps in the new report each time the run logs +something, on whatever view is open, until the run logs its end (`run_end`). +A run that stops logging without ending reads as unfinished, with how long it +has been quiet. Such a run is compiled in memory and published into its +directory only once it ends. + +**Compare** in the top bar puts the run on screen beside another the runs +panel lists (`#/compare/`): their metrics and stage outcomes in one table, +and the cases both evaluated that passed in one run and failed in the other, +each a link into the case studio. Runs are joined by case id, and the page +says when they used different datasets or one is an explore output. A portable +`report.html` holds a single run, so it has no Compare. + ## `evalrx report` Exports the same UI `serve` shows, as one portable HTML file — no server @@ -183,7 +199,6 @@ evalrx report outputs/qwen3.5-2b/chartqa --out chartqa_report.html | Flag | Default | Purpose | |---|---|---| | `run_dir` (positional) | `outputs` | Run directory holding `run.json`/`M1..M5`, or a `logs/` folder. | -| `--example-dir` | — | Root holding a benchmark/example's `data/` manifest, for legacy runs. | | `--out, -o` | `/report.html` | Output HTML path. | | `--embed-media` | `representative` | `representative` \| `all` \| `none` — how much image/audio to inline. | | `--audio-bitrate` | `48k` | Transcodes inlined lossless audio to mono MP3 via `ffmpeg` (needs `ffmpeg` on `PATH`); `none` inlines the original bytes. | @@ -200,8 +215,8 @@ HTML file. Useful for pre-warming a run's cache, or in CI. evalrx publish-report outputs/qwen3.5-2b/chartqa ``` -Takes `run_dir` (positional, default `outputs`), `--example-dir`, -`--source`, `--trace-id` — same meanings as `report`. +Takes `run_dir` (positional, default `outputs`), `--source`, `--trace-id` — +same meanings as `report`. ## `evalrx export-langfuse` diff --git a/docs/contract/README.md b/docs/contract/README.md index 8c8c1160..c222dfab 100644 --- a/docs/contract/README.md +++ b/docs/contract/README.md @@ -22,8 +22,8 @@ changes — adding a field is additive and does not bump it, so a reader must └── artifacts/ M1 heavy numeric data (.npy/.json) outside any stage ``` -`run.json` + `M1/log.json`..`M5/log.json` are RunLoggerV2's layout (see -`evalrx/eval_agent/RUN_LOGGER_V2.md`): no flat event stream, no separate +`run.json` + `M1/log.json`..`M5/log.json` are RunLogger's layout (see +`evalrx/eval_agent/RUN_LOGGER.md`): no flat event stream, no separate `report/`/`figures/` — generated text/code is inlined into the owning stage's JSON and media is copied into that stage's own `artifacts/`. `contract/` sits alongside it, independently typed and validated. diff --git a/docs/contract/contract.d.ts b/docs/contract/contract.d.ts index 3c2146cd..f50d82c2 100644 --- a/docs/contract/contract.d.ts +++ b/docs/contract/contract.d.ts @@ -126,6 +126,21 @@ export interface CorrectedRejections { */ export type EvidenceGrade = "intervention" | "observational" | "none"; +/** + * What the explore coding agent left: the analysis it wrote and ran. + * + * ``transcript`` is its CLI trajectory, cut to the report's budget; the run + * directory keeps the whole file. + */ +export interface ExploreAgentView { + code: string | null; + stdout: string | null; + stderr: string | null; + transcript: string | null; + transcript_truncated: boolean; + audit: unknown; +} + /** * Descriptive EDA notes from the optional explore side-path. * @@ -212,7 +227,7 @@ export interface FixAttemptWire { /** * The reader-facing identifier, e.g. `R3`. Assigned by the producer over the whole run and STABLE across `selection` and `attempted`, so a reader who sees R3 in the sweep can find R3's card and know it is the same repair. * - * This exists because `name` cannot do the job. Consumers that numbered rows by list position gave the same repair two different numbers in the two lists, which is worse than no number at all. Empty means the producer assigned none; a consumer may then number by position, but only within one list and never as a cross-list identity. + * This exists because `name` cannot do the job. Consumers that numbered rows by list position gave the same repair two different numbers in the two lists, which is worse than no number at all. */ ref?: string; /** @@ -415,13 +430,13 @@ export interface M2StageDetail { caveats: (unknown)[]; candidate_signals: (CandidateSignalView)[]; recommended_tests: (unknown)[]; + agent: ExploreAgentView | null; } export interface M3StageDetail { mode: string; hypotheses: (HypothesisView)[]; - unparsed_proposals: (UnparsedProposal)[]; - agent_response: string; + error?: string | null; candidate_signals: (CandidateSignalView)[]; recommended_tests: (unknown)[]; evidence_figures: (FigureView)[]; @@ -899,19 +914,6 @@ export interface TestEvidence { details?: { [key: string]: unknown }; } -/** - * A proposal recovered from the judge's raw reply after the parser - * rejected it. Shown for audit only; it never reached M4. - */ -export interface UnparsedProposal { - statement: string; - plain_statement: string; - failure_mode: string; - test_design: string; - expected_association: string; - accepted_by_pipeline: boolean; -} - /** * M4's raw log record. Verdict cards fall back to it when a result * lacks a field. diff --git a/docs/contract/m5_fix.FixOutput.schema.json b/docs/contract/m5_fix.FixOutput.schema.json index 8769eec6..98ed3312 100644 --- a/docs/contract/m5_fix.FixOutput.schema.json +++ b/docs/contract/m5_fix.FixOutput.schema.json @@ -18,7 +18,7 @@ }, "ref": { "default": "", - "description": "The reader-facing identifier, e.g. `R3`. Assigned by the producer over the whole run and STABLE across `selection` and `attempted`, so a reader who sees R3 in the sweep can find R3's card and know it is the same repair.\n\nThis exists because `name` cannot do the job. Consumers that numbered rows by list position gave the same repair two different numbers in the two lists, which is worse than no number at all. Empty means the producer assigned none; a consumer may then number by position, but only within one list and never as a cross-list identity.", + "description": "The reader-facing identifier, e.g. `R3`. Assigned by the producer over the whole run and STABLE across `selection` and `attempted`, so a reader who sees R3 in the sweep can find R3's card and know it is the same repair.\n\nThis exists because `name` cannot do the job. Consumers that numbered rows by list position gave the same repair two different numbers in the two lists, which is worse than no number at all.", "title": "Ref", "type": "string" }, diff --git a/docs/contract/report.StageDetail.schema.json b/docs/contract/report.StageDetail.schema.json index 182bec97..9d046979 100644 --- a/docs/contract/report.StageDetail.schema.json +++ b/docs/contract/report.StageDetail.schema.json @@ -7,6 +7,73 @@ "title": "CandidateSignalView", "type": "object" }, + "ExploreAgentView": { + "additionalProperties": false, + "description": "What the explore coding agent left: the analysis it wrote and ran.\n\n``transcript`` is its CLI trajectory, cut to the report's budget; the run\ndirectory keeps the whole file.", + "properties": { + "code": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Code" + }, + "stdout": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Stdout" + }, + "stderr": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Stderr" + }, + "transcript": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Transcript" + }, + "transcript_truncated": { + "title": "Transcript Truncated", + "type": "boolean" + }, + "audit": { + "title": "Audit" + } + }, + "required": [ + "code", + "stdout", + "stderr", + "transcript", + "transcript_truncated", + "audit" + ], + "title": "ExploreAgentView", + "type": "object" + }, "FigureView": { "additionalProperties": false, "description": "A chart the run saved, with the reading written for it.", @@ -315,6 +382,16 @@ "items": {}, "title": "Recommended Tests", "type": "array" + }, + "agent": { + "anyOf": [ + { + "$ref": "#/$defs/ExploreAgentView" + }, + { + "type": "null" + } + ] } }, "required": [ @@ -327,7 +404,8 @@ "observations", "caveats", "candidate_signals", - "recommended_tests" + "recommended_tests", + "agent" ], "title": "M2StageDetail", "type": "object" @@ -346,16 +424,17 @@ "title": "Hypotheses", "type": "array" }, - "unparsed_proposals": { - "items": { - "$ref": "#/$defs/UnparsedProposal" - }, - "title": "Unparsed Proposals", - "type": "array" - }, - "agent_response": { - "title": "Agent Response", - "type": "string" + "error": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Error" }, "candidate_signals": { "items": { @@ -387,8 +466,6 @@ "required": [ "mode", "hypotheses", - "unparsed_proposals", - "agent_response", "candidate_signals", "recommended_tests", "evidence_figures", @@ -1671,46 +1748,6 @@ "title": "TakeawayView", "type": "object" }, - "UnparsedProposal": { - "additionalProperties": false, - "description": "A proposal recovered from the judge's raw reply after the parser\nrejected it. Shown for audit only; it never reached M4.", - "properties": { - "statement": { - "title": "Statement", - "type": "string" - }, - "plain_statement": { - "title": "Plain Statement", - "type": "string" - }, - "failure_mode": { - "title": "Failure Mode", - "type": "string" - }, - "test_design": { - "title": "Test Design", - "type": "string" - }, - "expected_association": { - "title": "Expected Association", - "type": "string" - }, - "accepted_by_pipeline": { - "title": "Accepted By Pipeline", - "type": "boolean" - } - }, - "required": [ - "statement", - "plain_statement", - "failure_mode", - "test_design", - "expected_association", - "accepted_by_pipeline" - ], - "title": "UnparsedProposal", - "type": "object" - }, "ValidationEventView": { "additionalProperties": true, "description": "M4's raw log record. Verdict cards fall back to it when a result\nlacks a field.", diff --git a/docs/design_jax_backend.md b/docs/design_jax_backend.md index cc812c9e..6122f46b 100644 --- a/docs/design_jax_backend.md +++ b/docs/design_jax_backend.md @@ -454,10 +454,9 @@ What exists in the repo: - `evalrx/models/backends/jax/`: `protocol.py` (the contract above), `boundary.py` (jax -> CPU torch, bf16 bit-exact; a torch RMSNorm rebuilt from the JAX norm), `adapters/gemma.py` (the reference adapter: text, image - and audio inputs). The pre-0.1.2 `evalrx/models/jax/` paths are deprecated - aliases. + and audio inputs). - `evalrx/models/_media.py`: image / audio resolution shared by `hf_local` - and `jax_local` (moved out of `hf_local.py`, whose private names stay bound). + and `jax_local`. - `evalrx/models/backends/jax/backend.py`: `JaxLocalModel` / `JaxLocalBackend`, registered as `BACKENDS["jax_local"]`; `evalrx.wrap_jax(adapter)` mirrors `wrap()`. diff --git a/docs/extending.md b/docs/extending.md index 38778c39..fb3864d6 100755 --- a/docs/extending.md +++ b/docs/extending.md @@ -51,7 +51,7 @@ Guidelines: - If an artifact is a 2-D spatial map over a case's image (e.g. an attention heatmap), add `overlay()` / `image_overlays(fig_dir, stem_prefix)` methods to your `Result` subclass (see `RelativeAttentionResult` in - `analyzers/attention/relative_attn.py`). `RunLoggerV2` calls `image_overlays()` + `analyzers/attention/relative_attn.py`). `RunLogger` calls `image_overlays()` on any `Result` that defines it — no per-analyzer wiring needed to get the overlay PNGs into `M1/artifacts/` alongside the bare heatmap. @@ -224,31 +224,48 @@ loop = VLDiagnoseLoop(model=my_model, protocol=protocol, diagnosis_agent=DiagnosisAgent(judge=judge)) ``` -The judge receives a JSON dump of all analyzer findings and must reply with lines -of the form `HYPOTHESIS: ...` / `FAILURE_MODE: ...` (one pair per hypothesis) or -`NO_ISSUE`. You can use `evalrx.eval_agent.diagnosis._DIAGNOSE_PROMPT` as a -starting point and override it by subclassing `DiagnosisAgent`: +The judge receives a JSON dump of all analyzer findings and answers with JSON. +M3 does not parse text: it calls `evalrx.agent_runtime.judge_call.ask_judge`, which +appends the JSON Schema of the output model to the prompt and validates the reply +against it. The proposer's answer is a `Proposal` (up to three hypotheses, each with +`hypothesis`, `plain_statement`, a snake_case `failure_mode`, and optional `test` and +`expected_association`; an empty list means no problem was found). The adversarial +critic's answer is a `Review` (`keep`/`reject` plus a reason per numbered hypothesis). +An invalid reply is sent back once with the validation errors; if the second one is +invalid too, `ask_judge` raises `JudgeOutputError` (a judge that raises gives +`JudgeCallError`), and the loop logs the exchanges and retries M3. + +You can use `evalrx.eval_agent.prompts.diagnosis._DIAGNOSE_PROMPT` as a starting +point and override it by subclassing `DiagnosisAgent`. `diagnose` takes the M2 +report (an `AnalysisReport`; `raw_results` holds each analyzer's `Result`) and the +earlier cycles' summary: ```python -from evalrx.eval_agent.diagnosis import DiagnosisAgent, _parse_hypotheses, DiagnosisResult +from evalrx.agent_runtime.judge_call import ask_judge +from evalrx.eval_agent.hypothesis import Hypothesis +from evalrx.eval_agent.stages.diagnosis import DiagnosisAgent, DiagnosisResult, Proposal import json class MyDiagnosisAgent(DiagnosisAgent): _PROMPT = "Your custom prompt with {model_name} and {findings_json}." - def diagnose(self, results, model_name): - summary = {name: r.findings for name, r in results.items()} - raw = self.judge.generate( - self._PROMPT.format( - model_name=model_name, - findings_json=json.dumps(summary, indent=2, default=str), - ) + def diagnose(self, analysis, prior_cycles=None): + summary = {name: r.findings for name, r in analysis.raw_results.items()} + prompt = self._PROMPT.format( + model_name=analysis.model_name, + findings_json=json.dumps(summary, indent=2, default=str), ) + reply = ask_judge(self.judge, prompt, Proposal, role="diagnosis_judge") return DiagnosisResult( - model_name=model_name, - hypotheses=_parse_hypotheses(str(raw), model_name), + model_name=analysis.model_name, + hypotheses=[ + Hypothesis(statement=d.hypothesis, target_model=analysis.model_name, + predicted_failure_mode=d.failure_mode, + plain_statement=d.plain_statement, test_design=d.test) + for d in reply.output.hypotheses + ], findings_summary=summary, - raw_judge_output=str(raw), + raw_judge_output=reply.raw, ) ``` @@ -317,7 +334,7 @@ analyzer off a batch with no audio in it. The recommended way to persist a run is `RunContext` — it owns the whole output directory and hands every producer its subdirectory, including a -bound `RunLoggerV2`, always: `run.json` plus one `M1/log.json`..`M5/log.json` +bound `RunLogger`, always: `run.json` plus one `M1/log.json`..`M5/log.json` per stage. See [Architecture](architecture.md)'s "RunContext" section for the full layout. @@ -337,22 +354,22 @@ with RunContext("runs/exp_01") as ctx: ``` If you only want the event log and artifact sink — without `RunContext`'s -figures/contract/per-trial layout — construct `RunLoggerV2` standalone: +figures/contract/per-trial layout — construct `RunLogger` standalone: ```python -from evalrx.eval_agent import DiagnosisAgent, RunLoggerV2, VLDiagnoseLoop +from evalrx.eval_agent import DiagnosisAgent, RunLogger, VLDiagnoseLoop loop = VLDiagnoseLoop( model=model, protocol=protocol, diagnosis_agent=DiagnosisAgent(), - run_logger=RunLoggerV2("runs/exp_01"), # explicit path - # run_logger=RunLoggerV2() # auto: runs// + run_logger=RunLogger("runs/exp_01"), # explicit path + # run_logger=RunLogger() # auto: runs// ) report = loop.run(cases) ``` -Output layout (standalone `RunLoggerV2`, no `RunContext`): +Output layout (standalone `RunLogger`, no `RunContext`): ```text runs/exp_01/ @@ -381,20 +398,21 @@ sequence assigned under the logger's lock), and stage-specific fields: | `M3/log.json["diagnosis"]` | `hypotheses`, `raw_judge_output` (full LLM response) | | `M4/log.json["surgery"]` | `hypothesis`, `status`, `fixed`, `evidence`, `n_refocused_cases` | | `run.json["loop_end"]` | `cycles`, `resolved`, `final_hypotheses` | +| `run.json["run_end"]` | envelope only — written when the logger closes (schema 7) | The full, authoritative field contract is the published JSON Schema (`evalrx/eval_agent/run_log.schema.json`, from `log_schema.py`); validate one event with `from evalrx.eval_agent import validate_event` (needs the optional `jsonschema` dep). See `docs/architecture.md` for details, and -`evalrx.reporting.run_events.read_v2_events(root)` for a flat, ordered view +`evalrx.reporting.run_events.read_run_events(root)` for a flat, ordered view across every stage at once — the shape most downstream code wants instead of reading each `M/log.json` file directly. -`RunLoggerV2` is also a context manager, which ensures every document is +`RunLogger` is also a context manager, which ensures every document is closed even if the loop raises: ```python -with RunLoggerV2("runs/exp_01") as logger: +with RunLogger("runs/exp_01") as logger: loop = VLDiagnoseLoop(model=model, protocol=protocol, run_logger=logger) loop.run(cases) ``` diff --git a/docs/intervention.md b/docs/intervention.md index 83556ff0..ef35edac 100644 --- a/docs/intervention.md +++ b/docs/intervention.md @@ -24,13 +24,14 @@ For stage contracts and full data flow, see ## Quickstart — verify, then fix ```python -from evalrx.eval_agent import VLDiagnoseLoop, RunLogger +from evalrx.eval_agent import RunLogger, VLDiagnoseLoop from evalrx.eval_agent.stages.probe_agent import ProbeAgent from evalrx.analysis.stats_agent import StatsAnalysisAgent from evalrx.eval_agent.stages.diagnosis import DiagnosisAgent loop = VLDiagnoseLoop( model=model, + protocol=protocol, # an ExperimentProtocol probe_agent=ProbeAgent(max_analyzers=3), stats_agent=StatsAnalysisAgent(judge=judge), # feeds M4 diagnosis_agent=DiagnosisAgent(judge=judge), diff --git a/docs/m2_analysis.md b/docs/m2_analysis.md index f851ad6e..94836636 100644 --- a/docs/m2_analysis.md +++ b/docs/m2_analysis.md @@ -160,7 +160,7 @@ exemplars instead of the deterministic top-terms naming. `report.method` tells you which clustering backend actually ran (`"hdbscan"` / `"agglomerative"` / `"cosine_greedy"` / `"single_cluster"`); `report.as_hypothesis_context()` renders a compact section for feeding into M3 hypothesis generation — this is -exactly what `AgenticDiagnoseLoop`'s `cluster_failures` tool does +exactly what the `JudgePolicy` `cluster_failures` tool does automatically (see [quickstart](quickstart.md#agentic-diagnosis-loop)). ### Failure-aware embedding and boundary-aware naming (opt-in) @@ -223,8 +223,8 @@ default; supply your own `generate_macro`/`generate_micro` callables to `result.failure_cases` is a plain `CaseBatch` — feed it straight into `cluster_failures` above for failure-mode synthesis. Inside -`AgenticDiagnoseLoop`, the same capability is exposed as the `search_probes` -tool (host-capped via `max_calls`), reusing the loop's own decision judge and +a `JudgePolicy` run, the same capability is exposed as the `search_probes` +tool (host-capped via `max_calls`), reusing the policy's decision judge and the loop's target model. ## Backend notes diff --git a/docs/overview.md b/docs/overview.md index d7fdf1b6..e6788b66 100755 --- a/docs/overview.md +++ b/docs/overview.md @@ -93,8 +93,8 @@ to investigate), which drives analyzer prioritization in M1 and protocol-consist checking in M4. `StatsAnalysisAgent` (M2) generates an LLM-written evidence chain alongside the threshold-based findings. `HypothesisTester` (M4) applies a statistical fail-rate test and verifies protocol consistency; the loop stops as soon -as a supported, consistent hypothesis is found. **`AgenticDiagnoseLoop`** drives -the same stages from a judge-decided action loop instead of a fixed cycle. +as a supported, consistent hypothesis is found. With **`policy=JudgePolicy(judge)`** +the same loop is driven by a judge-decided action loop instead of a fixed cycle. Shared infrastructure: a durable `JsonlStore`, the multi-phase `ExperimentWriter` (blueprint → sequential → hard-validate → exec-fix → tree-search → review) behind diff --git a/docs/quickstart.md b/docs/quickstart.md index 03b937b4..8f1e39b5 100755 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -496,8 +496,8 @@ print(mr.significant_pairs) # [("A", "B"), ...] — pairs that pass Nemenyi CD ## VLDiagnoseLoop — Automated Failure Attribution (Current) `VLDiagnoseLoop` is the diagnosis loop for VL and LLM tasks -([`AgenticDiagnoseLoop`](#agentic-diagnosis-loop) drives the same stages from a -judge-decided action loop): +(with [`policy=JudgePolicy(judge)`](#agentic-diagnosis-loop) a judge picks each +next stage instead of the fixed cycle): ```text M1 ProbeAgent protocol-guided analyzer selection + execute @@ -516,7 +516,7 @@ for the stage contracts, M1's two-tier analyzer selection, and what M2/M4 ask. ```python from evalrx import compose from evalrx.core.capability import Capability -from evalrx.eval_agent import VLDiagnoseLoop, AgyModel, RunLoggerV2 +from evalrx.eval_agent import VLDiagnoseLoop, AgyModel, RunLogger from evalrx.eval_agent.stages.protocol import ExperimentProtocol from evalrx.eval_agent.stages.probe_agent import ProbeAgent from evalrx.analysis.stats_agent import StatsAnalysisAgent @@ -539,7 +539,7 @@ loop = VLDiagnoseLoop( diagnosis_agent=DiagnosisAgent(judge=judge), max_cycles=3, protocol=protocol, - run_logger=RunLoggerV2(), + run_logger=RunLogger(), ) report = loop.run(failure_cases) @@ -549,7 +549,7 @@ print(report.final_hypotheses) # list[Hypothesis] — status SUPPORTED/REFUTED fix = loop.run_m5(report, failure_cases) # post-loop fix proposal ``` -`RunLoggerV2()` above writes just its own `run.json` + `M/log.json` files at +`RunLogger()` above writes just its own `run.json` + `M/log.json` files at the given (or auto-generated) path — no other producer's output directory. For a full managed output directory — figures, per-trial fix/experiment sandboxes, contract export — construct a `RunContext` and pass @@ -574,11 +574,11 @@ protocol = ExperimentProtocol( -## AgenticDiagnoseLoop — Judge-Decided M1-M4 (Alternative to the Fixed Cycle) +## JudgePolicy — Judge-Decided M1-M4 (Alternative to the Fixed Cycle) `VLDiagnoseLoop` above always runs M1→M2→M3→M4 in the same order every cycle. -`AgenticDiagnoseLoop` wraps the identical stages, confirm-split, and post-loop -`run_m5`/`run_fix` — but a CLI judge decides which tool to call next each +Given `policy=JudgePolicy(judge)`, the same loop keeps its stages, confirm-split +and post-loop `run_m5`/`run_fix` — but a CLI judge decides which tool to call next each turn (probe, run stats, explore the raw data, cluster failure modes, search for new failure cases via a Macro/Micro MCTS probe search, propose hypotheses, test one, fix, or stop), instead of a fixed sequence. The host — not the judge — @@ -588,21 +588,23 @@ actually been tested and is statistically supported and protocol-consistent; an early attempt is rejected and fed back to the judge. ```python -from evalrx.eval_agent import AgenticDiagnoseLoop, ClaudeModel +from evalrx.eval_agent import ClaudeModel, JudgePolicy, VLDiagnoseLoop -loop = AgenticDiagnoseLoop( +loop = VLDiagnoseLoop( model=model, protocol=protocol, - judge=ClaudeModel(), # the decision judge — any CLI-backed Model - max_actions=12, # hard cap on judge decision turns - run_logger=RunLoggerV2(), + policy=JudgePolicy( + ClaudeModel(), # the decision judge — any CLI-backed Model + max_actions=12, # hard cap on judge decision turns + ), + run_logger=RunLogger(), ) -report = loop.run(failure_cases) # same VLDiagnoseReport shape as VLDiagnoseLoop +report = loop.run(failure_cases) # the same AutoDiagnoseReport as the fixed cycle ``` `report.stopped_by` is one of `agent_stop` / `max_actions` / `budget` / -`time_budget` / `invalid_actions` (three consecutive unparseable judge -responses, even after a repair prompt). Two event types — `agent_decision` +`time_budget` / `invalid_actions` (three consecutive turns where the judge gave +no valid action, even after its validation errors were sent back). Two event types — `agent_decision` (the chosen tool + rationale) and `agent_tool` (the dispatch layer's accept/reject outcome) — sit inside `run.json`, alongside the reused `probe`/`analysis`/`diagnosis`/`surgery` events from the wrapped stages diff --git a/docs/roadmap.md b/docs/roadmap.md index eb3cd225..36cf9673 100755 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -22,7 +22,7 @@ surfaces and planned interfaces. | Agent analyzers | `LoopDetector`, `IgnoredObservationDetector`, `FirstErrorJudge`, `CounterfactualReplay`. | | Statistics | `compare()` (McNemar + e-value + clustered bootstrap CI), `compare_multiple()` (Friedman + Nemenyi), `ebh()`, `kendall_tau`, `stratified_subset`. | | **ExperimentWriter** | **6-phase CodeAgent: blueprint → sequential multi-file generation (CodeMem AST summaries) → hard-validate → exec-fix (targeted traceback repair) → tree-search → review. CLI agent backends: `codex`, `claude_code`, `opencode`, `gemini_cli`, `kimi_cli`.** | -| **ExperimentSandbox** | **`run_project()` for multi-file projects; path traversal protection; harness injection; cleanup-on-success; `SandboxProtocol` + `create_sandbox()` factory.** | +| **ExperimentSandbox** | **`run_project()` for multi-file projects; path traversal protection; harness injection; cleanup-on-success; `SandboxProtocol`.** | | **JsonlStore** | **Durable JSONL-backed `Store`; hypotheses serialized via `hypothesis_to_dict`/`from_dict`; survives process restart.** | | **VLM image-attention rule** | **M2 derives `image_token_attention_ratio` from `top_attended_tokens`; fires medium-severity finding when VLM ignores image tokens.** | | **RunContext** | **Single owner of a run's output directory (`report/`, `figures/`, `artifacts/`, `experiments/`, `fixes/`, `manifest.json`, auto-generated `README.txt`); per-trial folders (`new_trial()`) for fix candidates and M5 experiments.** | diff --git a/docs/stage_io.md b/docs/stage_io.md index cfb051db..119d763a 100644 --- a/docs/stage_io.md +++ b/docs/stage_io.md @@ -3,15 +3,15 @@ A single reference for what goes into and comes out of each stage of the M1→M5 diagnosis pipeline. [Architecture](architecture.md#eval_agent-automated-diagnosis-pipeline) covers *why* the pipeline is shaped this way and how the two loops -(`VLDiagnoseLoop`, `AgenticDiagnoseLoop`) orchestrate these +(`VLDiagnoseLoop` with its fixed cycle or a `JudgePolicy`) orchestrate these same stages differently; [Exploratory Analysis (M2/M3)](m2_analysis.md) and [Intervention & Verification (M4/M5)](intervention.md) cover usage. This page covers the shape of the data crossing each boundary, and — since that shape is exactly what a viewer has to render — [what to put on screen for it](#ui-reference-building-a-viewer-on-this-pipeline). Building a new UI on this pipeline? Read the stage you're rendering below, then [UI Reference](#ui-reference-building-a-viewer-on-this-pipeline) at the -bottom for the static report's page layout, tab-to-stage mapping, and -rendering conventions (source: `evalrx/reporting/html_report.py`). +bottom for the report's page layout, tab-to-stage mapping, and +rendering conventions (source: `evalrx/reporting/web`). For an implementation hand-off, start with [Frontend implementation contract](#frontend-implementation-contract): it defines the files to load, event fields, joins, state derivation, null/error @@ -48,9 +48,9 @@ M5 FixAgent.propose_and_validate(...) → FixOutcome (propose + validate candidate repairs, tiered L1→L4) ``` -`VLDiagnoseLoop` runs M1→M2→M3→M4 in a cycle and calls M5 (`SurgeryAgent` then +`VLDiagnoseLoop` runs M1→M2→M3→M4 in a cycle (the default `FixedOrderPolicy`) and calls M5 (`SurgeryAgent` then `FixAgent`) once, post-loop, on the best verified hypothesis. -`AgenticDiagnoseLoop` lets a judge choose the next stage instead. Both consume and +With `policy=JudgePolicy(judge)` a judge chooses the next stage instead. Both consume and produce the same per-stage types described below — only the wiring differs. **Pre-M1 (optional):** `ProbeSearchAgent.run(model, seed_pool)` synthesizes @@ -73,7 +73,7 @@ then probes. See [m2_analysis.md](m2_analysis.md#probe-search-hierarchical-mcts- | M5 (verify) | `SurgeryAgent` | `operate(hypothesis, model, results, data)` | one `Hypothesis` + `dict[str, Result]` + `CaseBatch` | `InterventionResult` | | M5 (fix) | `FixAgent` | `propose_and_validate(model, data, hypotheses, prior_attempts=)` | `Model` + `CaseBatch` + `list[Hypothesis]` | `FixOutcome` | | M4 | `HypothesisTester` | `test(hypotheses, stats_report, data, protocol=)` | `list[Hypothesis]` + `StatsAnalysisReport` + `CaseBatch` | `list[HypothesisTestResult]` | -| Loop | `VLDiagnoseLoop` / `AgenticDiagnoseLoop` | `run(cases)` | `CaseBatch` | `AutoDiagnoseReport` (both loops return this one class — see below) | +| Loop | `VLDiagnoseLoop` (optionally `policy=JudgePolicy(...)`) | `run(cases)` | `CaseBatch` | `AutoDiagnoseReport` (both modes return this one class — see below) | ## Shared input type — `CaseBatch` @@ -241,8 +241,7 @@ verdicts must never look the same to the reader. ### `DiagnosisAgent` (loop-internal) -**Input:** `analysis: AnalysisReport | StatsAnalysisReport | dict[str, Result]` -(M2's output — dict form is accepted for backward compatibility), +**Input:** `analysis: AnalysisReport | StatsAnalysisReport` (M2's output), `prior_cycles: list[dict] | None` (summaries of earlier M1→M5 cycles, so the judge avoids re-proposing tested hypotheses), `explore_context`, `failure_modes` (optional, descriptive-only context from clustering). @@ -326,6 +325,16 @@ right anyway was solved by the pipeline's own computation, not a repair of the model. Those cases are excluded from the paired test (`n_model_independent`) rather than counted as `fixed`. +**A replacement fix agent.** `VLDiagnoseLoop(fix_agent=...)` and +`run_fix(fix_agent=...)` call the agent they are given the way they call +`FixAgent`, so subclass it, or provide the same members: +`propose_and_validate(model, data, hypotheses, prior_attempts=, context=, +max_tier=, min_tier=, record=)` returning a `FixOutcome`, +`validate_candidate(model, data, candidate)`, `recommend(routed, model=, +data=, reason_prefix=, max_tier=)`, `no_fix_recommendation(attempted, +routed_tiers, data, model, max_tier=)`, and the attributes `alpha`, +`max_tier` and `run_logger`. + **UI (Tab 5 — Fix):** greyed "not available" placeholder (`_render_unavailable_panel`: title, what happened, how to get it) when no `fix_report.json` sits next to the exploratory report — this pipeline phase @@ -387,8 +396,8 @@ attached to a specific claim. ## Loop-level output -Both loops — `VLDiagnoseLoop` and `AgenticDiagnoseLoop` — return the **same -class**: `AutoDiagnoseReport` (`VLDiagnoseReport` is a +Both modes — the fixed cycle and a `JudgePolicy` run — return the **same +class**: `AutoDiagnoseReport` (`AutoDiagnoseReport` is a back-compat alias for the identical class, so `isinstance` checks against either name succeed for a report from any loop). Each loop populates the subset of fields relevant to what it ran; fields the loop has no equivalent @@ -399,12 +408,10 @@ concept for stay at their default (`None` / empty): | `cycles` | all | M1→M4/M5 cycles executed (or agentic decision steps). | | `resolved: bool` | all | Diagnosis considered closed: `bool(verified_hypotheses)`. | | `stopped_by: str \| None` | VL / agentic | Why the loop stopped: `"criteria_met"` / `"max_cycles"` / `"budget"` / `"no_hypotheses"` / `"no_probe_results"` / `"analysis_complete"`, or agentic's `"agent_stop"` / `"max_actions"` / `"time_budget"` / `"invalid_actions"`. | -| `final_hypotheses: list[Hypothesis]` | all | All M3 proposals across every cycle. (`all_hypotheses` is a read-only alias, kept for existing callers.) | +| `final_hypotheses: list[Hypothesis]` | all | All M3 proposals across every cycle. | | `verified_hypotheses: list[HypothesisTestResult]` | VL / agentic (M4) | SUPPORTED + protocol-consistent, highest confidence first — feed into `run_m5`. | | `all_test_results: list[HypothesisTestResult]` | VL / agentic (M4) | All M4 test results across every cycle. | -| `final_results: dict[str, Result]` | — | Left empty by both loops (it was the removed `AutoDiagnoseLoop`'s); M1's results are in the run log and `final_analysis`. | -| `final_analysis: AnalysisReport \| None` | all | Last M2 report. Auto-populated from `final_stats_report` when only that was set (`StatsAnalysisReport` is an `AnalysisReport` subclass), so this field works regardless of which loop produced the report. | -| `final_stats_report: StatsAnalysisReport \| None` | VL / agentic | Last M2 report (same object as `final_analysis` when set). | +| `final_stats_report: StatsAnalysisReport \| None` | VL / agentic | Last M2 report. | | `fix_proposal` / `fix_outcome` | post-loop | Populated by `run_m5` / `run_fix` after `run()` returns. | | `store` | all | Accumulated results and hypotheses. | @@ -450,7 +457,7 @@ Two things the contract will not do for you, both deliberate: grounded. The rest of this section describes the raw run directory — `RunContext`'s -only layout now (`evalrx/eval_agent/RUN_LOGGER_V2.md`; there is no other +only layout now (`evalrx/eval_agent/RUN_LOGGER.md`; there is no other logger to select). `contract/` is unaffected by any of this. ### 1. Choose a source of truth @@ -502,8 +509,7 @@ For a finished run, `run.json["manifest"]` is the file inventory. Its shape is: `config` is intentionally extensible: render recognized values as summary chips and preserve the remainder in a raw configuration view. `files` is a -flat, complete file index (not grouped by category the way V1's was) — -render it as-is. +flat, complete file index — render it as-is. #### Artifact path resolution @@ -628,7 +634,7 @@ but keep the original JSON untouched. Each stage document (`M/log.json`) is one JSON object whose keys are event names, each mapping to an array of entries for that stage; `run.json` is the same shape for run-wide events (`run_start`, `cases`, `manifest`, -`diagnose_reports`, `loop_end`, …). `evalrx.reporting.run_events.read_v2_events(root)` +`diagnose_reports`, `loop_end`, …). `evalrx.reporting.run_events.read_run_events(root)` flattens all of it into one ordered list of independent event objects — the shape this section (and every table below) describes; prefer it over reading each file directly. Every event has: @@ -654,14 +660,15 @@ and cross-service correlation only. | Event | Stage | Required/important payload | UI interpretation | |---|---|---|---| | `run_start` | run | model/judge/config, `n_cases`, protocol, budgets, version/git/data fingerprint when available | create run header; missing optional provenance is “unknown,” not failure | -| `probe` | M1 | `cycle`, `analyzers`, `findings`, `results` (each analyzer's complete document, inline), `artifact_paths`; optional `selected_analyzers`, rationale, `failed_analyzers`, `judge_io`, duration | one analyzer card per selected analyzer; a name in `failed_analyzers` is a local analyzer failure | +| `probe` | M1 | `cycle`, `analyzers`, `findings`, `results` (each analyzer's complete document, inline), `artifact_paths`; optional `selected_analyzers`, rationale, `failed_analyzers`, `judge_prompt` / `judge_response`, duration | one analyzer card per selected analyzer; a name in `failed_analyzers` is a local analyzer failure | | `explore` | descriptive side path | `cycle`, `ok`, counts, observations, caveats, figures; optional error/report path | `ok: false` fails this optional step, but does not by itself fail the diagnosis loop | -| `analysis` | M2 | `cycle`, severity, findings, narrative, `descriptive_only`; optional stats outputs, conclusion, figures, `llm_fallback_reason`, `judge_io` | label descriptive and confirmatory analysis explicitly; a fallback can still be a successful M2 | -| `diagnosis` | M3 | `cycle`, model, `n_hypotheses`, `hypotheses`, raw output; optional referenced charts/context flags, `judge_io` | zero parsed hypotheses is a completed empty/abstained M3 unless an explicit error exists elsewhere | +| `analysis` | M2 | `cycle`, severity, findings, narrative, `descriptive_only`; optional stats outputs, conclusion, figures, `llm_fallback_reason`, `judge_prompt` / `judge_response` | label descriptive and confirmatory analysis explicitly; a fallback can still be a successful M2 | +| `diagnosis` | M3 | `cycle`, model, `n_hypotheses`, `hypotheses`, raw output; optional referenced charts/context flags, `judge_prompt` | zero parsed hypotheses is a completed empty/abstained M3 unless an explicit error exists elsewhere | | `surgery` | M5 or M4 | `cycle`, `module`, hypothesis text, failure mode, status, `fixed`, confidence/evidence, refocused-case count | route by `module`; do not infer M5 vs M4 from the event name alone | -| `experiment` | M5 | `cycle`, `module`, hypothesis, status/fixed; optional provider, metrics, exit/timing, code/output/workspace paths, record | generated verification execution detail; failure of one experiment need not fail the whole run | -| `fix` | post-loop Fix | `cycle: -1`, `max_tier`, selection/final attempts, best, fixed, recommendation/refine signal, records | distinguish EXPLORE selection from held-out FINAL confirmation; see below | +| `experiment` | M5 | `cycle`, `module`, hypothesis, status/fixed; optional provider, metrics, exit/timing, `code`, `stdout` / `stderr`, `workspace_snapshot` | generated verification execution detail; failure of one experiment need not fail the whole run | +| `fix` | post-loop Fix | `cycle: -1`, `max_tier`, selection/final attempts, best, fixed, recommendation/refine signal | distinguish EXPLORE selection from held-out FINAL confirmation; see below | | `loop_end` | diagnosis loop | cycles, resolved/stopped reason, final and verified hypotheses, tokens/timings | diagnosis loop ended; **not necessarily the last event in the run** | +| `run_end` | run | envelope only (schema 7) | the logger closed: the run-level completion signal, after everything else the run logged | | `agent_decision` | agentic loop | `step`, action/params/rationale, validity/repair/fallback, judge I/O | trajectory node; `valid: false` means host fallback, not automatically run failure | | `agent_tool` | agentic loop | `step`, tool, `ok`, summary/error, duration | dispatch result; stage-specific event remains the source for stage payload | | `tool_codegen` | support | cycle/module/tool/need/source/`ok`, error/code paths | one tool-generation attempt, not a stage verdict | @@ -706,8 +713,9 @@ Recommended derivation rules: 7. A hypothesis status of `inconclusive` is a valid abstention, not an exception. 8. `loop_end` terminates M1→M4 orchestration, but M5 verification and Fix can be logged after it. Do not mark the entire run immutable merely because - `loop_end` appeared. A live transport/process terminal signal or a finalized - manifest is the run-level completion signal. + `loop_end` appeared. `run_end` (log schema 7, written when the logger + closes) is the run-level completion signal; for an older log, `loop_end` is + the best there is. The report carries the result as `setting.finished`. 9. Missing events in an older/in-progress run mean “not observed”; do not invent a failure. Use `schema_version` and run configuration to decide skipped vs. not started. @@ -911,13 +919,13 @@ There is already a working viewer for this exact data: `evalrx serve ` runs it as a local dynamic UI, and `evalrx report ` exports the same UI as one portable `report.html` — see the [CLI reference](cli.md) for the full command set. The source of truth is -`evalrx/reporting/dynamic.py` (compiles `ReportData` + layout), +`evalrx/reporting/dynamic.py` (compiles `ReportData` + layout, from the +`report_inputs` / `stage_views` / `report_summary` modules beside it), `evalrx/reporting/server.py` (the `serve` FastAPI app) and `evalrx/reporting/static_export.py` (the `report` exporter); all three share -the same React/json-render renderer. (`evalrx/reporting/html_report.py` is -the older, pre-React renderer that `evalrx explore` / `run-codebase` still -use for their explore-shaped output — not this contract.) Read this section as the contract that -renderer must preserve. +the same React/json-render renderer, which also renders an `evalrx explore` / +`run-codebase` output. Read this section as the contract that renderer must +preserve. ### Requirements for the new UI diff --git a/docs/wsp_and_probe_tools.md b/docs/wsp_and_probe_tools.md index 8bafa536..93ecee62 100644 --- a/docs/wsp_and_probe_tools.md +++ b/docs/wsp_and_probe_tools.md @@ -76,7 +76,7 @@ pass a constructed analyzer through `overrides={name: analyzer}`. ### In the agentic loop -`AgenticDiagnoseLoop` gains one tool and extends another: +The judge-decided mode (`JudgePolicy`) gains one tool and extends another: | Tool | Arguments | Effect | |---|---|---| diff --git a/evalrx/__init__.py b/evalrx/__init__.py index dc2da017..43652df0 100755 --- a/evalrx/__init__.py +++ b/evalrx/__init__.py @@ -69,7 +69,7 @@ # logging_utils.py's module docstring for the full rationale. _logging.getLogger("evalrx").addHandler(_logging.NullHandler()) -__version__ = "0.1.2" +__version__ = "0.2.0" __all__ = [ "load", "load_config", @@ -129,12 +129,7 @@ def run(config: AnalysisConfig, data, **kwargs): Returns: A :class:`~evalrx.core.result.Result` subclass. """ - # Back-compat: tolerate a leading "call_" in the config (old style). - name = config.analysis - if name.startswith("call_"): - name = name[len("call_"):] - - analyzer_cls = registry.analyzers.get(name) + analyzer_cls = registry.analyzers.get(config.analysis) analyzer = analyzer_cls(**{**config.analysis_kwargs, **kwargs}) model = load_model(config.model) return analyzer.run(model, data) diff --git a/evalrx/agent_runtime/__init__.py b/evalrx/agent_runtime/__init__.py index 03da2856..d772801f 100644 --- a/evalrx/agent_runtime/__init__.py +++ b/evalrx/agent_runtime/__init__.py @@ -8,7 +8,7 @@ cli_runtime SubprocessRunner, ProcessRun, collect_py_files cli_transcript CLI stdout post-processing (e.g. Claude stream-json rendering) sandbox ExperimentSandbox — safe subprocess execution of generated code - factory create_sandbox() — subprocess/Docker sandbox backend selection + judge_call ask_judge — one typed judge call with validation retry codegen CodegenRunner — the single boundary stages use to invoke a CLI coding agent and harvest generated files providers CLI coding-provider adapters (claude_code, codex, antigravity, ...) @@ -25,12 +25,13 @@ CliAgentResult, ) from evalrx.agent_runtime.codegen import CodegenCodeResult, CodegenRunner -from evalrx.agent_runtime.factory import ( - SandboxConfig, - SandboxFactoryConfig, - create_sandbox, +from evalrx.agent_runtime.judge_call import ( + JudgeCallError, + JudgeError, + JudgeOutputError, + JudgeReply, + ask_judge, ) -from evalrx.agent_runtime.json_shape import validate_json_shape from evalrx.agent_runtime.judges import ( AgyModel, ClaudeModel, @@ -56,9 +57,11 @@ "CliAgentResult", "CodegenCodeResult", "CodegenRunner", - "SandboxConfig", - "SandboxFactoryConfig", - "create_sandbox", + "ask_judge", + "JudgeReply", + "JudgeError", + "JudgeCallError", + "JudgeOutputError", "AgyModel", "ClaudeModel", "CodexModel", @@ -74,5 +77,4 @@ "resolve_skill_paths", "skills_hint", "fences_hint", - "validate_json_shape", ] diff --git a/evalrx/agent_runtime/_docker_runner.py b/evalrx/agent_runtime/_docker_runner.py index f168ce12..eaa6b4cb 100755 --- a/evalrx/agent_runtime/_docker_runner.py +++ b/evalrx/agent_runtime/_docker_runner.py @@ -49,7 +49,7 @@ def _build_cases(raw_cases: list[dict]): cases = [] for rec in raw_cases: - label = None + label = Label.UNKNOWN raw_label = rec.get("label") if raw_label is not None: try: diff --git a/evalrx/agent_runtime/cli_runtime.py b/evalrx/agent_runtime/cli_runtime.py index 40a241e6..9d4f5378 100644 --- a/evalrx/agent_runtime/cli_runtime.py +++ b/evalrx/agent_runtime/cli_runtime.py @@ -3,6 +3,7 @@ from __future__ import annotations import os +import re import signal import subprocess import sys @@ -10,6 +11,16 @@ from dataclasses import dataclass from pathlib import Path +#: Limit notices the coding CLIs print on stdout, exit 0, in place of an answer. +LIMIT_NOTICE = re.compile( + r"hit your (monthly |weekly |session |daily )?(spend|usage|rate) limit|" + r"(spend|usage) limit (reached|exceeded)|out of (extra )?usage|" + r"limit resets", re.I) + +#: A real answer is never this short AND a limit notice; for a coding agent's +#: session, how much of its end is read for one. +NOTICE_MAX_CHARS = 400 + @dataclass(frozen=True) class ProcessRun: @@ -46,7 +57,14 @@ def collect_py_files(workdir: Path) -> dict[str, str]: class SubprocessRunner: """Run CLI agents in a workdir with timeout and environment normalization.""" - def run(self, cmd: list[str], workdir: Path, timeout_sec: int) -> ProcessRun: + def run( + self, cmd: list[str], workdir: Path, timeout_sec: int, *, stdin_text: str | None = None, + ) -> ProcessRun: + """Run *cmd* in *workdir*; on timeout, kill its whole process group. + + *stdin_text* is written to the process's stdin (prompts too large for + an argv entry); without it stdin is at EOF. + """ workdir.mkdir(parents=True, exist_ok=True) start = time.monotonic() timed_out = False @@ -63,7 +81,7 @@ def run(self, cmd: list[str], workdir: Path, timeout_sec: int) -> ProcessRun: # interactive continuation protocol, so leave stdin at EOF. If # inherited from the parent it remains open and Codex idles until # the wall-clock timeout, withholding its generated artifacts. - stdin=subprocess.DEVNULL, + stdin=subprocess.DEVNULL if stdin_text is None else subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=workdir, @@ -72,7 +90,10 @@ def run(self, cmd: list[str], workdir: Path, timeout_sec: int) -> ProcessRun: ) try: - stdout_bytes, stderr_bytes = proc.communicate(timeout=timeout_sec) + stdout_bytes, stderr_bytes = proc.communicate( + input=None if stdin_text is None else stdin_text.encode("utf-8", errors="replace"), + timeout=timeout_sec, + ) except subprocess.TimeoutExpired: timed_out = True try: diff --git a/evalrx/agent_runtime/cli_transcript.py b/evalrx/agent_runtime/cli_transcript.py index e0dbe5b3..fa7454f0 100644 --- a/evalrx/agent_runtime/cli_transcript.py +++ b/evalrx/agent_runtime/cli_transcript.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +from typing import Any RAW_OUTPUT_CAP = 3000 STREAM_TEXT_CAP = 4000 @@ -71,7 +72,7 @@ def render_claude_stream(stdout: str) -> tuple[str, dict | None]: out: list[str] = [] usage: dict | None = None - tool_seq: dict[str, int] = {} + tool_seq: dict[Any, int] = {} step = 0 for event in events: diff --git a/evalrx/agent_runtime/factory.py b/evalrx/agent_runtime/factory.py deleted file mode 100755 index d87d4921..00000000 --- a/evalrx/agent_runtime/factory.py +++ /dev/null @@ -1,102 +0,0 @@ -"""Sandbox factory — create the appropriate sandbox backend from config. - -Mirrors ``researchclaw/experiment/factory.py``. - -Supported modes: - ``"subprocess"`` (default) — :class:`ExperimentSandbox` running in a local - subprocess. No extra dependencies required. - ``"docker"`` — Docker-isolated sandbox. Falls back to the subprocess - backend when Docker is not available or the DockerSandbox import fails. -""" - -from __future__ import annotations - -import logging -from dataclasses import dataclass, field -from pathlib import Path - -from evalrx.agent_runtime.sandbox import ExperimentSandbox, SandboxProtocol - -logger = logging.getLogger(__name__) - - -# --------------------------------------------------------------------------- -# Configuration dataclasses -# --------------------------------------------------------------------------- - - -@dataclass(frozen=True) -class SandboxConfig: - """Configuration for the subprocess sandbox backend. - - Attributes: - python_path: Python executable to use. Empty string → ``sys.executable``. - timeout_sec: Default timeout for sandbox runs (seconds). - """ - - python_path: str = "" - timeout_sec: int = 60 - - -@dataclass(frozen=True) -class SandboxFactoryConfig: - """Top-level factory configuration. - - Attributes: - mode: Backend to use: ``"subprocess"`` (default) or ``"docker"``. - sandbox: Settings for the subprocess backend. - """ - - mode: str = "subprocess" - sandbox: SandboxConfig = field(default_factory=SandboxConfig) - - -# --------------------------------------------------------------------------- -# Factory -# --------------------------------------------------------------------------- - - -def create_sandbox(config: SandboxFactoryConfig, workdir: Path) -> SandboxProtocol: - """Instantiate the sandbox backend specified by *config.mode*. - - Args: - config: Factory configuration. - workdir: Directory where the sandbox writes scripts and project copies. - - Returns: - A :class:`~evalrx.agent_runtime.sandbox.SandboxProtocol` implementation. - Falls back to :class:`ExperimentSandbox` if the requested backend is - unavailable. - """ - if config.mode == "docker": - sandbox = _try_create_docker_sandbox(workdir) - if sandbox is not None: - return sandbox - logger.warning( - "Docker sandbox unavailable — falling back to subprocess sandbox" - ) - - python_path = config.sandbox.python_path or None - return ExperimentSandbox(workdir=workdir, python_path=python_path) - - -def _try_create_docker_sandbox(workdir: Path) -> SandboxProtocol | None: - """Attempt to create a DockerSandbox; return None if not available.""" - try: - import subprocess as _sp - result = _sp.run( - ["docker", "info"], - capture_output=True, - timeout=5, - check=False, - ) - if result.returncode != 0: - logger.debug("Docker not running (docker info returned %s)", result.returncode) - return None - except Exception as exc: # noqa: BLE001 - logger.debug("Docker check failed: %s", exc) - return None - - # DockerSandbox is not yet implemented in evalrx — stub falls through. - logger.debug("Docker is available but DockerSandbox is not yet implemented") - return None diff --git a/evalrx/agent_runtime/json_shape.py b/evalrx/agent_runtime/json_shape.py deleted file mode 100644 index 30e438d2..00000000 --- a/evalrx/agent_runtime/json_shape.py +++ /dev/null @@ -1,44 +0,0 @@ -"""Minimal JSON schema validator shared by anything that parses LLM JSON output. - -No external deps (not even ``jsonschema``) — only handles type/required/ -minLength, which is enough to catch the common LLM mistakes (missing field, -empty string, wrong top-level type). Used by M3's hypothesis parser, the -agentic loop's action parser, and failure-mode cluster naming. -""" - -from __future__ import annotations - - -def validate_json_shape(data: object, schema: dict) -> list[str]: - """Returns a list of error strings; empty means valid.""" - errors: list[str] = [] - - def _check(node: object, s: dict, path: str) -> None: - expected_type = s.get("type") - if expected_type == "array": - if not isinstance(node, list): - errors.append(f"{path}: expected array, got {type(node).__name__}") - return - item_schema = s.get("items", {}) - for i, item in enumerate(node): - _check(item, item_schema, f"{path}[{i}]") - elif expected_type == "object": - if not isinstance(node, dict): - errors.append(f"{path}: expected object, got {type(node).__name__}") - return - for req in s.get("required", []): - if req not in node: - errors.append(f"{path}: missing required field '{req}'") - for prop, prop_schema in s.get("properties", {}).items(): - if prop in node: - _check(node[prop], prop_schema, f"{path}.{prop}") - elif expected_type == "string": - if not isinstance(node, str): - errors.append(f"{path}: expected string, got {type(node).__name__}") - elif "minLength" in s and len(node) < s["minLength"]: - errors.append( - f"{path}: string too short ({len(node)} < {s['minLength']})" - ) - - _check(data, schema, "$") - return errors diff --git a/evalrx/agent_runtime/judge_call.py b/evalrx/agent_runtime/judge_call.py new file mode 100644 index 00000000..b429bc97 --- /dev/null +++ b/evalrx/agent_runtime/judge_call.py @@ -0,0 +1,267 @@ +"""One typed judge call: a prompt in, a validated pydantic object out. + +Every stage that needs structured output from a judge calls :func:`ask_judge` +instead of parsing text itself. PydanticAI runs the exchange: + +* the first JSON value in the reply that validates as ``output_type`` is the answer; +* an invalid reply goes back to the judge with the validation errors, up to + ``retries`` more times; +* when that budget runs out, :class:`JudgeOutputError` is raised; +* a judge that fails outright (timeout, a CLI limit notice) raises + :class:`JudgeCallError`. + +Both errors carry every exchange, so the caller can log what was asked and +what came back. A failed call is never turned into an empty answer here. + +Judges are text in, text out (CLI agents, or API models behind +:class:`~evalrx.core.model.Judge`), so each attempt is rendered as one +self-contained prompt: the output schema, the request, and every earlier +answer with the feedback it got. +""" + +from __future__ import annotations + +import asyncio +import inspect +import json +import re +import time +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Callable, Generic, Iterator, Sequence, TypeVar + +import pydantic_ai +from pydantic import BaseModel, ValidationError +from pydantic_ai import Agent, ModelRetry, RunContext +from pydantic_ai.exceptions import UnexpectedModelBehavior +from pydantic_ai.messages import ( + ModelMessage, + ModelResponse, + RetryPromptPart, + TextPart, +) +from pydantic_ai.models.function import AgentInfo, FunctionModel +from pydantic_ai.output import TextOutput + +# A library does not print a first-run banner into its users' terminals. +pydantic_ai.BANNER_ENABLED = False + +T = TypeVar("T", bound=BaseModel) + +_SCHEMA_INSTRUCTIONS = ( + "Answer with one JSON value that matches this JSON Schema. Put the JSON " + "in your reply; nothing else in the reply is read.\n\n{schema}" +) + + +@dataclass(frozen=True) +class Exchange: + """One prompt sent to the judge and what came back.""" + + role: str + attempt: int + prompt: str + output: str | None + error: str | None + duration_sec: float + images: tuple[str, ...] = () + + def record(self) -> dict[str, Any]: + """The model-call record a stage log stores.""" + inputs: Any = {"prompt": self.prompt, "images": list(self.images)} if self.images else self.prompt + return { + "role": self.role, "operation": "generate", "inputs": inputs, + "output": self.output, "error": self.error, + "duration_sec": self.duration_sec, "metadata": {"attempt": self.attempt}, + } + + +@dataclass(frozen=True) +class JudgeReply(Generic[T]): + """A validated answer and the exchanges that produced it.""" + + output: T + exchanges: tuple[Exchange, ...] + + @property + def raw(self) -> str: + return self.exchanges[-1].output or "" + + +class JudgeError(RuntimeError): + """A judge call that did not produce a valid answer.""" + + def __init__(self, message: str, exchanges: Sequence[Exchange]) -> None: + super().__init__(message) + self.exchanges = tuple(exchanges) + + @property + def raw(self) -> str: + return (self.exchanges[-1].output or "") if self.exchanges else "" + + +class JudgeCallError(JudgeError): + """The judge itself failed: it raised instead of answering.""" + + +class JudgeOutputError(JudgeError): + """The judge answered, but no answer was valid within the retry budget.""" + + +_THINK_BLOCK = re.compile(r".*?", re.DOTALL) + + +def json_values(text: str) -> Iterator[Any]: + """Every JSON object or array in *text*, in order of where it starts. + + Judges wrap JSON in prose and code fences, cite ``[2]``-style references, + and reasoning models put a ```` block first. Think blocks are + dropped; every ``{`` or ``[`` that starts a valid JSON value yields it, + nested ones included, so the caller can take the first that fits. + """ + text = _THINK_BLOCK.sub("", text) + decoder = json.JSONDecoder() + for i, char in enumerate(text): + if char in "{[": + try: + yield decoder.raw_decode(text, i)[0] + except json.JSONDecodeError: + continue + + +def validate_reply(text: str, output_type: type[T]) -> T: + """The first JSON value in *text* that validates as *output_type*. + + Raises ``ValueError`` when *text* holds no JSON, or the + ``ValidationError`` of the first JSON value when none validates. + """ + first_error: ValidationError | None = None + for value in json_values(text): + try: + return output_type.model_validate(value) + except ValidationError as exc: + first_error = first_error or exc + if first_error is not None: + raise first_error + raise ValueError("the reply contains no JSON object or array") + + +def _part_text(part: Any) -> str: + if isinstance(part, RetryPromptPart): + return part.model_response() + content = getattr(part, "content", "") + if isinstance(content, str): + return content + return "\n".join(str(c) for c in content if isinstance(c, str)) + + +def render_prompt(messages: Sequence[ModelMessage], instructions: str | None) -> str: + """Flatten a PydanticAI conversation into one prompt for a stateless judge. + + Everything sent after the judge's first answer is feedback on it. + """ + blocks: list[str] = [instructions] if instructions else [] + answered = False + for message in messages: + texts = [t for t in (_part_text(p) for p in message.parts) if t] + if not texts: + continue + if isinstance(message, ModelResponse): + blocks.append("Your previous answer:\n" + "\n".join(texts)) + answered = True + elif answered: + blocks.append("That answer could not be used:\n" + "\n".join(texts)) + else: + blocks.append("\n".join(texts)) + return "\n\n".join(blocks) + + +def _accepts_images(judge: Any) -> bool: + try: + return "images" in inspect.signature(judge.generate).parameters + except (TypeError, ValueError): + return False + + +def _run_sync(agent: Agent[None, Any], prompt: str) -> Any: + """``agent.run_sync``, also from a thread whose event loop is running (Jupyter).""" + try: + asyncio.get_running_loop() + except RuntimeError: + return agent.run_sync(prompt) + with ThreadPoolExecutor(max_workers=1) as pool: + return pool.submit(agent.run_sync, prompt).result() + + +def ask_judge( + judge: Any, + prompt: str, + output_type: type[T], + *, + role: str, + retries: int = 1, + images: Sequence[str | Path] = (), + check: Callable[[T], str | None] | None = None, +) -> JudgeReply[T]: + """Ask *judge* for one ``output_type`` answer to *prompt*. + + Args: + judge: Anything with ``generate(prompt, **kwargs) -> str``. + prompt: The request. The JSON Schema of ``output_type`` is + added by this function; the prompt need not describe it. + output_type: The pydantic model the answer must validate as. + role: Name recorded on every exchange (``diagnosis_judge``, ...). + retries: How many more times an invalid answer is sent back. + images: Figure paths for a judge whose ``generate`` takes ``images``; + ignored for one that does not. + check: Optional check on a valid answer. A message asks the judge + to revise; on the last attempt the answer is kept anyway. + + Raises: + JudgeCallError: the judge raised. + JudgeOutputError: no valid answer within ``1 + retries`` attempts. + """ + figures = tuple(str(p) for p in images) if images and _accepts_images(judge) else () + exchanges: list[Exchange] = [] + + def call_judge(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse: + text = render_prompt(messages, info.instructions) + started = time.perf_counter() + try: + raw = judge.generate(text, images=[Path(f) for f in figures]) if figures else judge.generate(text) + except Exception as exc: + exchanges.append(Exchange(role, len(exchanges) + 1, text, None, str(exc), + time.perf_counter() - started, figures)) + raise JudgeCallError(f"{role}: the judge failed: {exc}", exchanges) from exc + exchanges.append(Exchange(role, len(exchanges) + 1, text, str(raw), None, + time.perf_counter() - started, figures)) + return ModelResponse(parts=[TextPart(str(raw))]) + + def parse(ctx: RunContext[None], text: str) -> T: + try: + answer = validate_reply(text, output_type) + except (ValueError, ValidationError) as exc: + raise ModelRetry(str(exc)) from exc + problem = check(answer) if check is not None else None + if problem and ctx.retry < ctx.max_retries: + raise ModelRetry(problem) + return answer + + agent: Agent[None, T] = Agent( + FunctionModel(call_judge), + output_type=TextOutput(parse), + instructions=_SCHEMA_INSTRUCTIONS.format( + schema=json.dumps(output_type.model_json_schema(), indent=1) + ), + retries=retries, + ) + try: + result = _run_sync(agent, prompt) + except JudgeCallError: + raise + except UnexpectedModelBehavior as exc: + raise JudgeOutputError( + f"{role}: no valid answer after {len(exchanges)} attempt(s)", exchanges + ) from exc + return JudgeReply(output=result.output, exchanges=tuple(exchanges)) diff --git a/evalrx/agent_runtime/judges/__init__.py b/evalrx/agent_runtime/judges/__init__.py index 0fdd714e..d16e5a1c 100644 --- a/evalrx/agent_runtime/judges/__init__.py +++ b/evalrx/agent_runtime/judges/__init__.py @@ -11,11 +11,13 @@ resolve_cli_judge, ) from evalrx.agent_runtime.judges.claude import ClaudeModel +from evalrx.agent_runtime.judges.cli_agent import CliAgentJudge from evalrx.agent_runtime.judges.codex import CodexModel __all__ = [ "AgyModel", "ClaudeModel", + "CliAgentJudge", "CodexModel", "scan_agy_log", "DEFAULT_AGY_CANDIDATES", diff --git a/evalrx/agent_runtime/judges/_cli.py b/evalrx/agent_runtime/judges/_cli.py new file mode 100644 index 00000000..42e5f024 --- /dev/null +++ b/evalrx/agent_runtime/judges/_cli.py @@ -0,0 +1,56 @@ +"""What the CLI judges share: running the binary and deciding whether it answered. + +Each judge builds its own command line; this module runs it the same way for +all of them (process-group kill on timeout, prompt on stdin) and applies the +same reading of the result: + +* a limit notice (plan / session / spend / usage) printed as if it were an + answer raises, because the CLIs report one on stdout with exit 0; +* a non-zero exit with no output raises, with the reason the CLI gave; +* an empty answer is returned as ``""`` with a warning, so callers that read + free text can fall back; typed calls (``ask_judge``) treat it as invalid. +""" + +from __future__ import annotations + +import warnings +from pathlib import Path + +from evalrx.agent_runtime.cli_runtime import ( + LIMIT_NOTICE, + NOTICE_MAX_CHARS, + ProcessRun, + SubprocessRunner, +) + + +def run_cli( + name: str, cmd: list[str], *, cwd: Path, timeout_sec: int, stdin_text: str | None = None, +) -> ProcessRun: + """Run one judge invocation; raise ``RuntimeError`` when it times out.""" + run = SubprocessRunner().run(cmd, cwd, timeout_sec, stdin_text=stdin_text) + if run.timed_out: + raise RuntimeError(f"{name} timed out after {timeout_sec}s") + return run + + +def read_reply(name: str, run: ProcessRun, output: str, *, failure_reason: str = "") -> str: + """The judge's answer from *output*, or ``RuntimeError`` when it gave none. + + *failure_reason* replaces stderr/stdout as the explanation of a failed + exit (agy keeps its reason in a log file). + """ + output = output.strip() + if len(output) < NOTICE_MAX_CHARS and LIMIT_NOTICE.search(output): + raise RuntimeError(f"{name}: account limit reached, not a judge answer: {output!r}") + if run.returncode != 0 and not output: + reason = failure_reason or (run.stderr or run.stdout or "").strip()[-500:] + raise RuntimeError(f"{name} exited {run.returncode}: {reason}") + if not output: + detail = f" -- {failure_reason}" if failure_reason else "" + warnings.warn( + f"{name} returned an empty response{detail}; it is likely rate-limited or " + "out of quota.", + stacklevel=3, + ) + return output diff --git a/evalrx/agent_runtime/judges/agy.py b/evalrx/agent_runtime/judges/agy.py index 9b40b763..8037a75d 100644 --- a/evalrx/agent_runtime/judges/agy.py +++ b/evalrx/agent_runtime/judges/agy.py @@ -6,11 +6,11 @@ import pathlib import re import shutil -import subprocess import tempfile -import warnings from pathlib import Path +from evalrx.agent_runtime.judges._cli import read_reply, run_cli + AGY_ERROR_MARKERS = ( "RESOURCE_EXHAUSTED", "code 429", @@ -143,40 +143,16 @@ def generate( if self._effort: cmd += ["--effort", self._effort] - try: - proc = subprocess.run( - cmd, - capture_output=True, - timeout=self._timeout_sec, - text=True, - encoding="utf-8", - errors="replace", - env={**os.environ}, - ) - except subprocess.TimeoutExpired as exc: - raise RuntimeError( - f"AgyModel: agy timed out after {self._timeout_sec}s" - ) from exc - - output = proc.stdout.strip() - if proc.returncode != 0 and not output: - # Startup errors (e.g. an unsupported model) are on stderr; - # background quota logs can misleadingly say "not logged in" - # even when API-key authentication is configured correctly. - reason = (proc.stderr or "").strip()[:600] or scan_agy_log(log_path) - raise RuntimeError(f"AgyModel: agy exited {proc.returncode}: {reason}") - - output = re.sub(r".*?", "", output, flags=re.DOTALL).strip() - if not output: - reason = scan_agy_log(log_path) - warnings.warn( - "AgyModel: agy returned an empty response" - + (f" -- {reason}" if reason else "") - + ". agy is likely rate-limited or quota-exhausted; the caller " - "will fall back to a non-LLM path.", - stacklevel=2, - ) - return output + name = f"AgyModel: {Path(self._binary).name}" + cwd = Path(workspace_dir or tempfile.mkdtemp(prefix="agy_ws_")) + workspace_dir = str(cwd) + run = run_cli(name, cmd, cwd=cwd, timeout_sec=self._timeout_sec) + output = re.sub(r".*?", "", run.stdout, flags=re.DOTALL) + # Startup errors (e.g. an unsupported model) are on stderr; + # background quota logs can misleadingly say "not logged in" + # even when API-key authentication is configured correctly. + reason = (run.stderr or "").strip()[:600] if run.returncode != 0 else "" + return read_reply(name, run, output, failure_reason=reason or scan_agy_log(log_path)) finally: safe_unlink(log_path) if workspace_dir: diff --git a/evalrx/agent_runtime/judges/claude.py b/evalrx/agent_runtime/judges/claude.py index cbaebff0..c42650a0 100644 --- a/evalrx/agent_runtime/judges/claude.py +++ b/evalrx/agent_runtime/judges/claude.py @@ -4,19 +4,11 @@ import os import pathlib -import re import shutil -import subprocess import tempfile -import warnings from pathlib import Path -#: The Claude Code CLI's limit notices (plan / session / spend / usage), which -#: arrive on stdout with exit 0 exactly like a real answer. -_LIMIT_RE = re.compile( - r"hit your (monthly |weekly |session )?(spend|usage|rate) limit|" - r"(spend|usage) limit (reached|exceeded)|out of (extra )?usage|" - r"limit resets", re.I) +from evalrx.agent_runtime.judges._cli import read_reply, run_cli class ClaudeModel: @@ -110,44 +102,17 @@ def generate( if self._effort: cmd += ["--effort", self._effort] + # The CLI runs in a throwaway directory, never the caller's + # working tree; an image-bearing call reads the staged figures. + cwd = Path(img_dir or tempfile.mkdtemp(prefix="claude_judge_")) + scratch = None if img_dir else cwd try: - proc = subprocess.run( - cmd, - input=prompt_text, - capture_output=True, - timeout=self._timeout_sec, - text=True, - encoding="utf-8", - errors="replace", - env={**os.environ}, - ) - except subprocess.TimeoutExpired as exc: - raise RuntimeError( - f"ClaudeModel: claude timed out after {self._timeout_sec}s" - ) from exc - - output = (proc.stdout or "").strip() - # The CLI reports an exhausted plan/session/spend limit as a one-line - # *answer* on stdout with exit 0 ("You've hit your monthly spend - # limit ..."). Returned as a judge reply it parses to zero - # hypotheses and the run "finishes" with an empty diagnosis - # (qwen2-audio/mmau 2026-09-07, all three demo128 cells - # 2026-09-09). Fail loudly instead. - if len(output) < 400 and _LIMIT_RE.search(output): - raise RuntimeError(f"ClaudeModel: account limit reached, not a judge answer: {output!r}") - if proc.returncode != 0 and not output: - reason = (proc.stderr or "").strip()[:240] - raise RuntimeError( - f"ClaudeModel: claude exited {proc.returncode}: {reason}" - ) - if not output: - warnings.warn( - "ClaudeModel: claude returned an empty response -- likely " - "rate-limited or out of quota; the caller will fall back " - "to a non-LLM path.", - stacklevel=2, - ) - return output + run = run_cli(f"ClaudeModel: {Path(self._binary).name}", cmd, cwd=cwd, + timeout_sec=self._timeout_sec, stdin_text=prompt_text) + finally: + if scratch is not None: + shutil.rmtree(scratch, ignore_errors=True) + return read_reply(f"ClaudeModel: {Path(self._binary).name}", run, run.stdout) finally: if img_dir: shutil.rmtree(img_dir, ignore_errors=True) diff --git a/evalrx/agent_runtime/judges/cli_agent.py b/evalrx/agent_runtime/judges/cli_agent.py new file mode 100644 index 00000000..af711700 --- /dev/null +++ b/evalrx/agent_runtime/judges/cli_agent.py @@ -0,0 +1,53 @@ +"""A CLI coding agent used as a judge: it writes its answer to a file. + +A coding agent's output stream is a whole trajectory (plans, tool calls, drafts), +not an answer, so it is never parsed. The agent is asked to write its final +answer to ``answer.json`` in a fresh directory and that file is the reply. Each +call gets its own directory, so a retry can never read an earlier attempt. +""" + +from __future__ import annotations + +import tempfile +from pathlib import Path +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from evalrx.agent_runtime.cli_types import CliAgentConfig + +ANSWER_FILE = "answer.json" + +_ANSWER_NOTE = ( + f"\n\nWrite your final answer, and nothing else, to the file {ANSWER_FILE} in " + "the current directory. Do not write any other files." +) + + +class CliAgentJudge: + """``generate(prompt) -> str`` over a CLI coding agent (``claude_code``, ``codex``, ...). + + Returns the text of the answer file, ``""`` when the agent wrote none (so + :func:`~evalrx.agent_runtime.judge_call.ask_judge` asks again), and raises + when the agent itself failed (timeout, crash). + """ + + def __init__(self, cli_config: "CliAgentConfig", *, timeout_sec: int = 90) -> None: + self.cli_config = cli_config + self.timeout_sec = timeout_sec + + def __repr__(self) -> str: + return f"CliAgentJudge(provider={self.cli_config.provider!r}, model={self.cli_config.model!r})" + + def generate(self, prompt: str) -> str: + from evalrx.agent_runtime.codegen import CodegenRunner + + with tempfile.TemporaryDirectory(prefix="evalrx_answer_") as tmp: + result = CodegenRunner(self.cli_config).run( + prompt + _ANSWER_NOTE, workdir=Path(tmp), timeout_sec=self.timeout_sec, + ) + answer = Path(tmp) / ANSWER_FILE + if answer.is_file(): + return answer.read_text(encoding="utf-8") + if result.error: + raise RuntimeError(f"{self.cli_config.provider}: {result.error}") + return "" diff --git a/evalrx/agent_runtime/judges/codex.py b/evalrx/agent_runtime/judges/codex.py index 635b6b81..82b45ee5 100644 --- a/evalrx/agent_runtime/judges/codex.py +++ b/evalrx/agent_runtime/judges/codex.py @@ -10,11 +10,11 @@ import os import pathlib import shutil -import subprocess import tempfile -import warnings from pathlib import Path +from evalrx.agent_runtime.judges._cli import read_reply, run_cli + class CodexModel: """Codex CLI wrapped behind EvalRX' ``generate`` model protocol.""" @@ -84,32 +84,11 @@ def generate( cmd += ["--model", self._model] if self._effort: cmd += ["-c", f'model_reasoning_effort="{self._effort}"'] - try: - proc = subprocess.run( - cmd, - input=prompt_text, - capture_output=True, - timeout=self._timeout_sec, - text=True, - encoding="utf-8", - errors="replace", - env={**os.environ}, - ) - except subprocess.TimeoutExpired as exc: - raise RuntimeError( - f"CodexModel: codex timed out after {self._timeout_sec}s" - ) from exc - - output = output_path.read_text(encoding="utf-8", errors="replace").strip() if output_path.is_file() else "" - if proc.returncode != 0 and not output: - reason = (proc.stderr or proc.stdout or "").strip()[-500:] - raise RuntimeError(f"CodexModel: codex exited {proc.returncode}: {reason}") - if not output: - warnings.warn( - "CodexModel: codex returned an empty response; the caller will fall back to a non-LLM path.", - stacklevel=2, - ) - return output + name = f"CodexModel: {Path(self._binary).name}" + run = run_cli(name, cmd, cwd=Path(workspace), timeout_sec=self._timeout_sec, + stdin_text=prompt_text) + output = output_path.read_text(encoding="utf-8", errors="replace") if output_path.is_file() else "" + return read_reply(name, run, output) finally: shutil.rmtree(workspace, ignore_errors=True) diff --git a/evalrx/agent_runtime/providers/base.py b/evalrx/agent_runtime/providers/base.py index 9731c203..93e41688 100644 --- a/evalrx/agent_runtime/providers/base.py +++ b/evalrx/agent_runtime/providers/base.py @@ -5,7 +5,13 @@ import logging from pathlib import Path -from evalrx.agent_runtime.cli_runtime import ProcessRun, SubprocessRunner, collect_py_files +from evalrx.agent_runtime.cli_runtime import ( + LIMIT_NOTICE, + NOTICE_MAX_CHARS, + ProcessRun, + SubprocessRunner, + collect_py_files, +) from evalrx.agent_runtime.cli_transcript import RAW_OUTPUT_CAP from evalrx.agent_runtime.cli_types import CliAgentResult from evalrx.agent_runtime.skill_audit import build_agent_audit @@ -91,9 +97,14 @@ def _run_subprocess(self, cmd: list[str], workdir: Path, timeout_sec: int) -> Pr def _build_result(self, workdir: Path, run: ProcessRun) -> CliAgentResult: files = collect_py_files(workdir) + raw_output, usage = self._postprocess_output(run.stdout) + # The CLIs print a limit notice, exit 0, where the session would be. + tail = raw_output.strip()[-NOTICE_MAX_CHARS:] error: str | None = None if run.timed_out: error = f"[TIMEOUT] agent killed after {run.elapsed_sec:.0f}s" + elif not files and LIMIT_NOTICE.search(tail): + error = f"account limit reached: {tail!r}" elif run.returncode != 0 and not files: error = f"Exited {run.returncode}: {run.stderr[:500]}" @@ -110,7 +121,6 @@ def _build_result(self, workdir: Path, run: ProcessRun) -> CliAgentResult: except OSError: logger.debug("could not persist raw agent stream for %s", self._provider_name) - raw_output, usage = self._postprocess_output(run.stdout) audit = build_agent_audit( provider=self._provider_name, skills=self._skills, diff --git a/evalrx/agent_runtime/skill_audit.py b/evalrx/agent_runtime/skill_audit.py index ac67ad06..3502f555 100644 --- a/evalrx/agent_runtime/skill_audit.py +++ b/evalrx/agent_runtime/skill_audit.py @@ -64,7 +64,8 @@ def _codex_evidence(stdout: str, requested: list[str]) -> list[dict[str, str]]: """ evidence: list[dict[str, str]] = [] for event in _json_lines(stdout): - item = event.get("item") if isinstance(event.get("item"), dict) else {} + raw_item = event.get("item") + item = raw_item if isinstance(raw_item, dict) else {} if item.get("type") != "command_execution": continue command = str(item.get("command") or "") diff --git a/evalrx/analysis/DESIGN.md b/evalrx/analysis/DESIGN.md index 70ae36b6..26590f63 100644 --- a/evalrx/analysis/DESIGN.md +++ b/evalrx/analysis/DESIGN.md @@ -18,7 +18,7 @@ ``` M1 ProbeAgent analyzers → probe_results(Result.findings["per_case"] 是关键载体) → M2 StatsAnalysisAgent 在「全部 per_case 信号」上跑已验证工具族 - → e-BH → corrected_rejections.rejected_tools + conclusion/evidence + → e-BH → corrected_rejections.rejected_result_keys + conclusion/evidence → M3 DiagnosisAgent 读 M2 conclusion/evidence + findings → 提可证伪假设 → M4 HypothesisTester 检验每个假设 → M5 SurgeryAgent + FixAgent 设计实验、修复;配对 e-value、候选族 e-BH、留出 CONFIRM @@ -26,8 +26,8 @@ M1 ProbeAgent analyzers → probe_results(Result.findings["per_case"] 是 为什么不能删 M2、为什么 LAMBDA 必须在 M2 **上游**: -1. **M2 的信号族只从 `per_case` 构造**(`build_stats_input`,[stats_tools.py](stats_tools.py))。**一个信号若不在某 analyzer 的 `per_case` 里,永远进不了 M2 family、拿不到 e-value、永不出现在 `rejected_tools`。** -2. **M4 不自洽,gated on M2**(`_decisive`,[hypothesis_tester.py:324-343](../eval_agent/stages/hypothesis_tester.py)):带 e-value 的结果只有 `tool ∈ rejected_tools` 才算 decisive。 +1. **M2 的信号族只从 `per_case` 构造**(`build_stats_input`,[stats_tools.py](stats_tools.py))。**一个信号若不在某 analyzer 的 `per_case` 里,永远进不了 M2 family、拿不到 e-value、永不出现在 `rejected_result_keys`。** +2. **M4 不自洽,gated on M2**(`_decisive`,[hypothesis_tester.py:324-343](../eval_agent/stages/hypothesis_tester.py)):只有多重性校正后仍被拒绝的结果(`fdr_corrected`,或 `analysis_key ∈ rejected_result_keys`)才算 decisive。 3. **M3 优先读 M2 的 conclusion/evidence**([diagnosis.py:402-411](../eval_agent/stages/diagnosis.py))。 → 推论:若 LAMBDA 只在 M2 **之后**提假设,它发现的任何新信号永远拿不到 e-value,M4 判非 decisive,假设全塌成 INCONCLUSIVE。**必须在 M2 跑之前把信号桥接进它的族。** @@ -50,7 +50,7 @@ M1 ProbeAgent analyzers → probe_results(Result.findings["per_case"] 是 ▼ ▼ CONFIRM split ── ③ M2 = 防火墙(保留,信号族扩大):validated catalog 跑 「catalog 信号 + 桥接来的 LAMBDA 信号」→ e-BH FDR - → rejected_tools + conclusion/evidence 【盲于、先于 M3,在 CONFIRM 上】 + → rejected_result_keys + conclusion/evidence 【盲于、先于 M3,在 CONFIRM 上】 ▼ ④ M3 = 提议者(增强):读 (a) M2 survivor+evidence(什么真) + (b) LAMBDA observations/charts(机制语言)→ 提可证伪假设 @@ -88,7 +88,7 @@ def compile_recipe(recipe, records) -> dict[str, float]: 产物进 Result.findings["per_case"] → build_stats_input 自动收进 inp.per_case。""" ``` -**注册进 M2**:编译出的信号塞进合成 analyzer 的 per_case finding → 扩展 `default_plan` 为新信号加一条已验证工具 → 在 CONFIRM split 上跑 `fdr_correct`,把【catalog 信号 + 桥接信号】放进**同一个 e-BH family**("多提候选→多付多重性"自动成立)→ M4 `_decisive` 不变。 +**注册进 M2**:编译出的信号塞进合成 analyzer 的 per_case finding → 扩展 `plan_stats_input` 为新信号加一条已验证工具 → 在 CONFIRM split 上跑 `fdr_correct`,把【catalog 信号 + 桥接信号】放进**同一个 e-BH family**("多提候选→多付多重性"自动成立)→ M4 `_decisive` 不变。 **关键不变量**:信号在 **EXPLORE split** 被发现/选中,在 **CONFIRM split** 被编译求值 + 确证;case id 不相交。 diff --git a/evalrx/analysis/__init__.py b/evalrx/analysis/__init__.py index a7ce5c92..c043d79f 100755 --- a/evalrx/analysis/__init__.py +++ b/evalrx/analysis/__init__.py @@ -54,7 +54,6 @@ StatsToolResult, build_stats_input, build_stats_input_from_records, - default_plan, fdr_correct, run_stats_tool, ) @@ -66,8 +65,6 @@ extract_archive, ingest_directory, ) -from evalrx.reporting.compiler import compile_diagnostic_report -from evalrx.reporting.model import Claim, DiagnosticReport, Evidence, ReportStep __all__ = [ "explore", @@ -107,11 +104,6 @@ "run_fused_analysis", "FusedReport", "FusedSignal", - "DiagnosticReport", - "Claim", - "Evidence", - "ReportStep", - "compile_diagnostic_report", "load_records_from_path", "scan_folder", "StatsInput", @@ -120,7 +112,6 @@ "STATS_TOOL_CATALOG", "build_stats_input", "build_stats_input_from_records", - "default_plan", "fdr_correct", "run_stats_tool", "DatasetBundle", diff --git a/evalrx/analysis/adjudicate.py b/evalrx/analysis/adjudicate.py index 007bf0a0..74e36286 100644 --- a/evalrx/analysis/adjudicate.py +++ b/evalrx/analysis/adjudicate.py @@ -90,14 +90,15 @@ def adjudicate_signals( family_key[i] = key family.append( StatsToolResult( - tool=key, e_value=e_value, effect=effect, ci=ci, reject=bool(reject) + tool="candidate_signal", analysis_key=key, + e_value=e_value, effect=effect, ci=ci, reject=bool(reject), ) ) # 2) ONE e-BH family across the e-value-bearing candidates (the multiplicity # firewall). `fdr_correct` only considers results with an e-value. fdr = fdr_correct(family, alpha=alpha) - rejected_keys = set(fdr.get("rejected_tools", [])) + rejected_keys = set(fdr.get("rejected_result_keys", [])) # 3) Final reject per candidate. for i, c in enumerate(candidates): diff --git a/evalrx/analysis/explore_run.py b/evalrx/analysis/explore_run.py index 51e2db97..163cd5b4 100644 --- a/evalrx/analysis/explore_run.py +++ b/evalrx/analysis/explore_run.py @@ -12,7 +12,7 @@ -> HypothesisAgent.propose # M3: falsifiable hypotheses from M2's takeaways -> render_chart_specs # spec + CSV -> PNG, host-side -> write_report_artifacts # report.json + figures/ + tables/ + code - -> build_html_report # report.html (opened when asked) + -> write_report # report.html (opened when asked) """ from __future__ import annotations @@ -224,14 +224,11 @@ def run_explore( json.dumps(split_meta, indent=1), encoding="utf-8" ) - # The HTML report is the canonical visualization artifact. Generate it - # even when the caller does not immediately open a browser so every + # The report is written even when no browser is opened, so every # completed exploratory run is portable and reviewable. - from evalrx.reporting.html_report import build_html_report, open_in_browser + from evalrx.reporting.static_export import write_report - written = build_html_report(out_dir, out_path=out_dir / "report.html") - if open_report: - open_in_browser(written) + write_report(out_dir, open_report=open_report) return 0 if report.ok else 1 diff --git a/evalrx/analysis/explorer.py b/evalrx/analysis/explorer.py index 885e7470..fa081820 100755 --- a/evalrx/analysis/explorer.py +++ b/evalrx/analysis/explorer.py @@ -59,7 +59,7 @@ if TYPE_CHECKING: from evalrx.agent_runtime.cli_types import CliAgentConfig - from evalrx.core.model import Model + from evalrx.core.model import Judge, Model logger = logging.getLogger(__name__) @@ -245,7 +245,7 @@ class ExploratoryAnalysisAgent: def __init__( self, - judge: "Model | None" = None, + judge: "Judge | None" = None, inspector: "Model | None" = None, cli_config: "CliAgentConfig | None" = None, sandbox: ExperimentSandbox | None = None, diff --git a/evalrx/analysis/failure_modes.py b/evalrx/analysis/failure_modes.py index 99a78f6e..48ae585a 100644 --- a/evalrx/analysis/failure_modes.py +++ b/evalrx/analysis/failure_modes.py @@ -16,10 +16,12 @@ from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, Callable -from evalrx.agent_runtime.json_shape import validate_json_shape +from pydantic import BaseModel, Field, RootModel + +from evalrx.agent_runtime.judge_call import JudgeError, ask_judge if TYPE_CHECKING: - from evalrx.core.model import Model + from evalrx.core.model import Judge logger = logging.getLogger(__name__) @@ -134,18 +136,24 @@ def _error_signal_deterministic(row: dict[str, Any], expected_col: str) -> str: return f"expected={str(expected)[:80]} got={_row_output(row)[:80]}" +class _ErrorSignal(BaseModel): + index: int + error: str + + +class _ErrorSignals(RootModel[list[_ErrorSignal]]): + """One entry per FAIL pair.""" + + def _error_signals_llm( fail_rows: list[tuple[int, dict[str, Any]]], expected_col: str, - judge: "Model", - *, - max_repairs: int = 1, + judge: "Judge", ) -> "list[str] | None": """One batched call describing the failure mechanism for every FAIL row. - Returns a list aligned 1:1 with *fail_rows*, or None if the judge never - produced a parseable response (caller falls back to the deterministic - signal in that case). + Returns a list aligned 1:1 with *fail_rows*, or None when the judge gives + no valid answer (the caller then uses the deterministic signal). """ from evalrx.analysis.prompts.failure_modes import ERROR_SIGNAL_PROMPT @@ -153,29 +161,14 @@ def _error_signals_llm( f"{i}: expected={str(row.get(expected_col))[:150]!r} got={_row_output(row)[:150]!r}" for i, (_, row) in enumerate(fail_rows) ) - prompt = ERROR_SIGNAL_PROMPT.format(pairs_block=pairs_block) - schema = { - "type": "array", - "items": {"type": "object", "required": ["index", "error"]}, - } - - for _attempt in range(max_repairs + 1): - raw = judge.generate(prompt) - text = raw.strip() - if text.startswith("```"): - text = re.sub(r"^```\w*\n?", "", text) - text = re.sub(r"\n?```\s*$", "", text) - try: - import json - - data = json.loads(text) - except json.JSONDecodeError: - continue - if validate_json_shape(data, schema): - continue - by_index = {int(item["index"]): str(item["error"]) for item in data if "index" in item} - return [by_index.get(i, "") for i in range(len(fail_rows))] - return None + try: + reply = ask_judge(judge, ERROR_SIGNAL_PROMPT.format(pairs_block=pairs_block), + _ErrorSignals, role="failure_error_signals") + except JudgeError as exc: + logger.warning("cluster_failures: %s; using the deterministic error signal", exc) + return None + by_index = {item.index: item.error for item in reply.output.root} + return [by_index.get(i, "") for i in range(len(fail_rows))] def _compute_error_signals( @@ -183,7 +176,7 @@ def _compute_error_signals( *, expected_col: "str | None", error_fn: "Callable[[dict[str, Any]], str] | None", - judge: "Model | None", + judge: "Judge | None", ) -> list[str]: """Per-FAIL-row failure-mechanism strings, aligned with *fail_rows*. @@ -381,11 +374,22 @@ def _boundary_contrast_pairs( return pairs -def _name_clusters_with_llm( - judge: "Model", clusters: list[FailureMode], *, max_repairs: int = 1 -) -> bool: - """Best-effort: ask *judge* to name/describe each cluster from its - exemplars. Returns True on success (clusters updated in place).""" +class _ClusterName(BaseModel): + cluster_id: int + name: str = Field(min_length=1) + description: str = "" + + +class _ClusterNames(RootModel[list[_ClusterName]]): + """One entry per cluster.""" + + +def _name_clusters_with_llm(judge: "Judge", clusters: list[FailureMode]) -> bool: + """Ask *judge* to name/describe each cluster from its exemplars. + + Returns True when the clusters were renamed in place, False when the + judge gave no valid answer (they keep their deterministic names). + """ from evalrx.analysis.prompts.failure_modes import NAME_CLUSTERS_PROMPT blocks = [] @@ -402,39 +406,21 @@ def _name_clusters_with_llm( ] block += "\n Boundary contrast (failure vs. nearest success):\n" + "\n".join(contrast_lines) blocks.append(block) - prompt = NAME_CLUSTERS_PROMPT.format(clusters_block="\n\n".join(blocks)) - - schema = { - "type": "array", - "items": { - "type": "object", - "required": ["cluster_id", "name", "description"], - "properties": {"name": {"type": "string", "minLength": 1}}, - }, - } - - for _attempt in range(max_repairs + 1): - raw = judge.generate(prompt) - text = raw.strip() - if text.startswith("```"): - text = re.sub(r"^```\w*\n?", "", text) - text = re.sub(r"\n?```\s*$", "", text) - try: - import json - - data = json.loads(text) - except json.JSONDecodeError: - continue - if validate_json_shape(data, schema): - continue - by_id = {int(item["cluster_id"]): item for item in data if "cluster_id" in item} - for i, c in enumerate(clusters): - item = by_id.get(i) - if item: - c.name = str(item["name"]) - c.description = str(item.get("description", c.description)) - return True - return False + try: + reply = ask_judge( + judge, NAME_CLUSTERS_PROMPT.format(clusters_block="\n\n".join(blocks)), + _ClusterNames, role="failure_cluster_names", + ) + except JudgeError as exc: + logger.warning("cluster_failures: %s; keeping the deterministic names", exc) + return False + by_id = {item.cluster_id: item for item in reply.output.root} + for i, c in enumerate(clusters): + item = by_id.get(i) + if item: + c.name = item.name + c.description = item.description or c.description + return True def cluster_failures( @@ -445,7 +431,7 @@ def cluster_failures( text_cols: "list[str] | None" = None, signal_cols: "list[str] | None" = None, id_key: str = "case_id", - judge: "Model | None" = None, + judge: "Judge | None" = None, min_cluster_size: int = 3, max_clusters: int = 8, n_exemplars: int = 3, @@ -558,7 +544,7 @@ def cluster_failures( X, method=method, min_cluster_size=min_cluster_size, max_clusters=max_clusters ) - corpus_freq: Counter = Counter() + corpus_freq = Counter() for t in texts: corpus_freq.update(set(_tokenize(t))) diff --git a/evalrx/analysis/fused_pipeline.py b/evalrx/analysis/fused_pipeline.py index ddddfee8..01709cc8 100644 --- a/evalrx/analysis/fused_pipeline.py +++ b/evalrx/analysis/fused_pipeline.py @@ -24,9 +24,8 @@ dropped and nothing is over-claimed. Multiplicity note: paired/e-value tools use e-BH and marginal p-value tools use -BH. The report exposes both legacy ``rejected_tools`` and precise -``rejected_result_keys`` so M1-M4 remains compatible while standalone M2 can -audit the exact tested family. +BH. The report's ``rejected_result_keys`` name each surviving result, so the +exact tested family can be audited. """ from __future__ import annotations @@ -202,7 +201,7 @@ def run_fused_analysis( ) held_out = confirm_rows is not None confirm_label = "held_out" if held_out else "in_sample" - if not held_out: + if confirm_rows is None: confirm_rows = explore_rows # in-sample fallback (small batch) report = FusedReport(question=question) @@ -317,7 +316,6 @@ def run_fused_analysis( ) report.conclusion = getattr(confirm_report, "conclusion", "") corrected = getattr(confirm_report, "corrected_rejections", {}) or {} - rejected_tools = set(corrected.get("rejected_tools", [])) rejected_result_keys = set(corrected.get("rejected_result_keys", [])) # ── 5. Assemble per-signal verdicts (provenance-tagged) ── @@ -333,7 +331,6 @@ def run_fused_analysis( suggested_test=_suggested_test(origin, explorer_named), recipe=recipe_by_name.get(origin), result=result, - rejected_tools=rejected_tools, rejected_result_keys=rejected_result_keys, confirmed_on=confirm_label, ) @@ -366,7 +363,6 @@ def run_fused_analysis( "method": corrected.get("method", "e-BH"), "alpha": corrected.get("alpha"), "n_in_family": corrected.get("n_tested", 0), - "rejected_tools": sorted(rejected_tools), "rejected_result_keys": sorted(rejected_result_keys), "families": corrected.get("families", {}), "n_signals_tested": len(confirm_inp.per_case), @@ -418,7 +414,6 @@ def _fused_signal( suggested_test: str, recipe: dict[str, Any] | None, result: Any, - rejected_tools: set[str], rejected_result_keys: set[str], confirmed_on: str, ) -> FusedSignal: @@ -442,10 +437,8 @@ def _fused_signal( fs.underpowered = bool(getattr(result, "underpowered", False)) fs.reject = bool(getattr(result, "reject", False)) fs.correction_method = getattr(result, "correction_method", None) - result_key = getattr(result, "analysis_key", None) fs.fdr_corrected = bool(getattr(result, "fdr_corrected", False)) or ( - (result_key in rejected_result_keys) - or (getattr(result, "tool", "") in rejected_tools and fs.e_value is not None) + getattr(result, "analysis_key", None) in rejected_result_keys ) if fs.fdr_corrected: fs.reject = True @@ -477,8 +470,9 @@ def _describe( bridged_keys: set[str], ) -> str: c = explorer_named.get(origin) or explorer_named.get(name) - if c is not None and getattr(c, "rationale", ""): - return c.rationale + rationale = getattr(c, "rationale", "") if c is not None else "" + if rationale: + return rationale if name in bridged_keys: return "bridged explorer signal" return "existing per-case column" diff --git a/evalrx/analysis/holdout.py b/evalrx/analysis/holdout.py index a54c64e3..6558006a 100644 --- a/evalrx/analysis/holdout.py +++ b/evalrx/analysis/holdout.py @@ -24,10 +24,11 @@ from __future__ import annotations -import json -import re -from typing import Any +from typing import Any, Literal +from pydantic import BaseModel + +from evalrx.agent_runtime.judge_call import JudgeError, ask_judge from evalrx.analysis.adjudicate import adjudicate_signals from evalrx.analysis.explorer import CandidateSignal from evalrx.analysis.fused_pipeline import _split_records @@ -130,15 +131,10 @@ def _holdout_sufficient( return {"kind": "two_group", "a": a, "b": b} -def _judge_json(text: str) -> "dict[str, Any] | None": - m = re.search(r"\{.*\}", text, re.S) - if not m: - return None - try: - parsed = json.loads(m.group(0)) - except json.JSONDecodeError: - return None - return parsed if isinstance(parsed, dict) else None +class _HoldoutVerdict(BaseModel): + verdict: Literal["supported", "partial", "refuted", "not_testable"] + reasoning: str + needs_surgery: bool = False def holdout_confirm( @@ -228,13 +224,13 @@ def holdout_confirm( meta = adjudicate_signals(candidates, alpha=alpha, split_label="held_out") by_name = {c.name: c for c in candidates} for entry in signal_verdicts: - cand = by_name.get(str(entry.get("name"))) - if entry.get("status") == "adjudicated" and cand is not None: + adjudicated = by_name.get(str(entry.get("name"))) + if entry.get("status") == "adjudicated" and adjudicated is not None: entry.update( - reject=bool(cand.reject), - effect=cand.effect, - ci=cand.ci, - fdr_corrected=bool(cand.fdr_corrected), + reject=bool(adjudicated.reject), + effect=adjudicated.effect, + ci=adjudicated.ci, + fdr_corrected=bool(adjudicated.fdr_corrected), ) # ── 2. LLM judge per hypothesis, grounded in the held-out table ───────── @@ -263,23 +259,14 @@ def holdout_confirm( evidence=evidence, ) try: - raw = judge.generate(prompt) or "" - except Exception as exc: # noqa: BLE001 — judge outage must not sink the verdicts - raw = "" - verdict["judge_error"] = str(exc) - parsed = _judge_json(raw) - if parsed and parsed.get("verdict") in {"supported", "partial", "refuted", "not_testable"}: - verdict.update( - verdict=parsed["verdict"], - reasoning=str(parsed.get("reasoning", "")), - needs_surgery=bool(parsed.get("needs_surgery", False)), - ) + graded = ask_judge(judge, prompt, _HoldoutVerdict, role="holdout_judge").output + except JudgeError as exc: # a judge outage must not sink the signal verdicts + # "not_testable" would be a claim about the hypothesis; the judge made none. + verdict.update(verdict="not_judged", reasoning="", needs_surgery=True, + judge_error=str(exc)) else: - verdict.update( - verdict="not_testable", - reasoning="judge output unparseable — defaulting to not_testable", - needs_surgery=True, - ) + verdict.update(verdict=graded.verdict, reasoning=graded.reasoning, + needs_surgery=graded.needs_surgery) hypothesis_verdicts.append(verdict) return { diff --git a/evalrx/analysis/hypothesis_agent.py b/evalrx/analysis/hypothesis_agent.py index ad373e9f..c6fa0c8d 100644 --- a/evalrx/analysis/hypothesis_agent.py +++ b/evalrx/analysis/hypothesis_agent.py @@ -20,11 +20,12 @@ from __future__ import annotations import logging -import tempfile from dataclasses import dataclass -from pathlib import Path from typing import TYPE_CHECKING, Any +from pydantic import BaseModel, Field + +from evalrx.agent_runtime.judge_call import JudgeError, ask_judge from evalrx.analysis.plain_language import jargon_violation from evalrx.analysis.prompts.hypothesis_agent import ( AGENT_COLUMN_MARKERS as _AGENT_COLUMN_MARKERS, @@ -32,7 +33,6 @@ from evalrx.analysis.prompts.hypothesis_agent import ( AGENT_TRAJECTORY_HINT as _AGENT_TRAJECTORY_HINT, ) -from evalrx.analysis.prompts.hypothesis_agent import PLAIN_REPAIR_PROMPT as _PLAIN_REPAIR_PROMPT from evalrx.analysis.prompts.hypothesis_agent import PROPOSE_PROMPT as _PROPOSE_PROMPT @@ -59,7 +59,7 @@ def _is_agent_report(report: dict) -> bool: if TYPE_CHECKING: from evalrx.agent_runtime.cli_types import CliAgentConfig - from evalrx.core.model import Model + from evalrx.core.model import Judge logger = logging.getLogger(__name__) @@ -96,7 +96,7 @@ class HypothesisAgent: def __init__( self, - judge: "Model | None" = None, + judge: "Judge | None" = None, cli_config: "CliAgentConfig | None" = None, timeout_sec: int = 90, ) -> None: @@ -106,15 +106,14 @@ def __init__( @property def available(self) -> bool: - return self._judge is not None or ( - self._cli_config is not None and self._cli_config.provider != "llm" - ) + return self._backend() is not None def propose(self, report: dict[str, Any], *, max_items: int = 8) -> list[Hypothesis]: """Read *report* (an ``ExploratoryAnalysisReport.to_dict()``-shaped dict) and return 0-3 proposed hypotheses. Never raises — a backend - failure just yields no hypotheses.""" - if not self.available: + failure, or no valid answer after one retry, yields no hypotheses.""" + judge = self._backend() + if judge is None: return [] takeaways = [t for t in report.get("takeaways") or [] if isinstance(t, dict)][:max_items] @@ -140,91 +139,49 @@ def propose(self, report: dict[str, Any], *, max_items: int = 8) -> list[Hypothe if _is_agent_report(report): prompt += "\n\n" + _AGENT_TRAJECTORY_HINT try: - raw = self._generate(prompt) - except Exception as exc: # noqa: BLE001 - logger.warning("HypothesisAgent: generation failed: %s", exc) + reply = ask_judge(judge, prompt, _Proposal, role="explore_hypotheses", + check=_plain_language_problems) + except JudgeError as exc: + logger.warning("HypothesisAgent: no hypotheses: %s", exc) return [] - hypotheses = _parse_hypotheses(raw) - return self._repair_plain_language(raw, hypotheses) - - def _repair_plain_language(self, raw: str, hypotheses: list[Hypothesis]) -> list[Hypothesis]: - """One bounded retry: if any PLAIN line is missing or still jargon-y, - ask the backend to rewrite just those lines. Never raises — a repair - failure just keeps the original (possibly jargon-y) hypotheses.""" - if not hypotheses: - return hypotheses - violations = [ - f"hypothesis {i}'s PLAIN line {reason}: {h.plain_statement!r}" - for i, h in enumerate(hypotheses, start=1) - for reason in [jargon_violation(h.plain_statement, h.statement)] - if reason + return [ + Hypothesis(statement=d.hypothesis, plain_statement=d.plain_statement, + basis=d.basis, test_design=d.test) + for d in reply.output.hypotheses ] - if not violations: - return hypotheses - try: - repaired_raw = self._generate( - _PLAIN_REPAIR_PROMPT.format(raw=raw, violations="\n".join(f"- {v}" for v in violations)) - ) - except Exception as exc: # noqa: BLE001 - logger.warning("HypothesisAgent: plain-language repair failed: %s", exc) - return hypotheses - repaired = _parse_hypotheses(repaired_raw) - return repaired or hypotheses - - def _generate(self, prompt: str) -> str: + + def _backend(self) -> "Any | None": if self._cli_config is not None and self._cli_config.provider != "llm": - from evalrx.agent_runtime.codegen import CodegenRunner - - with tempfile.TemporaryDirectory(prefix="evalrx_m3_") as tmp: - res = CodegenRunner(self._cli_config).run( - prompt, - workdir=Path(tmp), - timeout_sec=self._timeout_sec, - ) - return res.raw_output or "" - return str(self._judge.generate(prompt)) # type: ignore[union-attr] - - -def _parse_hypotheses(raw: str) -> list[Hypothesis]: - """Parse ``HYPOTHESIS:``/``PLAIN:``/``BASIS:``/``TEST:`` blocks out of - *raw*. ``PLAIN:`` is optional (older/repaired responses may omit it), - in which case ``plain_statement`` stays "". - - For the CLI-agent backend, *raw* is the full rendered tool-call - trajectory, not just a final answer (``CliAgentResult.raw_output``'s - docstring: "assistant text, every Bash/Edit/Write/Read tool call + - result") — an agent that narrates its plan before giving a final answer - can restate the same hypothesis twice in one trajectory. Dedupe by - statement (case-insensitive), keeping the order hypotheses first - appeared but the most recent basis/test for a repeated statement, since - later restatements tend to be the more refined ones. - """ - if "HYPOTHESIS:" not in raw.upper(): - return [] - by_statement: dict[str, dict[str, str]] = {} - order: list[str] = [] - cur: dict[str, str] | None = None - cur_key: str = "" - - def _flush() -> None: - if cur and cur.get("statement"): - if cur_key not in by_statement: - order.append(cur_key) - by_statement[cur_key] = cur - - for line in raw.splitlines(): - line = line.strip() - upper = line.upper() - if upper.startswith("HYPOTHESIS:"): - _flush() - statement = line.split(":", 1)[1].strip() - cur = {"statement": statement, "plain_statement": "", "basis": "", "test_design": ""} - cur_key = statement.lower() - elif upper.startswith("PLAIN:") and cur is not None: - cur["plain_statement"] = line.split(":", 1)[1].strip() - elif upper.startswith("BASIS:") and cur is not None: - cur["basis"] = line.split(":", 1)[1].strip() - elif upper.startswith("TEST:") and cur is not None: - cur["test_design"] = line.split(":", 1)[1].strip() - _flush() - return [Hypothesis(**by_statement[key]) for key in order] + from evalrx.agent_runtime.judges.cli_agent import CliAgentJudge + + return CliAgentJudge(self._cli_config, timeout_sec=self._timeout_sec) + return self._judge + + +class _Draft(BaseModel): + hypothesis: str = Field(min_length=10, description="one falsifiable technical sentence") + plain_statement: str = Field("", description="the same claim in one everyday sentence") + basis: str = Field("", description="the takeaways or signals it rests on") + test: str = Field("", description="the evidence that would confirm or refute it") + + +class _Proposal(BaseModel): + hypotheses: list[_Draft] = Field(max_length=3) + + +def _plain_language_problems(proposal: _Proposal) -> str | None: + """Feedback for plain statements that fail the jargon check, or ``None``.""" + problems = [ + f"- hypothesis {i}'s plain_statement {reason}: {d.plain_statement!r}" + for i, d in enumerate(proposal.hypotheses, start=1) + for reason in [jargon_violation(d.plain_statement, d.hypothesis)] + if reason + ] + if not problems: + return None + return ( + "Some plain_statement fields fail the plain-language check: each must be a " + "jargon-free, one-sentence, everyday paraphrase of its hypothesis, with no " + "statistics terms, acronyms or symbols. Rewrite only those and keep every " + "other field as it was.\n" + "\n".join(problems) + ) diff --git a/evalrx/analysis/operationalize.py b/evalrx/analysis/operationalize.py index faa55954..7ec9e4d3 100644 --- a/evalrx/analysis/operationalize.py +++ b/evalrx/analysis/operationalize.py @@ -32,7 +32,7 @@ import operator import re from dataclasses import dataclass -from typing import Any +from typing import Any, Callable logger = logging.getLogger(__name__) @@ -109,9 +109,13 @@ def from_dict(cls, data: dict[str, Any]) -> "SignalRecipe": ast.Eq: operator.eq, ast.NotEq: operator.ne, } -_UNARY_OPS = {ast.UAdd: operator.pos, ast.USub: operator.neg, ast.Not: operator.not_} +_UNARY_OPS: dict[type[ast.unaryop], Callable[[Any], Any]] = { + ast.UAdd: operator.pos, ast.USub: operator.neg, ast.Not: operator.not_, +} # The ONLY callables a recipe may invoke. All pure, total, side-effect free. -_FUNCS = {"abs": abs, "min": min, "max": max, "float": float, "int": int, "len": len} +_FUNCS: dict[str, Callable[..., Any]] = { + "abs": abs, "min": min, "max": max, "float": float, "int": int, "len": len, +} # AST node types the validator permits (anything else is rejected outright). _ALLOWED_NODES = ( diff --git a/evalrx/analysis/planner.py b/evalrx/analysis/planner.py index 58bc207e..d0b1630b 100644 --- a/evalrx/analysis/planner.py +++ b/evalrx/analysis/planner.py @@ -29,9 +29,6 @@ class AnalysisPlanItem: family: str = "confirmatory" priority: float = 0.0 - def as_legacy_tuple(self) -> tuple[str, dict[str, Any], str]: - return self.tool, self.config, self.rationale - def to_dict(self) -> dict[str, Any]: return { "tool": self.tool, diff --git a/evalrx/analysis/prompts/failure_modes.py b/evalrx/analysis/prompts/failure_modes.py index 00938719..edc906b8 100644 --- a/evalrx/analysis/prompts/failure_modes.py +++ b/evalrx/analysis/prompts/failure_modes.py @@ -13,10 +13,8 @@ {clusters_block} -Reply with EXACTLY ONE JSON array, one object per cluster listed above: -[{{"cluster_id": , "name": "", "description": ""}}, ...] - -Return ONLY the JSON array — no prose outside it.""" +Give one entry per cluster listed above: its cluster_id, a short snake_case +name, and a one-sentence description.""" ERROR_SIGNAL_PROMPT = """\ You are an ML failure-analysis expert. Below are (expected, observed) pairs @@ -27,7 +25,4 @@ {pairs_block} -Reply with EXACTLY ONE JSON array, one object per pair listed above: -[{{"index": , "error": ""}}, ...] - -Return ONLY the JSON array — no prose outside it.""" +Give one entry per pair listed above: its index and the short phrase.""" diff --git a/evalrx/analysis/prompts/holdout.py b/evalrx/analysis/prompts/holdout.py index 2b429983..55356630 100644 --- a/evalrx/analysis/prompts/holdout.py +++ b/evalrx/analysis/prompts/holdout.py @@ -20,8 +20,6 @@ - "not_testable": these observational statistics cannot decide the claim at all (e.g. causal direction); it needs an intervention/surgery experiment. -Reply with ONLY a JSON object: -{{"verdict": "supported|partial|refuted|not_testable", - "reasoning": "<2-3 sentences citing the held-out numbers>", - "needs_surgery": true/false}} +Give the verdict, 2-3 sentences of reasoning citing the held-out numbers, and +whether the claim needs an intervention (surgery) experiment. """ diff --git a/evalrx/analysis/prompts/hypothesis_agent.py b/evalrx/analysis/prompts/hypothesis_agent.py index 59fa8f8d..b8dcb190 100644 --- a/evalrx/analysis/prompts/hypothesis_agent.py +++ b/evalrx/analysis/prompts/hypothesis_agent.py @@ -28,7 +28,7 @@ measure stability, not capability; failure_mode is a judge-assigned label — itself a hypothesis to verify, never ground truth; total_*_tokens and *_latency_ms are cost. -- A TEST line may propose re-running the agent with a changed prompt, tool +- A test may propose re-running the agent with a changed prompt, tool description, or tool subset on held-out cases — interventions are directly testable here, not just observational splits.""" @@ -51,28 +51,16 @@ Candidate signals already noted: {signals_text} -Propose 1-3 hypotheses. For each write exactly four lines: -HYPOTHESIS: -PLAIN: -BASIS: -TEST: +Propose 1-3 hypotheses. For each give: +- hypothesis: one falsifiable sentence explaining a pattern above; precise + language and technical terms are fine here. +- plain_statement: the SAME claim in ONE everyday sentence a non-technical + reader understands at a glance: no acronyms (AUC, CI...), no statistics + jargon (collinear, logistic, coefficient, p-value, latent, mediator...), no + symbols. Numbers and percentages are fine and encouraged. +- basis: which takeaway(s) or signal(s) above it is grounded in. +- test: what evidence or analysis would confirm or refute it. -Do not repeat a takeaway verbatim — propose a CAUSE or MECHANISM behind what +Do not repeat a takeaway verbatim; propose a CAUSE or MECHANISM behind what was observed. If the findings are too thin to support any falsifiable -hypothesis, respond with exactly: NO_HYPOTHESIS""" - -PLAIN_REPAIR_PROMPT = """\ -Your previous answer below proposed hypotheses correctly, but some PLAIN -lines fail a plain-language check: PLAIN must be a jargon-free, one-sentence, -everyday paraphrase of the matching HYPOTHESIS line — no statistics terms, -acronyms, or symbols. Numbers/percentages are fine. - -Previous answer: -{raw} - -Problems found: -{violations} - -Rewrite the FULL set of hypotheses in the exact same -HYPOTHESIS/PLAIN/BASIS/TEST format, fixing only the flagged PLAIN lines. Do -not change the HYPOTHESIS, BASIS, or TEST lines.""" +hypothesis, give an empty list.""" diff --git a/evalrx/analysis/prompts/stats_agent.py b/evalrx/analysis/prompts/stats_agent.py index f1c6cc3a..f8861221 100644 --- a/evalrx/analysis/prompts/stats_agent.py +++ b/evalrx/analysis/prompts/stats_agent.py @@ -38,20 +38,19 @@ more often on" or "is linked with", never "causes" or "explains", unless an intervention actually tested it. -Based on the protocol and the findings above, write: +Based on the protocol and the findings above, give: -CONCLUSION: -EVIDENCE_CHAIN: -- -- -- -QUALITATIVE: -- -- +- conclusion: one paragraph. FIRST sentence: what is going wrong, in plain + words, no numbers. Then the evidence for it, with counts. Then what this + evidence does NOT settle. If the model looks healthy given the protocol, say + that plainly in the first sentence. +- evidence_chain: the steps, in order — + 1. which measurement first caught your attention (say what it measures in + words, not just its identifier) and why it stood out; + 2. how it connects to the protocol's stated failure patterns; + 3. any corroborating or contradicting signals from other analyzers. +- qualitative: patterns not captured by numbers alone, and anything unexpected + or surprising. Keep each bullet to one sentence.""" @@ -68,5 +67,4 @@ {data_shape} Pick the tools whose data requirements are satisfied and that best test the \ -protocol's question. Return ONLY a JSON object, no other text: -{{"tools": ["name1", "name2", ...], "rationale": "one sentence"}}""" +protocol's question, with a one-sentence rationale.""" diff --git a/evalrx/analysis/run_codebase.py b/evalrx/analysis/run_codebase.py index b71085a9..b9d01b42 100644 --- a/evalrx/analysis/run_codebase.py +++ b/evalrx/analysis/run_codebase.py @@ -229,9 +229,7 @@ def run_codebase_cli( ok = result.ran_ok and (result.explore is None or result.explore.ok) if ok: - from evalrx.reporting.html_report import build_html_report, open_in_browser + from evalrx.reporting.static_export import write_report - written = build_html_report(out_dir, out_path=out_dir / "report.html") - if open_report: - open_in_browser(written) + write_report(out_dir, open_report=open_report) return 0 if ok else 1 diff --git a/evalrx/analysis/stats_agent.py b/evalrx/analysis/stats_agent.py index de1b2725..9bbede38 100755 --- a/evalrx/analysis/stats_agent.py +++ b/evalrx/analysis/stats_agent.py @@ -43,20 +43,21 @@ import json import logging import os -import re from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Literal +from pydantic import BaseModel, Field, create_model + +from evalrx.agent_runtime.judge_call import JudgeError, ask_judge from evalrx.analysis.analysis_module import AnalysisModule, AnalysisReport +from evalrx.analysis.planner import AnalysisPlanItem, plan_stats_input from evalrx.analysis.prompts.stats_agent import _ANALYSIS_PROMPT, _TOOL_SELECT_PROMPT -from evalrx.analysis.stats_tool_agent import StatsToolAgent as LegacyStatsToolAgent from evalrx.analysis.stats_tools import ( STATS_TOOL_CATALOG, StatsInput, StatsToolResult, build_stats_input, build_stats_input_from_records, - default_plan, describe_data, fdr_correct, has_testable_data, @@ -71,7 +72,7 @@ StatsToolGenerator, ) from evalrx.core.case import CaseBatch - from evalrx.core.model import Model + from evalrx.core.model import Judge from evalrx.core.result import Result from evalrx.eval_agent.stages.protocol import ExperimentProtocol @@ -79,102 +80,38 @@ def _select_tools_via_llm( - judge: "Model", + judge: "Judge", protocol: "ExperimentProtocol", inp: StatsInput, valid_names: set[str], ) -> set[str]: - """Ask the judge to choose tool names from the catalog. Returns a name set. + """Ask the judge to choose tool names from the catalog. - Raises on any failure so the caller can fall back to the deterministic plan. + Only catalog names validate. Raises ``JudgeError`` when the judge gives + no valid choice, so the caller can fall back to the deterministic plan. """ - import inspect - catalog = "\n".join(f" - {name}: {desc}" for name, desc in STATS_TOOL_CATALOG.items()) prompt = _TOOL_SELECT_PROMPT.format( protocol_text=protocol.prompt_text(), tool_catalog=catalog, data_shape=json.dumps(describe_data(inp), indent=2), ) - sig = inspect.signature(judge.generate) - if "temperature" in sig.parameters: - raw = judge.generate(prompt, temperature=0) - else: - raw = judge.generate(prompt) - - cleaned = re.sub(r".*?", "", str(raw), flags=re.DOTALL).strip() - match = re.search(r"\{[^{}]*\}", cleaned) - if match: - data = json.loads(match.group()) - names = {n.lower() for n in data.get("tools", []) if n.lower() in valid_names} - if names: - return names - # soft fallback: scan for any known tool name - low = cleaned.lower() - return {n for n in valid_names if n in low} - - -#: A section label as an LLM actually writes it. The original matcher required -#: a literal "CONCLUSION:" at line start; a judge that wrote the markdown -#: heading "## CONCLUSION" entered no section at all, so a 4,158-character -#: analysis fell through to the base narrative's first line -#: ("Model: EndpointModel(qwen3.5-2b)") and M3 had nothing to hypothesise from — -#: the run then reported stopped_by=no_hypotheses as if that were a finding. -#: Earlier runs parsed only because the judge happened to use the colon form. -_SECTION_HEADER = re.compile( - r"^[#*\s]*(CONCLUSION|EVIDENCE_CHAIN|QUALITATIVE)\s*[::]?[*#\s]*(.*)$", - re.IGNORECASE, -) + tool_list: Any = list[Literal[tuple(sorted(valid_names))]] # type: ignore[misc] + choice = create_model( + "ToolChoice", + tools=(tool_list, Field(min_length=1)), + rationale=(str, ""), + ) + reply = ask_judge(judge, prompt, choice, role="stats_tool_selection") + return set(reply.output.tools) # type: ignore[attr-defined] -def _parse_llm_analysis( - raw: str, - base: AnalysisReport, -) -> tuple[str, list[str], list[str]]: - """Parse LLM output into (conclusion, evidence_chain, qualitative_findings). - - Returns "" for conclusion when the judge's response didn't contain a - parseable CONCLUSION: section (empty/error response, quota message, - wrong format, ...) -- NOT a synthesized fallback string. The only caller - (_analyze_llm_guided) already built a real, statistically-grounded - conclusion via _build_conclusion() before this parse ever runs and only - overwrites it `if conclusion:` — inventing a fallback here (this used to - return base.narrative's first line, which is just "Model: ") meant - a failed/malformed judge call silently threw away the good deterministic - conclusion and replaced it with a useless one, with no error anywhere. - Measured live: a judge call that hit its account's spend limit returned - the CLI's plain-text quota message as `raw`, which parses to nothing - here — before this fix, that overwrote a real "statistically supported: - signal X flips on FAIL, effect +0.83" conclusion with "Model: ", and M3 saw the latter. - """ - conclusion = "" - evidence: list[str] = [] - qualitative: list[str] = [] - section: str | None = None - - for line in raw.splitlines(): - s = line.strip() - upper = s.upper() - header = _SECTION_HEADER.match(s) - if header: - section = header.group(1).upper() - section = {"CONCLUSION": "conclusion", - "EVIDENCE_CHAIN": "evidence", - "QUALITATIVE": "qualitative"}[section] - rest = header.group(2).strip() - if section == "conclusion" and rest: - conclusion = rest - elif s.startswith("- "): - content = s[2:].strip() - if section == "evidence": - evidence.append(content) - elif section == "qualitative": - qualitative.append(content) - elif section == "conclusion" and s and not upper.startswith(("EVIDENCE", "QUALITATIVE")): - conclusion = (conclusion + " " + s).strip() - - return conclusion, evidence, qualitative +class _Analysis(BaseModel): + """The M2 judge's written analysis.""" + + conclusion: str = Field(min_length=1) + evidence_chain: list[str] = Field(default_factory=list) + qualitative: list[str] = Field(default_factory=list) # --------------------------------------------------------------------------- @@ -201,8 +138,6 @@ class StatsAnalysisReport(AnalysisReport): M1's ProbingSchema). corrected_rejections: e-BH FDR correction across all tool e-values. figures: Paths to generated figures (forest plot, …). - stats_tool_results: Backward-compatible JSON-safe stats summaries. - visualizations: Backward-compatible figure/spec list. protocol: The protocol that guided this analysis, if any. llm_fallback_reason: Why the LLM-guided path did not produce this report. Empty when it was never attempted (no @@ -218,8 +153,6 @@ class StatsAnalysisReport(AnalysisReport): stats_plan: list[dict[str, Any]] = field(default_factory=list) corrected_rejections: dict[str, Any] = field(default_factory=dict) figures: list[str] = field(default_factory=list) - stats_tool_results: list[dict[str, Any]] = field(default_factory=list) - visualizations: list[dict[str, Any]] = field(default_factory=list) protocol: "ExperimentProtocol | None" = None # When True the report carries effect sizes + charts but NO validity verdict: # e-BH FDR correction was NOT run (``corrected_rejections`` is deferred). The @@ -246,8 +179,6 @@ def to_dict(self) -> dict[str, Any]: "stats_plan": self.stats_plan, "corrected_rejections": self.corrected_rejections, "figures": self.figures, - "stats_tool_results": self.stats_tool_results, - "visualizations": self.visualizations, "descriptive_only": self.descriptive_only, }) return d @@ -271,9 +202,8 @@ class StatsAnalysisAgent: def __init__( self, - judge: "Model | None" = None, + judge: "Judge | None" = None, extra_rules: dict | None = None, - stats_tool_agent: Any | None = None, enable_stats_tools: bool = True, figure_dir: "str | None" = None, max_signal_tools: int | None = None, @@ -284,7 +214,6 @@ def __init__( ) -> None: self._base = AnalysisModule(extra_rules) self._judge = judge - self._stats_tool_agent = stats_tool_agent or LegacyStatsToolAgent() self._enable_stats_tools = enable_stats_tools self._figure_dir = figure_dir self._max_signal_tools = max_signal_tools @@ -325,7 +254,6 @@ def analyze( :class:`~evalrx.analysis.analysis_module.AnalysisReport`. """ base = self._base.analyze(results, model_name) - legacy_tool_results = self._run_legacy_stats_tools(results, protocol) inp = build_stats_input(results, data) return self._analyze_from_input( @@ -334,7 +262,6 @@ def analyze( protocol=protocol, results=results, extra_figures=extra_figures, - legacy_tool_results=legacy_tool_results, confirmatory=confirmatory, ) @@ -365,7 +292,6 @@ def analyze_input( protocol=protocol, results={}, extra_figures=extra_figures, - legacy_tool_results=[], ) def analyze_records( @@ -405,7 +331,6 @@ def _analyze_from_input( protocol: "ExperimentProtocol | None", results: "dict[str, Result]", extra_figures: "list | None", - legacy_tool_results: list[Any], confirmatory: bool = True, ) -> StatsAnalysisReport: """Shared implementation for loop-driven and standalone M2 analysis. @@ -431,28 +356,29 @@ def _analyze_from_input( report: "StatsAnalysisReport | None" = None fallback_reason = "" + fallback_raw = "" if self._judge is not None and protocol is not None: try: report = self._analyze_llm_guided( base, results, protocol, stats_results, stats_plan, corrected, figures, - legacy_tool_results, ) except Exception as exc: # A judge that never answered and a judge that found nothing # produce the SAME downstream run: threshold narrative, M3 with # nothing to hypothesise from, stopped_by=no_hypotheses, rc=0. # The reason has to travel with the report — a logger.warning - # here reached neither the console nor run_log.jsonl, so an + # here reached neither the console nor the run log, so an # OSError(E2BIG) on the prompt left no trace anywhere in the run. fallback_reason = f"{type(exc).__name__}: {exc}" + fallback_raw = exc.raw if isinstance(exc, JudgeError) else "" logger.warning("LLM-guided M2 analysis failed, falling back: %s", exc) if report is None: report = self._to_stats_report( base, protocol, stats_results, stats_plan, corrected, figures, - legacy_tool_results, ) report.llm_fallback_reason = fallback_reason + report.llm_raw = fallback_raw report.descriptive_only = not confirmatory return report @@ -460,20 +386,6 @@ def _analyze_from_input( # Statistical tool layer # ------------------------------------------------------------------ - def _run_stats_tools( - self, - results: "dict[str, Result]", - data: "CaseBatch | None", - protocol: "ExperimentProtocol | None", - ) -> tuple[list[StatsToolResult], list[dict[str, Any]], dict[str, Any], list[str]]: - """Build input, select and run tools, FDR-correct, and plot. - - Returns ``(stats_results, stats_plan, corrected, figures)``. All empty - when there is no labeled/grouped data to test (pure backward compat). - """ - inp = build_stats_input(results, data) - return self._run_stats_tools_input(inp, protocol) - def _run_stats_tools_input( self, inp: StatsInput, @@ -493,20 +405,21 @@ def _run_stats_tools_input( plan = self._select_plan(inp, protocol) stats_results: list[StatsToolResult] = [] - for tool, cfg, rationale in plan: + for item in plan: try: - r = run_stats_tool(tool, inp, cfg) + r = run_stats_tool(item.tool, inp, item.config) except Exception as exc: # never let one tool sink the analysis - logger.warning("stats tool %r failed: %s", tool, exc) + logger.warning("stats tool %r failed: %s", item.tool, exc) r = StatsToolResult( - tool=tool, config=cfg, ok=False, - error=str(exc), summary=f"{tool}: {exc}", + tool=item.tool, config=item.config, ok=False, + error=str(exc), summary=f"{item.tool}: {exc}", ) - r.details.setdefault("rationale", rationale) + r.details.setdefault("rationale", item.rationale) stats_results.append(r) stats_plan = [ - {"tool": t, "config": c, "rationale": rat} for t, c, rat in plan + {"tool": item.tool, "config": item.config, "rationale": item.rationale} + for item in plan ] # Tier (b)/(c): reuse previously generated tools, then generate a new one @@ -519,7 +432,8 @@ def _run_stats_tools_input( # (analysis-phase) mode; the confirm phase recomputes it. corrected = ( fdr_correct(stats_results) if confirmatory - else {"method": "e-BH", "deferred": True, "n_tested": 0, "rejected_tools": [], + else {"method": "e-BH", "deferred": True, "n_tested": 0, + "rejected_result_keys": [], "note": "validity deferred to the confirm phase (descriptive_only)"} ) @@ -533,20 +447,6 @@ def _run_stats_tools_input( return stats_results, stats_plan, corrected, figures - def _run_legacy_stats_tools( - self, - results: "dict[str, Result]", - protocol: "ExperimentProtocol | None", - ) -> list[Any]: - """Run the older lightweight M2 tools for backward-compatible reports.""" - if not self._enable_stats_tools or self._stats_tool_agent is None: - return [] - try: - return list(self._stats_tool_agent.analyze(results, protocol=protocol)) - except Exception as exc: - logger.warning("legacy M2 stats-tool analysis failed: %s", exc) - return [] - def _run_generated_tools( self, inp: StatsInput, @@ -585,12 +485,12 @@ def _run_generated_tools( "whether the analyzer signals predict case FAIL." ) name = f"custom{len(self._generated_tools) + 1}" - result, tool = generator.generate(need, inp, name=name) + result, new_tool = generator.generate(need, inp, name=name) results.append(result) plan.append({"tool": f"generated:{name}", "config": {}, "rationale": "generated: no catalog tool fit the data"}) - if tool is not None: - self._generated_tools.append(tool) + if new_tool is not None: + self._generated_tools.append(new_tool) return results, plan def _get_generator(self) -> "StatsToolGenerator | None": @@ -617,14 +517,14 @@ def _select_plan( self, inp: StatsInput, protocol: "ExperimentProtocol | None", - ) -> list[tuple[str, dict, str]]: + ) -> list[AnalysisPlanItem]: """Select tools: LLM picks from the catalog, deterministic plan otherwise. The deterministic plan is always the backbone (it guarantees coverage); when a judge + protocol are present, the LLM *narrows* it to the chosen tools. Any failure or empty selection falls back to the full plan. """ - plan = default_plan(inp, max_signals=self._max_signal_tools) + plan = plan_stats_input(inp, max_signals=self._max_signal_tools) if self._judge is None or protocol is None or not plan: return plan try: @@ -640,7 +540,7 @@ def _select_plan( # the plan when their inputs exist — they carry causal / tensor-level # verdicts and must never be silently dropped by name-based narrowing. _mandatory = {"mcnemar_evalue", "friedman_nemenyi", "attention_decoding"} - filtered = [p for p in plan if p[0] in chosen or p[0] in _mandatory] + filtered = [item for item in plan if item.tool in chosen or item.tool in _mandatory] return filtered or plan # ------------------------------------------------------------------ @@ -655,14 +555,12 @@ def _to_stats_report( stats_plan: list[dict[str, Any]] | None = None, corrected: dict[str, Any] | None = None, figures: list[str] | None = None, - legacy_tool_results: list[Any] | None = None, ) -> StatsAnalysisReport: """Basic path: wrap AnalysisReport + stats-tool results into a report.""" stats_results = stats_results or [] stats_plan = stats_plan or [] corrected = corrected or {} figures = figures or [] - legacy_tool_results = legacy_tool_results or [] chain: list[str] = [] if base.findings: @@ -689,9 +587,10 @@ def _to_stats_report( chain.append(f"[stats:{r.tool}] {r.summary}") else: chain.append(f"[stats:{r.tool}] N/A ({r.error})") - if corrected.get("rejected_tools"): + if corrected.get("rejected_result_keys"): chain.append( - f"FDR (e-BH) survivors: {', '.join(corrected['rejected_tools'])}" + f"FDR ({corrected.get('method') or 'e-BH'}) survivors: " + f"{', '.join(corrected['rejected_result_keys'])}" ) qualitative = [str(f) for f in base.findings] @@ -719,14 +618,6 @@ def _to_stats_report( stats_plan=stats_plan, corrected_rejections=corrected, figures=figures, - stats_tool_results=( - _serialize_legacy_tool_results(legacy_tool_results) - or _compat_stats_tool_results(stats_results) - ), - visualizations=( - _legacy_visualizations(legacy_tool_results) - or [{"type": "figure", "path": p} for p in figures] - ), protocol=protocol, ) @@ -739,7 +630,6 @@ def _analyze_llm_guided( stats_plan: list[dict[str, Any]], corrected: dict[str, Any], figures: list[str], - legacy_tool_results: list[Any], ) -> StatsAnalysisReport: """LLM-guided path: judge synthesises protocol-specific insights. @@ -758,29 +648,26 @@ def _analyze_llm_guided( narrative=base.narrative + stats_block, findings_json=findings_json, ) - import inspect as _inspect from pathlib import Path as _Path - _sig = _inspect.signature(self._judge.generate) # type: ignore[union-attr] - if "images" in _sig.parameters and figures: - _imgs = [_Path(f) for f in figures if _Path(f).exists()] - raw = self._judge.generate(prompt, images=_imgs or None) # type: ignore[union-attr] - else: - raw = self._judge.generate(prompt) # type: ignore[union-attr] - conclusion, evidence, qualitative = _parse_llm_analysis(str(raw), base) + # A judge with no valid answer raises JudgeError; the caller keeps the + # deterministic report and records why in llm_fallback_reason. + reply = ask_judge( + self._judge, prompt, _Analysis, role="stats_analysis", + images=[_Path(f) for f in figures if _Path(f).exists()], + ) + analysis = reply.output report = self._to_stats_report( base, protocol, stats_results, stats_plan, corrected, figures, - legacy_tool_results, ) - if conclusion: - report.conclusion = conclusion - if evidence: - report.evidence_chain = evidence - if qualitative: - report.qualitative_findings = qualitative + report.conclusion = analysis.conclusion + if analysis.evidence_chain: + report.evidence_chain = analysis.evidence_chain + if analysis.qualitative: + report.qualitative_findings = analysis.qualitative report.stats_tool = "llm_guided" report.llm_prompt = prompt - report.llm_raw = str(raw) + report.llm_raw = reply.raw return report @@ -843,39 +730,6 @@ def _build_input_narrative(model_name: str, inp: StatsInput) -> str: return "\n".join(lines) -def _compat_stats_tool_results(stats_results: list[StatsToolResult]) -> list[dict[str, Any]]: - """Return the legacy JSON shape used by older logs/examples.""" - out: list[dict[str, Any]] = [] - for result in stats_results: - payload = result.to_dict() - payload["name"] = result.tool - payload["conclusion"] = result.summary or result.error or "" - payload["visualizations"] = ( - [{"type": "figure", "path": result.figure_path}] - if result.figure_path - else [] - ) - out.append(payload) - return out - - -def _serialize_legacy_tool_results(tool_results: list[Any]) -> list[dict[str, Any]]: - payloads: list[dict[str, Any]] = [] - for result in tool_results: - if hasattr(result, "to_dict"): - payloads.append(result.to_dict()) - elif isinstance(result, dict): - payloads.append(dict(result)) - return payloads - - -def _legacy_visualizations(tool_results: list[Any]) -> list[dict[str, Any]]: - visualizations: list[dict[str, Any]] = [] - for result in tool_results: - visualizations.extend(getattr(result, "visualizations", []) or []) - return visualizations - - def _multiplicity_note(result: StatsToolResult) -> str: """Per-result multiplicity verdict, or "" for a result outside every family. @@ -911,13 +765,13 @@ def _format_stats_for_prompt( bbh_word_sorting, 23 of 42 ``signal_label_assoc`` results printed REJECT H0 while BH kept 13; of the other ten, one rested on a single case at permutation p = 1.000. - * The footer used to list ``rejected_tools`` — a set of TOOL NAMES. Every - per-signal test shares the name ``signal_label_assoc``, so a 42-signal - family collapsed to the single word "signal_label_assoc" and no reader - could tell WHICH signals survived. The judge on that run reconciled the - mismatch the only way left to it, concluding the tool had not run at all, - and discarded the entire family. ``rejected_result_keys`` was already in - the same dict, at per-signal granularity. + * The footer lists ``rejected_result_keys``, one per surviving test, not + the surviving TOOL NAMES. Every per-signal test shares the name + ``signal_label_assoc``, so a 42-signal family named by tool collapses to + the single word "signal_label_assoc" and no reader can tell WHICH signals + survived. The judge on that run reconciled the mismatch the only way + left to it, concluding the tool had not run at all, and discarded the + entire family. ``reject`` itself is deliberately not touched here: for the BH family it keeps the tool's raw CI verdict for the M1-M4 loop (see diff --git a/evalrx/analysis/stats_tool_agent.py b/evalrx/analysis/stats_tool_agent.py deleted file mode 100755 index 6ec0511d..00000000 --- a/evalrx/analysis/stats_tool_agent.py +++ /dev/null @@ -1,261 +0,0 @@ -"""Stats-tool selection and execution for M2 exploratory analysis. - -The goal is to make M2 more than a narrative wrapper around threshold rules: -given raw analyzer results, this module selects small, reproducible analysis -tools and returns quantitative tables plus visualization specs. The specs are -JSON-safe so they can be logged, rendered later, or handed to an LLM without -shipping heavy arrays. -""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from statistics import mean -from typing import TYPE_CHECKING, Any - -from evalrx.core.case import CaseBatch, Label - -if TYPE_CHECKING: - from evalrx.core.result import Result - from evalrx.eval_agent.stages.protocol import ExperimentProtocol - - -@dataclass -class StatsToolResult: - """Output from one selected stats tool.""" - - name: str - rationale: str - metrics: dict[str, Any] = field(default_factory=dict) - tables: dict[str, list[dict[str, Any]]] = field(default_factory=dict) - visualizations: list[dict[str, Any]] = field(default_factory=list) - conclusion: str = "" - - def to_dict(self) -> dict[str, Any]: - return { - "name": self.name, - "rationale": self.rationale, - "metrics": self.metrics, - "tables": self.tables, - "visualizations": self.visualizations, - "conclusion": self.conclusion, - } - - -class StatsToolAgent: - """Select and run built-in exploratory stats tools. - - This is the deterministic baseline for the future self-extending path where - an agent can generate new stats code. It intentionally keeps tool outputs - compact and JSON-serializable. - """ - - def __init__(self, max_tools: int = 3) -> None: - self.max_tools = max_tools - - def analyze( - self, - results: dict[str, "Result"], - *, - protocol: "ExperimentProtocol | None" = None, - ) -> list[StatsToolResult]: - selected = self.select(results, protocol=protocol) - outputs: list[StatsToolResult] = [] - for name in selected: - if name == "scalar_summary": - out = _scalar_summary(results) - elif name == "per_case_signal_label_association": - out = _per_case_signal_label_association(results) - else: - continue - if out is not None: - outputs.append(out) - return outputs - - def select( - self, - results: dict[str, "Result"], - *, - protocol: "ExperimentProtocol | None" = None, - ) -> list[str]: - names: list[str] = [] - if _has_numeric_scalars(results): - names.append("scalar_summary") - if _has_per_case_entries(results): - names.append("per_case_signal_label_association") - return names[: self.max_tools] - - -def _has_numeric_scalars(results: dict[str, "Result"]) -> bool: - for result in results.values(): - for key, value in result.findings.items(): - if key == "per_case": - continue - if isinstance(value, (int, float, bool)): - return True - return False - - -def _has_per_case_entries(results: dict[str, "Result"]) -> bool: - return any( - isinstance(result.findings.get("per_case"), list) - and len(result.findings.get("per_case", [])) > 0 - for result in results.values() - ) - - -def _scalar_summary(results: dict[str, "Result"]) -> StatsToolResult | None: - rows: list[dict[str, Any]] = [] - values: list[float] = [] - - for analyzer_name, result in sorted(results.items()): - for metric, raw in sorted(result.findings.items()): - if metric == "per_case" or not isinstance(raw, (int, float, bool)): - continue - value = float(raw) - values.append(value) - rows.append({ - "analyzer": analyzer_name, - "metric": metric, - "value": round(value, 6), - }) - - if not rows: - return None - - chart = { - "kind": "bar", - "title": "Analyzer scalar metrics", - "x": [f"{r['analyzer']}.{r['metric']}" for r in rows], - "y": [r["value"] for r in rows], - "y_label": "value", - } - - return StatsToolResult( - name="scalar_summary", - rationale="Summarize numeric analyzer findings before hypothesis generation.", - metrics={ - "n_scalar_metrics": len(rows), - "min": round(min(values), 6), - "max": round(max(values), 6), - "mean": round(mean(values), 6), - }, - tables={"scalar_metrics": rows}, - visualizations=[chart], - conclusion=f"Collected {len(rows)} numeric metric(s) across analyzer outputs.", - ) - - -def _per_case_signal_label_association( - results: dict[str, "Result"], -) -> StatsToolResult | None: - cases = _find_cases(results) - signal = _extract_signals(results) - if not signal: - return None - - labeled: dict[str, bool] = {} - if cases is not None: - for case in cases: - if getattr(case, "label", None) in {Label.PASS, Label.FAIL}: - labeled[case.id] = case.label == Label.FAIL - signal.setdefault(case.id, False) - - rows: list[dict[str, Any]] = [] - for cid, has_signal in sorted(signal.items()): - row: dict[str, Any] = { - "case_id": cid, - "has_signal": bool(has_signal), - } - if cid in labeled: - row["label"] = "fail" if labeled[cid] else "pass" - rows.append(row) - - n_signal = sum(1 for hit in signal.values() if hit) - n_no_signal = len(signal) - n_signal - metrics: dict[str, Any] = { - "n_cases_with_signal_entries": len(signal), - "n_signal": n_signal, - "n_no_signal": n_no_signal, - } - - labeled_rows = [r for r in rows if "label" in r] - if labeled_rows: - signal_labels = [r["label"] == "fail" for r in labeled_rows if r["has_signal"]] - control_labels = [r["label"] == "fail" for r in labeled_rows if not r["has_signal"]] - if signal_labels: - metrics["fail_rate_signal"] = round(sum(signal_labels) / len(signal_labels), 6) - if control_labels: - metrics["fail_rate_control"] = round(sum(control_labels) / len(control_labels), 6) - if signal_labels and control_labels: - metrics["effect_size"] = round( - metrics["fail_rate_signal"] - metrics["fail_rate_control"], 6 - ) - - chart = { - "kind": "bar", - "title": "Per-case diagnostic signal split", - "x": ["signal", "no_signal"], - "y": [n_signal, n_no_signal], - "y_label": "case count", - } - if "fail_rate_signal" in metrics or "fail_rate_control" in metrics: - chart_rates = { - "kind": "bar", - "title": "Fail rate by diagnostic signal", - "x": ["signal", "no_signal"], - "y": [ - metrics.get("fail_rate_signal", 0.0), - metrics.get("fail_rate_control", 0.0), - ], - "y_label": "fail rate", - } - visualizations = [chart, chart_rates] - else: - visualizations = [chart] - - conclusion = ( - "Computed per-case diagnostic signal coverage." - if "effect_size" not in metrics - else f"Signal fail-rate gap is {metrics['effect_size']:.3f}." - ) - - return StatsToolResult( - name="per_case_signal_label_association", - rationale="Check whether analyzer per-case signals align with PASS/FAIL outcomes.", - metrics=metrics, - tables={"per_case_signal": rows}, - visualizations=visualizations, - conclusion=conclusion, - ) - - -def _find_cases(results: dict[str, "Result"]) -> CaseBatch | None: - for result in results.values(): - cases = getattr(result, "cases", None) - if cases is not None and len(cases) > 0: - return cases - return None - - -def _extract_signals(results: dict[str, "Result"]) -> dict[str, bool]: - signal: dict[str, bool] = {} - non_signal_keys = {"sample_id", "id", "step", "first_error_step", "action", "judge_raw"} - - for result in results.values(): - per_case = result.findings.get("per_case", []) - if not isinstance(per_case, list): - continue - for entry in per_case: - if not isinstance(entry, dict): - continue - cid = str(entry.get("sample_id") or entry.get("id") or "") - if not cid: - continue - hit = any( - isinstance(v, (int, float, bool)) and bool(v) - for k, v in entry.items() - if k not in non_signal_keys - ) - signal[cid] = signal.get(cid, False) or hit - return signal diff --git a/evalrx/analysis/stats_tool_generator.py b/evalrx/analysis/stats_tool_generator.py index 0dddfa64..bfd8fa72 100755 --- a/evalrx/analysis/stats_tool_generator.py +++ b/evalrx/analysis/stats_tool_generator.py @@ -47,7 +47,7 @@ if TYPE_CHECKING: from evalrx.agent_runtime.cli_types import CliAgentConfig - from evalrx.core.model import Model + from evalrx.core.model import Judge logger = logging.getLogger(__name__) @@ -91,7 +91,7 @@ class StatsToolGenerator: def __init__( self, - judge: "Model | None" = None, + judge: "Judge | None" = None, cli_config: "CliAgentConfig | None" = None, sandbox: "ExperimentSandbox | None" = None, timeout_sec: int = 60, @@ -373,7 +373,8 @@ def _parse_result(stdout: str, name: str, alpha: float = 0.05) -> StatsToolResul ci = data.get("ci") ci_tuple = tuple(ci) if isinstance(ci, (list, tuple)) and len(ci) == 2 else None effect = _as_float(data.get("effect")) - details = data.get("details") if isinstance(data.get("details"), dict) else {} + raw_details = data.get("details") + details = raw_details if isinstance(raw_details, dict) else {} # HOST reconstructs the decision; the script's own reject/e_value/p_value are # never trusted as a verdict (closes the codegen p-hacking hole). diff --git a/evalrx/analysis/stats_tools.py b/evalrx/analysis/stats_tools.py index f43dec25..e78b4b73 100755 --- a/evalrx/analysis/stats_tools.py +++ b/evalrx/analysis/stats_tools.py @@ -13,7 +13,8 @@ ``CaseBatch`` into a single :class:`StatsInput` (per-case signals, labels, scalar metrics, optional strategy groups). 2. The agent picks tool names from :data:`STATS_TOOL_CATALOG` (LLM-guided) or - falls back to :func:`default_plan` (deterministic). + falls back to :func:`~evalrx.analysis.planner.plan_stats_input` + (deterministic). 3. Each ``(tool, config)`` runs via :func:`run_stats_tool`, returning a uniform :class:`StatsToolResult` (effect, CI, e-value, reject, underpowered). 4. :func:`fdr_correct` applies e-BH across all tools that produced an e-value so @@ -1084,25 +1085,6 @@ def run_stats_tool(name: str, inp: StatsInput, config: dict | None = None) -> St return tool(inp, config or {}) -# --------------------------------------------------------------------------- -# Deterministic planner (fallback when no judge / LLM selection fails) -# --------------------------------------------------------------------------- - -def default_plan( - inp: StatsInput, - max_signals: int | None = None, -) -> list[tuple[str, dict, str]]: - """Deterministic ``[(tool, config, rationale)]`` plan from the data shape. - - The implementation delegates to the generic M2 planner so per-case signals - are ranked by testability instead of original column order. ``max_signals`` - remains for backward compatibility; ``None`` means test every ranked signal. - """ - from evalrx.analysis.planner import plan_stats_input - - return [item.as_legacy_tuple() for item in plan_stats_input(inp, max_signals=max_signals)] - - # --------------------------------------------------------------------------- # Multiple-testing correction + visualization # --------------------------------------------------------------------------- @@ -1110,9 +1092,8 @@ def default_plan( def fdr_correct(results: list[StatsToolResult], alpha: float = 0.05) -> dict[str, Any]: """Apply multiplicity correction across all supported result families. - e-values use e-BH; p-values use BH. The returned ``rejected_tools`` field is - preserved for existing M1-M4 consumers, while ``rejected_result_keys`` and - ``families`` expose the precise generalized-M2 family membership. + e-values use e-BH; p-values use BH. ``rejected_result_keys`` names each + surviving result and ``families`` the family it was corrected in. """ return correct_results(results, alpha=alpha) diff --git a/evalrx/analysis/trajectory_records.py b/evalrx/analysis/trajectory_records.py index d37b40a8..7c53accd 100644 --- a/evalrx/analysis/trajectory_records.py +++ b/evalrx/analysis/trajectory_records.py @@ -164,6 +164,7 @@ def trajectories_to_records( """ rows: list[dict[str, Any]] = [] tool_cols: set[str] = set() + trajectory: Trajectory | None for item in items: if isinstance(item, Trajectory): case, trajectory = None, item diff --git a/evalrx/analysis/workbench.py b/evalrx/analysis/workbench.py index bd042551..27a2b72b 100644 --- a/evalrx/analysis/workbench.py +++ b/evalrx/analysis/workbench.py @@ -331,7 +331,7 @@ def _media_units(path: Path, source: Path, entry: dict[str, Any], remaining: int duration = unit.get("duration_sec") if isinstance(duration, (float, int)) and duration > 0 and remaining > 1: segment_sec = 30.0 if suffix in AUDIO_SUFFIXES else 10.0 - children = [] + children: list[dict[str, Any]] = [] start = 0.0 while start < float(duration) and len(children) < remaining - 1: end = min(start + segment_sec, float(duration)) diff --git a/evalrx/analyzers/_internals/access.py b/evalrx/analyzers/_internals/access.py index 40b237a6..5e51f9b9 100644 --- a/evalrx/analyzers/_internals/access.py +++ b/evalrx/analyzers/_internals/access.py @@ -9,7 +9,7 @@ from __future__ import annotations import sys -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any if TYPE_CHECKING: @@ -101,10 +101,10 @@ class DecoderStack: path: str # dotted path of ``layers`` inside the module attn: list # per layer: softmax attention submodule or None parent: Any # module owning ``layers`` (the text model) - linear: list = None # per layer: delta-rule linear-attention mixer or None + linear: list = field(default_factory=list) # per layer: delta-rule mixer or None def __post_init__(self) -> None: - if self.linear is None: + if not self.linear: self.linear = [None] * len(self.attn) @property diff --git a/evalrx/analyzers/_internals/attn_tap.py b/evalrx/analyzers/_internals/attn_tap.py index 1320fdc7..dbab76f6 100644 --- a/evalrx/analyzers/_internals/attn_tap.py +++ b/evalrx/analyzers/_internals/attn_tap.py @@ -40,7 +40,7 @@ import math from contextlib import contextmanager from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, Callable, Iterable, Iterator, Optional +from typing import TYPE_CHECKING, Any, Callable, Iterable, Iterator, Optional, cast from evalrx.analyzers._internals.access import decoder_stack, torch_module @@ -236,13 +236,14 @@ def _tap_attention(module: Any, query: Any, key: Any, value: Any, attention_mask layer = state.layer_of.get(id(module)) if state is not None else None if layer is not None: - state.calls.append(layer) - scores = state.edit_scores(layer, scores) + tap = cast(TapState, state) # layer is only resolved from a live state + tap.calls.append(layer) + scores = tap.edit_scores(layer, scores) probs = nn.functional.softmax(scores, dim=-1, dtype=torch.float32).to(query.dtype) if layer is not None: - probs = state.edit_probs(layer, probs) - if state.on_probs is not None: - state.on_probs(layer, probs) + probs = tap.edit_probs(layer, probs) + if tap.on_probs is not None: + tap.on_probs(layer, probs) probs = nn.functional.dropout(probs, p=dropout, training=module.training) out = torch.matmul(probs, value).transpose(1, 2).contiguous() return out, probs diff --git a/evalrx/analyzers/_internals/maps.py b/evalrx/analyzers/_internals/maps.py index 1bd4bee1..dddacd66 100644 --- a/evalrx/analyzers/_internals/maps.py +++ b/evalrx/analyzers/_internals/maps.py @@ -8,7 +8,7 @@ * ``artifacts["spatial_map"]`` (first case), ``per_case_maps`` (float16 per case), ``fail_mean_map`` / ``pass_mean_map`` / ``diff_map_fail_minus_pass``; * ``findings["_case_id"]`` naming the case whose image each map overlays; -* :class:`SpatialMapResult.image_overlays` — the duck-typed hook RunLoggerV2 +* :class:`SpatialMapResult.image_overlays` — the duck-typed hook RunLogger calls to save heatmap-on-photo PNGs. numpy and the overlay helpers are imported inside functions: this module is @@ -126,7 +126,7 @@ def overlay(self, key: str = "spatial_map", *, alpha: float = 0.6, cmap: str = " return None def image_overlays(self, fig_dir: Any, stem_prefix: str) -> "list[Any]": - """Save every available overlay under ``fig_dir`` (RunLoggerV2 hook).""" + """Save every available overlay under ``fig_dir`` (RunLogger hook).""" from pathlib import Path out = [] diff --git a/evalrx/analyzers/agent/counterfactual.py b/evalrx/analyzers/agent/counterfactual.py index 8f339402..2f29c51e 100755 --- a/evalrx/analyzers/agent/counterfactual.py +++ b/evalrx/analyzers/agent/counterfactual.py @@ -20,7 +20,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Callable +from typing import TYPE_CHECKING, Any, Callable, cast from evalrx.core.analyzer import Analyzer from evalrx.core.capability import Capability @@ -44,6 +44,8 @@ class CounterfactualReplay(Analyzer): requires_trajectories = True applies_to_modalities = frozenset({"text", "image"}) # trajectory analysis is modality-agnostic + n_replays: int + def __init__(self, rerun_fn: Callable, n_replays: int = 3) -> None: super().__init__(rerun_fn=rerun_fn, n_replays=n_replays) self.rerun_fn = rerun_fn @@ -56,7 +58,7 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: continue original_success = traj.outcome == Label.PASS candidates = [s for s in traj.steps if s.tool_call] - step_scores = [] + step_scores: list[dict[str, Any]] = [] for s in candidates: flips = sum( 1 for seed in range(self.n_replays) @@ -64,7 +66,7 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: ) step_scores.append({ "step": s.idx, - "action": s.tool_call.get("name"), + "action": cast(dict, s.tool_call).get("name"), # candidates keep only steps with a tool_call "flip_rate": round(flips / self.n_replays, 4) if self.n_replays else 0.0, }) step_scores.sort(key=lambda d: -d["flip_rate"]) diff --git a/evalrx/analyzers/agent/first_error_judge.py b/evalrx/analyzers/agent/first_error_judge.py index 0c4acad1..4cbb213b 100755 --- a/evalrx/analyzers/agent/first_error_judge.py +++ b/evalrx/analyzers/agent/first_error_judge.py @@ -27,7 +27,7 @@ if TYPE_CHECKING: from evalrx.core.case import CaseBatch, Trajectory - from evalrx.core.model import Model + from evalrx.core.model import Judge, Model _PROMPT = """You are debugging an AI agent trajectory. The agent failed to achieve the goal. Goal: {goal} @@ -65,7 +65,9 @@ class FirstErrorJudge(Analyzer): requires_trajectories = True applies_to_modalities = frozenset({"text", "image"}) # trajectory analysis is modality-agnostic - def __init__(self, judge: Optional["Model"] = None) -> None: + judge: Optional['Model'] + + def __init__(self, judge: Optional["Judge"] = None) -> None: super().__init__(judge=judge) def _run(self, model: "Model", cases: "CaseBatch") -> Result: diff --git a/evalrx/analyzers/agent/ignored_obs.py b/evalrx/analyzers/agent/ignored_obs.py index 1c6d598d..cb814674 100755 --- a/evalrx/analyzers/agent/ignored_obs.py +++ b/evalrx/analyzers/agent/ignored_obs.py @@ -38,6 +38,8 @@ class IgnoredObservationDetector(Analyzer): DEFAULT_MARKERS = ("error", "not found", "failed", "no result", "none", "invalid", "empty", "exception") + markers: tuple[str, ...] + def __init__(self, markers: tuple[str, ...] | None = None) -> None: super().__init__(markers=markers or self.DEFAULT_MARKERS) diff --git a/evalrx/analyzers/agent/loop_detect.py b/evalrx/analyzers/agent/loop_detect.py index 24b9c3cf..7ed9d8e7 100755 --- a/evalrx/analyzers/agent/loop_detect.py +++ b/evalrx/analyzers/agent/loop_detect.py @@ -44,6 +44,8 @@ class LoopDetector(Analyzer): requires_trajectories = True applies_to_modalities = frozenset({"text", "image"}) # trajectory analysis is modality-agnostic + min_repeats: int + def __init__(self, min_repeats: int = 2) -> None: super().__init__(min_repeats=min_repeats) diff --git a/evalrx/analyzers/agent/reliability.py b/evalrx/analyzers/agent/reliability.py index fafa28c0..b95dc7af 100644 --- a/evalrx/analyzers/agent/reliability.py +++ b/evalrx/analyzers/agent/reliability.py @@ -82,6 +82,9 @@ class ReliabilityProbe(Analyzer): requires = frozenset() # the injected runner encapsulates the model applies_to_modalities = frozenset({"text", "image"}) + k: int + max_cases: Optional[int] + def __init__( self, runs_fn: Callable[["FailureCase", int], "list[Trajectory]"], diff --git a/evalrx/analyzers/agent/tool_shap.py b/evalrx/analyzers/agent/tool_shap.py index 40df9bb6..1cd710e0 100644 --- a/evalrx/analyzers/agent/tool_shap.py +++ b/evalrx/analyzers/agent/tool_shap.py @@ -111,6 +111,11 @@ class ToolShap(Analyzer): requires_trajectories = True applies_to_modalities = frozenset({"text", "image"}) + tool_names: list[str] + max_combinations: Optional[int] + max_cases: Optional[int] + seed: int + def __init__( self, run_with_tools: Callable[["FailureCase", tuple], "Trajectory"], diff --git a/evalrx/analyzers/agent/trajectory_rubric.py b/evalrx/analyzers/agent/trajectory_rubric.py index 799cf7c6..b087b99a 100644 --- a/evalrx/analyzers/agent/trajectory_rubric.py +++ b/evalrx/analyzers/agent/trajectory_rubric.py @@ -98,6 +98,9 @@ class TrajectoryRubricJudge(Analyzer): requires_trajectories = True applies_to_modalities = frozenset({"text", "image"}) + max_cases: Optional[int] + annotate: bool + def __init__(self, judge: Any, max_cases: Optional[int] = None, annotate: bool = True) -> None: super().__init__(max_cases=max_cases, annotate=annotate) if judge is None or not hasattr(judge, "generate"): diff --git a/evalrx/analyzers/attention/relative_attn.py b/evalrx/analyzers/attention/relative_attn.py index bb8111ba..eff91c81 100755 --- a/evalrx/analyzers/attention/relative_attn.py +++ b/evalrx/analyzers/attention/relative_attn.py @@ -64,7 +64,8 @@ def _blend_heatmap_on_image( def _upsample(mat: np.ndarray) -> np.ndarray: img = Image.fromarray((np.clip(mat, 0.0, 1.0) * 255).astype(np.uint8), mode="L") - return np.asarray(img.resize(base.size, Image.BILINEAR), dtype=np.float64) / 255.0 + # Pillow sets the module-level filter aliases dynamically, so its type hints miss them + return np.asarray(img.resize(base.size, Image.BILINEAR), dtype=np.float64) / 255.0 # type: ignore[attr-defined] norm_up = _upsample(norm) intensity_up = _upsample(intensity) @@ -138,7 +139,7 @@ def image_token_attention(attn_layer, mask): def attention_heatmap( - model: "Model", case: "FailureCase", layer: "int | float" = 0.75 + model: "Model | None", case: "FailureCase", layer: "int | float" = 0.75 ) -> "np.ndarray | None": """One ATTENTION forward → (H, W) image-patch heatmap, or ``None``. @@ -152,7 +153,7 @@ def attention_heatmap( """ from evalrx.core.capability import Capability - if Capability.ATTENTION not in getattr(model, "capabilities", frozenset()): + if model is None or Capability.ATTENTION not in getattr(model, "capabilities", frozenset()): return None try: trace = model.forward(case.inputs, capture={Capability.ATTENTION}) @@ -260,7 +261,7 @@ def save_overlay(self, key: str, path: "Any", **kwargs) -> bool: def image_overlays(self, fig_dir: "Any", stem_prefix: str) -> "list[Any]": """Save every available overlay under ``fig_dir``; return the paths. - Hook called by :class:`~evalrx.eval_agent.run_logger_v2.RunLoggerV2` + Hook called by :class:`~evalrx.eval_agent.run_logger.RunLogger` (duck-typed — any :class:`Result` subclass may define this) so the overlay PNGs land alongside the bare heatmaps and get forwarded to a multimodal judge the same way. @@ -358,6 +359,11 @@ class RelativeAttentionAnalyzer(Analyzer): # batch matches on "image" and would map attention over nothing. requires_modalities = frozenset({"image", "video"}) + general_prompt: str + layer: 'int | float' + top_k: int + max_cases: int + def __init__( self, general_prompt: str = "Describe the image.", diff --git a/evalrx/analyzers/attention/rollout.py b/evalrx/analyzers/attention/rollout.py index 790cd8dc..1a8bd442 100755 --- a/evalrx/analyzers/attention/rollout.py +++ b/evalrx/analyzers/attention/rollout.py @@ -45,6 +45,8 @@ class AttentionRolloutAnalyzer(Analyzer): requires = frozenset({Capability.ATTENTION}) applies_to_modalities = frozenset({"text", "image"}) + top_k: int + def __init__(self, top_k: int = 5) -> None: super().__init__(top_k=top_k) diff --git a/evalrx/analyzers/attention/sink.py b/evalrx/analyzers/attention/sink.py index 916d2e62..b5cbb98c 100755 --- a/evalrx/analyzers/attention/sink.py +++ b/evalrx/analyzers/attention/sink.py @@ -47,6 +47,9 @@ class AttentionSinkAnalyzer(Analyzer): "sink_peak_layer_frac": ("Strongest-sink depth", "Relative depth (0 = first layer, 1 = last) of the layer with the most attention on the sink."), } + sink_pos: int + max_cases: int + def __init__(self, sink_pos: int = 0, max_cases: int = 0) -> None: super().__init__(sink_pos=sink_pos, max_cases=max_cases) diff --git a/evalrx/analyzers/attention/summary.py b/evalrx/analyzers/attention/summary.py index ed7fb283..2ba637f9 100755 --- a/evalrx/analyzers/attention/summary.py +++ b/evalrx/analyzers/attention/summary.py @@ -157,6 +157,11 @@ class AttentionAnalyzer(Analyzer): "media_mass_mid": ("Attention on image/audio", "Share of the final prompt position's attention that lands on image/audio tokens, averaged over heads and the middle half of the layers; low = the answer position barely reads the media."), } + layer: int + head: int | str + top_k: int + max_cases: int + def __init__(self, layer: int = -1, head: int | str = "mean", top_k: int = 10, max_cases: int = 0) -> None: super().__init__(layer=layer, head=head, top_k=top_k, max_cases=max_cases) diff --git a/evalrx/analyzers/attribution/generic_attn.py b/evalrx/analyzers/attribution/generic_attn.py index 18dc69cd..dea6e168 100755 --- a/evalrx/analyzers/attribution/generic_attn.py +++ b/evalrx/analyzers/attribution/generic_attn.py @@ -82,6 +82,11 @@ class GenericAttentionExplainability(Analyzer): "rel_edge_mass": ("Image relevance on border", "Share of image relevance on the outermost ring of patches."), } + target: str + top_k: int + fidelity_rtol: float + max_cases: int + def __init__(self, target: str = "prediction", top_k: int = 10, fidelity_rtol: float = 1e-2, max_cases: int = 0) -> None: super().__init__(target=target, top_k=top_k, fidelity_rtol=fidelity_rtol, diff --git a/evalrx/analyzers/attribution/gradcam.py b/evalrx/analyzers/attribution/gradcam.py index 33b0c83f..68c7850d 100755 --- a/evalrx/analyzers/attribution/gradcam.py +++ b/evalrx/analyzers/attribution/gradcam.py @@ -30,7 +30,7 @@ from __future__ import annotations from collections import Counter -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, cast from evalrx.core.analyzer import Analyzer from evalrx.core.capability import Capability @@ -74,6 +74,10 @@ class GradCAMAnalyzer(Analyzer): "gc_edge_mass": ("Grad-CAM on border", "Share of the map on the outermost ring of patches."), } + layer: 'int | float' + target: str + max_cases: int + def __init__(self, layer: "int | float" = 0.5, target: str = "prediction", max_cases: int = 0) -> None: super().__init__(layer=layer, target=target, max_cases=max_cases) @@ -145,7 +149,7 @@ def _run(self, model: "Model", cases: "CaseBatch"): if not per_case: raise ValueError(f"{self.name}: no case could be analysed (skipped: {dict(skipped)})") artifacts: dict[str, Any] = { - "spatial_map": per_case_maps[first_id].astype(np.float64), + "spatial_map": per_case_maps[cast(str, first_id)].astype(np.float64), # set with the first row "per_case_maps": per_case_maps, } group_artifacts, group_findings = group_maps(per_case_maps, cases) diff --git a/evalrx/analyzers/geometry/linear_probe.py b/evalrx/analyzers/geometry/linear_probe.py index c01f2a4b..5874f6bf 100755 --- a/evalrx/analyzers/geometry/linear_probe.py +++ b/evalrx/analyzers/geometry/linear_probe.py @@ -46,6 +46,11 @@ class LinearProbeAnalyzer(Analyzer): # max_cases sized for enriched batches (see LogitLensAnalyzer): the held-out # probe needs enough of the scarce FAIL class for a trustworthy accuracy # curve and a powered downstream contrast; one forward per case. + pos: int + max_cases: int + min_per_class: int + seed: int + def __init__(self, pos: int = -1, max_cases: int = 0, min_per_class: int = 4, l2: float = 1e-2, epochs: int = 200, seed: int = 0) -> None: super().__init__(pos=pos, max_cases=max_cases, min_per_class=min_per_class, diff --git a/evalrx/analyzers/hallucination/chair.py b/evalrx/analyzers/hallucination/chair.py index 4aa8dfb0..8f6ac34e 100755 --- a/evalrx/analyzers/hallucination/chair.py +++ b/evalrx/analyzers/hallucination/chair.py @@ -50,6 +50,9 @@ class CHAIRAnalyzer(Analyzer): # match alone still offers this on a batch with no images in it. requires_modalities = frozenset({"image"}) + object_vocab: Iterable[str] + gt_key: str + def __init__(self, object_vocab: Iterable[str], gt_key: str = "gt_objects") -> None: super().__init__(object_vocab=list(object_vocab), gt_key=gt_key) diff --git a/evalrx/analyzers/hallucination/pope.py b/evalrx/analyzers/hallucination/pope.py index 87a94da3..862f5654 100755 --- a/evalrx/analyzers/hallucination/pope.py +++ b/evalrx/analyzers/hallucination/pope.py @@ -55,6 +55,8 @@ class POPEAnalyzer(Analyzer): # match alone still offers this on a batch with no images in it. requires_modalities = frozenset({"image"}) + label_key: str + def __init__(self, label_key: str = "pope_label") -> None: super().__init__(label_key=label_key) diff --git a/evalrx/analyzers/hallucination/selfcheck.py b/evalrx/analyzers/hallucination/selfcheck.py index 5af8c9a3..07484020 100644 --- a/evalrx/analyzers/hallucination/selfcheck.py +++ b/evalrx/analyzers/hallucination/selfcheck.py @@ -77,6 +77,11 @@ class SelfCheckConsistencyAnalyzer(Analyzer): requires = frozenset({Capability.GENERATE}) applies_to_modalities = frozenset({"text", "image"}) + n_samples: int + gen_kwargs: dict[str, Any] + max_cases: int + min_sentence_chars: int + def __init__( self, n_samples: int = 4, diff --git a/evalrx/analyzers/lens/embed_lens.py b/evalrx/analyzers/lens/embed_lens.py index 3b994c32..515d92cf 100644 --- a/evalrx/analyzers/lens/embed_lens.py +++ b/evalrx/analyzers/lens/embed_lens.py @@ -104,6 +104,14 @@ class EmbedLensAnalyzer(Analyzer): "el_prompt_best_sim": ("Its grounding similarity", "Cosine similarity of that word's embedding to its closest media token."), } + layer: 'int | float' + top_k: int + recurring_frac: float + min_images: int + norm_ratio: float + vocab_chunk: int + max_cases: int + def __init__(self, layer: "int | float" = 0, top_k: int = 5, recurring_frac: float = 0.5, min_images: int = 3, norm_ratio: float = 4.0, vocab_chunk: int = 32768, max_cases: int = 0) -> None: @@ -142,7 +150,8 @@ def nearest(x: Any) -> "tuple[Any, Any]": """Top-k cosine neighbours of *x* ``(n, dim)``: ``(sims, ids)``, each ``(n, k)``.""" x = x.float().to(table.device) x = x / x.norm(dim=-1, keepdim=True).clamp(min=1e-12) - best_s = best_i = None + best_s = None + best_i: Any = None # set together with best_s for start in range(0, table.shape[0], max(1, self.vocab_chunk)): block = table[start:start + self.vocab_chunk].float() sims = (x @ block.T) / row_norms[start:start + self.vocab_chunk] @@ -214,7 +223,7 @@ def nearest(x: Any) -> "tuple[Any, Any]": "el_frac_high_norm": round(sum(per_token[case.id]["high_norm"]) / len(media), 4), } if grounding: - best_word = max(grounding, key=grounding.get) + best_word = max(grounding, key=grounding.__getitem__) row["el_prompt_best_word"] = best_word row["el_prompt_best_sim"] = grounding[best_word] rows.append(row) diff --git a/evalrx/analyzers/lens/head_attribution.py b/evalrx/analyzers/lens/head_attribution.py index 624bf5e9..85a6bfd8 100644 --- a/evalrx/analyzers/lens/head_attribution.py +++ b/evalrx/analyzers/lens/head_attribution.py @@ -73,6 +73,10 @@ class HeadAttributionAnalyzer(Analyzer): "dla_linear_share": ("Linear-attention share", "Hybrid stacks only: share of all heads' absolute contribution written by the linear-attention (gated delta rule) layers rather than softmax attention."), } + target: str + top_k: int + max_cases: int + def __init__(self, target: str = "prediction", top_k: int = 10, max_cases: int = 0) -> None: super().__init__(target=target, top_k=top_k, max_cases=max_cases) @@ -94,7 +98,7 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: stack = decoder_stack(module) norm = get_final_norm(module) unembed = get_unembed(module) - projs = [out_proj(m) if m is not None else None for m in stack.mixers] + projs: list[Any] = [out_proj(m) if m is not None else None for m in stack.mixers] if any(p is None for p in projs): raise ValueError(f"{self.name}: some decoder layers have no recognised token mixer " "with an output projection; head attribution would miss them.") diff --git a/evalrx/analyzers/lens/layer_contrast.py b/evalrx/analyzers/lens/layer_contrast.py index 3901c795..4cc02e57 100644 --- a/evalrx/analyzers/lens/layer_contrast.py +++ b/evalrx/analyzers/lens/layer_contrast.py @@ -48,6 +48,10 @@ class LayerContrastAnalyzer(Analyzer): requires = frozenset({Capability.HIDDEN_STATES}) applies_to_modalities = frozenset({"text", "image"}) + pos: int + skip_first_frac: float + max_cases: int + def __init__(self, pos: int = -1, skip_first_frac: float = 0.25, max_cases: int = 0) -> None: super().__init__(pos=pos, skip_first_frac=float(skip_first_frac), max_cases=max_cases) diff --git a/evalrx/analyzers/lens/logit_lens.py b/evalrx/analyzers/lens/logit_lens.py index 6667dbac..79c837a6 100755 --- a/evalrx/analyzers/lens/logit_lens.py +++ b/evalrx/analyzers/lens/logit_lens.py @@ -59,6 +59,10 @@ class LogitLensAnalyzer(Analyzer): # starves it — on a curated batch the stratified subsample then carries only # ~16 FAILs, too few for M4 to clear the e-value bar. 128 covers typical # mined fail counts (tens) plus controls at one forward each. + pos: int + top_k: int + max_cases: int + def __init__(self, pos: int = -1, top_k: int = 3, max_cases: int = 0) -> None: super().__init__(pos=pos, top_k=top_k, max_cases=max_cases) diff --git a/evalrx/analyzers/lens/patchscope.py b/evalrx/analyzers/lens/patchscope.py index 27edef1b..9ed09da7 100644 --- a/evalrx/analyzers/lens/patchscope.py +++ b/evalrx/analyzers/lens/patchscope.py @@ -96,6 +96,13 @@ class PatchscopeAnalyzer(Analyzer): "ps_agree_mid": ("Mid-stack readout agrees", "Share of the middle third of the layers whose readout ranks the model's final answer first."), } + target: str + target_prompt: str + n_points: int + media_layers: int + batch_rows: int + max_cases: int + def __init__(self, target: str = "prediction", target_prompt: str = IDENTITY_PROMPT, n_points: int = 0, media_layers: int = 0, batch_rows: int = 64, max_cases: int = 0) -> None: diff --git a/evalrx/analyzers/lens/tuned_lens.py b/evalrx/analyzers/lens/tuned_lens.py index 3698b20f..66717f83 100755 --- a/evalrx/analyzers/lens/tuned_lens.py +++ b/evalrx/analyzers/lens/tuned_lens.py @@ -24,7 +24,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, cast from evalrx.core.analyzer import Analyzer from evalrx.core.capability import Capability @@ -98,6 +98,14 @@ class TunedLensAnalyzer(Analyzer): "tl_kl_mid": ("Mid-stack disagreement", "Tuned-lens KL divergence from the final distribution, averaged over the middle third of the layers."), } + train_tokens: int + steps: int + batch_size: int + lr: float + seed: int + translators_path: 'str | None' + max_cases: int + def __init__(self, train_tokens: int = 4096, steps: int = 200, batch_size: int = 256, lr: float = 1e-3, seed: int = 0, translators_path: "str | None" = None, max_cases: int = 0) -> None: @@ -135,7 +143,7 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: for layer, h in enumerate(hidden): train[layer].append(h[pick].detach().float().cpu()) last_states.append((case.id, [h[-1].detach().float().cpu() for h in hidden])) - data = [torch.cat(chunks) for chunks in train] + data = [torch.cat(chunks) for chunks in cast("list[list]", train)] # rows is non-empty n_layers = len(data) - 1 # entries 0..L-1 premature, L = final (post-norm) dim = data[0].shape[1] apply_norm = _functional_norm(norm, data[0][:1].to(device)) diff --git a/evalrx/analyzers/patching/attention_knockout.py b/evalrx/analyzers/patching/attention_knockout.py index fedf1030..66e8c383 100644 --- a/evalrx/analyzers/patching/attention_knockout.py +++ b/evalrx/analyzers/patching/attention_knockout.py @@ -88,6 +88,11 @@ class AttentionKnockoutAnalyzer(Analyzer): "ko_delta_late": ("Drop, late layers", "Margin drop when media attention is blocked only in the last third of the layers."), } + target: str + queries: str + fidelity_rtol: float + max_cases: int + def __init__(self, target: str = "prediction", queries: str = "text", fidelity_rtol: float = 1e-2, max_cases: int = 0) -> None: if queries not in ("text", "last"): diff --git a/evalrx/analyzers/patching/attention_sensitivity.py b/evalrx/analyzers/patching/attention_sensitivity.py index 128956c5..4ef3504a 100644 --- a/evalrx/analyzers/patching/attention_sensitivity.py +++ b/evalrx/analyzers/patching/attention_sensitivity.py @@ -79,6 +79,13 @@ class AttentionSensitivityAnalyzer(Analyzer): "rw_flips_up": ("Answer flips, more looking", "Scaling media attention up changes the model's top next token."), } + down: float + up: float + band: str + target: str + fidelity_rtol: float + max_cases: int + def __init__(self, down: float = 0.5, up: float = 2.0, band: str = "all", target: str = "prediction", fidelity_rtol: float = 1e-2, max_cases: int = 0) -> None: if band not in _BANDS: diff --git a/evalrx/analyzers/patching/attention_temperature.py b/evalrx/analyzers/patching/attention_temperature.py index 347a9042..206f58c7 100644 --- a/evalrx/analyzers/patching/attention_temperature.py +++ b/evalrx/analyzers/patching/attention_temperature.py @@ -83,6 +83,14 @@ class AttentionTemperatureAnalyzer(Analyzer): "tt_media_entropy": ("Focus inside the media", "Normalized entropy of the answer position's attention distribution over the media tokens in the edited layers (1 = spread evenly, 0 = one token)."), } + sharp: float + flat: float + scope: str + band: str + target: str + fidelity_rtol: float + max_cases: int + def __init__(self, sharp: float = 0.5, flat: float = 2.0, scope: str = "within", band: str = "all", target: str = "prediction", fidelity_rtol: float = 1e-2, max_cases: int = 0) -> None: diff --git a/evalrx/analyzers/patching/attribution_patching.py b/evalrx/analyzers/patching/attribution_patching.py index 9ca04ef9..ed8443c6 100644 --- a/evalrx/analyzers/patching/attribution_patching.py +++ b/evalrx/analyzers/patching/attribution_patching.py @@ -61,7 +61,7 @@ from collections import Counter from contextlib import contextmanager, nullcontext -from typing import TYPE_CHECKING, Any, Iterator +from typing import TYPE_CHECKING, Any, Iterator, cast from evalrx.core.analyzer import Analyzer from evalrx.core.capability import Capability @@ -191,6 +191,18 @@ class AttributionPatchingAnalyzer(Analyzer): "ap_verified": ("Estimate verified", "ap_verify_mae is within verify_tol: this case's curves and relay token can be read (only these enter the aggregates)."), } + corruption: str + noise_scale: float + n_noise: int + ig_steps: int + direction: str + n_verify: int + verify_tol: float + min_effect: float + target: str + seed: int + max_cases: int + def __init__(self, corruption: str = "noise", noise_scale: float = 3.0, n_noise: int = 1, ig_steps: int = 5, direction: str = "denoise", n_verify: int = 2, verify_tol: float = 0.25, min_effect: float = 1.0, target: str = "prediction", @@ -284,7 +296,7 @@ def attributed(clean_h: list, corrupt_h: list, grads: list) -> Any: skipped: Counter = Counter() slots: Counter = Counter() for index, case in enumerate(cases.stratified_head(self.max_cases)): - clean_variant = (case.inputs, {}, (None, None)) + clean_variant: tuple[Any, dict, tuple[Any, Any]] = (case.inputs, {}, (None, None)) # A gray image's DeepStack copies are interpolated too: record both runs' copies. clean_rec: "dict | None" = {} if (integrated and mergers and self.corruption == "gray") else None clean_grad_needed = not (denoise or integrated) @@ -329,7 +341,8 @@ def attributed(clean_h: list, corrupt_h: list, grads: list) -> Any: corrupt_h = [states[layer] for layer in layers] del trace, states store = variant[2][0] - deltas = ({i: corrupt_rec[i] - clean_rec[i] for i in corrupt_rec} if corrupt_rec + # corrupt_rec is only a dict when clean_rec is + deltas = ({i: corrupt_rec[i] - cast(dict, clean_rec)[i] for i in corrupt_rec} if corrupt_rec else (dict(store) if store else None)) term = None for alpha in alphas: # ḡ averaged along the corrupt → clean media path @@ -347,7 +360,7 @@ def attributed(clean_h: list, corrupt_h: list, grads: list) -> Any: del trace, states, grads else: corrupt_h = [states[layer] for layer in layers] - term = attributed(clean_h, corrupt_h, clean_grad) + term = attributed(clean_h, corrupt_h, cast(list, clean_grad)) # computed: not denoise/integrated del trace, states if not denoise: corrupt_runs.append(corrupt_h) @@ -423,7 +436,7 @@ def attributed(clean_h: list, corrupt_h: list, grads: list) -> Any: curves[case.id] = {"last": [round(r, 4) for r in last_curve]} if relay_curve is not None: curves[case.id]["relay"] = [round(r, 4) for r in relay_curve] - curves[case.id]["relay_pos_from_end"] = [last - p for p in relay_at] + curves[case.id]["relay_pos_from_end"] = [last - p for p in cast("list[int]", relay_at)] # set with relay_curve del contrib, share, clean_h, clean_grad, corrupt_runs if not per_case: diff --git a/evalrx/analyzers/patching/causal_trace.py b/evalrx/analyzers/patching/causal_trace.py index 82013a5c..a22ca544 100755 --- a/evalrx/analyzers/patching/causal_trace.py +++ b/evalrx/analyzers/patching/causal_trace.py @@ -59,7 +59,7 @@ def _gray(image: Any) -> Any: from evalrx.analyzers.attention.relative_attn import _resolve_image - img = _resolve_image(image) + img: Any = _resolve_image(image) if not hasattr(img, "convert"): return None rgb = img.convert("RGB") @@ -152,7 +152,7 @@ def corrupted_variants( variants = [] for _ in range(max(1, n_noise)): noise = torch.randn(embeddings.shape, generator=gen).to(embeddings.device, embeddings.dtype) * std - store = {} if deepstack and slot == "image" else None + store: dict | None = {} if deepstack and slot == "image" else None variants.append((inputs, {0: (media, embeddings + noise)}, (store, gen))) return variants, "" @@ -216,6 +216,15 @@ class CausalTraceAnalyzer(Analyzer): "ct_last_recovery_max": ("Best recovery at answer pos.", "Largest share of the lost margin recovered by restoring the final prompt position at any probed layer."), } + corruption: str + noise_scale: float + n_noise: int + n_points: int + min_effect: float + target: str + seed: int + max_cases: int + def __init__(self, corruption: str = "noise", noise_scale: float = 3.0, n_noise: int = 1, n_points: int = 8, min_effect: float = 1.0, target: str = "prediction", seed: int = 0, max_cases: int = 0) -> None: diff --git a/evalrx/analyzers/patching/path_patching.py b/evalrx/analyzers/patching/path_patching.py index 3d051d94..4d0d8c7b 100644 --- a/evalrx/analyzers/patching/path_patching.py +++ b/evalrx/analyzers/patching/path_patching.py @@ -138,6 +138,14 @@ class PathPatchingAnalyzer(Analyzer): "pp_linear_share": ("Direct effect via linear heads", "Share of the patched heads' absolute exact direct effect carried by linear-attention heads (hybrid stacks)."), } + corruption: str + noise_scale: float + top_k: int + min_effect: float + target: str + seed: int + max_cases: int + def __init__(self, corruption: str = "noise", noise_scale: float = 3.0, top_k: int = 8, min_effect: float = 1.0, target: str = "prediction", seed: int = 0, max_cases: int = 0) -> None: @@ -174,7 +182,7 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: stack = decoder_stack(module) mergers = deepstack_mergers(module) norm, unembed = get_final_norm(module), get_unembed(module) - projs = [out_proj(m) if m is not None else None for m in stack.mixers] + projs: list[Any] = [out_proj(m) if m is not None else None for m in stack.mixers] if any(p is None for p in projs): raise ValueError(f"{self.name}: some decoder layers have no recognised token mixer " "with an output projection; their heads could not be frozen.") @@ -206,7 +214,7 @@ def with_senders(base: dict, donor: dict, senders: "list[tuple[int, int]]", skipped: Counter = Counter() slots: Counter = Counter() for index, case in enumerate(cases.stratified_head(self.max_cases)): - clean_variant = (case.inputs, {}, (None, None)) + clean_variant: tuple[Any, dict, tuple[Any, Any]] = (case.inputs, {}, (None, None)) trace, clean_mix, clean_res = forward(clean_variant, capture=True, residual0=True) slot, media = media_positions(trace) if not media: @@ -268,7 +276,7 @@ def share(replace: dict) -> float: trace, _, _ = forward(clean_variant, replace=replace) return (m_clean - margin.value(trace.require(Capability.LOGITS)[-1:])) / effect - table = [] + table: list[dict[str, Any]] = [] for layer, head in chosen: direct = share(with_senders(clean_in, donor_in, [(layer, head)], freeze=True)) table.append({"head": head_name(layer, head), "layer": layer, "head_index": head, diff --git a/evalrx/analyzers/perturbation/context_shap.py b/evalrx/analyzers/perturbation/context_shap.py index 7f058e19..bce10258 100644 --- a/evalrx/analyzers/perturbation/context_shap.py +++ b/evalrx/analyzers/perturbation/context_shap.py @@ -82,6 +82,12 @@ class ContextShapAnalyzer(Analyzer): requires = frozenset({Capability.GENERATE}) applies_to_modalities = frozenset({"text", "image"}) + granularity: str + n_samples: int + max_chunks: int + max_cases: int + seed: int + def __init__( self, granularity: str = "paragraph", diff --git a/evalrx/analyzers/perturbation/cot_faithfulness.py b/evalrx/analyzers/perturbation/cot_faithfulness.py index 3f6e51fe..a2a570e5 100644 --- a/evalrx/analyzers/perturbation/cot_faithfulness.py +++ b/evalrx/analyzers/perturbation/cot_faithfulness.py @@ -104,6 +104,9 @@ class CoTFaithfulnessAnalyzer(Analyzer): requires = frozenset({Capability.GENERATE}) applies_to_modalities = frozenset({"text", "image"}) + truncation_fracs: tuple + max_cases: int + def __init__( self, truncation_fracs: tuple = (0.25, 0.5, 0.75), diff --git a/evalrx/analyzers/perturbation/format_sensitivity.py b/evalrx/analyzers/perturbation/format_sensitivity.py index 0da21bf5..91769ec7 100644 --- a/evalrx/analyzers/perturbation/format_sensitivity.py +++ b/evalrx/analyzers/perturbation/format_sensitivity.py @@ -146,6 +146,9 @@ class FormatSensitivityAnalyzer(Analyzer): requires = frozenset({Capability.GENERATE}) applies_to_modalities = frozenset({"text", "image"}) + n_variants: int + max_cases: int + def __init__(self, n_variants: int = 3, max_cases: int = 0) -> None: super().__init__(n_variants=max(1, int(n_variants)), max_cases=max_cases) @@ -154,7 +157,7 @@ def _variant_prompt( prompt: str, block: Optional[str], options: list[str], shift: int ) -> tuple[str, list[str]]: rotated = options[shift:] + options[:shift] - paren = bool(block) and bool(_PAREN_OPTION.match(block)) + paren = bool(block and _PAREN_OPTION.match(block)) rotated_block = render_options(rotated, paren=paren) if block: # identical restatements of the same block rotate together diff --git a/evalrx/analyzers/perturbation/mm_shap.py b/evalrx/analyzers/perturbation/mm_shap.py index 61e5c067..14733665 100755 --- a/evalrx/analyzers/perturbation/mm_shap.py +++ b/evalrx/analyzers/perturbation/mm_shap.py @@ -45,10 +45,6 @@ def _slot_player(slot: str) -> str: return f"__{slot}__" -#: Kept for backwards compatibility with callers that imported the old constant. -_IMAGE = _slot_player("image") - - @register_analyzer("mm_shap") class MMShapAnalyzer(Analyzer): """Per-modality Shapley contribution + the MM-SHAP media-reliance scores.""" @@ -75,6 +71,12 @@ class MMShapAnalyzer(Analyzer): #: and the "modality contribution" it reports is a text-only tautology. requires_modalities = frozenset(MEDIA_SLOTS) + score_fn: Optional[Callable[[Inputs], float]] + n_samples: int + mask_token: str + top_k: int + seed: int + def __init__( self, score_fn: Optional[Callable[[Inputs], float]] = None, diff --git a/evalrx/analyzers/perturbation/modality_ablation.py b/evalrx/analyzers/perturbation/modality_ablation.py index 508680fd..c563abe7 100644 --- a/evalrx/analyzers/perturbation/modality_ablation.py +++ b/evalrx/analyzers/perturbation/modality_ablation.py @@ -82,6 +82,11 @@ class ModalityAblationAnalyzer(Analyzer): #: the analyzer would report a grounding rate over zero probes. requires_modalities = frozenset(MEDIA_SLOTS) + mode: str + slots: 'tuple[str, ...] | None' + score_fn: Optional[Callable[['FailureCase', str], Optional[bool]]] + max_cases: int + def __init__( self, mode: str = "drop", @@ -147,7 +152,7 @@ def _run(self, model: "Model", cases: "CaseBatch") -> Result: row: dict[str, Any] = {"sample_id": case.id} for slot in self._slots_of(case): - donor = self._donor(selected, slot, case) if self.mode == "swap" else None + donor: Any = self._donor(selected, slot, case) if self.mode == "swap" else None # swap with no donor degrades to drop rather than skipping: the # weaker evidence is still evidence, and silently probing nothing # would look identical to a fully-grounded model. diff --git a/evalrx/analyzers/perturbation/perturbation_battery.py b/evalrx/analyzers/perturbation/perturbation_battery.py index 007d5aca..6b560ce1 100644 --- a/evalrx/analyzers/perturbation/perturbation_battery.py +++ b/evalrx/analyzers/perturbation/perturbation_battery.py @@ -150,6 +150,9 @@ class PerturbationBattery(Analyzer): 'sensitivity_rate': ('Responds to real changes', 'For this case: share of meaning-ALTERING edits that did change the answer. Low is bad — the model ignored a change that should matter.'), } + max_cases: int + gen_kwargs: dict[str, Any] + def __init__( self, perturbations: tuple = DEFAULT_PERTURBATIONS, diff --git a/evalrx/analyzers/perturbation/prompt_contrast.py b/evalrx/analyzers/perturbation/prompt_contrast.py index c38329be..eb9fb723 100755 --- a/evalrx/analyzers/perturbation/prompt_contrast.py +++ b/evalrx/analyzers/perturbation/prompt_contrast.py @@ -154,6 +154,10 @@ class PromptContrastAnalyzer(Analyzer): 'success_rate_sensitive': ('Correct, report-subtle', "Share correct when told to report a finding even if subtle. Higher than baseline means the model's yes/no threshold was set too high, not that it could not tell."), } + strategies: dict[str, str] + score_fn: Callable[[Any, str], Optional[bool]] | None + max_cases: int + def __init__( self, strategies: dict[str, str] | None = None, diff --git a/evalrx/analyzers/perturbation/rise.py b/evalrx/analyzers/perturbation/rise.py index 336f3087..86877d8f 100755 --- a/evalrx/analyzers/perturbation/rise.py +++ b/evalrx/analyzers/perturbation/rise.py @@ -46,6 +46,13 @@ class RISEAnalyzer(Analyzer): requires = frozenset({Capability.GENERATE}) applies_to_modalities = frozenset({"text"}) + score_fn: Optional[Callable[[str], float]] + n_masks: int + keep_prob: float + mask_token: str + top_k: int + seed: int + def __init__( self, score_fn: Optional[Callable[[str], float]] = None, diff --git a/evalrx/analyzers/perturbation/vl_shap.py b/evalrx/analyzers/perturbation/vl_shap.py index eff0b0f2..177904ae 100755 --- a/evalrx/analyzers/perturbation/vl_shap.py +++ b/evalrx/analyzers/perturbation/vl_shap.py @@ -48,6 +48,12 @@ class VLShapAnalyzer(Analyzer): # audio batch matched here and then raised on the first case. requires_modalities = frozenset({"image"}) + n_regions: int + region_score_fn: Optional[Callable[[set], float]] + n_samples: int + top_k: int + seed: int + def __init__( self, n_regions: int = 16, diff --git a/evalrx/analyzers/reasoning/answer_extraction_audit.py b/evalrx/analyzers/reasoning/answer_extraction_audit.py index ff89539c..5a8a768b 100644 --- a/evalrx/analyzers/reasoning/answer_extraction_audit.py +++ b/evalrx/analyzers/reasoning/answer_extraction_audit.py @@ -161,6 +161,10 @@ class AnswerExtractionAudit(Analyzer): 'suspect_rate': ('Possible grading misses', 'Share of wrong answers that may be grading mistakes rather than model mistakes. High means the failure numbers are not trustworthy yet.'), } + reask: bool + max_cases: int + tail_chars: int + def __init__( self, reask: bool = False, diff --git a/evalrx/analyzers/reasoning/arith_audit.py b/evalrx/analyzers/reasoning/arith_audit.py index 8f8f2b08..6cac0a6c 100644 --- a/evalrx/analyzers/reasoning/arith_audit.py +++ b/evalrx/analyzers/reasoning/arith_audit.py @@ -78,6 +78,10 @@ class ArithmeticAudit(Analyzer): requires = frozenset() applies_to_modalities = frozenset({"text", "image"}) + rel_tol: float + generate_missing: bool + max_cases: int + def __init__( self, rel_tol: float = 1e-6, diff --git a/evalrx/analyzers/reasoning/contamination.py b/evalrx/analyzers/reasoning/contamination.py index 4fd2d083..a908151d 100644 --- a/evalrx/analyzers/reasoning/contamination.py +++ b/evalrx/analyzers/reasoning/contamination.py @@ -93,6 +93,14 @@ class ContaminationProbe(Analyzer): requires = frozenset({Capability.GENERATE}) applies_to_modalities = frozenset({"text", "image"}) + dataset_name: str + split: str + split_frac: float + ngram: int + flag_threshold: float + ask_provenance: bool + max_cases: int + def __init__( self, dataset_name: str = "the evaluation", diff --git a/evalrx/analyzers/reasoning/knowledge_split.py b/evalrx/analyzers/reasoning/knowledge_split.py index 7a0670ce..7e5bef2c 100644 --- a/evalrx/analyzers/reasoning/knowledge_split.py +++ b/evalrx/analyzers/reasoning/knowledge_split.py @@ -80,6 +80,10 @@ class KnowledgeReasoningSplit(Analyzer): requires = frozenset({Capability.GENERATE}) applies_to_modalities = frozenset({"text", "image"}) + use_context: bool + context_keys: tuple + max_cases: int + def __init__( self, use_context: bool = True, diff --git a/evalrx/analyzers/reasoning/self_repair.py b/evalrx/analyzers/reasoning/self_repair.py index c2d72785..bc0e5b0d 100644 --- a/evalrx/analyzers/reasoning/self_repair.py +++ b/evalrx/analyzers/reasoning/self_repair.py @@ -79,6 +79,10 @@ class SelfRepairAnalyzer(Analyzer): requires = frozenset({Capability.GENERATE}) applies_to_modalities = frozenset({"text", "image"}) + revise_with_critique: bool + max_cases: int + generate_missing: bool + def __init__( self, revise_with_critique: bool = False, diff --git a/evalrx/analyzers/reasoning/step_rollout_value.py b/evalrx/analyzers/reasoning/step_rollout_value.py index b4da5635..bd870ec3 100644 --- a/evalrx/analyzers/reasoning/step_rollout_value.py +++ b/evalrx/analyzers/reasoning/step_rollout_value.py @@ -82,6 +82,12 @@ class StepRolloutValueAnalyzer(Analyzer): requires = frozenset({Capability.GENERATE}) applies_to_modalities = frozenset({"text", "image"}) + n_rollouts: int + max_steps: int + drop_threshold: float + max_cases: int + gen_kwargs: dict[str, Any] + def __init__( self, n_rollouts: int = 3, diff --git a/evalrx/analyzers/reasoning/termination_audit.py b/evalrx/analyzers/reasoning/termination_audit.py index 6fd2ce02..f26215a7 100644 --- a/evalrx/analyzers/reasoning/termination_audit.py +++ b/evalrx/analyzers/reasoning/termination_audit.py @@ -92,6 +92,11 @@ class TerminationAudit(Analyzer): 'truncation_rate': ('Cut off by length', 'Share of answers cut off by the length limit before finishing.'), } + continue_non_clean: bool + repetition_n: int + repetition_thresh: float + max_cases: int + def __init__( self, continue_non_clean: bool = True, diff --git a/evalrx/analyzers/uncertainty/calibration.py b/evalrx/analyzers/uncertainty/calibration.py index 18f72d4f..40331805 100644 --- a/evalrx/analyzers/uncertainty/calibration.py +++ b/evalrx/analyzers/uncertainty/calibration.py @@ -92,6 +92,10 @@ class CalibrationAnalyzer(Analyzer): requires = frozenset({Capability.GENERATE}) applies_to_modalities = frozenset({"text", "image"}) + n_bins: int + max_cases: int + elicit: str + def __init__(self, n_bins: int = 10, max_cases: int = 0, elicit: str = _ELICIT) -> None: super().__init__(n_bins=max(2, int(n_bins)), max_cases=max_cases, elicit=elicit) diff --git a/evalrx/analyzers/uncertainty/coverage_gap.py b/evalrx/analyzers/uncertainty/coverage_gap.py index de0a0a49..3805efab 100644 --- a/evalrx/analyzers/uncertainty/coverage_gap.py +++ b/evalrx/analyzers/uncertainty/coverage_gap.py @@ -79,6 +79,11 @@ class CoverageVerificationGap(Analyzer): requires = frozenset({Capability.GENERATE}) applies_to_modalities = frozenset({"text", "image"}) + k: int + self_verify: bool + max_cases: int + gen_kwargs: dict[str, Any] + def __init__( self, k: int = 5, diff --git a/evalrx/analyzers/uncertainty/entropy.py b/evalrx/analyzers/uncertainty/entropy.py index 6d8c5eac..bdd70013 100755 --- a/evalrx/analyzers/uncertainty/entropy.py +++ b/evalrx/analyzers/uncertainty/entropy.py @@ -51,6 +51,8 @@ class TokenEntropyAnalyzer(Analyzer): name = "token_entropy" requires = frozenset({Capability.LOGITS}) + top_k: int + def __init__(self, top_k: int = 5) -> None: super().__init__(top_k=top_k) diff --git a/evalrx/analyzers/uncertainty/self_consistency.py b/evalrx/analyzers/uncertainty/self_consistency.py index 59f5a203..41fd7db5 100755 --- a/evalrx/analyzers/uncertainty/self_consistency.py +++ b/evalrx/analyzers/uncertainty/self_consistency.py @@ -115,6 +115,10 @@ class SelfConsistencyAnalyzer(Analyzer): 'normalized_semantic_entropy': ('Answer spread', 'How spread out the answers were. High means the model has no settled view.'), } + n: int + gen_kwargs: dict[str, Any] + semantic: bool + def __init__( self, n: int = 5, diff --git a/evalrx/analyzers/uncertainty/verbalized_conf.py b/evalrx/analyzers/uncertainty/verbalized_conf.py index d2d01067..4a255f0a 100755 --- a/evalrx/analyzers/uncertainty/verbalized_conf.py +++ b/evalrx/analyzers/uncertainty/verbalized_conf.py @@ -40,6 +40,8 @@ class VerbalizedConfidenceAnalyzer(Analyzer): requires = frozenset({Capability.GENERATE}) applies_to_modalities = frozenset({"text", "image"}) + elicit: str + def __init__(self, elicit: str = _DEFAULT_ELICIT) -> None: super().__init__(elicit=elicit) diff --git a/evalrx/analyzers/weights/continuation_audit.py b/evalrx/analyzers/weights/continuation_audit.py index 454b34a8..99bb5148 100644 --- a/evalrx/analyzers/weights/continuation_audit.py +++ b/evalrx/analyzers/weights/continuation_audit.py @@ -113,6 +113,17 @@ class WeightEditContinuationAudit(Analyzer): ), } + edit: Any + groups: str + repeat_ngram: int + controls: tuple[str, ...] + n_seeds: int + steering: bool + max_tokens: int + chunk: int + seed: int + max_cases: int + def __init__(self, edit: "Any", groups: str = "repetition", repeat_ngram: int = 32, controls: "tuple[str, ...]" = ("random_direction", "random_columns"), n_seeds: int = 1, steering: bool = True, max_tokens: int = 4096, @@ -204,11 +215,11 @@ def hook(_m: Any, args: Any) -> None: for t in delta.tensors} # ---- Pass 2: per case, the clean run and every state ------------------------ - def score(clean: Any, other: Any, item: dict[str, Any]) -> "tuple[Any, Any, Any, Any]": + def score(clean: Any, other: Any, item: dict[str, Any]) -> "tuple[Any, ...]": """Per target: clean NLL, NLL change, KL from clean, top-1 changed.""" pos = torch.tensor([i - 1 for i in item["targets"]], device=device) tgt = torch.tensor([item["ids"][i] for i in item["targets"]], device=device) - out = [[], [], [], []] + out: list[list[Any]] = [[], [], [], []] for a in range(0, len(pos), int(self.chunk)): p, t = pos[a:a + int(self.chunk)], tgt[a:a + int(self.chunk)] lp0 = torch.log_softmax(clean[p].float(), dim=-1) @@ -296,14 +307,14 @@ def cat(parts: list) -> Any: edit_kl = float(cat(pooled["edit"][g]["kl"]).mean()) for label in state_names: dnll = cat(pooled[label][g]["dnll"]) - kl = float(cat(pooled[label][g]["kl"]).mean()) + mean_kl = float(cat(pooled[label][g]["kl"]).mean()) findings[f"mean_dnll_{label}_{g}"] = float(dnll.mean()) - findings[f"mean_kl_{label}_{g}"] = kl + findings[f"mean_kl_{label}_{g}"] = mean_kl findings[f"frac_flips_{label}_{g}"] = round( float(cat(pooled[label][g]["flip"]).mean()), 4) if label in self.controls: # Output movement of the edit over that of the matched control. - findings[f"specificity_{label}_{g}"] = round(edit_kl / kl, 4) if kl > 0 else None + findings[f"specificity_{label}_{g}"] = round(edit_kl / mean_kl, 4) if mean_kl > 0 else None if label == "steer": total = float((edit_dnll ** 2).sum()) findings[f"steer_recovery_{g}"] = ( diff --git a/evalrx/analyzers/weights/edit_audit.py b/evalrx/analyzers/weights/edit_audit.py index d59539b8..9aad4d2c 100644 --- a/evalrx/analyzers/weights/edit_audit.py +++ b/evalrx/analyzers/weights/edit_audit.py @@ -103,6 +103,14 @@ class WeightEditAudit(Analyzer): ), } + edit: Any + target: str + controls: tuple[str, ...] + n_seeds: int + steering: bool + seed: int + max_cases: int + def __init__(self, edit: "Any", target: str = "prediction", controls: "tuple[str, ...]" = ("random_direction", "random_columns"), n_seeds: int = 3, steering: bool = True, seed: int = 0, diff --git a/evalrx/analyzers/weights/edit_structure.py b/evalrx/analyzers/weights/edit_structure.py index 264af3a7..94e8d11a 100644 --- a/evalrx/analyzers/weights/edit_structure.py +++ b/evalrx/analyzers/weights/edit_structure.py @@ -58,6 +58,10 @@ class WeightEditStructure(Analyzer): ), } + edit: Any + verify_base: bool + top_singular: int + def __init__(self, edit: "Any", verify_base: bool = False, top_singular: int = 8) -> None: super().__init__(edit=edit, verify_base=verify_base, top_singular=top_singular) diff --git a/evalrx/benchmark/runner.py b/evalrx/benchmark/runner.py index 7518f722..596d045f 100644 --- a/evalrx/benchmark/runner.py +++ b/evalrx/benchmark/runner.py @@ -128,7 +128,7 @@ def load_model(resolved: Resolved, args, task: T.Task): # gemma library underneath; text, image and audio inputs. apply_chat_template # as on hf_local. A --model-path is a local Orbax mirror of the spec's # gs:// checkpoint (17 GB for E2B; see docs/design_jax_backend.md section 4). - engine_kwargs = {"checkpoint": str(args.model_path)} if getattr(args, "model_path", None) else {} + engine_kwargs: dict[str, Any] = {"checkpoint": str(args.model_path)} if getattr(args, "model_path", None) else {} # text cells skip the vision / audio towers (~2 GB float32 and their load # time); the vlm / alm cells need them, and the adapter reports the # modalities it can serve accordingly @@ -342,36 +342,21 @@ def run_fix_isolated(loop, run_dir: Path, ctx, report, cases, **fix_kwargs): return loop.run_fix(report, cases, **fix_kwargs) -def run(args, task: T.Task, resolved: Resolved) -> int: - manifest = ensure_manifest(task, args) - # Fail fast: the held-out validation manifest must exist before any model - # or judge is loaded. - val_manifest = ensure_val_manifest(task, args) if args.held_out else None - if args.download_only: - return 0 - limit = args.limit if args.limit is not None else task.default_limit - candidates, rows = T.build_cases(task, manifest, limit) - run_dir = run_dir_for(args, task) - run_dir.mkdir(parents=True, exist_ok=True) - label = model_label(resolved) - print(f"[model] {label}; backend={resolved.backend}; benchmark={task.title}; n={len(candidates)}") - - judge = coder_provider = coder_model = coder_extra = None - if not args.baseline_only: - judge, coder_provider, coder_model, coder_extra = build_judge(args) +def _load_target(resolved: Resolved, args, task: T.Task, run_dir: Path): + """``(model, generation_kwargs, spec)`` for the model under test, weights in memory. + The weights load here, OUTSIDE the timed discovery pass (hf_local is lazy). + """ model, gen_kwargs, spec = load_model(resolved, args, task) if resolved.backend == "gemini": from evalrx.models.backends.api.gemini import runtime_state - capabilities = {"capabilities": sorted(c.value for c in model.capabilities), + capabilities: dict[str, Any] = {"capabilities": sorted(c.value for c in model.capabilities), "runtime": runtime_state(model)} (run_dir / "api_capabilities.json").write_text( json.dumps(capabilities, indent=2) + "\n", encoding="utf-8") print(f"[model] logprobs: {capabilities['runtime'].get('logprobs_probe')}") - protocol = task.protocol(label) if hasattr(model, "load"): - # load the weights OUTSIDE the timed discovery pass (hf_local is lazy) t0 = time.monotonic() model = load_weights(model, resolved, args, task) print(f"[model] weights loaded in {time.monotonic() - t0:.0f}s " @@ -381,166 +366,119 @@ def run(args, task: T.Task, resolved: Resolved) -> int: print(f"[device] {jax.default_backend()}: " + ", ".join(f"{d} ({d.device_kind})" for d in jax.devices())) + return model, gen_kwargs, spec - # Winner-as-new-baseline (recursive rounds with an L2 spec winner): the - # deployed pipeline becomes the handle everything downstream measures — - # Stage-0, the M stages, and the fix stage's baseline arm — while fix - # candidates run on the raw model and REPLACE the pipeline. - raw_model, deployed_spec = model, None - if getattr(args, "baseline_spec", ""): - from evalrx.eval_agent.stages.fix.tools import SpecPipelineModel - - payload = json.loads(Path(args.baseline_spec).read_text(encoding="utf-8")) - if isinstance(payload, dict) and isinstance(payload.get("payload"), dict): - payload = payload["payload"] # a fix attempt's result.json - model = SpecPipelineModel(model, payload) - deployed_spec = model.spec.to_dict() - print(f"[baseline-spec] baseline = deployed pipeline {deployed_spec.get('name')!r} " - f"(n_samples={model.spec.n_samples}, strategy={model.spec.strategy}); " - "fix candidates run on the raw model and replace it") - - from evalrx.eval_agent import CaseDiscoveryAgent, RunContext - ctx = None - if not args.baseline_only: - # Create the V2 sink before Stage-0 so each discovery request is durable - # as it happens, including its real latency and any transport error. - ctx = RunContext( - # narrate: aligned live M1-M5 lines ("M1 probe ···· cycle 0 · ..."), - # same style as examples/m1_m5/qwen_loop_claude, instead of verbose's - # raw "[M1] probe cycle=0" one-liners. - run_dir / "logs", narrate=True, - config={ - "benchmark": task.title, "dataset": task.name, "modality": task.modality, - "model": args.model, "spec": spec.key, "hf_repo": spec.hf_repo, - "backend": resolved.backend, "n_cases": len(candidates), - "manifest": str(manifest), - "manifest_seed": rows[0].get("sample_seed") if rows else None, - "split_mode": ("held_out_val" if args.held_out else "explore_confirm"), - "confirm_split": float(args.confirm_split), "test_split": 0.0, - "val_limit": int(getattr(args, "val_limit", 0) or 0), - "held_out": bool(args.held_out), - "fix_tier": args.fix_tier, - "allow_codegen": args.allow_codegen, "auto_escalate": args.auto_escalate, - "m1_selection": args.m1_selection, "generation_kwargs": gen_kwargs, - "diagnosis_mode": getattr(args, "diagnosis_mode", "agentic"), - "max_actions": getattr(args, "max_actions", 12), - "diagnosis_retries": 1, - "enable_thinking": bool(args.enable_thinking), - "judge_provider": args.judge_provider, "judge_model": args.judge_model, - }, - ) +def _deploy_baseline_spec(model, spec_path: str): + """``(the baseline to measure, its spec as a dict)`` for ``--baseline-spec``. - discovery_model = model - if ctx is not None: - from evalrx.eval_agent.model_instrumentation import InstrumentedModel + Winner-as-new-baseline (recursive rounds with an L2 spec winner): the + deployed pipeline becomes the handle everything downstream measures — + Stage-0, the M stages, and the fix stage's baseline arm — while fix + candidates run on the raw model and REPLACE the pipeline. Without a spec + the model itself is the baseline. + """ + if not spec_path: + return model, None + from evalrx.eval_agent.stages.fix.tools import SpecPipelineModel + + payload = json.loads(Path(spec_path).read_text(encoding="utf-8")) + if isinstance(payload, dict) and isinstance(payload.get("payload"), dict): + payload = payload["payload"] # a fix attempt's result.json + deployed = SpecPipelineModel(model, payload) + deployed_spec = deployed.spec.to_dict() + print(f"[baseline-spec] baseline = deployed pipeline {deployed_spec.get('name')!r} " + f"(n_samples={deployed.spec.n_samples}, strategy={deployed.spec.strategy}); " + "fix candidates run on the raw model and replace it") + return deployed, deployed_spec + + +def _run_config(args, task: T.Task, resolved: Resolved, spec, gen_kwargs: dict, manifest: Path, + rows: list, n_cases: int) -> dict[str, Any]: + """How this cell was asked to run, as the run log records it.""" + return { + "benchmark": task.title, "dataset": task.name, "modality": task.modality, + "model": args.model, "spec": spec.key, "hf_repo": spec.hf_repo, + "backend": resolved.backend, "n_cases": n_cases, + "manifest": str(manifest), + "manifest_seed": rows[0].get("sample_seed") if rows else None, + "split_mode": ("held_out_val" if args.held_out else "explore_confirm"), + "confirm_split": float(args.confirm_split), "test_split": 0.0, + "val_limit": int(getattr(args, "val_limit", 0) or 0), + "held_out": bool(args.held_out), + "fix_tier": args.fix_tier, + "allow_codegen": args.allow_codegen, "auto_escalate": args.auto_escalate, + "m1_selection": args.m1_selection, "generation_kwargs": gen_kwargs, + "diagnosis_mode": getattr(args, "diagnosis_mode", "agentic"), + "max_actions": getattr(args, "max_actions", 12), + "diagnosis_retries": 1, + "enable_thinking": bool(args.enable_thinking), + "judge_provider": args.judge_provider, "judge_model": args.judge_model, + } - candidate_list = list(candidates) - discovery_model = InstrumentedModel( - model, ctx.logger, cycle=-1, analyzer="case_discovery", - case_prompts={c.inputs.prompt: c.id for c in candidate_list}, - batch_case_ids=[c.id for c in candidate_list], - ) - candidates = candidate_list + +def _discover(model, candidates, protocol, gen_kwargs: dict, args): + """Stage 0: generate an answer per candidate and label it. ``(discovery, seconds)``.""" + from evalrx.eval_agent import CaseDiscoveryAgent started = time.monotonic() discovery = CaseDiscoveryAgent( scorer=T.label_case, generation_kwargs=gen_kwargs, include_unknown=False, concurrency=getattr(args, "concurrency", 1), - ).discover(discovery_model, candidates, protocol=protocol) - cases = discovery.cases - if ctx is not None: - ctx.config["n_cases"] = len(cases) - elapsed = time.monotonic() - started - accuracy = discovery.n_pass / max(1, len(cases)) - baseline = { - "model": args.model, "spec": spec.key, "hf_repo": spec.hf_repo, "backend": resolved.backend, - "dataset": task.name, "task": task.kind, "n": len(cases), - "n_pass": discovery.n_pass, "n_fail": discovery.n_fail, "n_unknown": discovery.n_unknown, - "accuracy": round(accuracy, 4), "seconds": round(elapsed, 1), - "generation_kwargs": gen_kwargs, "enable_thinking": bool(args.enable_thinking), - "manifest": str(manifest), "limit": limit, - "cases": [{ - "id": c.id, "expected": c.expected, "observed": str(c.observed), "label": c.label.value, - } for c in cases], - } - version = _api_model_version(model) - if version: - baseline["model_version"] = version - print(f"[model] served version: {version}") - (run_dir / "baseline.json").write_text(json.dumps(baseline, indent=2, ensure_ascii=False) + "\n", - encoding="utf-8") - print(f"Baseline: PASS={discovery.n_pass}, FAIL={discovery.n_fail}, UNKNOWN={discovery.n_unknown}, " - f"accuracy={accuracy:.3f} ({elapsed:.0f}s, {elapsed / max(1, len(cases)):.1f}s/case)") - if task.modality == "llm" and not 0.15 <= accuracy <= 0.85: - print(" NOTE accuracy is outside the usable band [0.15, 0.85]: M2 has little to contrast " - "and the paired tests downstream are short of power (results valid, weak)") + ).discover(model, candidates, protocol=protocol) + return discovery, time.monotonic() - started + + +def _case_labels(cases) -> list[dict[str, Any]]: + return [{ + "id": c.id, "expected": c.expected, "observed": str(c.observed), "label": c.label.value, + } for c in cases] + + +def _mark_short_answers_stopped(task: T.Task, cases) -> None: + """A terse answer that ended well below the cap is a normal EOS stop, not + the free-form truncation heuristic.""" if task.short_answer: - # A terse answer that ended well below the cap is a normal EOS stop, not - # the free-form truncation heuristic. for case in cases: case.metadata["finish_reason"] = "stop" - if args.baseline_only: - print(f"Done (baseline only). {run_dir / 'baseline.json'}") - return 0 - if not discovery.has_m4_groups: - raise SystemExit("M4 needs both PASS and FAIL cases; adjust --limit / --seed") - # Held-out validation set (--held-out): a SEPARATE frozen sample, labeled - # by its own Stage-0 pass. It takes the M4-holdout + fix-development roles; - # the main batch keeps its full explore/confirm split and CONFIRM stays - # the single frozen-winner gate. - val_cases = None - if val_manifest is not None: - val_candidates, _ = T.build_cases(task, val_manifest, int(getattr(args, "val_limit", 0) or 0)) - v0 = time.monotonic() - val_discovery = CaseDiscoveryAgent( - scorer=T.label_case, generation_kwargs=gen_kwargs, include_unknown=False, - concurrency=getattr(args, "concurrency", 1), - ).discover(model, val_candidates, protocol=protocol) - val_cases = val_discovery.cases - val_elapsed = time.monotonic() - v0 - val_accuracy = val_discovery.n_pass / max(1, len(val_cases)) - (run_dir / "baseline_val.json").write_text(json.dumps({ - "model": args.model, "spec": spec.key, "dataset": task.name, "role": "validation", - "n": len(val_cases), "n_pass": val_discovery.n_pass, "n_fail": val_discovery.n_fail, - "n_unknown": val_discovery.n_unknown, "accuracy": round(val_accuracy, 4), - "seconds": round(val_elapsed, 1), "manifest": str(val_manifest), - "cases": [{ - "id": c.id, "expected": c.expected, "observed": str(c.observed), "label": c.label.value, - } for c in val_cases], - }, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") - print(f"Validation baseline: PASS={val_discovery.n_pass}, FAIL={val_discovery.n_fail}, " - f"accuracy={val_accuracy:.3f} ({val_elapsed:.0f}s, n={len(val_cases)})") - if task.short_answer: - for case in val_cases: - case.metadata["finish_reason"] = "stop" - if not val_discovery.has_m4_groups: - print(" NOTE the validation set lacks a PASS or FAIL group; the holdout " - "M4 verification there will have nothing to contrast") - if ctx is not None: - ctx.config["val_manifest"] = str(val_manifest) - ctx.config["n_val_cases"] = len(val_cases) - from evalrx.eval_agent import ( - CliAgentConfig, - DiagnosisAgent, - FixAgent, - HypothesisTester, - ProbeAgent, - StatsAnalysisAgent, - StrategyProbe, - SurgeryAgent, - VLDiagnoseLoop, - ) - from evalrx.eval_agent.stages.experiment_writer import ExperimentWriterConfig - from evalrx.eval_agent.stages.fix.repair_catalog import method_names +def _label_validation_set(model, val_manifest: Path, protocol, gen_kwargs: dict, args, task: T.Task, + spec, run_dir: Path): + """The ``--held-out`` validation cases, labeled by their own Stage-0 pass. + + A SEPARATE frozen sample. It takes the M4-holdout + fix-development roles; + the main batch keeps its full explore/confirm split and CONFIRM stays the + single frozen-winner gate. + """ + val_candidates, _ = T.build_cases(task, val_manifest, int(getattr(args, "val_limit", 0) or 0)) + val_discovery, val_elapsed = _discover(model, val_candidates, protocol, gen_kwargs, args) + val_cases = val_discovery.cases + val_accuracy = val_discovery.n_pass / max(1, len(val_cases)) + (run_dir / "baseline_val.json").write_text(json.dumps({ + "model": args.model, "spec": spec.key, "dataset": task.name, "role": "validation", + "n": len(val_cases), "n_pass": val_discovery.n_pass, "n_fail": val_discovery.n_fail, + "n_unknown": val_discovery.n_unknown, "accuracy": round(val_accuracy, 4), + "seconds": round(val_elapsed, 1), "manifest": str(val_manifest), + "cases": _case_labels(val_cases), + }, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") + print(f"Validation baseline: PASS={val_discovery.n_pass}, FAIL={val_discovery.n_fail}, " + f"accuracy={val_accuracy:.3f} ({val_elapsed:.0f}s, n={len(val_cases)})") + _mark_short_answers_stopped(task, val_cases) + if not val_discovery.has_m4_groups: + print(" NOTE the validation set lacks a PASS or FAIL group; the holdout " + "M4 verification there will have nothing to contrast") + return val_cases + + +def _is_agentic(args) -> bool: + return getattr(args, "diagnosis_mode", "agentic") == "agentic" + + +def _probe_agent(args, task: T.Task, resolved: Resolved, model, judge, coder_cfg, config: dict[str, Any]): + """The M1 agent; records its worker count and selection mode in ``config``.""" + from evalrx.eval_agent import ProbeAgent, StrategyProbe - # ctx already exists (constructed before Stage-0, above) with held_out/ - # val_manifest/n_val_cases folded into its config as they became known. - assert ctx is not None - coder_cfg = CliAgentConfig(provider=coder_provider, model=coder_model, timeout_sec=900, - extra_args=coder_extra) pinned = list(task.pinned_m1) if resolved.backend == "gemini": from evalrx.core.capability import Capability @@ -553,13 +491,13 @@ def run(args, task: T.Task, resolved: Resolved) -> int: # model access. Keep native probes on the calling thread, while serving # backends can continue issuing concurrent requests. probe_workers = 1 if resolved.backend in {"hf_local", "jax_local"} else 8 - ctx.config["m1_workers"] = probe_workers - agentic = getattr(args, "diagnosis_mode", "agentic") == "agentic" + config["m1_workers"] = probe_workers + agentic = _is_agentic(args) m1_codegen = agentic and args.allow_codegen - ctx.config["m1_codegen"] = bool(m1_codegen) - ctx.config["m1_selection"] = "judge" if agentic or m1_codegen else args.m1_selection + config["m1_codegen"] = bool(m1_codegen) + config["m1_selection"] = "judge" if agentic or m1_codegen else args.m1_selection if args.m1_selection == "pinned" and not agentic and not m1_codegen: - probe_agent = ProbeAgent( + return ProbeAgent( # StrategyProbe dispatches by the model's detected kind. Keep the # benchmark's pinned list authoritative for every supported kind, # including the audio-language kinds used by ALM/AVLM examples. @@ -569,17 +507,30 @@ def run(args, task: T.Task, resolved: Resolved) -> int: analyzer_overrides=overrides, max_workers=probe_workers, ) - else: - probe_agent = ProbeAgent(judge=judge, allow_codegen=m1_codegen, - codegen_config=coder_cfg, - max_cases_per_analyzer=args.analyzer_max_cases, - analyzer_overrides=overrides, max_workers=probe_workers) - m2_codegen = args.m2_codegen if args.m2_codegen is not None else (agentic or task.modality == "llm") + return ProbeAgent(judge=judge, allow_codegen=m1_codegen, + codegen_config=coder_cfg, + max_cases_per_analyzer=args.analyzer_max_cases, + analyzer_overrides=overrides, max_workers=probe_workers) + + +def _stats_agent(args, task: T.Task, judge, coder_cfg, ctx): + """The M2 agent; records whether it may write code in ``ctx.config``.""" + from evalrx.eval_agent import StatsAnalysisAgent + + m2_codegen = args.m2_codegen if args.m2_codegen is not None else (_is_agentic(args) or task.modality == "llm") ctx.config["m2_codegen"] = bool(m2_codegen) - stats_agent = StatsAnalysisAgent( + stats_kwargs: dict[str, Any] = {"codegen_config": coder_cfg} if m2_codegen else {} + return StatsAnalysisAgent( judge=judge, figure_dir=str(ctx.figures_dir), max_signal_tools=16, - allow_codegen=m2_codegen, **({"codegen_config": coder_cfg} if m2_codegen else {}), + allow_codegen=m2_codegen, **stats_kwargs, ) + + +def _fix_agent(args, task: T.Task, judge, coder_cfg, gen_kwargs: dict, ctx, raw_model, deployed_spec): + """The fix agent, scoped by the ``--fix-*`` / ``--code-only`` flags.""" + from evalrx.eval_agent import FixAgent + from evalrx.eval_agent.stages.fix.repair_catalog import method_names + fix_kwargs: dict[str, Any] = {} sampled = bool(gen_kwargs.get("do_sample")) # Noise model for a sampled baseline: per-case PASS RATE over k samples (the @@ -597,10 +548,11 @@ def run(args, task: T.Task, resolved: Resolved) -> int: ) if deployed_spec is not None: fix_kwargs.update(candidate_model=raw_model, deployed_spec=deployed_spec) - fix_agent = FixAgent( + if args.code_only: + fix_kwargs["max_judge_candidates"] = 1 + return FixAgent( judge=judge, max_tier=args.fix_tier, score_fn=T.score_case, run_logger=ctx.logger, - cli_config=(CliAgentConfig(provider=coder_provider, timeout_sec=420, model=coder_model, - extra_args=coder_extra) if args.allow_codegen else None), + cli_config=replace(coder_cfg, timeout_sec=420) if args.allow_codegen else None, allow_codegen=args.allow_codegen, run_context=ctx, max_validation_cases=args.fix_validation_cases, alpha=0.05, allow_adapted_paper_methods=args.allow_adapted_paper_methods, @@ -610,42 +562,189 @@ def run(args, task: T.Task, resolved: Resolved) -> int: else (method_names() if args.registered_repairs_only else None)) ), max_repair_rounds=max(1, args.fix_repair_rounds), - **({"max_judge_candidates": 1} if args.code_only else {}), exec_timeout_sec=args.fix_exec_timeout, prewritten_code=prewritten_code, concurrency=getattr(args, "concurrency", 1), - floor_candidates=() if agentic else ("self_consistency_5",), + floor_candidates=() if _is_agentic(args) else ("self_consistency_5",), progress_callback=_print_fix_progress, **fix_kwargs, ) - explorer = None - if args.explore: - from evalrx.agent_runtime.sandbox import ExperimentSandbox - from evalrx.analysis import ExploratoryAnalysisAgent - - explorer = ExploratoryAnalysisAgent( - cli_config=coder_cfg, - sandbox=ExperimentSandbox( - workdir=ctx.explore_dir / "sandbox", - cleanup=False, - ), - timeout_sec=900, max_attempts=3, + + +def _explorer(coder_cfg, ctx): + from evalrx.agent_runtime.sandbox import ExperimentSandbox + from evalrx.analysis import ExploratoryAnalysisAgent + + return ExploratoryAnalysisAgent( + cli_config=coder_cfg, + sandbox=ExperimentSandbox( + workdir=ctx.explore_dir / "sandbox", + cleanup=False, + ), + timeout_sec=900, max_attempts=3, + ) + + +def _run_m5(loop, report, cases, args) -> None: + """M5 on the best hypothesis, unless the flags make it pointless. + + No M4-verified hypothesis still gets M5 + a fix attempt on the best + unverified leads (the candidate validation on CONFIRM is the gate). + An explicitly pre-registered fix is already the experiment the + caller asked to validate. Running an unrelated M5 surgery first is + pure latency and can contend for the same GPU; it cannot influence + the frozen candidate or its EXPLORE/CONFIRM verdict. + """ + if args.skip_m5: + print("M5: skipped by --skip-m5 (tiered fix search remains enabled)") + elif args.fix_candidate or args.code_only or args.registered_repairs_only: + requested = ( + args.fix_candidate or ("coded_pipeline" if args.code_only else "registered methods") + ) + print(f"M5: skipped for pre-registered fix scope {requested!r}") + else: + proposal = loop.run_m5(report, cases, allow_unverified=True) + if proposal is not None: + tag = "verified" if report.verified_hypotheses else "UNVERIFIED (best lead)" + print(f"M5 experiment on the {tag} hypothesis: status={proposal.status}") + else: + print("M5: no hypothesis to experiment on") + + +def _run_fix(loop, run_dir: Path, ctx, report, cases, args, fix_tier: str) -> dict[str, Any]: + """Run the fix ladder; the ``fix`` entry of summary.json.""" + outcome = run_fix_isolated(loop, run_dir, ctx, report, cases, max_tier=fix_tier, + auto_escalate=args.auto_escalate, allow_unverified=True) + attempted = [] + for validation in outcome.attempted: + effect = "n/a" if validation.effect is None else f"{validation.effect:+.3f}" + print(f"Fix [{validation.candidate.tier.label}] {validation.candidate.name}: " + f"fixed={validation.fixed}, repairs={validation.n_fixed}, " + f"breaks={validation.n_broken}, effect={effect}") + attempted.append({"tier": validation.candidate.tier.label, "name": validation.candidate.name, + "fixed": bool(validation.fixed), "repairs": validation.n_fixed, + "breaks": validation.n_broken, "effect": validation.effect}) + return {"recommendation": str(getattr(outcome, "recommendation", "") or ""), + "attempted": attempted} + + +def run(args, task: T.Task, resolved: Resolved) -> int: + """Run one cell: Stage 0 baseline, the diagnosis loop, then M5 and the fix ladder. + + Returns the process exit code (2 when the diagnosis itself failed). + """ + manifest = ensure_manifest(task, args) + # Fail fast: the held-out validation manifest must exist before any model + # or judge is loaded. + val_manifest = ensure_val_manifest(task, args) if args.held_out else None + if args.download_only: + return 0 + limit = args.limit if args.limit is not None else task.default_limit + candidates, rows = T.build_cases(task, manifest, limit) + run_dir = run_dir_for(args, task) + run_dir.mkdir(parents=True, exist_ok=True) + label = model_label(resolved) + print(f"[model] {label}; backend={resolved.backend}; benchmark={task.title}; n={len(candidates)}") + + judge = None + coder_provider: Any = None + coder_model: Any = None + coder_extra: Any = None + if not args.baseline_only: + judge, coder_provider, coder_model, coder_extra = build_judge(args) + + model, gen_kwargs, spec = _load_target(resolved, args, task, run_dir) + protocol = task.protocol(label) + raw_model = model + model, deployed_spec = _deploy_baseline_spec(model, getattr(args, "baseline_spec", "")) + + ctx = None + discovery_model = model + if not args.baseline_only: + from evalrx.eval_agent import RunContext + from evalrx.eval_agent.model_instrumentation import InstrumentedModel + + # Create the run log before Stage-0 so each discovery request is durable + # as it happens, including its real latency and any transport error. + ctx = RunContext( + # narrate: aligned live M1-M5 lines ("M1 probe ···· cycle 0 · ..."), + # same style as examples/m1_m5/qwen_loop_claude, instead of verbose's + # raw "[M1] probe cycle=0" one-liners. + run_dir / "logs", narrate=True, + config=_run_config(args, task, resolved, spec, gen_kwargs, manifest, rows, len(candidates)), + ) + candidates = list(candidates) + discovery_model = InstrumentedModel( + model, ctx.logger, cycle=-1, analyzer="case_discovery", + case_prompts={c.inputs.prompt: c.id for c in candidates}, + batch_case_ids=[c.id for c in candidates], ) - loop_class = VLDiagnoseLoop - loop_kwargs = {} - if agentic: - from evalrx.eval_agent.agentic import AgenticDiagnoseLoop - - loop_class = AgenticDiagnoseLoop - loop_kwargs = dict(judge=judge, max_actions=args.max_actions, - registry_factory=_benchmark_agentic_registry) - loop = loop_class( - **loop_kwargs, + + discovery, elapsed = _discover(discovery_model, candidates, protocol, gen_kwargs, args) + cases = discovery.cases + if ctx is not None: + ctx.config["n_cases"] = len(cases) + accuracy = discovery.n_pass / max(1, len(cases)) + baseline = { + "model": args.model, "spec": spec.key, "hf_repo": spec.hf_repo, "backend": resolved.backend, + "dataset": task.name, "task": task.kind, "n": len(cases), + "n_pass": discovery.n_pass, "n_fail": discovery.n_fail, "n_unknown": discovery.n_unknown, + "accuracy": round(accuracy, 4), "seconds": round(elapsed, 1), + "generation_kwargs": gen_kwargs, "enable_thinking": bool(args.enable_thinking), + "manifest": str(manifest), "limit": limit, + "cases": _case_labels(cases), + } + version = _api_model_version(model) + if version: + baseline["model_version"] = version + print(f"[model] served version: {version}") + (run_dir / "baseline.json").write_text(json.dumps(baseline, indent=2, ensure_ascii=False) + "\n", + encoding="utf-8") + print(f"Baseline: PASS={discovery.n_pass}, FAIL={discovery.n_fail}, UNKNOWN={discovery.n_unknown}, " + f"accuracy={accuracy:.3f} ({elapsed:.0f}s, {elapsed / max(1, len(cases)):.1f}s/case)") + if task.modality == "llm" and not 0.15 <= accuracy <= 0.85: + print(" NOTE accuracy is outside the usable band [0.15, 0.85]: M2 has little to contrast " + "and the paired tests downstream are short of power (results valid, weak)") + _mark_short_answers_stopped(task, cases) + if ctx is None: # --baseline-only + print(f"Done (baseline only). {run_dir / 'baseline.json'}") + return 0 + if not discovery.has_m4_groups: + raise SystemExit("M4 needs both PASS and FAIL cases; adjust --limit / --seed") + + val_cases = None + if val_manifest is not None: + val_cases = _label_validation_set(model, val_manifest, protocol, gen_kwargs, args, task, spec, run_dir) + ctx.config["val_manifest"] = str(val_manifest) + ctx.config["n_val_cases"] = len(val_cases) + + from evalrx.eval_agent import ( + CliAgentConfig, + DiagnosisAgent, + HypothesisTester, + SurgeryAgent, + VLDiagnoseLoop, + ) + from evalrx.eval_agent.stages.experiment_writer import ExperimentWriterConfig + + coder_cfg = CliAgentConfig(provider=coder_provider, model=coder_model, timeout_sec=900, + extra_args=coder_extra) + policy = None + if _is_agentic(args): + from evalrx.eval_agent.agentic import JudgePolicy + + policy = JudgePolicy(judge, max_actions=args.max_actions, + registry_factory=_benchmark_agentic_registry) + loop = VLDiagnoseLoop( + policy=policy, diagnosis_retries=1, - model=model, protocol=protocol, probe_agent=probe_agent, stats_agent=stats_agent, + model=model, protocol=protocol, + probe_agent=_probe_agent(args, task, resolved, model, judge, coder_cfg, ctx.config), + stats_agent=_stats_agent(args, task, judge, coder_cfg, ctx), diagnosis_agent=DiagnosisAgent(judge=judge), hypothesis_tester=HypothesisTester(judge=judge, min_effect=0.05), - fix_agent=fix_agent, max_cycles=args.max_cycles, run_logger=ctx.logger, + fix_agent=_fix_agent(args, task, judge, coder_cfg, gen_kwargs, ctx, raw_model, deployed_spec), + max_cycles=args.max_cycles, run_logger=ctx.logger, confirm_split=float(args.confirm_split), confirm_split_seed=20260818, # Default: the 50/50 explore/confirm design — M1-M4 work on EXPLORE # (M4 in-cycle), the fix ladder searches on EXPLORE, and CONFIRM is @@ -659,13 +758,14 @@ def run(args, task: T.Task, resolved: Resolved) -> int: m4_holdout=bool(args.held_out), val_data=val_cases, surgery_agent=SurgeryAgent(judge=judge, writer_config=ExperimentWriterConfig(cli_agent=coder_cfg)), - explorer=explorer, + explorer=_explorer(coder_cfg, ctx) if args.explore else None, explore_dir=ctx.explore_dir, # RunContext(narrate=True) above owns the console; verbose would pipe # the stages' logger.info() stream over the aligned narration. verbose=False, ) - print(f"\n{'=' * 64}\n{loop_class.__name__} model={args.model} max_cycles={args.max_cycles}\n{'=' * 64}") + mode = "VLDiagnoseLoop + JudgePolicy" if policy is not None else "VLDiagnoseLoop" + print(f"\n{'=' * 64}\n{mode} model={args.model} max_cycles={args.max_cycles}\n{'=' * 64}") report = loop.run(cases) discovery_rows = [{ "id": c.id, "prompt": c.inputs.prompt, "expected": c.expected, @@ -687,39 +787,8 @@ def run(args, task: T.Task, resolved: Resolved) -> int: print(f"[fix] --fix-tier {args.fix_tier} clamped to {fix_tier}: the {resolved.backend} backend " "exposes no model internals (L3a/L3b need the white-box executors)") if not args.skip_fix: - # No M4-verified hypothesis still gets M5 + a fix attempt on the best - # unverified leads (the candidate validation on CONFIRM is the gate). - # An explicitly pre-registered fix is already the experiment the - # caller asked to validate. Running an unrelated M5 surgery first is - # pure latency and can contend for the same GPU; it cannot influence - # the frozen candidate or its EXPLORE/CONFIRM verdict. - if args.skip_m5: - print("M5: skipped by --skip-m5 (tiered fix search remains enabled)") - elif args.fix_candidate or args.code_only or args.registered_repairs_only: - requested = ( - args.fix_candidate or ("coded_pipeline" if args.code_only else "registered methods") - ) - print(f"M5: skipped for pre-registered fix scope {requested!r}") - else: - proposal = loop.run_m5(report, cases, allow_unverified=True) - if proposal is not None: - tag = "verified" if report.verified_hypotheses else "UNVERIFIED (best lead)" - print(f"M5 experiment on the {tag} hypothesis: status={proposal.status}") - else: - print("M5: no hypothesis to experiment on") - outcome = run_fix_isolated(loop, run_dir, ctx, report, cases, max_tier=fix_tier, - auto_escalate=args.auto_escalate, allow_unverified=True) - attempted = [] - for validation in outcome.attempted: - effect = "n/a" if validation.effect is None else f"{validation.effect:+.3f}" - print(f"Fix [{validation.candidate.tier.label}] {validation.candidate.name}: " - f"fixed={validation.fixed}, repairs={validation.n_fixed}, " - f"breaks={validation.n_broken}, effect={effect}") - attempted.append({"tier": validation.candidate.tier.label, "name": validation.candidate.name, - "fixed": bool(validation.fixed), "repairs": validation.n_fixed, - "breaks": validation.n_broken, "effect": validation.effect}) - summary["fix"] = {"recommendation": str(getattr(outcome, "recommendation", "") or ""), - "attempted": attempted} + _run_m5(loop, report, cases, args) + summary["fix"] = _run_fix(loop, run_dir, ctx, report, cases, args, fix_tier) ctx.finalize() (run_dir / "summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") print(f"Done. Tidy M1-M5 logs: {ctx.root.resolve()}") diff --git a/evalrx/benchmark/tasks/audiocaps_hallu.py b/evalrx/benchmark/tasks/audiocaps_hallu.py index 360d9b90..815f8faf 100644 --- a/evalrx/benchmark/tasks/audiocaps_hallu.py +++ b/evalrx/benchmark/tasks/audiocaps_hallu.py @@ -59,7 +59,8 @@ def download(out_dir: Path, limit: int = 300, seed: int = 20260814, scan_rows: i random.Random(seed).shuffle(order) order = order[: min(scan_rows, q_table.num_rows)] target = limit + max(0, val_limit) - rows, n_nomatch, n_dur = [], 0, 0 + rows: list[dict] = [] + n_nomatch, n_dur = 0, 0 seen: set[str] = set() for row_index in order: if len(rows) >= target: diff --git a/evalrx/benchmark/tasks/llm/fetch.py b/evalrx/benchmark/tasks/llm/fetch.py index a3296d10..6d0c635b 100644 --- a/evalrx/benchmark/tasks/llm/fetch.py +++ b/evalrx/benchmark/tasks/llm/fetch.py @@ -112,7 +112,9 @@ def _draw_windows(spec: Spec, want: int, seed: int, n_windows: Optional[int], keep = spec.row_filter or (lambda row: True) #: windows that came back unknown after all retries — reported alongside the #: band so a thin sample is never read as a measured one - fetch_rows.last_failed_windows = 0 + # A diagnostic counter callers read off the function (band_locate.py); mypy + # cannot model attributes set on a function. + fetch_rows.last_failed_windows = 0 # type: ignore[attr-defined] rng = random.Random(seed) # over-fetch: the adapter drops ungradable rows on top of the filter target = want * max(1, spec.fetch_multiplier) @@ -147,7 +149,7 @@ def _draw_windows(spec: Spec, want: int, seed: int, n_windows: Optional[int], seen_offsets.add(offset) page = get_page(offset, min(per_window, total - offset)) if page is None: - fetch_rows.last_failed_windows += 1 + fetch_rows.last_failed_windows += 1 # type: ignore[attr-defined] continue for key, row in page: if key is None: diff --git a/evalrx/benchmark/tasks/mmau.py b/evalrx/benchmark/tasks/mmau.py index bd45d0e6..a5b76604 100644 --- a/evalrx/benchmark/tasks/mmau.py +++ b/evalrx/benchmark/tasks/mmau.py @@ -58,7 +58,8 @@ def download(out_dir: Path, limit: int = 256, seed: int = 20260814, scan_rows: i random.Random(seed).shuffle(order) order = order[: min(scan_rows, table.num_rows)] target = limit + max(0, val_limit) - rows, n_dur, n_bad = [], 0, 0 + rows: list[dict] = [] + n_dur, n_bad = 0, 0 for row_index in order: if len(rows) >= target: break diff --git a/evalrx/benchmark/tasks/mmsu.py b/evalrx/benchmark/tasks/mmsu.py index ec6f287d..54d40549 100644 --- a/evalrx/benchmark/tasks/mmsu.py +++ b/evalrx/benchmark/tasks/mmsu.py @@ -103,7 +103,8 @@ def download(out_dir: Path, limit: int = 256, seed: int = 20260814) -> dict: random.Random(seed).shuffle(order) requested = len(order) if limit <= 0 else min(limit, len(order)) - rows, n_dur, n_bad, n_noaudio, scanned = [], 0, 0, 0, 0 + rows: list[dict] = [] + n_dur, n_bad, n_noaudio, scanned = 0, 0, 0, 0 for order_index in order: if len(rows) >= requested: break diff --git a/evalrx/cli.py b/evalrx/cli.py index 62e9d1c8..ef746afa 100755 --- a/evalrx/cli.py +++ b/evalrx/cli.py @@ -4,27 +4,12 @@ import argparse from pathlib import Path +from typing import overload from evalrx.analysis.explore_run import run_explore from evalrx.analysis.run_codebase import run_codebase_cli -def serve_report( - run_dir: str | Path | None, - *, - port: int, - no_audio: bool = False, - open_browser: bool = True, - block: bool = True, - runs_root: str | Path | None = None, -) -> int: - """CLI seam for the dynamic UI (signature kept for compatibility/tests).""" - del no_audio, block - from evalrx.reporting.server import serve_dynamic_report - - return serve_dynamic_report(run_dir, port=port, open_browser=open_browser, runs_root=runs_root) - - def _langfuse_cache(trace_id: str) -> Path: """Stable local cache for a Langfuse-backed static report, not run storage.""" safe_id = "".join(char for char in trace_id if char.isalnum() or char in "-_") @@ -33,6 +18,10 @@ def _langfuse_cache(trace_id: str) -> Path: return Path(".evalrx-cache") / safe_id +@overload +def _resolve_report_source(source: str, trace_id: str | None, run_dir: str) -> str: ... +@overload +def _resolve_report_source(source: str, trace_id: str | None, run_dir: str | None) -> str | None: ... def _resolve_report_source(source: str, trace_id: str | None, run_dir: str | None) -> str | None: if source == "auto": if trace_id: @@ -52,25 +41,26 @@ def _resolve_report_source(source: str, trace_id: str | None, run_dir: str | Non return str(LangfuseRunSource().materialize(trace_id, _langfuse_cache(trace_id))) -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser( - prog="evalrx", - description="EvalRX command-line interface.", - ) - parser.add_argument( - "-v", "--verbose", - action="store_true", - help="Print evalrx' internal stage-by-stage narration " - "(evalrx.enable_console_logging()) to stdout. Applies to any subcommand.", - ) - sub = parser.add_subparsers(dest="command") +# Each command is a pair: ``_add_`` declares its arguments and names +# ``_`` as its handler, which runs it and returns the exit code. +# Handlers import what they run, so ``evalrx --help`` stays light and a +# command whose extra is not installed fails only when it is used. +def _add_run(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None: from evalrx.benchmark.run import build_parser as benchmark_parser benchmark_parser(sub.add_parser( "run", help="Evaluate a model and run the M1–M5 diagnosis and repair workflow.", - )) + )).set_defaults(handler=_run) + +def _run(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int: + from evalrx.benchmark.run import run_args + + return run_args(args) + + +def _add_explore(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None: explore = sub.add_parser( "explore", help="Run a single-shot exploratory analysis over a results directory.", @@ -157,7 +147,60 @@ def main(argv: list[str] | None = None) -> int: ) explore.add_argument("--thread-id", default="", help=argparse.SUPPRESS) explore.add_argument("--turn-id", default="", help=argparse.SUPPRESS) + explore.set_defaults(handler=_explore) + +def _explore(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int: + if not args.path: + parser.error("evalrx explore requires a results path") + from evalrx.analysis.narration import MultiSink, TerminalNarrator + + event_sink = None + if args.progress_path: + from evalrx.analysis.workbench import EventSink + + event_sink = EventSink( + args.progress_path, + thread_id=args.thread_id or "standalone", + turn_id=args.turn_id or "explore", + ) + event_sink.emit("job", "started", "Analysis worker started") + # "job" bookkeeping above/below stays workbench-only (event_sink), not + # narrated -- it wraps the whole process rather than one M-stage. + progress_sink = MultiSink(TerminalNarrator() if args.narrate else None, event_sink) or None + code = run_explore( + args.path, + question=args.question, + out=args.out, + coder_provider=args.coder_provider, + coder_model=args.coder_model, + coder_binary=args.coder_binary, + max_rows=args.max_rows, + max_files=args.max_files, + include_tool_calls=args.include_tool_calls, + timeout_sec=args.timeout_sec, + max_attempts=args.max_attempts, + open_report=args.serve_report, + skills=args.skill, + allow_skills=args.allow_skills, + use_bundled_skills=args.use_bundled_skills, + outcome_col=args.outcome_col, + propose_hypotheses=args.propose_hypotheses, + holdout_frac=args.holdout_frac, + holdout_seed=args.holdout_seed, + holdout_confirm=args.holdout_confirm, + judge_model=args.judge_model, + progress_sink=progress_sink, + ) + if event_sink is not None: + event_sink.emit( + "job", "completed" if code == 0 else "failed", + "Analysis worker completed" if code == 0 else "Analysis worker failed", + ) + return code + + +def _add_run_codebase(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None: run_codebase = sub.add_parser( "run-codebase", help="Run a user's evaluation codebase, then explore the results it produces.", @@ -199,8 +242,31 @@ def main(argv: list[str] | None = None) -> int: "--no-narrate", dest="narrate", action="store_false", default=True, help="Do not print live per-stage narration (run/M2/M3/... lines) to the terminal.", ) + run_codebase.set_defaults(handler=_run_codebase) + + +def _run_codebase(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int: + from evalrx.analysis.explorer import RECORDS_FILENAME + from evalrx.analysis.narration import TerminalNarrator + + return run_codebase_cli( + args.path, + out=args.out, + coder_provider=args.coder_provider, + coder_model=args.coder_model, + coder_binary=args.coder_binary, + outcome_col=args.outcome_col, + records_name=args.records_name or RECORDS_FILENAME, + timeout_sec=args.timeout_sec, + max_attempts=args.max_attempts, + question=args.question, + analyze=args.analyze, + open_report=args.serve_report, + progress_sink=TerminalNarrator() if args.narrate else None, + ) +def _add_serve(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None: serve = sub.add_parser( "serve", help="Publish (if needed) and serve the dynamic completed-run UI.", @@ -208,35 +274,86 @@ def main(argv: list[str] | None = None) -> int: ) serve.add_argument("run_dir", nargs="?", default=None, help="Run directory. Omit to start empty and drop a zipped run on the page.") serve.add_argument("--port", type=int, default=8501, help="Loopback port (default: 8501).") - serve.add_argument("--no-audio", action="store_true", help=argparse.SUPPRESS) serve.add_argument("--no-browser", action="store_true", help="Do not open a browser automatically.") serve.add_argument("--source", choices=["auto", "local", "langfuse"], default="auto", help="Run data source (default: Langfuse when --trace-id is set, otherwise local).") serve.add_argument("--trace-id", default=None, help="Langfuse trace id (required for --source langfuse).") serve.add_argument("--runs-root", default=None, help="Where the runs panel looks for other experiments (default: run_dir's parent, or the current directory).") + serve.set_defaults(handler=_serve) + + +def _serve(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int: + try: + source_dir = _resolve_report_source(args.source, args.trace_id, args.run_dir) + except (ImportError, LookupError, RuntimeError, ValueError) as exc: + parser.error(str(exc)) + from evalrx.reporting.server import serve_dynamic_report + + try: + return serve_dynamic_report( + source_dir, port=args.port, open_browser=not args.no_browser, runs_root=args.runs_root, + ) + except ImportError as exc: # the [ui] extra is not installed + parser.error(str(exc)) + +def _add_report(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None: report_cmd = sub.add_parser( "report", help="Explicitly export a portable self-contained HTML snapshot.", description="Uses the same React/json-render layout as `serve`; the dynamic UI remains the primary experience.", ) report_cmd.add_argument("run_dir", nargs="?", default="outputs", help="Run directory holding run.json/M1..M5, or logs/") - report_cmd.add_argument("--example-dir", default=None, help="Root holding data/ manifest.") report_cmd.add_argument("--out", "-o", default=None, help="Output HTML path (default: /report.html).") report_cmd.add_argument("--no-audio", action="store_true", help="Skip audio transcoding.") report_cmd.add_argument("--embed-media", choices=["representative", "all", "none"], default="representative", help="Media to inline in the portable export (default: representative).") report_cmd.add_argument("--audio-bitrate", default="48k", help="Transcode inlined lossless audio to mono MP3 at this bitrate via ffmpeg (default: 48k; 'none' = inline the original bytes).") report_cmd.add_argument("--source", choices=["local", "langfuse"], default="local", help="Run data source.") report_cmd.add_argument("--trace-id", default=None, help="Langfuse trace id (required for --source langfuse).") + report_cmd.set_defaults(handler=_report) + + +def _report(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int: + from evalrx.reporting.static_export import export_static_report + + try: + source_dir = _resolve_report_source(args.source, args.trace_id, args.run_dir) + except (ImportError, LookupError, RuntimeError, ValueError) as exc: + parser.error(str(exc)) + + export_static_report( + run_dir=source_dir, + out_path=args.out, + embed_media="none" if args.no_audio else args.embed_media, + audio_bitrate=None if str(getattr(args, "audio_bitrate", "48k")).lower() == "none" else args.audio_bitrate, + ) + return 0 + +def _add_publish_report(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None: publish_cmd = sub.add_parser( "publish-report", help="Compile and cache ReportData plus a validated json-render layout.", ) publish_cmd.add_argument("run_dir", nargs="?", default="outputs", help="Completed run directory.") - publish_cmd.add_argument("--example-dir", default=None, help="Optional benchmark/example root for legacy runs.") publish_cmd.add_argument("--source", choices=["auto", "local", "langfuse"], default="auto") publish_cmd.add_argument("--trace-id", default=None) + publish_cmd.set_defaults(handler=_publish_report) + + +def _publish_report(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int: + from evalrx.reporting.dynamic import publish_report + + try: + source_dir = _resolve_report_source(args.source, args.trace_id, args.run_dir) + published = publish_report(source_dir) + except (ImportError, LookupError, RuntimeError, ValueError) as exc: + parser.error(str(exc)) + print(f"Published report data: {published.data_path}") + print(f"Published report layout: {published.spec_path} ({published.generated_by})") + return 0 + +def _add_export_langfuse(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None: langfuse_cmd = sub.add_parser( "export-langfuse", help="Export a diagnostic run to Langfuse trace JSON format or sync live.", @@ -245,153 +362,68 @@ def main(argv: list[str] | None = None) -> int: langfuse_cmd.add_argument("run_dir", nargs="?", default="outputs", help="Run directory.") langfuse_cmd.add_argument("--out", "-o", default=None, help="Output JSON path.") langfuse_cmd.add_argument("--sync", action="store_true", help="Sync live to Langfuse server.") + langfuse_cmd.set_defaults(handler=_export_langfuse) + + +def _export_langfuse(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int: + from evalrx.observability import export_to_langfuse_bundle, sync_to_langfuse_live + + if args.sync: + return 0 if sync_to_langfuse_live(args.run_dir) else 1 + out_p = args.out or (Path(args.run_dir) / "langfuse_trace.json") + export_to_langfuse_bundle(args.run_dir, out_p) + return 0 + +def _add_backfill_langfuse(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None: backfill_langfuse = sub.add_parser( "backfill-langfuse", help="Queue an existing run (run.json/M1..M5) for reliable Langfuse ingestion.", ) backfill_langfuse.add_argument("run_dir", help="Run directory holding run.json/M1..M5, or logs/.") backfill_langfuse.add_argument("--dry-run", action="store_true", help="Inspect the run without writing an outbox.") + backfill_langfuse.set_defaults(handler=_backfill_langfuse) + + +def _backfill_langfuse(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int: + from evalrx.observability import backfill_run_to_langfuse + + summary = backfill_run_to_langfuse(args.run_dir, dry_run=args.dry_run) + print( + "Langfuse backfill: " + f"trace={summary['trace_id']} events={summary['events']} " + f"published={summary['published']} pending={summary['pending']}" + ) + return 0 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + prog="evalrx", + description="EvalRX command-line interface.", + ) + parser.add_argument( + "-v", "--verbose", + action="store_true", + help="Print evalrx' internal stage-by-stage narration " + "(evalrx.enable_console_logging()) to stdout. Applies to any subcommand.", + ) + sub = parser.add_subparsers(dest="command") + for add_command in ( + _add_run, _add_explore, _add_run_codebase, _add_serve, _add_report, + _add_publish_report, _add_export_langfuse, _add_backfill_langfuse, + ): + add_command(sub) args = parser.parse_args(argv) if args.verbose: from evalrx.logging_utils import enable_console_logging enable_console_logging() - if args.command == "run": - from evalrx.benchmark.run import run_args - - return run_args(args) - if args.command == "explore": - if not args.path: - parser.error("evalrx explore requires a results path") - from evalrx.analysis.narration import MultiSink, TerminalNarrator - - event_sink = None - if args.progress_path: - from evalrx.analysis.workbench import EventSink - - event_sink = EventSink( - args.progress_path, - thread_id=args.thread_id or "standalone", - turn_id=args.turn_id or "explore", - ) - event_sink.emit("job", "started", "Analysis worker started") - # "job" bookkeeping above/below stays workbench-only (event_sink), not - # narrated -- it wraps the whole process rather than one M-stage. - progress_sink = MultiSink(TerminalNarrator() if args.narrate else None, event_sink) or None - code = run_explore( - args.path, - question=args.question, - out=args.out, - coder_provider=args.coder_provider, - coder_model=args.coder_model, - coder_binary=args.coder_binary, - max_rows=args.max_rows, - max_files=args.max_files, - include_tool_calls=args.include_tool_calls, - timeout_sec=args.timeout_sec, - max_attempts=args.max_attempts, - open_report=args.serve_report, - skills=args.skill, - allow_skills=args.allow_skills, - use_bundled_skills=args.use_bundled_skills, - outcome_col=args.outcome_col, - propose_hypotheses=args.propose_hypotheses, - holdout_frac=args.holdout_frac, - holdout_seed=args.holdout_seed, - holdout_confirm=args.holdout_confirm, - judge_model=args.judge_model, - progress_sink=progress_sink, - ) - if event_sink is not None: - event_sink.emit( - "job", "completed" if code == 0 else "failed", - "Analysis worker completed" if code == 0 else "Analysis worker failed", - ) - return code - if args.command == "run-codebase": - from evalrx.analysis.explorer import RECORDS_FILENAME - from evalrx.analysis.narration import TerminalNarrator - - return run_codebase_cli( - args.path, - out=args.out, - coder_provider=args.coder_provider, - coder_model=args.coder_model, - coder_binary=args.coder_binary, - outcome_col=args.outcome_col, - records_name=args.records_name or RECORDS_FILENAME, - timeout_sec=args.timeout_sec, - max_attempts=args.max_attempts, - question=args.question, - analyze=args.analyze, - open_report=args.serve_report, - progress_sink=TerminalNarrator() if args.narrate else None, - ) - if args.command == "serve": - try: - source_dir = _resolve_report_source(args.source, args.trace_id, args.run_dir) - except (ImportError, LookupError, RuntimeError, ValueError) as exc: - parser.error(str(exc)) - try: - return serve_report( - source_dir, port=args.port, no_audio=args.no_audio, - open_browser=not args.no_browser, runs_root=args.runs_root, - ) - except ImportError as exc: - parser.error(str(exc)) - if args.command == "publish-report": - from evalrx.reporting.dynamic import publish_report - - try: - source_dir = _resolve_report_source(args.source, args.trace_id, args.run_dir) - published = publish_report(source_dir, example_dir=args.example_dir) - except (ImportError, LookupError, RuntimeError, ValueError) as exc: - parser.error(str(exc)) - print(f"Published report data: {published.data_path}") - print(f"Published report layout: {published.spec_path} ({published.generated_by})") - return 0 - if args.command == "report": - from evalrx.reporting.static_export import export_static_report - - try: - source_dir = _resolve_report_source(args.source, args.trace_id, args.run_dir) - except (ImportError, LookupError, RuntimeError, ValueError) as exc: - parser.error(str(exc)) - - export_static_report( - run_dir=source_dir, - example_dir=args.example_dir, - out_path=args.out, - embed_media="none" if args.no_audio else args.embed_media, - audio_bitrate=None if str(getattr(args, "audio_bitrate", "48k")).lower() == "none" else args.audio_bitrate, - ) - return 0 - if args.command == "export-langfuse": - from evalrx.reporting.langfuse_exporter import ( - export_to_langfuse_bundle, - sync_to_langfuse_live, - ) - - if args.sync: - return 0 if sync_to_langfuse_live(args.run_dir) else 1 - out_p = args.out or (Path(args.run_dir) / "langfuse_trace.json") - export_to_langfuse_bundle(args.run_dir, out_p) - return 0 - if args.command == "backfill-langfuse": - from evalrx.observability import backfill_run_to_langfuse - - summary = backfill_run_to_langfuse(args.run_dir, dry_run=args.dry_run) - print( - "Langfuse backfill: " - f"trace={summary['trace_id']} events={summary['events']} " - f"published={summary['published']} pending={summary['pending']}" - ) + if args.command is None: + parser.print_help() return 0 - - parser.print_help() - return 0 + return args.handler(args, parser) if __name__ == "__main__": # pragma: no cover diff --git a/evalrx/config.py b/evalrx/config.py index 2f5cfbf8..251be5f5 100755 --- a/evalrx/config.py +++ b/evalrx/config.py @@ -6,20 +6,20 @@ from pathlib import Path from typing import Any -import yaml +import yaml # type: ignore[import-untyped] # PyYAML ships no stubs; types-PyYAML not a dependency @dataclass class ModelConfig: """Declarative model selection — resolved to a spec + backend at load time. - ``name`` is a :mod:`evalrx.specs` key (e.g. ``"qwen2.5-7b-instruct"``) or a - legacy alias (e.g. ``"qwen"``); resolution happens in - :func:`evalrx.models.load_model` via ``compose(spec, backend)``. No + ``name`` is a :mod:`evalrx.specs` key (e.g. ``"qwen2.5-7b-instruct"``); + resolution happens in :func:`evalrx.models.load_model` via + ``compose(spec, backend)``. No checkpoint is baked here — identity lives in the spec. Attributes: - name: Spec key or legacy alias. + name: Spec key. checkpoint: Optional override of the spec's ``hf_repo``. device: Runtime device (``"auto"``, ``"cuda"``, ``"cpu"``, ``"cuda:N"``). dtype: Runtime dtype (``"bfloat16"``, ``"float16"``, ``"float32"``). @@ -47,7 +47,7 @@ def load_config(path: str | Path) -> AnalysisConfig: Supports both short form:: - model: qwen2.5-7b-instruct # spec key (or a legacy alias like "qwen") + model: qwen2.5-7b-instruct # spec key analysis: attention and full form:: diff --git a/evalrx/contract/__init__.py b/evalrx/contract/__init__.py index c3cfa8e9..6ad11d97 100644 --- a/evalrx/contract/__init__.py +++ b/evalrx/contract/__init__.py @@ -43,6 +43,8 @@ from typing import NamedTuple +from pydantic import BaseModel + from evalrx.contract.common import ( SCHEMA_VERSION, ArtifactRef, @@ -110,8 +112,8 @@ class StageContract(NamedTuple): stage: str purpose: str - input: type - output: type + input: type[BaseModel] + output: type[BaseModel] optional: bool = False diff --git a/evalrx/contract/common.py b/evalrx/contract/common.py index 2eaee6ee..afcb63db 100644 --- a/evalrx/contract/common.py +++ b/evalrx/contract/common.py @@ -242,20 +242,10 @@ def modalities(self) -> set[Modality]: return present -#: Legacy role names this contract shipped before it was aligned to -#: :class:`evalrx.core.case.StepRole`. Mapped rather than rejected so a -#: trajectory written by an older producer still validates. -_LEGACY_STEP_ROLES = {"env": "tool", "critic": "verifier"} - - class StepWire(OpenWireModel): """One step of an agent trajectory. - ``role`` is exactly :class:`evalrx.core.case.StepRole`. It was not, and - the divergence was not cosmetic: ``planner`` / ``verifier`` / ``memory`` / - ``system`` are values the producer emits every multi-agent run, and every one - of them failed validation here, while ``env`` / ``critic`` named steps no - producer can emit. + ``role`` is exactly :class:`evalrx.core.case.StepRole`. """ idx: int @@ -273,9 +263,7 @@ class StepWire(OpenWireModel): @field_validator("role", mode="before") @classmethod - def _map_legacy_role(cls, v: Any) -> Any: - if isinstance(v, str): - return _LEGACY_STEP_ROLES.get(v, v) + def _role_value(cls, v: Any) -> Any: return getattr(v, "value", v) @@ -406,6 +394,9 @@ def is_broken(self) -> bool: return self.n_left > 0 and self.n_matched == 0 +StageName = Literal["pre_m1", "m1", "explore", "m2", "m3", "m5_surgery", "m5_fix", "m4"] + + class StageStatus(WireModel): """Terminal state of one stage in one cycle. @@ -414,7 +405,7 @@ class StageStatus(WireModel): has for whether to trust the absence of a result. """ - stage: Literal["pre_m1", "m1", "explore", "m2", "m3", "m5_surgery", "m5_fix", "m4"] + stage: StageName state: StageState cycle: int = Field(description="Normal cycles start at 0; the post-loop fix uses -1.") reason: str | None = Field( diff --git a/evalrx/contract/emit.py b/evalrx/contract/emit.py index aa29ad2f..f2c81805 100644 --- a/evalrx/contract/emit.py +++ b/evalrx/contract/emit.py @@ -5,7 +5,7 @@ failure it was written to prevent, one level up. This module is the missing half: every M1-M5 stage runs its result through the matching wire model and writes the validated JSON under ``/contract/``, so a frontend reads ONE -shape per stage instead of re-deriving it from ``run_log.jsonl`` with defensive +shape per stage instead of re-deriving it from the run log with defensive ``.get(x) or y`` chains. Two rules govern everything here. @@ -29,13 +29,14 @@ import logging from datetime import datetime, timezone from pathlib import Path -from typing import Any, Callable, Iterable +from typing import Any, Callable, Iterable, cast from evalrx.contract.common import ( SCHEMA_VERSION, CaseBatchRef, CaseBatchWire, FailureCaseWire, + StageName, StageState, StageStatus, WireModel, @@ -57,6 +58,7 @@ ) from evalrx.contract.m3 import DiagnosisOutput, HypothesisWire from evalrx.contract.m4 import ( + EvidenceSource, HypothesisTestOutput, HypothesisTestResultWire, TestEvidence, @@ -95,7 +97,7 @@ def _scalar(value: Any) -> bool: # --------------------------------------------------------------------------- def envelope( - stage: str, *, trace_id: str, cycle: int = 0, + stage: StageName, *, trace_id: str, cycle: int = 0, state: StageState = StageState.SUCCEEDED, reason: str | None = None, duration_sec: float | None = None, ) -> dict[str, Any]: @@ -207,7 +209,7 @@ def _readable_model(recorded: Any, live: Any) -> str: def model_ref(model: Any, *, backend: str | None = None) -> ModelRef: """Build the :class:`ModelRef` carried on M1's output.""" - caps = getattr(model, "capabilities", frozenset()) or frozenset() + caps: Iterable[Any] = getattr(model, "capabilities", frozenset()) or frozenset() return ModelRef( name=model_name(model), backend=backend or getattr(getattr(model, "runtime", None), "backend", None), @@ -387,13 +389,6 @@ def from_stats_report( summary=str(_val(r, "summary", "") or ""), details=dict(_val(r, "details", {}) or {}), ) - # `stats_results` (typed StatsToolResult verdicts), NOT the similarly - # named `stats_tool_results` -- which is a legacy JSON-safe *summary* - # shape keyed by `name`, so preferring it and then filtering on `tool` - # dropped every result. A live run shipped M2 with zero statistics - # beside corrected_rejections.n_tested=16, and both are valid states on - # their own, so nothing downstream could tell that the payload was empty - # because of a field mix-up rather than because nothing was tested. for r in (_val(report, "stats_results", []) or []) if _val(r, "tool", None) ] @@ -465,7 +460,7 @@ def from_diagnosis( # substituting a plausible directive here would make it read as # routable to every downstream reader. test_design=str(_val(h, "test_design", "") or "").strip(), - status=_enum(_val(h, "status")) or "proposed", + status=_enum(_val(h, "status")) or "proposed", # type: ignore[arg-type] # pydantic validates; pydantic.mypy plugin not enabled parent_id=_val(h, "parent_id"), metadata=dict(_val(h, "metadata", {}) or {}), )) @@ -506,15 +501,15 @@ def from_test_results( status = "inconclusive" rows.append(HypothesisTestResultWire( hypothesis_id=hypothesis_id(hyp), - status=status, + status=status, # type: ignore[arg-type] # pydantic validates; pydantic.mypy plugin not enabled test_name=str(_val(tr, "test_name", "") or "unknown"), effect_size=_val(tr, "effect_size"), confidence=float(_val(tr, "confidence", 0.0) or 0.0), - evidence_grade=grade, + evidence_grade=grade, # type: ignore[arg-type] # pydantic validates; pydantic.mypy plugin not enabled is_consistent_with_protocol=consistent, verdict=str(_val(tr, "verdict", "") or ""), evidence=TestEvidence( - source=(ev.get("source") + source=(cast(EvidenceSource, ev.get("source")) if ev.get("source") in _EVIDENCE_SOURCES else "none"), chosen_tool=ev.get("chosen_tool"), routed_by=str(ev.get("routed_by", "") or ""), @@ -643,7 +638,7 @@ def from_intervention( return InterventionOutput( **envelope("m5_surgery", trace_id=trace_id, cycle=cycle, duration_sec=duration_sec), hypothesis_id=hypothesis_id(hyp), - hypothesis_status=_enum(_val(result, "status")) or "inconclusive", + hypothesis_status=_enum(_val(result, "status")) or "inconclusive", # type: ignore[arg-type] # pydantic validates; pydantic.mypy plugin not enabled strategy=_val(result, "strategy", "passive_correlation") or "passive_correlation", fixed=bool(_val(result, "fixed", False)), confidence_score=float(_val(result, "confidence_score", 0.0) or 0.0), @@ -736,7 +731,7 @@ def from_fix_outcome( "not_executed" if _val(v, "exec_error", None) else "no_effect" ) attempts.append(FixAttemptWire( - tier=_tier(_val(cand, "tier", "L1")), + tier=_tier(_val(cand, "tier", "L1")), # type: ignore[arg-type] # pydantic validates; pydantic.mypy plugin not enabled name=str(_val(cand, "name", "") or "candidate"), headline=_headline(cand), kind=_val(cand, "kind"), source=_val(cand, "source"), @@ -753,7 +748,7 @@ def from_fix_outcome( n_model_independent=int(_val(v, "n_model_independent", 0) or 0), effect=_val(v, "effect"), e_value=_val(v, "e_value"), reject=bool(_val(v, "reject", False)), - verdict=verdict, + verdict=verdict, # type: ignore[arg-type] # pydantic validates; pydantic.mypy plugin not enabled summary=str(_val(v, "summary", "") or ""), )) # The selection phase's audit rows: name/tier/n_pairs/n_fixed/n_broken/ @@ -762,7 +757,7 @@ def from_fix_outcome( # reader could mistake for confirmation. selection = [ FixAttemptWire( - tier=_tier(row.get("tier")), + tier=_tier(row.get("tier")), # type: ignore[arg-type] # pydantic validates; pydantic.mypy plugin not enabled name=str(row.get("name") or "candidate"), headline=" ".join(str(row.get("headline") or "").split())[:300], n_pairs=int(row.get("n_pairs") or 0), @@ -813,7 +808,7 @@ def from_fix_outcome( break return FixOutput( **envelope("m5_fix", trace_id=trace_id, cycle=cycle, duration_sec=duration_sec), - max_tier=_tier(_val(outcome, "max_tier", "L1")), + max_tier=_tier(_val(outcome, "max_tier", "L1")), # type: ignore[arg-type] # pydantic validates; pydantic.mypy plugin not enabled routed=[{str(k): str(v) for k, v in dict(r).items()} for r in (_val(outcome, "routed", []) or []) if isinstance(r, dict)], attempted=attempts, @@ -907,7 +902,8 @@ def write_index(root: "str | Path", *, trace_id: str = "") -> Path: """ directory = Path(root) / CONTRACT_DIR directory.mkdir(parents=True, exist_ok=True) - payloads, invalid = [], [] + payloads: list[dict[str, Any]] = [] + invalid: list[dict[str, Any]] = [] for path in sorted(directory.glob("*.json")): if path.name == "index.json": continue diff --git a/evalrx/contract/export.py b/evalrx/contract/export.py index ad7d1544..a246f043 100644 --- a/evalrx/contract/export.py +++ b/evalrx/contract/export.py @@ -136,8 +136,8 @@ def _layout_doc() -> str: "└── artifacts/ M1 heavy numeric data (.npy/.json) outside any stage", "```", "", - "`run.json` + `M1/log.json`..`M5/log.json` are RunLoggerV2's layout (see", - "`evalrx/eval_agent/RUN_LOGGER_V2.md`): no flat event stream, no separate", + "`run.json` + `M1/log.json`..`M5/log.json` are RunLogger's layout (see", + "`evalrx/eval_agent/RUN_LOGGER.md`): no flat event stream, no separate", "`report/`/`figures/` — generated text/code is inlined into the owning", "stage's JSON and media is copied into that stage's own `artifacts/`.", "`contract/` sits alongside it, independently typed and validated.", diff --git a/evalrx/contract/m1.py b/evalrx/contract/m1.py index 40a394d9..313592e9 100644 --- a/evalrx/contract/m1.py +++ b/evalrx/contract/m1.py @@ -22,6 +22,11 @@ WireModel, ) + +def _text_only() -> list[Modality]: + return ["text"] + + # --------------------------------------------------------------------------- # Input # --------------------------------------------------------------------------- @@ -57,7 +62,7 @@ class ModelRef(WireModel): "name, e.g. 'qwen3.5-2b' or 'VideoLLaMA2.1-7B-AV'.", ) backend: str | None = None - modalities: list[Modality] = Field(default_factory=lambda: ["text"]) + modalities: list[Modality] = Field(default_factory=_text_only) capabilities: list[str] = Field( default_factory=list, description="e.g. GENERATE / LOGPROBS / ATTENTION / HIDDEN_STATES.", @@ -231,15 +236,15 @@ class AnalyzerSelection(WireModel): """ model_modalities: list[Modality] = Field( - default_factory=lambda: ["text"], + default_factory=_text_only, description="What the model DECLARES it can consume (from its spec).", ) probed_modalities: list[Modality] = Field( - default_factory=lambda: ["text"], + default_factory=_text_only, description="What the case batch actually FILLS. Text is the floor, not a slot.", ) routed_on: list[Modality] = Field( - default_factory=lambda: ["text"], + default_factory=_text_only, description="The slots routing actually used. Normally model ∩ probed; equal to " "model_modalities when the batch filled no media slot at all, because " "an empty batch is no evidence about what is under test. A reader " diff --git a/evalrx/contract/m2.py b/evalrx/contract/m2.py index 012725b7..ef722555 100644 --- a/evalrx/contract/m2.py +++ b/evalrx/contract/m2.py @@ -11,7 +11,7 @@ from typing import Any, Literal -from pydantic import Field, field_validator, model_validator +from pydantic import Field, model_validator from evalrx.contract.common import ( ArtifactRef, @@ -171,12 +171,6 @@ def is_decisive(self, report_survivors: set[str] | None = None) -> bool: return True -#: Legacy spellings this contract shipped before it was checked against the -#: producer. ``evalrx.stats.multiplicity`` writes the hyphenated names and -#: has a fourth value the contract had no member for. -_LEGACY_CORRECTION_METHODS = {"ebh": "e-BH", "bh": "BH"} - - class CorrectedRejections(WireModel): """Family-level multiplicity control across every tested signal. @@ -199,13 +193,6 @@ class CorrectedRejections(WireModel): default_factory=list, description="analysis_key values that survived. The source of truth." ) - @field_validator("method", mode="before") - @classmethod - def _normalise_method(cls, v: Any) -> Any: - if isinstance(v, str): - return _LEGACY_CORRECTION_METHODS.get(v.lower(), v) - return v - class StatsReportWire(StageEnvelope): """M2's serialized report. diff --git a/evalrx/contract/m4.py b/evalrx/contract/m4.py index 4dd82b02..425ae42e 100644 --- a/evalrx/contract/m4.py +++ b/evalrx/contract/m4.py @@ -54,10 +54,13 @@ class HypothesisTestInput(WireModel): # Output # --------------------------------------------------------------------------- +EvidenceSource = Literal["m2_stats_results", "fallback_per_case", "none"] + + class TestEvidence(WireModel): """The statistics behind one verdict, with its provenance.""" - source: Literal["m2_stats_results", "fallback_per_case", "none"] = "none" + source: EvidenceSource = "none" chosen_tool: str | None = None routed_by: str = Field(default="", description="How test_design resolved to this result.") consulted_tools: list[str] = Field(default_factory=list) diff --git a/evalrx/contract/m5.py b/evalrx/contract/m5.py index b54ae2c1..142c9e28 100644 --- a/evalrx/contract/m5.py +++ b/evalrx/contract/m5.py @@ -130,9 +130,7 @@ class FixAttemptWire(WireModel): "sees R3 in the sweep can find R3's card and know it is the same repair.\n\n" "This exists because `name` cannot do the job. Consumers that numbered rows " "by list position gave the same repair two different numbers in the two " - "lists, which is worse than no number at all. Empty means the producer " - "assigned none; a consumer may then number by position, but only within one " - "list and never as a cross-list identity.", + "lists, which is worse than no number at all.", ) name: str = Field( description="Machine slug, e.g. `audio_evidence_then_answer`. It is the JOIN KEY — " diff --git a/evalrx/contract/methodology.py b/evalrx/contract/methodology.py index 0bf7e312..cb52fa90 100644 --- a/evalrx/contract/methodology.py +++ b/evalrx/contract/methodology.py @@ -57,7 +57,7 @@ def _xml_is_renderable(self) -> "MethodologyWire": cells = list(root.iter("mxCell")) if not cells: raise ValueError("drawio_xml contains no mxCell elements") - ids = [c.get("id") for c in cells if c.get("id")] + ids = [cid for c in cells if (cid := c.get("id"))] dupes = {i for i in ids if ids.count(i) > 1} if dupes: raise ValueError(f"duplicate mxCell ids render unpredictably: {sorted(dupes)}") diff --git a/evalrx/contract/stage_detail.py b/evalrx/contract/stage_detail.py index 14814b0b..abf57732 100644 --- a/evalrx/contract/stage_detail.py +++ b/evalrx/contract/stage_detail.py @@ -189,6 +189,21 @@ class TakeawayView(WireModel): table_names: list[str] | None +class ExploreAgentView(WireModel): + """What the explore coding agent left: the analysis it wrote and ran. + + ``transcript`` is its CLI trajectory, cut to the report's budget; the run + directory keeps the whole file. + """ + + code: str | None + stdout: str | None + stderr: str | None + transcript: str | None + transcript_truncated: bool + audit: Any + + class M2StageDetail(WireModel): mode: str conclusion: str @@ -200,6 +215,7 @@ class M2StageDetail(WireModel): caveats: list[Any] candidate_signals: list[CandidateSignalView] recommended_tests: list[Any] + agent: ExploreAgentView | None # --------------------------------------------------------------------------- @@ -221,23 +237,11 @@ class HypothesisView(OpenWireModel): status: str | None = None -class UnparsedProposal(WireModel): - """A proposal recovered from the judge's raw reply after the parser - rejected it. Shown for audit only; it never reached M4.""" - - statement: str - plain_statement: str - failure_mode: str - test_design: str - expected_association: str - accepted_by_pipeline: bool - - class M3StageDetail(WireModel): mode: str hypotheses: list[HypothesisView] - unparsed_proposals: list[UnparsedProposal] - agent_response: str + #: Why M3 gave nothing, when the run stopped on it; ``None`` otherwise. + error: str | None = None candidate_signals: list[CandidateSignalView] recommended_tests: list[Any] evidence_figures: list[FigureView] @@ -425,6 +429,7 @@ class StageDetail(WireModel): __all__ = [ "CandidateSignalView", + "ExploreAgentView", "FigureView", "HypothesisView", "M1StageDetail", @@ -446,7 +451,6 @@ class StageDetail(WireModel): "StageDetail", "StatView", "TakeawayView", - "UnparsedProposal", "ValidationEventView", "ValidationEvidence", "ValidationExample", diff --git a/evalrx/contract/typescript.py b/evalrx/contract/typescript.py index fe891b04..e3746504 100644 --- a/evalrx/contract/typescript.py +++ b/evalrx/contract/typescript.py @@ -15,7 +15,7 @@ from typing import Any -_SCALARS = { +_SCALARS: dict[str | None, str] = { "string": "string", "integer": "number", "number": "number", "boolean": "boolean", "null": "null", } diff --git a/evalrx/core/__init__.py b/evalrx/core/__init__.py index d852b33b..37e76a59 100755 --- a/evalrx/core/__init__.py +++ b/evalrx/core/__init__.py @@ -32,7 +32,6 @@ from evalrx.core.registry import ( Registry, register_analyzer, - register_model, registry, ) from evalrx.core.result import Result @@ -79,7 +78,6 @@ "Result", "registry", "Registry", - "register_model", "register_analyzer", "Pipeline", "Experiment", diff --git a/evalrx/core/capability.py b/evalrx/core/capability.py index 69877f01..9a0c48e1 100755 --- a/evalrx/core/capability.py +++ b/evalrx/core/capability.py @@ -9,6 +9,7 @@ from __future__ import annotations +from collections.abc import Set as AbstractSet from enum import Enum @@ -40,7 +41,7 @@ def __init__( self, analyzer: str, model: str, - missing: set[Capability], + missing: AbstractSet[Capability], ) -> None: self.analyzer = analyzer self.model = model diff --git a/evalrx/core/case.py b/evalrx/core/case.py index f8e89ea6..d41ba5b3 100755 --- a/evalrx/core/case.py +++ b/evalrx/core/case.py @@ -432,6 +432,7 @@ def as_casebatch( return CaseBatch([FailureCase(inputs=Inputs(prompt=data.goal), trajectory=data)]) if isinstance(data, Iterable): batch = CaseBatch() + item: Any # elements are validated by the recursive call for item in data: # flatten via single-item normalisation for case in as_casebatch(item): diff --git a/evalrx/core/model.py b/evalrx/core/model.py index b1097a93..3f732641 100755 --- a/evalrx/core/model.py +++ b/evalrx/core/model.py @@ -17,7 +17,7 @@ from abc import ABC, abstractmethod from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, Callable +from typing import TYPE_CHECKING, Any, Callable, Protocol from evalrx.core.capability import Capability @@ -96,6 +96,18 @@ def require(self, capability: Capability) -> Any: return value +class Judge(Protocol): + """A model a stage asks to read and write text — its judge. + + Every :class:`Model` qualifies; so do the CLI-backed judges in + :mod:`evalrx.agent_runtime.judges`, which can do nothing else. + """ + + capabilities: frozenset[Capability] + + def generate(self, inputs: Any, **kwargs: Any) -> str: ... + + class Model(ABC): """Abstract base for every analyzable model. diff --git a/evalrx/core/registry.py b/evalrx/core/registry.py index fb044ee5..9f41ddef 100755 --- a/evalrx/core/registry.py +++ b/evalrx/core/registry.py @@ -6,10 +6,9 @@ registry.analyzers.list() # ["attention", "token_entropy", ...] registry.analyzers.compatible_with(model) # [AttentionAnalyzer, ...] -Model *identity* lives in :mod:`evalrx.specs` (``ModelSpec``), not here; -``registry.models`` is a deprecated shim that delegates to it. This is what -makes the package programmatically explorable rather than something you have to -read source code to use. +Model *identity* lives in :mod:`evalrx.specs` (``ModelSpec``), not here. This +is what makes the package programmatically explorable rather than something you +have to read source code to use. """ from __future__ import annotations @@ -80,51 +79,10 @@ def names_compatible_with(self, model: "Model") -> list[str]: return sorted(name for name, cls in self._items.items() if self._matches(cls, model)) -class _DeprecatedModelRegistry(_Registry["Model"]): - """Deprecated shim: model identity now lives in :mod:`evalrx.specs`. - - ``registry.models`` is kept so older code keeps working, but it delegates to - the spec registry and warns. Use ``evalrx.list_specs()`` / - ``evalrx.get_spec()`` (or ``evalrx.load`` / ``compose``) instead. - """ - - @staticmethod - def _warn() -> None: - import warnings - - warnings.warn( - "registry.models is deprecated; model identity now lives in " - "evalrx.specs (use evalrx.list_specs() / get_spec(), or " - "evalrx.load / compose to build a model).", - DeprecationWarning, - stacklevel=3, - ) - - def list(self) -> list[str]: - self._warn() - from evalrx.specs import list_specs - - return list_specs() - - def has(self, name: str) -> bool: - self._warn() - from evalrx.specs import REGISTRY - - return name.lower() in REGISTRY - - def get(self, name: str): # returns a ModelSpec, not a class - self._warn() - from evalrx.specs import get_spec - - return get_spec(name.lower()) - - class Registry: - """Top-level namespace bundling the model and analyzer registries.""" + """Top-level namespace for the analyzer registry.""" def __init__(self) -> None: - # Model identity is the spec registry's job now; this is a back-compat shim. - self.models: _DeprecatedModelRegistry = _DeprecatedModelRegistry("model") self.analyzers: AnalyzerRegistry = AnalyzerRegistry("analyzer") @@ -132,11 +90,6 @@ def __init__(self) -> None: registry = Registry() -def register_model(name: str): - """Class decorator registering a model under *name*.""" - return registry.models.register(name) - - def register_analyzer(name: str): """Class decorator registering an analyzer under *name*.""" return registry.analyzers.register(name) diff --git a/evalrx/datasets/__init__.py b/evalrx/datasets/__init__.py index 7df53ec6..3b2758db 100755 --- a/evalrx/datasets/__init__.py +++ b/evalrx/datasets/__init__.py @@ -2,7 +2,6 @@ Text QA: ``LLMQADataset``. Image+text QA: ``VLMQADataset`` and the ``TextVQASizeDataset`` / ``Spatial457Dataset`` / ``VQARADDataset`` benchmarks. -``PureQADataset`` is a back-compat alias of ``LLMQADataset``. """ from evalrx.datasets.base import ( @@ -14,7 +13,7 @@ read_jsonl, ) from evalrx.datasets.gui_os import GUIOSDataset -from evalrx.datasets.llm_qa import LLMQADataset, PureQADataset +from evalrx.datasets.llm_qa import LLMQADataset from evalrx.datasets.vlm_qa import ( Spatial457Dataset, TextVQASizeDataset, @@ -30,7 +29,6 @@ "TextVQASizeDataset", "Spatial457Dataset", "VQARADDataset", - "PureQADataset", "WebSearchQADataset", "GUIOSDataset", "cases_from_records", diff --git a/evalrx/datasets/gui_os.py b/evalrx/datasets/gui_os.py index 13dc81e3..e69af0c9 100755 --- a/evalrx/datasets/gui_os.py +++ b/evalrx/datasets/gui_os.py @@ -8,6 +8,8 @@ from __future__ import annotations +from typing import Any + from evalrx.core.case import CaseBatch from evalrx.datasets.base import Dataset, cases_from_records, read_jsonl @@ -31,7 +33,7 @@ def __init__( ) -> None: self._records = records self._path = path - self._keys = dict(prompt_key=prompt_key, answer_key="expected_state", image_key=image_key) + self._keys: dict[str, Any] = dict(prompt_key=prompt_key, answer_key="expected_state", image_key=image_key) @classmethod def from_records(cls, records: list[dict], **keys) -> "GUIOSDataset": diff --git a/evalrx/datasets/llm_qa.py b/evalrx/datasets/llm_qa.py index 5963de73..274b219e 100755 --- a/evalrx/datasets/llm_qa.py +++ b/evalrx/datasets/llm_qa.py @@ -8,6 +8,8 @@ from __future__ import annotations +from typing import Any + from evalrx.core.case import CaseBatch from evalrx.datasets.base import Dataset, cases_from_records, read_jsonl @@ -32,7 +34,7 @@ def __init__( ) -> None: self._records = records self._path = path - self._keys = dict(prompt_key=prompt_key, answer_key=answer_key) + self._keys: dict[str, Any] = dict(prompt_key=prompt_key, answer_key=answer_key) @classmethod def from_records(cls, records: list[dict], **keys) -> "LLMQADataset": @@ -51,7 +53,3 @@ def load(self) -> CaseBatch: read_jsonl(self._path) if self._path else _SAMPLE ) return cases_from_records(records, tags={"llm_qa"}, **self._keys) - - -# Back-compat: the old combined name. Prefer LLMQADataset (text) / VLMQADataset (image+text). -PureQADataset = LLMQADataset diff --git a/evalrx/datasets/pure_qa.py b/evalrx/datasets/pure_qa.py deleted file mode 100755 index 99619ece..00000000 --- a/evalrx/datasets/pure_qa.py +++ /dev/null @@ -1,12 +0,0 @@ -"""Back-compat shim — ``pure_qa`` was split into ``llm_qa`` (text) and ``vlm_qa`` (image+text). - -``PureQADataset`` remains importable here as an alias of -:class:`~evalrx.datasets.llm_qa.LLMQADataset`. Prefer the explicit names: -``LLMQADataset`` for text QA, ``VLMQADataset`` / ``Spatial457Dataset`` for image+text. -""" - -from __future__ import annotations - -from evalrx.datasets.llm_qa import LLMQADataset, PureQADataset - -__all__ = ["PureQADataset", "LLMQADataset"] diff --git a/evalrx/datasets/web_search_qa.py b/evalrx/datasets/web_search_qa.py index 11a3db07..6a598072 100755 --- a/evalrx/datasets/web_search_qa.py +++ b/evalrx/datasets/web_search_qa.py @@ -7,6 +7,8 @@ from __future__ import annotations +from typing import Any + from evalrx.core.case import CaseBatch from evalrx.datasets.base import Dataset, cases_from_records, read_jsonl @@ -31,7 +33,7 @@ def __init__( ) -> None: self._records = records self._path = path - self._keys = dict(prompt_key=prompt_key, answer_key=answer_key) + self._keys: dict[str, Any] = dict(prompt_key=prompt_key, answer_key=answer_key) @classmethod def from_records(cls, records: list[dict], **keys) -> "WebSearchQADataset": diff --git a/evalrx/eval_agent/RUN_LOGGER.md b/evalrx/eval_agent/RUN_LOGGER.md new file mode 100644 index 00000000..8c03735f --- /dev/null +++ b/evalrx/eval_agent/RUN_LOGGER.md @@ -0,0 +1,173 @@ +# RunLogger — design notes + +`RunLogger` (`run_logger.py`) is the run log every diagnosis loop writes +through, and the logger a `RunContext` owns. This file says what it writes and +why the layout is the way it is. + +## The code + +| module | what it holds | +|---|---| +| `run_logger.py` | `RunLogger`: routes each event to its document, stamps it, writes atomically | +| `run_log_entries.py` | what each event records: one pure function per event kind | +| `run_log_files.py` | what lands on disk beside the JSON: atomic writes, inlined workspaces, saved artifacts | +| `run_log_tracing.py` | the same events mirrored into Langfuse, one function per event | +| `log_schema.py` | the published JSON Schema of an event | + +## The layout + +``` +run_dir/ + run.json run-wide events (see below) + M1/log.json + M2/log.json + M3/log.json + M4/log.json + M5/log.json + M*/artifacts/ binary media a stage produced + media/ case-level images / audio + artifacts/ named JSON written with save_artifact_json() +``` + +Four rules shaped it. + +### 1. Few files + +One JSON document per pipeline stage. `close()` flushes all five stages, so a +finished run has all five `M*/log.json`; a run that died earlier has a folder +only for the stages that logged something. `artifacts/` subfolders are created +on first use. + +### 2. Same-type logging in one JSON + +Within a stage's `log.json`, every event of one kind is one array under one +key: + +```json +{ + "probe": [ {"cycle": 0}, {"cycle": 1} ], + "model_calls": [ {}, {} ], + "tool_codegen": [ {} ], + "stage_skipped": [ {} ] +} +``` + +There is never one small file per call. `model_calls` is the highest fan-out +event (self-consistency resampling, counterfactual regeneration; see +`model_instrumentation.py`) and it is just another key in its stage's document. + +### 3. M1..M5 each get their own folder + +A reader who cares about M3 opens one folder. `run.json` holds what is not +stage content: + +| `run.json` key | what | +|---|---| +| `run_start` | run config, git commit, versions (one object, not a list) | +| `cases` | the baseline `FailureCase` records, their media references and `split` | +| `report_published` | one audit record per published report | +| `diagnose_reports` | hypotheses, M4 verdicts, discovery rows and a summary | +| `manifest` | final config and a compact file index | +| `loop_end` | one entry per loop summary | +| `run_end` | written by `close()`: the run is finished | +| `agent_decisions` | `JudgePolicy`'s dispatch-judge turns | +| `agent_tool_calls` | the dispatch layer's accept / reject outcome per tool call | +| `unrouted` | events whose stage could not be resolved (see Routing) | + +### 4. Nothing but JSON, except real binary media + +Everything text-shaped is a string value inside the relevant entry: judge +prompts and responses (`judge_prompt`, `judge_response`), generated code +(`experiment[].code`, `tool_codegen[].code`), stdout and stderr, the coder +agent's raw narration. No Markdown summary is generated; a renderer builds its +own view from the fields. + +What stays a separate file is binary media: tensors (`.npy`), figures +(`.png`), audio or video. Those live under `M/artifacts/` (or `media/` for +case-level media) and the JSON holds a run-relative path (`_MEDIA_EXTS` in +`run_log_files.py`). + +A sandbox workspace is a directory of arbitrary files, not one value. +`inline_workspace()` walks it and, per file, inlines the text or copies +recognised media into the stage's `artifacts/` and leaves a path. An +unrecognised binary file gets a one-line `""` note, so nothing +disappears from the record. + +`RunContext` gives producers an ephemeral runtime tree outside the run +directory. Explore, M5 experiments and fix candidates execute there. At +finalization the logger inlines what they left and the runtime tree is deleted. + +## The event envelope + +Every event carries `event`, `stage`, `event_seq`, `span_id`, `trace_id`, +`schema_version` and `ts`. `event_seq` is one global sequence, assigned under +the logger's lock at write time, so the order holds when calls finish +concurrently or the wall clock moves backwards. Readers sort on it. + +## Model-call fidelity + +Every recorded exchange is one entry in its stage's `model_calls` array: `role`, +`operation`, complete JSON-safe `inputs`, complete `output`, `error`, +`duration_sec` when measured, and correlation metadata such as `case_id`, +candidate, generation kwargs or tool name. It covers: + +- every pre-loop case-discovery request, written as each call completes; +- every in-process M1 analyzer `generate` / `forward` / `logprobs` / `chat` call; +- selection, statistics, diagnosis and critic, protocol, tool-codegen, + fix-judge, experiment-writer and CLI-coder calls; +- fresh fix baselines, template candidates, declarative multi-call pipelines, + guided search, and every coded-pipeline bridge request and reply. + +A stage summary keeps its convenient `judge_prompt` / `judge_response` fields; +`model_calls` is the exhaustive query surface. + +## Routing: how an event picks its folder + +Most events know their stage (`log_probe` is M1, `log_analysis` is M2). +`log_experiment`, `log_tool_codegen`, `log_tool_registry` and +`log_stage_skipped` carry a free-text `module` / `stage` tag that is resolved: + +1. Search the tag for `m[1-5]`, case-insensitive, anywhere in the string: + `"m1_probe"`, `"M4_SURGERY"`, `"codegen_m2_stats"`. +2. Fall back to `_STAGE_ALIASES` for tags with no digit (`"fix_pipeline"`). +3. If neither matches, the event goes into `run.json["unrouted"]` with a + `warnings.warn`. A new call site with an unknown tag surfaces loudly instead + of vanishing. + +`log_surgery` is not tag-based: an intervention result whose evidence carries +`m4_test_name` is a hypothesis verification (M4), anything else an intervention +(M5). `run_metadata.py` is where `m4_test_name` is set. + +## Durability: why every event rewrites its document + +The logger keeps one in-memory dict per stage plus one for `run.json`, and on +every `log_*` call serialises the whole dict it touched and writes it with +temp-file-then-`os.replace` (`atomic_write_json`). + +- **Why not append?** Rule 2 wants one JSON document per stage, a bucketed + object rather than a line stream, and a document cannot be appended to + without a reader seeing an invalid partial file. +- **Why not write once at `close()`?** A crash mid-run would lose every event. + `model_calls` exists to survive "the process dies mid-cycle". +- **The cost:** each write is `O(current stage document size)`. A stage that + logs many small events (M1's `model_calls`) rewrites a growing document. For + a realistic run this is low tens of MB of I/O over a cycle, negligible next + to inference time. If a run's volume makes it a bottleneck, the fix is to + coalesce writes behind `_flush_stage` / `_flush_run`, not to change the layout. +- **Atomic:** a reader sees the complete state as of event N or N-1, never a + truncated document. + +## What callers depend on beyond logging + +- `log_probe(...)` returns `list[Path]`, the rendered figures under + `M1/artifacts/`; the loop forwards them to the judge as visual context. +- `current_cycle` is a read/write attribute the loop sets before probing and + `InstrumentedModel` reads at call time. +- `save_artifact_json(stem, obj)` writes under the run-global `artifacts/`, + because callers address those files by a fixed name, not by cycle. + +## Console output + +`verbose=True` prints one line per event (`[M3] diagnosis cycle=0`). +`narrate=True` prints the aligned live M1-M5 narration instead +(`narration.LoopNarrator`) and takes over from `verbose`. diff --git a/evalrx/eval_agent/RUN_LOGGER_V2.md b/evalrx/eval_agent/RUN_LOGGER_V2.md deleted file mode 100644 index 106f3b67..00000000 --- a/evalrx/eval_agent/RUN_LOGGER_V2.md +++ /dev/null @@ -1,350 +0,0 @@ -# RunLoggerV2 — design notes - -Status: **the only run logger.** `RunLoggerV2` is `RunContext`'s unconditional -logger — there is no `logger_version` argument, no V1 to opt into. `RunLogger` -(the old `run_logger.py`, "V1") has been deleted outright: the file, its own -test suite, and every "try V1 first, fall back to V2" branch in the -report/observability readers (`dynamic.py`, `html_report.py`, `tracer.py`, -`dashboard.py`, `case_study.py`, `server.py`). Reading an old V1-format -archive (`run_log.jsonl`, `manifest.json`, `README.txt`) is no longer -supported by anything in this package — that was a deliberate choice, not an -oversight: see "History" below for how the migration got here. - -## Why this exists - -`RunLogger` (the deleted "V1" logger) grew organically over many stages of -the diagnose-loop project (see CLAUDE.md history) and its output for one run -looked like: - -``` -run_dir/ - run_log.jsonl one JSON line per event, EVERY stage interleaved - model_calls.jsonl a second, separate JSONL stream - artifacts/ *.npy, *.json, *.png — all stages mixed together - prompts/ one *.prompt.txt + *.response.txt PER judge call - experiments/ *.py, *.txt, record.md per M5 experiment - tools/ *.py, *.txt per synthesised tool - workspace/ copied sandbox files - fixes/ record.md + result.json + outputs.jsonl per candidate -``` - -That's 7+ top-level directories, an unbounded number of small text files (one -pair per judge call, one per tool-codegen attempt, one per experiment), and no -way to look at "just M3" without grep-ing a shared JSONL stream and cross -referencing `cycle`/`event` fields. - -This file describes the replacement layout and the reasoning behind each -rule the user asked for. - -## The four rules, and how the layout satisfies them - -### 1. Few files - -One JSON document per pipeline stage. A run that used all five stages -produces exactly: - -``` -run_dir/ - run.json run-wide events (see below) - M1/log.json - M2/log.json - M3/log.json - M4/log.json - M5/log.json - M*/artifacts/ only for stages that actually produced binary media - media/ only if the run had case-level images/audio - artifacts/ only if save_artifact_json() was called -``` - -A stage that never ran (e.g. a run with no M4/M5 activity) still gets a -folder + an empty-ish `log.json` — but only once `close()` runs: `close()` is -the one call site that flushes all five stages unconditionally, so a normal -`with RunLoggerV2(...) as logger: ...` run, or any `run_logger.close()` at the -end of a loop, produces all five `M*/log.json` regardless of activity. A run -that crashes before `close()` leaves folders only for stages that actually -logged something — `_append_stage`/`log_model_call` only flush the stage they -just wrote to, and `RunLoggerV2.__init__` doesn't pre-create anything. -`_stage_dir`/`_stage_artifacts_dir` create the `artifacts/` subfolders lazily, -on first use, so an unused stage never costs more than one small JSON file. - -### 2. Same-type logging in one JSON - -Within one stage's `log.json`, every event of a given kind is one array, one -key: - -```json -{ - "probe": [ {...cycle 0...}, {...cycle 1...} ], - "model_calls": [ {...}, {...}, ... ], - "tool_codegen": [ {...} ], - "tool_registry": [ {...} ], - "stage_skipped": [ {...} ] -} -``` - -Never one small file per call. This is what let `model_calls` — the highest -fan-out event (self-consistency resampling, counterfactual regeneration — -see `model_instrumentation.py`) — collapse from its own `model_calls.jsonl` -stream into just another key in `M1/log.json`. - -### 3. M1..M5 each get their own folder - -Everything above. `run.json` at the top level is the one deliberate -exception — it holds events that are not stage content: - -| `run.json` key | what | -|---|---| -| `run_start` | run config, git commit, versions (a single object, not a list) | -| `cases` | the baseline `FailureCase` records + media references | -| `report_published` | cached-report-publication audit records | -| `diagnose_reports` | hypotheses, M4 verdicts, discovery rows, and summary | -| `manifest` | final config and compact file index | -| `loop_end` | one entry per loop-run summary | -| `agent_decisions` | `AgenticDiagnoseLoop`'s own dispatch-judge turns | -| `agent_tool_calls` | the dispatch layer's accept/reject outcome per tool call | -| `unrouted` | see "Routing", below — never silently dropped | - -### 4. Nothing but JSON, except real binary media - -Every text-shaped thing `RunLogger` wrote as a sibling file — judge prompts -and responses, generated code, stdout/stderr, the coder agent's raw -narration, human-readable Markdown summaries — is now a **string value -inside the relevant JSON entry**: - -| RunLogger (a file + a path field) | RunLoggerV2 (inline) | -|---|---| -| `prompts/c0_m1_selection.prompt.txt` + `judge_io.prompt_path` | `probe[].judge_prompt` | -| `experiments/c0_m5_main.py` + `code_paths["main.py"]` | `experiment[].code["main.py"]` | -| `experiments/c0_m5_stdout.txt` + `output_paths["stdout"]` | `experiment[].stdout` | -| `fixes/01_L1_cand1/record.md` (human summary) | not generated — the same fields (`status`, `evidence`, `verdict`, ...) are already in `fix[]`; a renderer builds its own view from them | -| `tools/c0_m1_probe_gen_probe_01_code.py` | `tool_codegen[].code` | - -The one thing that stays a separate file is **real binary media**: numeric -tensors (`.npy`), rendered figures (`.png`), and any audio/video a sandbox -happens to produce. Those live under `M/artifacts/` (or `media/` for -case-level images/audio), referenced by a relative-path string in the JSON — -see `_MEDIA_EXTS` in `run_logger_v2.py`. - -A sandbox workspace snapshot (`log_experiment`'s `workdir`) is a directory of -arbitrary files, not a single value — `_inline_workspace()` walks it and, per -file, either inlines the text (source, data, logs) or — for a recognised -media extension — copies it to that stage's `artifacts/` and leaves a path -reference. Nothing is silently skipped: an unrecognised binary file gets a -one-line `""` note instead of being dropped from the record. - -`RunContext` gives V2 producers an ephemeral runtime tree outside the run -artifact. Explore, M5 experiments, and fix candidates may execute real code -there. Before finalization, source, prompts, responses, tables, stdout/stderr, -and validation records are inlined into JSON; recognised binary media is -copied into `M/artifacts/`; then the runtime tree is deleted. V2 finalization -does not emit V1's `README.txt`, `summary.md`, trial `.txt`/`.py` files, or -in-run SQLite outbox. - -## Model-call fidelity - -Every recorded exchange lives in that stage's single `model_calls` array and -contains `role`, `operation`, complete JSON-safe `inputs`, complete `output`, -`error`, `duration_sec` when measured, and correlation metadata such as -`case_id`, candidate, generation kwargs, or tool name. Coverage includes: - -- every pre-loop case-discovery request, response/error, generation kwargs, - case id, and individually measured latency (written as each call completes); -- every in-process M1 analyzer `generate`/`forward`/`logprobs`/`chat` call, - without V1's 8,000-character truncation when V2 is active; -- selection, statistics, diagnosis/critic, protocol, tool-codegen, fix-judge, - experiment-writer, and CLI-coder calls for which the stage exposes I/O; -- fresh fix baselines, template candidates, declarative multi-call pipelines, - guided/detector search, and every coded-pipeline bridge request/reply. - -The stage summary keeps its convenient `judge_prompt`/`judge_response` fields; -`model_calls` is the exhaustive query surface. - -## Routing: how an event picks its folder - -Most events know their stage unambiguously (`log_probe` → M1, `log_analysis` -→ M2, ...). Four kinds of event carry a free-text `module`/`stage` string -instead (`log_surgery`'s M4-vs-M5 split, `log_experiment`, `log_tool_codegen`, -`log_tool_registry`, `log_stage_skipped`) and need to be **resolved**: - -```python -_STAGE_RE = re.compile(r"m([1-5])", re.IGNORECASE) -_STAGE_ALIASES = {"fix_pipeline": "M5", "fix": "M5", "explore": "M2"} -``` - -1. Search the tag for `m[1-5]` (case-insensitive), anywhere in the string — - covers `"m1_probe"`, `"M4_SURGERY"`, `"codegen_m2_stats"`. -2. Fall back to `_STAGE_ALIASES` for the handful of tags that carry no digit - at all — as of this writing, only `fix_agent.py`'s - `log_tool_codegen(module="fix_pipeline", ...)` needs this. -3. If NEITHER matches, the event goes into `run.json["unrouted"]` with a - `warnings.warn` — never silently discarded. `_STAGE_ALIASES` was built by - grepping every literal `module=`/`stage=` call site in `evalrx/eval_agent/` - as of this writing (see the commit that introduced this file); a NEW call - site added later with a tag that matches neither the regex nor the alias - table will still surface — loudly, in `unrouted` — rather than vanish. - -`log_surgery`'s M4/M5 split is NOT tag-based — it inspects -`"m4_test_name" in iv.evidence`, exactly mirroring `RunLogger.log_surgery` -post the M4/M5 stage-id swap (hypothesis verification = M4, intervention = -M5). Verified directly against `evalrx/eval_agent/run_metadata.py`, which is -where `m4_test_name` is actually set. - -## Durability: why every event triggers a full-file rewrite - -`RunLogger` appends one line to a JSONL stream per event — cheap, and a crash -mid-run leaves everything written so far intact. `RunLoggerV2` instead keeps -one in-memory dict per stage (+ one for `run.json`) and, on every single -`log_*` call, serialises the WHOLE current dict and writes it via -temp-file-then-`os.replace` (`_atomic_write_json`): - -- **Why not just append?** Rule 2 requires one JSON *document* per stage — - a bucketed object, not a line stream — so there's no way to "append" to it - without rewriting the document (or accepting that reads mid-run see a - syntactically invalid partial file). -- **Why not buffer everything and write once at `close()`?** That would lose - every event on a crash mid-run — the same failure mode - `test_holdout_cases_logged.py` exists to catch for V1 (an unlogged case id - is unrecoverable). `model_calls` in particular was built specifically to - survive "the process dies mid-cycle" (see `model_instrumentation.py`) — an - in-memory-only V2 would silently regress that guarantee. -- **The trade-off, stated plainly:** each write is `O(current stage document - size)`, and a stage that logs many small events (M1's `model_calls`, chiefly - — a self-consistency/coverage_gap analyzer can make dozens of calls per - case) rewrites a document that keeps growing. For a realistic run (dozens - to a few hundred model calls, each a KB or two serialized) this is at most - low tens of MB of total I/O across a whole cycle — negligible next to the - model-inference time the run is dominated by. If a future run's volume - makes this a real bottleneck, the fix is a batching/coalescing write behind - the same `_flush_stage`/`_flush_run` calls, not a redesign of the layout. -- The write is **atomic**: a reader (a human `cat`-ing the file, or a future - dashboard) either sees the complete state as of event N, or as of N-1 — - never a truncated document. - -## API parity: how this can be a drop-in - -Every `RunLogger.log_*` method has a same-named, same-signature counterpart -here, including the two that matter for callers who don't just log — they -depend on the return value or a live attribute: - -- `log_probe(...)` returns `list[Path]` (rendered PNG figures) — `loop.py` - forwards these to the judge as visual context. `RunLoggerV2.log_probe` - returns the same shape, pointing into `M1/artifacts/`. -- `current_cycle` is a plain read/write attribute `ProbeAgent`/`loop.py` set - before probing and `InstrumentedModel` reads at call time — present here - unchanged. -- `save_artifact_json(stem, obj)` — used by `agentic/tools.py` for - fixed-name lookups (`failure_modes.json`, `probe_search_result.json`) — - present, writing under a run-global `artifacts/` (not stage-scoped, since - callers address it by a fixed name, not by cycle). - -`RunLoggerV2` keeps its `RunContext` in `_context`, matching V1's integration -boundary. The difference is storage: `new_trial()` and `new_workdir()` allocate -ephemeral execution space for V2, and the logger captures its evidence before -`RunContext.finalize()` removes it. - -## Deliberate scope cuts - -- **No Markdown summaries** (`record.md`, `outcome.md`). Same information, - no separate file; a renderer builds a human view from the JSON on demand. -- **Simplified verbose console output.** `RunLogger`'s `verbose=True` renders - multi-line, stage-specific narration (`_VerboseFormatter`). `RunLoggerV2`'s - `verbose=True` prints one line per event (`[M3] diagnosis cycle=0`) — this - change was about file layout, not console UX, and porting that formatter - verbatim would have doubled the size of this module for no layout benefit. - -## What "confirmed working" means so far - -### Non-Langfuse parity additions - -- Non-numeric dict/list probe artifacts are inlined under - `M1/log.json["probe"][i]["artifacts"]`, keyed by `analyzer/artifact`. - Numeric artifacts remain `.npy` files. `results` retains result metadata - and summaries independently from these artifacts. -- Fix attempts (including EXPLORE selection attempts with a `trial_root`) - carry a `workspace_snapshot`. Before deleting its temporary execution tree, - `RunContext.finalize()` also captures the entire remaining tree in - `run.json["runtime_snapshot"]`, including discarded trials and late files. - These managed snapshots preserve text without the normal 2 MB cap, inline - other UTF-8 text such as shell scripts, and copy binary files into M5 artifacts. - Failed archival prevents cleanup so it can be retried. Media names include - source path and content hashes to preserve different trials and revisions. -- M4/M5 surgery records include `module`; the reader supplies this field for - older V2 bundles too. Existing case-study M4 filtering works on both. -- `loop_end.verified_hypotheses` retains `failure_mode`, `status`, `confidence`, - and `protocol_consistent`, alongside `statement` and `verdict`. -- Every newly written event carries `event`, `schema_version`, `trace_id`, - `stage`, `span_id`, and a global `event_seq` assigned under the logger lock. - The reader preserves these identities and sorts new bundles by sequence; - historical bundles still use timestamp ordering. These local span IDs do - not add or change Langfuse delivery. -- `EVALRX_VALIDATE_LOG=1` enables warn-only validation of persisted events - using `log_schema.build_schema()` — the single, merged event schema (V1's - builder and V2's were folded into one when V1 was deleted; validation - requires the optional `jsonschema` package). - -Regression tests cover data retention after cleanup, retry after archival -failure, M4 rendering of old/new bundles, verified-summary parity, concurrent -event ordering, and valid/invalid schema inputs. These are local tests, not -a new real-model benchmark or live Langfuse acceptance run. - -`tests/test_eval_agent/test_run_logger_v2.py`: - -1. Drives every single `log_*` method with the SAME real domain objects - (`Result`, `StatsAnalysisReport`, `DiagnosisResult`, `InterventionResult`, - `ExploratoryAnalysisReport`, `Hypothesis`) — not bespoke fakes. -2. Asserts the layout rules directly: exactly one folder per stage, no - non-JSON/non-media files anywhere under the complete RunContext root, same-type events - share one array, an unroutable tag lands in `unrouted` rather than - vanishing, every JSON file left on disk is valid (parses) after a full - run including after `close()`, no leftover `.tmp*` files. -3. Runs a real `VLDiagnoseLoop.run()` end to end (the same scenario - `test_holdout_cases_logged.py` uses to catch a real historical bug — - the held-out confirm split's cases never getting logged) with - `RunLoggerV2` and also tests the actual `RunContext(...)` boundary, - ephemeral trial/explore cleanup, full model-call I/O, report inlining, - artifact copying, and quarantine rewrites. - -The reader in `evalrx/reporting/run_events.py` (`read_v2_events`) exposes V2 -documents to the dynamic report, HTML report, server, dashboard, case-study -loader, and Langfuse backfill paths as one flat event list, so those readers -don't each re-implement the bucket-flattening logic. It's the sole read -path now — there's no other format for it to fall back to. - -## History — how the migration got here - -**Phase 1** flipped `RunContext`'s default from V1 to V2 (`logger_version` -went `"v1"` → `"v2"`, still an opt-out), fixed the two on-disk-layout bugs the -flip exposed (`VLDiagnoseLoop._explore_out_dir()` was hand-deriving -`/explore` instead of calling `ctx.explore_dir`; `html_report. -embed_figures()` was only checking V1's `figures/`, so every V2 run's static -HTML export rendered zero embedded M2 charts), and triaged the test suite so -V1-specific tests were pinned explicitly (`logger_version="v1"`) rather than -silently inheriting the new default. - -**Phase 2** removed V1 outright, both writing and reading: deleted -`run_logger.py`, its own test suite, the `logger_version` parameter itself -(there is nothing to select between anymore), `run_log.schema.json`'s -separate builder (merged into `log_schema.build_schema()`, schema version -bumped 5→6 for the merged envelope), and every "try V1, fall back to V2" -branch in the report/observability readers and in -`examples/dataset_selection/llm_benchmark/run_pipeline.py`'s own confirm-only -reloader. `evalrx/reporting/run_events.py`'s `read_v2_events` stayed as the -one read path; it never had a V1 branch to remove. A pre-existing archive -written by V1 is no longer readable by anything in this package — that -includes `examples/benchmark/tools/extract_figure_data.py`, a standalone -analysis tool outside the `evalrx` package proper, which got its own, -independent V1→V2 conversion in the same pass. - -## Known gaps (not V1/V2 related, found along the way) - -- `RunLoggerV2` never pushes structured events through the outbox - (`tracer.record_event`) the way V1 did for every event — it relies on live - spans/generations (`start_span`/`log_generation`/`log_score`) instead. One - consequence: `evalrx/reporting/langfuse_source.py`'s `LangfuseRunSource`, - which recovers a run from Langfuse Observations shaped like V1's outbox - deliveries (`input={"event": {...}}`), gets back events with no `stage` tag - for a V2 run. `materialize()` routes those by event name to a best-guess - stage instead of losing them, but this is a workaround, not proof V2 runs - round-trip through Langfuse correctly — that needs RunLoggerV2 emitting - outbox-durable events itself, out of scope for the V1 removal this file - otherwise documents. diff --git a/evalrx/eval_agent/__init__.py b/evalrx/eval_agent/__init__.py index 8c08306d..67480214 100755 --- a/evalrx/eval_agent/__init__.py +++ b/evalrx/eval_agent/__init__.py @@ -1,11 +1,11 @@ """Self-evolving evaluation agent — automated failure discovery and diagnosis. -Two loops are available: +One loop, two policies for the order of its stages: - VLDiagnoseLoop M1 → M2 → M3 → M4 inner loop, M5 called post-loop (Plan A) - Stops when M4 finds a statistically supported, - protocol-consistent hypothesis. - AgenticDiagnoseLoop the same stages, driven by a judge-decided action loop. + VLDiagnoseLoop M1 → M2 → M3 → M4, M5 called post-loop (Plan A) + FixedOrderPolicy the default: M1 → M4 cycles until M4 finds a statistically + supported, protocol-consistent hypothesis. + JudgePolicy pass as VLDiagnoseLoop(policy=...): a judge picks each next stage. Stage modules live in ``stages/``; shared infrastructure stays at the top level. The CLI-agent runtime (sandboxing, code generation, providers, judge models, @@ -15,7 +15,7 @@ Top-level (shared / orchestration): loop.py VLDiagnoseLoop loop_fix.py run_fix orchestration: fix targets, tier ladder, EXPLORE→CONFIRM - run_logger_v2.py RunLoggerV2 — run.json + per-stage M/log.json event log + run_logger.py RunLogger — run.json + per-stage M/log.json event log hypothesis.py Hypothesis, HypothesisStatus, serialization helpers store.py Store / InMemoryStore / JsonlStore — persistent memory @@ -48,7 +48,6 @@ stats_tools.py M2 — statistical tool catalog wrapping evalrx.stats (signal/label association, McNemar+e-value, Friedman, single-rate e-value, rank corr) + StatsInput/fdr_correct - stats_tool_agent.py M2 — legacy deterministic exploratory stats tools stats_tool_generator.py M2 tier(b) — StatsToolGenerator: LLM/CLI writes a new stats script, runs it in a sandbox, parses a STATS_RESULT_JSON contract (never mutates repo source) @@ -88,7 +87,6 @@ """ from evalrx.agent_runtime.cli_types import CliAgentConfig, CliAgentResult -from evalrx.agent_runtime.factory import SandboxConfig, SandboxFactoryConfig, create_sandbox from evalrx.agent_runtime.judges import AgyModel, ClaudeModel, CodexModel from evalrx.agent_runtime.providers import create_cli_agent from evalrx.agent_runtime.sandbox import ( @@ -109,7 +107,6 @@ profile_stats_input, ) from evalrx.analysis.stats_agent import StatsAnalysisAgent, StatsAnalysisReport -from evalrx.analysis.stats_tool_agent import StatsToolAgent from evalrx.analysis.stats_tool_generator import ( GeneratedStatsTool, StatsToolGenerator, @@ -121,12 +118,11 @@ StatsToolResult, build_stats_input, build_stats_input_from_records, - default_plan, fdr_correct, run_stats_tool, ) from evalrx.eval_agent.agentic import ( - AgenticDiagnoseLoop, + JudgePolicy, ToolOutcome, ToolRegistry, ToolSpec, @@ -143,15 +139,15 @@ RUN_LOG_SCHEMA_VERSION, SCHEMA_PATH, build_schema, - iter_log_errors, load_schema, validate_event, ) from evalrx.eval_agent.loop import VLDiagnoseLoop -from evalrx.eval_agent.loop_reports import AutoDiagnoseReport, VLDiagnoseReport +from evalrx.eval_agent.loop_reports import AutoDiagnoseReport from evalrx.eval_agent.nl_runner import scaffold_from_description +from evalrx.eval_agent.policy import FixedOrderPolicy from evalrx.eval_agent.run_context import RunContext -from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 +from evalrx.eval_agent.run_logger import RunLogger from evalrx.eval_agent.stages.case_discovery import ( CaseDiscoveryAgent, CaseDiscoveryReport, @@ -233,9 +229,9 @@ # Loop "AutoDiagnoseReport", "VLDiagnoseLoop", - "VLDiagnoseReport", - # Agentic loop (judge-decided M1-M4, alternative to VLDiagnoseLoop's fixed cycle) - "AgenticDiagnoseLoop", + # Policies: who picks the next stage + "FixedOrderPolicy", + "JudgePolicy", "ToolSpec", "ToolOutcome", "ToolRegistry", @@ -245,7 +241,6 @@ # M2 stats agent "StatsAnalysisAgent", "StatsAnalysisReport", - "StatsToolAgent", # M2 stats tools "StatsInput", "StatsToolResult", @@ -253,7 +248,6 @@ "STATS_TOOL_CATALOG", "build_stats_input", "build_stats_input_from_records", - "default_plan", "fdr_correct", "run_stats_tool", "ColumnProfile", @@ -281,13 +275,12 @@ "InMemoryStore", "JsonlStore", "RunContext", - "RunLoggerV2", + "RunLogger", # Published event schema "RUN_LOG_SCHEMA_VERSION", "build_schema", "load_schema", "validate_event", - "iter_log_errors", "SCHEMA_PATH", # Experiment execution "ExperimentWriter", @@ -302,9 +295,6 @@ "validate_entry_point", "validate_entry_point_resolved", # Sandbox factory - "SandboxConfig", - "SandboxFactoryConfig", - "create_sandbox", # NL scaffold "scaffold_from_description", # CLI agents diff --git a/evalrx/eval_agent/agentic/__init__.py b/evalrx/eval_agent/agentic/__init__.py index 9c404a92..a3002631 100644 --- a/evalrx/eval_agent/agentic/__init__.py +++ b/evalrx/eval_agent/agentic/__init__.py @@ -1,24 +1,17 @@ -"""Agentic diagnosis loop — a judge-decided alternative to VLDiagnoseLoop's -fixed M1->M2->M3->M4 cycle. See ``loop.py`` for the full picture. +"""Judge-decided next steps for VLDiagnoseLoop, in place of its fixed +M1->M2->M3->M4 cycle: ``VLDiagnoseLoop(..., policy=JudgePolicy(judge))``. - actions.py Action, parse_action, decide — judge output -> validated action + actions.py Action, decide — the judge's typed choice of the next tool board.py EvidenceBoard, BudgetState — what the judge sees each turn tools.py ToolSpec, ToolRegistry, build_default_registry — the M1-M4 tools - loop.py AgenticDiagnoseLoop + policy.py JudgePolicy """ from __future__ import annotations -from evalrx.eval_agent.agentic.actions import ( - ACTION_SCHEMA, - Action, - ActionParseError, - decide, - parse_action, - validate_json_shape, -) +from evalrx.eval_agent.agentic.actions import Action, decide from evalrx.eval_agent.agentic.board import BudgetState, EvidenceBoard -from evalrx.eval_agent.agentic.loop import AgenticDiagnoseLoop +from evalrx.eval_agent.agentic.policy import JudgePolicy from evalrx.eval_agent.agentic.tools import ( ToolOutcome, ToolRegistry, @@ -27,13 +20,9 @@ ) __all__ = [ - "AgenticDiagnoseLoop", + "JudgePolicy", "Action", - "ActionParseError", - "ACTION_SCHEMA", - "parse_action", "decide", - "validate_json_shape", "EvidenceBoard", "BudgetState", "ToolSpec", diff --git a/evalrx/eval_agent/agentic/actions.py b/evalrx/eval_agent/agentic/actions.py index c2f241fa..340aba7c 100644 --- a/evalrx/eval_agent/agentic/actions.py +++ b/evalrx/eval_agent/agentic/actions.py @@ -1,48 +1,31 @@ """Judge-decided actions for the agentic diagnosis loop. -Each decision turn, the CLI judge returns one strict JSON object describing -the next tool to call. ``parse_action`` turns that raw text into a validated -:class:`Action`, using the shared :func:`~evalrx.agent_runtime.json_shape.validate_json_shape` -(re-exported here for convenience — also used by M3's hypothesis parser and -failure-mode cluster naming). +Each decision turn, the judge picks the next tool. :func:`decide` asks for it +through :func:`~evalrx.agent_runtime.judge_call.ask_judge` with an output +model whose ``tool`` field only admits registered tool names, so an unknown +tool, a missing rationale or a non-JSON reply goes back to the judge with the +validation errors. When no valid answer comes back, the deterministic +next-unmet-stage heuristic runs instead and the decision is logged with +``valid=False``. """ from __future__ import annotations -import json import logging -import re -import time from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Literal -from evalrx.agent_runtime.json_shape import validate_json_shape +from pydantic import BaseModel, Field, create_model + +from evalrx.agent_runtime.judge_call import JudgeError, ask_judge if TYPE_CHECKING: from evalrx.eval_agent.agentic.board import EvidenceBoard from evalrx.eval_agent.agentic.tools import ToolRegistry - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger logger = logging.getLogger(__name__) -ACTION_SCHEMA: dict[str, Any] = { - "type": "object", - "required": ["tool", "rationale"], - "properties": { - "tool": {"type": "string", "minLength": 1}, - "params": {"type": "object"}, - "rationale": {"type": "string", "minLength": 1}, - }, -} - - -class ActionParseError(Exception): - """Raised when the judge's raw output cannot be turned into a valid Action.""" - - def __init__(self, message: str, errors: list[str] | None = None) -> None: - super().__init__(message) - self.errors = errors or [] - @dataclass class Action: @@ -56,47 +39,21 @@ class Action: valid: bool = True -def _strip_fences(text: str) -> str: - text = text.strip() - if text.startswith("```"): - text = re.sub(r"^```\w*\n?", "", text) - text = re.sub(r"\n?```\s*$", "", text) - return text.strip() - - -def parse_action(raw: str, registry: "ToolRegistry") -> Action: - """Parse the judge's raw text into a validated :class:`Action`. - - Raises :class:`ActionParseError` when the text is not JSON, fails the - action schema, or names a tool the registry doesn't know about. - """ - text = _strip_fences(raw) - try: - data = json.loads(text) - except json.JSONDecodeError as exc: - raise ActionParseError(f"not valid JSON: {exc}") from exc - - errors = validate_json_shape(data, ACTION_SCHEMA) - if errors: - raise ActionParseError("action schema validation failed", errors) - - tool = str(data["tool"]) - if tool not in registry.tool_names(): - raise ActionParseError( - f"unknown tool {tool!r}", [f"must be one of {sorted(registry.tool_names())}"] - ) - - params = data.get("params") or {} - if not isinstance(params, dict): - raise ActionParseError("params must be an object", [f"$.params: got {type(params).__name__}"]) - - return Action(tool=tool, params=params, rationale=str(data["rationale"]), raw=raw) +def action_model(registry: "ToolRegistry") -> type[BaseModel]: + """The decision's output model: ``tool`` is one of *registry*'s names.""" + tool_name: Any = Literal[tuple(sorted(registry.tool_names()))] + return create_model( + "NextAction", + tool=(tool_name, Field(description="a tool name from AVAILABLE TOOLS")), + params=(dict[str, Any], Field(default_factory=dict, description="the tool's parameters")), + rationale=(str, Field(min_length=1, description="one sentence: why this tool, why now")), + ) def _fallback_action(board: "EvidenceBoard") -> Action: """Deterministic next-step heuristic: the first unmet M1->M4 stage. - Used when the judge's output is unusable even after one repair prompt, so + Used when the judge fails or gives no valid answer within its retries, so a stuck judge doesn't stall the run — the action is marked ``valid=False`` so the loop can track a consecutive-failure streak and give up cleanly. """ @@ -122,81 +79,39 @@ def decide( board: "EvidenceBoard", registry: "ToolRegistry", *, - run_logger: "RunLoggerV2 | None" = None, + run_logger: "RunLogger | None" = None, step: int = 0, - max_repairs: int = 1, + retries: int = 1, ) -> Action: - """Ask the judge for the next action, repairing/falling back as needed. + """Ask the judge for the next action; never raises. - Always returns an :class:`Action` — never raises. When the judge's - response can't be salvaged after *max_repairs* repair prompts, returns the - deterministic :func:`_fallback_action` with ``valid=False``. + An answer that fails validation is sent back up to *retries* times. When + the judge fails or no answer is valid, returns :func:`_fallback_action` + with ``valid=False``. """ - from evalrx.eval_agent.prompts.agentic import ACTION_REPAIR_PROMPT, DECISION_PROMPT + from evalrx.eval_agent.prompts.agentic import DECISION_PROMPT - evidence = board.to_prompt(registry) - prompt = DECISION_PROMPT.format(evidence=evidence) - judge_calls: list[dict[str, Any]] = [] - started = time.perf_counter() + prompt = DECISION_PROMPT.format(evidence=board.to_prompt(registry)) try: - raw = judge.generate(prompt) - except Exception as exc: # noqa: BLE001 - judge_calls.append({ - "role": "agent_decision", "operation": "generate", "inputs": prompt, - "output": None, "error": str(exc), - "duration_sec": time.perf_counter() - started, - }) - raw = "" - action: Action | None = _fallback_action(board) - else: - judge_calls.append({ - "role": "agent_decision", "operation": "generate", "inputs": prompt, - "output": str(raw), "error": None, - "duration_sec": time.perf_counter() - started, - }) - try: - action = parse_action(raw, registry) - except ActionParseError as exc: - action = None - last_raw, last_exc = raw, exc - if action is None: - for attempt in range(1, max_repairs + 1): - repair_prompt = ACTION_REPAIR_PROMPT.format( - raw=last_raw, - errors="\n".join(last_exc.errors) or str(last_exc), - evidence=evidence, - ) - started = time.perf_counter() - try: - last_raw = judge.generate(repair_prompt) - except Exception as exc: # noqa: BLE001 - judge_calls.append({ - "role": "agent_decision_repair", "operation": "generate", - "inputs": repair_prompt, "output": None, "error": str(exc), - "duration_sec": time.perf_counter() - started, - "metadata": {"attempt": attempt}, - }) - break - judge_calls.append({ - "role": "agent_decision_repair", "operation": "generate", - "inputs": repair_prompt, "output": str(last_raw), "error": None, - "duration_sec": time.perf_counter() - started, - "metadata": {"attempt": attempt}, - }) - try: - action = parse_action(last_raw, registry) - action.repair_attempts = attempt - break - except ActionParseError as exc2: - last_exc = exc2 - action = None - if action is None: + reply = ask_judge( + judge, prompt, action_model(registry), role="agent_decision", retries=retries, + ) + except JudgeError as exc: + logger.warning("decide: %s; using the next-unmet-stage heuristic", exc) + exchanges = exc.exchanges action = _fallback_action(board) - action.raw = raw + else: + exchanges = reply.exchanges + chosen = reply.output + action = Action( + tool=str(chosen.tool), params=dict(chosen.params), rationale=chosen.rationale, # type: ignore[attr-defined] + repair_attempts=len(exchanges) - 1, + ) + action.raw = (exchanges[-1].output or "") if exchanges else "" if run_logger is not None: try: - log_kwargs = dict( + run_logger.log_agent_decision( step=step, action=action.tool, params=action.params, @@ -205,11 +120,9 @@ def decide( repair_attempts=action.repair_attempts, fallback_used=not action.valid, judge_prompt=prompt, - judge_raw=raw, + judge_raw=action.raw, + judge_calls=[e.record() for e in exchanges], ) - if getattr(run_logger, "preserve_full_model_io", False): - log_kwargs["judge_calls"] = judge_calls - run_logger.log_agent_decision(**log_kwargs) except Exception: # noqa: BLE001 — logging must never break the loop logger.warning("decide: log_agent_decision failed", exc_info=True) diff --git a/evalrx/eval_agent/agentic/loop.py b/evalrx/eval_agent/agentic/loop.py deleted file mode 100644 index 80a4c18c..00000000 --- a/evalrx/eval_agent/agentic/loop.py +++ /dev/null @@ -1,187 +0,0 @@ -"""AgenticDiagnoseLoop — an LLM-driven decision loop over the M1-M4 stages. - -``VLDiagnoseLoop`` runs M1->M2->M3->M4 in a hardcoded sequence every cycle. -This loop keeps every stage (and the confirm-split / post-loop run_m5/run_fix -discipline) exactly as-is, but replaces the fixed sequence with a CLI judge -that decides, one tool call at a time, what to do next — probe, run stats, -explore the raw data, propose hypotheses, test one, fix, or stop. The host, -not the judge, enforces call caps, tool preconditions, and the pre-registered -stopping discipline (no declaring success without a tested, supported, -protocol-consistent hypothesis). - -``VLDiagnoseLoop`` itself is untouched — this is a new mode, not a -replacement (see the module docstring in ``eval_agent/loop.py``). -""" - -from __future__ import annotations - -import logging -from typing import TYPE_CHECKING, Any - -from evalrx.eval_agent.agentic.actions import decide -from evalrx.eval_agent.agentic.board import BudgetState, EvidenceBoard -from evalrx.eval_agent.agentic.tools import ToolRegistry, _RunState, build_default_registry -from evalrx.eval_agent.loop import VLDiagnoseLoop -from evalrx.eval_agent.loop_reports import VLDiagnoseReport -from evalrx.eval_agent.run_metadata import _data_provenance - -if TYPE_CHECKING: - from evalrx.core.case import CaseBatch - -logger = logging.getLogger(__name__) - -_MAX_INVALID_STREAK = 3 - - -def _protocol_summary(protocol: "Any | None") -> str: - if protocol is None: - return "" - bits = [f"description: {getattr(protocol, 'description', '')}"] - domain = getattr(protocol, "task_domain", None) - if domain: - bits.append(f"task_domain: {domain}") - patterns = getattr(protocol, "failure_patterns", None) - if patterns: - bits.append(f"failure_patterns: {patterns}") - return "\n".join(bits) - - -class AgenticDiagnoseLoop(VLDiagnoseLoop): - """M1-M4 investigation driven by judge decisions instead of a fixed cycle. - - Reuses :class:`~evalrx.eval_agent.loop.VLDiagnoseLoop`'s constructor, - stage helpers (``_do_m1``..``_do_m4``), confirm-split, and post-loop - ``run_m5``/``run_fix`` — only :meth:`run` differs. - - Args: - judge: CLI-backed judge that decides the next action each - turn (e.g. ``ClaudeModel()`` / ``AgyModel()``). - Required — this is a genuinely new capability, not - a Gemini-fallback stage judge. - explorer: Optional ``ExploratoryAnalysisAgent`` — when given, - registers the ``explore_data`` tool. - max_actions: Hard cap on judge decision turns (default 12). - time_budget_sec: Wall-clock cap for the whole run (0 = unlimited). - registry_factory: Advanced override — ``(loop, run_state) -> ToolRegistry`` - instead of :func:`build_default_registry`. - **kwargs: Forwarded to ``VLDiagnoseLoop.__init__`` (model, - protocol, probe_agent, stats_agent, hypothesis_tester, - surgery_agent, fix_agent, store, token_budget, - confirm_split, run_logger, ...). - """ - - def __init__( - self, - model: "Any", - protocol: "Any", - *, - judge: "Any", - explorer: "Any | None" = None, - max_actions: int = 12, - time_budget_sec: float = 0.0, - registry_factory: "Any | None" = None, - **kwargs: Any, - ) -> None: - super().__init__(model, protocol, **kwargs) - if judge is None: - raise ValueError( - "AgenticDiagnoseLoop requires a decision judge, e.g. " - "judge=ClaudeModel() or judge=AgyModel()." - ) - self.judge = judge - self.explorer = explorer - self.max_actions = max_actions - self.time_budget_sec = time_budget_sec - self._registry_factory = registry_factory - - def run(self, data: "CaseBatch") -> VLDiagnoseReport: - """Drive the judge-decided action loop to a stop or a budget limit.""" - self._tokens_used = 0 - timings: dict[str, float] = {} - - explore, confirm = self._split_explore_confirm(data) - original_data = data - if confirm is not None: - data = explore - - # run_start's judge is the M3 *stage* judge (loop.diagnosis_agent.judge), - # not the decision judge driving this loop's own tool-calling — add it - # explicitly so the report header can show who is actually deciding. - self._start_run_log( - data, "AgenticDiagnoseLoop", confirm=confirm, - extra={"decision_judge": repr(self.judge), "max_actions": self.max_actions}, - ) - - board = EvidenceBoard( - protocol_summary=_protocol_summary(self.protocol), - data_summary=_data_provenance(data), - budget=BudgetState( - max_actions=self.max_actions, - token_budget=self.token_budget, - time_budget_sec=self.time_budget_sec, - ), - ) - board.budget.start() - - state = _RunState(original_data=original_data, data=data, timings=timings) - registry: ToolRegistry = ( - self._registry_factory(self, state) - if self._registry_factory is not None - else build_default_registry(self, state) - ) - - stopped_by = "max_actions" - invalid_streak = 0 - step = 0 - while True: - reason = board.budget.exhausted() - if reason: - stopped_by = reason - break - - action = decide(self.judge, board, registry, run_logger=self.run_logger, step=step) - board.budget.actions_taken += 1 - invalid_streak = 0 if action.valid else invalid_streak + 1 - - outcome = registry.dispatch(action, board) - board.action_log.append({ - "step": step, "tool": action.tool, "params": action.params, - "ok": outcome.ok, "summary": outcome.summary, - }) - if self.run_logger is not None: - self.run_logger.log_agent_tool( - step, tool=action.tool, ok=outcome.ok, - summary=outcome.summary, error=outcome.error, - ) - - if action.tool == "stop" and outcome.ok: - stopped_by = "agent_stop" - step += 1 - break - - if invalid_streak >= _MAX_INVALID_STREAK: - logger.warning( - "AgenticDiagnoseLoop: %d consecutive invalid actions — stopping.", - invalid_streak, - ) - stopped_by = "invalid_actions" - step += 1 - break - - step += 1 - - if state.diagnosis_failed: - stopped_by = "diagnosis_error" - verified = self.hypothesis_tester.best_hypotheses(state.all_test_results) - report = VLDiagnoseReport( - cycles=step, - resolved=bool(verified), - stopped_by=stopped_by, - verified_hypotheses=verified, - final_hypotheses=state.all_hypotheses, - all_test_results=state.all_test_results, - final_stats_report=state.stats_report, - store=self.store, - _run_id=self._run_id, - ) - return self._end_run(report, timings) diff --git a/evalrx/eval_agent/agentic/policy.py b/evalrx/eval_agent/agentic/policy.py new file mode 100644 index 00000000..d8253940 --- /dev/null +++ b/evalrx/eval_agent/agentic/policy.py @@ -0,0 +1,166 @@ +"""JudgePolicy — a judge picks each next stage of a VLDiagnoseLoop run. + +By default ``VLDiagnoseLoop`` runs M1->M2->M3->M4 in a fixed cycle +(``FixedOrderPolicy``). Given ``policy=JudgePolicy(judge)``, the same loop +instead asks the judge, one tool +call at a time, what to do next — probe, run stats, explore the raw data, +propose hypotheses, test one, fix, or stop. The stages, the confirm split and +the post-loop run_m5/run_fix discipline stay the loop's own. The host, not the +judge, enforces call caps, tool preconditions, and the pre-registered stopping +discipline (no declaring success without a tested, supported, +protocol-consistent hypothesis). +""" + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING, Any + +from evalrx.eval_agent.agentic.actions import decide +from evalrx.eval_agent.agentic.board import BudgetState, EvidenceBoard +from evalrx.eval_agent.agentic.tools import ToolRegistry, build_default_registry +from evalrx.eval_agent.loop_reports import STOPPED_BY_DIAG_ERROR, AutoDiagnoseReport +from evalrx.eval_agent.policy import RunState +from evalrx.eval_agent.run_metadata import _data_provenance + +if TYPE_CHECKING: + from evalrx.core.case import CaseBatch + from evalrx.eval_agent.loop import VLDiagnoseLoop + +logger = logging.getLogger(__name__) + +_MAX_INVALID_STREAK = 3 + + +def _protocol_summary(protocol: "Any | None") -> str: + if protocol is None: + return "" + bits = [f"description: {getattr(protocol, 'description', '')}"] + domain = getattr(protocol, "task_domain", None) + if domain: + bits.append(f"task_domain: {domain}") + patterns = getattr(protocol, "failure_patterns", None) + if patterns: + bits.append(f"failure_patterns: {patterns}") + return "\n".join(bits) + + +class JudgePolicy: + """Next-step policy for :class:`~evalrx.eval_agent.loop.VLDiagnoseLoop`. + + Args: + judge: Judge that decides the next action each turn (e.g. + ``ClaudeModel()`` / ``AgyModel()``). + max_actions: Hard cap on decision turns (default 12). + time_budget_sec: Wall-clock cap for the whole run (0 = unlimited). + registry_factory: ``(loop, run_state) -> ToolRegistry`` in place of + :func:`build_default_registry` (e.g. to withhold + the repair tools). + + The loop's ``explorer`` (when set) becomes the ``explore_data`` tool + instead of running in every cycle. + """ + + def __init__( + self, + judge: Any, + *, + max_actions: int = 12, + time_budget_sec: float = 0.0, + registry_factory: "Any | None" = None, + ) -> None: + if judge is None: + raise ValueError("JudgePolicy needs a decision judge, e.g. ClaudeModel() or AgyModel().") + self.judge = judge + self.max_actions = max_actions + self.time_budget_sec = time_budget_sec + self.registry_factory = registry_factory + + def run(self, loop: "VLDiagnoseLoop", data: "CaseBatch", + timings: dict[str, float]) -> AutoDiagnoseReport: + """Drive the judge-decided action loop to a stop or a budget limit.""" + explore, confirm = loop._split_explore_confirm(data) + original_data = data + if confirm is not None: + data = explore + + # run_start's judge is the M3 *stage* judge; the decision judge is + # recorded separately so the report shows who is actually deciding. + loop._start_run_log( + data, "JudgePolicy", confirm=confirm, + extra={"decision_judge": repr(self.judge), "max_actions": self.max_actions}, + ) + + board = EvidenceBoard( + protocol_summary=_protocol_summary(loop.protocol), + data_summary=_data_provenance(data), + budget=BudgetState( + max_actions=self.max_actions, + token_budget=loop.token_budget, + time_budget_sec=self.time_budget_sec, + ), + ) + board.budget.start() + + state = RunState(original_data=original_data, data=data, timings=timings, + judge=self.judge) + registry: ToolRegistry = ( + self.registry_factory(loop, state) + if self.registry_factory is not None + else build_default_registry(loop, state) + ) + + stopped_by = "max_actions" + invalid_streak = 0 + step = 0 + while True: + reason = board.budget.exhausted() + if reason: + stopped_by = reason + break + + action = decide(self.judge, board, registry, run_logger=loop.run_logger, step=step) + board.budget.actions_taken += 1 + invalid_streak = 0 if action.valid else invalid_streak + 1 + + outcome = registry.dispatch(action, board) + board.action_log.append({ + "step": step, "tool": action.tool, "params": action.params, + "ok": outcome.ok, "summary": outcome.summary, + }) + if loop.run_logger is not None: + loop.run_logger.log_agent_tool( + step, tool=action.tool, ok=outcome.ok, + summary=outcome.summary, error=outcome.error, + ) + + if action.tool == "stop" and outcome.ok: + stopped_by = "agent_stop" + step += 1 + break + + if invalid_streak >= _MAX_INVALID_STREAK: + logger.warning( + "JudgePolicy: %d consecutive invalid actions — stopping.", + invalid_streak, + ) + stopped_by = "invalid_actions" + step += 1 + break + + step += 1 + + if state.diagnosis_failed: + stopped_by = STOPPED_BY_DIAG_ERROR + verified = loop.hypothesis_tester.best_hypotheses(state.all_test_results) + return AutoDiagnoseReport( + cycles=step, + resolved=bool(verified), + stopped_by=stopped_by, + verified_hypotheses=verified, + final_hypotheses=state.all_hypotheses, + all_test_results=state.all_test_results, + final_stats_report=state.stats_report, + store=loop.store, + _run_id=loop._run_id, + ) diff --git a/evalrx/eval_agent/agentic/tools.py b/evalrx/eval_agent/agentic/tools.py index e049d038..5e472666 100644 --- a/evalrx/eval_agent/agentic/tools.py +++ b/evalrx/eval_agent/agentic/tools.py @@ -9,13 +9,15 @@ from __future__ import annotations -from dataclasses import dataclass, field +from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Callable +from evalrx.eval_agent.policy import RunState, cycle_summary + if TYPE_CHECKING: from evalrx.eval_agent.agentic.actions import Action from evalrx.eval_agent.agentic.board import EvidenceBoard - from evalrx.eval_agent.loop_reports import VLDiagnoseReport + from evalrx.eval_agent.loop_reports import AutoDiagnoseReport @dataclass(frozen=True) @@ -118,33 +120,6 @@ def dispatch(self, action: "Action", board: "EvidenceBoard") -> ToolOutcome: # --------------------------------------------------------------------------- -@dataclass -class _RunState: - """Mutable, per-run state the default tool handlers read and update. - - Mirrors the local variables ``VLDiagnoseLoop.run()`` keeps on its stack — - an agentic run just spreads the same bookkeeping across tool calls instead - of a fixed cycle. - """ - - original_data: Any - data: Any - cycle: int = 0 - timings: dict[str, float] = field(default_factory=dict) - all_hypotheses: list[Any] = field(default_factory=list) - pending_hypotheses: list[Any] = field(default_factory=list) - all_test_results: list[Any] = field(default_factory=list) - prior_cycles: list[dict[str, Any]] = field(default_factory=list) - probe_results: dict[str, Any] = field(default_factory=dict) - artifact_pngs: list[Any] = field(default_factory=list) - stats_report: Any = None - failure_modes: Any = None - probe_search_result: Any = None - surgery_outcome: Any = None - fix_outcome: Any = None - diagnosis_failed: bool = False - - def _summarize_probe(probe_results: dict[str, Any]) -> list[dict[str, Any]]: """Compact, board-friendly summary of one M1 pass (scalars only, no per-case rows).""" out = [] @@ -170,12 +145,12 @@ def _summarize_stats(report: Any) -> list[dict[str, Any]]: ] -def _current_report(loop: Any, state: _RunState) -> "VLDiagnoseReport": +def _current_report(loop: Any, state: RunState) -> "AutoDiagnoseReport": """Snapshot the run so far into the same report shape run_m5/run_fix expect.""" - from evalrx.eval_agent.loop_reports import VLDiagnoseReport + from evalrx.eval_agent.loop_reports import AutoDiagnoseReport verified = loop.hypothesis_tester.best_hypotheses(state.all_test_results) - return VLDiagnoseReport( + return AutoDiagnoseReport( cycles=state.cycle, resolved=bool(verified), stopped_by="in_progress", @@ -225,7 +200,7 @@ def _requested_probes(params: "dict[str, Any]") -> "list[tuple[str, dict[str, An return out -def _list_probes(loop: Any, state: _RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": +def _list_probes(loop: Any, state: RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: from evalrx.probing import ProbeRouter @@ -262,7 +237,7 @@ def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: return handler -def _run_probe(loop: Any, state: _RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": +def _run_probe(loop: Any, state: RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: requested = _requested_probes(params or {}) if isinstance(requested, str): @@ -341,7 +316,7 @@ def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: return handler -def _run_stats(loop: Any, state: _RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": +def _run_stats(loop: Any, state: RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: confirmatory = bool(params.get("confirmatory", True)) stats_report = loop._do_m2( @@ -362,7 +337,7 @@ def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: return handler -def _explore_data(loop: Any, state: _RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": +def _explore_data(loop: Any, state: RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: question = str( params.get("question") @@ -384,7 +359,7 @@ def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: return handler -def _cluster_failures(loop: Any, state: _RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": +def _cluster_failures(loop: Any, state: RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: from evalrx.analysis.failure_modes import cluster_failures from evalrx.analysis.operationalize import per_case_to_records @@ -412,7 +387,7 @@ def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: return handler -def _search_probes(loop: Any, state: _RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": +def _search_probes(loop: Any, state: RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: from evalrx.eval_agent.stages.probe_search_agent import ProbeSearchAgent @@ -421,7 +396,7 @@ def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: return ToolOutcome(False, "no seed cases available to probe", error="empty") budget = int(params.get("budget", 10)) agent = ProbeSearchAgent( - judge=loop.judge, protocol=loop.protocol, budget=budget, + judge=state.judge, protocol=loop.protocol, budget=budget, run_logger=getattr(loop, "run_logger", None), ) result = agent.run(loop.model, seed_pool) @@ -445,7 +420,7 @@ def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: return handler -def _propose_hypotheses(loop: Any, state: _RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": +def _propose_hypotheses(loop: Any, state: RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: diag = loop._do_m3( state.cycle, state.stats_report, state.prior_cycles, state.timings, @@ -469,24 +444,13 @@ def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: } for h in state.all_hypotheses ] - state.prior_cycles.append({ - "cycle": state.cycle, - "severity": getattr(state.stats_report, "severity", "none"), - "hypotheses": [ - { - "statement": h.statement, - "failure_mode": h.predicted_failure_mode, - "status": h.status.value if h.status else "pending", - } - for h in diag.hypotheses - ], - }) + state.prior_cycles.append(cycle_summary(state.cycle, state.stats_report, diag.hypotheses)) return ToolOutcome(True, f"proposed {len(diag.hypotheses)} hypothesis(es)", payload=diag) return handler -def _test_hypothesis(loop: Any, state: _RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": +def _test_hypothesis(loop: Any, state: RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: if not state.pending_hypotheses: return ToolOutcome( @@ -521,7 +485,7 @@ def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: return handler -def _run_surgery(loop: Any, state: _RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": +def _run_surgery(loop: Any, state: RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: report = _current_report(loop, state) iv = loop.run_m5(report, state.original_data) @@ -533,7 +497,7 @@ def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: return handler -def _run_fix(loop: Any, state: _RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": +def _run_fix(loop: Any, state: RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: report = _current_report(loop, state) outcome = loop.run_fix(report, state.original_data) @@ -546,7 +510,7 @@ def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: return handler -def _stop(loop: Any, state: _RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": +def _stop(loop: Any, state: RunState) -> "Callable[[EvidenceBoard, dict], ToolOutcome]": def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: resolved = bool(params.get("resolved", False)) reason = str(params.get("reason") or "") @@ -555,8 +519,8 @@ def handler(board: "EvidenceBoard", params: dict[str, Any]) -> ToolOutcome: return handler -def build_default_registry(loop: Any, state: _RunState) -> ToolRegistry: - """Build the default M1-M4 tool registry for one :class:`AgenticDiagnoseLoop` run.""" +def build_default_registry(loop: Any, state: RunState) -> ToolRegistry: + """Build the default M1-M4 tool registry for one :class:`JudgePolicy` run.""" registry = ToolRegistry() registry.register(ToolSpec( name="list_probes", diff --git a/evalrx/eval_agent/label_quarantine.py b/evalrx/eval_agent/label_quarantine.py index d65fe319..0a65afae 100644 --- a/evalrx/eval_agent/label_quarantine.py +++ b/evalrx/eval_agent/label_quarantine.py @@ -113,10 +113,10 @@ def quarantine_run_dir( run_dir: The run directory (``baseline.json``, ``logs/``, ...). append_logs: Files that a live handler holds open in append mode. They are truncated to zero length instead of unlinked - and restored as ``old + new``. RunLoggerV2 rewrites its + and restored as ``old + new``. RunLogger rewrites its documents atomically instead of appending, so its callers pass ``rewrite_logs`` (see - ``RunLoggerV2.managed_json_paths``), not this. + ``RunLogger.managed_json_paths``), not this. keep: Relative path prefixes (POSIX style) to leave visible, e.g. ``("logs/fixes",)`` when resuming a fix search. write_manifest: Write ``fix_quarantine.json`` into *run_dir* on exit. diff --git a/evalrx/eval_agent/log_schema.py b/evalrx/eval_agent/log_schema.py index e250ac3b..cdc97e37 100644 --- a/evalrx/eval_agent/log_schema.py +++ b/evalrx/eval_agent/log_schema.py @@ -2,7 +2,7 @@ A run's events (``run_start``, ``probe``, ``diagnosis``, ...) are the contract between a diagnosis run and everything downstream (dashboards, -parsers, the agent's own memory) — RunLoggerV2 stores them bucketed into +parsers, the agent's own memory) — RunLogger stores them bucketed into ``run.json`` + per-stage ``M/log.json`` rather than a flat JSONL file, but each individual event has this same shape wherever it lives. Until this module existed that contract lived only in docstrings + a table in @@ -19,8 +19,8 @@ ``run_log.schema.json`` (shipped as package data) so non-Python consumers can validate too; :func:`load_schema` reads it and a drift test keeps the two in lock-step. -* :func:`validate_event` / :func:`iter_log_errors` validate real log lines. - They need the ``jsonschema`` package (a *dev*/optional dep, not core) and +* :func:`validate_event` validates one logged event. + It needs the ``jsonschema`` package (a *dev*/optional dep, not core) and raise a clear, actionable error if it is missing rather than failing obscurely. Design note — the schema is intentionally **permissive**: it pins the common @@ -58,9 +58,14 @@ # pre-rename logs. # v6: folded in the bucketed-storage events (`model_call`, `diagnose_report`, # `unrouted`) and the `stage`/`event_seq`/`span_id` envelope fields that -# were previously a separate, RunLoggerV2-only schema layered on top of +# were previously a separate, RunLogger-only schema layered on top of # this one — there is now one event schema, not a base plus an overlay. -RUN_LOG_SCHEMA_VERSION = 6 +# v7: `run_end`, written when the logger closes: the run-level completion +# signal. `loop_end` ends M1-M4 only; M5 and the fix step log after it. +# v8: `analysis` no longer carries `stats_tool_results` / `visualizations` +# (summaries from a retired tool layer); `stats_results` and `figures` +# hold the same information. +RUN_LOG_SCHEMA_VERSION = 8 #: The event types a run logs. EVENT_TYPES: tuple[str, ...] = ( @@ -73,6 +78,7 @@ "experiment", "fix", "loop_end", + "run_end", "tool_codegen", "tool_registry", "agent_decision", @@ -101,19 +107,8 @@ }, } -_JUDGE_IO = { - "type": "object", - "properties": { - "prompt_path": {"type": "string"}, - "prompt_chars": {"type": "integer"}, - "raw_path": {"type": "string"}, - "raw_chars": {"type": "integer"}, - }, -} - -# An M2 stats field is either its raw value (object/array) or, once it exceeds -# the inline-size threshold, an externalized {path, n_items, bytes} pointer. -_INLINE_OR_EXTERNAL = {"type": ["object", "array"]} +# An M2 stats field: a list of rows, or one object. +_ROWS_OR_OBJECT = {"type": ["object", "array"]} # Per-event field schemas + the fields each event always carries ------------- # (event, schema_version, ts, trace_id come from the shared envelope.) @@ -129,7 +124,7 @@ "label_distribution": {"type": "object"}, "n_cases": {"type": "integer"}, "model": {"type": "string"}, - # AgenticDiagnoseLoop only: the decision judge (distinct from the M3 + # JudgePolicy runs only: the decision judge (distinct from the M3 # stage judge already covered by "judge") and its action-turn budget. "decision_judge": {"type": "string"}, "max_actions": {"type": "integer"}, @@ -145,17 +140,13 @@ "artifact_paths": {"type": "object"}, # Additive M1 fields (permissive schema): result_paths (per-analyzer # complete result json), failed_analyzers (selected-but-errored), - # selected_analyzers — see RunLoggerV2.log_probe. + # selected_analyzers — see RunLogger.log_probe. "selection_rationale": {"type": "string"}, - "judge_io": _JUDGE_IO, "duration_sec": {"type": "number"}, - # Every generate/forward/logprobs/chat call an analyzer made against - # the target model this cycle (see model_instrumentation.py); full - # verbatim records live in the sibling model_calls.jsonl this points - # to, kept out of this event so an analyzer making dozens of calls - # per case doesn't drown out the cycle-level narrative. + # How many generate/forward/logprobs/chat calls the analyzers made + # against the target model this cycle (see model_instrumentation.py); + # each call is its own ``model_call`` event. "n_model_calls": {"type": "integer"}, - "model_calls_path": {"type": "string"}, }, }, "analysis": { @@ -167,13 +158,10 @@ "narrative": {"type": "string"}, "conclusion": {"type": "string"}, "evidence_chain": {"type": "array"}, - "stats_tool_results": _INLINE_OR_EXTERNAL, - "stats_plan": _INLINE_OR_EXTERNAL, - "stats_results": _INLINE_OR_EXTERNAL, - "corrected_rejections": _INLINE_OR_EXTERNAL, - "visualizations": {"type": "array"}, + "stats_plan": _ROWS_OR_OBJECT, + "stats_results": _ROWS_OR_OBJECT, + "corrected_rejections": _ROWS_OR_OBJECT, "figures": {"type": "array"}, - "judge_io": _JUDGE_IO, "duration_sec": {"type": "number"}, }, }, @@ -219,7 +207,6 @@ # Whether a (clustered, descriptive-only) FailureModeReport was # shown to M3 — additive field, no schema version bump needed. "failure_modes_used": {"type": "boolean"}, - "judge_io": _JUDGE_IO, "duration_sec": {"type": "number"}, }, }, @@ -237,7 +224,6 @@ "duration_sec": {"type": "number"}, # Additive: M4 protocol-consistency judge prompt/response, persisted # under prompts/ (same pattern as probe/analysis/diagnosis). - "judge_io": _JUDGE_IO, }, }, "experiment": { @@ -253,17 +239,13 @@ "returncode": {"type": ["integer", "null"]}, "timed_out": {"type": ["boolean", "null"]}, "llm_calls": {"type": ["integer", "null"]}, - "code_paths": {"type": "object"}, - "output_paths": {"type": "object"}, "workspace_snapshot": {"type": ["object", "null"]}, - "record": {"type": "string"}, }, }, "fix": { "required": ["cycle", "module"], "properties": { "module": {"type": "string"}, - "record": {"type": "string"}, }, }, "loop_end": { @@ -281,6 +263,7 @@ "verified_hypotheses": {"type": "array"}, }, }, + "run_end": {"required": [], "properties": {}}, "tool_codegen": { "required": ["cycle", "module", "tool_name", "need", "source", "ok"], "properties": { @@ -290,7 +273,6 @@ "source": {"type": "string"}, "ok": {"type": "boolean"}, "error": {"type": ["string", "null"]}, - "code_paths": {"type": "object"}, }, }, "tool_registry": { @@ -311,7 +293,6 @@ "valid": {"type": "boolean"}, "repair_attempts": {"type": "integer"}, "fallback_used": {"type": "boolean"}, - "judge_io": _JUDGE_IO, "duration_sec": {"type": "number"}, }, }, @@ -461,7 +442,7 @@ def _validator(schema: dict[str, Any] | None = None): import jsonschema except ImportError as exc: # pragma: no cover - exercised via message only raise ImportError( - "validating run_log.jsonl needs the 'jsonschema' package — " + "validating a run log needs the 'jsonschema' package — " "install it with `pip install jsonschema` or `pip install evalrx[dev]`." ) from exc schema = schema if schema is not None else build_schema() @@ -473,25 +454,3 @@ def _validator(schema: dict[str, Any] | None = None): def validate_event(event: dict[str, Any], *, schema: dict[str, Any] | None = None) -> None: """Validate a single decoded event; raise ``jsonschema.ValidationError`` if bad.""" _validator(schema).validate(event) - - -def iter_log_errors(path: str | Path, *, schema: dict[str, Any] | None = None): - """Yield ``(line_number, message)`` for every invalid line in a JSONL log. - - A convenience for CI / downstream consumers: parse-and-validate a whole - ``run_log.jsonl`` in one call. Lines that aren't valid JSON are reported - too. An empty iterator means the file fully conforms. - """ - validator = _validator(schema) - with open(path, encoding="utf-8") as fh: - for i, line in enumerate(fh, start=1): - line = line.strip() - if not line: - continue - try: - event = json.loads(line) - except json.JSONDecodeError as exc: - yield i, f"invalid JSON: {exc}" - continue - for err in validator.iter_errors(event): - yield i, err.message diff --git a/evalrx/eval_agent/loop.py b/evalrx/eval_agent/loop.py index 67111b69..59a1eb45 100755 --- a/evalrx/eval_agent/loop.py +++ b/evalrx/eval_agent/loop.py @@ -13,10 +13,10 @@ loop stops — propose a fix for the best verified hypothesis (Plan A), or propose + execute a fix (Plan B). -See also: - - :class:`~evalrx.eval_agent.agentic.AgenticDiagnoseLoop` — the same - M1-M4 stages driven by a judge-decided action loop instead of a fixed - cycle. +The order of the stages is a policy (:mod:`evalrx.eval_agent.policy`): the +default :class:`~evalrx.eval_agent.policy.FixedOrderPolicy` runs the cycle +above; ``VLDiagnoseLoop(..., policy=JudgePolicy(judge))`` lets a judge pick +each next stage instead (:class:`~evalrx.eval_agent.agentic.JudgePolicy`). Usage:: @@ -38,7 +38,6 @@ import logging import random import time -from dataclasses import dataclass, field from pathlib import Path from typing import TYPE_CHECKING, Any @@ -49,10 +48,18 @@ _fix_hypotheses, _log_fix, _merge_rungs, - _propose_and_validate, _unverified_hypotheses, ) -from evalrx.eval_agent.loop_reports import VLDiagnoseReport +from evalrx.eval_agent.loop_reports import ( + STOPPED_BY_ANALYSIS, + STOPPED_BY_CRITERIA, + STOPPED_BY_DIAG_ERROR, + STOPPED_BY_MAX, + STOPPED_BY_NO_HYPS, + STOPPED_BY_NO_PROBE, + AutoDiagnoseReport, +) +from evalrx.eval_agent.policy import FixedOrderPolicy, Policy from evalrx.eval_agent.run_metadata import ( _attach_run_logger, _coerce_explore_context, @@ -63,6 +70,8 @@ from evalrx.eval_agent.store import InMemoryStore, Store if TYPE_CHECKING: + from collections.abc import Mapping + from evalrx.analysis.stats_agent import StatsAnalysisAgent from evalrx.core.case import CaseBatch from evalrx.core.model import Model @@ -71,46 +80,6 @@ logger = logging.getLogger(__name__) -_STOPPED_BY_CRITERIA = "criteria_met" -_STOPPED_BY_MAX = "max_cycles" -_STOPPED_BY_BUDGET = "budget" -_STOPPED_BY_NO_HYPS = "no_hypotheses" -_STOPPED_BY_DIAG_ERROR = "diagnosis_error" -_STOPPED_BY_NO_PROBE = "no_probe_results" -# run_analysis() ran M1->M2->M3 and proposed hypotheses without confirming them -# (M4 deferred to run_confirm()). Not a failure — the analysis report is ready. -_STOPPED_BY_ANALYSIS = "analysis_complete" - - -@dataclass -class _LoopState: - """What :meth:`VLDiagnoseLoop.run` accumulates across cycles.""" - - hypotheses: list = field(default_factory=list) - test_results: list = field(default_factory=list) - #: Each finished cycle's summary, M3's context for the next one. - prior_cycles: list = field(default_factory=list) - stats_report: Any = None - #: The last M1's analyzers — what the held-out M4 pass re-runs. - analyzer_names: list = field(default_factory=list) - - -def _cycle_summary(cycle: int, stats_report: Any, hypotheses: list) -> dict[str, Any]: - """One finished cycle as the next M3 call sees it.""" - return { - "cycle": cycle, - "severity": stats_report.severity, - "hypotheses": [ - { - "statement": h.statement, - "failure_mode": h.predicted_failure_mode, - "status": h.status.value if h.status else "pending", - } - for h in hypotheses - ], - } - - def _exact_size(picked: "list", pool: "list", n: int, seed: int) -> "list": """Top a stratified draw up to exactly *n* items, deterministically. @@ -141,6 +110,7 @@ def _diagnose_with_optional_context( optional = {"explore_context": explore_context, "failure_modes": failure_modes, "cases": cases} if any(v is not None for v in optional.values()): + params: "Mapping[str, _inspect.Parameter]" try: params = _inspect.signature(diag_agent.diagnose).parameters except (TypeError, ValueError): @@ -155,7 +125,7 @@ class VLDiagnoseLoop: """M1→M2→M3→M4 failure-analysis loop for VL tasks (Plan A architecture). M5 (**SurgeryAgent**) is intentionally excluded from the inner loop. - Call :meth:`run_m5` on the returned :class:`VLDiagnoseReport` to obtain + Call :meth:`run_m5` on the returned :class:`AutoDiagnoseReport` to obtain a fix proposal based on the best verified hypothesis candidates. Inner loop:: @@ -230,6 +200,10 @@ class VLDiagnoseLoop: the validation data costs no confirm power and no training cases. Mutually exclusive with ``test_split > 0``. + policy: Who picks the next stage: + :class:`~evalrx.eval_agent.policy.FixedOrderPolicy` + (default) or + :class:`~evalrx.eval_agent.agentic.JudgePolicy`. max_cycles: Hard cap on M1→M4 iterations (default 1: one diagnosis pass, then the caller moves on to M5/fix — with fix-on-unverified enabled the @@ -237,7 +211,7 @@ class VLDiagnoseLoop: tripled the wall-clock; raise it to keep mining when a cycle's M4 designs feed the next cycle's M1). - run_logger: Optional :class:`~evalrx.eval_agent.run_logger_v2.RunLoggerV2`. + run_logger: Optional :class:`~evalrx.eval_agent.run_logger.RunLogger`. token_budget: Stop early when accumulated token usage reaches this limit (0 = unlimited). analysis_only: Run only M1→M2 and stop before hypothesis generation. @@ -298,6 +272,7 @@ def __init__( explore_question: str = "", verbose: bool = False, diagnosis_retries: int = 1, + policy: "Policy | None" = None, ) -> None: from evalrx.analysis.stats_agent import StatsAnalysisAgent from evalrx.eval_agent.stages.fix.agent import FixAgent @@ -373,10 +348,11 @@ def __init__( # In-cycle explore step (off by default): a free-form EDA pass over the # M1 per-case table, run between M1 and M2. Same standing as a Step-1 # explore_report — descriptive notes for M3 + files for the report. - # AgenticDiagnoseLoop overrides `self.explorer` after this constructor - # and drives it through its own judge-decided `explore_data` tool - # instead of the fixed in-cycle call (see run()/run_analysis()). + # Under a JudgePolicy it is the judge-decided `explore_data` tool + # instead of the fixed in-cycle call. self.explorer = explorer + # Who picks the next stage (see evalrx.eval_agent.policy). + self.policy: Policy = policy if policy is not None else FixedOrderPolicy() self._explore_dir = Path(explore_dir) if explore_dir is not None else None self._explore_question = str(explore_question or "") self._tokens_used: int = 0 @@ -423,13 +399,12 @@ def _emit(self, name: str, build: "Any") -> None: def _set_fix_outcome(self, report: "Any", outcome: "Any") -> "Any": """Attach M5b's outcome to the report and emit it. - ``run_fix`` has five return paths (escalation, frozen-candidate confirm, - legacy agents, skip, plain), so the assignment is the one point they all - pass through. Emitting per return would have missed whichever path was + ``run_fix`` has four return paths (escalation, frozen-candidate confirm, + skip, plain), so the assignment is the one point they all pass through. Emitting per return would have missed whichever path was added next. """ report.fix_outcome = outcome - if self.emitter is not None and hasattr(outcome, "attempted"): + if self.emitter is not None: from evalrx.contract.emit import from_fix_outcome self._emit("m5_fix", lambda: from_fix_outcome( @@ -437,12 +412,7 @@ def _set_fix_outcome(self, report: "Any", outcome: "Any") -> "Any": )) return outcome - def publish_report( - self, - *, - model: "Any | None" = None, - example_dir: "str | Path | None" = None, - ) -> "Any": + def publish_report(self, *, model: "Any | None" = None) -> "Any": """Compose the completed-run UI, reusing the M3 judge when available.""" if self.run_logger is None: raise RuntimeError("publish_report needs a run_logger with a durable run directory") @@ -450,12 +420,7 @@ def publish_report( model = getattr(self.diagnosis_agent, "judge", None) from evalrx.reporting.dynamic import publish_report - return publish_report( - self.run_logger.run_dir, - example_dir=example_dir, - model=model, - run_logger=self.run_logger, - ) + return publish_report(self.run_logger.run_dir, model=model, run_logger=self.run_logger) @staticmethod def _strat_key(case: "Any") -> "tuple": @@ -556,7 +521,7 @@ def _bridge_signals(self, probe_results: "dict[str, Any]", data: "Any | None") - probe_results[name] = synth self.store.add_result(synth) # The bridged signals ARE the discovered candidates — they must be tested, - # not optional. default_plan caps at the stats agent's max_signal_tools and + # not optional. The plan caps at the stats agent's max_signal_tools and # appends bridged signals LAST, so a low cap silently drops them. Raise the # cap to cover the expanded family (more multiplicity = more conservative, # never less — e-BH still controls FDR over whatever is tested). @@ -609,6 +574,10 @@ def _do_m1( h.predicted_failure_mode for h in all_hypotheses if getattr(h, "predicted_failure_mode", None) )) + # Named calls run exactly what was named (no cap, no backfill). + named: dict[str, Any] = {"analyzers": analyzers, "exact": True} if analyzers is not None else {} + if analyzer_params: + named["analyzer_params"] = analyzer_params _t0 = time.monotonic() probe_results = self.probe_agent.probe( self.model, @@ -616,9 +585,7 @@ def _do_m1( protocol=self.protocol, prior_hypotheses=all_hypotheses or None, hint_failure_modes=prior_modes or None, - # Named calls run exactly what was named (no cap, no backfill). - **({"analyzers": analyzers, "exact": True} if analyzers is not None else {}), - **({"analyzer_params": analyzer_params} if analyzer_params else {}), + **named, ) _dt = time.monotonic() - _t0 timings["m1"] = timings.get("m1", 0.0) + _dt @@ -690,8 +657,8 @@ def _explore_out_dir(self) -> "Path | None": → ``ctx.explore_dir``, an ephemeral tree under ``ctx.runtime_root`` (captured into ``M2/log.json`` and deleted at ``finalize()``; writing straight to ``/explore`` would leak real files - outside V2's JSON-only run artifact); - - a standalone ``RunLoggerV2("/logs")`` / ``logs_confirm`` … → + outside the JSON-only run artifact); + - a standalone ``RunLogger("/logs")`` / ``logs_confirm`` … → ``/explore`` (a sibling of the ``logs*/`` dir, the llm_benchmark layout — under the log dir it would be two levels down for a ``logs_confirm/`` carrier log and the report would miss it); @@ -867,6 +834,13 @@ def _do_m3( logger.warning("M3 attempt %d failed (%s); retrying=%s", attempt + 1, error, retrying) if self.run_logger is not None: + # A JudgeError carries what the judge was asked and answered. + for call in (e.record() for e in getattr(exc, "exchanges", ())): + self.run_logger.log_model_exchange( + "M3", cycle=cycle, role=call["role"], operation=call["operation"], + inputs=call["inputs"], output=call["output"], error=call["error"], + duration_sec=call["duration_sec"], metadata=call["metadata"], + ) self.run_logger.log_model_exchange( stage="M3", cycle=cycle, role="diagnosis", operation="diagnose", inputs=None, output=None, error=error, @@ -949,7 +923,7 @@ def _do_m4( if split_label and isinstance(getattr(tr, "evidence", None), dict): tr.evidence["split"] = split_label if log and self.run_logger: - # Reuse the surgery log slot for M4 results (backward compat). + # M4 results are logged through the surgery slot. for tr in test_results: _iv = _make_intervention_result_from_test(tr) self.run_logger.log_surgery( @@ -1009,19 +983,12 @@ def _m4_holdout_pass( if self.run_logger: self.run_logger.current_cycle = -1 _t0 = time.monotonic() - try: - if pinned: - probe_results = self.probe_agent.probe( - self.model, confirm, protocol=self.protocol, - prior_hypotheses=hypotheses or None, analyzers=pinned, - ) - else: - probe_results = self.probe_agent.probe( - self.model, confirm, protocol=self.protocol, - prior_hypotheses=hypotheses or None, - ) - except TypeError: - # A custom probe agent that predates the ``analyzers=`` hook. + if pinned: + probe_results = self.probe_agent.probe( + self.model, confirm, protocol=self.protocol, + prior_hypotheses=hypotheses or None, analyzers=pinned, + ) + else: probe_results = self.probe_agent.probe( self.model, confirm, protocol=self.protocol, prior_hypotheses=hypotheses or None, @@ -1052,7 +1019,7 @@ def _m4_holdout_pass( # Public API # ────────────────────────────────────────────────────────────────── - def run(self, data: "CaseBatch") -> VLDiagnoseReport: + def run(self, data: "CaseBatch") -> AutoDiagnoseReport: """Drive the M1→M2→M3→M4 loop to convergence. Args: @@ -1060,122 +1027,15 @@ def run(self, data: "CaseBatch") -> VLDiagnoseReport: values for the M4 statistical tests to work). Returns: - :class:`VLDiagnoseReport` with the final state. + :class:`AutoDiagnoseReport` with the final state. Call :meth:`run_m5` on this to get a fix proposal (Plan A). """ self._tokens_used = 0 # Per-stage wall-clock totals (seconds) for the loop_end cost profile. timings: dict[str, float] = {} - - # Held-out CONFIRM split (leak #3): M1-M4 see only EXPLORE; the post-loop - # fix/surgery validate on the frozen CONFIRM partition (run_m5/run_fix - # re-derive the same deterministic split from the same input batch). - # With test_split > 0 (train/val/test mode) a third partition is also - # reserved here: CONFIRM plays validation (M4 holdout + fix candidate - # development) and TEST is only ever touched by the final frozen-fix - # gate in run_fix. - explore, confirm, test = self._split_partitions(data) - if confirm is not None: - self._log_partitions(explore, confirm, test) - data = explore - - # With held-out data (and m4_holdout on), M4 runs ONCE after the loop, - # on that data — the cycles only mine (M1→M3). Without any, M4 stays - # in-cycle. - holdout_target = self._holdout_target(confirm) - self._start_run_log(data, "VLDiagnoseLoop", confirm=confirm, test=test, val=self.val_data) - - state = _LoopState() - stopped_by = _STOPPED_BY_MAX - for cycle in range(self.max_cycles): - stop = self._run_cycle(cycle, data, state, timings, holdout=holdout_target is not None) - if stop is not None: - stopped_by = stop - break - - # The M4 pass: with a confirm split in play the hypotheses are tested - # ONCE, on the held-out split — the same discipline run_fix already - # applies to candidates. Without one, the in-cycle results stand. - m4_holdout_status: "str | None" = None - if holdout_target is not None and state.hypotheses: - state.test_results, m4_holdout_status = self._m4_holdout_pass( - state.hypotheses, holdout_target, state.analyzer_names, timings, - ) - verified = self.hypothesis_tester.best_hypotheses(state.test_results) - - report = VLDiagnoseReport( - cycles=cycle + 1 if self.max_cycles > 0 else 0, # type: ignore[possibly-undefined] - resolved=bool(verified), - stopped_by=stopped_by, - verified_hypotheses=verified, - final_hypotheses=state.hypotheses, - all_test_results=state.test_results, - final_stats_report=state.stats_report, - store=self.store, - m4_holdout=m4_holdout_status, - _run_id=self._run_id, - ) + report = self.policy.run(self, data, timings) return self._end_run(report, timings) - def _run_cycle( - self, cycle: int, data: "CaseBatch", state: _LoopState, - timings: dict[str, float], *, holdout: bool, - ) -> "str | None": - """One M1→M2→M3(→M4) cycle. Returns why the loop stops, or None to go on. - - With *holdout*, M4 is deferred to the single held-out pass after the - loop: testing here would re-use the explore data the hypotheses were - mined from, and its verdict must not steer the loop (no early stop / - no extra cycles keyed on SUPPORTED-or-not). - """ - if self.token_budget > 0 and self._tokens_used >= self.token_budget: - logger.warning("Token budget %d exhausted after %d cycles", self.token_budget, cycle) - return _STOPPED_BY_BUDGET - if self.run_logger is not None: - self.run_logger.current_cycle = cycle - - # ── M1: protocol-guided probing (+ signal bridge) ───────── - probe_results, artifact_pngs = self._do_m1(cycle, data, state.hypotheses, timings) - if not probe_results: - logger.info("M1 produced no probe results — stopping.") - return _STOPPED_BY_NO_PROBE - state.analyzer_names = list(probe_results) - - # ── explore (optional): free-form EDA on M1's table → M3 notes ── - self._do_explore(cycle, probe_results, data, timings) - - # ── M2: protocol-aware stats analysis ──────────────────── - stats_report = self._do_m2(cycle, probe_results, data, artifact_pngs, timings) - state.stats_report = stats_report - if self.analysis_only: - return _STOPPED_BY_NO_HYPS - - # ── M3: hypothesis generation ("AI scientist") ──────────── - diag = self._do_m3(cycle, stats_report, state.prior_cycles, timings, cases=data) - if diag is None: - return _STOPPED_BY_DIAG_ERROR - if not diag.hypotheses: - logger.info("M3 produced no hypotheses at cycle %d.", cycle) - return _STOPPED_BY_NO_HYPS - for h in diag.hypotheses: - self.store.add_hypothesis(h) - state.hypotheses.extend(diag.hypotheses) - - # ── M4: hypothesis testing (stats + protocol consistency) ─ - if not holdout: - test_results = self._do_m4(cycle, diag.hypotheses, stats_report, data, timings) - state.test_results.extend(test_results) - if self.hypothesis_tester.stopping_criteria_met(test_results, self.protocol): - logger.info( - "Stopping criteria met at cycle %d: verified, protocol-consistent " - "hypothesis found.", - cycle, - ) - return _STOPPED_BY_CRITERIA - - state.prior_cycles.append(_cycle_summary(cycle, stats_report, diag.hypotheses)) - return None - def _log_partitions(self, explore: "CaseBatch", confirm: "CaseBatch", test: "CaseBatch | None") -> None: if test is not None: logger.info( @@ -1234,12 +1094,12 @@ def _start_run_log( if batch is not None: self.run_logger.log_cases(batch, split=split) - def _end_run(self, report: VLDiagnoseReport, timings: dict[str, float]) -> VLDiagnoseReport: + def _end_run(self, report: AutoDiagnoseReport, timings: dict[str, float]) -> AutoDiagnoseReport: if self.run_logger: self.run_logger.log_loop_end(report, tokens_used=self._tokens_used, timings=timings) return report - def run_analysis(self, data: "CaseBatch") -> VLDiagnoseReport: + def run_analysis(self, data: "CaseBatch") -> AutoDiagnoseReport: """Phase 1 — analyse + propose, WITHOUT confirming (no M4, no fix). Runs a single **M1 → M2 → M3** pass: select+execute analyzers (M1), @@ -1248,7 +1108,7 @@ def run_analysis(self, data: "CaseBatch") -> VLDiagnoseReport: that feeds the report *before* deciding whether to confirm and repair. - The returned :class:`VLDiagnoseReport` carries: + The returned :class:`AutoDiagnoseReport` carries: - ``final_hypotheses`` — the M3 proposals (UNCONFIRMED), and - ``final_stats_report`` — the M2 report, with ``all_test_results`` / ``verified_hypotheses`` left empty (M4 has @@ -1278,12 +1138,12 @@ def run_analysis(self, data: "CaseBatch") -> VLDiagnoseReport: all_hypotheses: list[Any] = [] final_stats_report = None - stopped_by = _STOPPED_BY_ANALYSIS + stopped_by = STOPPED_BY_ANALYSIS probe_results, artifact_pngs = self._do_m1(0, data, all_hypotheses, timings) if not probe_results: logger.info("M1 produced no probe results — stopping.") - stopped_by = _STOPPED_BY_NO_PROBE + stopped_by = STOPPED_BY_NO_PROBE else: # Optional explore step (descriptive EDA → M3 notes + report files). self._do_explore(0, probe_results, data, timings) @@ -1298,13 +1158,13 @@ def run_analysis(self, data: "CaseBatch") -> VLDiagnoseReport: # Stats + report are still valid; just no hypotheses to confirm. if diag is not None: logger.info("M3 produced no hypotheses.") - stopped_by = _STOPPED_BY_DIAG_ERROR if diag is None else _STOPPED_BY_NO_HYPS + stopped_by = STOPPED_BY_DIAG_ERROR if diag is None else STOPPED_BY_NO_HYPS else: for h in diag.hypotheses: self.store.add_hypothesis(h) all_hypotheses.extend(diag.hypotheses) - report = VLDiagnoseReport( + report = AutoDiagnoseReport( cycles=1, stopped_by=stopped_by, verified_hypotheses=[], @@ -1322,7 +1182,7 @@ def run_confirm( hypotheses: "list[Any]", *, stats_report: "Any | None" = None, - ) -> VLDiagnoseReport: + ) -> AutoDiagnoseReport: """Phase 2a — confirm previously-proposed hypotheses with M4. Runs **M4** (:class:`~evalrx.eval_agent.stages.hypothesis_tester.HypothesisTester`) @@ -1337,7 +1197,7 @@ def run_confirm( M1→M2 are re-run silently (not logged — they belong to the analysis phase) to regenerate it. - Returns a :class:`VLDiagnoseReport` with ``all_test_results`` and + Returns a :class:`AutoDiagnoseReport` with ``all_test_results`` and ``verified_hypotheses`` populated. Feed it into :meth:`run_m5` / :meth:`run_fix` for the repair step. """ @@ -1358,8 +1218,8 @@ def run_confirm( if stats_report is None: stats_report = self._confirm_stats(data, hypotheses, timings) if stats_report is None: - report = VLDiagnoseReport( - cycles=1, stopped_by=_STOPPED_BY_NO_PROBE, + report = AutoDiagnoseReport( + cycles=1, stopped_by=STOPPED_BY_NO_PROBE, final_hypotheses=hypotheses, store=self.store, _run_id=self._run_id, ) return self._end_run(report, timings) @@ -1376,9 +1236,9 @@ def run_confirm( hypotheses, stats_report, data, confirm, timings, ) verified = self.hypothesis_tester.best_hypotheses(test_results) - stopped_by = _STOPPED_BY_CRITERIA if verified else _STOPPED_BY_MAX + stopped_by = STOPPED_BY_CRITERIA if verified else STOPPED_BY_MAX - report = VLDiagnoseReport( + report = AutoDiagnoseReport( cycles=1, resolved=bool(verified), stopped_by=stopped_by, @@ -1433,7 +1293,7 @@ def _m4_verdicts( def run_m5( self, - report: VLDiagnoseReport, + report: AutoDiagnoseReport, data: "CaseBatch", *, allow_unverified: bool = False, @@ -1442,7 +1302,7 @@ def run_m5( Called *after* :meth:`run` to avoid polluting the inner loop with fix-execution noise. Operates on the highest-confidence verified - hypothesis from :attr:`VLDiagnoseReport.verified_hypotheses`; with + hypothesis from :attr:`AutoDiagnoseReport.verified_hypotheses`; with ``allow_unverified=True`` and no verified hypothesis it falls back to the best *unverified* one (see :func:`_unverified_hypotheses`) — the experiment is then a genuine test of a lead M4 could not decide, and @@ -1522,7 +1382,7 @@ def run_m5( def run_fix( self, - report: VLDiagnoseReport, + report: AutoDiagnoseReport, data: "CaseBatch", max_tier: "str | Any | None" = None, fix_agent: "Any | None" = None, @@ -1606,7 +1466,7 @@ def run_fix( ) context.hypotheses_note = hypotheses_note requested = parse_tier(max_tier) if max_tier is not None else None - agent_logger = getattr(agent, "run_logger", None) + agent_logger = agent.run_logger if auto_escalate: # With a held-out split the entire ladder is searched on the @@ -1617,8 +1477,6 @@ def run_fix( ceiling = requested if requested is not None else FixTier.L3B_INTERNALS_WRITE rungs = _climb_ladder(agent, self.model, dev_data, hypotheses, context, ceiling, dev_label) - if not hasattr(rungs[-1], "attempted"): # opaque custom-agent result - return self._set_fix_outcome(report, rungs[-1]) if final_data is None: outcome = _merge_rungs(rungs, ceiling, agent.alpha) else: @@ -1626,27 +1484,23 @@ def run_fix( agent, self.model, final_data, [v for rung in rungs for v in rung.attempted], max_tier=ceiling, - repair_rounds=sum(int(getattr(r, "repair_rounds", 0) or 0) for r in rungs), + repair_rounds=sum(r.repair_rounds for r in rungs), ) _log_fix(agent_logger, outcome) return self._set_fix_outcome(report, outcome) if final_data is None: - outcome = _propose_and_validate(agent, self.model, data, hypotheses, - context=context, max_tier=requested) + outcome = agent.propose_and_validate(self.model, data, hypotheses, + context=context, max_tier=requested) return self._set_fix_outcome(report, outcome) # A two-stage repair experiment: the agent may iterate and select on the # development partition, then exactly one frozen candidate is tested on # the final partition. Selection statistics are descriptive only; the # final paired gate is computed from the final partition alone. - selection = _propose_and_validate(agent, self.model, dev_data, hypotheses, - context=context, max_tier=requested, record=False) - # Custom/legacy agents may return an opaque application-specific result - # rather than FixOutcome. They cannot take part in the frozen-candidate - # confirmation, but their return contract is kept. - if not hasattr(selection, "attempted"): - return self._set_fix_outcome(report, selection) + selection = agent.propose_and_validate(self.model, dev_data, hypotheses, + context=context, max_tier=requested, + record=False) outcome = _confirm_from_explore( agent, self.model, final_data, selection.attempted, max_tier=requested if requested is not None else agent.max_tier, @@ -1655,34 +1509,34 @@ def run_fix( _log_fix(agent_logger, outcome) return self._set_fix_outcome(report, outcome) - def _skip_fix(self, report: VLDiagnoseReport, agent: "Any") -> "Any": + def _skip_fix(self, report: AutoDiagnoseReport, agent: "Any") -> "Any": """Record a skipped M5 stage: no hypothesis passed the evidence gate. A repair proposal is an intervention, not another exploratory probe, so an unreviewed/unsupported M3 lead must not become a misleading empty M5 outcome. The caller still gets a stable outcome object. """ - from evalrx.eval_agent.stages.fix.tiers import FixTier from evalrx.eval_agent.stages.fix.types import FixOutcome diagnosis_failed = report.stopped_by == "diagnosis_error" + recommendation = { + "reason": ("Repair was not attempted because diagnosis failed; inspect M3 errors." + if diagnosis_failed else + "Repair was not attempted because no hypothesis passed the evidence gate."), + "next_step": ("Inspect the recorded M3 error, fix its cause, and retry diagnosis." + if diagnosis_failed else + "Run the targeted diagnostic probe proposed by M3."), + } outcome = FixOutcome( - max_tier=getattr(agent, "max_tier", FixTier.L2_SCAFFOLD), + max_tier=agent.max_tier, stage_status="skipped", skip_reason="diagnosis_error" if diagnosis_failed else "no_accepted_hypothesis", - recommendation={ - "reason": ("Repair was not attempted because diagnosis failed; inspect M3 errors." - if diagnosis_failed else - "Repair was not attempted because no hypothesis passed the evidence gate."), - "next_step": ("Inspect the recorded M3 error, fix its cause, and retry diagnosis." - if diagnosis_failed else - "Run the targeted diagnostic probe proposed by M3."), - }, + recommendation=recommendation, ) if self.run_logger is not None: self.run_logger.log_stage_skipped( "M5", outcome.skip_reason, - detail=outcome.recommendation["reason"], + detail=recommendation["reason"], ) return self._set_fix_outcome(report, outcome) diff --git a/evalrx/eval_agent/loop_fix.py b/evalrx/eval_agent/loop_fix.py index cded7b00..2f1f42eb 100644 --- a/evalrx/eval_agent/loop_fix.py +++ b/evalrx/eval_agent/loop_fix.py @@ -17,42 +17,6 @@ logger = logging.getLogger(__name__) -def _call_supported(fn: "Any", *args: Any, required: "tuple[str, ...]" = (), - **kwargs: Any) -> "Any": - """Call *fn* with the non-None *kwargs* it accepts. - - Custom/stub fix agents keep working with optional extras such as - ``prior_attempts`` / ``context`` / ``record`` (same pattern as - ``_diagnose_with_optional_context``). A *required* keyword the function - cannot take raises instead of being dropped: running a tier ladder on an - agent that ignores the tier window would silently test the wrong tier. - """ - import inspect as _inspect - - try: - params = _inspect.signature(fn).parameters - except (TypeError, ValueError): - params = {} - accepts_any = any(p.kind == p.VAR_KEYWORD for p in params.values()) - passed = {k: v for k, v in kwargs.items() - if v is not None and (accepts_any or k in params)} - missing = [k for k in required if kwargs.get(k) is not None and k not in passed] - if missing: - raise TypeError( - f"{getattr(fn, '__qualname__', fn)} does not accept {', '.join(missing)}; " - "the fix loop needs it to restrict the tier window" - ) - return fn(*args, **passed) - - -def _propose_and_validate(agent: "Any", model: "Any", data: "Any", hypotheses: "Any", - **kwargs: Any) -> "Any": - """``agent.propose_and_validate`` with a per-call tier window (required when - given) and optional extras (see :func:`_call_supported`).""" - return _call_supported(agent.propose_and_validate, model, data, hypotheses, - required=("max_tier", "min_tier"), **kwargs) - - def _unverified_hypotheses(report: "Any") -> "list[Any]": """Best-first UNVERIFIED hypotheses: M4-tested and not refuted, highest confidence first; then untested proposals from the last cycle.""" @@ -164,7 +128,7 @@ def _fix_context_from_report( lines.append(f" - {stmt}{conf_s} grade={grade}") if verdict: lines.append(f" evidence: {verdict}") - stats = getattr(report, "final_stats_report", None) or getattr(report, "final_analysis", None) + stats = getattr(report, "final_stats_report", None) if stats is not None: conclusion = str(getattr(stats, "conclusion", "") or getattr(stats, "narrative", "") or "") if conclusion: @@ -263,8 +227,7 @@ def _climb_ladder( Each rung sees only its own tier (cheaper candidates are not pooled with a newly opened, more invasive tier) plus every failed attempt so far, so the judge can try something fundamentally different. Stops at the first fix. - Rungs record nothing; the caller records one combined outcome. An opaque - custom-agent result ends the climb as the last rung. + Rungs record nothing; the caller records one combined outcome. """ from evalrx.eval_agent.stages.fix.tiers import FixTier @@ -282,17 +245,15 @@ def _climb_ladder( break logger.info("run_fix: %s trying tier %s (%d prior attempt(s))", label, tier.label, len(prior)) - rung = _propose_and_validate( - agent, model, data, hypotheses, - prior_attempts=prior if prior else None, + rung = agent.propose_and_validate( + model, data, hypotheses, + prior_attempts=prior or None, context=context, max_tier=tier, min_tier=tier, record=False, ) rungs.append(rung) - if not hasattr(rung, "attempted"): - break if rung.fixed: logger.info("run_fix: %s fixed at tier %s", label, tier.label) break @@ -334,38 +295,8 @@ def _log_fix(run_logger: "Any | None", outcome: "Any") -> None: logger.debug("run_fix: log_fix failed: %s", exc) -def _confirm_from_explore( - agent: "Any", - model: "Any", - confirm: "CaseBatch", - attempted: "list[Any]", - *, - max_tier: "Any", - repair_rounds: int, -) -> "Any": - """Freeze the strongest EXPLORE improvement and test it once on CONFIRM.""" - from evalrx.eval_agent.stages.fix.descriptions import plain_description - from evalrx.eval_agent.stages.fix.types import FixOutcome - from evalrx.eval_agent.stages.fix.verdict import ebh_survivors, refine_signal - - def _recommend(reason: str, validations: "list[Any]") -> "dict[str, Any] | None": - routed = sorted({v.candidate.tier for v in validations}) - recommend = getattr(agent, "recommend", None) - if callable(recommend): - try: - return _call_supported( - recommend, - routed, - model=model, - data=confirm, - reason_prefix=reason, - max_tier=max_tier, - ) - except TypeError: - # Backward compatibility for application-specific FixAgents. - pass - return {"recommend_tier": max_tier.label, "reason": reason} - +def _select_on_explore(attempted: "list[Any]") -> "Any | None": + """The strongest EXPLORE improvement with enough support, or None.""" executed = [ validation for validation in attempted @@ -382,7 +313,7 @@ def _recommend(reason: str, validations: "list[Any]") -> "dict[str, Any] | None" # candidate family; small experiments still select from what they have. support_floor = min(8, max((v.n_pairs for v in improving), default=0)) supported = [v for v in improving if v.n_pairs >= support_floor] - selected = max( + return max( supported, key=lambda validation: ( validation.e_value or 0.0, @@ -394,10 +325,16 @@ def _recommend(reason: str, validations: "list[Any]") -> "dict[str, Any] | None" ), default=None, ) + + +def _selection_audit(attempted: "list[Any]") -> "list[dict[str, Any]]": + """One row per EXPLORE candidate, as the contract emitter reads it.""" + from evalrx.eval_agent.stages.fix.descriptions import plain_description + # `headline` travels with the audit row because the candidate object does # not: the contract emitter sees only these dicts, and a slug is the one # thing it must not show a reader. - audit = [ + return [ { "name": validation.candidate.name, "headline": plain_description(validation.candidate), @@ -412,14 +349,33 @@ def _recommend(reason: str, validations: "list[Any]") -> "dict[str, Any] | None" } for validation in attempted ] + + +def _confirm_from_explore( + agent: "Any", + model: "Any", + confirm: "CaseBatch", + attempted: "list[Any]", + *, + max_tier: "Any", + repair_rounds: int, +) -> "Any": + """Freeze the strongest EXPLORE improvement and test it once on CONFIRM.""" + from evalrx.eval_agent.stages.fix.types import FixOutcome + from evalrx.eval_agent.stages.fix.verdict import ebh_survivors, refine_signal + + selected = _select_on_explore(attempted) + audit = _selection_audit(attempted) if selected is None: return FixOutcome( max_tier=max_tier, repair_rounds=repair_rounds, selection_attempted=audit, - recommendation=_recommend( - "no EXPLORE candidate had positive net repairs; CONFIRM was left untouched", - attempted, + recommendation=agent.recommend( + sorted({v.candidate.tier for v in attempted}), + model=model, data=confirm, max_tier=max_tier, + reason_prefix="no EXPLORE candidate had positive net repairs; " + "CONFIRM was left untouched", ), ) @@ -442,21 +398,13 @@ def _recommend(reason: str, validations: "list[Any]") -> "dict[str, Any] | None" selected_on_explore=selected.candidate.name, ) if not outcome.fixed: - no_fix = getattr(agent, "no_fix_recommendation", None) - if callable(no_fix): - outcome.recommendation = _call_supported( - no_fix, [validation], [selected.candidate.tier], confirm, model, - max_tier=max_tier, - ) - if outcome.recommendation is not None: - outcome.recommendation["reason"] = ( - "the candidate selected on EXPLORE did not validate on untouched CONFIRM; " - + outcome.recommendation["reason"] - ) - else: - outcome.recommendation = _recommend( - "the candidate selected on EXPLORE did not validate on untouched CONFIRM", - [validation], + outcome.recommendation = agent.no_fix_recommendation( + [validation], [selected.candidate.tier], confirm, model, max_tier=max_tier, + ) + if outcome.recommendation is not None: + outcome.recommendation["reason"] = ( + "the candidate selected on EXPLORE did not validate on untouched CONFIRM; " + + outcome.recommendation["reason"] ) outcome.refine_signal = refine_signal([validation], confirm) return outcome diff --git a/evalrx/eval_agent/loop_reports.py b/evalrx/eval_agent/loop_reports.py index 3c0c0ca6..23716f68 100644 --- a/evalrx/eval_agent/loop_reports.py +++ b/evalrx/eval_agent/loop_reports.py @@ -1,7 +1,7 @@ """Report dataclasses returned by the diagnosis loops. -Split out of ``loop.py`` so the loops (``loop.VLDiagnoseLoop`` and -``agentic.AgenticDiagnoseLoop``) can share them without a circular import. +Split out of ``loop.py`` so the loop and its policies (``policy.FixedOrderPolicy``, +``agentic.JudgePolicy``) can share them without a circular import. """ from __future__ import annotations @@ -12,37 +12,37 @@ from evalrx.eval_agent.store import InMemoryStore, Store if TYPE_CHECKING: - from evalrx.analysis.analysis_module import AnalysisReport from evalrx.analysis.stats_agent import StatsAnalysisReport - from evalrx.core.result import Result from evalrx.eval_agent.hypothesis import Hypothesis from evalrx.eval_agent.stages.hypothesis_tester import HypothesisTestResult +# ``AutoDiagnoseReport.stopped_by`` values. +STOPPED_BY_CRITERIA = "criteria_met" +STOPPED_BY_MAX = "max_cycles" +STOPPED_BY_BUDGET = "budget" +STOPPED_BY_NO_HYPS = "no_hypotheses" +STOPPED_BY_DIAG_ERROR = "diagnosis_error" +STOPPED_BY_NO_PROBE = "no_probe_results" +# run_analysis() ran M1->M2->M3 and proposed hypotheses without confirming them +# (M4 deferred to run_confirm()). Not a failure — the analysis report is ready. +STOPPED_BY_ANALYSIS = "analysis_complete" @dataclass class AutoDiagnoseReport: """Summary returned by every diagnosis loop: :class:`~evalrx.eval_agent.loop.VLDiagnoseLoop.run` and - :class:`~evalrx.eval_agent.agentic.AgenticDiagnoseLoop.run` both return - this one class — ``VLDiagnoseReport`` below is a back-compat alias for - it, not a separate type, so ``isinstance(report, VLDiagnoseReport)`` - holds for a report from either loop. - - Unified 2026-08 from two previously-separate dataclasses - (``AutoDiagnoseReport`` / ``VLDiagnoseReport``) that carried the same - information under different field names. Every field below is populated - by both loops except where noted "M4-only" (or ``final_results``), which stay - at their default (``None`` / empty) when the producing loop has no - equivalent concept. + :meth:`~evalrx.eval_agent.agentic.JudgePolicy.run` both return + this one class. Every field below is populated by both loops except + where noted "M4-only", which stay at their default (``None`` / empty) + when the producing loop has no equivalent concept. Attributes: cycles: Number of M1→M4/M5 cycles executed (or agentic decision steps taken). resolved: ``True`` once the diagnosis is considered - closed — M5 surgery confirmed a fix (legacy - loop), or M4 found at least one supported, - protocol-consistent hypothesis (``bool(verified_hypotheses)``, - current/agentic loops). + closed — M4 found at least one supported, + protocol-consistent hypothesis + (``bool(verified_hypotheses)``). stopped_by: M4-path only. Why the loop stopped: ``"criteria_met"``, ``"max_cycles"``, ``"budget"``, ``"no_hypotheses"``, ``"no_probe_results"``, ``"analysis_complete"`` @@ -50,25 +50,13 @@ class AutoDiagnoseReport: without confirming them) — or, for the agentic loop, ``"agent_stop"`` / ``"max_actions"`` / ``"time_budget"`` / ``"invalid_actions"``. ``"diagnosis_error"`` - means M3 failed after bounded retries; it is not an empty finding. ``None`` - for the legacy M5-per-cycle loop, which has no - single stopping-reason concept. - final_hypotheses: All M3 proposals across every cycle. (Formerly - ``all_hypotheses`` on the VL-shaped report — - ``all_hypotheses`` is now a read-only alias - for this field, kept for existing callers.) + means M3 failed after bounded retries; it is not an empty finding. + final_hypotheses: All M3 proposals across every cycle. verified_hypotheses: M4-only. Statistically supported, protocol-consistent test results — sorted highest confidence first. Feed into ``run_m5``. all_test_results: M4-only. All M4 test results across every cycle. - final_results: Left empty by both loops (the removed AutoDiagnoseLoop - filled it with the last M1 probe's raw results). - final_analysis: Structured M2 report from the last cycle. Mirrors - ``final_stats_report`` when only that was set - (``StatsAnalysisReport`` is an ``AnalysisReport`` - subclass), so this field works for every loop. - final_stats_report: M2 report from the last cycle (M4-path shape; - same object as ``final_analysis`` when set). + final_stats_report: M2 report from the last cycle. fix_proposal: Populated by ``run_m5`` when called after ``run``. m4_holdout: Held-out M4 confirmation status (see field note). fix_outcome: Populated by ``run_fix`` — tiered fix attempts + @@ -82,8 +70,6 @@ class AutoDiagnoseReport: final_hypotheses: "list[Hypothesis]" = field(default_factory=list) verified_hypotheses: "list[HypothesisTestResult]" = field(default_factory=list) all_test_results: "list[HypothesisTestResult]" = field(default_factory=list) - final_results: "dict[str, Result]" = field(default_factory=dict) - final_analysis: "AnalysisReport | None" = None final_stats_report: "StatsAnalysisReport | None" = None fix_proposal: "Any | None" = None fix_outcome: "Any | None" = None @@ -97,21 +83,3 @@ class AutoDiagnoseReport: m4_holdout: "str | None" = None # Internal — the run id the loop ran under _run_id: str = field(default="", repr=False) - - def __post_init__(self) -> None: - # StatsAnalysisReport IS-A AnalysisReport, so a report built from the - # M4 path can satisfy readers that only know the Auto-shaped field. - if self.final_analysis is None and self.final_stats_report is not None: - self.final_analysis = self.final_stats_report - - @property - def all_hypotheses(self) -> "list[Any]": - """Read-only back-compat alias for :attr:`final_hypotheses`.""" - return self.final_hypotheses - - -# Back-compat alias — the two report shapes were merged into one class (see -# AutoDiagnoseReport's docstring). Keep the name importable for existing -# code; it is literally the same class, so isinstance checks against either -# name succeed for a report from any loop. -VLDiagnoseReport = AutoDiagnoseReport diff --git a/evalrx/eval_agent/model_instrumentation.py b/evalrx/eval_agent/model_instrumentation.py index b1056209..b36b6086 100644 --- a/evalrx/eval_agent/model_instrumentation.py +++ b/evalrx/eval_agent/model_instrumentation.py @@ -15,9 +15,9 @@ ``InstrumentedModel`` closes that hole *without touching any analyzer*: wrap the model handed to ``analyzer.run(model, data)`` in this proxy and every call -is durably logged via :meth:`RunLoggerV2.log_model_call`, tagged with +is durably logged via :meth:`RunLogger.log_model_call`, tagged with ``(cycle, analyzer, method, call_index)`` — the primary key that was missing -before. See ``run_logger_v2.py``'s ``log_model_call`` docstring for where the +before. See ``run_logger.py``'s ``log_model_call`` docstring for where the record ends up (inlined into the owning stage's ``M/log.json``, not a sibling file) and how it is mirrored into Langfuse. @@ -42,7 +42,7 @@ ``tools.py``, ``pipeline.py``) — but these already have a durable, pre-existing home: per-candidate per-case outputs land inline under each candidate's own ``"outputs"`` key in ``M5/log.json`` via - ``RunLoggerV2.log_fix``. + ``RunLogger.log_fix``. - Pre-loop ``case_discovery.py`` harvesting in arbitrary callers. The common benchmark runner wraps this path, so its exact per-case input/output/error/latency is covered there as well. @@ -62,13 +62,15 @@ if TYPE_CHECKING: from evalrx.core.capability import Capability - from evalrx.core.model import CaptureSpec, Model, Trace - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.core.model import CaptureSpec, Judge, Model, Trace + from evalrx.eval_agent.run_logger import RunLogger -#: Longest single string field kept verbatim before it is truncated. Generous -#: enough for almost every prompt/response; a truncated field says so rather -#: than silently clipping, so a reader never mistakes it for the whole thing. -_MAX_FIELD_CHARS = 8000 + # The proxy stands in for the Model it wraps. It is not a subclass at run + # time: Model's class-level defaults (capabilities, modalities) would + # shadow the forwarding __getattr__ below. + _ProxyBase = Model +else: + _ProxyBase = object #: How many of the batch's case ids get repeated verbatim on EVERY model_call #: record (see ``batch_case_ids`` in ``_record``). Unlike prompts/outputs this @@ -76,23 +78,16 @@ #: a real batch (136 cases in the run this instrumentation was built against) #: it would otherwise duplicate ~5KB of uuids per record, times however many #: calls the analyzer makes — the one field here that scales with batch size -#: rather than with prompt/response length, so it gets its own cap instead of -#: reusing ``_MAX_FIELD_CHARS``. +#: rather than with prompt/response length, so it is the one field capped. _MAX_BATCH_IDS_INLINE = 20 -def _truncate(text: str) -> str: - if len(text) <= _MAX_FIELD_CHARS: - return text - return text[:_MAX_FIELD_CHARS] + f"...[truncated, {len(text)} chars total]" - - def _capped_ids(ids: "list[str]") -> "tuple[list[str], int]": """First ``_MAX_BATCH_IDS_INLINE`` ids, plus the true total count.""" return ids[:_MAX_BATCH_IDS_INLINE], len(ids) -def _snapshot_inputs(inputs: Any, *, full: bool = False) -> Any: +def _snapshot_inputs(inputs: Any) -> Any: """A JSON-safe stand-in for whatever an analyzer passed as *inputs*. Handles the three shapes analyzers actually use: a bare string (some @@ -100,17 +95,15 @@ def _snapshot_inputs(inputs: Any, *, full: bool = False) -> Any: ``Inputs``-like object (``.prompt`` + optional ``.image``/``.audio``/ ``.video``), or anything else (falls back to ``str()``). Media slots are never inlined — a decoded ``PIL.Image``/waveform is far too large and a - path/URL is recorded as-is, the same convention ``RunLoggerV2.log_cases`` + path/URL is recorded as-is, the same convention ``RunLogger.log_cases`` uses for baseline case media. """ if isinstance(inputs, str): - return inputs if full else _truncate(inputs) + return inputs prompt = getattr(inputs, "prompt", None) if prompt is None: - return str(inputs) if full else _truncate(str(inputs)) - snapshot: dict[str, Any] = { - "prompt": str(prompt) if full else _truncate(str(prompt)) - } + return str(inputs) + snapshot: dict[str, Any] = {"prompt": str(prompt)} for kind in ("image", "audio", "video"): value = getattr(inputs, kind, None) if value is None: @@ -124,7 +117,7 @@ def _snapshot_trace(trace: "Trace") -> "dict[str, Any]": The heavy arrays (attentions/hidden_states/logits) already have a durable home: whichever ones an analyzer chooses to return via ``Result.artifacts`` - are saved by ``RunLoggerV2._save_media``. Duplicating them here would + are saved by ``RunLogger._save_media``. Duplicating them here would multiply disk use for no new evidence, so this keeps only what a reader needs to tell one ``forward()`` call apart from another. """ @@ -134,22 +127,22 @@ def _snapshot_trace(trace: "Trace") -> "dict[str, Any]": } -class InstrumentedModel: - """Forwarding proxy around a ``Model`` that reports every call to a ``RunLoggerV2``. +class InstrumentedModel(_ProxyBase): + """Forwarding proxy around a ``Model`` that reports every call to a ``RunLogger``. One instance per analyzer invocation — construct fresh in ``ProbeAgent._run_direct`` rather than sharing across analyzers, so ``call_index`` is scoped to exactly the (cycle, analyzer) pair it is tagged with. Safe to use from a ``ThreadPoolExecutor`` worker: each instance is only ever touched by the one thread running that analyzer, - and the underlying atomic-rewrite sink (guarded by ``RunLoggerV2``'s own + and the underlying atomic-rewrite sink (guarded by ``RunLogger``'s own lock) is itself thread-safe. """ def __init__( self, - model: "Model", - run_logger: "RunLoggerV2", + model: "Model | Judge", + run_logger: "RunLogger", *, cycle: int, analyzer: str, @@ -157,7 +150,9 @@ def __init__( case_prompts: "dict[str, str] | None" = None, batch_case_ids: "list[str] | None" = None, ) -> None: - self._model = model + # A Model, or a stage's judge: forward / logprobs / chat are only ever + # called on a wrapped object that has them. + self._model: Any = model self._run_logger = run_logger self._cycle = cycle self._analyzer = analyzer @@ -200,11 +195,10 @@ def _record( ) -> None: prompt = inputs if isinstance(inputs, str) else getattr(inputs, "prompt", None) case_id = self._case_prompts.get(str(prompt)) if prompt is not None else None - full = bool(getattr(self._run_logger, "preserve_full_model_io", False)) - if self._stage != "M1" and callable(getattr(self._run_logger, "log_model_exchange", None)): + if self._stage != "M1": self._run_logger.log_model_exchange( self._stage, role=self._analyzer, operation=method, - inputs=_snapshot_inputs(inputs, full=full), output=output, error=error, + inputs=_snapshot_inputs(inputs), output=output, error=error, duration_sec=duration_sec, cycle=self._cycle, metadata={ "call_index": self._next_call_index(), "case_id": case_id, @@ -222,7 +216,7 @@ def _record( case_id=case_id, batch_case_ids=self._batch_case_ids_inline, n_batch_cases=self._n_batch_cases, - inputs=_snapshot_inputs(inputs, full=full), + inputs=_snapshot_inputs(inputs), kwargs={k: str(v) for k, v in (kwargs or {}).items()}, output=output, duration_sec=duration_sec, @@ -236,8 +230,7 @@ def generate(self, inputs: Any, **kwargs: Any) -> str: except Exception as exc: # noqa: BLE001 - record the failure, then re-raise it self._record("generate", inputs, kwargs, None, time.monotonic() - t0, repr(exc)) raise - rendered = str(out) if getattr(self._run_logger, "preserve_full_model_io", False) else _truncate(str(out)) - self._record("generate", inputs, kwargs, rendered, time.monotonic() - t0, None) + self._record("generate", inputs, kwargs, str(out), time.monotonic() - t0, None) return out def forward( @@ -271,10 +264,7 @@ def chat(self, messages: list, tools: "list | None" = None) -> Any: except Exception as exc: # noqa: BLE001 self._record("chat", messages, {"tools": tools}, None, time.monotonic() - t0, repr(exc)) raise - text = str(getattr(turn, "text", turn)) - if not getattr(self._run_logger, "preserve_full_model_io", False): - text = _truncate(text) - output = {"text": text} + output = {"text": str(getattr(turn, "text", turn))} raw_tool_calls = getattr(turn, "raw_tool_calls", None) if raw_tool_calls: output["tool_calls"] = str(raw_tool_calls) diff --git a/evalrx/eval_agent/narration.py b/evalrx/eval_agent/narration.py index b9d6bde3..eff3a718 100644 --- a/evalrx/eval_agent/narration.py +++ b/evalrx/eval_agent/narration.py @@ -1,19 +1,19 @@ """Live per-stage terminal narration for the M1-M5 diagnosis loop -(:class:`~evalrx.eval_agent.run_logger_v2.RunLoggerV2`). +(:class:`~evalrx.eval_agent.run_logger.RunLogger`). Sibling of :class:`evalrx.analysis.narration.TerminalNarrator` (built for the `evalrx explore`/`run-codebase` CLI pipeline) — same visual grammar ("M2 explore ············ ...") and the same non-simulated promise: every -count here comes from the real event RunLoggerV2 just logged, nothing is +count here comes from the real event RunLogger just logged, nothing is invented. The two narrators don't share code (small, deliberate style-block duplication below) because their event shapes differ: EventSink emits -started/completed pairs, RunLoggerV2 emits one already-finished record per +started/completed pairs, RunLogger emits one already-finished record per stage occurrence, so this one always prints exactly one line per event instead of a running/completed pair. -Opt in on any ``RunLoggerV2``:: +Opt in on any ``RunLogger``:: - RunLoggerV2(run_dir=out / "logs", narrate=True) + RunLogger(run_dir=out / "logs", narrate=True) """ from __future__ import annotations @@ -41,7 +41,7 @@ # `stage` argument there -- only on_run_start/on_run_event use this label. _RUN_LABEL = "loop" -# Event keys worth a narrated line. Everything else RunLoggerV2 logs +# Event keys worth a narrated line. Everything else RunLogger logs # (model_call, tool_codegen, tool_registry, agent_decision/tool, cases, # report_published, diagnose_reports) is real detail too, but at a finer # grain than "what stage is the loop on" — narrating all of it would bury @@ -67,7 +67,7 @@ def _or_na(value: Any) -> Any: class LoopNarrator: - """Prints one real, aligned line per M1-M5 event, as RunLoggerV2 logs it.""" + """Prints one real, aligned line per M1-M5 event, as RunLogger logs it.""" LABEL_WIDTH = 12 @@ -87,7 +87,7 @@ def _row(self, key: str, detail: str) -> str: def _print(self, key: str, detail: str) -> None: print(self._row(key, detail), file=self.stream, flush=True) - # -- stage events (M1-M5), from RunLoggerV2._append_stage ------------- + # -- stage events (M1-M5), from RunLogger._append_stage ------------- def on_event(self, stage: str, key: str, record: dict[str, Any]) -> None: if key == "model_calls" and record.get("error"): @@ -173,7 +173,7 @@ def _tier_line(self, attempt: dict[str, Any]) -> str: return (f"{self._c(_DIM, tier)} {name} {mark} {eff_str} " f"(n_fixed={_or_na(attempt.get('n_fixed'))}, n_broken={_or_na(attempt.get('n_broken'))})") - # -- run-level events, from RunLoggerV2._append_run / log_run_start --- + # -- run-level events, from RunLogger._append_run / log_run_start --- def on_run_start(self, entry: dict[str, Any]) -> None: model = entry.get("model") or "target model" diff --git a/evalrx/eval_agent/policy.py b/evalrx/eval_agent/policy.py new file mode 100644 index 00000000..3c529c53 --- /dev/null +++ b/evalrx/eval_agent/policy.py @@ -0,0 +1,200 @@ +"""Who picks the next stage of a :class:`~evalrx.eval_agent.loop.VLDiagnoseLoop` run. + +The loop owns the stages (M1 probe, explore, M2 stats, M3 diagnosis, M4 test), +the run log and the confirm split. A policy decides the order: +:class:`FixedOrderPolicy` (the default) runs M1→M2→M3→M4 cycles; +:class:`~evalrx.eval_agent.agentic.policy.JudgePolicy` asks a judge, one tool +call at a time. Both keep their bookkeeping in one :class:`RunState`. +""" + +from __future__ import annotations + +import logging +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Protocol + +from evalrx.eval_agent.loop_reports import ( + STOPPED_BY_BUDGET, + STOPPED_BY_CRITERIA, + STOPPED_BY_DIAG_ERROR, + STOPPED_BY_MAX, + STOPPED_BY_NO_HYPS, + STOPPED_BY_NO_PROBE, + AutoDiagnoseReport, +) + +if TYPE_CHECKING: + from evalrx.core.case import CaseBatch + from evalrx.eval_agent.loop import VLDiagnoseLoop + +logger = logging.getLogger(__name__) + + +class Policy(Protocol): + def run(self, loop: "VLDiagnoseLoop", data: "CaseBatch", + timings: dict[str, float]) -> AutoDiagnoseReport: ... + + +@dataclass +class RunState: + """What one run accumulates, whichever policy drives it.""" + + original_data: Any + data: Any + timings: dict[str, float] = field(default_factory=dict) + cycle: int = 0 + all_hypotheses: list[Any] = field(default_factory=list) + all_test_results: list[Any] = field(default_factory=list) + #: Each finished cycle's summary, M3's context for the next one. + prior_cycles: list[dict[str, Any]] = field(default_factory=list) + stats_report: Any = None + diagnosis_failed: bool = False + #: The last M1's analyzers — what the held-out M4 pass re-runs. + analyzer_names: list[str] = field(default_factory=list) + # Judge-decided runs only: the decision judge and the tools' working state. + judge: Any = None + pending_hypotheses: list[Any] = field(default_factory=list) + probe_results: dict[str, Any] = field(default_factory=dict) + artifact_pngs: list[Any] = field(default_factory=list) + failure_modes: Any = None + probe_search_result: Any = None + surgery_outcome: Any = None + fix_outcome: Any = None + + +def cycle_summary(cycle: int, stats_report: Any, hypotheses: list) -> dict[str, Any]: + """One finished cycle as the next M3 call sees it.""" + return { + "cycle": cycle, + "severity": getattr(stats_report, "severity", "none"), + "hypotheses": [ + { + "statement": h.statement, + "failure_mode": h.predicted_failure_mode, + "status": h.status.value if h.status else "pending", + } + for h in hypotheses + ], + } + + +class FixedOrderPolicy: + """M1→M2→M3(→M4) cycles until a stopping rule fires (the default policy). + + ``max_cycles``, ``token_budget``, ``analysis_only`` and ``m4_holdout`` are + read from the loop. + """ + + def run(self, loop: "VLDiagnoseLoop", data: "CaseBatch", + timings: dict[str, float]) -> AutoDiagnoseReport: + # Held-out CONFIRM split (leak #3): M1-M4 see only EXPLORE; the post-loop + # fix/surgery validate on the frozen CONFIRM partition (run_m5/run_fix + # re-derive the same deterministic split from the same input batch). + # With test_split > 0 (train/val/test mode) a third partition is also + # reserved here: CONFIRM plays validation (M4 holdout + fix candidate + # development) and TEST is only ever touched by the final frozen-fix + # gate in run_fix. + explore, confirm, test = loop._split_partitions(data) + original_data = data + if confirm is not None: + loop._log_partitions(explore, confirm, test) + data = explore + + # With held-out data (and m4_holdout on), M4 runs ONCE after the loop, + # on that data — the cycles only mine (M1→M3). Without any, M4 stays + # in-cycle. + holdout_target = loop._holdout_target(confirm) + loop._start_run_log(data, "VLDiagnoseLoop", confirm=confirm, test=test, val=loop.val_data) + + state = RunState(original_data=original_data, data=data, timings=timings) + stopped_by = STOPPED_BY_MAX + cycles = 0 + for cycle in range(loop.max_cycles): + cycles = cycle + 1 + stop = self._cycle(loop, cycle, state, holdout=holdout_target is not None) + if stop is not None: + stopped_by = stop + break + + # The M4 pass: with a confirm split in play the hypotheses are tested + # ONCE, on the held-out split — the same discipline run_fix already + # applies to candidates. Without one, the in-cycle results stand. + m4_holdout_status: "str | None" = None + if holdout_target is not None and state.all_hypotheses: + state.all_test_results, m4_holdout_status = loop._m4_holdout_pass( + state.all_hypotheses, holdout_target, state.analyzer_names, timings, + ) + verified = loop.hypothesis_tester.best_hypotheses(state.all_test_results) + + return AutoDiagnoseReport( + cycles=cycles, + resolved=bool(verified), + stopped_by=stopped_by, + verified_hypotheses=verified, + final_hypotheses=state.all_hypotheses, + all_test_results=state.all_test_results, + final_stats_report=state.stats_report, + store=loop.store, + m4_holdout=m4_holdout_status, + _run_id=loop._run_id, + ) + + @staticmethod + def _cycle(loop: "VLDiagnoseLoop", cycle: int, state: RunState, *, holdout: bool) -> "str | None": + """One M1→M2→M3(→M4) cycle. Returns why the loop stops, or None to go on. + + With *holdout*, M4 is deferred to the single held-out pass after the + loop: testing here would re-use the explore data the hypotheses were + mined from, and its verdict must not steer the loop (no early stop / + no extra cycles keyed on SUPPORTED-or-not). + """ + data, timings = state.data, state.timings + state.cycle = cycle + if loop.token_budget > 0 and loop._tokens_used >= loop.token_budget: + logger.warning("Token budget %d exhausted after %d cycles", loop.token_budget, cycle) + return STOPPED_BY_BUDGET + if loop.run_logger is not None: + loop.run_logger.current_cycle = cycle + + # ── M1: protocol-guided probing (+ signal bridge) ───────── + probe_results, artifact_pngs = loop._do_m1(cycle, data, state.all_hypotheses, timings) + if not probe_results: + logger.info("M1 produced no probe results — stopping.") + return STOPPED_BY_NO_PROBE + state.analyzer_names = list(probe_results) + + # ── explore (optional): free-form EDA on M1's table → M3 notes ── + loop._do_explore(cycle, probe_results, data, timings) + + # ── M2: protocol-aware stats analysis ──────────────────── + stats_report = loop._do_m2(cycle, probe_results, data, artifact_pngs, timings) + state.stats_report = stats_report + if loop.analysis_only: + return STOPPED_BY_NO_HYPS + + # ── M3: hypothesis generation ("AI scientist") ──────────── + diag = loop._do_m3(cycle, stats_report, state.prior_cycles, timings, cases=data) + if diag is None: + state.diagnosis_failed = True + return STOPPED_BY_DIAG_ERROR + if not diag.hypotheses: + logger.info("M3 produced no hypotheses at cycle %d.", cycle) + return STOPPED_BY_NO_HYPS + for h in diag.hypotheses: + loop.store.add_hypothesis(h) + state.all_hypotheses.extend(diag.hypotheses) + + # ── M4: hypothesis testing (stats + protocol consistency) ─ + if not holdout: + test_results = loop._do_m4(cycle, diag.hypotheses, stats_report, data, timings) + state.all_test_results.extend(test_results) + if loop.hypothesis_tester.stopping_criteria_met(test_results, loop.protocol): + logger.info( + "Stopping criteria met at cycle %d: verified, protocol-consistent " + "hypothesis found.", + cycle, + ) + return STOPPED_BY_CRITERIA + + state.prior_cycles.append(cycle_summary(cycle, stats_report, diag.hypotheses)) + return None diff --git a/evalrx/eval_agent/prompts/agentic.py b/evalrx/eval_agent/prompts/agentic.py index f1f9852c..61e781c2 100644 --- a/evalrx/eval_agent/prompts/agentic.py +++ b/evalrx/eval_agent/prompts/agentic.py @@ -11,9 +11,7 @@ {evidence} -Reply with EXACTLY ONE JSON object choosing your next action — no prose -outside it: -{{"tool": "", "params": {{...}}, "rationale": ""}} +Choose your next action. Rules: - You may only call "stop" with params.resolved=true once a hypothesis has @@ -27,23 +25,4 @@ probe's name; "run_probe" with no params lets the probe agent choose. - Prefer the order that makes evidentiary sense (e.g. you need probe findings before stats, stats before hypotheses, hypotheses before testing one) but - you decide the sequence and when to stop, not a fixed script. - -Return ONLY the JSON object.""" - -ACTION_REPAIR_PROMPT = """\ -Your previous response could not be used as an action. - -Previous response: -{raw} - -Problem(s): -{errors} - -{evidence} - -Reply with EXACTLY ONE JSON object choosing your next action — no prose -outside it: -{{"tool": "", "params": {{...}}, "rationale": ""}} - -Return ONLY the JSON object.""" + you decide the sequence and when to stop, not a fixed script.""" diff --git a/evalrx/eval_agent/prompts/case_discovery.py b/evalrx/eval_agent/prompts/case_discovery.py index 7509cbe6..16483b5a 100644 --- a/evalrx/eval_agent/prompts/case_discovery.py +++ b/evalrx/eval_agent/prompts/case_discovery.py @@ -18,8 +18,7 @@ Observed model answer: {observed} -Return a JSON object: -{{"label": "PASS|FAIL|UNKNOWN", "reason": "one concise sentence"}} +Give a label (PASS, FAIL or UNKNOWN) and a one-sentence reason. Use PASS only when the observed answer satisfies the expected answer/rubric under the success criteria.""" diff --git a/evalrx/eval_agent/prompts/diagnosis.py b/evalrx/eval_agent/prompts/diagnosis.py index b2e479a6..086ce176 100644 --- a/evalrx/eval_agent/prompts/diagnosis.py +++ b/evalrx/eval_agent/prompts/diagnosis.py @@ -4,11 +4,11 @@ You are an expert ML diagnostician. Based on the analysis report below, propose specific, falsifiable hypotheses about the root cause of the model's failures. -Each hypothesis is written twice: once for a specialist (HYPOTHESIS, TEST) and +Each hypothesis is written twice: once for a specialist (hypothesis, test) and once for the person who will read the report. That reader builds and runs evaluations but does not do statistics — they know what a benchmark, a prompt and a failure case are, and they have never met an e-value, a McNemar test or a -multiple-comparisons correction. The PLAIN_STATEMENT line is written for them. +multiple-comparisons correction. The plain_statement field is written for them. {prior_section} Model: {model_name} Overall severity (threshold rules): {severity} @@ -22,18 +22,17 @@ Raw findings (JSON): {findings_json} -{available_signals_section}Propose 1-3 hypotheses. For each write: -HYPOTHESIS: -PLAIN_STATEMENT: -FAILURE_MODE: -TEST: -EXPECTED_ASSOCIATION: +higher_on_failures for a fixed_by_* signal. Base your hypotheses on the analysis conclusion and evidence above — an analyzer can surface a real failure mode even when no numeric threshold fired, so do NOT rely on the threshold severity alone. Do NOT repeat hypotheses already listed in the prior cycles above. -If the conclusion and evidence genuinely show no problem, respond with: NO_ISSUE""" +If the conclusion and evidence genuinely show no problem, return no hypotheses.""" _VALIDATE_PROMPT = """\ You are an adversarial ML reviewer. Your job is to find reasons to REJECT each @@ -78,50 +77,9 @@ Findings summary (the evidence the hypotheses were drawn from): {findings_json} -Hypotheses to review: +Hypotheses to review (numbered): {hypotheses_text} -For each hypothesis output two lines: -KEEP: or REJECT: -REASON: -REASON: """ - - -_FORMAT_REPAIR_PROMPT = """\ -Your previous answer below could not be read: it contains no line that starts -with the label HYPOTHESIS:. The hypotheses are only usable in the exact -line-labelled format. - -Previous answer: -{raw} - -Rewrite the SAME hypotheses (do not invent new ones) so that each one is a block -of these lines, in this order, each label at the start of its own line: -HYPOTHESIS: -PLAIN_STATEMENT: -FAILURE_MODE: -TEST: -EXPECTED_ASSOCIATION: - -If your previous answer meant that there is no issue to report, reply with the -single word NO_ISSUE.""" - -_PLAIN_REPAIR_PROMPT = """\ -Your previous answer below proposed hypotheses correctly, but some -PLAIN_STATEMENT lines fail a plain-language check. - -PLAIN_STATEMENT must be a one-sentence everyday paraphrase of the matching -HYPOTHESIS line, written for an engineer who runs evaluations but does no -statistics: no statistics terms, no acronyms, no symbols, and not a verbatim -copy of the HYPOTHESIS line. Numbers are welcome, but each one must come with -what it amounts to rather than standing bare. - -Previous answer: -{raw} - -Problems found: -{violations} - -Rewrite the FULL set of hypotheses in the exact same -HYPOTHESIS/PLAIN_STATEMENT/FAILURE_MODE/TEST/EXPECTED_ASSOCIATION format, -fixing only the flagged PLAIN_STATEMENT lines. Do not change any other line.""" +Give one decision per hypothesis, by its number: keep or reject, with a reason +of one or two sentences naming the flaw you found, or "evidence directly +supports this claim" if keeping.""" diff --git a/evalrx/eval_agent/prompts/nl_runner.py b/evalrx/eval_agent/prompts/nl_runner.py index ff742128..208acebe 100644 --- a/evalrx/eval_agent/prompts/nl_runner.py +++ b/evalrx/eval_agent/prompts/nl_runner.py @@ -27,10 +27,12 @@ 6. Accept CLI flags: --model, --device, --dtype, --max-cycles, --max-analyzers, --smoke-test, --run-dir. 7. Write outputs via `RunContext(args.run_dir)` (from `evalrx.eval_agent`), - defaulting `--run-dir` to `Path(__file__).parent / "outputs"`. This - defaults to the V2 logger (`run.json` + `M1..M5/log.json`, no flat - `run_log.jsonl`, no `README.txt`/`manifest.json`) — don't assume those - V1-only files exist when printing a completion summary. + defaulting `--run-dir` to `Path(__file__).parent / "outputs"`. The run + is logged as `run.json` + `M1..M5/log.json`; print a completion summary + from those, not from any other file. Call + `ctx.finalize()` once everything has run (or use `with RunContext(...) as + ctx:`): it logs the run's end, without which the report reads it as + unfinished. 8. Include a `--smoke-test` path with a `_SmokeModel` stand-in so the script can be verified without a GPU. diff --git a/evalrx/eval_agent/run_context.py b/evalrx/eval_agent/run_context.py index 40cc9651..ccdbad41 100755 --- a/evalrx/eval_agent/run_context.py +++ b/evalrx/eval_agent/run_context.py @@ -8,8 +8,8 @@ gluing with one library-owned object that owns the whole run directory and hands every producer its subdirectory. -The logger is :class:`~evalrx.eval_agent.run_logger_v2.RunLoggerV2` (see -``evalrx/eval_agent/RUN_LOGGER_V2.md``): one ``run.json`` plus one +The logger is :class:`~evalrx.eval_agent.run_logger.RunLogger` (see +``evalrx/eval_agent/RUN_LOGGER.md``): one ``run.json`` plus one ``M1/log.json``..``M5/log.json`` per stage, no flat event file, no persisted ``prompts/``/``experiments/``/``tools/``/``workspace/``/``fixes/`` — generated text/code is captured inline into the relevant stage's JSON via an ephemeral @@ -48,16 +48,16 @@ from __future__ import annotations -import json import re import shutil import tempfile +from collections.abc import Sized from datetime import datetime from pathlib import Path from typing import TYPE_CHECKING, Any if TYPE_CHECKING: - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger class Trial: @@ -98,14 +98,6 @@ def write(self, name: str, content: "str | bytes") -> Path: path.write_text(content, encoding="utf-8") return path - def write_record(self, markdown: str) -> Path: - """Write the human-readable summary to ``/record.md``.""" - return self.write("record.md", markdown) - - def write_result(self, data: "dict[str, Any]") -> Path: - """Write the machine-readable outcome to ``/result.json``.""" - return self.write("result.json", json.dumps(data, indent=2, default=str)) - def __repr__(self) -> str: return f"Trial(root={str(self.root)!r})" @@ -155,7 +147,7 @@ def __init__( self._verbose = verbose self._narrate = narrate self._observability_mode = observability_mode - self._logger: "RunLoggerV2 | None" = None + self._logger: "RunLogger | None" = None self._workdir_seq = 0 self._trial_seq: "dict[str, int]" = {} self._runtime_root: "Path | None" = None @@ -205,12 +197,12 @@ def artifacts_dir(self) -> Path: # ------------------------------------------------------------------ @property - def logger(self) -> "RunLoggerV2": + def logger(self) -> "RunLogger": """The logger bound to this context (created on first use).""" if self._logger is None: - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger - self._logger = RunLoggerV2( + self._logger = RunLogger( run_dir=self.root, verbose=self._verbose, narrate=self._narrate, observability_mode=self._observability_mode, context=self, @@ -273,33 +265,25 @@ def figure_path(self, name: str) -> Path: def write_diagnose_report( self, report: Any, - cases: "list[Any]", + cases: "Sized", *, discovery: "list[dict[str, Any]] | None" = None, ) -> None: """Inline the standard post-diagnosis report into ``run.json``. - *report* is an :class:`AutoDiagnoseReport` (both loops return - this one unified class — ``VLDiagnoseReport`` is an alias for it). + *report* is an :class:`AutoDiagnoseReport` (both loops return it). *discovery* (optional) is a list of already-serialised case rows — examples that compute task-specific columns (e.g. parsed yes/no) build the rows themselves. Delegates to - :meth:`~evalrx.eval_agent.run_logger_v2.RunLoggerV2.log_diagnose_report`. + :meth:`~evalrx.eval_agent.run_logger.RunLogger.log_diagnose_report`. """ self.logger.log_diagnose_report(report, cases, discovery=discovery) - def publish_report( - self, - *, - model: "Any | None" = None, - example_dir: "str | Path | None" = None, - ) -> "Any": + def publish_report(self, *, model: "Any | None" = None) -> "Any": """Publish the dynamic report after all diagnostic/fix stages finish.""" from evalrx.reporting.dynamic import publish_report - return publish_report( - self.root, example_dir=example_dir, model=model, run_logger=self._logger, - ) + return publish_report(self.root, model=model, run_logger=self._logger) # ------------------------------------------------------------------ # Lifecycle diff --git a/evalrx/eval_agent/run_log.schema.json b/evalrx/eval_agent/run_log.schema.json index 83964f9f..6b9eefc8 100644 --- a/evalrx/eval_agent/run_log.schema.json +++ b/evalrx/eval_agent/run_log.schema.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://evalrx.dev/schemas/run_log.schema.json", "title": "EvalRX run event", - "description": "One logged event, wherever a run stores it (run.json / M/log.json). Discriminated on `event`; matches schema_version 6. Permissive: extra (additive) fields are allowed.", + "description": "One logged event, wherever a run stores it (run.json / M/log.json). Discriminated on `event`; matches schema_version 8. Permissive: extra (additive) fields are allowed.", "$defs": { "envelope": { "type": "object", @@ -28,6 +28,7 @@ "experiment", "fix", "loop_end", + "run_end", "tool_codegen", "tool_registry", "agent_decision", @@ -41,7 +42,7 @@ ] }, "schema_version": { - "const": 6 + "const": 8 }, "ts": { "type": "string", @@ -150,31 +151,11 @@ "selection_rationale": { "type": "string" }, - "judge_io": { - "type": "object", - "properties": { - "prompt_path": { - "type": "string" - }, - "prompt_chars": { - "type": "integer" - }, - "raw_path": { - "type": "string" - }, - "raw_chars": { - "type": "integer" - } - } - }, "duration_sec": { "type": "number" }, "n_model_calls": { "type": "integer" - }, - "model_calls_path": { - "type": "string" } }, "required": [ @@ -219,12 +200,6 @@ "evidence_chain": { "type": "array" }, - "stats_tool_results": { - "type": [ - "object", - "array" - ] - }, "stats_plan": { "type": [ "object", @@ -243,29 +218,9 @@ "array" ] }, - "visualizations": { - "type": "array" - }, "figures": { "type": "array" }, - "judge_io": { - "type": "object", - "properties": { - "prompt_path": { - "type": "string" - }, - "prompt_chars": { - "type": "integer" - }, - "raw_path": { - "type": "string" - }, - "raw_chars": { - "type": "integer" - } - } - }, "duration_sec": { "type": "number" } @@ -440,23 +395,6 @@ "failure_modes_used": { "type": "boolean" }, - "judge_io": { - "type": "object", - "properties": { - "prompt_path": { - "type": "string" - }, - "prompt_chars": { - "type": "integer" - }, - "raw_path": { - "type": "string" - }, - "raw_chars": { - "type": "integer" - } - } - }, "duration_sec": { "type": "number" } @@ -521,23 +459,6 @@ }, "duration_sec": { "type": "number" - }, - "judge_io": { - "type": "object", - "properties": { - "prompt_path": { - "type": "string" - }, - "prompt_chars": { - "type": "integer" - }, - "raw_path": { - "type": "string" - }, - "raw_chars": { - "type": "integer" - } - } } }, "required": [ @@ -614,20 +535,11 @@ "null" ] }, - "code_paths": { - "type": "object" - }, - "output_paths": { - "type": "object" - }, "workspace_snapshot": { "type": [ "object", "null" ] - }, - "record": { - "type": "string" } }, "required": [ @@ -655,9 +567,6 @@ }, "module": { "type": "string" - }, - "record": { - "type": "string" } }, "required": [ @@ -755,6 +664,24 @@ } ] }, + "run_end": { + "allOf": [ + { + "$ref": "#/$defs/envelope" + }, + { + "type": "object", + "properties": { + "event": { + "const": "run_end" + } + }, + "required": [ + "event" + ] + } + ] + }, "tool_codegen": { "allOf": [ { @@ -786,9 +713,6 @@ "string", "null" ] - }, - "code_paths": { - "type": "object" } }, "required": [ @@ -866,23 +790,6 @@ "fallback_used": { "type": "boolean" }, - "judge_io": { - "type": "object", - "properties": { - "prompt_path": { - "type": "string" - }, - "prompt_chars": { - "type": "integer" - }, - "raw_path": { - "type": "string" - }, - "raw_chars": { - "type": "integer" - } - } - }, "duration_sec": { "type": "number" } @@ -1181,6 +1088,9 @@ { "$ref": "#/$defs/loop_end" }, + { + "$ref": "#/$defs/run_end" + }, { "$ref": "#/$defs/tool_codegen" }, diff --git a/evalrx/eval_agent/run_log_entries.py b/evalrx/eval_agent/run_log_entries.py new file mode 100644 index 00000000..0693036d --- /dev/null +++ b/evalrx/eval_agent/run_log_entries.py @@ -0,0 +1,442 @@ +"""What each logged event records: one pure function per event kind. + +Each takes the object a stage produced and returns the JSON-safe entry the +logger appends for it. None of them touches a file or the logger's state; +`RunLogger` saves any media first, stamps the time, and appends the result. +""" + +from __future__ import annotations + +import dataclasses +import json +from collections.abc import Sized +from pathlib import Path +from typing import Any, Callable + +from evalrx.eval_agent.hypothesis import hypothesis_id + + +def json_safe(value: Any) -> Any: + """*value* as plain JSON data: dataclasses and ``to_dict`` objects unpacked.""" + if dataclasses.is_dataclass(value) and not isinstance(value, type): + value = dataclasses.asdict(value) + elif hasattr(value, "to_dict") and callable(value.to_dict): + try: + value = value.to_dict() + except Exception: # noqa: BLE001 + pass + return json.loads(json.dumps(value, ensure_ascii=False, default=str)) + + +def _case_snapshot(case: Any) -> "dict[str, Any]": + """Make a small, renderer-safe baseline record for an evidence example.""" + if hasattr(case, "to_dict"): + value = case.to_dict() + elif isinstance(case, dict): + value = dict(case) + else: + value = {"id": str(getattr(case, "id", ""))} + inputs = value.get("inputs") if isinstance(value.get("inputs"), dict) else {} + return { + "id": str(value.get("id") or value.get("case_id") or ""), + "input": inputs.get("prompt") or value.get("prompt") or value.get("instruction") or "", + "baseline_output": value.get("observed", value.get("output")), + "expected": value.get("expected"), + "outcome": value.get("label") or value.get("status") or "unknown", + } + + +def _iter_cases(cases: Any) -> "list[Any]": + """Accept CaseBatch, a plain sequence, or a generator without assumptions.""" + if cases is None: + return [] + value = getattr(cases, "cases", cases) + try: + return list(value) + except TypeError: + return [] + + +def _probe_examples(results: "dict[str, Any]", cases: Any) -> "list[dict[str, Any]]": + """Persist two real, bounded M1 walkthroughs beside aggregate findings. + + A probe only becomes a before/after comparison when its analyzer explicitly + records both outputs. Otherwise this records an honest *baseline case + + check result* example; downstream UI must not call it an intervention. + """ + snapshots: dict[str, dict[str, Any]] = {} + for case in _iter_cases(cases): + snapshot = _case_snapshot(case) + if snapshot["id"]: + snapshots[snapshot["id"]] = snapshot + output: list[dict[str, Any]] = [] + used: set[str] = set() + for name, result in results.items(): + findings = getattr(result, "findings", {}) or {} + rows = findings.get("per_case") or [] + if not isinstance(rows, list): + continue + rows = sorted( + (row for row in rows if isinstance(row, dict)), + key=lambda row: 0 if str(snapshots.get(str(row.get("sample_id") or row.get("case_id") or ""), {}).get("outcome", "")).lower() == "fail" else 1, + ) + for row in rows: + case_id = str(row.get("sample_id") or row.get("case_id") or "") + case_snapshot = snapshots.get(case_id) + if not case_snapshot or case_id in used: + continue + checked = { + str(key).replace("_", " "): value for key, value in row.items() + if key not in {"sample_id", "case_id"} and isinstance(value, (str, int, float, bool)) + } + if not checked: + continue + used.add(case_id) + output.append({ + "id": f"m1-{name}-{case_id}", "kind": "case_measurement", "case_id": case_id, + "probe_title": str(name).replace("_", " ").title(), + **case_snapshot, "check_result": checked, + "plain_reading": "This one case illustrates the recorded check. The aggregate M1 result uses all measured cases.", + "evidence_scope": "one recorded case within M1", + }) + break + if len(output) >= 2: + break + return output + + +def probe_entry( + cycle: int, results: dict[str, Any], *, result_docs: dict[str, Any], artifact_paths: dict[str, str], + inline_artifacts: dict[str, Any], n_model_calls: int, cases: Any, schema: Any, + failed_analyzers: "dict[str, str] | None", judge_prompt: "str | None", judge_raw: "str | None", + duration_sec: "float | None", +) -> dict[str, Any]: + """One M1 probe pass: every analyzer's findings and complete result, inline.""" + entry: dict[str, Any] = { + "cycle": cycle, + "analyzers": list(results), + "findings": {name: r.findings for name, r in results.items()}, + "results": result_docs, + "artifact_paths": artifact_paths, + "artifacts": inline_artifacts, + "n_model_calls": n_model_calls, + } + examples = _probe_examples(results, cases) + if examples: + entry["examples"] = examples + if failed_analyzers: + entry["failed_analyzers"] = dict(failed_analyzers) + if schema is not None: + entry["selection_rationale"] = getattr(schema, "rationale", "") + selected = getattr(schema, "selected_analyzers", None) + if selected is not None: + entry["selected_analyzers"] = list(selected) + if judge_prompt: + entry["judge_prompt"] = judge_prompt + if judge_raw: + entry["judge_response"] = judge_raw + if duration_sec is not None: + entry["duration_sec"] = round(duration_sec, 3) + return entry + + +def analysis_entry( + cycle: int, report: Any, *, portable_path: "Callable[[Any], str]", duration_sec: "float | None", +) -> dict[str, Any]: + """One M2 analysis: severity, findings, and whichever statistical outputs the report carries.""" + entry: dict[str, Any] = { + "cycle": cycle, + "severity": report.severity, + "n_findings": len(report.findings), + "findings": [str(f) for f in report.findings], + "narrative": report.narrative, + "descriptive_only": bool(getattr(report, "descriptive_only", False)), + } + stats_tool = getattr(report, "stats_tool", None) + if stats_tool: + entry["stats_tool"] = stats_tool + fallback_reason = getattr(report, "llm_fallback_reason", None) + if fallback_reason: + entry["llm_fallback_reason"] = fallback_reason + conclusion = getattr(report, "conclusion", None) + if conclusion: + entry["conclusion"] = conclusion + evidence_chain = getattr(report, "evidence_chain", None) + if evidence_chain: + entry["evidence_chain"] = list(evidence_chain) + stats_plan = getattr(report, "stats_plan", None) + if stats_plan: + entry["stats_plan"] = stats_plan + stats_results = getattr(report, "stats_results", None) + if stats_results: + entry["stats_results"] = [r.to_dict() for r in stats_results] + corrected = getattr(report, "corrected_rejections", None) + if corrected: + entry["corrected_rejections"] = corrected + figures = getattr(report, "figures", None) + if figures: + entry["figures"] = [portable_path(f) for f in figures] + llm_prompt = getattr(report, "llm_prompt", None) + llm_raw = getattr(report, "llm_raw", None) + if llm_prompt: + entry["judge_prompt"] = llm_prompt + if llm_raw: + entry["judge_response"] = llm_raw + if duration_sec is not None: + entry["duration_sec"] = round(duration_sec, 3) + return entry + + +def explore_entry( + cycle: int, report: Any, *, ok: bool, charts: list[Any], rendered: list[str], + workspace: "dict[str, Any] | None", out_dir: Any, duration_sec: "float | None", +) -> dict[str, Any]: + """One explore step: counts, the first observations and caveats, and the inlined workspace.""" + tables = getattr(report, "tables", None) or {} + adjudication = dict(getattr(report, "adjudication", None) or {}) if report is not None else {} + entry: dict[str, Any] = { + "cycle": cycle, "ok": ok, + "n_observations": len(getattr(report, "observations", None) or []) if report is not None else 0, + "n_charts": len(charts), "n_charts_rendered": len(rendered), + "n_tables": len(tables) if isinstance(tables, dict) else len(list(tables or [])), + "n_candidate_signals": len(getattr(report, "candidate_signals", None) or []) if report is not None else 0, + "n_hypotheses": len(getattr(report, "hypotheses", None) or []) if report is not None else 0, + "adjudication": { + k: adjudication[k] for k in ( + "method", "alpha", "split", "n_host_adjudicated", "n_rejected", + "n_in_family", "n_descriptive_only", + ) if k in adjudication + }, + "observations": [str(o) for o in (getattr(report, "observations", None) or [])[:12]] if report is not None else [], + "caveats": [str(c) for c in (getattr(report, "caveats", None) or [])[:8]] if report is not None else [], + "figures": rendered, + "workspace_snapshot": workspace, + "attempts": int(getattr(report, "attempts", 0) or 0) if report is not None else 0, + } + error = str(getattr(report, "error", "") or "") if report is not None else "explorer produced no report" + if error: + entry["error"] = error + if out_dir is not None and workspace is None: + entry["out_dir"] = str(out_dir) + report_path = Path(out_dir) / "exploratory_report.json" + if report_path.exists(): + entry["report_path"] = str(report_path) + if report is not None and getattr(report, "code", None): + entry["code"] = str(report.code) + if report is not None and getattr(report, "raw_outputs", None): + entry["raw_outputs"] = [str(r) for r in report.raw_outputs] + if duration_sec is not None: + entry["duration_sec"] = round(duration_sec, 3) + return entry + + +def diagnosis_entry( + cycle: int, diag: Any, *, duration_sec: "float | None", explore_figures: "list[str] | None", +) -> dict[str, Any]: + """One M3 diagnosis: the accepted hypotheses, what was proposed, and the critic's review.""" + entry: dict[str, Any] = { + "cycle": cycle, + "model_name": diag.model_name, + "n_hypotheses": len(diag.hypotheses), + "hypotheses": [ + { + # Join key for M4/M5 entries logged against this same + # hypothesis later (log_surgery/log_experiment/log_fix) — + # see evalrx.eval_agent.hypothesis.hypothesis_id. + "id": hypothesis_id(h), + "statement": h.statement, "plain_statement": h.plain_statement, + "failure_mode": h.predicted_failure_mode, + "status": h.status.value if h.status else None, + "test_design": h.test_design, + "critic": (h.metadata or {}).get("critic"), + "critic_reason": (h.metadata or {}).get("critic_reason"), + } + for h in diag.hypotheses + ], + "raw_judge_output": diag.raw_judge_output, + "n_critic_kept": int(getattr(diag, "n_critic_kept", 0) or 0), + "n_critic_rejected": int(getattr(diag, "n_critic_rejected", 0) or 0), + } + critic_raw = getattr(diag, "critic_raw_output", "") or "" + if critic_raw: + entry["critic_raw_output"] = critic_raw + entry["critic_prompt"] = getattr(diag, "critic_prompt", "") or "" + proposed = list(getattr(diag, "proposed_hypotheses", None) or []) + if proposed: + entry["proposed_hypotheses"] = [ + {"statement": h.statement, "plain_statement": h.plain_statement, + "failure_mode": h.predicted_failure_mode, "test_design": h.test_design} + for h in proposed + ] + review_decisions = list(getattr(diag, "review_decisions", None) or []) + if review_decisions: + entry["review"] = { + "n_kept": sum(d.get("decision") == "keep" for d in review_decisions), + "n_rejected": sum(d.get("decision") == "reject" for d in review_decisions), + "decisions": review_decisions, + } + referenced = getattr(diag, "referenced_charts", None) + if referenced: + entry["referenced_charts"] = list(referenced) + if getattr(diag, "explore_context_used", False): + entry["explore_context_used"] = True + if getattr(diag, "failure_modes_used", False): + entry["failure_modes_used"] = True + if explore_figures: + entry["explore_figures"] = list(explore_figures) + m3_prompt = getattr(diag, "prompt", None) or "" + if m3_prompt: + entry["judge_prompt"] = m3_prompt + review_prompt = getattr(diag, "review_prompt", None) or "" + review_raw = getattr(diag, "review_raw", None) or "" + if review_prompt or review_raw: + entry["review_prompt"] = review_prompt + entry["review_response"] = review_raw + if duration_sec is not None: + entry["duration_sec"] = round(duration_sec, 3) + return entry + + +def surgery_entry( + cycle: int, hypothesis: Any, iv: Any, *, stage: str, validation_cases: Any, + judge_prompt: "str | None", judge_raw: "str | None", duration_sec: "float | None", +) -> dict[str, Any]: + """One M4 verdict or M5 intervention on a hypothesis.""" + entry: dict[str, Any] = { + "cycle": cycle, + "module": stage.lower(), + + # Joins this verdict back to its M3 hypotheses[] entry (same id). + "hypothesis_id": hypothesis_id(hypothesis), + "hypothesis": hypothesis.statement, + "failure_mode": hypothesis.predicted_failure_mode, + "status": iv.status.value, "fixed": iv.fixed, + "confidence_score": iv.confidence_score, + "evidence_dimensions": iv.evidence_dimensions, + "evidence": iv.evidence, + "n_refocused_cases": len(iv.new_data) if iv.new_data else None, + } + if stage == "M4": + candidates = _iter_cases(validation_cases) + if candidates: + snapshots = [_case_snapshot(case) for case in candidates] + snapshot = next( + (item for item in snapshots if str(item.get("outcome", "")).lower() == "fail"), + snapshots[0], + ) + entry["validation_examples"] = [{ + "id": f"m4-{snapshot.get('id')}", "kind": "validation_case", + "case_id": snapshot.get("id"), **snapshot, + "plain_reading": "This is one case in the independent validation pool. The verdict is determined from the full pool, not this case alone.", + "evidence_scope": "one case in the independent validation pool", + }] + if judge_prompt: + entry["judge_prompt"] = judge_prompt + if judge_raw: + entry["judge_response"] = judge_raw + if duration_sec is not None: + entry["duration_sec"] = round(duration_sec, 3) + return entry + + +def experiment_entry( + cycle: int, hypothesis: Any, iv: Any, *, module: str, exp: dict[str, Any], files: dict[str, Any], + workspace: "dict[str, Any] | None", +) -> dict[str, Any]: + """One experiment the agent wrote and ran: its code, output and verdict as strings.""" + entry: dict[str, Any] = { + "cycle": cycle, "module": module, + # Joins this experiment back to its M3 hypotheses[] entry (same id). + "hypothesis_id": hypothesis_id(hypothesis), + "hypothesis": hypothesis.statement, + "failure_mode": hypothesis.predicted_failure_mode, + "status": iv.status.value if iv.status else None, + "fixed": iv.fixed, + "provider": exp.get("provider"), "verdict": exp.get("verdict"), + "metrics": exp.get("metrics"), "returncode": exp.get("returncode"), + "timed_out": exp.get("timed_out"), "cli_usage": exp.get("cli_usage"), + "llm_calls": exp.get("llm_calls"), "sandbox_runs": exp.get("sandbox_runs"), + "code": files, + "stdout": exp.get("stdout"), "stderr": exp.get("stderr"), + "blueprint": exp.get("blueprint"), "cli_raw_output": exp.get("cli_raw_output"), + "validation_log": list(exp.get("validation_log") or []) or None, + "workspace_snapshot": workspace, + "trial_root": exp.get("trial_root"), + } + return entry + + +def diagnose_report_entry( + report: Any, cases: Sized, discovery: "list[dict[str, Any]] | None", +) -> dict[str, Any]: + """The post-diagnosis report: every hypothesis, every M4 verdict, the discovery rows.""" + hypotheses = [ + { + "statement": h.statement, + "plain_statement": getattr(h, "plain_statement", ""), + "failure_mode": h.predicted_failure_mode, + "status": h.status.value if h.status else None, + } + for h in getattr(report, "final_hypotheses", []) + ] + m4_results = [ + { + "hypothesis": tr.hypothesis.statement, + "failure_mode": tr.hypothesis.predicted_failure_mode, + "status": tr.status.value, + "effect_size": tr.effect_size, + "confidence": tr.confidence, + "protocol_consistent": tr.is_consistent_with_protocol, + "verdict": tr.verdict, + "evidence": tr.evidence, + } + for tr in getattr(report, "all_test_results", []) + ] + return { + "cycles": report.cycles, + "stopped_by": getattr(report, "stopped_by", None), + "resolved": getattr(report, "resolved", None), + "n_cases": len(cases), + "n_hypotheses": len(hypotheses), + "n_verified": len(getattr(report, "verified_hypotheses", [])), + "hypotheses": hypotheses, + "m4_results": m4_results, + "discovery": list(discovery or []), + } + + +def loop_end_entry( + report: Any, *, tokens_used: "int | None", timings: "dict[str, float] | None", +) -> dict[str, Any]: + """How a loop ended: cycles, timings, and the hypotheses it finished with.""" + entry: dict[str, Any] = {"cycles": report.cycles} + if tokens_used is not None: + entry["tokens_used"] = tokens_used + if timings: + entry["timings_sec"] = {k: round(v, 3) for k, v in timings.items()} + entry["total_duration_sec"] = round(sum(timings.values()), 3) + if hasattr(report, "resolved"): + entry["resolved"] = report.resolved + hyps = getattr(report, "final_hypotheses", []) + entry["n_hypotheses"] = len(hyps) + entry["final_hypotheses"] = [ + {"statement": h.statement, "plain_statement": h.plain_statement, + "failure_mode": h.predicted_failure_mode, "status": h.status.value if h.status else None} + for h in hyps + ] + if hasattr(report, "stopped_by"): + entry["stopped_by"] = report.stopped_by + all_hyps = getattr(report, "final_hypotheses", []) + verified = getattr(report, "verified_hypotheses", []) + entry["n_hypotheses"] = len(all_hyps) + entry["n_verified"] = len(verified) + entry["verified_hypotheses"] = [ + {"statement": tr.hypothesis.statement, + "failure_mode": tr.hypothesis.predicted_failure_mode, + "status": tr.status.value, + "confidence": tr.confidence, + "protocol_consistent": tr.is_consistent_with_protocol, + "verdict": getattr(tr, "verdict", None)} + for tr in verified + ] + return entry diff --git a/evalrx/eval_agent/run_log_files.py b/evalrx/eval_agent/run_log_files.py new file mode 100644 index 00000000..f63d0df0 --- /dev/null +++ b/evalrx/eval_agent/run_log_files.py @@ -0,0 +1,218 @@ +"""What the run logger puts on disk beside its JSON: atomic document writes, +sandbox workspaces inlined into an event, and numeric artifacts saved as +``.npy`` with a rendered figure. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +from typing import Any + +#: Extensions treated as genuine binary media — the one thing the run log +#: keeps as a separate file. Everything else becomes a JSON string value. +_MEDIA_EXTS = frozenset({ + ".npy", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", + ".wav", ".mp3", ".flac", ".ogg", ".mp4", ".avi", ".mov", +}) + +#: Text/code file suffixes worth inlining from a sandbox workspace snapshot +#: (skip weights/binaries — those go through the media/artifact path instead). +_INLINE_SUFFIXES = frozenset( + {".py", ".json", ".jsonl", ".md", ".txt", ".yaml", ".yml", ".csv", ".log", ".toml"} +) +_INLINE_MAX_BYTES = 2_000_000 # skip (note-only) any single file larger than this + + +def atomic_write_json(path: Path, obj: Any) -> None: + """Write *obj* as JSON to *path* such that a reader never sees a partial file. + + Writes to a sibling temp file first, then ``os.replace`` (atomic on the + same filesystem) — a crash mid-write leaves the OLD complete file in + place, never a truncated one. This runs on every single logged event + (see the design doc's "durability" section for the cost trade-off that + was chosen deliberately here, not overlooked). + """ + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(f".{path.name}.tmp{os.getpid()}") + tmp.write_text(json.dumps(obj, indent=2, default=str, ensure_ascii=False), encoding="utf-8") + os.replace(tmp, path) + + +def inline_workspace( + workdir: "str | Path", media_dir: Path, *, run_dir: "Path | None" = None, + max_bytes: "int | None" = _INLINE_MAX_BYTES, + preserve_all: bool = False, +) -> "dict[str, Any] | None": + """Read a sandbox working directory into a JSON-safe dict, inlining text. + + Returns ``{"files": {relative_path: content_or_note}, "media": [rel_paths], + "skipped": n}`` or ``None`` when *workdir* does not exist. Text-like files + (see ``_INLINE_SUFFIXES``) are read and inlined verbatim; recognised media + extensions are COPIED into *media_dir* (a real binary artifact, rule 4's + one exception) with a path reference left in ``"media"``; anything else is + skipped with a one-line note so its existence is still visible. + """ + import hashlib + import shutil + + src = Path(workdir) + if not src.exists() or not src.is_dir(): + return None + files: dict[str, Any] = {} + media: list[str] = [] + media_files: dict[str, str] = {} + skipped = 0 + for f in sorted(src.rglob("*")): + if not f.is_file(): + continue + rel = str(f.relative_to(src)) + suffix = f.suffix.lower() + inline_content = None + binary = suffix in _MEDIA_EXTS + if preserve_all and suffix not in _INLINE_SUFFIXES and not binary: + try: + inline_content = f.read_text(encoding="utf-8") + if "\x00" in inline_content: + binary = True + except UnicodeError: + binary = True + if binary: + media_dir.mkdir(parents=True, exist_ok=True) + # Path + content identify a snapshot: trials cannot collide, and + # later writes to the same source cannot replace earlier evidence. + hasher = hashlib.sha256(str(f.resolve()).encode("utf-8")) + with f.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + hasher.update(chunk) + digest = hasher.hexdigest()[:12] + dest = media_dir / f"{f.stem}_{digest}{suffix}" + try: + shutil.copy2(f, dest) + try: + media.append(str(dest.relative_to(run_dir)) if run_dir else str(dest)) + except ValueError: + media.append(str(dest)) + media_files[rel] = media[-1] + except Exception: # noqa: BLE001 + if preserve_all: + raise # do not let finalization delete unarchived evidence + skipped += 1 + continue + if suffix not in _INLINE_SUFFIXES and inline_content is None: + files[rel] = f"" + skipped += 1 + continue + try: + if max_bytes is not None and f.stat().st_size > max_bytes: + files[rel] = f"" + skipped += 1 + continue + files[rel] = inline_content if inline_content is not None else f.read_text(encoding="utf-8", errors="replace") + except Exception as exc: # noqa: BLE001 + if preserve_all: + raise + files[rel] = f"" + skipped += 1 + return {"files": files, "media": media, "media_files": media_files, "skipped": skipped} + + +def artifact_to_numpy(artifact: Any) -> "Any | None": + """Convert *artifact* to a numpy array, or return None if not possible. + + Handles: torch.Tensor, list[torch.Tensor] (e.g. per-layer attentions), + and numpy arrays. A list of tensors is stacked along a new first axis so + that ``attentions`` (list of ``(heads, seq, seq)``) becomes + ``(layers, heads, seq, seq)`` — a single array that retains all the data. + """ + try: + import numpy as np + except ImportError: + return None + + if hasattr(artifact, "detach"): # torch.Tensor + return artifact.detach().cpu().float().numpy() + if isinstance(artifact, np.ndarray): + return artifact + if isinstance(artifact, list) and artifact and hasattr(artifact[0], "detach"): + try: + import torch + return torch.stack(artifact).detach().cpu().float().numpy() + except Exception: # noqa: BLE001 + return None + return None + + +def save_artifact_figure(artifact_dir: Path, stem: str, arr: Any) -> None: + """Save a matplotlib figure of *arr* when the shape and stem are recognised. + + Dispatch table (first match wins): + - 4-D + ``attn`` in stem → mean over (layers, heads) → 2-D heatmap + - 3-D + ``attn`` in stem → mean over heads → 2-D heatmap + - 2-D + heatmap keyword → direct heatmap (viridis) + - 1-D + curve keyword → line plot + Skips silently when matplotlib is unavailable or the shape is unrecognised. + """ + try: + import matplotlib.pyplot as plt + plt.ioff() + except ImportError: + return + + key = stem.lower() + # Skip logit arrays — (seq, vocab) shape is too large for a useful figure + if "logit" in key: + return + + _is_attn = any(k in key for k in ("attn", "attention")) + + fig = None + try: + ndim = arr.ndim + if ndim == 4 and _is_attn: + mat = arr.mean(axis=(0, 1)) # (layers, heads, seq, seq) → (seq, seq) + n_layers, n_heads = arr.shape[0], arr.shape[1] + fig, ax = plt.subplots(figsize=(8, 7)) + im = ax.imshow(mat, cmap="viridis", aspect="auto", vmin=0) + ax.set_title(f"{stem} (mean over {n_layers}L × {n_heads}H)") + plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04) + plt.tight_layout() + elif ndim == 3 and _is_attn: + mat = arr.mean(axis=0) # (heads, seq, seq) → (seq, seq) + n_heads = arr.shape[0] + fig, ax = plt.subplots(figsize=(8, 7)) + im = ax.imshow(mat, cmap="viridis", aspect="auto", vmin=0) + ax.set_title(f"{stem} (mean over {n_heads} heads)") + plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04) + plt.tight_layout() + elif ndim == 2 and "diff" in key: + # Signed difference map (e.g. FAIL-mean minus PASS-mean attention): + # diverging colormap with symmetric limits so the sign is readable. + bound = float(max(abs(arr.min()), abs(arr.max()))) or 1.0 + fig, ax = plt.subplots(figsize=(8, 7)) + im = ax.imshow(arr, cmap="coolwarm", aspect="auto", vmin=-bound, vmax=bound) + ax.set_title(stem) + plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04) + plt.tight_layout() + elif ndim == 2 and (_is_attn or any(k in key for k in ("rollout", "spatial", "map"))): + fig, ax = plt.subplots(figsize=(8, 7)) + im = ax.imshow(arr, cmap="viridis", aspect="auto") + ax.set_title(stem) + plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04) + plt.tight_layout() + elif ndim == 1 and any(k in key for k in ("entropy", "score", "prob", "weight", "rollout")): + fig, ax = plt.subplots(figsize=(8, 3)) + ax.plot(arr) + ax.set_xlabel("position") + ax.set_ylabel(stem) + ax.set_title(stem) + plt.tight_layout() + + if fig is not None: + fig.savefig(artifact_dir / f"{stem}.png", dpi=100, bbox_inches="tight") + except Exception: # noqa: BLE001 + pass + finally: + if fig is not None: + plt.close(fig) diff --git a/evalrx/eval_agent/run_log_tracing.py b/evalrx/eval_agent/run_log_tracing.py new file mode 100644 index 00000000..0334f9b9 --- /dev/null +++ b/evalrx/eval_agent/run_log_tracing.py @@ -0,0 +1,293 @@ +"""The run log mirrored into Langfuse: one function per logged event. + +`RunLogger` writes an event to its JSON document and then calls the matching +function here with the tracer it owns. Nothing in this module touches the +log's files; a run with tracing off calls the same functions on a tracer that +records nothing. +""" + +from __future__ import annotations + +from typing import Any + +#: How many of an analyzer's target-model calls are mirrored per probe. +_MAX_CALLS_PER_PROBE = 50 + + +def trace_run_start(tracer: Any, entry: dict[str, Any]) -> None: + """Open the trace for a run that just logged its start.""" + model_name = str(entry.get("model") or "Target Model") + proto = entry.get("protocol") or {} + proto_desc = proto.get("description", "") if isinstance(proto, dict) else str(proto) + bench_name = str(entry.get("benchmark_name") or proto_desc or "Benchmark") + tracer.start_trace( + model=model_name, benchmark=bench_name, + n_cases=int(entry.get("n_cases", 0) or 0), metadata=entry, + ) + + +def _trace_model_calls(tracer: Any, analyzer: str, model_calls: list[dict[str, Any]], span: Any) -> int: + """Mirror *analyzer*'s target-model calls under *span*; how many it made.""" + calls = [c for c in model_calls if c.get("analyzer") == analyzer] + for call in calls[:_MAX_CALLS_PER_PROBE]: + tracer.log_generation( + name=f"{analyzer} · {call.get('method')} #{call.get('call_index')}", + model="target_model", prompt=call.get("inputs"), + completion=call.get("error") or call.get("output"), + span_id=span, + metadata={"duration_sec": call.get("duration_sec"), "error": call.get("error")}, + ) + return len(calls) + + +def trace_probe( + tracer: Any, cycle: int, results: dict[str, Any], entry: dict[str, Any], *, + artifact_paths: dict[str, str], figures: list[Any], judge_prompt: "str | None", + judge_raw: "str | None", duration_sec: "float | None", model_calls: list[dict[str, Any]], +) -> None: + """One M1 span, a child span per analyzer, and the target-model calls each made.""" + m1_span = tracer.start_span( + name=f"M1: Multi-Dimensional Checkup (Cycle {cycle})", + stage="M1", + input_data={"analyzers": list(results.keys()), "selected_analyzers": entry.get("selected_analyzers", [])}, + metadata={"duration_sec": duration_sec, "artifacts": { + "artifact_paths": artifact_paths, "figures": [str(p) for p in figures], + }}, + ) + if judge_prompt or judge_raw: + tracer.log_generation( + name="M1 Analyzer Selection", model="judge", + prompt=judge_prompt or "", completion=judge_raw or "", span_id=m1_span, + ) + for name, r in results.items(): + findings = getattr(r, "findings", {}) or {} + per_case = findings.get("per_case") or [] + probe_span = tracer.start_span( + name=f"Probe: {name}", stage=f"M1_{name}", input_data={"probe": name}, + parent_id=m1_span, + metadata={ + "n_scored": len(per_case) if per_case else (findings.get("n_cases") or findings.get("n_scored")), + }, + ) + n_calls = _trace_model_calls(tracer, name, model_calls, probe_span) + tracer.end_span(probe_span, output_data={"findings": findings, "n_model_calls": n_calls}) + orphaned = {c["analyzer"] for c in model_calls} - set(results) + for name in orphaned: + failed_span = tracer.start_span( + name=f"Probe: {name} (failed)", stage=f"M1_{name}", input_data={"probe": name}, + parent_id=m1_span, metadata={"note": "analyzer raised before producing a Result"}, + ) + n_calls = _trace_model_calls(tracer, name, model_calls, failed_span) + tracer.end_span(failed_span, status="failed", output_data={"n_model_calls": n_calls}) + tracer.end_span(m1_span, output_data={"n_probes": len(results)}) + + +def trace_analysis(tracer: Any, cycle: int, report: Any, *, duration_sec: "float | None") -> None: + """One M2 span with the judge exchange and an effect score per signal.""" + stats_tool = getattr(report, "stats_tool", None) + figures = getattr(report, "figures", None) + llm_prompt, llm_raw = getattr(report, "llm_prompt", None), getattr(report, "llm_raw", None) + stats_results = getattr(report, "stats_results", None) + conclusion = getattr(report, "conclusion", None) + m2_span = tracer.start_span( + name=f"M2: Screening & Confirmatory Signals (Cycle {cycle})", stage="M2", + input_data={"severity": report.severity, "n_findings": len(report.findings)}, + metadata={"duration_sec": duration_sec, "stats_tool": stats_tool, + "artifacts": {"figures": [str(f) for f in (figures or [])]}}, + ) + if llm_prompt or llm_raw: + tracer.log_generation( + name="M2 Statistical Screening Analysis", model="judge", + prompt=llm_prompt or "", completion=llm_raw or "", span_id=m2_span, + ) + for s in (stats_results or []): + s_dict = s.to_dict() if hasattr(s, "to_dict") else (s if isinstance(s, dict) else {}) + sig_name = s_dict.get("config", {}).get("signal") or s_dict.get("tool") or "signal" + eff = s_dict.get("effect") + if eff is not None: + tracer.log_score( + name=f"m2_effect_{sig_name}", value=float(eff), + comment=f"p={s_dict.get('p_value')}", span_id=m2_span, + ) + tracer.end_span(m2_span, output_data={"conclusion": conclusion or ""}) + + +def trace_explore( + tracer: Any, cycle: int, report: Any, entry: dict[str, Any], *, + ok: bool, out_dir: Any, rendered: list[str], duration_sec: "float | None", +) -> None: + """One span for the explore step with the coder agent's outputs.""" + exp_span = tracer.start_span( + name=f"Explore: Free-form EDA (Cycle {cycle})", stage="EXPLORE", + input_data={"ok": ok, "attempts": entry.get("attempts", 0)}, + metadata={"duration_sec": duration_sec, "artifacts": { + "out_dir": str(out_dir) if out_dir is not None else None, + "report_path": entry.get("report_path"), "figures": rendered, + }}, + ) + if report is not None: + for i, raw in enumerate(getattr(report, "raw_outputs", None) or []): + tracer.log_generation( + name=f"Explore Coder Agent (attempt {i + 1})", model="coder_agent", + prompt=None, completion=str(raw), span_id=exp_span, + ) + if getattr(report, "code", None): + tracer.log_generation( + name="Explore Analysis Code (analysis.py)", model="coder_agent", + prompt=None, completion=str(report.code), span_id=exp_span, + ) + tracer.end_span(exp_span, output_data={ + "n_observations": entry.get("n_observations", 0), + "n_candidate_signals": entry.get("n_candidate_signals", 0), + }) + + +def trace_diagnosis( + tracer: Any, cycle: int, diag: Any, entry: dict[str, Any], *, duration_sec: "float | None", +) -> None: + """One M3 span with the diagnosis exchange and the adversarial review.""" + m3_prompt = getattr(diag, "prompt", None) or "" + review_prompt = getattr(diag, "review_prompt", None) or "" + review_raw = getattr(diag, "review_raw", None) or "" + review_decisions = list(getattr(diag, "review_decisions", None) or []) + proposed = list(getattr(diag, "proposed_hypotheses", None) or []) + m3_span = tracer.start_span( + name=f"M3: Root-Cause Diagnosis (Cycle {cycle})", stage="M3", + input_data={"model_name": diag.model_name, "n_hypotheses": len(diag.hypotheses)}, + metadata={"duration_sec": duration_sec}, + ) + tracer.log_generation( + name="AI Doctor Diagnostician", + model=str(tracer.trace_metadata.get("judge") or "diagnosis_judge"), + prompt=m3_prompt, completion=diag.raw_judge_output or "", span_id=m3_span, + metadata={"hypotheses": [h.statement for h in diag.hypotheses]}, + ) + if review_prompt or review_raw: + tracer.log_generation( + name="M3 Adversarial Evidence Review", + model=str(tracer.trace_metadata.get("judge") or "diagnosis_judge"), + prompt=review_prompt, completion=review_raw, span_id=m3_span, + metadata={"decisions": review_decisions}, + ) + tracer.end_span(m3_span, output_data={ + "n_hypotheses": len(diag.hypotheses), + "n_proposed": len(proposed) or len(diag.hypotheses), + "review": entry.get("review"), + }) + + +def trace_surgery( + tracer: Any, hypothesis: Any, iv: Any, *, is_m4: bool, judge_prompt: "str | None", judge_raw: "str | None", +) -> None: + """One span per verdict (M4) or intervention (M5) with its confidence score.""" + stage_title = "M4 Adjudication" if is_m4 else "M5 Intervention" + surg_span = tracer.start_span( + name=f"{stage_title}: {hypothesis.statement[:60]}", + stage="M4" if is_m4 else "M5_SURGERY", + input_data={"hypothesis": hypothesis.statement, "failure_mode": hypothesis.predicted_failure_mode}, + metadata={"status": iv.status.value, "fixed": iv.fixed, "confidence_score": iv.confidence_score}, + ) + if judge_prompt or judge_raw: + tracer.log_generation( + name=f"{stage_title}: Protocol Consistency Judge", model="judge", + prompt=judge_prompt or "", completion=judge_raw or "", span_id=surg_span, + ) + if iv.confidence_score is not None: + tracer.log_score( + name="adjudication_confidence", value=float(iv.confidence_score), + comment=f"status={iv.status.value}, fixed={iv.fixed}", span_id=surg_span, + ) + tracer.end_span(surg_span, output_data={"evidence": iv.evidence or {}}) + + +def trace_experiment( + tracer: Any, hypothesis: Any, exp: dict[str, Any], entry: dict[str, Any], *, stage: str, module: str, +) -> None: + """One span for an experiment the agent wrote and ran.""" + exp_span = tracer.start_span( + name=f"{stage}: Experiment — {hypothesis.statement[:60]}", + stage=f"{stage}_EXPERIMENT", + input_data={"hypothesis": hypothesis.statement, "failure_mode": hypothesis.predicted_failure_mode}, + metadata={"provider": exp.get("provider"), "returncode": exp.get("returncode")}, + ) + cli_raw = exp.get("cli_raw_output") + if cli_raw: + tracer.log_generation( + name=f"{module.upper()} Coder Agent", model=str(exp.get("provider") or "coder_agent"), + prompt=None, completion=str(cli_raw), span_id=exp_span, + ) + vlog = exp.get("validation_log") + if vlog: + tracer.log_generation( + name=f"{module.upper()} Validation Log", model=str(exp.get("provider") or "coder_agent"), + prompt=None, completion="\n".join(str(x) for x in vlog), span_id=exp_span, + ) + tracer.end_span(exp_span, output_data={ + "status": entry.get("status"), "fixed": entry.get("fixed"), "verdict": entry.get("verdict"), + }) + + +def trace_fix(tracer: Any, outcome: dict[str, Any], best: dict[str, Any]) -> None: + """One span for the fix step with the winner's gain and patch.""" + fix_span = tracer.start_span( + name="M5: Targeted Repair & Confirmation", stage="M5_FIX", + input_data={"candidates_evaluated": len(outcome.get("attempted", []))}, + ) + if best.get("effect") is not None: + tracer.log_score( + name="repair_net_accuracy_gain", value=float(best.get("effect", 0.0)), + comment=f"cured={best.get('n_fixed')}, broken={best.get('n_broken')}", + span_id=fix_span, + ) + if (best.get("payload") or {}).get("prompt_template"): + tracer.log_generation( + name="Winning Repair Patch", model="evalrx_repair", + prompt="Repair Candidate Search", + completion=best["payload"]["prompt_template"], span_id=fix_span, + ) + tracer.end_span(fix_span, output_data={"selected": best.get("name")}) + + +def trace_agent_decision( + tracer: Any, step: int, *, action: str, params: "dict[str, Any] | None", rationale: str, valid: bool, + repair_attempts: int, fallback_used: bool, judge_prompt: "str | None", judge_raw: "str | None", +) -> None: + """One span per decision the agentic loop's judge made.""" + decision_span = tracer.start_span( + name=f"Agent Decision: step {step}", stage="AGENT_DECISION", + input_data={"action": action, "params": params or {}}, + metadata={"valid": valid, "repair_attempts": repair_attempts, "fallback_used": fallback_used}, + ) + if judge_prompt or judge_raw: + tracer.log_generation( + name="Agent Decision Judge", model="judge", + prompt=judge_prompt or "", completion=judge_raw or "", span_id=decision_span, + ) + tracer.end_span(decision_span, output_data={"action": action, "rationale": rationale}) + + +def trace_stage_skipped(tracer: Any, stage: str, reason_code: str, detail: str) -> None: + """A zero-length span marking a stage the run skipped.""" + span = tracer.start_span( + name=f"{stage}: skipped", stage=stage, + input_data={"reason_code": reason_code}, metadata={"detail": detail}, + ) + tracer.end_span(span, output_data={"reason_code": reason_code}, status="skipped") + + +def trace_tool_codegen( + tracer: Any, *, module: str, name: str, need: str, source: str, ok: bool, error: str, + prompt: str, raw_output: str, raw_stream: str, code: str, +) -> None: + """One span per tool the agent wrote.""" + cg_span = tracer.start_span( + name=f"Tool Codegen: {module}/{name}", stage=f"CODEGEN_{module}", + input_data={"need": need, "source": source}, + metadata={"ok": ok, "error": error or None}, + ) + if prompt or raw_output: + tracer.log_generation( + name=f"Tool Synthesis: {name}", model=source, + prompt=prompt or "", completion=raw_stream or raw_output or code, span_id=cg_span, + ) + tracer.end_span(cg_span, output_data={"ok": ok, "code_chars": len(code or "")}) diff --git a/evalrx/eval_agent/run_logger.py b/evalrx/eval_agent/run_logger.py new file mode 100644 index 00000000..046857aa --- /dev/null +++ b/evalrx/eval_agent/run_logger.py @@ -0,0 +1,1041 @@ +"""RunLogger — the run log every diagnosis loop writes through. + +One JSON document per pipeline stage (``M1/log.json`` .. ``M5/log.json``) plus +``run.json`` for what is not stage content; every event of one kind is one +array in one file; everything text-shaped is a string value in the JSON, and +only binary media (figures, tensors, audio) is a separate file. See +``RUN_LOGGER.md`` beside this file for the layout and the reasoning. + +This module is the class and what only it can do: route an event to its +document, stamp it, and write the document atomically. What an event records +is built in :mod:`run_log_entries`, what lands on disk beside the JSON is in +:mod:`run_log_files`, and the Langfuse mirror of each event is in +:mod:`run_log_tracing`. +""" + +from __future__ import annotations + +import getpass +import json +import os +import re +import tempfile +import threading +import uuid +import warnings +from collections.abc import Sized +from datetime import datetime, timezone +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from evalrx.eval_agent.log_schema import RUN_LOG_SCHEMA_VERSION +from evalrx.eval_agent.run_log_entries import ( + analysis_entry, + diagnose_report_entry, + diagnosis_entry, + experiment_entry, + explore_entry, + json_safe, + loop_end_entry, + probe_entry, + surgery_entry, +) +from evalrx.eval_agent.run_log_files import ( + artifact_to_numpy, + atomic_write_json, + inline_workspace, + save_artifact_figure, +) +from evalrx.eval_agent.run_log_tracing import ( + trace_agent_decision, + trace_analysis, + trace_diagnosis, + trace_experiment, + trace_explore, + trace_fix, + trace_probe, + trace_run_start, + trace_stage_skipped, + trace_surgery, + trace_tool_codegen, +) + +if TYPE_CHECKING: + from evalrx.analysis.analysis_module import AnalysisReport + from evalrx.core.result import Result + from evalrx.eval_agent.hypothesis import Hypothesis + from evalrx.eval_agent.loop_reports import AutoDiagnoseReport + from evalrx.eval_agent.stages.diagnosis import DiagnosisResult + from evalrx.eval_agent.stages.surgery import InterventionResult + +_STAGES = ("M1", "M2", "M3", "M4", "M5") + +#: A tag string not matching this falls back to _STAGE_ALIASES, then to the +#: run-level "unrouted" bucket (never silently dropped — see _resolve_stage). +_STAGE_RE = re.compile(r"m([1-5])", re.IGNORECASE) + +#: Tags used somewhere in the codebase that carry no "m" substring at all +#: (checked against every literal `module=`/`stage=` value passed to a +#: log_* method as of this writing — see RUN_LOGGER.md's "routing" table). +_STAGE_ALIASES: dict[str, str] = { + "fix_pipeline": "M5", + "fix": "M5", + "explore": "M2", +} + +def _resolve_stage(tag: "str | None") -> "str | None": + """"m1_probe" / "M4_SURGERY" / "codegen_m2_stats" / "fix_pipeline" -> "M1".."M5". + + Returns ``None`` when *tag* matches nothing — the caller must not drop + the event in that case; route it to the run-level "unrouted" bucket + instead (see ``RunLogger._route``). A tag is never assumed unroutable + without trying both the regex AND the alias table. + """ + if not tag: + return None + m = _STAGE_RE.search(tag) + if m: + return f"M{m.group(1)}" + return _STAGE_ALIASES.get(tag.strip().lower()) + + +def _outbox_dir() -> Path: + """Per-user temp directory for the Langfuse delivery queue. + + A single shared ``/tmp/evalrx-outbox`` breaks on multi-user hosts: the + first user to create it owns it, and everyone else gets "unable to open + database file". + """ + try: + user = getpass.getuser() + except Exception: # noqa: BLE001 - no login name (e.g. bare containers) + user = str(os.getuid()) if hasattr(os, "getuid") else "default" + return Path(tempfile.gettempdir()) / f"evalrx-outbox-{user}" + + +class _EventLine: + """Renders one plain one-line console summary per event, for ``verbose=True``. + + Intentionally simple — file layout was this module's ask, not console UX; + see the design doc. + """ + + @staticmethod + def line(stage: "str | None", event: str, payload: "dict[str, Any]") -> str: + where = f"[{stage}]" if stage else "[run]" + cycle = payload.get("cycle") + tail = f" cycle={cycle}" if cycle is not None else "" + return f"{where} {event}{tail}" + + +class RunLogger: + """A tidy, from-scratch M1..M5 logger. See the module docstring + design doc. + + Args: + run_dir: Directory to write into. Created if missing. Defaults to + ``runs_v2//`` relative to cwd. + verbose: Print a one-line raw summary of every event to stdout + (``[M1] probe cycle=0``). Ignored when *narrate* is set. + narrate: Print live, aligned M1-M5 narration instead — the same + visual style as ``evalrx explore``'s terminal output (see + :mod:`evalrx.eval_agent.narration.LoopNarrator`), built + from real per-stage counts instead of a raw event dump. + trace_id: Ties every event to one Langfuse trace; auto-generated if + omitted. + observability_mode: Forwarded to :class:`DiagnosticTracer` unchanged. + + Layout written under *run_dir*:: + + run.json run-wide: run_start, cases, report_published, + loop_end, agent_decisions, agent_tool_calls, + unrouted (see _resolve_stage) + M1/log.json probe, model_calls, tool_codegen, tool_registry, + stage_skipped — all M1-tagged events + M2/log.json analysis, explore, ... + M3/log.json diagnosis, ... + M4/log.json surgery (hypothesis-verification kind), ... + M5/log.json surgery (intervention kind), experiment, fix, ... + M*/artifacts/ binary media for that stage only (rule 4's exception) + media/ case-level baseline media (images/audio referenced + by FailureCase.inputs) + artifacts/ run-global named JSON (save_artifact_json) + """ + + def __init__( + self, + run_dir: "str | Path | None" = None, + *, + verbose: bool = False, + narrate: bool = False, + trace_id: "str | None" = None, + observability_mode: "str | None" = None, + context: "Any | None" = None, + ) -> None: + if run_dir is None: + run_dir = Path("runs_v2") / datetime.now().strftime("%Y%m%d_%H%M%S") + self.run_dir = Path(run_dir) + self.run_dir.mkdir(parents=True, exist_ok=True) + self.run_json_path = self.run_dir / "run.json" + + self.trace_id: str = trace_id or str(uuid.uuid4()) + self.current_cycle: int = -1 + # Live M1-M5 terminal narration (see evalrx.eval_agent.narration) -- + # opt-in, takes over from the plain `verbose` one-liner below rather + # than stacking with it, so a run never prints each event twice. + self._narrator = None + if narrate: + from evalrx.eval_agent.narration import LoopNarrator + + self._narrator = LoopNarrator() + self.verbose = verbose + self._context = context + self._closed = False + + # One in-memory doc per stage + one run-level doc. Every log_* method + # appends to the relevant bucket(s), then atomically rewrites exactly + # the doc(s) it touched — see atomic_write_json. + self._lock = threading.RLock() + self._event_seq = 0 + self._validate_events = bool(os.environ.get("EVALRX_VALIDATE_LOG")) + self._event_validator: Any = None + self._run_doc: dict[str, Any] = { + "trace_id": self.trace_id, + "run_start": None, + "cases": [], + "report_published": [], + "diagnose_reports": [], + "manifest": None, + "loop_end": [], + "run_end": [], + "agent_decisions": [], + "agent_tool_calls": [], + "unrouted": [], + } + self._stage_docs: dict[str, dict[str, Any]] = {s: {} for s in _STAGES} + self._logged_case_ids: set[str] = set() + self._model_call_seq = 0 + self._codegen_seq = 0 + # See log_model_call / log_probe: calls are recorded immediately into + # M1's doc AND buffered here so log_probe can replay them into + # Langfuse nested under the right probe span once it exists. + self._pending_model_calls: "dict[int, list[dict[str, Any]]]" = {} + + from evalrx.observability.tracer import DiagnosticTracer + # The SQLite delivery queue is runtime state, not part of the tidy run + # artifact. Keep it outside the run tree; langfuse_trace.json remains + # the durable, portable JSON trace bundled with the run. + self._outbox_path = _outbox_dir() / f"{self.trace_id}.sqlite3" + self.tracer = DiagnosticTracer( + run_dir=self.run_dir, mode=observability_mode, auto_sync=True, + outbox_path=self._outbox_path, + ) + self.tracer.trace_id = self.trace_id + + self._flush_run() + + # ------------------------------------------------------------------ + # Internal: doc access, routing, durability + # ------------------------------------------------------------------ + + def _stage_dir(self, stage: str) -> Path: + d = self.run_dir / stage + d.mkdir(parents=True, exist_ok=True) + return d + + def _stage_artifacts_dir(self, stage: str) -> Path: + d = self._stage_dir(stage) / "artifacts" + d.mkdir(parents=True, exist_ok=True) + return d + + def _flush_run(self) -> None: + atomic_write_json(self.run_json_path, self._run_doc) + + def _flush_stage(self, stage: str) -> None: + atomic_write_json(self._stage_dir(stage) / "log.json", self._stage_docs[stage]) + + def _bucket(self, stage: str, key: str) -> list: + return self._stage_docs[stage].setdefault(key, []) + + def _stamp_event(self, key: str, record: dict[str, Any], stage: str) -> None: + """Assign durable event identity under ``_lock``; no telemetry side effects.""" + event = { + "cases": "case_record", "model_calls": "model_call", + "diagnose_reports": "diagnose_report", "agent_decisions": "agent_decision", + "agent_tool_calls": "agent_tool", + }.get(key, key) + self._event_seq += 1 + cycle = record.get("cycle", -1) + span = { + "run_start": "run_start", "probe": f"c{cycle}.m1", + "analysis": f"c{cycle}.m2", "diagnosis": f"c{cycle}.m3", + "explore": f"c{cycle}.explore", "surgery": f"c{cycle}.{stage.lower()}", + "fix": "fix", "agent_decision": f"s{record.get('step')}.decision", + "agent_tool": f"s{record.get('step')}.tool", + "stage_skipped": f"{stage.lower()}.skipped", + }.get(event, f"{stage.lower()}.{event}.{self._event_seq}") + record.update(event=event, schema_version=RUN_LOG_SCHEMA_VERSION, + trace_id=self.trace_id, event_seq=self._event_seq, + stage=stage, span_id=span) + record.setdefault("ts", self._ts()) + if self._validate_events: + try: + from evalrx.eval_agent.log_schema import _validator, build_schema + + if self._event_validator is None: + self._event_validator = _validator(build_schema()) + self._event_validator.validate(record) + except ImportError: + pass + except Exception as exc: # warn-only + warnings.warn(f"RunLogger: event {event!r} violates log schema: {exc}") + + def _append_stage(self, tag: "str | None", key: str, record: "dict[str, Any]") -> str: + """Route *record* by *tag* into the right stage bucket; flush; return the stage.""" + stage = _resolve_stage(tag) + with self._lock: + if stage is None: + warnings.warn( + f"RunLogger: could not route event {key!r} (tag={tag!r}) to a " + "stage — filed under run.json['unrouted'] instead of being lost.", + stacklevel=3, + ) + record = {"key": key, "tag": tag, **record} + self._stamp_event("unrouted", record, "RUN") + self._run_doc["unrouted"].append(record) + self._flush_run() + return "unrouted" + self._stamp_event(key, record, stage) + self._bucket(stage, key).append(record) + self._flush_stage(stage) + if self._narrator is not None: + self._narrator.on_event(stage, key, record) + elif self.verbose: + print(_EventLine.line(stage, key, record)) + return stage + + def _append_run(self, key: str, record: "dict[str, Any]") -> None: + """Append *record* to the (always list-valued) run.json bucket *key*. + + ``run_start`` is the one run.json field that isn't a list — it's set + directly by ``log_run_start``, never through here. + """ + with self._lock: + self._stamp_event(key, record, "RUN") + self._run_doc[key].append(record) + self._flush_run() + if self._narrator is not None: + self._narrator.on_run_event(key, record) + elif self.verbose: + print(_EventLine.line(None, key, record)) + + @property + def managed_json_paths(self) -> "tuple[Path, ...]": + """Atomic JSON documents that may be rewritten while quarantine runs.""" + return (self.run_json_path, *(self.run_dir / s / "log.json" for s in _STAGES)) + + @staticmethod + def _ts() -> str: + return datetime.now(timezone.utc).isoformat(timespec="microseconds") + + def _save_media(self, stage: str, stem: str, artifact: Any) -> "str | None": + """Save a numeric artifact (tensor/array) + a rendered figure, if any. + + Writes under this stage's ``artifacts/`` dir. Returns the ``.npy`` + path (run-relative) or ``None`` when *artifact* isn't a recognised + numeric type. + """ + try: + import numpy as np + + arr = artifact_to_numpy(artifact) + if arr is not None: + art_dir = self._stage_artifacts_dir(stage) + path = art_dir / f"{stem}.npy" + np.save(path, arr) + save_artifact_figure(art_dir, stem, arr) + return str(path.relative_to(self.run_dir)) + return None + except Exception as exc: # noqa: BLE001 + warnings.warn(f"RunLogger: could not save artifact {stem!r}: {exc}") + return None + + def _save_case_media(self, path: Path) -> "str | None": + """Copy external case media into ``media/`` (content-hash-deduped); return rel path.""" + import hashlib + import shutil + + media_dir = self.run_dir / "media" + media_dir.mkdir(parents=True, exist_ok=True) + digest = hashlib.sha256() + try: + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + except OSError: + return None + copied = media_dir / f"{digest.hexdigest()[:16]}_{path.name}" + if not copied.exists(): + shutil.copy2(path, copied) + return str(copied.relative_to(self.run_dir)) + + def _portable_path(self, value: "str | Path") -> str: + path = Path(value) + try: + return str(path.resolve().relative_to(self.run_dir.resolve())) + except (OSError, ValueError): + return str(value) + + # ------------------------------------------------------------------ + # Run provenance + # ------------------------------------------------------------------ + + def log_run_start(self, config: "dict[str, Any] | None" = None) -> None: + import platform + + entry: dict[str, Any] = {"ts": self._ts(), "trace_id": self.trace_id} + if config: + entry.update(config) + entry.setdefault("python_version", platform.python_version()) + try: + from evalrx import __version__ as _ver # type: ignore + entry.setdefault("evalrx_version", _ver) + except Exception: # noqa: BLE001 + pass + commit = self._git_commit() + if commit: + entry.setdefault("git_commit", commit) + with self._lock: + self._stamp_event("run_start", entry, "RUN") + self._run_doc["run_start"] = entry + self._flush_run() + if self._narrator is not None: + self._narrator.on_run_start(entry) + elif self.verbose: + print(_EventLine.line(None, "run_start", entry)) + + trace_run_start(self.tracer, entry) + + @staticmethod + def _git_commit() -> "str | None": + import subprocess + + try: + out = subprocess.run( + ["git", "rev-parse", "--short", "HEAD"], + capture_output=True, text=True, timeout=3, check=False, + ) + commit = out.stdout.strip() + if commit: + return commit + except Exception: # noqa: BLE001 + pass + return os.environ.get("EVALRX_GIT_COMMIT") or None + + def log_cases(self, cases: "Any", *, split: "str | None" = None) -> None: + """Persist complete case I/O; media is copied into ``media/`` (rule 4's exception). + + ``split`` is the partition the loop assigned (``explore`` / ``confirm`` / + ``test``), recorded on the row so a report can group the cases the way + the run actually used them. + """ + for case in cases: + case_id = str(getattr(case, "id", "") or "") + if not case_id or case_id in self._logged_case_ids: + continue + if hasattr(case, "to_dict"): + payload = case.to_dict() + elif isinstance(case, dict): + payload = dict(case) + else: + payload = {"id": case_id, "value": str(case)} + payload = json.loads(json.dumps(payload, ensure_ascii=False, default=str)) + media_paths: list[str] = [] + inputs = getattr(case, "inputs", None) + for kind in ("image", "audio", "video"): + value = getattr(inputs, kind, None) + if not isinstance(value, (str, Path)): + continue + path = Path(value) + if not path.is_absolute(): + run_relative = self.run_dir / path + path = run_relative if run_relative.is_file() else path.resolve() + if not path.is_file(): + continue + saved = self._save_case_media(path) + if saved: + media_paths.append(saved) + record: dict[str, Any] = { + "ts": self._ts(), "case_id": case_id, "case": payload, "media_paths": media_paths, + } + if split: + record["split"] = str(split) + self._append_run("cases", record) + self._logged_case_ids.add(case_id) + + def log_report_published(self, envelope: "dict[str, Any]") -> None: + generated = envelope.get("generated_by") or {} + self._append_run("report_published", { + "ts": self._ts(), + "report_schema_version": int(envelope.get("schema_version") or 1), + "catalog_version": str(envelope.get("catalog_version") or ""), + "json_render_version": str(envelope.get("json_render_version") or ""), + "source_event_seq": int(envelope.get("source_event_seq") or 0), + "sha256": str(envelope.get("sha256") or ""), + "generated_by": generated, + "report_paths": ["report/report_data.json", "report/report_spec.json"], + }) + + def log_diagnose_report( + self, + report: Any, + cases: "Sized", + *, + discovery: "list[dict[str, Any]] | None" = None, + ) -> None: + """Inline the standard post-diagnosis report into ``run.json`` as one + detailed machine-readable record; a UI renders prose from this data + rather than reading separate JSON/Markdown siblings.""" + self._append_run("diagnose_reports", { + "ts": self._ts(), **diagnose_report_entry(report, cases, discovery), + }) + + def log_manifest(self, *, run_id: str, config: "dict[str, Any]") -> None: + """Record final run provenance and a compact file index in ``run.json``.""" + files = [ + str(path.relative_to(self.run_dir)) + for path in sorted(self.run_dir.rglob("*")) + if path.is_file() and not path.name.startswith(".") + ] + with self._lock: + self._run_doc["manifest"] = { + "ts": self._ts(), "run_id": run_id, "config": dict(config), "files": files, + } + self._flush_run() + + def log_runtime_snapshot(self, root: Path) -> None: + """Preserve execution files, including discarded trials, before cleanup.""" + snapshot = inline_workspace( + root, self._stage_artifacts_dir("M5"), run_dir=self.run_dir, + max_bytes=None, preserve_all=True, + ) + with self._lock: + self._run_doc["runtime_snapshot"] = snapshot + self._flush_run() + + def log_model_exchange( + self, + stage: str, + *, + role: str, + operation: str, + inputs: Any, + output: Any = None, + error: "str | None" = None, + duration_sec: "float | None" = None, + metadata: "dict[str, Any] | None" = None, + cycle: "int | None" = None, + ) -> None: + """Persist one exact model/agent input-output exchange in its stage.""" + entry: dict[str, Any] = { + "ts": self._ts(), + "cycle": self.current_cycle if cycle is None else cycle, + "role": role, + "operation": operation, "inputs": json_safe(inputs), "output": json_safe(output), + "error": error, "metadata": json_safe(dict(metadata or {})), + } + if duration_sec is not None: + entry["duration_sec"] = round(duration_sec, 4) + self._append_stage(stage, "model_calls", entry) + + def save_artifact_json(self, stem: str, obj: Any) -> "str | None": + """Write *obj* as JSON under the run-global ``artifacts/`` dir; return rel path.""" + try: + d = self.run_dir / "artifacts" + d.mkdir(parents=True, exist_ok=True) + path = d / stem + path.write_text(json.dumps(obj, indent=2, default=str), encoding="utf-8") + return str(path.relative_to(self.run_dir)) + except Exception as exc: # noqa: BLE001 + warnings.warn(f"RunLogger: could not save artifact {stem!r}: {exc}") + return None + + # ------------------------------------------------------------------ + # M1 — target-model calls (see model_instrumentation.InstrumentedModel) + # ------------------------------------------------------------------ + + def log_model_call( + self, + *, + cycle: int, + analyzer: str, + call_index: int, + method: str, + inputs: Any, + kwargs: "dict[str, Any]", + output: Any, + duration_sec: float, + error: "str | None", + case_id: "str | None" = None, + batch_case_ids: "list[str] | None" = None, + n_batch_cases: "int | None" = None, + ) -> None: + record: dict[str, Any] = { + "ts": self._ts(), "cycle": cycle, "analyzer": analyzer, + "call_index": call_index, "method": method, + "case_id": case_id, "batch_case_ids": batch_case_ids or [], + "n_batch_cases": n_batch_cases if n_batch_cases is not None else len(batch_case_ids or []), + "inputs": inputs, "kwargs": kwargs, "output": output, + "duration_sec": round(duration_sec, 4), + } + if error is not None: + record["error"] = error + with self._lock: + self._model_call_seq += 1 + record["seq"] = self._model_call_seq + self._stamp_event("model_calls", record, "M1") + self._bucket("M1", "model_calls").append(record) + self._flush_stage("M1") + self._pending_model_calls.setdefault(cycle, []).append(record) + if self.verbose: + print(_EventLine.line("M1", "model_call", record)) + + # ------------------------------------------------------------------ + # M1 — probe + # ------------------------------------------------------------------ + + def log_probe( + self, + cycle: int, + results: "dict[str, Result]", + schema: "Any | None" = None, + *, + cases: "Any | None" = None, + judge_prompt: "str | None" = None, + judge_raw: "str | None" = None, + duration_sec: "float | None" = None, + failed_analyzers: "dict[str, str] | None" = None, + ) -> "list[Path]": + """M1: one entry in M1/log.json's "probe" list. ``artifact_paths``/ + results are inlined here instead of living in separate + ``.result.json`` files.""" + artifact_paths: dict[str, str] = {} + overlay_pngs: list[Path] = [] + result_docs: dict[str, Any] = {} + inline_artifacts: dict[str, Any] = {} + for name, result in results.items(): + for art_name, artifact in getattr(result, "artifacts", {}).items(): + stem = f"c{cycle}_{name}_{art_name}" + rel = self._save_media("M1", stem, artifact) + if rel is not None: + artifact_paths[f"{name}/{art_name}"] = rel + elif isinstance(artifact, (dict, list)): + inline_artifacts[f"{name}/{art_name}"] = json.loads( + json.dumps(artifact, ensure_ascii=False, default=str) + ) + image_overlays = getattr(result, "image_overlays", None) + if image_overlays is not None: + try: + overlay_pngs.extend( + image_overlays(self._stage_artifacts_dir("M1"), f"c{cycle}_{name}") + ) + except Exception as exc: # noqa: BLE001 - viz must never break the probe + warnings.warn(f"RunLogger: image_overlays failed for {name}: {exc}") + to_dict = getattr(result, "to_dict", None) + if callable(to_dict): + try: + doc = to_dict() + summary = getattr(result, "summary", None) + if callable(summary): + doc["summary"] = summary() + result_docs[name] = doc + except Exception as exc: # noqa: BLE001 + warnings.warn(f"RunLogger: could not serialise result {name!r}: {exc}") + + with self._lock: + pending_calls = [c for bucket in self._pending_model_calls.values() for c in bucket] + self._pending_model_calls.clear() + + entry = {"ts": self._ts(), **probe_entry( + cycle, results, result_docs=result_docs, artifact_paths=artifact_paths, + inline_artifacts=inline_artifacts, n_model_calls=len(pending_calls), cases=cases, schema=schema, + failed_analyzers=failed_analyzers, judge_prompt=judge_prompt, judge_raw=judge_raw, + duration_sec=duration_sec, + )} + self._append_stage("M1", "probe", entry) + if judge_prompt or judge_raw: + self.log_model_exchange( + "M1", role="analyzer_selection_judge", operation="generate", + inputs=judge_prompt or "", output=judge_raw or "", cycle=cycle, + duration_sec=duration_sec, + ) + + png_figures: list[Path] = list(overlay_pngs) + for rel_npy in artifact_paths.values(): + if not rel_npy.endswith(".npy"): + continue + png = self.run_dir / (rel_npy[: -len(".npy")] + ".png") + if png.exists(): + png_figures.append(png) + + trace_probe( + self.tracer, cycle, results, entry, artifact_paths=artifact_paths, figures=png_figures, + judge_prompt=judge_prompt, judge_raw=judge_raw, duration_sec=duration_sec, + model_calls=pending_calls, + ) + return png_figures + + # ------------------------------------------------------------------ + # M2 — analysis + explore + # ------------------------------------------------------------------ + + def log_analysis( + self, cycle: int, report: "AnalysisReport", *, duration_sec: "float | None" = None, + ) -> None: + entry = {"ts": self._ts(), **analysis_entry( + cycle, report, portable_path=self._portable_path, duration_sec=duration_sec, + )} + self._append_stage("M2", "analysis", entry) + llm_prompt, llm_raw = entry.get("judge_prompt"), entry.get("judge_response") + if llm_prompt or llm_raw: + self.log_model_exchange( + "M2", role="statistics_judge", operation="generate", + inputs=llm_prompt or "", output=llm_raw or "", cycle=cycle, + duration_sec=duration_sec, + ) + + trace_analysis(self.tracer, cycle, report, duration_sec=duration_sec) + + def log_explore( + self, cycle: int, report: "Any | None", *, + out_dir: "Path | str | None" = None, duration_sec: "float | None" = None, + ) -> None: + ok = bool(getattr(report, "ok", False)) if report is not None else False + charts = list(getattr(report, "charts", None) or []) if report is not None else [] + rendered = [ + str(c.get("figure_path")) for c in charts + if isinstance(c, dict) and c.get("figure_path") + ] + workspace = None + if out_dir is not None: + workspace = inline_workspace( + out_dir, self._stage_artifacts_dir("M2"), run_dir=self.run_dir, + ) + if workspace and workspace.get("media"): + rendered = [ + path for path in workspace["media"] + if Path(path).suffix.lower() in {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"} + ] + entry = {"ts": self._ts(), **explore_entry( + cycle, report, ok=ok, charts=charts, rendered=rendered, workspace=workspace, out_dir=out_dir, + duration_sec=duration_sec, + )} + self._append_stage("M2", "explore", entry) + for call in list(getattr(report, "model_calls", None) or []): + self.log_model_exchange( + "M2", + role=str(call.get("role") or "explore_coder"), + operation=str(call.get("operation") or "generate"), + inputs=call.get("inputs"), output=call.get("output"), + error=call.get("error"), duration_sec=call.get("duration_sec"), + metadata=dict(call.get("metadata") or {}), cycle=cycle, + ) + + trace_explore( + self.tracer, cycle, report, entry, ok=ok, out_dir=out_dir, rendered=rendered, + duration_sec=duration_sec, + ) + + # ------------------------------------------------------------------ + # M3 — diagnosis + # ------------------------------------------------------------------ + + def log_diagnosis( + self, cycle: int, diag: "DiagnosisResult", *, + duration_sec: "float | None" = None, explore_figures: "list[str] | None" = None, + ) -> None: + entry = {"ts": self._ts(), **diagnosis_entry( + cycle, diag, duration_sec=duration_sec, explore_figures=explore_figures, + )} + self._append_stage("M3", "diagnosis", entry) + m3_prompt = entry.get("judge_prompt", "") + critic_raw = entry.get("critic_raw_output", "") + review_prompt, review_raw = entry.get("review_prompt", ""), entry.get("review_response", "") + detailed_calls = list(getattr(diag, "model_calls", None) or []) + if detailed_calls: + for call in detailed_calls: + self.log_model_exchange( + "M3", + role=str(call.get("role") or "diagnosis_judge"), + operation=str(call.get("operation") or "generate"), + inputs=call.get("inputs"), output=call.get("output"), + error=call.get("error"), duration_sec=call.get("duration_sec"), + metadata=dict(call.get("metadata") or {}), cycle=cycle, + ) + else: + # Compatibility for DiagnosisResult values created by older callers. + if m3_prompt or diag.raw_judge_output: + self.log_model_exchange( + "M3", role="diagnosis_judge", operation="generate", + inputs=m3_prompt, output=diag.raw_judge_output or "", cycle=cycle, + duration_sec=duration_sec, + ) + if critic_raw or review_prompt or review_raw: + self.log_model_exchange( + "M3", role="hypothesis_critic", operation="generate", + inputs=entry.get("critic_prompt") or review_prompt, + output=critic_raw or review_raw, cycle=cycle, + ) + + trace_diagnosis(self.tracer, cycle, diag, entry, duration_sec=duration_sec) + + # ------------------------------------------------------------------ + # M4/M5 — hypothesis verification & intervention + # ------------------------------------------------------------------ + + def log_surgery( + self, cycle: int, hypothesis: "Hypothesis", iv: "InterventionResult", *, + validation_cases: "Any | None" = None, duration_sec: "float | None" = None, + judge_prompt: "str | None" = None, judge_raw: "str | None" = None, + ) -> None: + """M4 (hypothesis verification) or M5 (intervention) — split on + whether "m4_test_name" is present in ``iv.evidence``.""" + is_m4 = "m4_test_name" in (iv.evidence or {}) + stage = "M4" if is_m4 else "M5" + entry = {"ts": self._ts(), **surgery_entry( + cycle, hypothesis, iv, stage=stage, validation_cases=validation_cases, + judge_prompt=judge_prompt, judge_raw=judge_raw, duration_sec=duration_sec, + )} + self._append_stage(stage, "surgery", entry) + if judge_prompt or judge_raw: + self.log_model_exchange( + stage, role="protocol_consistency_judge", operation="generate", + inputs=judge_prompt or "", output=judge_raw or "", cycle=cycle, + duration_sec=duration_sec, + ) + + trace_surgery(self.tracer, hypothesis, iv, is_m4=is_m4, judge_prompt=judge_prompt, judge_raw=judge_raw) + + def log_experiment( + self, cycle: int, hypothesis: "Hypothesis", iv: "InterventionResult", *, + module: str = "m5", + ) -> None: + """The experiment the agent wrote and ran to test *hypothesis*. + + No separate ``experiments/``/``workspace/`` files: the generated + source (``exp["files"]``/``exp["code"]``), stdout/stderr, the coder + agent's raw narration, and the validation log are already plain + strings in *iv.experiment* and go straight into the entry as JSON + string values. + """ + exp = getattr(iv, "experiment", None) or {} + files = exp.get("files") or {} + if not files and exp.get("code"): + files = {"main.py": exp["code"]} + + # An "experiment" is always M4/M5-shaped content by definition, so it + # gets the same resolve-with-M5-floor treatment as its workspace + # media, rather than trusting `_append_stage`'s generic unroutable + # fallback (which would file a genuinely M5-ish record under + # run.json["unrouted"] if *module* is ever something the M1-M5 regex + # and alias table don't recognize). + stage = _resolve_stage(module) or "M5" + + workspace = None + workdir = exp.get("workdir") + if workdir: + workspace = inline_workspace( + workdir, self._stage_artifacts_dir(stage), run_dir=self.run_dir, + ) + + entry = {"ts": self._ts(), **experiment_entry( + cycle, hypothesis, iv, module=module, exp=exp, files=files, workspace=workspace, + )} + self._append_stage(stage, "experiment", entry) + for call in exp.get("model_calls") or []: + if isinstance(call, dict): + self.log_model_exchange( + stage, + role=str(call.get("role") or "experiment_writer"), + operation=str(call.get("operation") or "generate"), + inputs=call.get("inputs"), output=call.get("output"), + error=call.get("error"), duration_sec=call.get("duration_sec"), + metadata=call.get("metadata"), + ) + + trace_experiment(self.tracer, hypothesis, exp, entry, stage=stage, module=module) + + def log_fix(self, outcome: "Any") -> None: + """Post-loop fix module: the tiered repair attempt + recommendation. + + Per-case outputs are NOT popped out to a sibling ``outputs.jsonl`` — + they stay inline in ``M5/log.json`` under each candidate's own + ``"outputs"`` key. Fewer files was the whole point; a bulkier single + JSON is the intended trade for that. + """ + d = json.loads(json.dumps(outcome.to_dict(), ensure_ascii=False, default=str)) + for attempt in [*(d.get("attempted") or []), *(d.get("selection_attempted") or [])]: + trial_root = attempt.get("trial_root") + if trial_root: + attempt["workspace_snapshot"] = inline_workspace( + trial_root, self._stage_artifacts_dir("M5"), + run_dir=self.run_dir, max_bytes=None, preserve_all=True, + ) + best_ref = d.get("best") + if isinstance(best_ref, dict): + best = best_ref + elif isinstance(best_ref, str): + best = next((a for a in d.get("attempted") or [] if a.get("name") == best_ref), {}) + else: + best = {} + entry: dict[str, Any] = {"ts": self._ts(), "cycle": -1, "module": "fix"} + entry.update(d) + entry["best"] = best + self._append_stage("M5", "fix", entry) + + trace_fix(self.tracer, d, best) + + # ------------------------------------------------------------------ + # JudgePolicy dispatch layer — run-level, not stage content + # ------------------------------------------------------------------ + + def log_agent_decision( + self, step: int, *, action: str, params: "dict[str, Any] | None" = None, + rationale: str = "", valid: bool = True, repair_attempts: int = 0, + fallback_used: bool = False, judge_prompt: "str | None" = None, + judge_raw: "str | None" = None, duration_sec: "float | None" = None, + judge_calls: "list[dict[str, Any]] | None" = None, + ) -> None: + entry: dict[str, Any] = { + "ts": self._ts(), "step": step, "action": action, "params": params or {}, + "rationale": rationale, "valid": valid, "repair_attempts": repair_attempts, + "fallback_used": fallback_used, + } + if judge_prompt: + entry["judge_prompt"] = judge_prompt + if judge_raw: + entry["judge_response"] = judge_raw + if judge_calls: + entry["model_calls"] = json.loads(json.dumps(judge_calls, default=str)) + if duration_sec is not None: + entry["duration_sec"] = round(duration_sec, 3) + self._append_run("agent_decisions", entry) + + trace_agent_decision( + self.tracer, step, action=action, params=params, rationale=rationale, valid=valid, + repair_attempts=repair_attempts, fallback_used=fallback_used, + judge_prompt=judge_prompt, judge_raw=judge_raw, + ) + + def log_agent_tool( + self, step: int, *, tool: str, ok: bool, summary: str = "", + error: "str | None" = None, duration_sec: "float | None" = None, + ) -> None: + entry: dict[str, Any] = { + "ts": self._ts(), "step": step, "tool": tool, "ok": ok, "summary": summary, + } + if error is not None: + entry["error"] = error + if duration_sec is not None: + entry["duration_sec"] = round(duration_sec, 3) + self._append_run("agent_tool_calls", entry) + + def log_stage_skipped(self, stage: str, reason_code: str, *, cycle: int = -1, detail: str = "") -> None: + entry = {"ts": self._ts(), "stage": stage, "cycle": cycle, "reason_code": reason_code, "detail": detail} + self._append_stage(stage, "stage_skipped", entry) + trace_stage_skipped(self.tracer, stage, reason_code, detail) + + def log_loop_end( + self, report: "AutoDiagnoseReport", *, + tokens_used: "int | None" = None, timings: "dict[str, float] | None" = None, + ) -> None: + entry = {"ts": self._ts(), **loop_end_entry(report, tokens_used=tokens_used, timings=timings)} + self._append_run("loop_end", entry) + + # ------------------------------------------------------------------ + # Tool synthesis (M1/M2 probes+stats tools, generated on demand) + # ------------------------------------------------------------------ + + def log_tool_codegen( + self, *, module: str, name: str, need: str, source: str, ok: bool, + code: str = "", prompt: str = "", raw_output: str = "", raw_stream: str = "", + error: str = "", stdout: str = "", cycle: "int | None" = None, + extra: "dict[str, Any] | None" = None, + ) -> None: + cyc = self.current_cycle if cycle is None else cycle + entry: dict[str, Any] = { + "ts": self._ts(), "cycle": cyc, "module": module, "tool_name": name, + "need": need, "source": source, "ok": ok, "error": error or None, + "code": code or None, "prompt": prompt or None, + "raw_output": raw_output or None, "raw_stream": raw_stream or None, + "stdout": stdout or None, + } + if extra: + entry.update(extra) + self._append_stage(module, "tool_codegen", entry) + if prompt or raw_stream or raw_output: + self.log_model_exchange( + _resolve_stage(module) or "M5", role="tool_codegen", + operation=source, inputs=prompt or "", + output=raw_stream or raw_output or code, + error=error or None, cycle=cyc, + metadata={"tool_name": name, "ok": ok}, + ) + + trace_tool_codegen( + self.tracer, module=module, name=name, need=need, source=source, ok=ok, error=error, + prompt=prompt, raw_output=raw_output, raw_stream=raw_stream, code=code, + ) + + def log_tool_registry(self, cycle: int, module: str, generated: "list[Any]") -> None: + if not generated: + return + tools = [ + { + "name": getattr(g, "name", "tool"), "need": getattr(g, "need", ""), + "source": getattr(g, "source", ""), "code": getattr(g, "code", "") or None, + } + for g in generated + ] + self._append_stage(module, "tool_registry", { + "ts": self._ts(), "cycle": cycle, "module": module, "n_tools": len(tools), "tools": tools, + }) + + # ------------------------------------------------------------------ + # Lifecycle + # ------------------------------------------------------------------ + + def close(self) -> None: + """Flush every doc one last time and persist the Langfuse trace bundle.""" + if self._closed: + return + # The run-level completion signal: everything this run logs is above it. + self._append_run("run_end", {}) + with self._lock: + self._flush_run() + for stage in _STAGES: + self._flush_stage(stage) + self.tracer.end_trace({ + "spans": len(self.tracer.spans), + "generations": len(self.tracer.generations), + "scores": len(self.tracer.scores), + }) + self.tracer.flush() + try: + self.tracer.export_bundle(self.run_dir / "langfuse_trace.json") + except Exception: # noqa: BLE001 + pass + # Offline runs need no retry queue once the complete JSON trace bundle + # has been exported. A live run keeps a non-empty queue for retry. + if self.tracer.mode == "offline" or self.tracer.outbox.pending_count() == 0: + try: + self._outbox_path.unlink(missing_ok=True) + self._outbox_path.parent.rmdir() + except OSError: + pass + self._closed = True + + def __enter__(self) -> "RunLogger": + return self + + def __exit__(self, *exc_info: Any) -> None: + self.close() diff --git a/evalrx/eval_agent/run_logger_v2.py b/evalrx/eval_agent/run_logger_v2.py deleted file mode 100644 index d9237436..00000000 --- a/evalrx/eval_agent/run_logger_v2.py +++ /dev/null @@ -1,1778 +0,0 @@ -"""RunLoggerV2 — the diagnose-loop logger. - -The only logger: an earlier flat ``run_log.jsonl`` design this one replaced -coexisted with it for one migration window and has since been removed — see -``RUN_LOGGER_V2.md`` (next to this file) for the full design rationale, -layout, and trade-offs; the four rules that shaped it: - -1. Few files. One JSON document per pipeline stage, not a scattered pile of - ``prompts/*.txt`` + ``artifacts/*.json`` + ``experiments/*.py`` + ... -2. Same-type logging in one JSON. Every event of a given kind (all ``probe`` - events, all ``model_call`` events, ...) lives in ONE array, in ONE file — - not one small file per call. -3. M1..M5 each get their own folder. A reader who only cares about M3 opens - exactly one folder. -4. Nothing but JSON, except real binary artifacts (images, audio, tensors). Code, - stdout, prompts, markdown summaries — all of that is now a STRING VALUE - inside the JSON, not a sibling ``.py``/``.txt``/``.md`` file. - -Every ``log_*`` method keeps the same name, signature, and call-site -behavior for return values (e.g. ``log_probe``'s ``list[Path]``) the flat -JSONL logger it replaced had, so ``VLDiagnoseLoop(run_logger=...)`` / -``ProbeAgent(run_logger=...)`` never -needed to change in ``loop.py``, ``probe_agent.py``, or any ``stages/*.py`` -across the switch. - -Scope, by design: - - RunContext integration uses an external ephemeral runtime tree. Generated - text/code is captured into stage JSON and the runtime tree is removed at - finalization instead of becoming a forest of trial files. - - No human-readable Markdown summaries (``record.md``, ``outcome.md``) — - the same information is in the JSON for a renderer to build one from. - - Verbose console narration is a plain one-line-per-event summary, not a - multi-line stage narration. -Native Langfuse/OpenTelemetry mirroring (:class:`DiagnosticTracer`) IS kept, -reused unchanged — it is orthogonal to file layout. -""" - -from __future__ import annotations - -import getpass -import json -import os -import re -import tempfile -import threading -import uuid -import warnings -from datetime import datetime, timezone -from pathlib import Path -from typing import TYPE_CHECKING, Any - -from evalrx.eval_agent.hypothesis import hypothesis_id -from evalrx.eval_agent.log_schema import RUN_LOG_SCHEMA_VERSION - -if TYPE_CHECKING: - from evalrx.analysis.analysis_module import AnalysisReport - from evalrx.core.result import Result - from evalrx.eval_agent.hypothesis import Hypothesis - from evalrx.eval_agent.loop_reports import AutoDiagnoseReport - from evalrx.eval_agent.stages.diagnosis import DiagnosisResult - from evalrx.eval_agent.stages.surgery import InterventionResult - -RUN_LOGGER_V2_VERSION = 1 - -_STAGES = ("M1", "M2", "M3", "M4", "M5") - -#: A tag string not matching this falls back to _STAGE_ALIASES, then to the -#: run-level "unrouted" bucket (never silently dropped — see _resolve_stage). -_STAGE_RE = re.compile(r"m([1-5])", re.IGNORECASE) - -#: Tags used somewhere in the codebase that carry no "m" substring at all -#: (checked against every literal `module=`/`stage=` value passed to a -#: log_* method as of this writing — see RUN_LOGGER_V2.md's "routing" table). -_STAGE_ALIASES: dict[str, str] = { - "fix_pipeline": "M5", - "fix": "M5", - "explore": "M2", -} - -#: Extensions treated as genuine binary media — the one thing rule 4 still -#: allows as a separate file. Everything else becomes a JSON string value. -_MEDIA_EXTS = frozenset({ - ".npy", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", - ".wav", ".mp3", ".flac", ".ogg", ".mp4", ".avi", ".mov", -}) - -#: Text/code file suffixes worth inlining from a sandbox workspace snapshot -#: (skip weights/binaries — those go through the media/artifact path instead). -_INLINE_SUFFIXES = frozenset( - {".py", ".json", ".jsonl", ".md", ".txt", ".yaml", ".yml", ".csv", ".log", ".toml"} -) -_INLINE_MAX_BYTES = 2_000_000 # skip (note-only) any single file larger than this - - -def _resolve_stage(tag: "str | None") -> "str | None": - """"m1_probe" / "M4_SURGERY" / "codegen_m2_stats" / "fix_pipeline" -> "M1".."M5". - - Returns ``None`` when *tag* matches nothing — the caller must not drop - the event in that case; route it to the run-level "unrouted" bucket - instead (see ``RunLoggerV2._route``). A tag is never assumed unroutable - without trying both the regex AND the alias table. - """ - if not tag: - return None - m = _STAGE_RE.search(tag) - if m: - return f"M{m.group(1)}" - return _STAGE_ALIASES.get(tag.strip().lower()) - - -def _outbox_dir() -> Path: - """Per-user temp directory for the Langfuse delivery queue. - - A single shared ``/tmp/evalrx-v2-outbox`` breaks on multi-user hosts: the - first user to create it owns it, and everyone else gets "unable to open - database file". - """ - try: - user = getpass.getuser() - except Exception: # noqa: BLE001 - no login name (e.g. bare containers) - user = str(os.getuid()) if hasattr(os, "getuid") else "default" - return Path(tempfile.gettempdir()) / f"evalrx-v2-outbox-{user}" - - -def _atomic_write_json(path: Path, obj: Any) -> None: - """Write *obj* as JSON to *path* such that a reader never sees a partial file. - - Writes to a sibling temp file first, then ``os.replace`` (atomic on the - same filesystem) — a crash mid-write leaves the OLD complete file in - place, never a truncated one. This runs on every single logged event - (see the design doc's "durability" section for the cost trade-off that - was chosen deliberately here, not overlooked). - """ - path.parent.mkdir(parents=True, exist_ok=True) - tmp = path.with_name(f".{path.name}.tmp{os.getpid()}") - tmp.write_text(json.dumps(obj, indent=2, default=str, ensure_ascii=False), encoding="utf-8") - os.replace(tmp, path) - - -def _inline_workspace( - workdir: "str | Path", media_dir: Path, *, run_dir: "Path | None" = None, - max_bytes: "int | None" = _INLINE_MAX_BYTES, - preserve_all: bool = False, -) -> "dict[str, Any] | None": - """Read a sandbox working directory into a JSON-safe dict, inlining text. - - Returns ``{"files": {relative_path: content_or_note}, "media": [rel_paths], - "skipped": n}`` or ``None`` when *workdir* does not exist. Text-like files - (see ``_INLINE_SUFFIXES``) are read and inlined verbatim; recognised media - extensions are COPIED into *media_dir* (a real binary artifact, rule 4's - one exception) with a path reference left in ``"media"``; anything else is - skipped with a one-line note so its existence is still visible. - """ - import hashlib - import shutil - - src = Path(workdir) - if not src.exists() or not src.is_dir(): - return None - files: dict[str, Any] = {} - media: list[str] = [] - media_files: dict[str, str] = {} - skipped = 0 - for f in sorted(src.rglob("*")): - if not f.is_file(): - continue - rel = str(f.relative_to(src)) - suffix = f.suffix.lower() - inline_content = None - binary = suffix in _MEDIA_EXTS - if preserve_all and suffix not in _INLINE_SUFFIXES and not binary: - try: - inline_content = f.read_text(encoding="utf-8") - if "\x00" in inline_content: - binary = True - except UnicodeError: - binary = True - if binary: - media_dir.mkdir(parents=True, exist_ok=True) - # Path + content identify a snapshot: trials cannot collide, and - # later writes to the same source cannot replace earlier evidence. - hasher = hashlib.sha256(str(f.resolve()).encode("utf-8")) - with f.open("rb") as stream: - for chunk in iter(lambda: stream.read(1024 * 1024), b""): - hasher.update(chunk) - digest = hasher.hexdigest()[:12] - dest = media_dir / f"{f.stem}_{digest}{suffix}" - try: - shutil.copy2(f, dest) - try: - media.append(str(dest.relative_to(run_dir)) if run_dir else str(dest)) - except ValueError: - media.append(str(dest)) - media_files[rel] = media[-1] - except Exception: # noqa: BLE001 - if preserve_all: - raise # do not let finalization delete unarchived evidence - skipped += 1 - continue - if suffix not in _INLINE_SUFFIXES and inline_content is None: - files[rel] = f"" - skipped += 1 - continue - try: - if max_bytes is not None and f.stat().st_size > max_bytes: - files[rel] = f"" - skipped += 1 - continue - files[rel] = inline_content if inline_content is not None else f.read_text(encoding="utf-8", errors="replace") - except Exception as exc: # noqa: BLE001 - if preserve_all: - raise - files[rel] = f"" - skipped += 1 - return {"files": files, "media": media, "media_files": media_files, "skipped": skipped} - - -# Pure, stateless content-shaping helpers with no file-writing side effects. - - -def _case_snapshot(case: Any) -> "dict[str, Any]": - """Make a small, renderer-safe baseline record for an evidence example.""" - if hasattr(case, "to_dict"): - value = case.to_dict() - elif isinstance(case, dict): - value = dict(case) - else: - value = {"id": str(getattr(case, "id", ""))} - inputs = value.get("inputs") if isinstance(value.get("inputs"), dict) else {} - return { - "id": str(value.get("id") or value.get("case_id") or ""), - "input": inputs.get("prompt") or value.get("prompt") or value.get("instruction") or "", - "baseline_output": value.get("observed", value.get("output")), - "expected": value.get("expected"), - "outcome": value.get("label") or value.get("status") or "unknown", - } - - -def _iter_cases(cases: Any) -> "list[Any]": - """Accept CaseBatch, a plain sequence, or a generator without assumptions.""" - if cases is None: - return [] - value = getattr(cases, "cases", cases) - try: - return list(value) - except TypeError: - return [] - - -def _probe_examples(results: "dict[str, Any]", cases: Any) -> "list[dict[str, Any]]": - """Persist two real, bounded M1 walkthroughs beside aggregate findings. - - A probe only becomes a before/after comparison when its analyzer explicitly - records both outputs. Otherwise this records an honest *baseline case + - check result* example; downstream UI must not call it an intervention. - """ - snapshots: dict[str, dict[str, Any]] = {} - for case in _iter_cases(cases): - snapshot = _case_snapshot(case) - if snapshot["id"]: - snapshots[snapshot["id"]] = snapshot - output: list[dict[str, Any]] = [] - used: set[str] = set() - for name, result in results.items(): - findings = getattr(result, "findings", {}) or {} - rows = findings.get("per_case") or [] - if not isinstance(rows, list): - continue - rows = sorted( - (row for row in rows if isinstance(row, dict)), - key=lambda row: 0 if str(snapshots.get(str(row.get("sample_id") or row.get("case_id") or ""), {}).get("outcome", "")).lower() == "fail" else 1, - ) - for row in rows: - case_id = str(row.get("sample_id") or row.get("case_id") or "") - snapshot = snapshots.get(case_id) - if not snapshot or case_id in used: - continue - checked = { - str(key).replace("_", " "): value for key, value in row.items() - if key not in {"sample_id", "case_id"} and isinstance(value, (str, int, float, bool)) - } - if not checked: - continue - used.add(case_id) - output.append({ - "id": f"m1-{name}-{case_id}", "kind": "case_measurement", "case_id": case_id, - "probe_title": str(name).replace("_", " ").title(), - **snapshot, "check_result": checked, - "plain_reading": "This one case illustrates the recorded check. The aggregate M1 result uses all measured cases.", - "evidence_scope": "one recorded case within M1", - }) - break - if len(output) >= 2: - break - return output - - -def _artifact_to_numpy(artifact: Any) -> "Any | None": - """Convert *artifact* to a numpy array, or return None if not possible. - - Handles: torch.Tensor, list[torch.Tensor] (e.g. per-layer attentions), - and numpy arrays. A list of tensors is stacked along a new first axis so - that ``attentions`` (list of ``(heads, seq, seq)``) becomes - ``(layers, heads, seq, seq)`` — a single array that retains all the data. - """ - try: - import numpy as np - except ImportError: - return None - - if hasattr(artifact, "detach"): # torch.Tensor - return artifact.detach().cpu().float().numpy() - if isinstance(artifact, np.ndarray): - return artifact - if isinstance(artifact, list) and artifact and hasattr(artifact[0], "detach"): - try: - import torch - return torch.stack(artifact).detach().cpu().float().numpy() - except Exception: # noqa: BLE001 - return None - return None - - -def _save_artifact_figure(artifact_dir: Path, stem: str, arr: Any) -> None: - """Save a matplotlib figure of *arr* when the shape and stem are recognised. - - Dispatch table (first match wins): - - 4-D + ``attn`` in stem → mean over (layers, heads) → 2-D heatmap - - 3-D + ``attn`` in stem → mean over heads → 2-D heatmap - - 2-D + heatmap keyword → direct heatmap (viridis) - - 1-D + curve keyword → line plot - Skips silently when matplotlib is unavailable or the shape is unrecognised. - """ - try: - import matplotlib.pyplot as plt - plt.ioff() - except ImportError: - return - - key = stem.lower() - # Skip logit arrays — (seq, vocab) shape is too large for a useful figure - if "logit" in key: - return - - _is_attn = any(k in key for k in ("attn", "attention")) - - fig = None - try: - ndim = arr.ndim - if ndim == 4 and _is_attn: - mat = arr.mean(axis=(0, 1)) # (layers, heads, seq, seq) → (seq, seq) - n_layers, n_heads = arr.shape[0], arr.shape[1] - fig, ax = plt.subplots(figsize=(8, 7)) - im = ax.imshow(mat, cmap="viridis", aspect="auto", vmin=0) - ax.set_title(f"{stem} (mean over {n_layers}L × {n_heads}H)") - plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04) - plt.tight_layout() - elif ndim == 3 and _is_attn: - mat = arr.mean(axis=0) # (heads, seq, seq) → (seq, seq) - n_heads = arr.shape[0] - fig, ax = plt.subplots(figsize=(8, 7)) - im = ax.imshow(mat, cmap="viridis", aspect="auto", vmin=0) - ax.set_title(f"{stem} (mean over {n_heads} heads)") - plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04) - plt.tight_layout() - elif ndim == 2 and "diff" in key: - # Signed difference map (e.g. FAIL-mean minus PASS-mean attention): - # diverging colormap with symmetric limits so the sign is readable. - bound = float(max(abs(arr.min()), abs(arr.max()))) or 1.0 - fig, ax = plt.subplots(figsize=(8, 7)) - im = ax.imshow(arr, cmap="coolwarm", aspect="auto", vmin=-bound, vmax=bound) - ax.set_title(stem) - plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04) - plt.tight_layout() - elif ndim == 2 and (_is_attn or any(k in key for k in ("rollout", "spatial", "map"))): - fig, ax = plt.subplots(figsize=(8, 7)) - im = ax.imshow(arr, cmap="viridis", aspect="auto") - ax.set_title(stem) - plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04) - plt.tight_layout() - elif ndim == 1 and any(k in key for k in ("entropy", "score", "prob", "weight", "rollout")): - fig, ax = plt.subplots(figsize=(8, 3)) - ax.plot(arr) - ax.set_xlabel("position") - ax.set_ylabel(stem) - ax.set_title(stem) - plt.tight_layout() - - if fig is not None: - fig.savefig(artifact_dir / f"{stem}.png", dpi=100, bbox_inches="tight") - except Exception: # noqa: BLE001 - pass - finally: - if fig is not None: - plt.close(fig) - - -class _V2JsonFormatter: - """Renders one plain one-line console summary per event, for ``verbose=True``. - - Intentionally simple — file layout was this module's ask, not console UX; - see the design doc. - """ - - @staticmethod - def line(stage: "str | None", event: str, payload: "dict[str, Any]") -> str: - where = f"[{stage}]" if stage else "[run]" - cycle = payload.get("cycle") - tail = f" cycle={cycle}" if cycle is not None else "" - return f"{where} {event}{tail}" - - -class RunLoggerV2: - """A tidy, from-scratch M1..M5 logger. See the module docstring + design doc. - - Args: - run_dir: Directory to write into. Created if missing. Defaults to - ``runs_v2//`` relative to cwd. - verbose: Print a one-line raw summary of every event to stdout - (``[M1] probe cycle=0``). Ignored when *narrate* is set. - narrate: Print live, aligned M1-M5 narration instead — the same - visual style as ``evalrx explore``'s terminal output (see - :mod:`evalrx.eval_agent.narration.LoopNarrator`), built - from real per-stage counts instead of a raw event dump. - trace_id: Ties every event to one Langfuse trace; auto-generated if - omitted. - observability_mode: Forwarded to :class:`DiagnosticTracer` unchanged. - - Layout written under *run_dir*:: - - run.json run-wide: run_start, cases, report_published, - loop_end, agent_decisions, agent_tool_calls, - unrouted (see _resolve_stage) - M1/log.json probe, model_calls, tool_codegen, tool_registry, - stage_skipped — all M1-tagged events - M2/log.json analysis, explore, ... - M3/log.json diagnosis, ... - M4/log.json surgery (hypothesis-verification kind), ... - M5/log.json surgery (intervention kind), experiment, fix, ... - M*/artifacts/ binary media for that stage only (rule 4's exception) - media/ case-level baseline media (images/audio referenced - by FailureCase.inputs) - artifacts/ run-global named JSON (save_artifact_json) - """ - - def __init__( - self, - run_dir: "str | Path | None" = None, - *, - verbose: bool = False, - narrate: bool = False, - trace_id: "str | None" = None, - observability_mode: "str | None" = None, - context: "Any | None" = None, - ) -> None: - if run_dir is None: - run_dir = Path("runs_v2") / datetime.now().strftime("%Y%m%d_%H%M%S") - self.run_dir = Path(run_dir) - self.run_dir.mkdir(parents=True, exist_ok=True) - self.run_json_path = self.run_dir / "run.json" - - self.trace_id: str = trace_id or str(uuid.uuid4()) - self.current_cycle: int = -1 - # Live M1-M5 terminal narration (see evalrx.eval_agent.narration) -- - # opt-in, takes over from the plain `verbose` one-liner below rather - # than stacking with it, so a run never prints each event twice. - self._narrator = None - if narrate: - from evalrx.eval_agent.narration import LoopNarrator - - self._narrator = LoopNarrator() - self.verbose = verbose - self._context = context - self._closed = False - # Producers use this capability flag to keep text/code in log events - # instead of writing sibling files into trial directories. - self.inline_text_artifacts = True - self.preserve_full_model_io = True - - # One in-memory doc per stage + one run-level doc. Every log_* method - # appends to the relevant bucket(s), then atomically rewrites exactly - # the doc(s) it touched — see _atomic_write_json. - self._lock = threading.RLock() - self._event_seq = 0 - self._validate_events = bool(os.environ.get("EVALRX_VALIDATE_LOG")) - self._event_validator = None - self._run_doc: dict[str, Any] = { - "trace_id": self.trace_id, - "run_start": None, - "cases": [], - "report_published": [], - "diagnose_reports": [], - "manifest": None, - "loop_end": [], - "agent_decisions": [], - "agent_tool_calls": [], - "unrouted": [], - } - self._stage_docs: dict[str, dict[str, Any]] = {s: {} for s in _STAGES} - self._logged_case_ids: set[str] = set() - self._model_call_seq = 0 - self._codegen_seq = 0 - # See log_model_call / log_probe: calls are recorded immediately into - # M1's doc AND buffered here so log_probe can replay them into - # Langfuse nested under the right probe span once it exists. - self._pending_model_calls: "dict[int, list[dict[str, Any]]]" = {} - - from evalrx.observability.tracer import DiagnosticTracer - # The SQLite delivery queue is runtime state, not part of the tidy run - # artifact. Keep it outside the run tree; langfuse_trace.json remains - # the durable, portable JSON trace bundled with the run. - self._outbox_path = _outbox_dir() / f"{self.trace_id}.sqlite3" - self.tracer = DiagnosticTracer( - run_dir=self.run_dir, mode=observability_mode, auto_sync=True, - outbox_path=self._outbox_path, - ) - self.tracer.trace_id = self.trace_id - - self._flush_run() - - # ------------------------------------------------------------------ - # Internal: doc access, routing, durability - # ------------------------------------------------------------------ - - def _stage_dir(self, stage: str) -> Path: - d = self.run_dir / stage - d.mkdir(parents=True, exist_ok=True) - return d - - def _stage_artifacts_dir(self, stage: str) -> Path: - d = self._stage_dir(stage) / "artifacts" - d.mkdir(parents=True, exist_ok=True) - return d - - def _flush_run(self) -> None: - _atomic_write_json(self.run_json_path, self._run_doc) - - def _flush_stage(self, stage: str) -> None: - _atomic_write_json(self._stage_dir(stage) / "log.json", self._stage_docs[stage]) - - def _bucket(self, stage: str, key: str) -> list: - return self._stage_docs[stage].setdefault(key, []) - - def _stamp_event(self, key: str, record: dict[str, Any], stage: str) -> None: - """Assign durable event identity under ``_lock``; no telemetry side effects.""" - event = { - "cases": "case_record", "model_calls": "model_call", - "diagnose_reports": "diagnose_report", "agent_decisions": "agent_decision", - "agent_tool_calls": "agent_tool", - }.get(key, key) - self._event_seq += 1 - cycle = record.get("cycle", -1) - span = { - "run_start": "run_start", "probe": f"c{cycle}.m1", - "analysis": f"c{cycle}.m2", "diagnosis": f"c{cycle}.m3", - "explore": f"c{cycle}.explore", "surgery": f"c{cycle}.{stage.lower()}", - "fix": "fix", "agent_decision": f"s{record.get('step')}.decision", - "agent_tool": f"s{record.get('step')}.tool", - "stage_skipped": f"{stage.lower()}.skipped", - }.get(event, f"{stage.lower()}.{event}.{self._event_seq}") - record.update(event=event, schema_version=RUN_LOG_SCHEMA_VERSION, - trace_id=self.trace_id, event_seq=self._event_seq, - stage=stage, span_id=span) - record.setdefault("ts", self._ts()) - if self._validate_events: - try: - from evalrx.eval_agent.log_schema import _validator, build_schema - - if self._event_validator is None: - self._event_validator = _validator(build_schema()) - self._event_validator.validate(record) - except ImportError: - pass - except Exception as exc: # warn-only - warnings.warn(f"RunLoggerV2: event {event!r} violates log schema: {exc}") - - def _append_stage(self, tag: "str | None", key: str, record: "dict[str, Any]") -> str: - """Route *record* by *tag* into the right stage bucket; flush; return the stage.""" - stage = _resolve_stage(tag) - with self._lock: - if stage is None: - warnings.warn( - f"RunLoggerV2: could not route event {key!r} (tag={tag!r}) to a " - "stage — filed under run.json['unrouted'] instead of being lost.", - stacklevel=3, - ) - record = {"key": key, "tag": tag, **record} - self._stamp_event("unrouted", record, "RUN") - self._run_doc["unrouted"].append(record) - self._flush_run() - return "unrouted" - self._stamp_event(key, record, stage) - self._bucket(stage, key).append(record) - self._flush_stage(stage) - if self._narrator is not None: - self._narrator.on_event(stage, key, record) - elif self.verbose: - print(_V2JsonFormatter.line(stage, key, record)) - return stage - - def _append_run(self, key: str, record: "dict[str, Any]") -> None: - """Append *record* to the (always list-valued) run.json bucket *key*. - - ``run_start`` is the one run.json field that isn't a list — it's set - directly by ``log_run_start``, never through here. - """ - with self._lock: - self._stamp_event(key, record, "RUN") - self._run_doc[key].append(record) - self._flush_run() - if self._narrator is not None: - self._narrator.on_run_event(key, record) - elif self.verbose: - print(_V2JsonFormatter.line(None, key, record)) - - @property - def managed_json_paths(self) -> "tuple[Path, ...]": - """Atomic JSON documents that may be rewritten while quarantine runs.""" - return (self.run_json_path, *(self.run_dir / s / "log.json" for s in _STAGES)) - - @staticmethod - def _ts() -> str: - return datetime.now(timezone.utc).isoformat(timespec="microseconds") - - def _save_media(self, stage: str, stem: str, artifact: Any) -> "str | None": - """Save a numeric artifact (tensor/array) + a rendered figure, if any. - - Writes under this stage's ``artifacts/`` dir. Returns the ``.npy`` - path (run-relative) or ``None`` when *artifact* isn't a recognised - numeric type. - """ - try: - import numpy as np - - arr = _artifact_to_numpy(artifact) - if arr is not None: - art_dir = self._stage_artifacts_dir(stage) - path = art_dir / f"{stem}.npy" - np.save(path, arr) - _save_artifact_figure(art_dir, stem, arr) - return str(path.relative_to(self.run_dir)) - return None - except Exception as exc: # noqa: BLE001 - warnings.warn(f"RunLoggerV2: could not save artifact {stem!r}: {exc}") - return None - - def _save_case_media(self, path: Path) -> "str | None": - """Copy external case media into ``media/`` (content-hash-deduped); return rel path.""" - import hashlib - import shutil - - media_dir = self.run_dir / "media" - media_dir.mkdir(parents=True, exist_ok=True) - digest = hashlib.sha256() - try: - with path.open("rb") as handle: - for chunk in iter(lambda: handle.read(1024 * 1024), b""): - digest.update(chunk) - except OSError: - return None - copied = media_dir / f"{digest.hexdigest()[:16]}_{path.name}" - if not copied.exists(): - shutil.copy2(path, copied) - return str(copied.relative_to(self.run_dir)) - - def _portable_path(self, value: "str | Path") -> str: - path = Path(value) - try: - return str(path.resolve().relative_to(self.run_dir.resolve())) - except (OSError, ValueError): - return str(value) - - # ------------------------------------------------------------------ - # Run provenance - # ------------------------------------------------------------------ - - def log_run_start(self, config: "dict[str, Any] | None" = None) -> None: - import platform - - entry: dict[str, Any] = {"ts": self._ts(), "trace_id": self.trace_id} - if config: - entry.update(config) - entry.setdefault("python_version", platform.python_version()) - try: - from evalrx import __version__ as _ver # type: ignore - entry.setdefault("evalrx_version", _ver) - except Exception: # noqa: BLE001 - pass - commit = self._git_commit() - if commit: - entry.setdefault("git_commit", commit) - with self._lock: - self._stamp_event("run_start", entry, "RUN") - self._run_doc["run_start"] = entry - self._flush_run() - if self._narrator is not None: - self._narrator.on_run_start(entry) - elif self.verbose: - print(_V2JsonFormatter.line(None, "run_start", entry)) - - model_name = str(entry.get("model") or "Target Model") - proto = entry.get("protocol") or {} - proto_desc = proto.get("description", "") if isinstance(proto, dict) else str(proto) - bench_name = str(entry.get("benchmark_name") or proto_desc or "Benchmark") - self.tracer.start_trace( - model=model_name, benchmark=bench_name, - n_cases=int(entry.get("n_cases", 0) or 0), metadata=entry, - ) - - @staticmethod - def _git_commit() -> "str | None": - import subprocess - - try: - out = subprocess.run( - ["git", "rev-parse", "--short", "HEAD"], - capture_output=True, text=True, timeout=3, check=False, - ) - commit = out.stdout.strip() - if commit: - return commit - except Exception: # noqa: BLE001 - pass - return os.environ.get("EVALRX_GIT_COMMIT") or None - - def log_cases(self, cases: "Any", *, split: "str | None" = None) -> None: - """Persist complete case I/O; media is copied into ``media/`` (rule 4's exception). - - ``split`` is the partition the loop assigned (``explore`` / ``confirm`` / - ``test``), recorded on the row so a report can group the cases the way - the run actually used them. - """ - for case in cases: - case_id = str(getattr(case, "id", "") or "") - if not case_id or case_id in self._logged_case_ids: - continue - if hasattr(case, "to_dict"): - payload = case.to_dict() - elif isinstance(case, dict): - payload = dict(case) - else: - payload = {"id": case_id, "value": str(case)} - payload = json.loads(json.dumps(payload, ensure_ascii=False, default=str)) - media_paths: list[str] = [] - inputs = getattr(case, "inputs", None) - for kind in ("image", "audio", "video"): - value = getattr(inputs, kind, None) - if not isinstance(value, (str, Path)): - continue - path = Path(value) - if not path.is_absolute(): - run_relative = self.run_dir / path - path = run_relative if run_relative.is_file() else path.resolve() - if not path.is_file(): - continue - saved = self._save_case_media(path) - if saved: - media_paths.append(saved) - record: dict[str, Any] = { - "ts": self._ts(), "case_id": case_id, "case": payload, "media_paths": media_paths, - } - if split: - record["split"] = str(split) - self._append_run("cases", record) - self._logged_case_ids.add(case_id) - - def log_report_published(self, envelope: "dict[str, Any]") -> None: - generated = envelope.get("generated_by") or {} - self._append_run("report_published", { - "ts": self._ts(), - "report_schema_version": int(envelope.get("schema_version") or 1), - "catalog_version": str(envelope.get("catalog_version") or ""), - "json_render_version": str(envelope.get("json_render_version") or ""), - "source_event_seq": int(envelope.get("source_event_seq") or 0), - "sha256": str(envelope.get("sha256") or ""), - "generated_by": generated, - "report_paths": ["report/report_data.json", "report/report_spec.json"], - }) - - def log_diagnose_report( - self, - report: Any, - cases: "list[Any]", - *, - discovery: "list[dict[str, Any]] | None" = None, - ) -> None: - """Inline the standard post-diagnosis report into ``run.json`` as one - detailed machine-readable record; a UI renders prose from this data - rather than reading separate JSON/Markdown siblings.""" - hyps_src = getattr(report, "all_hypotheses", None) - if hyps_src is None: - hyps_src = getattr(report, "final_hypotheses", []) - hypotheses = [ - { - "statement": h.statement, - "plain_statement": getattr(h, "plain_statement", ""), - "failure_mode": h.predicted_failure_mode, - "status": h.status.value if h.status else None, - } - for h in hyps_src - ] - m4_results = [ - { - "hypothesis": tr.hypothesis.statement, - "failure_mode": tr.hypothesis.predicted_failure_mode, - "status": tr.status.value, - "effect_size": tr.effect_size, - "confidence": tr.confidence, - "protocol_consistent": tr.is_consistent_with_protocol, - "verdict": tr.verdict, - "evidence": tr.evidence, - } - for tr in getattr(report, "all_test_results", []) - ] - self._append_run("diagnose_reports", { - "ts": self._ts(), - "cycles": report.cycles, - "stopped_by": getattr(report, "stopped_by", None), - "resolved": getattr(report, "resolved", None), - "n_cases": len(cases), - "n_hypotheses": len(hypotheses), - "n_verified": len(getattr(report, "verified_hypotheses", [])), - "hypotheses": hypotheses, - "m4_results": m4_results, - "discovery": list(discovery or []), - }) - - def log_manifest(self, *, run_id: str, config: "dict[str, Any]") -> None: - """Record final run provenance and a compact file index in ``run.json``.""" - files = [ - str(path.relative_to(self.run_dir)) - for path in sorted(self.run_dir.rglob("*")) - if path.is_file() and not path.name.startswith(".") - ] - with self._lock: - self._run_doc["manifest"] = { - "ts": self._ts(), "run_id": run_id, "config": dict(config), "files": files, - } - self._flush_run() - - def log_runtime_snapshot(self, root: Path) -> None: - """Preserve execution files, including discarded trials, before cleanup.""" - snapshot = _inline_workspace( - root, self._stage_artifacts_dir("M5"), run_dir=self.run_dir, - max_bytes=None, preserve_all=True, - ) - with self._lock: - self._run_doc["runtime_snapshot"] = snapshot - self._flush_run() - - def log_model_exchange( - self, - stage: str, - *, - role: str, - operation: str, - inputs: Any, - output: Any = None, - error: "str | None" = None, - duration_sec: "float | None" = None, - metadata: "dict[str, Any] | None" = None, - cycle: "int | None" = None, - ) -> None: - """Persist one exact model/agent input-output exchange in its stage.""" - def json_safe(value: Any) -> Any: - import dataclasses - - if dataclasses.is_dataclass(value): - value = dataclasses.asdict(value) - elif hasattr(value, "to_dict") and callable(value.to_dict): - try: - value = value.to_dict() - except Exception: # noqa: BLE001 - pass - return json.loads(json.dumps(value, ensure_ascii=False, default=str)) - - entry: dict[str, Any] = { - "ts": self._ts(), - "cycle": self.current_cycle if cycle is None else cycle, - "role": role, - "operation": operation, "inputs": json_safe(inputs), "output": json_safe(output), - "error": error, "metadata": json_safe(dict(metadata or {})), - } - if duration_sec is not None: - entry["duration_sec"] = round(duration_sec, 4) - self._append_stage(stage, "model_calls", entry) - - def save_artifact_json(self, stem: str, obj: Any) -> "str | None": - """Write *obj* as JSON under the run-global ``artifacts/`` dir; return rel path.""" - try: - d = self.run_dir / "artifacts" - d.mkdir(parents=True, exist_ok=True) - path = d / stem - path.write_text(json.dumps(obj, indent=2, default=str), encoding="utf-8") - return str(path.relative_to(self.run_dir)) - except Exception as exc: # noqa: BLE001 - warnings.warn(f"RunLoggerV2: could not save artifact {stem!r}: {exc}") - return None - - # ------------------------------------------------------------------ - # M1 — target-model calls (see model_instrumentation.InstrumentedModel) - # ------------------------------------------------------------------ - - def log_model_call( - self, - *, - cycle: int, - analyzer: str, - call_index: int, - method: str, - inputs: Any, - kwargs: "dict[str, Any]", - output: Any, - duration_sec: float, - error: "str | None", - case_id: "str | None" = None, - batch_case_ids: "list[str] | None" = None, - n_batch_cases: "int | None" = None, - ) -> None: - record: dict[str, Any] = { - "ts": self._ts(), "cycle": cycle, "analyzer": analyzer, - "call_index": call_index, "method": method, - "case_id": case_id, "batch_case_ids": batch_case_ids or [], - "n_batch_cases": n_batch_cases if n_batch_cases is not None else len(batch_case_ids or []), - "inputs": inputs, "kwargs": kwargs, "output": output, - "duration_sec": round(duration_sec, 4), - } - if error is not None: - record["error"] = error - with self._lock: - self._model_call_seq += 1 - record["seq"] = self._model_call_seq - self._stamp_event("model_calls", record, "M1") - self._bucket("M1", "model_calls").append(record) - self._flush_stage("M1") - self._pending_model_calls.setdefault(cycle, []).append(record) - if self.verbose: - print(_V2JsonFormatter.line("M1", "model_call", record)) - - # ------------------------------------------------------------------ - # M1 — probe - # ------------------------------------------------------------------ - - def log_probe( - self, - cycle: int, - results: "dict[str, Result]", - schema: "Any | None" = None, - *, - cases: "Any | None" = None, - judge_prompt: "str | None" = None, - judge_raw: "str | None" = None, - duration_sec: "float | None" = None, - failed_analyzers: "dict[str, str] | None" = None, - ) -> "list[Path]": - """M1: one entry in M1/log.json's "probe" list. ``artifact_paths``/ - results are inlined here instead of living in separate - ``.result.json`` files.""" - artifact_paths: dict[str, str] = {} - overlay_pngs: list[Path] = [] - result_docs: dict[str, Any] = {} - inline_artifacts: dict[str, Any] = {} - for name, result in results.items(): - for art_name, artifact in getattr(result, "artifacts", {}).items(): - stem = f"c{cycle}_{name}_{art_name}" - rel = self._save_media("M1", stem, artifact) - if rel is not None: - artifact_paths[f"{name}/{art_name}"] = rel - elif isinstance(artifact, (dict, list)): - inline_artifacts[f"{name}/{art_name}"] = json.loads( - json.dumps(artifact, ensure_ascii=False, default=str) - ) - image_overlays = getattr(result, "image_overlays", None) - if image_overlays is not None: - try: - overlay_pngs.extend( - image_overlays(self._stage_artifacts_dir("M1"), f"c{cycle}_{name}") - ) - except Exception as exc: # noqa: BLE001 - viz must never break the probe - warnings.warn(f"RunLoggerV2: image_overlays failed for {name}: {exc}") - to_dict = getattr(result, "to_dict", None) - if callable(to_dict): - try: - doc = to_dict() - summary = getattr(result, "summary", None) - if callable(summary): - doc["summary"] = summary() - result_docs[name] = doc - except Exception as exc: # noqa: BLE001 - warnings.warn(f"RunLoggerV2: could not serialise result {name!r}: {exc}") - - with self._lock: - pending_calls = [c for bucket in self._pending_model_calls.values() for c in bucket] - self._pending_model_calls.clear() - - entry: dict[str, Any] = { - "ts": self._ts(), "cycle": cycle, - "analyzers": list(results), - "findings": {name: r.findings for name, r in results.items()}, - "results": result_docs, - "artifact_paths": artifact_paths, - "artifacts": inline_artifacts, - "n_model_calls": len(pending_calls), - } - examples = _probe_examples(results, cases) - if examples: - entry["examples"] = examples - if failed_analyzers: - entry["failed_analyzers"] = dict(failed_analyzers) - if schema is not None: - entry["selection_rationale"] = getattr(schema, "rationale", "") - selected = getattr(schema, "selected_analyzers", None) - if selected is not None: - entry["selected_analyzers"] = list(selected) - if judge_prompt: - entry["judge_prompt"] = judge_prompt - if judge_raw: - entry["judge_response"] = judge_raw - if duration_sec is not None: - entry["duration_sec"] = round(duration_sec, 3) - self._append_stage("M1", "probe", entry) - if judge_prompt or judge_raw: - self.log_model_exchange( - "M1", role="analyzer_selection_judge", operation="generate", - inputs=judge_prompt or "", output=judge_raw or "", cycle=cycle, - duration_sec=duration_sec, - ) - - png_figures: list[Path] = list(overlay_pngs) - for rel_npy in artifact_paths.values(): - if not rel_npy.endswith(".npy"): - continue - png = self.run_dir / (rel_npy[: -len(".npy")] + ".png") - if png.exists(): - png_figures.append(png) - - m1_span = self.tracer.start_span( - name=f"M1: Multi-Dimensional Checkup (Cycle {cycle})", - stage="M1", - input_data={"analyzers": list(results.keys()), "selected_analyzers": entry.get("selected_analyzers", [])}, - metadata={"duration_sec": duration_sec, "artifacts": { - "artifact_paths": artifact_paths, "figures": [str(p) for p in png_figures], - }}, - ) - if judge_prompt or judge_raw: - self.tracer.log_generation( - name="M1 Analyzer Selection", model="judge", - prompt=judge_prompt or "", completion=judge_raw or "", span_id=m1_span, - ) - for name, r in results.items(): - findings = getattr(r, "findings", {}) or {} - per_case = findings.get("per_case") or [] - probe_span = self.tracer.start_span( - name=f"Probe: {name}", stage=f"M1_{name}", input_data={"probe": name}, - parent_id=m1_span, - metadata={ - "n_scored": len(per_case) if per_case else (findings.get("n_cases") or findings.get("n_scored")), - }, - ) - calls_for_analyzer = [c for c in pending_calls if c.get("analyzer") == name] - for call in calls_for_analyzer[:50]: - self.tracer.log_generation( - name=f"{name} · {call.get('method')} #{call.get('call_index')}", - model="target_model", prompt=call.get("inputs"), - completion=call.get("error") or call.get("output"), - span_id=probe_span, - metadata={"duration_sec": call.get("duration_sec"), "error": call.get("error")}, - ) - self.tracer.end_span(probe_span, output_data={ - "findings": findings, "n_model_calls": len(calls_for_analyzer), - }) - orphaned = {c["analyzer"] for c in pending_calls} - set(results) - for name in orphaned: - failed_span = self.tracer.start_span( - name=f"Probe: {name} (failed)", stage=f"M1_{name}", input_data={"probe": name}, - parent_id=m1_span, metadata={"note": "analyzer raised before producing a Result"}, - ) - calls_for_analyzer = [c for c in pending_calls if c.get("analyzer") == name] - for call in calls_for_analyzer[:50]: - self.tracer.log_generation( - name=f"{name} · {call.get('method')} #{call.get('call_index')}", - model="target_model", prompt=call.get("inputs"), - completion=call.get("error") or call.get("output"), - span_id=failed_span, - metadata={"duration_sec": call.get("duration_sec"), "error": call.get("error")}, - ) - self.tracer.end_span(failed_span, status="failed", output_data={ - "n_model_calls": len(calls_for_analyzer), - }) - self.tracer.end_span(m1_span, output_data={"n_probes": len(results)}) - return png_figures - - # ------------------------------------------------------------------ - # M2 — analysis + explore - # ------------------------------------------------------------------ - - def log_analysis( - self, cycle: int, report: "AnalysisReport", *, duration_sec: "float | None" = None, - ) -> None: - entry: dict[str, Any] = { - "ts": self._ts(), "cycle": cycle, - "severity": report.severity, - "n_findings": len(report.findings), - "findings": [str(f) for f in report.findings], - "narrative": report.narrative, - "descriptive_only": bool(getattr(report, "descriptive_only", False)), - } - stats_tool = getattr(report, "stats_tool", None) - if stats_tool: - entry["stats_tool"] = stats_tool - fallback_reason = getattr(report, "llm_fallback_reason", None) - if fallback_reason: - entry["llm_fallback_reason"] = fallback_reason - conclusion = getattr(report, "conclusion", None) - if conclusion: - entry["conclusion"] = conclusion - evidence_chain = getattr(report, "evidence_chain", None) - if evidence_chain: - entry["evidence_chain"] = list(evidence_chain) - stats_tool_results = getattr(report, "stats_tool_results", None) - if stats_tool_results: - entry["stats_tool_results"] = list(stats_tool_results) - visualizations = getattr(report, "visualizations", None) - if visualizations: - entry["visualizations"] = list(visualizations) - stats_plan = getattr(report, "stats_plan", None) - if stats_plan: - entry["stats_plan"] = stats_plan - stats_results = getattr(report, "stats_results", None) - if stats_results: - entry["stats_results"] = [r.to_dict() for r in stats_results] - corrected = getattr(report, "corrected_rejections", None) - if corrected: - entry["corrected_rejections"] = corrected - figures = getattr(report, "figures", None) - if figures: - entry["figures"] = [self._portable_path(f) for f in figures] - llm_prompt = getattr(report, "llm_prompt", None) - llm_raw = getattr(report, "llm_raw", None) - if llm_prompt: - entry["judge_prompt"] = llm_prompt - if llm_raw: - entry["judge_response"] = llm_raw - if duration_sec is not None: - entry["duration_sec"] = round(duration_sec, 3) - self._append_stage("M2", "analysis", entry) - if llm_prompt or llm_raw: - self.log_model_exchange( - "M2", role="statistics_judge", operation="generate", - inputs=llm_prompt or "", output=llm_raw or "", cycle=cycle, - duration_sec=duration_sec, - ) - - m2_span = self.tracer.start_span( - name=f"M2: Screening & Confirmatory Signals (Cycle {cycle})", stage="M2", - input_data={"severity": report.severity, "n_findings": len(report.findings)}, - metadata={"duration_sec": duration_sec, "stats_tool": stats_tool, - "artifacts": {"figures": [str(f) for f in (figures or [])]}}, - ) - if llm_prompt or llm_raw: - self.tracer.log_generation( - name="M2 Statistical Screening Analysis", model="judge", - prompt=llm_prompt or "", completion=llm_raw or "", span_id=m2_span, - ) - for s in (stats_results or []): - s_dict = s.to_dict() if hasattr(s, "to_dict") else (s if isinstance(s, dict) else {}) - sig_name = s_dict.get("config", {}).get("signal") or s_dict.get("tool") or "signal" - eff = s_dict.get("effect") - if eff is not None: - self.tracer.log_score( - name=f"m2_effect_{sig_name}", value=float(eff), - comment=f"p={s_dict.get('p_value')}", span_id=m2_span, - ) - self.tracer.end_span(m2_span, output_data={"conclusion": conclusion or ""}) - - def log_explore( - self, cycle: int, report: "Any | None", *, - out_dir: "Path | str | None" = None, duration_sec: "float | None" = None, - ) -> None: - ok = bool(getattr(report, "ok", False)) if report is not None else False - charts = list(getattr(report, "charts", None) or []) if report is not None else [] - rendered = [ - str(c.get("figure_path")) for c in charts - if isinstance(c, dict) and c.get("figure_path") - ] - workspace = None - if out_dir is not None: - workspace = _inline_workspace( - out_dir, self._stage_artifacts_dir("M2"), run_dir=self.run_dir, - ) - if workspace and workspace.get("media"): - rendered = [ - path for path in workspace["media"] - if Path(path).suffix.lower() in {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"} - ] - tables = getattr(report, "tables", None) or {} - adjudication = dict(getattr(report, "adjudication", None) or {}) if report is not None else {} - entry: dict[str, Any] = { - "ts": self._ts(), "cycle": cycle, "ok": ok, - "n_observations": len(getattr(report, "observations", None) or []) if report is not None else 0, - "n_charts": len(charts), "n_charts_rendered": len(rendered), - "n_tables": len(tables) if isinstance(tables, dict) else len(list(tables or [])), - "n_candidate_signals": len(getattr(report, "candidate_signals", None) or []) if report is not None else 0, - "n_hypotheses": len(getattr(report, "hypotheses", None) or []) if report is not None else 0, - "adjudication": { - k: adjudication[k] for k in ( - "method", "alpha", "split", "n_host_adjudicated", "n_rejected", - "n_in_family", "n_descriptive_only", - ) if k in adjudication - }, - "observations": [str(o) for o in (getattr(report, "observations", None) or [])[:12]] if report is not None else [], - "caveats": [str(c) for c in (getattr(report, "caveats", None) or [])[:8]] if report is not None else [], - "figures": rendered, - "workspace_snapshot": workspace, - "attempts": int(getattr(report, "attempts", 0) or 0) if report is not None else 0, - } - error = str(getattr(report, "error", "") or "") if report is not None else "explorer produced no report" - if error: - entry["error"] = error - if out_dir is not None and workspace is None: - entry["out_dir"] = str(out_dir) - report_path = Path(out_dir) / "exploratory_report.json" - if report_path.exists(): - entry["report_path"] = str(report_path) - if report is not None and getattr(report, "code", None): - entry["code"] = str(report.code) - if report is not None and getattr(report, "raw_outputs", None): - entry["raw_outputs"] = [str(r) for r in report.raw_outputs] - if duration_sec is not None: - entry["duration_sec"] = round(duration_sec, 3) - self._append_stage("M2", "explore", entry) - for call in list(getattr(report, "model_calls", None) or []): - self.log_model_exchange( - "M2", - role=str(call.get("role") or "explore_coder"), - operation=str(call.get("operation") or "generate"), - inputs=call.get("inputs"), output=call.get("output"), - error=call.get("error"), duration_sec=call.get("duration_sec"), - metadata=dict(call.get("metadata") or {}), cycle=cycle, - ) - - exp_span = self.tracer.start_span( - name=f"Explore: Free-form EDA (Cycle {cycle})", stage="EXPLORE", - input_data={"ok": ok, "attempts": entry.get("attempts", 0)}, - metadata={"duration_sec": duration_sec, "artifacts": { - "out_dir": str(out_dir) if out_dir is not None else None, - "report_path": entry.get("report_path"), "figures": rendered, - }}, - ) - if report is not None: - for i, raw in enumerate(getattr(report, "raw_outputs", None) or []): - self.tracer.log_generation( - name=f"Explore Coder Agent (attempt {i + 1})", model="coder_agent", - prompt=None, completion=str(raw), span_id=exp_span, - ) - if getattr(report, "code", None): - self.tracer.log_generation( - name="Explore Analysis Code (analysis.py)", model="coder_agent", - prompt=None, completion=str(report.code), span_id=exp_span, - ) - self.tracer.end_span(exp_span, output_data={ - "n_observations": entry.get("n_observations", 0), - "n_candidate_signals": entry.get("n_candidate_signals", 0), - }) - - # ------------------------------------------------------------------ - # M3 — diagnosis - # ------------------------------------------------------------------ - - def log_diagnosis( - self, cycle: int, diag: "DiagnosisResult", *, - duration_sec: "float | None" = None, explore_figures: "list[str] | None" = None, - ) -> None: - entry: dict[str, Any] = { - "ts": self._ts(), "cycle": cycle, - "model_name": diag.model_name, - "n_hypotheses": len(diag.hypotheses), - "hypotheses": [ - { - # Join key for M4/M5 entries logged against this same - # hypothesis later (log_surgery/log_experiment/log_fix) — - # see evalrx.eval_agent.hypothesis.hypothesis_id. - "id": hypothesis_id(h), - "statement": h.statement, "plain_statement": h.plain_statement, - "failure_mode": h.predicted_failure_mode, - "status": h.status.value if h.status else None, - "test_design": h.test_design, - "critic": (h.metadata or {}).get("critic"), - "critic_reason": (h.metadata or {}).get("critic_reason"), - } - for h in diag.hypotheses - ], - "raw_judge_output": diag.raw_judge_output, - "n_critic_kept": int(getattr(diag, "n_critic_kept", 0) or 0), - "n_critic_rejected": int(getattr(diag, "n_critic_rejected", 0) or 0), - } - critic_raw = getattr(diag, "critic_raw_output", "") or "" - if critic_raw: - entry["critic_raw_output"] = critic_raw - entry["critic_prompt"] = getattr(diag, "critic_prompt", "") or "" - proposed = list(getattr(diag, "proposed_hypotheses", None) or []) - if proposed: - entry["proposed_hypotheses"] = [ - {"statement": h.statement, "plain_statement": h.plain_statement, - "failure_mode": h.predicted_failure_mode, "test_design": h.test_design} - for h in proposed - ] - review_decisions = list(getattr(diag, "review_decisions", None) or []) - if review_decisions: - entry["review"] = { - "n_kept": sum(d.get("decision") == "keep" for d in review_decisions), - "n_rejected": sum(d.get("decision") == "reject" for d in review_decisions), - "decisions": review_decisions, - } - referenced = getattr(diag, "referenced_charts", None) - if referenced: - entry["referenced_charts"] = list(referenced) - if getattr(diag, "explore_context_used", False): - entry["explore_context_used"] = True - if getattr(diag, "failure_modes_used", False): - entry["failure_modes_used"] = True - if explore_figures: - entry["explore_figures"] = list(explore_figures) - m3_prompt = getattr(diag, "prompt", None) or "" - if m3_prompt: - entry["judge_prompt"] = m3_prompt - review_prompt = getattr(diag, "review_prompt", None) or "" - review_raw = getattr(diag, "review_raw", None) or "" - if review_prompt or review_raw: - entry["review_prompt"] = review_prompt - entry["review_response"] = review_raw - if duration_sec is not None: - entry["duration_sec"] = round(duration_sec, 3) - self._append_stage("M3", "diagnosis", entry) - detailed_calls = list(getattr(diag, "model_calls", None) or []) - if detailed_calls: - for call in detailed_calls: - self.log_model_exchange( - "M3", - role=str(call.get("role") or "diagnosis_judge"), - operation=str(call.get("operation") or "generate"), - inputs=call.get("inputs"), output=call.get("output"), - error=call.get("error"), duration_sec=call.get("duration_sec"), - metadata=dict(call.get("metadata") or {}), cycle=cycle, - ) - else: - # Compatibility for DiagnosisResult values created by older callers. - if m3_prompt or diag.raw_judge_output: - self.log_model_exchange( - "M3", role="diagnosis_judge", operation="generate", - inputs=m3_prompt, output=diag.raw_judge_output or "", cycle=cycle, - duration_sec=duration_sec, - ) - if critic_raw or review_prompt or review_raw: - self.log_model_exchange( - "M3", role="hypothesis_critic", operation="generate", - inputs=entry.get("critic_prompt") or review_prompt, - output=critic_raw or review_raw, cycle=cycle, - ) - - m3_span = self.tracer.start_span( - name=f"M3: Root-Cause Diagnosis (Cycle {cycle})", stage="M3", - input_data={"model_name": diag.model_name, "n_hypotheses": len(diag.hypotheses)}, - metadata={"duration_sec": duration_sec}, - ) - self.tracer.log_generation( - name="AI Doctor Diagnostician", - model=str(self.tracer.trace_metadata.get("judge") or "diagnosis_judge"), - prompt=m3_prompt, completion=diag.raw_judge_output or "", span_id=m3_span, - metadata={"hypotheses": [h.statement for h in diag.hypotheses]}, - ) - if review_prompt or review_raw: - self.tracer.log_generation( - name="M3 Adversarial Evidence Review", - model=str(self.tracer.trace_metadata.get("judge") or "diagnosis_judge"), - prompt=review_prompt, completion=review_raw, span_id=m3_span, - metadata={"decisions": review_decisions}, - ) - self.tracer.end_span(m3_span, output_data={ - "n_hypotheses": len(diag.hypotheses), - "n_proposed": len(proposed) or len(diag.hypotheses), - "review": entry.get("review"), - }) - - # ------------------------------------------------------------------ - # M4/M5 — hypothesis verification & intervention - # ------------------------------------------------------------------ - - def log_surgery( - self, cycle: int, hypothesis: "Hypothesis", iv: "InterventionResult", *, - validation_cases: "Any | None" = None, duration_sec: "float | None" = None, - judge_prompt: "str | None" = None, judge_raw: "str | None" = None, - ) -> None: - """M4 (hypothesis verification) or M5 (intervention) — split on - whether "m4_test_name" is present in ``iv.evidence``.""" - is_m4 = "m4_test_name" in (iv.evidence or {}) - stage = "M4" if is_m4 else "M5" - entry: dict[str, Any] = { - "ts": self._ts(), "cycle": cycle, - "module": stage.lower(), - - # Joins this verdict back to its M3 hypotheses[] entry (same id). - "hypothesis_id": hypothesis_id(hypothesis), - "hypothesis": hypothesis.statement, - "failure_mode": hypothesis.predicted_failure_mode, - "status": iv.status.value, "fixed": iv.fixed, - "confidence_score": iv.confidence_score, - "evidence_dimensions": iv.evidence_dimensions, - "evidence": iv.evidence, - "n_refocused_cases": len(iv.new_data) if iv.new_data else None, - } - if is_m4: - candidates = _iter_cases(validation_cases) - if candidates: - snapshots = [_case_snapshot(case) for case in candidates] - snapshot = next( - (item for item in snapshots if str(item.get("outcome", "")).lower() == "fail"), - snapshots[0], - ) - entry["validation_examples"] = [{ - "id": f"m4-{snapshot.get('id')}", "kind": "validation_case", - "case_id": snapshot.get("id"), **snapshot, - "plain_reading": "This is one case in the independent validation pool. The verdict is determined from the full pool, not this case alone.", - "evidence_scope": "one case in the independent validation pool", - }] - if judge_prompt: - entry["judge_prompt"] = judge_prompt - if judge_raw: - entry["judge_response"] = judge_raw - if duration_sec is not None: - entry["duration_sec"] = round(duration_sec, 3) - self._append_stage(stage, "surgery", entry) - if judge_prompt or judge_raw: - self.log_model_exchange( - stage, role="protocol_consistency_judge", operation="generate", - inputs=judge_prompt or "", output=judge_raw or "", cycle=cycle, - duration_sec=duration_sec, - ) - - stage_title = "M4 Adjudication" if is_m4 else "M5 Intervention" - surg_span = self.tracer.start_span( - name=f"{stage_title}: {hypothesis.statement[:60]}", - stage="M4" if is_m4 else "M5_SURGERY", - input_data={"hypothesis": hypothesis.statement, "failure_mode": hypothesis.predicted_failure_mode}, - metadata={"status": iv.status.value, "fixed": iv.fixed, "confidence_score": iv.confidence_score}, - ) - if judge_prompt or judge_raw: - self.tracer.log_generation( - name=f"{stage_title}: Protocol Consistency Judge", model="judge", - prompt=judge_prompt or "", completion=judge_raw or "", span_id=surg_span, - ) - if iv.confidence_score is not None: - self.tracer.log_score( - name="adjudication_confidence", value=float(iv.confidence_score), - comment=f"status={iv.status.value}, fixed={iv.fixed}", span_id=surg_span, - ) - self.tracer.end_span(surg_span, output_data={"evidence": iv.evidence or {}}) - - def log_experiment( - self, cycle: int, hypothesis: "Hypothesis", iv: "InterventionResult", *, - module: str = "m5", - ) -> None: - """The experiment the agent wrote and ran to test *hypothesis*. - - No separate ``experiments/``/``workspace/`` files: the generated - source (``exp["files"]``/``exp["code"]``), stdout/stderr, the coder - agent's raw narration, and the validation log are already plain - strings in *iv.experiment* and go straight into the entry as JSON - string values. - """ - exp = getattr(iv, "experiment", None) or {} - files = exp.get("files") or {} - if not files and exp.get("code"): - files = {"main.py": exp["code"]} - - # An "experiment" is always M4/M5-shaped content by definition, so it - # gets the same resolve-with-M5-floor treatment as its workspace - # media, rather than trusting `_append_stage`'s generic unroutable - # fallback (which would file a genuinely M5-ish record under - # run.json["unrouted"] if *module* is ever something the M1-M5 regex - # and alias table don't recognize). - stage = _resolve_stage(module) or "M5" - - workspace = None - workdir = exp.get("workdir") - if workdir: - workspace = _inline_workspace( - workdir, self._stage_artifacts_dir(stage), run_dir=self.run_dir, - ) - - entry: dict[str, Any] = { - "ts": self._ts(), "cycle": cycle, "module": module, - # Joins this experiment back to its M3 hypotheses[] entry (same id). - "hypothesis_id": hypothesis_id(hypothesis), - "hypothesis": hypothesis.statement, - "failure_mode": hypothesis.predicted_failure_mode, - "status": iv.status.value if iv.status else None, - "fixed": iv.fixed, - "provider": exp.get("provider"), "verdict": exp.get("verdict"), - "metrics": exp.get("metrics"), "returncode": exp.get("returncode"), - "timed_out": exp.get("timed_out"), "cli_usage": exp.get("cli_usage"), - "llm_calls": exp.get("llm_calls"), "sandbox_runs": exp.get("sandbox_runs"), - "code": files, - "stdout": exp.get("stdout"), "stderr": exp.get("stderr"), - "blueprint": exp.get("blueprint"), "cli_raw_output": exp.get("cli_raw_output"), - "validation_log": list(exp.get("validation_log") or []) or None, - "workspace_snapshot": workspace, - "trial_root": exp.get("trial_root"), - } - self._append_stage(stage, "experiment", entry) - for call in exp.get("model_calls") or []: - if isinstance(call, dict): - self.log_model_exchange( - stage, - role=str(call.get("role") or "experiment_writer"), - operation=str(call.get("operation") or "generate"), - inputs=call.get("inputs"), output=call.get("output"), - error=call.get("error"), duration_sec=call.get("duration_sec"), - metadata=call.get("metadata"), - ) - - exp_span = self.tracer.start_span( - name=f"{stage}: Experiment — {hypothesis.statement[:60]}", - stage=f"{stage}_EXPERIMENT", - input_data={"hypothesis": hypothesis.statement, "failure_mode": hypothesis.predicted_failure_mode}, - metadata={"provider": exp.get("provider"), "returncode": exp.get("returncode")}, - ) - cli_raw = exp.get("cli_raw_output") - if cli_raw: - self.tracer.log_generation( - name=f"{module.upper()} Coder Agent", model=str(exp.get("provider") or "coder_agent"), - prompt=None, completion=str(cli_raw), span_id=exp_span, - ) - vlog = exp.get("validation_log") - if vlog: - self.tracer.log_generation( - name=f"{module.upper()} Validation Log", model=str(exp.get("provider") or "coder_agent"), - prompt=None, completion="\n".join(str(x) for x in vlog), span_id=exp_span, - ) - self.tracer.end_span(exp_span, output_data={ - "status": entry.get("status"), "fixed": entry.get("fixed"), "verdict": entry.get("verdict"), - }) - - def log_fix(self, outcome: "Any") -> None: - """Post-loop fix module: the tiered repair attempt + recommendation. - - Per-case outputs are NOT popped out to a sibling ``outputs.jsonl`` — - they stay inline in ``M5/log.json`` under each candidate's own - ``"outputs"`` key. Fewer files was the whole point; a bulkier single - JSON is the intended trade for that. - """ - d = json.loads(json.dumps(outcome.to_dict(), ensure_ascii=False, default=str)) - for attempt in [*(d.get("attempted") or []), *(d.get("selection_attempted") or [])]: - trial_root = attempt.get("trial_root") - if trial_root: - attempt["workspace_snapshot"] = _inline_workspace( - trial_root, self._stage_artifacts_dir("M5"), - run_dir=self.run_dir, max_bytes=None, preserve_all=True, - ) - best_ref = d.get("best") - if isinstance(best_ref, dict): - best = best_ref - elif isinstance(best_ref, str): - best = next((a for a in d.get("attempted") or [] if a.get("name") == best_ref), {}) - else: - best = {} - entry: dict[str, Any] = {"ts": self._ts(), "cycle": -1, "module": "fix"} - entry.update(d) - entry["best"] = best - self._append_stage("M5", "fix", entry) - - fix_span = self.tracer.start_span( - name="M5: Targeted Repair & Confirmation", stage="M5_FIX", - input_data={"candidates_evaluated": len(d.get("attempted", []))}, - ) - if best.get("effect") is not None: - self.tracer.log_score( - name="repair_net_accuracy_gain", value=float(best.get("effect", 0.0)), - comment=f"cured={best.get('n_fixed')}, broken={best.get('n_broken')}", - span_id=fix_span, - ) - if (best.get("payload") or {}).get("prompt_template"): - self.tracer.log_generation( - name="Winning Repair Patch", model="evalrx_repair", - prompt="Repair Candidate Search", - completion=best["payload"]["prompt_template"], span_id=fix_span, - ) - self.tracer.end_span(fix_span, output_data={"selected": best.get("name")}) - - # ------------------------------------------------------------------ - # AgenticDiagnoseLoop dispatch layer — run-level, not stage content - # ------------------------------------------------------------------ - - def log_agent_decision( - self, step: int, *, action: str, params: "dict[str, Any] | None" = None, - rationale: str = "", valid: bool = True, repair_attempts: int = 0, - fallback_used: bool = False, judge_prompt: "str | None" = None, - judge_raw: "str | None" = None, duration_sec: "float | None" = None, - judge_calls: "list[dict[str, Any]] | None" = None, - ) -> None: - entry: dict[str, Any] = { - "ts": self._ts(), "step": step, "action": action, "params": params or {}, - "rationale": rationale, "valid": valid, "repair_attempts": repair_attempts, - "fallback_used": fallback_used, - } - if judge_prompt: - entry["judge_prompt"] = judge_prompt - if judge_raw: - entry["judge_response"] = judge_raw - if judge_calls: - entry["model_calls"] = json.loads(json.dumps(judge_calls, default=str)) - if duration_sec is not None: - entry["duration_sec"] = round(duration_sec, 3) - self._append_run("agent_decisions", entry) - - decision_span = self.tracer.start_span( - name=f"Agent Decision: step {step}", stage="AGENT_DECISION", - input_data={"action": action, "params": params or {}}, - metadata={"valid": valid, "repair_attempts": repair_attempts, "fallback_used": fallback_used}, - ) - if judge_prompt or judge_raw: - self.tracer.log_generation( - name="Agent Decision Judge", model="judge", - prompt=judge_prompt or "", completion=judge_raw or "", span_id=decision_span, - ) - self.tracer.end_span(decision_span, output_data={"action": action, "rationale": rationale}) - - def log_agent_tool( - self, step: int, *, tool: str, ok: bool, summary: str = "", - error: "str | None" = None, duration_sec: "float | None" = None, - ) -> None: - entry: dict[str, Any] = { - "ts": self._ts(), "step": step, "tool": tool, "ok": ok, "summary": summary, - } - if error is not None: - entry["error"] = error - if duration_sec is not None: - entry["duration_sec"] = round(duration_sec, 3) - self._append_run("agent_tool_calls", entry) - - def log_stage_skipped(self, stage: str, reason_code: str, *, cycle: int = -1, detail: str = "") -> None: - entry = {"ts": self._ts(), "stage": stage, "cycle": cycle, "reason_code": reason_code, "detail": detail} - self._append_stage(stage, "stage_skipped", entry) - span = self.tracer.start_span( - name=f"{stage}: skipped", stage=stage, - input_data={"reason_code": reason_code}, metadata={"detail": detail}, - ) - self.tracer.end_span(span, output_data={"reason_code": reason_code}, status="skipped") - - def log_loop_end( - self, report: "AutoDiagnoseReport", *, - tokens_used: "int | None" = None, timings: "dict[str, float] | None" = None, - ) -> None: - entry: dict[str, Any] = {"ts": self._ts(), "cycles": report.cycles} - if tokens_used is not None: - entry["tokens_used"] = tokens_used - if timings: - entry["timings_sec"] = {k: round(v, 3) for k, v in timings.items()} - entry["total_duration_sec"] = round(sum(timings.values()), 3) - if hasattr(report, "resolved"): - entry["resolved"] = report.resolved - hyps = getattr(report, "final_hypotheses", []) - entry["n_hypotheses"] = len(hyps) - entry["final_hypotheses"] = [ - {"statement": h.statement, "plain_statement": h.plain_statement, - "failure_mode": h.predicted_failure_mode, "status": h.status.value if h.status else None} - for h in hyps - ] - if hasattr(report, "stopped_by"): - entry["stopped_by"] = report.stopped_by - all_hyps = getattr(report, "all_hypotheses", []) - verified = getattr(report, "verified_hypotheses", []) - entry["n_hypotheses"] = len(all_hyps) - entry["n_verified"] = len(verified) - entry["verified_hypotheses"] = [ - {"statement": tr.hypothesis.statement, - "failure_mode": tr.hypothesis.predicted_failure_mode, - "status": tr.status.value, - "confidence": tr.confidence, - "protocol_consistent": tr.is_consistent_with_protocol, - "verdict": getattr(tr, "verdict", None)} - for tr in verified - ] - self._append_run("loop_end", entry) - - # ------------------------------------------------------------------ - # Tool synthesis (M1/M2 probes+stats tools, generated on demand) - # ------------------------------------------------------------------ - - def log_tool_codegen( - self, *, module: str, name: str, need: str, source: str, ok: bool, - code: str = "", prompt: str = "", raw_output: str = "", raw_stream: str = "", - error: str = "", stdout: str = "", cycle: "int | None" = None, - extra: "dict[str, Any] | None" = None, - ) -> None: - cyc = self.current_cycle if cycle is None else cycle - entry: dict[str, Any] = { - "ts": self._ts(), "cycle": cyc, "module": module, "tool_name": name, - "need": need, "source": source, "ok": ok, "error": error or None, - "code": code or None, "prompt": prompt or None, - "raw_output": raw_output or None, "raw_stream": raw_stream or None, - "stdout": stdout or None, - } - if extra: - entry.update(extra) - self._append_stage(module, "tool_codegen", entry) - if prompt or raw_stream or raw_output: - self.log_model_exchange( - _resolve_stage(module) or "M5", role="tool_codegen", - operation=source, inputs=prompt or "", - output=raw_stream or raw_output or code, - error=error or None, cycle=cyc, - metadata={"tool_name": name, "ok": ok}, - ) - - cg_span = self.tracer.start_span( - name=f"Tool Codegen: {module}/{name}", stage=f"CODEGEN_{module}", - input_data={"need": need, "source": source}, - metadata={"ok": ok, "error": error or None}, - ) - if prompt or raw_output: - self.tracer.log_generation( - name=f"Tool Synthesis: {name}", model=source, - prompt=prompt or "", completion=raw_stream or raw_output or code, span_id=cg_span, - ) - self.tracer.end_span(cg_span, output_data={"ok": ok, "code_chars": len(code or "")}) - - def log_tool_registry(self, cycle: int, module: str, generated: "list[Any]") -> None: - if not generated: - return - tools = [ - { - "name": getattr(g, "name", "tool"), "need": getattr(g, "need", ""), - "source": getattr(g, "source", ""), "code": getattr(g, "code", "") or None, - } - for g in generated - ] - self._append_stage(module, "tool_registry", { - "ts": self._ts(), "cycle": cycle, "module": module, "n_tools": len(tools), "tools": tools, - }) - - # ------------------------------------------------------------------ - # Lifecycle - # ------------------------------------------------------------------ - - def close(self) -> None: - """Flush every doc one last time and persist the Langfuse trace bundle.""" - if self._closed: - return - with self._lock: - self._flush_run() - for stage in _STAGES: - self._flush_stage(stage) - self.tracer.end_trace({ - "spans": len(self.tracer.spans), - "generations": len(self.tracer.generations), - "scores": len(self.tracer.scores), - }) - self.tracer.flush() - try: - self.tracer.export_bundle(self.run_dir / "langfuse_trace.json") - except Exception: # noqa: BLE001 - pass - # Offline runs need no retry queue once the complete JSON trace bundle - # has been exported. A live run keeps a non-empty queue for retry. - if self.tracer.mode == "offline" or self.tracer.outbox.pending_count() == 0: - try: - self._outbox_path.unlink(missing_ok=True) - self._outbox_path.parent.rmdir() - except OSError: - pass - self._closed = True - - def __enter__(self) -> "RunLoggerV2": - return self - - def __exit__(self, *exc_info: Any) -> None: - self.close() diff --git a/evalrx/eval_agent/run_metadata.py b/evalrx/eval_agent/run_metadata.py index 87c6405f..f9722c55 100644 --- a/evalrx/eval_agent/run_metadata.py +++ b/evalrx/eval_agent/run_metadata.py @@ -1,5 +1,5 @@ """Shared run-provenance and logging-wiring helpers used by both -``VLDiagnoseLoop`` (loop.py) and ``AgenticDiagnoseLoop`` (agentic/loop.py). +``VLDiagnoseLoop`` (loop.py) and its ``JudgePolicy`` (agentic/policy.py). """ from __future__ import annotations diff --git a/evalrx/eval_agent/stages/__init__.py b/evalrx/eval_agent/stages/__init__.py index 76799ba3..5d03c94b 100755 --- a/evalrx/eval_agent/stages/__init__.py +++ b/evalrx/eval_agent/stages/__init__.py @@ -22,8 +22,6 @@ adds LLM-written conclusion + evidence chain StatsAnalysisReport AnalysisReport subclass — adds conclusion, evidence_chain, qualitative_findings, protocol - stats_tool_agent.py StatsToolAgent selects/runs deterministic exploratory - stats tools and visualization specs stats_tools.py STATS_TOOL_CATALOG signal/label association, McNemar+e-value, Friedman, single-rate e-value, rank corr stats_tool_generator.py StatsToolGenerator LLM/CLI writes a new stats script when @@ -31,7 +29,7 @@ M3 — Diagnosis (hypothesis generation) diagnosis.py DiagnosisAgent LLM judge reads AnalysisReport → Hypothesis list; - falls back to threshold-derived hypotheses on NO_ISSUE + falls back to threshold-derived hypotheses on an empty proposal M5 — Surgery (fix proposal + execution) surgery.py SurgeryAgent four strategies: verify_fn → analyzer_params → diff --git a/evalrx/eval_agent/stages/case_discovery.py b/evalrx/eval_agent/stages/case_discovery.py index 3821757f..61616c26 100755 --- a/evalrx/eval_agent/stages/case_discovery.py +++ b/evalrx/eval_agent/stages/case_discovery.py @@ -6,16 +6,18 @@ M4 receives the PASS/FAIL labels it needs for statistical testing. """ -import json import re from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any, Callable, Iterable +from typing import TYPE_CHECKING, Any, Callable, Iterable, Literal +from pydantic import BaseModel, field_validator + +from evalrx.agent_runtime.judge_call import JudgeOutputError, ask_judge from evalrx.core.case import CaseBatch, FailureCase, Label from evalrx.eval_agent.prompts.case_discovery import _JUDGE_PROMPT if TYPE_CHECKING: - from evalrx.core.model import Model + from evalrx.core.model import Judge, Model from evalrx.eval_agent.stages.protocol import ExperimentProtocol @@ -66,7 +68,7 @@ class CaseDiscoveryAgent: def __init__( self, scorer: ScoreFn | None = None, - judge: "Model | None" = None, + judge: "Judge | None" = None, generation_kwargs: dict[str, Any] | None = None, include_unknown: bool = True, concurrency: int = 1, @@ -132,7 +134,7 @@ def _generate( """ workers = self._workers(model, len(cases)) if workers <= 1: - out = [] + out: "list[tuple[FailureCase, Any, Exception | None]]" = [] for case in cases: try: out.append((case, model.generate(case.inputs, **self.generation_kwargs), None)) @@ -207,22 +209,21 @@ def _judge_score( expected=case.expected, observed=observed, ) - raw = self.judge.generate(prompt) # type: ignore[union-attr] - text = str(raw).strip() - parsed = _parse_judge_json(text) - if parsed is not None: - return parsed - first_lines = "\n".join(text.splitlines()[:5]).upper() - if "PASS" in first_lines and "FAIL" not in first_lines: - return Label.PASS, "judge text contained PASS" - if "FAIL" in first_lines and "PASS" not in first_lines: - return Label.FAIL, "judge text contained FAIL" - first = text.splitlines()[0].strip().upper() if text else "" - if first.startswith("PASS"): - return Label.PASS, "judge first line was PASS" - if first.startswith("FAIL"): - return Label.FAIL, "judge first line was FAIL" - return Label.UNKNOWN, "judge output did not contain a parseable label" + try: + graded = ask_judge(self.judge, prompt, _CaseLabel, role="case_label").output + except JudgeOutputError as exc: + return Label.UNKNOWN, f"judge gave no valid label ({exc})" + return _coerce_label(graded.label), graded.reason + + +class _CaseLabel(BaseModel): + label: Literal["PASS", "FAIL", "UNKNOWN"] + reason: str = "judge returned a structured label" + + @field_validator("label", mode="before") + @classmethod + def _upper(cls, value: Any) -> Any: + return value.strip().upper() if isinstance(value, str) else value def _coerce_label(value: Label | bool | str) -> Label: @@ -238,23 +239,6 @@ def _coerce_label(value: Label | bool | str) -> Label: return Label.UNKNOWN -def _parse_judge_json(text: str) -> tuple[Label, str] | None: - raw = text.strip() - if raw.startswith("```"): - raw = re.sub(r"^```\w*\n?", "", raw) - raw = re.sub(r"\n?```\s*$", "", raw) - match = re.search(r"\{.*\}", raw, flags=re.DOTALL) - if not match: - return None - try: - payload = json.loads(match.group()) - except json.JSONDecodeError: - return None - label = _coerce_label(payload.get("label", "unknown")) - reason = str(payload.get("reason", "judge returned structured label")) - return label, reason - - def _heuristic_score(expected: Any, observed: str) -> Label: """Score simple expected-answer rubrics without an LLM judge. diff --git a/evalrx/eval_agent/stages/diagnosis.py b/evalrx/eval_agent/stages/diagnosis.py index 546b36b6..ea13a0ee 100755 --- a/evalrx/eval_agent/stages/diagnosis.py +++ b/evalrx/eval_agent/stages/diagnosis.py @@ -1,9 +1,9 @@ """M3 — DiagnosisAgent: synthesize analysis findings into falsifiable hypotheses. The agent reads the structured :class:`~evalrx.eval_agent.analysis.AnalysisReport` -produced by M2, formats it as a prompt, sends it to an LLM judge (Gemini by -default), and parses the response into :class:`~evalrx.eval_agent.hypothesis.Hypothesis` -objects. +produced by M2, formats it as a prompt, and asks the judge for a typed +:class:`Proposal` through :func:`~evalrx.agent_runtime.judge_call.ask_judge`. +A second call, the adversarial critic, returns a typed :class:`Review`. The judge model defaults to **Gemini** when ``GEMINI_API_KEY`` is set in the environment and no explicit judge is passed. @@ -22,25 +22,20 @@ from __future__ import annotations import json -import re -import time +import logging from dataclasses import dataclass, field -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, Literal -from evalrx.agent_runtime.json_shape import validate_json_shape +from pydantic import BaseModel, Field + +from evalrx.agent_runtime.judge_call import JudgeError, ask_judge from evalrx.analysis.plain_language import jargon_violation from evalrx.eval_agent.hypothesis import Hypothesis -from evalrx.eval_agent.prompts.diagnosis import ( - _DIAGNOSE_PROMPT, - _FORMAT_REPAIR_PROMPT, - _PLAIN_REPAIR_PROMPT, - _VALIDATE_PROMPT, -) +from evalrx.eval_agent.prompts.diagnosis import _DIAGNOSE_PROMPT, _VALIDATE_PROMPT if TYPE_CHECKING: from evalrx.analysis.analysis_module import AnalysisReport - from evalrx.core.model import Model - from evalrx.core.result import Result + from evalrx.core.model import Judge def _format_prior_section(prior_cycles: list[dict]) -> str: """Render prior cycle history as a context block for the diagnosis prompt.""" @@ -231,196 +226,66 @@ class DiagnosisResult: model_calls: list[dict[str, Any]] = field(default_factory=list) -_HYPOTHESIS_SCHEMA: dict = { - "type": "array", - "items": { - "type": "object", - "required": ["hypothesis", "failure_mode"], - "properties": { - "hypothesis": {"type": "string", "minLength": 10}, - "plain_statement": {"type": "string"}, - "failure_mode": {"type": "string", "minLength": 2}, - "expected_association": {"type": "string"}, - }, - }, -} +logger = logging.getLogger(__name__) -def _parse_hypotheses_json(raw: str, model_name: str) -> list[Hypothesis] | None: - """Try to parse *raw* as a JSON array of hypothesis objects. +class HypothesisDraft(BaseModel): + """One hypothesis as the judge proposes it.""" - Returns ``None`` when the response is not JSON or fails schema validation - so the caller can fall back to the text parser. - """ - text = raw.strip() - # Strip markdown code fences if present - if text.startswith("```"): - import re as _re - text = _re.sub(r"^```\w*\n?", "", text) - text = _re.sub(r"\n?```\s*$", "", text) - try: - data = json.loads(text) - except json.JSONDecodeError: - return None + hypothesis: str = Field(min_length=10, description="one-sentence falsifiable technical claim") + plain_statement: str = Field("", description="the same claim in one everyday sentence") + failure_mode: str = Field(pattern=r"^[a-z][a-z0-9_]*$", + description="snake_case tag naming the mechanism") + test: str = Field("", description="the evidence that verifies the claim") + expected_association: Literal["higher_on_failures", "lower_on_failures"] | None = None - errors = validate_json_shape(data, _HYPOTHESIS_SCHEMA) - if errors: - import logging as _logging - _logging.getLogger(__name__).debug( - "DiagnosisAgent JSON schema validation failed: %s", errors - ) - return None - return [ - Hypothesis( - statement=item["hypothesis"], - target_model=model_name, - predicted_failure_mode=item["failure_mode"], - plain_statement=str(item.get("plain_statement") or item.get("plain_language") or item.get("plain") or ""), - test_design=str(item.get("test", "")), - expected_association=str(item.get("expected_association", "")), - ) - for item in data - if item.get("hypothesis") and item.get("failure_mode") +class Proposal(BaseModel): + """M3's answer: up to three hypotheses, none when there is no problem.""" + + hypotheses: list[HypothesisDraft] = Field(max_length=3) + + +class ReviewDecision(BaseModel): + number: int = Field(ge=1, description="the hypothesis number in the list") + decision: Literal["keep", "reject"] + reason: str = Field(min_length=1) + + +class Review(BaseModel): + """The critic's answer: one decision per numbered hypothesis.""" + + decisions: list[ReviewDecision] + + +def _plain_language_problems(proposal: Proposal) -> str | None: + """Feedback for plain statements that fail the jargon check, or ``None``.""" + problems = [ + f"- hypothesis {i}'s plain_statement {reason}: {d.plain_statement!r}" + for i, d in enumerate(proposal.hypotheses, start=1) + for reason in [jargon_violation(d.plain_statement, d.hypothesis)] + if reason ] + if not problems: + return None + return ( + "Some plain_statement fields fail the plain-language check. Rewrite only " + "those, for an engineer who runs evaluations but does no statistics: no " + "statistics terms, acronyms or symbols, not a copy of the hypothesis, and " + "every number with what it amounts to. Keep every other field as it was.\n" + + "\n".join(problems) + ) -# A judge that answers in Markdown decorates the labels — ``**HYPOTHESIS:**``, -# ``**HYPOTHESIS**:``, ``- HYPOTHESIS:``, ``1. TEST:``, ``### FAILURE_MODE:`` — -# and the bare ``startswith("HYPOTHESIS:")`` check saw none of them: a live -# qwen3.5-2b/bbh_word_sorting run had three well-formed hypotheses in the -# response and M3 reported zero. Normalise the label, leave the text alone. -# -# The ordinal AFTER the label is the same bug and was missed the first time. -# ``HYPOTHESIS 1:`` is how a model numbers a list of three of them — the most -# natural formatting there is, and the one Opus used on a 560-case audio-visual -# run: three hypotheses, each with a test design naming a BH-surviving signal, -# and M3 again reported zero. Two and a half hours of GPU and a high-effort -# judge, discarded over a digit. Accept the ordinal in either position. -_LABEL_LINE = re.compile( - r"^\s*(?:(?:[-*•>]|#+|\d+[.)])\s*)*[*_`]*\s*" - r"(HYPOTHESIS|PLAIN_STATEMENT|PLAIN_LANGUAGE|FAILURE_MODE|TEST|EXPECTED_ASSOCIATION|KEEP|REJECT|REASON)" - r"(?:\s*[#(]?\d+[.)]?)?" # HYPOTHESIS 1: / TEST #2: / REASON (3): - r"\s*(?P[*_`]*)\s*:\s*(?P[*_`]*)\s*", - re.IGNORECASE, -) - - -#: A leading emphasis/code marker, past any list bullet or heading. Its presence -#: is what makes a marker after the colon a CLOSER rather than content. -_OPENING_MARKER = re.compile(r"^\s*(?:(?:[-*•>]|#+|\d+[.)])\s*)*[*_`]") - - -#: A value that is ENTIRELY one code span or emphasis pair: `mode`, **mode**. -_WRAPPED_VALUE = re.compile(r"^([*_`]{1,2})(.+?)\1$") - - -def _unwrap_value(value: str) -> str: - """Strip wrapping decoration from a value that is a bare identifier. - - Applied to FAILURE_MODE and EXPECTED_ASSOCIATION only. Those are looked up - verbatim -- ``_FAILURE_MODE_TO_ANALYZERS["ignored_obs"]`` decides which - analyzers the next cycle re-probes with -- so a judge writing - ``FAILURE_MODE: `ignored_obs` `` must not produce a key with a backtick in - it. Prose fields (HYPOTHESIS, TEST) keep their code spans: there the - backticks mark identifiers inside a sentence and removing them was its own - bug. - - Only an ENTIRELY wrapped value is unwrapped, so ``some `sig` text`` is left - exactly as written. - """ - text = value.strip() - m = _WRAPPED_VALUE.match(text) - return m.group(2).strip() if m else text - - -#: ``predicted_failure_mode`` given to a hypothesis whose ``FAILURE_MODE:`` line the -#: judge omitted. Downstream stages treat the mode as a tag, so an explicit -#: placeholder keeps the claim (statement / test design) instead of dropping it. -MISSING_FAILURE_MODE = "unspecified" - - -def _normalise_label_line(line: str) -> str: - """``**HYPOTHESIS:** foo`` / ``- FAILURE_MODE: bar`` → ``HYPOTHESIS: foo`` / - ``FAILURE_MODE: bar``. Lines without a recognised label are returned - stripped and otherwise untouched (emphasis inside the statement stays).""" - line = line.strip() - m = _LABEL_LINE.match(line) - if not m: - return line - - # Decoration is only decoration when something opened it. `**KEEP:** x` and - # `` `KEEP:` x `` wrap the LABEL, so the marker after the colon closes that - # wrapper and goes. `TEST: `modality_ablation.grounded_in_audio` ...` opens a - # code span belonging to the CONTENT, and eating it corrupts the identifier - # M4 routes on. The difference is whether the line opened with a marker at - # all -- so decide on that rather than on the marker's position. - opened = bool(_OPENING_MARKER.match(line)) - rest = line[m.end():] if opened else (m.group("after") or "") + line[m.end():] - rest = rest.strip() - if opened: - rest = re.sub(r"[*_`]+$", "", rest).strip() - return f"{m.group(1).upper()}: {rest}" - - -def _parse_hypotheses(raw: str, model_name: str) -> list[Hypothesis]: - """Parse hypothesis objects from LLM output. - - Tries JSON structured format first (more reliable), then falls back to the - line-oriented ``HYPOTHESIS:`` / ``FAILURE_MODE:`` text format. This makes - the parser resilient to both output modes without requiring a hard migration. - Labels may carry Markdown decoration (see :func:`_normalise_label_line`). - """ - json_result = _parse_hypotheses_json(raw, model_name) - if json_result is not None: - return json_result - - # Text-format fallback. A hypothesis is opened by ``HYPOTHESIS:`` and closed - # by ``FAILURE_MODE:`` — or, when the judge forgot that line, by the next - # ``HYPOTHESIS:`` / the end of the text. gemma-4-e2b / gsm8k (2026-08-27): - # the judge wrote three complete HYPOTHESIS / PLAIN_STATEMENT / TEST blocks - # without FAILURE_MODE and the old parser (append-on-FAILURE_MODE only) - # returned zero, so the loop stopped with "no_hypotheses" and the fix stage - # never ran. The mode is a tag; a missing tag must not erase the claim. - hypotheses: list[Hypothesis] = [] - pending: Hypothesis | None = None - - def _flush() -> None: - nonlocal pending - if pending is not None and pending.statement: - if not pending.predicted_failure_mode: - pending.predicted_failure_mode = MISSING_FAILURE_MODE - hypotheses.append(pending) - pending = None - - for line in raw.splitlines(): - line = _normalise_label_line(line) - upper = line.upper() - if upper.startswith("HYPOTHESIS:"): - _flush() - pending = Hypothesis( - statement=line[len("HYPOTHESIS:"):].strip(), - target_model=model_name, - predicted_failure_mode="", - ) - continue - target = pending if pending is not None else (hypotheses[-1] if hypotheses else None) - if upper.startswith("PLAIN_STATEMENT:") or upper.startswith("PLAIN_LANGUAGE:"): - tag = "PLAIN_STATEMENT:" if upper.startswith("PLAIN_STATEMENT:") else "PLAIN_LANGUAGE:" - if target is not None and not target.plain_statement: - target.plain_statement = line[len(tag):].strip() - elif upper.startswith("FAILURE_MODE:") and pending is not None: - pending.predicted_failure_mode = _unwrap_value(line[len("FAILURE_MODE:"):]) - _flush() - elif upper.startswith("TEST:") and target is not None: - # Attach the test design to the hypothesis being read (or the last one). - target.test_design = line[len("TEST:"):].strip() - elif upper.startswith("EXPECTED_ASSOCIATION:") and target is not None: - target.expected_association = _unwrap_value( - line[len("EXPECTED_ASSOCIATION:"):] - ).lower() - _flush() - return hypotheses +def _to_hypothesis(draft: HypothesisDraft, model_name: str) -> Hypothesis: + return Hypothesis( + statement=draft.hypothesis, + target_model=model_name, + predicted_failure_mode=draft.failure_mode, + plain_statement=draft.plain_statement, + test_design=draft.test, + expected_association=draft.expected_association or "", + ) def _format_label_context(cases: "Any | None") -> str: @@ -476,46 +341,35 @@ def _format_label_context(cases: "Any | None") -> str: def _validate_hypotheses( hypotheses: list[Hypothesis], findings_json: str, - judge: "Model", + judge: "Judge", *, capture: "dict[str, Any] | None" = None, context: str = "", ) -> list[Hypothesis]: - """Adversarial review of *hypotheses*: a critic call at temperature=0. + """Adversarial review of *hypotheses* by a second judge call. - The same judge is called a second time with a prompt designed to find - reasons to *reject* each hypothesis, breaking the confirmation-bias loop - where the model that generated a claim then waves it through. + The same judge is asked to find reasons to *reject* each hypothesis, + breaking the loop where the model that proposed a claim then waves it + through. - The critic ANNOTATES, it does not filter: every hypothesis comes back, + The critic ANNOTATES, it does not filter: every hypothesis comes back with ``metadata["critic"]`` set to ``"keep"`` / ``"reject"`` (``"unparsed"`` - when the critic's answer named neither), ``metadata["critic_reason"]`` - carrying its ``REASON:`` line, kept hypotheses ordered first. Dropping - the rejected ones used to end a run at "0 hypotheses" whenever a strict - critic (opus at high effort, n=32 evidence) rejected all of them — - three llm_benchmark runs in a row on 2026-08-20 — with no M4, M5 or fix - afterwards. M4 now tests on the held-out split, so the data decides; the - critic's verdict travels with the hypothesis as provenance and as the - tie-breaker for M5's best-lead ordering. - - *capture*, when given, receives ``raw`` (the critic's verbatim answer), - ``prompt``, ``n_kept`` and ``n_rejected``. Falls back to the unannotated - list if the critic call fails so the loop is never blocked by a transient - error. - - *context* is the evidence the PROPOSER worked from beyond the findings - JSON -- M2's conclusion and evidence chain, the statistical verdicts, the - explore notes and the label summary. Without it the critic judged the - hypotheses against less than the proposer had seen and rejected them for - missing evidence that was on the table (audiocaps 2026-08-20). + for one the critic gave no decision for) and ``metadata["critic_reason"]``, + kept hypotheses first. Dropping rejected ones used to end runs at "0 + hypotheses" with no M4, M5 or fix; M4 tests on held-out data, so the data + decides and the verdict travels with the hypothesis as provenance. + + *capture*, when given, receives ``prompt``, ``raw``, ``error``, + ``exchanges``, ``decisions``, ``n_kept`` and ``n_rejected``. When the + critic call fails, the hypotheses come back unannotated and every + decision reads ``review_unavailable``. + + *context* is the evidence the proposer worked from beyond the findings + JSON, so the critic judges against what the proposer saw. """ if not hypotheses: return hypotheses - - hyp_lines = "\n".join( - f"- HYPOTHESIS: {h.statement} (failure_mode: {h.predicted_failure_mode})" - for h in hypotheses - ) + capture = {} if capture is None else capture context_section = ( "\nContext the proposer worked from (analyst conclusion, evidence chain, " "statistical verdicts, exploratory notes, label summary):\n" @@ -524,106 +378,47 @@ def _validate_hypotheses( prompt = _VALIDATE_PROMPT.format( context_section=context_section, findings_json=findings_json, - hypotheses_text=hyp_lines, + hypotheses_text="\n".join( + f"{i}. {h.statement} (failure_mode: {h.predicted_failure_mode})" + for i, h in enumerate(hypotheses, start=1) + ), ) - if capture is not None: - capture["prompt"] = prompt - - started = time.perf_counter() + capture["prompt"] = prompt try: - # Use temperature=0 so the critic is deterministic and strict. - # Models that don't accept a temperature kwarg are called without it. - import inspect - sig = inspect.signature(judge.generate) - if "temperature" in sig.parameters: - raw = judge.generate(prompt, temperature=0) - else: - raw = judge.generate(prompt) - except Exception as exc: - if capture is not None: - # A transport failure must not silently delete ideas — and the - # record must distinguish it from an evidence-based rejection. - capture["decisions"] = [{ + reply = ask_judge(judge, prompt, Review, role="hypothesis_critic") + except JudgeError as exc: + logger.warning("DiagnosisAgent: the critic gave no usable review (%s); " + "keeping %d hypothesis(es) unreviewed", exc, len(hypotheses)) + capture.update( + raw=exc.raw, error=str(exc), exchanges=exc.exchanges, n_kept=0, n_rejected=0, + decisions=[{ "statement": h.statement, "decision": "review_unavailable", - "reason": "The adversarial review call failed; proposal retained.", - } for h in hypotheses] - capture["error"] = str(exc) - capture["duration_sec"] = time.perf_counter() - started - return hypotheses # validation failed — keep originals, unannotated - raw = str(raw) - if capture is not None: - capture["raw"] = raw - capture["error"] = None - capture["duration_sec"] = time.perf_counter() - started - - def _match(stmt: str) -> "Hypothesis | None": - stmt = stmt.strip().lower() - for h in hypotheses: - hs = h.statement.lower() - if hs[:60] in stmt or stmt[:60] in hs: - return h - return None - - verdicts: dict[int, str] = {} - reasons: dict[int, str] = {} - last: "Hypothesis | None" = None - saw_decision = False - for line in raw.splitlines(): - line = _normalise_label_line(line) - upper = line.upper() - if upper.startswith("KEEP:") or upper.startswith("REJECT:"): - saw_decision = True - verdict = "keep" if upper.startswith("KEEP:") else "reject" - h = _match(line.split(":", 1)[1]) - if h is not None: - verdicts[id(h)] = verdict - last = h - else: - last = None - elif upper.startswith("REASON:") and last is not None: - reasons[id(last)] = line[len("REASON:"):].strip() - - if not saw_decision: - # Malformed/empty critic output is an infrastructure failure: keep the - # proposals, say so, and mark them so the record shows no review ran. - import logging as _logging - _logging.getLogger(__name__).warning( - "DiagnosisAgent validation: critic response could not be parsed for " - "%d hypothesis(es) — keeping them unreviewed", - len(hypotheses), + "reason": "The adversarial review produced no usable answer; proposal retained.", + } for h in hypotheses], ) - for h in hypotheses: - h.metadata["critic"] = "unparsed" - if capture is not None: - capture.update(n_kept=0, n_rejected=0, decisions=_critic_decisions(hypotheses)) return hypotheses + for d in reply.output.decisions: + if d.number <= len(hypotheses): + hypotheses[d.number - 1].metadata.update(critic=d.decision, critic_reason=d.reason) for h in hypotheses: - h.metadata["critic"] = verdicts.get(id(h), "unparsed") - if id(h) in reasons: - h.metadata["critic_reason"] = reasons[id(h)] - n_kept = sum(1 for h in hypotheses if h.metadata.get("critic") == "keep") - n_rejected = sum(1 for h in hypotheses if h.metadata.get("critic") == "reject") - if capture is not None: - capture.update(n_kept=n_kept, n_rejected=n_rejected, - decisions=_critic_decisions(hypotheses)) + h.metadata.setdefault("critic", "unparsed") + n_kept = sum(1 for h in hypotheses if h.metadata["critic"] == "keep") + n_rejected = sum(1 for h in hypotheses if h.metadata["critic"] == "reject") + capture.update(raw=reply.raw, error=None, exchanges=reply.exchanges, + n_kept=n_kept, n_rejected=n_rejected, decisions=_critic_decisions(hypotheses)) if n_rejected and not n_kept: - import logging as _logging - _logging.getLogger(__name__).info( - "DiagnosisAgent validation: critic rejected all %d hypothesis(es) — " - "kept as flagged leads; M4 testing decides", - len(hypotheses), - ) + logger.info("DiagnosisAgent: the critic rejected all %d hypothesis(es); " + "kept as flagged leads, M4 testing decides", len(hypotheses)) order = {"keep": 0, "unparsed": 1, "reject": 2} - return sorted(hypotheses, key=lambda h: order.get(h.metadata.get("critic"), 1)) + return sorted(hypotheses, key=lambda h: order.get(h.metadata["critic"], 1)) def _critic_decisions(hypotheses: list[Hypothesis]) -> list[dict[str, Any]]: """Per-hypothesis review record derived from the critic's annotations: the ``{statement, decision, reason}`` shape the run log, report and Langfuse - consume. ``decision`` is ``keep`` / ``reject`` / ``unparsed`` (or - ``review_unavailable`` when the critic call itself failed). The critic - never removes a hypothesis, so this is a record, not a filter.""" + consume. The critic never removes a hypothesis, so this is a record, not a + filter.""" return [{ "statement": h.statement, "decision": str(h.metadata.get("critic", "unparsed")), @@ -631,7 +426,7 @@ def _critic_decisions(hypotheses: list[Hypothesis]) -> list[dict[str, Any]]: } for h in hypotheses] -def _default_judge() -> "Model": +def _default_judge() -> "Judge": """Return a judge model without requiring an explicit API key. Resolution order: @@ -673,7 +468,7 @@ class DiagnosisAgent: def __init__( self, - judge: "Model | None" = None, + judge: "Judge | None" = None, api_key: str | None = None, model_id: str = "gemini-2.0-flash", ) -> None: @@ -684,114 +479,18 @@ def __init__( self._judge = judge # None → resolved lazily on first call @property - def judge(self) -> "Model": + def judge(self) -> "Judge": if self._judge is None: self._judge = _default_judge() return self._judge @judge.setter - def judge(self, value: "Model") -> None: + def judge(self, value: "Judge") -> None: self._judge = value - def _reask_for_format(self, raw: str, model_name: str) -> tuple[str, list[Hypothesis]]: - """One re-ask when a non-empty, non-NO_ISSUE answer parsed to zero hypotheses. - - gemma-4-e2b / gsm8k (2026-08-27): the judge wrote three hypotheses in prose - blocks the label parser could not read and the run ended with - ``no_hypotheses`` — no warning, no second chance, no fix stage. The - label format is the contract, but a single formatting miss should cost - one more judge call, not the diagnosis. Returns the answer that was - finally parsed (so ``raw_judge_output`` records what the hypotheses came - from) and the hypotheses; on any failure the original answer and the - empty list come back and the existing fallbacks apply. - """ - text = raw.strip() - if not text or "NO_ISSUE" in text.upper(): - return raw, [] - import logging - - log = logging.getLogger(__name__) - log.warning( - "DiagnosisAgent: the judge wrote %d chars that parsed to zero hypotheses; " - "re-asking once for the labelled format: %r", len(text), text[:160], - ) - repair_prompt = _FORMAT_REPAIR_PROMPT.format(raw=raw) - started = time.perf_counter() - try: - reasked = str(self.judge.generate(repair_prompt)) - except Exception as exc: # noqa: BLE001 - self._model_calls.append({ - "role": "diagnosis_format_repair", "operation": "generate", - "inputs": repair_prompt, "output": None, "error": str(exc), - "duration_sec": time.perf_counter() - started, - }) - log.warning("DiagnosisAgent: format re-ask failed: %s", exc) - return raw, [] - self._model_calls.append({ - "role": "diagnosis_format_repair", "operation": "generate", - "inputs": repair_prompt, "output": reasked, "error": None, - "duration_sec": time.perf_counter() - started, - }) - hypotheses = _parse_hypotheses(reasked, model_name) - if hypotheses: - return reasked, hypotheses - if "NO_ISSUE" in reasked.upper(): - return reasked, [] - log.warning("DiagnosisAgent: the re-asked answer also parsed to zero hypotheses") - return raw, [] - - def _repair_plain_language( - self, raw: str, hypotheses: list[Hypothesis], model_name: str, - ) -> list[Hypothesis]: - """One bounded retry when a PLAIN_STATEMENT line is missing or jargon-y. - - The prompt asking for plain language is not enough on its own — a judge - will happily reuse the technical line — so the same host-side check the - explorer and the analysis-side hypothesis agent already run - (:func:`~evalrx.analysis.plain_language.jargon_violation`) also - guards this path, which is the one the benchmark runner takes. Never - raises: a failed repair keeps the original hypotheses, since a jargon-y - headline is worse than no diagnosis only for the reader, not for M4. - """ - if not hypotheses: - return hypotheses - violations = [ - f"hypothesis {i}'s PLAIN_STATEMENT {reason}: {h.plain_statement!r}" - for i, h in enumerate(hypotheses, start=1) - for reason in [jargon_violation(h.plain_statement, h.statement)] - if reason - ] - if not violations: - return hypotheses - repair_prompt = _PLAIN_REPAIR_PROMPT.format( - raw=raw, violations="\n".join(f"- {v}" for v in violations), - ) - started = time.perf_counter() - try: - repaired_raw = self.judge.generate(repair_prompt) - except Exception as exc: # noqa: BLE001 - self._model_calls.append({ - "role": "diagnosis_plain_language_repair", "operation": "generate", - "inputs": repair_prompt, "output": None, "error": str(exc), - "duration_sec": time.perf_counter() - started, - }) - import logging - - logging.getLogger(__name__).warning( - "DiagnosisAgent: plain-language repair failed: %s", exc) - return hypotheses - self._model_calls.append({ - "role": "diagnosis_plain_language_repair", "operation": "generate", - "inputs": repair_prompt, "output": str(repaired_raw), "error": None, - "duration_sec": time.perf_counter() - started, - }) - repaired = _parse_hypotheses(str(repaired_raw), model_name) - return repaired or hypotheses - def diagnose( self, - analysis: "AnalysisReport | dict[str, Result]", - model_name: str = "", + analysis: "AnalysisReport", prior_cycles: list[dict] | None = None, explore_context: "ExploreContext | None" = None, failure_modes: "Any | None" = None, @@ -800,11 +499,9 @@ def diagnose( """Synthesize *analysis* into a set of falsifiable hypotheses. Args: - analysis: An :class:`~evalrx.eval_agent.analysis.AnalysisReport` - from M2, or (for backward compatibility) a plain - ``{analyzer_name: Result}`` dict. - model_name: Ignored when *analysis* is an ``AnalysisReport`` - (the name is taken from the report). + analysis: The M2 report: an + :class:`~evalrx.analysis.analysis_module.AnalysisReport` + (``StatsAnalysisAgent`` returns a subclass). prior_cycles: Summary of previous M1→M5 cycles, from the caller. Each entry is ``{"cycle": int, "severity": str, "hypotheses": [{"statement", "failure_mode", "status"}]}``. @@ -823,14 +520,8 @@ def diagnose( Returns: :class:`DiagnosisResult` with zero or more hypotheses. """ - from evalrx.analysis.analysis_module import AnalysisModule, AnalysisReport - self._model_calls: list[dict[str, Any]] = [] - if not isinstance(analysis, AnalysisReport): - # Backward compat: wrap raw results in a minimal AnalysisReport. - analysis = AnalysisModule().analyze(analysis, model_name) - summary = {name: r.findings for name, r in analysis.raw_results.items()} # Prefer M2's LLM conclusion + evidence chain (StatsAnalysisReport) over @@ -883,7 +574,7 @@ def diagnose( prompt = _DIAGNOSE_PROMPT.format( prior_section=_format_prior_section(prior_cycles or []), - model_name=analysis.model_name or model_name, + model_name=analysis.model_name, severity=analysis.severity, protocol_section=protocol_section, conclusion=conclusion, @@ -894,7 +585,6 @@ def diagnose( available_signals_section=available_signals_section, findings_json=json.dumps(summary, indent=2, default=str), ) - import inspect as _inspect from pathlib import Path as _Path # M2's confirmatory figures, then the explorer's (UNCONFIRMED) charts. # The explore charts are attached to the M3 prompt ONLY — they never reach @@ -902,35 +592,16 @@ def diagnose( _figs = [_Path(f) for f in getattr(analysis, "figures", []) if _Path(f).exists()] if explore_context is not None: _figs += [_Path(f) for f in explore_context.figure_paths if _Path(f).exists()] - _sig = _inspect.signature(self.judge.generate) - started = time.perf_counter() - try: - if "images" in _sig.parameters and _figs: - raw = self.judge.generate(prompt, images=_figs) - else: - raw = self.judge.generate(prompt) - except Exception as exc: - self._model_calls.append({ - "role": "diagnosis_judge", "operation": "generate", - "inputs": {"prompt": prompt, "images": [str(f) for f in _figs]}, - "output": None, "error": str(exc), - "duration_sec": time.perf_counter() - started, - }) - raise - self._model_calls.append({ - "role": "diagnosis_judge", "operation": "generate", - "inputs": {"prompt": prompt, "images": [str(f) for f in _figs]}, - "output": str(raw), "error": None, - "duration_sec": time.perf_counter() - started, - }) - proposed_hypotheses = _parse_hypotheses(str(raw), analysis.model_name or model_name) - if not proposed_hypotheses: - raw, proposed_hypotheses = self._reask_for_format( - str(raw), analysis.model_name or model_name, - ) - proposed_hypotheses = self._repair_plain_language( - str(raw), proposed_hypotheses, analysis.model_name or model_name, + # A failed or unreadable proposal raises JudgeError with every exchange; + # the loop logs them and retries M3 or stops, instead of this stage + # standing in a guess for the judge's answer. + reply = ask_judge( + self.judge, prompt, Proposal, role="diagnosis_judge", + images=_figs, check=_plain_language_problems, ) + self._model_calls.extend(e.record() for e in reply.exchanges) + raw = reply.raw + proposed_hypotheses = [_to_hypothesis(d, analysis.model_name) for d in reply.output.hypotheses] hypotheses = list(proposed_hypotheses) # Adversarial validation: run a second critic call at temperature=0 to @@ -955,32 +626,14 @@ def diagnose( hypotheses, findings_json_str, self.judge, capture=critic, context=critic_context, ) - self._model_calls.append({ - "role": "hypothesis_critic", "operation": "generate", - "inputs": critic.get("prompt", ""), "output": critic.get("raw"), - "error": critic.get("error"), - "duration_sec": critic.get("duration_sec"), - }) - - # Fallback: if the judge returned NO_ISSUE but M2 has medium/high findings, - # auto-generate one hypothesis per finding so M5 can still run. - # This prevents self-diagnosis bias when the judge is the model under test. + self._model_calls.extend(e.record() for e in critic.get("exchanges", ())) + + # The judge saw no problem, but M2 has medium/high findings: one + # hypothesis per finding so M4 still tests them. This guards against + # self-diagnosis bias when the judge is the model under test. if not hypotheses and analysis.findings: from evalrx.analysis.analysis_module import _SEVERITY_ORDER - raw_text = str(raw or "").strip() - if raw_text and "NO_ISSUE" not in raw_text.upper(): - # Not a NO_ISSUE verdict: the judge proposed something the label - # parser could not read (gemma-4-e2b/bbh_causal_judgement 2026-08-22: - # ``**HYPOTHESIS 1:**``). Substituting templates silently turned a - # three-hypothesis diagnosis into "low self-consistency". - import logging - - logging.getLogger(__name__).warning( - "DiagnosisAgent: the judge wrote %d chars that parsed to zero hypotheses " - "(not NO_ISSUE); falling back to analysis-module template hypotheses — " - "check the label format in the response: %r", - len(raw_text), raw_text[:160], - ) + for finding in analysis.findings: if _SEVERITY_ORDER.get(finding.severity, 0) >= 2: # medium or high hypotheses.append(Hypothesis( @@ -988,12 +641,12 @@ def diagnose( f"The model {finding.message} " f"({finding.analyzer}.{finding.metric}={finding.value:.3g})" ), - target_model=analysis.model_name or model_name, + target_model=analysis.model_name, predicted_failure_mode=finding.analyzer, )) return DiagnosisResult( - model_name=analysis.model_name or model_name, + model_name=analysis.model_name, hypotheses=hypotheses, findings_summary=summary, raw_judge_output=str(raw), diff --git a/evalrx/eval_agent/stages/experiment_code.py b/evalrx/eval_agent/stages/experiment_code.py new file mode 100644 index 00000000..8a1a2f1a --- /dev/null +++ b/evalrx/eval_agent/stages/experiment_code.py @@ -0,0 +1,318 @@ +"""Reading and checking the code an experiment writer produces. + +Pulling files out of an LLM reply, summarising a file for the next one's +prompt, and the static checks run before anything executes: syntax, a main +guard, resolvable cross-file imports, and no model load on an artifacts-only +run. +""" + +from __future__ import annotations + +import ast +import json +import re +from typing import Any + + +def extract_code_block(text: str) -> str: + """Extract the first ```python … ``` block, or the raw text if none found.""" + m = re.search(r"```(?:python)?\s*\n(.*?)```", text, re.DOTALL) + if m: + return m.group(1).strip() + lines = text.strip().splitlines() + if lines and lines[0].startswith("```"): + lines = lines[1:] + if lines and lines[-1].strip() == "```": + lines = lines[:-1] + return "\n".join(lines).strip() + + +def extract_single_file_code(content: str, expected_name: str) -> str: + """Extract Python code from LLM response for a single named file.""" + m = re.search(r"```python\s*\n(.*?)```", content, re.DOTALL) + if m: + return m.group(1).strip() + m = re.search( + rf"```(?:filename:)?{re.escape(expected_name)}\s*\n(.*?)```", + content, re.DOTALL, + ) + if m: + return m.group(1).strip() + stripped = content.strip() + if stripped and stripped.startswith( + ("import ", "from ", "#", "def ", "class ", '"""') + ): + return stripped + return "" + + +def extract_files(content: str) -> dict[str, str]: + """Extract multi-file blocks from LLM output. + + Recognises both: + ```filename:foo.py + ...code... + ``` + and: + ```python # foo.py + ...code... + ``` + """ + files: dict[str, str] = {} + # Primary format: ```filename:xxx.py + for m in re.finditer( + r"```filename:([^\s`]+\.py)\s*\n(.*?)```", content, re.DOTALL + ): + fname = m.group(1).strip() + code = m.group(2).strip() + if fname and code: + files[fname] = code + if files: + return files + # Fallback: single ```python block → treat as main.py + block = re.search(r"```python\s*\n(.*?)```", content, re.DOTALL) + if block: + return {"main.py": block.group(1).strip()} + return files + + +def format_files(files: dict[str, str]) -> str: + parts = [f"```filename:{fname}\n{files[fname]}\n```" for fname in sorted(files)] + return "\n\n".join(parts) + + +def build_code_summary(filename: str, code: str) -> dict[str, Any]: + """Build a CodeMem-style AST summary (mirrors ARC's implementation).""" + summary: dict[str, Any] = { + "filename": filename, + "classes": [], + "functions": [], + "imports": [], + } + try: + tree = ast.parse(code) + except SyntaxError: + summary["parse_error"] = True + return summary + + for node in ast.walk(tree): + if isinstance(node, ast.ClassDef): + methods = [ + {"name": n.name, "args": [a.arg for a in n.args.args if a.arg != "self"]} + for n in node.body + if isinstance(n, ast.FunctionDef) + ] + summary["classes"].append({ + "name": node.name, + "bases": [ast.unparse(b) for b in node.bases], + "methods": methods, + }) + elif isinstance(node, ast.FunctionDef) and node.col_offset == 0: + summary["functions"].append({ + "name": node.name, + "args": [a.arg for a in node.args.args], + }) + elif isinstance(node, (ast.Import, ast.ImportFrom)): + try: + summary["imports"].append(ast.unparse(node)) + except Exception: + pass + + return summary + + +def parse_json(text: str) -> dict[str, Any] | None: + """Best-effort JSON extraction from LLM response.""" + def _as_dict(val: Any) -> dict[str, Any] | None: + return val if isinstance(val, dict) else None + + try: + return _as_dict(json.loads(text)) + except (json.JSONDecodeError, ValueError): + pass + m = re.search(r"```json\s*\n(.*?)```", text, re.DOTALL) + if m: + try: + return _as_dict(json.loads(m.group(1))) + except (json.JSONDecodeError, ValueError): + pass + m = re.search( + r"\{[^{}]*(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^{}]*)*\}", + text, re.DOTALL, + ) + if m: + try: + return _as_dict(json.loads(m.group(0))) + except (json.JSONDecodeError, ValueError): + pass + return None + + +def is_valid_blueprint(blueprint: dict[str, Any]) -> bool: + files = blueprint.get("files", []) + if not files or not isinstance(files, list): + return False + has_order = sum( + 1 for f in files if isinstance(f, dict) and "generation_order" in f + ) + return has_order >= 2 + + +def parse_error_location( + stderr: str, files: dict[str, str] +) -> tuple[str, int, str] | None: + """Parse Python traceback to find (filename, line_number, error_message).""" + known_files = set(files.keys()) + tb_pattern = re.compile(r'File "(?:[^"]*[/\\])?([^"]+\.py)", line (\d+)') + matches = list(tb_pattern.finditer(stderr)) + if not matches: + return None + for m in reversed(matches): + fname = m.group(1) + lineno = int(m.group(2)) + if fname in known_files: + lines = stderr.strip().split("\n") + error_msg = lines[-1] if lines else "Unknown error" + return fname, lineno, error_msg + return None + + +def hard_validate( + files: dict[str, str], *, forbid_model_load: bool +) -> tuple[list[str], list[str]]: + """Return (critical_issues, warnings).""" + critical: list[str] = [] + warnings: list[str] = [] + + # 1. Syntax errors — always critical + for fname, code in files.items(): + if not fname.endswith(".py"): + continue + try: + ast.parse(code) + except SyntaxError as exc: + critical.append( + f"[{fname}] SyntaxError at line {exc.lineno}: {exc.msg}" + ) + + # 2. main.py MUST have `if __name__ == "__main__":` block (BUG-R41-04) + main_code = files.get("main.py", "") + if main_code: + try: + main_tree = ast.parse(main_code) + has_main_guard = any( + isinstance(node, ast.If) + and isinstance(node.test, ast.Compare) + and isinstance(node.test.left, ast.Name) + and node.test.left.id == "__name__" + and len(node.test.comparators) == 1 + and isinstance(node.test.comparators[0], ast.Constant) + and node.test.comparators[0].value == "__main__" + for node in ast.walk(main_tree) + ) + if not has_main_guard: + critical.append( + '[main.py] Missing `if __name__ == "__main__":` block — ' + "script will define functions/classes but never execute. " + "Add a main guard that calls the experiment entry point." + ) + except SyntaxError: + pass # already caught above + + # 3. verdict line must be reachable in main.py (warning only) + if main_code and "verdict:" not in main_code: + warnings.append( + "[main.py] No 'verdict:' output found — " + "the script must print 'verdict: 1.0' or 'verdict: 0.0'" + ) + + # 4. Cross-file import consistency + known_modules = { + fname.replace(".py", "") + for fname in files + if fname.endswith(".py") + } + for fname, code in files.items(): + if not fname.endswith(".py"): + continue + try: + tree = ast.parse(code) + except SyntaxError: + continue + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom) and node.module: + mod_top = node.module.split(".")[0] + if mod_top in known_modules: + target_file = f"{mod_top}.py" + if target_file in files and node.names: + try: + target_tree = ast.parse(files[target_file]) + except SyntaxError: + continue + exported = { + n.name + for n in ast.walk(target_tree) + if isinstance(n, (ast.ClassDef, ast.FunctionDef)) + } + for alias in node.names: + name = alias.name + if name != "*" and name not in exported: + critical.append( + f"[{fname}] ImportError: '{name}' not " + f"defined in '{target_file}' — will crash" + ) + + if forbid_model_load and contains_forbidden_model_load(files): + critical.append( + "[project] Model reconstruction is forbidden in this artifact-only M5 " + "sandbox. Remove evalrx.load/compose/from_pretrained/model-client " + "construction and analyze the stored case artifacts; if those cannot " + "test the hypothesis, emit inconclusive: 1.0 without a verdict." + ) + + return critical, warnings + + +def contains_forbidden_model_load(files: dict[str, str]) -> bool: + """Detect heavyweight/network model construction in generated M5 code.""" + for name, code in files.items(): + if not name.endswith(".py"): + continue + try: + tree = ast.parse(code) + except SyntaxError: + continue + evalrx_aliases = {"evalrx"} + direct_loaders: set[str] = set() + model_classes: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + if alias.name == "evalrx": + evalrx_aliases.add(alias.asname or alias.name) + elif isinstance(node, ast.ImportFrom): + module = node.module or "" + for alias in node.names: + local = alias.asname or alias.name + if module == "evalrx" and alias.name in {"load", "compose"}: + direct_loaders.add(local) + if module.startswith(("transformers", "evalrx.models")) and ( + alias.name.startswith("AutoModel") or alias.name == "GeminiModel" + ): + model_classes.add(local) + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + fn = node.func + if isinstance(fn, ast.Attribute): + if fn.attr.startswith("from_pretrained"): + return True + if ( + fn.attr in {"load", "compose"} + and isinstance(fn.value, ast.Name) + and fn.value.id in evalrx_aliases + ): + return True + if isinstance(fn, ast.Name) and fn.id in direct_loaders | model_classes: + return True + return False diff --git a/evalrx/eval_agent/stages/experiment_writer.py b/evalrx/eval_agent/stages/experiment_writer.py index 393a7577..125c6d75 100755 --- a/evalrx/eval_agent/stages/experiment_writer.py +++ b/evalrx/eval_agent/stages/experiment_writer.py @@ -26,12 +26,10 @@ (or first .py file) and run once via ``sandbox.run_project()``. No exec-fix loop — the agent self-repairs during its own run. -Backward compatibility - The public ``write_and_run(hypothesis, model_context, cases_json, sandbox)`` - signature is unchanged. With default config the LLM path runs Phase 2 - (single-pass write) → Phase 3 → Phase 4, identical to the previous 3-phase - implementation. ``result.code`` always equals ``result.files["main.py"]`` - (or the single-file code) so existing callers are unaffected. +Defaults + With default config the LLM path runs Phase 2 (single-pass write) → + Phase 3 → Phase 4. ``result.code`` always equals + ``result.files["main.py"]`` (or the single-file code). """ from __future__ import annotations @@ -58,10 +56,22 @@ _WRITE_USER, build_cli_prompt, ) +from evalrx.eval_agent.stages.experiment_code import ( + build_code_summary, + contains_forbidden_model_load, + extract_code_block, + extract_files, + extract_single_file_code, + format_files, + hard_validate, + is_valid_blueprint, + parse_error_location, + parse_json, +) if TYPE_CHECKING: from evalrx.agent_runtime.sandbox import SandboxProtocol - from evalrx.core.model import Model + from evalrx.core.model import Judge, Model from evalrx.eval_agent.hypothesis import Hypothesis logger = logging.getLogger(__name__) @@ -116,7 +126,7 @@ class ExperimentWriterConfig: # Phase 6: review dialog (off by default) review_max_rounds: int = 0 - # CLI agent dispatch — None → LLM path (backward-compatible default) + # CLI agent dispatch — None → LLM path cli_agent: Any = None @@ -131,7 +141,6 @@ class ExperimentWriterResult: Attributes: code: ``files["main.py"]`` or the single-file code. - Kept for backward compatibility. files: Multi-file output dict. ``{}`` in single-file mode. blueprint: YAML spec produced in Phase 1; empty if disabled. metrics: ``{name: float}`` parsed from stdout. @@ -304,7 +313,7 @@ class ExperimentWriter: def __init__( self, - judge: "Model", + judge: "Judge", config: ExperimentWriterConfig = ExperimentWriterConfig(), ) -> None: self._judge = judge @@ -368,7 +377,7 @@ def write_and_run( if ( self._cfg.sequential_generation and blueprint_dict is not None - and self._is_valid_blueprint(blueprint_dict) + and is_valid_blueprint(blueprint_dict) ): files = self._phase2_sequential( hypothesis, model_context, cases_json, blueprint_yaml, blueprint_dict @@ -395,7 +404,7 @@ def write_and_run( if self._cfg.hard_validation and files: files = self._phase3_hard_validate(files, hypothesis, model_context, cases_json) - if self._forbid_model_load and self._contains_forbidden_model_load(files): + if self._forbid_model_load and contains_forbidden_model_load(files): message = ( "generated M5 code attempted to reconstruct or download a second model; " "execution blocked to protect the resident host model and GPU memory" @@ -566,15 +575,6 @@ def _parse_blueprint(self, yaml_text: str) -> dict[str, Any] | None: self._log_event(f" Blueprint YAML parse error: {exc}") return None - @staticmethod - def _is_valid_blueprint(blueprint: dict[str, Any]) -> bool: - files = blueprint.get("files", []) - if not files or not isinstance(files, list): - return False - has_order = sum( - 1 for f in files if isinstance(f, dict) and "generation_order" in f - ) - return has_order >= 2 # ------------------------------------------------------------------ # Phase 2a: Sequential file generation @@ -636,13 +636,13 @@ def _phase2_sequential( model_access_note=model_context.get("access_note", ""), ) raw = self._llm_call(system, user) - code = self._extract_single_file_code(raw, file_name) + code = extract_single_file_code(raw, file_name) if not code: self._log_event(f" WARNING: Empty code for {file_name}") continue generated[file_name] = code - code_memory[file_name] = self._build_code_summary(file_name, code) + code_memory[file_name] = build_code_summary(file_name, code) self._log_event( f" {file_name}: {len(code.splitlines())} lines, " f"{len(code_memory[file_name].get('classes', []))} classes" @@ -686,7 +686,7 @@ def _phase2_write( cases_json=cases_json, ) raw = self._llm_call(system, user) - code = self._extract_code_block(raw) + code = extract_code_block(raw) self._log_event(f" Script: {len(code)} chars") return code @@ -705,7 +705,7 @@ def _phase3_hard_validate( self._log_event("Phase 3: Hard validation") for attempt in range(self._cfg.hard_validation_max_repairs + 1): - critical, warnings = self._hard_validate(files) + critical, warnings = hard_validate(files, forbid_model_load=self._forbid_model_load) for w in warnings: self._log_event(f" WARNING: {w}") @@ -732,145 +732,6 @@ def _phase3_hard_validate( return files - def _hard_validate( - self, files: dict[str, str] - ) -> tuple[list[str], list[str]]: - """Return (critical_issues, warnings).""" - critical: list[str] = [] - warnings: list[str] = [] - - # 1. Syntax errors — always critical - for fname, code in files.items(): - if not fname.endswith(".py"): - continue - try: - ast.parse(code) - except SyntaxError as exc: - critical.append( - f"[{fname}] SyntaxError at line {exc.lineno}: {exc.msg}" - ) - - # 2. main.py MUST have `if __name__ == "__main__":` block (BUG-R41-04) - main_code = files.get("main.py", "") - if main_code: - try: - main_tree = ast.parse(main_code) - has_main_guard = any( - isinstance(node, ast.If) - and isinstance(node.test, ast.Compare) - and isinstance(node.test.left, ast.Name) - and node.test.left.id == "__name__" - and len(node.test.comparators) == 1 - and isinstance(node.test.comparators[0], ast.Constant) - and node.test.comparators[0].value == "__main__" - for node in ast.walk(main_tree) - ) - if not has_main_guard: - critical.append( - '[main.py] Missing `if __name__ == "__main__":` block — ' - "script will define functions/classes but never execute. " - "Add a main guard that calls the experiment entry point." - ) - except SyntaxError: - pass # already caught above - - # 3. verdict line must be reachable in main.py (warning only) - if main_code and "verdict:" not in main_code: - warnings.append( - "[main.py] No 'verdict:' output found — " - "the script must print 'verdict: 1.0' or 'verdict: 0.0'" - ) - - # 4. Cross-file import consistency - known_modules = { - fname.replace(".py", "") - for fname in files - if fname.endswith(".py") - } - for fname, code in files.items(): - if not fname.endswith(".py"): - continue - try: - tree = ast.parse(code) - except SyntaxError: - continue - for node in ast.walk(tree): - if isinstance(node, ast.ImportFrom) and node.module: - mod_top = node.module.split(".")[0] - if mod_top in known_modules: - target_file = f"{mod_top}.py" - if target_file in files and node.names: - try: - target_tree = ast.parse(files[target_file]) - except SyntaxError: - continue - exported = { - n.name - for n in ast.walk(target_tree) - if isinstance(n, (ast.ClassDef, ast.FunctionDef)) - } - for alias in node.names: - name = alias.name - if name != "*" and name not in exported: - critical.append( - f"[{fname}] ImportError: '{name}' not " - f"defined in '{target_file}' — will crash" - ) - - if self._forbid_model_load and self._contains_forbidden_model_load(files): - critical.append( - "[project] Model reconstruction is forbidden in this artifact-only M5 " - "sandbox. Remove evalrx.load/compose/from_pretrained/model-client " - "construction and analyze the stored case artifacts; if those cannot " - "test the hypothesis, emit inconclusive: 1.0 without a verdict." - ) - - return critical, warnings - - @staticmethod - def _contains_forbidden_model_load(files: dict[str, str]) -> bool: - """Detect heavyweight/network model construction in generated M5 code.""" - for name, code in files.items(): - if not name.endswith(".py"): - continue - try: - tree = ast.parse(code) - except SyntaxError: - continue - evalrx_aliases = {"evalrx"} - direct_loaders: set[str] = set() - model_classes: set[str] = set() - for node in ast.walk(tree): - if isinstance(node, ast.Import): - for alias in node.names: - if alias.name == "evalrx": - evalrx_aliases.add(alias.asname or alias.name) - elif isinstance(node, ast.ImportFrom): - module = node.module or "" - for alias in node.names: - local = alias.asname or alias.name - if module == "evalrx" and alias.name in {"load", "compose"}: - direct_loaders.add(local) - if module.startswith(("transformers", "evalrx.models")) and ( - alias.name.startswith("AutoModel") or alias.name == "GeminiModel" - ): - model_classes.add(local) - for node in ast.walk(tree): - if not isinstance(node, ast.Call): - continue - fn = node.func - if isinstance(fn, ast.Attribute): - if fn.attr.startswith("from_pretrained"): - return True - if ( - fn.attr in {"load", "compose"} - and isinstance(fn.value, ast.Name) - and fn.value.id in evalrx_aliases - ): - return True - if isinstance(fn, ast.Name) and fn.id in direct_loaders | model_classes: - return True - return False def _repair_critical_issues( self, @@ -890,7 +751,7 @@ def _repair_critical_issues( if not affected: affected.update(f for f in files if f.endswith(".py")) - files_ctx = self._format_files(files) + files_ctx = format_files(files) issues_text = "\n".join(f"- {issue}" for issue in critical_issues) prompt = ( @@ -908,7 +769,7 @@ def _repair_critical_issues( "You are an expert Python debugging engineer. Fix the code issues listed.", prompt, ) - fixed = self._extract_files(raw) + fixed = extract_files(raw) if fixed: merged = dict(files) merged.update(fixed) @@ -916,7 +777,7 @@ def _repair_critical_issues( return merged # Fall back to single-file repair if multi-file extraction failed if "main.py" in files: - single = self._extract_code_block(raw) + single = extract_code_block(raw) if single.strip(): result = dict(files) result["main.py"] = single @@ -969,7 +830,7 @@ def _fix_runtime_error( ) -> dict[str, str]: """Targeted or full-file repair after a sandbox crash (E-05 pattern).""" stderr_tail = result.stderr[-3000:] - error_loc = self._parse_error_location(stderr_tail, files) + error_loc = parse_error_location(stderr_tail, files) if error_loc: fname, lineno, error_msg = error_loc @@ -985,12 +846,12 @@ def _fix_runtime_error( _REPAIR_SYSTEM, _REPAIR_USER.format(error=stderr_tail[-2000:], code=code), ) - repaired_code = self._extract_code_block(repaired) + repaired_code = extract_code_block(repaired) if repaired_code.strip(): fname = next(iter(files)) return {fname: repaired_code} else: - files_ctx = self._format_files(files) + files_ctx = format_files(files) prompt = ( f"## Error\n```\n{stderr_tail}\n```\n\n" f"## Code\n{files_ctx}\n\n" @@ -999,7 +860,7 @@ def _fix_runtime_error( raw = self._llm_call( "You are a Python debugging expert. Fix the runtime error.", prompt ) - fixed = self._extract_files(raw) + fixed = extract_files(raw) if fixed: merged = dict(files) merged.update(fixed) @@ -1007,24 +868,6 @@ def _fix_runtime_error( return files - @staticmethod - def _parse_error_location( - stderr: str, files: dict[str, str] - ) -> tuple[str, int, str] | None: - """Parse Python traceback to find (filename, line_number, error_message).""" - known_files = set(files.keys()) - tb_pattern = re.compile(r'File "(?:[^"]*[/\\])?([^"]+\.py)", line (\d+)') - matches = list(tb_pattern.finditer(stderr)) - if not matches: - return None - for m in reversed(matches): - fname = m.group(1) - lineno = int(m.group(2)) - if fname in known_files: - lines = stderr.strip().split("\n") - error_msg = lines[-1] if lines else "Unknown error" - return fname, lineno, error_msg - return None def _targeted_file_repair( self, @@ -1051,7 +894,7 @@ def _targeted_file_repair( dep_summaries = "" for fname, fcode in files.items(): if fname != target_file and fname.endswith(".py"): - summary = self._build_code_summary(fname, fcode) + summary = build_code_summary(fname, fcode) dep_summaries += ( f"\n### {fname}: " f"{len(summary.get('classes', []))} classes, " @@ -1081,7 +924,7 @@ def _targeted_file_repair( "Output the COMPLETE fixed file.", prompt, ) - fixed = self._extract_files(raw) + fixed = extract_files(raw) if not fixed: m = re.search(r"```(?:python|filename:\S+)\s*\n(.*?)```", raw, re.DOTALL) if m: @@ -1221,12 +1064,12 @@ def _phase6_review( for r in range(self._cfg.review_max_rounds): rounds += 1 - files_ctx = self._format_files(files) + files_ctx = format_files(files) raw = self._llm_call( _REVIEW_SYSTEM, f"## Experiment Code\n{files_ctx}\n\nReturn JSON only.", ) - review = self._parse_json(raw) + review = parse_json(raw) if not isinstance(review, dict): self._log_event(f" Review round {r + 1}: could not parse JSON, skipping") break @@ -1254,7 +1097,7 @@ def _phase6_review( "You are an expert Python engineer. Fix the critical issues listed.", fix_prompt, ) - fixed = self._extract_files(fix_raw) + fixed = extract_files(fix_raw) if not fixed: break @@ -1353,7 +1196,7 @@ def _cli_write_and_run( code = cli_result.files.get("experiment.py") or next(iter(cli_result.files.values())) self._log_event(f" collected script: {len(code)} chars") - if self._forbid_model_load and self._contains_forbidden_model_load( + if self._forbid_model_load and contains_forbidden_model_load( {"experiment.py": code} ): message = ( @@ -1410,15 +1253,6 @@ def _cli_write_and_run( model_calls=list(self._model_calls), ) - @staticmethod - def _build_cli_prompt( - hypothesis: "Hypothesis", - model_context: dict[str, Any], - timeout_sec: int, - n_images: int = 0, - ) -> str: - """Backward-compatible wrapper for the external CLI-agent prompt.""" - return build_cli_prompt(hypothesis, model_context, timeout_sec, n_images=n_images) # ------------------------------------------------------------------ # Sandbox execution helpers @@ -1464,143 +1298,6 @@ def _run_files(self, files: dict[str, str], sandbox: Any) -> SandboxResult: ) return result - # ------------------------------------------------------------------ - # Code extraction helpers - # ------------------------------------------------------------------ - - @staticmethod - def _extract_code_block(text: str) -> str: - """Extract the first ```python … ``` block, or the raw text if none found.""" - m = re.search(r"```(?:python)?\s*\n(.*?)```", text, re.DOTALL) - if m: - return m.group(1).strip() - lines = text.strip().splitlines() - if lines and lines[0].startswith("```"): - lines = lines[1:] - if lines and lines[-1].strip() == "```": - lines = lines[:-1] - return "\n".join(lines).strip() - - @staticmethod - def _extract_single_file_code(content: str, expected_name: str) -> str: - """Extract Python code from LLM response for a single named file.""" - m = re.search(r"```python\s*\n(.*?)```", content, re.DOTALL) - if m: - return m.group(1).strip() - m = re.search( - rf"```(?:filename:)?{re.escape(expected_name)}\s*\n(.*?)```", - content, re.DOTALL, - ) - if m: - return m.group(1).strip() - stripped = content.strip() - if stripped and stripped.startswith( - ("import ", "from ", "#", "def ", "class ", '"""') - ): - return stripped - return "" - - @staticmethod - def _extract_files(content: str) -> dict[str, str]: - """Extract multi-file blocks from LLM output. - - Recognises both: - ```filename:foo.py - ...code... - ``` - and: - ```python # foo.py - ...code... - ``` - """ - files: dict[str, str] = {} - # Primary format: ```filename:xxx.py - for m in re.finditer( - r"```filename:([^\s`]+\.py)\s*\n(.*?)```", content, re.DOTALL - ): - fname = m.group(1).strip() - code = m.group(2).strip() - if fname and code: - files[fname] = code - if files: - return files - # Fallback: single ```python block → treat as main.py - m = re.search(r"```python\s*\n(.*?)```", content, re.DOTALL) - if m: - return {"main.py": m.group(1).strip()} - return files - - @staticmethod - def _format_files(files: dict[str, str]) -> str: - parts = [f"```filename:{fname}\n{files[fname]}\n```" for fname in sorted(files)] - return "\n\n".join(parts) - - @staticmethod - def _build_code_summary(filename: str, code: str) -> dict[str, Any]: - """Build a CodeMem-style AST summary (mirrors ARC's implementation).""" - summary: dict[str, Any] = { - "filename": filename, - "classes": [], - "functions": [], - "imports": [], - } - try: - tree = ast.parse(code) - except SyntaxError: - summary["parse_error"] = True - return summary - - for node in ast.walk(tree): - if isinstance(node, ast.ClassDef): - methods = [ - {"name": n.name, "args": [a.arg for a in n.args.args if a.arg != "self"]} - for n in node.body - if isinstance(n, ast.FunctionDef) - ] - summary["classes"].append({ - "name": node.name, - "bases": [ast.unparse(b) for b in node.bases], - "methods": methods, - }) - elif isinstance(node, ast.FunctionDef) and node.col_offset == 0: - summary["functions"].append({ - "name": node.name, - "args": [a.arg for a in node.args.args], - }) - elif isinstance(node, (ast.Import, ast.ImportFrom)): - try: - summary["imports"].append(ast.unparse(node)) - except Exception: - pass - - return summary - - @staticmethod - def _parse_json(text: str) -> dict[str, Any] | None: - """Best-effort JSON extraction from LLM response.""" - def _as_dict(val: Any) -> dict[str, Any] | None: - return val if isinstance(val, dict) else None - - try: - return _as_dict(json.loads(text)) - except (json.JSONDecodeError, ValueError): - pass - m = re.search(r"```json\s*\n(.*?)```", text, re.DOTALL) - if m: - try: - return _as_dict(json.loads(m.group(1))) - except (json.JSONDecodeError, ValueError): - pass - m = re.search( - r"\{[^{}]*(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^{}]*)*\}", - text, re.DOTALL, - ) - if m: - try: - return _as_dict(json.loads(m.group(0))) - except (json.JSONDecodeError, ValueError): - pass - return None # ------------------------------------------------------------------ # LLM call diff --git a/evalrx/eval_agent/stages/fix/agent.py b/evalrx/eval_agent/stages/fix/agent.py index 6d790ef0..213c25b4 100755 --- a/evalrx/eval_agent/stages/fix/agent.py +++ b/evalrx/eval_agent/stages/fix/agent.py @@ -94,7 +94,7 @@ if TYPE_CHECKING: from evalrx.agent_runtime.cli_types import CliAgentConfig from evalrx.core.case import CaseBatch, FailureCase - from evalrx.core.model import Model + from evalrx.core.model import Judge, Model from evalrx.eval_agent.hypothesis import Hypothesis logger = logging.getLogger(__name__) @@ -228,7 +228,7 @@ class FixAgent: def __init__( self, - judge: "Model | None" = None, + judge: "Judge | None" = None, max_tier: "str | FixTier" = FixTier.L2_SCAFFOLD, min_tier: "str | FixTier | None" = None, score_fn: "Callable[[FailureCase, str], Optional[bool]] | None" = None, diff --git a/evalrx/eval_agent/stages/fix/codegen.py b/evalrx/eval_agent/stages/fix/codegen.py index c5069e08..7bf2ccd3 100644 --- a/evalrx/eval_agent/stages/fix/codegen.py +++ b/evalrx/eval_agent/stages/fix/codegen.py @@ -30,7 +30,7 @@ if TYPE_CHECKING: from evalrx.agent_runtime.cli_types import CliAgentConfig from evalrx.core.case import CaseBatch, FailureCase - from evalrx.core.model import Model + from evalrx.core.model import Judge, Model from evalrx.eval_agent.run_context import Trial logger = logging.getLogger(__name__) @@ -104,7 +104,7 @@ class PipelineCoder: def __init__( self, *, - judge: "Model | None", + judge: "Judge | None", cli_config: "CliAgentConfig | None", allow_codegen: bool, score: "Callable[[FailureCase, str], Optional[bool]]", @@ -542,8 +542,7 @@ def _workdir(self, trial: "Trial | None" = None) -> str: With a *trial* (a ``RunContext`` is in play), each candidate gets its own durable ``/workspace/`` — no cross-attempt overwriting. - Without one (legacy / no ``RunContext``), falls back to a single - shared sandbox for the agent's lifetime, exactly as before. + Without one, a single shared sandbox serves the agent's lifetime. """ if trial is not None: return str(trial.workspace) diff --git a/evalrx/eval_agent/stages/fix/pipeline.py b/evalrx/eval_agent/stages/fix/pipeline.py index c86bf318..971c070b 100755 --- a/evalrx/eval_agent/stages/fix/pipeline.py +++ b/evalrx/eval_agent/stages/fix/pipeline.py @@ -51,12 +51,12 @@ from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass, field from pathlib import Path -from typing import TYPE_CHECKING, Any, Callable, Optional +from typing import TYPE_CHECKING, Any, Callable, Optional, cast from evalrx.eval_agent.stages.fix.tools import apply_image_ops, score_to_bool if TYPE_CHECKING: - from evalrx.core.case import CaseBatch + from evalrx.core.case import CaseBatch, FailureCase from evalrx.core.model import Model logger = logging.getLogger(__name__) @@ -330,7 +330,8 @@ def _serve(raw: str, request: "dict[str, Any]", case_id: str) -> bool: # sampling the record is the frozen baseline arm the paired test # compares against, so replaying it keeps anchor and baseline # identical (a resample could drift from both). - reply: "dict[str, Any]" = {"output": str(case.observed)} + # _replayable_direct is False for a missing case. + reply: "dict[str, Any]" = {"output": str(cast("FailureCase", case).observed)} with records_lock: res.n_replayed += 1 else: @@ -658,7 +659,7 @@ def _service_call( gen_kwargs["max_tokens"] = int(max_tokens_floor) # dataclasses.replace keeps .video/.audio (a bare Inputs(prompt=, # image=) dropped them — the same modality bug run_pipeline had). - if inp is not None and dataclasses.is_dataclass(inp): + if dataclasses.is_dataclass(inp) and not isinstance(inp, type): new_inputs = dataclasses.replace(inp, prompt=str(prompt), image=image) else: new_inputs = inputs_cls(prompt=str(prompt), image=image) diff --git a/evalrx/eval_agent/stages/fix/proposal.py b/evalrx/eval_agent/stages/fix/proposal.py index 229cef3e..24bfa0ee 100644 --- a/evalrx/eval_agent/stages/fix/proposal.py +++ b/evalrx/eval_agent/stages/fix/proposal.py @@ -13,8 +13,11 @@ import logging import re from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, Callable, Iterable +from typing import TYPE_CHECKING, Any, Callable, Iterable, TypeVar, cast +from pydantic import RootModel + +from evalrx.agent_runtime.judge_call import JudgeError, ask_judge from evalrx.eval_agent.prompts.fix_agent import ( _L1_PROMPT, _L2_PROMPT, @@ -42,11 +45,22 @@ if TYPE_CHECKING: from evalrx.core.case import CaseBatch - from evalrx.core.model import Model + from evalrx.core.model import Judge, Model from evalrx.eval_agent.hypothesis import Hypothesis logger = logging.getLogger(__name__) + +class _JudgeList(RootModel[list[dict[str, Any]]]): + """A fix judge's array of proposal objects.""" + + +class _JudgeObject(RootModel[dict[str, Any]]): + """A fix judge's single JSON object (the L4 recipe).""" + + +_T = TypeVar("_T", _JudgeList, _JudgeObject) + MAX_JUDGE_CANDIDATES = 3 @@ -329,7 +343,8 @@ def _chart_batch(tasks: "set[str]", has_images: bool) -> bool: name="upscale_count_extract", qualifies=_chart_batch, predicate=_chart_count_extract_predicate, - spec=lambda: builtin_spec("upscale_sharpen"), + # A BUILTIN_SPECS key, so never None. + spec=lambda: cast(PipelineSpec, builtin_spec("upscale_sharpen")), ), ) @@ -355,7 +370,8 @@ def enforce_generation_floor(candidates: "list[FixCandidate]", floor: "int | Non if not isinstance(gk, dict): continue try: - proposed = int(gk.get("max_tokens")) + proposed_raw: Any = gk.get("max_tokens") # may be absent or non-numeric + proposed = int(proposed_raw) except (TypeError, ValueError): continue if proposed < floor: @@ -378,7 +394,7 @@ class FixProposer: def __init__( self, *, - judge: "Model | None", + judge: "Judge | None", recorder: FixRecorder, coder: PipelineCoder, max_judge_candidates: int = MAX_JUDGE_CANDIDATES, @@ -584,12 +600,12 @@ def propose( for name in floor_names: if name in present or name in prior_names: continue - spec = self._default_spec(name) - if spec is not None: + floor_spec = self._default_spec(name) + if floor_spec is not None: candidates.append( FixCandidate( tier=FixTier.L2_SCAFFOLD, name=name, kind="spec", - source="floor", payload=spec.to_dict(), + source="floor", payload=floor_spec.to_dict(), ) ) if (not skip_lower_tiers and max_tier >= FixTier.L2_SCAFFOLD @@ -675,7 +691,7 @@ def resolve_max_tokens_floor(self, model: "Model | None", data: "CaseBatch") -> caps: "list[int]" = [] for case in data: meta = getattr(case, "metadata", {}) or {} - config = meta.get("generation_config") or {} + config: Any = meta.get("generation_config") or {} try: cap = int(config.get("max_tokens")) except (AttributeError, TypeError, ValueError): @@ -830,14 +846,14 @@ def _runtime_candidates( meta = getattr(case, "metadata", {}) or {} if str(meta.get("finish_reason", "")).lower() != "length": continue - config = meta.get("generation_config") or {} + config: Any = meta.get("generation_config") or {} try: cap = int(config.get("max_tokens")) except (AttributeError, TypeError, ValueError): continue if 1 <= cap < 8192: caps.append(cap) - policy = meta.get("generation_policy") or {} + policy: Any = meta.get("generation_policy") or {} try: policy_cap = int(policy.get("max_tokens_cap")) except (AttributeError, TypeError, ValueError): @@ -1452,51 +1468,27 @@ def _weight_edit_candidates( ] def _ask_judge_object(self, prompt: str) -> "dict[str, Any]": - """Single-JSON-object variant of :meth:`_ask_judge`.""" - if self._judge is None: - return {} - raw = "" - error = None - try: - raw = str(self._judge.generate(prompt)) - except Exception as exc: - logger.warning("FixAgent: judge call failed: %s", exc) - error = str(exc) - self.recorder.judge_exchange("fix_judge_object", prompt, raw, error=error) - return {} - self.recorder.judge_exchange("fix_judge_object", prompt, raw) - match = re.search( - r"\{.*\}", re.sub(r".*?", "", raw, flags=re.DOTALL), flags=re.DOTALL - ) - if not match: - return {} - try: - parsed = json.loads(match.group(0)) - except json.JSONDecodeError: - return {} - return parsed if isinstance(parsed, dict) else {} + """One JSON object from the judge, or ``{}`` when it gives none.""" + reply = self._ask(prompt, _JudgeObject, "fix_judge_object") + return dict(reply.root) if reply is not None else {} def _ask_judge(self, prompt: str) -> "list[dict[str, Any]]": + """A JSON array of proposal objects, or ``[]`` when the judge gives none. + + Each tier validates its own items (``PipelineSpec.from_dict``, the + catalog and primitive lookups), so only the array shape is checked here. + """ + reply = self._ask(prompt, _JudgeList, "fix_judge_list") + return list(reply.root) if reply is not None else [] + + def _ask(self, prompt: str, output_type: "type[_T]", operation: str) -> "_T | None": if self._judge is None: - return [] - raw = "" - error = None + return None try: - raw = str(self._judge.generate(prompt)) - except Exception as exc: - logger.warning("FixAgent: judge call failed: %s", exc) - error = str(exc) - self.recorder.judge_exchange("fix_judge_list", prompt, raw, error=error) - return [] - self.recorder.judge_exchange("fix_judge_list", prompt, raw) - match = re.search( - r"\[.*\]", re.sub(r".*?", "", raw, flags=re.DOTALL), flags=re.DOTALL - ) - if not match: - return [] - try: - parsed = json.loads(match.group(0)) - except json.JSONDecodeError: - logger.warning("FixAgent: unparseable judge proposal; using defaults") - return [] - return [p for p in parsed if isinstance(p, dict)] if isinstance(parsed, list) else [] + reply = ask_judge(self._judge, prompt, output_type, role="fix_judge") + except JudgeError as exc: + logger.warning("FixAgent: %s; using the tier's defaults", exc) + self.recorder.judge_exchanges(operation, exc.exchanges) + return None + self.recorder.judge_exchanges(operation, reply.exchanges) + return reply.output diff --git a/evalrx/eval_agent/stages/fix/recorder.py b/evalrx/eval_agent/stages/fix/recorder.py index ccfb6aa1..e88bc8ae 100644 --- a/evalrx/eval_agent/stages/fix/recorder.py +++ b/evalrx/eval_agent/stages/fix/recorder.py @@ -11,8 +11,9 @@ from typing import TYPE_CHECKING, Any if TYPE_CHECKING: - from collections.abc import Iterator + from collections.abc import Iterator, Sequence + from evalrx.agent_runtime.judge_call import Exchange from evalrx.core.case import CaseBatch from evalrx.core.model import Model from evalrx.eval_agent.run_context import Trial @@ -45,20 +46,20 @@ def outcome(self, outcome: "FixOutcome") -> None: except Exception as exc: # logging must never break the fix step logger.debug("FixAgent: log_fix failed: %s", exc) - def judge_exchange( - self, operation: str, prompt: str, output: str, *, error: "str | None" = None, - ) -> None: - """Best-effort detailed V2 model-call logging without changing V1.""" - fn = getattr(self.run_logger, "log_model_exchange", None) - if not callable(fn): + def judge_exchanges(self, operation: str, exchanges: "Sequence[Exchange]") -> None: + """Log every attempt of one fix-judge call; logging must never break repair.""" + if self.run_logger is None: return - try: - fn( - "M5", role="fix_judge", operation=operation, - inputs=prompt, output=output, error=error, - ) - except Exception as exc: # logging must never break repair - logger.debug("FixAgent: model exchange logging failed: %s", exc) + for exchange in exchanges: + call = exchange.record() + try: + self.run_logger.log_model_exchange( + "M5", role="fix_judge", operation=operation, + inputs=call["inputs"], output=call["output"], error=call["error"], + duration_sec=call["duration_sec"], metadata=call["metadata"], + ) + except Exception as exc: # logging must never break repair + logger.debug("FixAgent: model exchange logging failed: %s", exc) def target_exchange( self, @@ -71,11 +72,10 @@ def target_exchange( duration_sec: "float | None" = None, metadata: "dict[str, Any] | None" = None, ) -> None: - fn = getattr(self.run_logger, "log_model_exchange", None) - if not callable(fn): + if self.run_logger is None: return try: - fn( + self.run_logger.log_model_exchange( "M5", role="target_model", operation=operation, inputs=inputs, output=output, error=error, duration_sec=duration_sec, metadata={"case_id": case_id, **(metadata or {})}, @@ -109,33 +109,18 @@ def codegen( usage: "dict | None" = None, raw_stream: str = "", ) -> None: - """Log one codegen attempt; persist its prompt/code/thinking. + """Log one codegen attempt: its prompt, code and the coder's narration. - With a *trial*, the files live under ``trial.root`` (alongside the - rest of that attempt's record) instead of the run-global ``tools/`` — - only a lean event (paths via ``extra["trial_root"]``) goes through - :meth:`RunLogger.log_tool_codegen`, with no duplicate file copy. + The text goes into the event. With a *trial*, the event also names + ``trial.root`` so the attempt joins the workspace it ran in. """ - extra = ( + extra: "dict[str, Any] | None" = ( {"cli_usage": usage} if source.startswith("cli:") and usage else None ) - inline = bool(getattr(self.run_logger, "inline_text_artifacts", False)) - if trial is not None and not inline: - if prompt: - trial.write(f"{name}_prompt.txt", prompt) - if code: - trial.write(f"{name}_code.py", code) - if raw: - trial.write(f"{name}_agent_thinking.txt", raw) - if raw_stream: - trial.write(f"{name}_agent_raw_stream.txt", raw_stream) - extra = {**(extra or {}), "trial_root": str(trial.root)} - prompt, code, raw = "", "", "" - elif trial is not None: - # V2 keeps the exact prompt/code/response in M5/log.json. The - # trial workspace is ephemeral execution state and is snapshotted + if trial is not None: + # The trial workspace is ephemeral execution state, snapshotted # separately by log_experiment/log_fix. extra = {**(extra or {}), "trial_root": str(trial.root)} if self.run_logger is None: @@ -158,8 +143,8 @@ def codegen( logger.debug("FixAgent: log_tool_codegen failed: %s", exc) def instrument(self, model: "Model", data: "CaseBatch", analyzer: str) -> "Model": - """Wrap *model* so every call is logged, when the run keeps full model I/O.""" - if not getattr(self.run_logger, "preserve_full_model_io", False): + """Wrap *model* so every call is logged, when the run has a log.""" + if self.run_logger is None: return model from evalrx.eval_agent.model_instrumentation import InstrumentedModel diff --git a/evalrx/eval_agent/stages/fix/repair_catalog.py b/evalrx/eval_agent/stages/fix/repair_catalog.py index 9afec12f..edf7ca4f 100644 --- a/evalrx/eval_agent/stages/fix/repair_catalog.py +++ b/evalrx/eval_agent/stages/fix/repair_catalog.py @@ -55,7 +55,7 @@ def discover_methods( """Return physically executable repairs without consulting labels or data IDs.""" fidelity_fn = getattr(model, "paper_method_fidelity", None) - capabilities = getattr(model, "capabilities", frozenset()) + capabilities: frozenset[Capability] = getattr(model, "capabilities", frozenset()) inputs = frozenset( name for name, present in (("image", has_images), ("audio", has_audio)) if present ) diff --git a/evalrx/eval_agent/stages/fix/tools.py b/evalrx/eval_agent/stages/fix/tools.py index 09df1470..2fdacfda 100755 --- a/evalrx/eval_agent/stages/fix/tools.py +++ b/evalrx/eval_agent/stages/fix/tools.py @@ -117,7 +117,7 @@ def zoom_center(img, factor: float = 1.5): left, top = (w - cw) // 2, (h - ch) // 2 from PIL import Image - return img.crop((left, top, left + cw, top + ch)).resize((w, h), Image.LANCZOS) + return img.crop((left, top, left + cw, top + ch)).resize((w, h), Image.LANCZOS) # type: ignore[attr-defined] # alias set dynamically by Pillow def enhance_contrast(img, factor: float = 1.5): @@ -144,7 +144,7 @@ def upscale(img, factor: float = 2.0): from PIL import Image w, h = img.size - return img.resize((int(w * factor), int(h * factor)), Image.LANCZOS) + return img.resize((int(w * factor), int(h * factor)), Image.LANCZOS) # type: ignore[attr-defined] # alias set dynamically by Pillow def crop_region(img, box=(0.25, 0.25, 0.75, 0.75)): @@ -286,7 +286,7 @@ def crop_salient_region(img, padding: float = 0.05, min_delta: float = 18.0): bottom = min(h, int(ys.max()) + pad_px + 1) if right <= left or bottom <= top: return img - return rgb.crop((left, top, right, bottom)).resize((w, h), Image.LANCZOS) + return rgb.crop((left, top, right, bottom)).resize((w, h), Image.LANCZOS) # type: ignore[attr-defined] # alias set dynamically by Pillow def separate_horizontal_bands( @@ -458,6 +458,7 @@ def annotate_horizontal_band_count( banner_h = max(44, int(round(0.16 * h))) draw.rectangle([0, 0, w - 1, banner_h], fill=(255, 255, 255), outline=(0, 0, 0)) text = f"COUNT: {count}" + font: ImageFont.FreeTypeFont | ImageFont.ImageFont try: font = ImageFont.truetype("DejaVuSans-Bold.ttf", max(28, int(round(banner_h * 0.55)))) except Exception: @@ -714,7 +715,7 @@ def _safe_generation_kwargs(value: Any) -> "dict[str, Any]": only tune controls that are safe to replay and audit; this avoids a judge smuggling arbitrary provider arguments or callbacks into ``generate``. """ - raw = value if isinstance(value, dict) else {} + raw: Any = value if isinstance(value, dict) else {} out: "dict[str, Any]" = {} try: max_tokens = int(raw.get("max_tokens")) diff --git a/evalrx/eval_agent/stages/fix/types.py b/evalrx/eval_agent/stages/fix/types.py index 3723d979..b574b63d 100644 --- a/evalrx/eval_agent/stages/fix/types.py +++ b/evalrx/eval_agent/stages/fix/types.py @@ -177,7 +177,7 @@ def to_dict(self) -> "dict[str, Any]": "source": v.candidate.source, "payload": v.candidate.payload, # Self-contained attempt folder (see RunContext.new_trial) — - # None when no RunContext is in play (legacy flat layout). + # None when no RunContext is in play. "trial_root": (str(v.candidate.trial.root) if v.candidate.trial else None), "n_pairs": v.n_pairs, "n_baseline_correct": v.n_baseline_correct, diff --git a/evalrx/eval_agent/stages/fix/validation.py b/evalrx/eval_agent/stages/fix/validation.py index 0f1de24c..4c698838 100644 --- a/evalrx/eval_agent/stages/fix/validation.py +++ b/evalrx/eval_agent/stages/fix/validation.py @@ -277,12 +277,13 @@ def scores( max_tokens_floor: "int | None" = None, ) -> "dict[str, Optional[bool]]": """Per-case success of one candidate on *data*.""" - batch = { + runners: "dict[str, Callable[..., dict[str, Optional[bool]]]]" = { "primitive": self._run_primitive, "code": self._run_code, "finetune_spec": self._run_finetune, "weight_edit": self._run_weight_edit, - }.get(candidate.kind) + } + batch = runners.get(candidate.kind) if batch is not None: return batch(candidate, model, data, max_tokens_floor=max_tokens_floor) strategy = self.strategy(candidate) diff --git a/evalrx/eval_agent/stages/fix/verdict.py b/evalrx/eval_agent/stages/fix/verdict.py index 07c56230..44af010a 100644 --- a/evalrx/eval_agent/stages/fix/verdict.py +++ b/evalrx/eval_agent/stages/fix/verdict.py @@ -8,7 +8,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, cast from evalrx.eval_agent.stages.fix.internals import INTERNALS_PRIMITIVES from evalrx.eval_agent.stages.fix.repair_catalog import discover_methods, supports_tier @@ -47,7 +47,8 @@ def ebh_survivors(tested: "list[FixValidation]", alpha: float) -> "set[int]": """ if not tested: return set() - evalues = [float(v.e_value) for v in tested] + # Callers pass only validations that carry an e-value. + evalues = [float(cast(float, v.e_value)) for v in tested] return {id(tested[i]) for i in ebh(evalues, alpha=alpha)} diff --git a/evalrx/eval_agent/stages/hypothesis_tester.py b/evalrx/eval_agent/stages/hypothesis_tester.py index f7ab9bd0..f86f2c3f 100755 --- a/evalrx/eval_agent/stages/hypothesis_tester.py +++ b/evalrx/eval_agent/stages/hypothesis_tester.py @@ -49,7 +49,7 @@ if TYPE_CHECKING: from evalrx.analysis.stats_agent import StatsAnalysisReport from evalrx.analysis.stats_tools import StatsToolResult - from evalrx.core.model import Model + from evalrx.core.model import Judge from evalrx.eval_agent.stages.protocol import ExperimentProtocol logger = logging.getLogger(__name__) @@ -163,7 +163,7 @@ class HypothesisTester: def __init__( self, - judge: "Model | None" = None, + judge: "Judge | None" = None, alpha: float = 0.05, min_effect: float = 0.10, min_evidence_grade: str = "observational", @@ -318,8 +318,8 @@ def _test_one( verdict: str = core["verdict"] # ── Protocol consistency check ──────────────────────────────── - self._last_judge_prompt: "str | None" = None - self._last_judge_raw: "str | None" = None + self._last_judge_prompt = None + self._last_judge_raw = None is_consistent = self._check_protocol_consistency( hypothesis, stats_report, protocol ) @@ -414,6 +414,7 @@ def _agrees(r: "StatsToolResult") -> bool: consulted = [r.tool for r in relevant] + [r.tool for r in global_res] + chosen: "StatsToolResult | None" if supporting: chosen = max(supporting, key=lambda r: abs(r.effect or 0.0)) status = HypothesisStatus.SUPPORTED diff --git a/evalrx/eval_agent/stages/probe.py b/evalrx/eval_agent/stages/probe.py index b5408061..cbbe196a 100755 --- a/evalrx/eval_agent/stages/probe.py +++ b/evalrx/eval_agent/stages/probe.py @@ -199,36 +199,9 @@ class ModelKind(str, Enum): "path_patching", # which heads carry it to the answer "logprob_entropy", "self_consistency", ], - "text": [], # filled below from the legacy LLM list -} - -# Back-compat view: ``StrategyProbe(priority_override=...)`` and the docs are -# written against ModelKind keys. Composition is the default path; an override -# still selects one list by kind, exactly as before. -_PRIORITY: dict[str, list[str]] = { - ModelKind.VLM: [ - "pope", "chair", # hallucination metrics - "attention_knockout", # white-box: is the image READ at all? - "attention", "attention_rollout", # where is the model looking? - "attention_sink", # sink collapse? - "attention_sensitivity", # would looking more help? - "attention_temperature", # ... or looking more sharply / more broadly? - "prompt_contrast", # are failures prompt-repairable? - "mm_shap", # text vs image reliance - "gradcam", "generic_attention", # which image regions the answer depends on - "embed_lens", # what the image tokens mean at the LLM input - "causal_trace", # where the image's effect hands off - "attribution_patching", # ... estimated at every layer and token - "path_patching", # which heads carry it to the answer - "logprob_entropy", "self_consistency", - ], - ModelKind.AGENT: [ - "loop_detect", "ignored_obs", # behavioral heuristics - "first_error_judge", "trajectory_rubric", # LLM-judge localisation + classification - "counterfactual", "reliability_probe", # re-run probes: step perturbation, pass@k - "tool_shap", # re-run probe: tool-subset Shapley - ], - ModelKind.LLM: [ + # Every model has a prompt, so this is the floor every composition ends + # with rather than a peer of the media slots. + "text": [ # Hygiene first: both produce confounds that mimic every mechanism # column below, so a finding read before them is not interpretable. "answer_extraction_audit", # is the FAIL label real or a parse miss? @@ -258,20 +231,6 @@ class ModelKind(str, Enum): ], } -# text IS the legacy LLM list: every model has a prompt, so this is the floor -# every composition starts from rather than a peer of the media slots. -_SLOT_PRIORITY["text"] = _PRIORITY[ModelKind.LLM] - -# Slots each ModelKind stands for, in composition order. Only the back-compat -# ``_PRIORITY`` view and ``detect_kind`` read this; ``select`` uses the batch. -_KIND_SLOTS: dict[str, tuple[str, ...]] = { - ModelKind.AGENT: ("agent", "text"), - ModelKind.AVLM: ("audio", "image", "text"), - ModelKind.ALM: ("audio", "text"), - ModelKind.VLM: ("image", "text"), - ModelKind.LLM: ("text",), -} - def _compose(slots: "Iterable[str]") -> "list[str]": """Concatenate the slot lists in ranking order, first occurrence wins. @@ -286,12 +245,6 @@ def _compose(slots: "Iterable[str]") -> "list[str]": return list(dict.fromkeys(ordered)) -# ALM / AVLM complete the back-compat view; they never had an entry because the -# enum had no member for them. -for _kind, _slots in _KIND_SLOTS.items(): - _PRIORITY.setdefault(_kind, _compose(_slots)) - - def get_analyzer_catalog(model: "Model") -> dict[str, str]: """Return ``{name: description}`` for all analyzers compatible with *model*. @@ -321,8 +274,9 @@ class StrategyProbe: """Selects analyzers appropriate for a given model. Args: - priority_override: Replaces the built-in per-kind priority tables - (keyed by ``ModelKind``). Useful for domain-specific orderings. + priority_override: A table keyed by ``ModelKind`` that replaces the + ranking composed from ``_SLOT_PRIORITY``. It is an allowlist as + well as an ordering. """ def __init__(self, priority_override: dict[str, list[str]] | None = None) -> None: diff --git a/evalrx/eval_agent/stages/probe_agent.py b/evalrx/eval_agent/stages/probe_agent.py index d5a14f61..06bb0afc 100755 --- a/evalrx/eval_agent/stages/probe_agent.py +++ b/evalrx/eval_agent/stages/probe_agent.py @@ -58,7 +58,7 @@ if TYPE_CHECKING: from evalrx.core.analyzer import Analyzer from evalrx.core.case import CaseBatch - from evalrx.core.model import Model + from evalrx.core.model import Judge, Model from evalrx.core.result import Result from evalrx.eval_agent.stages.protocol import ExperimentProtocol, ProbingSchema @@ -67,7 +67,7 @@ # Capabilities that a containerised (API-based) model can satisfy. _BLACKBOX_CAPS = frozenset({Capability.GENERATE, Capability.LOGPROBS, Capability.TOOL_CALLS}) -def _is_blackbox_compatible(analyzer_cls: type) -> bool: +def _is_blackbox_compatible(analyzer_cls: "type[Analyzer]") -> bool: """True when the analyzer's requires are all satisfiable by a black-box API model.""" return analyzer_cls.requires <= _BLACKBOX_CAPS @@ -102,7 +102,7 @@ class ProbeAgent: def __init__( self, probe: StrategyProbe | None = None, - judge: "Model | None" = None, + judge: "Judge | None" = None, runner: ExperimentRunner | None = None, max_analyzers: int | None = None, analyzer_overrides: dict[str, "Analyzer"] | None = None, diff --git a/evalrx/eval_agent/stages/probe_candidate_generator.py b/evalrx/eval_agent/stages/probe_candidate_generator.py index 153b4f9c..056ca3f2 100644 --- a/evalrx/eval_agent/stages/probe_candidate_generator.py +++ b/evalrx/eval_agent/stages/probe_candidate_generator.py @@ -32,7 +32,7 @@ if TYPE_CHECKING: from evalrx.analysis.probe_search import ProbeNode - from evalrx.core.model import Model + from evalrx.core.model import Judge logger = logging.getLogger(__name__) @@ -77,7 +77,7 @@ class VLMProbeCandidateGenerator: """ seed_pool: CaseBatch - judge: "Model | None" = None + judge: "Judge | None" = None max_repairs: int = 1 @property diff --git a/evalrx/eval_agent/stages/probe_generator.py b/evalrx/eval_agent/stages/probe_generator.py index 69ea8c96..b014f64b 100755 --- a/evalrx/eval_agent/stages/probe_generator.py +++ b/evalrx/eval_agent/stages/probe_generator.py @@ -45,7 +45,7 @@ if TYPE_CHECKING: from evalrx.agent_runtime.cli_types import CliAgentConfig from evalrx.core.case import CaseBatch - from evalrx.core.model import Model + from evalrx.core.model import Judge, Model logger = logging.getLogger(__name__) @@ -82,7 +82,7 @@ class ProbeGenerator: def __init__( self, - judge: "Model | None" = None, + judge: "Judge | None" = None, cli_config: "CliAgentConfig | None" = None, sandbox: "ExperimentSandbox | None" = None, timeout_sec: int = 60, @@ -188,7 +188,7 @@ def _collect_outputs(self, model: "Model", cases: "CaseBatch") -> None: selected = list(cases) if self._max_cases > 0: # 0 = every case selected = selected[: self._max_cases] - if getattr(self.run_logger, "preserve_full_model_io", False): + if self.run_logger is not None: from evalrx.eval_agent.model_instrumentation import InstrumentedModel model = InstrumentedModel( diff --git a/evalrx/eval_agent/stages/probe_search_agent.py b/evalrx/eval_agent/stages/probe_search_agent.py index 7aed976e..60db8a90 100644 --- a/evalrx/eval_agent/stages/probe_search_agent.py +++ b/evalrx/eval_agent/stages/probe_search_agent.py @@ -26,7 +26,7 @@ if TYPE_CHECKING: from evalrx.core.case import CaseBatch, FailureCase - from evalrx.core.model import Model + from evalrx.core.model import Judge, Model from evalrx.eval_agent.stages.protocol import ExperimentProtocol logger = logging.getLogger(__name__) @@ -50,7 +50,7 @@ class ProbeSearchAgent: widening forces a deeper descent instead of a new sibling. """ - judge: "Model" + judge: "Judge" protocol: "ExperimentProtocol | None" = None budget: int = 20 beta: float = 1.0 @@ -67,18 +67,19 @@ def __post_init__(self) -> None: def run(self, model: "Model", seed_pool: "CaseBatch") -> ProbeSearchResult: judge = self.judge - if getattr(self.run_logger, "preserve_full_model_io", False): + if self.run_logger is not None: from evalrx.eval_agent.model_instrumentation import InstrumentedModel - cycle = int(getattr(self.run_logger, "current_cycle", -1)) + run_logger = self.run_logger + cycle = int(getattr(run_logger, "current_cycle", -1)) ids = [case.id for case in seed_pool] prompts = {case.inputs.prompt: case.id for case in seed_pool} judge = InstrumentedModel( - judge, self.run_logger, cycle=cycle, analyzer="probe_search_judge", + judge, run_logger, cycle=cycle, analyzer="probe_search_judge", batch_case_ids=ids, ) model = InstrumentedModel( - model, self.run_logger, cycle=cycle, analyzer="probe_search_target", + model, run_logger, cycle=cycle, analyzer="probe_search_target", case_prompts=prompts, batch_case_ids=ids, ) discovery = CaseDiscoveryAgent(judge=judge) diff --git a/evalrx/eval_agent/stages/surgery.py b/evalrx/eval_agent/stages/surgery.py index be1aaeb5..86395ecd 100755 --- a/evalrx/eval_agent/stages/surgery.py +++ b/evalrx/eval_agent/stages/surgery.py @@ -30,7 +30,7 @@ from evalrx.eval_agent.hypothesis import Hypothesis, HypothesisStatus if TYPE_CHECKING: - from evalrx.core.model import Model + from evalrx.core.model import Judge, Model from evalrx.core.result import Result @@ -105,7 +105,7 @@ def _serialize_cases(data: CaseBatch, image_dir: "Any | None" = None) -> str: """ from pathlib import Path as _Path - records = [] + records: list[dict[str, Any]] = [] for case in data: rec: dict[str, Any] = {"prompt": str(case.inputs)} if getattr(case, "label", None) is not None: @@ -226,14 +226,14 @@ class SurgeryAgent: sandbox_dir: Directory for sandbox script files. A temp dir is created automatically when ``None``. Sets up ONE shared sandbox for the agent's lifetime — pass this - (or omit ``run_context``) to keep that legacy - behaviour even when a ``RunContext`` is given. + (or omit ``run_context``) to keep one shared + sandbox even when a ``RunContext`` is given. writer_config: :class:`~evalrx.eval_agent.experiment_writer.ExperimentWriterConfig` controlling phases and limits. run_context: Optional :class:`~evalrx.eval_agent.run_context.RunContext`. When set (and *sandbox_dir* is not), each ``operate()`` call allocates its own self-contained *trial* under - ``experiments/`` (code + sandbox + record.md, see + ``experiments/`` (code + sandbox, see :meth:`RunContext.new_trial`) instead of every M5 experiment sharing — and overwriting — one sandbox. """ @@ -246,7 +246,7 @@ def __init__( ] | None = None, analyzer_params: dict[str, dict[str, Any]] | None = None, - judge: "Model | None" = None, + judge: "Judge | None" = None, sandbox_dir: "str | None" = None, writer_config: "Any | None" = None, run_context: "Any | None" = None, @@ -458,7 +458,7 @@ def _execute_experiment( "model_calls": writer_result.model_calls, "workdir": writer_result.workdir, # Self-contained trial folder (see RunContext.new_trial) — None - # when no RunContext is in play (legacy flat layout). + # when no RunContext is in play. "trial_root": str(trial.root) if trial is not None else None, } diff --git a/evalrx/eval_agent/stages/whitebox_probe_generator.py b/evalrx/eval_agent/stages/whitebox_probe_generator.py index 8129712b..a9aae5cc 100755 --- a/evalrx/eval_agent/stages/whitebox_probe_generator.py +++ b/evalrx/eval_agent/stages/whitebox_probe_generator.py @@ -53,7 +53,7 @@ if TYPE_CHECKING: from evalrx.agent_runtime.cli_types import CliAgentConfig from evalrx.core.case import CaseBatch - from evalrx.core.model import Model + from evalrx.core.model import Judge, Model, Trace logger = logging.getLogger(__name__) @@ -82,7 +82,7 @@ class WhiteboxProbeGenerator: def __init__( self, - judge: "Model | None" = None, + judge: "Judge | None" = None, cli_config: "CliAgentConfig | None" = None, sandbox: "ExperimentSandbox | None" = None, timeout_sec: int = 60, @@ -198,7 +198,7 @@ def _capture(self, model: "Model", cases: "CaseBatch") -> int: selected = list(cases) if self._max_cases > 0: # 0 = every case selected = selected[: self._max_cases] - if getattr(self.run_logger, "preserve_full_model_io", False): + if self.run_logger is not None: from evalrx.eval_agent.model_instrumentation import InstrumentedModel model = InstrumentedModel( @@ -208,6 +208,7 @@ def _capture(self, model: "Model", cases: "CaseBatch") -> int: case_prompts={c.inputs.prompt: c.id for c in selected}, batch_case_ids=[c.id for c in selected], ) + trace: "Trace | None" for case in selected: try: trace = model.forward(case.inputs, capture={Capability.ATTENTION}) diff --git a/evalrx/models/__init__.py b/evalrx/models/__init__.py index d28669f1..28028f7d 100755 --- a/evalrx/models/__init__.py +++ b/evalrx/models/__init__.py @@ -10,6 +10,7 @@ from __future__ import annotations from dataclasses import replace +from types import ModuleType from typing import Any from evalrx.config import ModelConfig @@ -18,17 +19,15 @@ # Backend layer + agent loop (torch-free at import; heavy deps are lazy in build/load). from evalrx.core.tool import ChatTurn, Tool, ToolCall -from evalrx.models import ( - _moved, # noqa: F401 (registers the pre-0.1.2 module paths: backends.hf_local, models.jax, ...) -) from evalrx.models.agent import Agent, APIToolHandlerExecutor, ToolExecutor from evalrx.models.backends import BACKENDS, RuntimeConfig, call_vision_api_chat_fn from evalrx.models.base import BaseAgent from evalrx.models.compose import compose from evalrx.models.toolcodec import OpenAIToolCodec, QwenToolCodec, codec_for -# Legacy concrete white-box model (now a thin deprecated alias) — optional on the -# light, pure-API install (its module imports nothing heavy at top level). +# The per-version white-box factories — optional on the light, pure-API +# install (the module imports nothing heavy at top level). +_whitebox: ModuleType | None try: from evalrx.models import whitebox as _whitebox # noqa: F401 except ImportError: # pragma: no cover - light install @@ -44,7 +43,6 @@ "compose", "RuntimeConfig", "BACKENDS", - "resolve_spec_key", "Agent", "ToolExecutor", "APIToolHandlerExecutor", @@ -57,28 +55,6 @@ "call_vision_api_chat_fn", ] -# Legacy name → canonical spec key. Keeps old configs/code working. -_SPEC_ALIASES: dict[str, str] = { - "qwen": "qwen2.5-7b-instruct", - "qwen2.5-7b": "qwen2.5-7b-instruct", -} - - -def resolve_spec_key(name: str) -> str: - """Resolve a spec key or legacy alias to a canonical :mod:`evalrx.specs` key.""" - from evalrx.specs import REGISTRY - - key = name.lower() - if key in REGISTRY: - return key - if key in _SPEC_ALIASES: - return _SPEC_ALIASES[key] - raise ValueError( - f"Unknown model {name!r}. Known specs: {sorted(REGISTRY)}; " - f"aliases: {sorted(_SPEC_ALIASES)}." - ) - - def load( key: str, *, @@ -89,12 +65,12 @@ def load( ) -> Model: """Build a model by spec key — the friendly one-liner. - ``evalrx.load("qwen2.5-7b-instruct")`` is the modern replacement for the - old ``QwenLLM()``. It wraps ``compose(get_spec(key), backend, RuntimeConfig(**runtime))`` - and negotiates capabilities up front (``want``). + ``evalrx.load("qwen2.5-7b-instruct")`` wraps + ``compose(get_spec(key), backend, RuntimeConfig(**runtime))`` and + negotiates capabilities up front (``want``). Args: - key: Spec key or legacy alias (see :func:`resolve_spec_key`). + key: A :mod:`evalrx.specs` key (see ``evalrx.list_specs()``). backend: ``"hf_local"`` (internals) / ``"api"`` / ``"vllm_offline"``. Forced to ``"api"`` for ``api_only`` (closed-weight) specs. want: Capabilities the backend must provide (names or ``Capability``). @@ -103,7 +79,7 @@ def load( """ from evalrx.specs import get_spec - spec = get_spec(resolve_spec_key(key)) + spec = get_spec(key) if checkpoint: spec = replace(spec, hf_repo=checkpoint) chosen = "api" if spec.api_only else backend diff --git a/evalrx/models/_media.py b/evalrx/models/_media.py index 75a0625f..dafda310 100644 --- a/evalrx/models/_media.py +++ b/evalrx/models/_media.py @@ -3,7 +3,7 @@ ``Inputs.image`` / ``Inputs.audio`` hold either a decoded object (PIL image, mono waveform) or a path / URL the backend resolves. Both ``hf_local`` and ``jax_local`` need the same resolution, so it lives here rather than in either -backend module. ``hf_local`` re-exports the historical private names. +backend module. """ from __future__ import annotations diff --git a/evalrx/models/_moved.py b/evalrx/models/_moved.py deleted file mode 100644 index 6c919901..00000000 --- a/evalrx/models/_moved.py +++ /dev/null @@ -1,54 +0,0 @@ -"""Import aliases for modules that moved into ``evalrx.models.backends`` (0.1.2). - -Backends are grouped by framework (``api``, ``hf``, ``jax``); the old flat -paths keep importing, each with a ``DeprecationWarning``, and resolve to the -SAME module object (so attribute access and monkeypatching behave as before). -A meta-path finder does this instead of stub files at the old paths, which -would hide the moves from git's rename tracking. -""" - -from __future__ import annotations - -import importlib -import importlib.abc -import importlib.util -import sys -import warnings - -MOVED: dict[str, str] = { - "evalrx.models.backends.hf_local": "evalrx.models.backends.hf.model", - "evalrx.models.backends.jax_local": "evalrx.models.backends.jax.backend", - "evalrx.models.backends.openai_compat": "evalrx.models.backends.api.openai", - "evalrx.models.backends.gemini_compat": "evalrx.models.backends.api.gemini", - "evalrx.models.blackbox.gemini": "evalrx.models.backends.api.gemini_model", - "evalrx.models._discover": "evalrx.models.backends.hf.discover", - "evalrx.models.inference": "evalrx.models.backends.hf.inference", - "evalrx.models.jax": "evalrx.models.backends.jax", - "evalrx.models.jax.gemma": "evalrx.models.backends.jax.adapters.gemma", - "evalrx.models.jax.protocol": "evalrx.models.backends.jax.protocol", - "evalrx.models.jax._boundary": "evalrx.models.backends.jax.boundary", -} - - -class _MovedModuleFinder(importlib.abc.MetaPathFinder, importlib.abc.Loader): - def find_spec(self, fullname, path, target=None): - if fullname not in MOVED: - return None - return importlib.util.spec_from_loader(fullname, self, is_package=fullname == "evalrx.models.jax") - - def create_module(self, spec): - new = MOVED[spec.name] - warnings.warn(f"{spec.name} moved to {new}; the old path will be removed in a future release", - DeprecationWarning, stacklevel=3) - return importlib.import_module(new) # importlib keeps its __name__ / __spec__ - - def exec_module(self, module): - pass - - -def install() -> None: - if not any(isinstance(f, _MovedModuleFinder) for f in sys.meta_path): - sys.meta_path.insert(0, _MovedModuleFinder()) - - -install() diff --git a/evalrx/models/backends/api/gemini.py b/evalrx/models/backends/api/gemini.py index 84dfebd1..407aab0a 100644 --- a/evalrx/models/backends/api/gemini.py +++ b/evalrx/models/backends/api/gemini.py @@ -1,6 +1,6 @@ """Built-in Gemini client — chat_fn / generate_fn / logprobs_fn factories for APIModel. -The mirror of :mod:`openai_compat` on Google's official ``google-genai`` SDK, +The mirror of :mod:`evalrx.models.backends.api.openai` on Google's official ``google-genai`` SDK, so a closed-weight Gemini model rides the same ``api`` backend as a served open model:: diff --git a/evalrx/models/backends/hf/decoding.py b/evalrx/models/backends/hf/decoding.py index 59e70583..e2f24366 100644 --- a/evalrx/models/backends/hf/decoding.py +++ b/evalrx/models/backends/hf/decoding.py @@ -15,7 +15,7 @@ import logging import math from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any, cast from evalrx.core.capability import Capability from evalrx.core.case import Inputs @@ -30,12 +30,35 @@ _read_nested_attr, ) +if TYPE_CHECKING: + from evalrx.core.model import Trace + from evalrx.core.spec import ModelSpec + from evalrx.models.backends.base import RuntimeConfig + from evalrx.models.backends.hf.model import HFLocalModel + logger = logging.getLogger(__name__) class ContrastiveDecodingMixin: """L3a decoding-time repairs (see the module docstring).""" + if TYPE_CHECKING: + # Provided by the host model (HFLocalModel), which this mixin is written for. + spec: ModelSpec + runtime: RuntimeConfig + _ifcd_editors: dict[str, Any] + @property + def _loaded(self) -> tuple[Any, Any]: ... + + @staticmethod + def _as_prompt(inputs: Any) -> str: ... + + def _encode_vlm(self, inputs: Any, model: Any, processor: Any) -> Any: ... + + def generate(self, inputs: Any, **kwargs: Any) -> str: ... + + def forward(self, inputs: Any, capture: set[Capability], spec: Any = None) -> Trace: ... + def paper_method_fidelity(self, method: str) -> str: """Declare whether a paper-method adapter is exact or architecture-adapted. @@ -246,26 +269,6 @@ def generate_aad_baseline(self, inputs: Any) -> str: return tok.decode(_new_tokens(out[0], enc["input_ids"][0]), skip_special_tokens=True) - def _vcd_next_token_logits( - self, - inputs: Any, - *, - noise_step: int, - noise_seed: int, - ) -> tuple[Any, Any]: - """Return clean/noisy next-token logits for the legacy binary route.""" - import torch - - model, _ = self._loaded - enc, noisy_enc = self._vcd_encodings( - inputs, noise_step=noise_step, noise_seed=noise_seed - ) - with torch.no_grad(): - clean = model(**enc).logits[0, -1] - noisy = model(**noisy_enc).logits[0, -1] - return clean, noisy - - def generate_vcd( self, inputs: Any, @@ -458,7 +461,7 @@ def token_id(answer: str) -> int: for answer in ids if clean_scores[answer] >= cutoff } - return max(scores or clean_scores, key=(scores or clean_scores).get) + return max(scores or clean_scores, key=(scores or clean_scores).__getitem__) def generate_vicrop(self, inputs: Any, *, layer: int | float = 14) -> str: @@ -468,7 +471,7 @@ def generate_vicrop(self, inputs: Any, *, layer: int | float = 14) -> str: raise ValueError(f"{self.spec.key}: ViCrop is only native on the LLaVA executor") from evalrx.models.paper_methods.vicrop import generate - return generate(self, inputs, layer=layer) + return generate(cast("HFLocalModel", self), inputs, layer=layer) # the mixin's only host def generate_opera_binary( @@ -838,7 +841,7 @@ def generate_vicrop_consensus( raise ValueError(f"{self.spec.key}: ViCrop is only native on the LLaVA executor") from evalrx.models.paper_methods.vicrop import prepare_views - image, crop, fused_prompt = prepare_views(self, inputs, layer=layer) + image, crop, fused_prompt = prepare_views(cast("HFLocalModel", self), inputs, layer=layer) # the mixin's only host fused = self.generate(Inputs(fused_prompt, [image, crop])) crop_only_prompt = ( "The image is a task-relative crop selected from a larger scene. " diff --git a/evalrx/models/backends/hf/discover.py b/evalrx/models/backends/hf/discover.py index e163f323..e6b30845 100755 --- a/evalrx/models/backends/hf/discover.py +++ b/evalrx/models/backends/hf/discover.py @@ -27,7 +27,7 @@ def find_decoder_layers(model: Any, num_hidden_layers: int | None = None) -> tup import torch.nn as nn if num_hidden_layers is None: - cfg = getattr(model, "config", None) + cfg: Any = getattr(model, "config", None) text_cfg = cfg.get_text_config() if hasattr(cfg, "get_text_config") else cfg num_hidden_layers = getattr(text_cfg, "num_hidden_layers", None) diff --git a/evalrx/models/backends/hf/model.py b/evalrx/models/backends/hf/model.py index d2716677..9727c273 100755 --- a/evalrx/models/backends/hf/model.py +++ b/evalrx/models/backends/hf/model.py @@ -26,7 +26,7 @@ from evalrx.core.model import Model, TokenLogprob, Trace from evalrx.core.spec import AttnSemantics from evalrx.core.tool import ChatTurn -from evalrx.models._media import AUDIO_SAMPLE_RATE, resolve_audio, resolve_image +from evalrx.models._media import AUDIO_SAMPLE_RATE, resolve_audio from evalrx.models.backends.base import Backend, RuntimeConfig from evalrx.models.backends.hf._util import ( # noqa: F401 _check_audio_duration, @@ -48,19 +48,13 @@ } -# Media resolution lives in evalrx.models._media (shared with jax_local); the -# private names stay bound here for existing callers and tests. -_resolve_image = resolve_image -_resolve_audio = resolve_audio - - class HFLocalModel(ContrastiveDecodingMixin, SpecialistRepairsMixin, Model): """A locally-loaded HF model, constructed from a :class:`ModelSpec`.""" def __init__(self, spec, runtime: RuntimeConfig) -> None: self.spec = spec self.runtime = runtime - self._hf = None # (model, processor) — lazy + self._hf: tuple[Any, Any] | None = None # (model, processor) — lazy self._ifcd_editors: dict[str, Any] = {} self._detect_engines: dict[str, Any] = {} self._audio_text_engines: dict[tuple[str, str], Any] = {} @@ -186,7 +180,7 @@ def _generate_without_talker(*args, **kwargs): kwargs.setdefault("return_audio", False) return original_generate(*args, **kwargs) - _generate_without_talker._evalrx_talker_suppressed = True + setattr(_generate_without_talker, "_evalrx_talker_suppressed", True) model.generate = _generate_without_talker @staticmethod @@ -533,7 +527,7 @@ def _encode_vlm(self, inputs, model, processor): audios: list = [] if self.spec.audio is not None and audio is not None: raw_audios = list(audio) if isinstance(audio, (list, tuple)) else [audio] - audios = [_resolve_audio(a) for a in raw_audios] + audios = [resolve_audio(a) for a in raw_audios] # Audio blocks precede the text block, matching the image/video # convention above; order must match the ``audio=`` list below. content = [{"type": "audio"} for _ in audios] + content diff --git a/evalrx/models/backends/hf/specialists.py b/evalrx/models/backends/hf/specialists.py index 343ac48d..5161331a 100644 --- a/evalrx/models/backends/hf/specialists.py +++ b/evalrx/models/backends/hf/specialists.py @@ -11,7 +11,7 @@ from __future__ import annotations import logging -from typing import Any +from typing import TYPE_CHECKING, Any from evalrx.core.case import Inputs from evalrx.models._media import resolve_audio as _resolve_audio @@ -26,12 +26,30 @@ _read_nested_attr, ) +if TYPE_CHECKING: + from evalrx.core.spec import ModelSpec + logger = logging.getLogger(__name__) class SpecialistRepairsMixin: """L2 calibrated specialist repairs (see the module docstring).""" + if TYPE_CHECKING: + # Provided by the host model (HFLocalModel), which this mixin is written for. + spec: ModelSpec + runtime: RuntimeConfig + _detect_engines: dict[str, Any] + _audio_text_engines: dict[tuple[str, str], Any] + _audio_api_specialist_engines: dict[str, Any] + _vision_api_specialist_engines: dict[str, Any] + _vision_specialist_engines: dict[str, Any] + @property + def _loaded(self) -> tuple[Any, Any]: ... + + @staticmethod + def _as_prompt(inputs: Any) -> str: ... + def generate_detector_grounded_presence( self, inputs: Any, @@ -130,7 +148,10 @@ def generate_clap_grounded_presence( from transformers import ClapModel, ClapProcessor processor = ClapProcessor.from_pretrained(model_id) - clap = ClapModel.from_pretrained(model_id).to(device).eval() + # transformers 5.2x types ``.to`` as an unbound wrapper, so a + # device string fails mypy there; the call itself is fine. + clap: Any = ClapModel.from_pretrained(model_id) + clap = clap.to(device).eval() def engine(waveform: Any, text: str) -> float: samples = resample_poly(waveform, 3, 1).astype("float32") diff --git a/evalrx/models/backends/jax/adapters/gemma.py b/evalrx/models/backends/jax/adapters/gemma.py index bf64c767..2823406b 100644 --- a/evalrx/models/backends/jax/adapters/gemma.py +++ b/evalrx/models/backends/jax/adapters/gemma.py @@ -306,12 +306,13 @@ def __init__(self, spec, runtime) -> None: ) if kw: logger.warning("GemmaJaxAdapter: ignoring engine_kwargs %s", sorted(kw)) - self._model = None - self._params = None - self._tok = None + # untyped gemma/flax handles, set by load() + self._model: Any = None + self._params: Any = None + self._tok: Any = None self._pieces: list[str] = [] self._special_ids: set[int] = set() - self._raw_call = None + self._raw_call: Any = None self._n_layers: int | None = None self._forward_cache: dict = {} # fresh sampler seeds for calls without SamplingParams.seed (hf_local's @@ -568,7 +569,7 @@ def _preprocess_images(self, images: list): positions_xy=jnp.reshape(positions_xy, (1, n_images * max_patches, positions_xy.shape[2])), soft_token_counts=tuple(int(c) for c in counts), ) - grids = [] + grids: list[tuple[int, int, int]] = [] for a, c in zip(arrays, counts): rows, cols = image_grid(a.shape[0], a.shape[1], **settings) if rows * cols != int(c): # the encoder changed its pooling rule: fall back to "unknown" @@ -722,12 +723,12 @@ def fwd(params, tokens, images, audio, audio_lengths, audio_soft_token_counts): fn = jax.jit(fwd, static_argnames=("audio_soft_token_counts",)) else: - def fwd(params, tokens): + def fwd_text(params, tokens): out = model.apply({"params": params}, tokens, return_last_only=False, method=raw, **capture) out, state = out if capture else (out, {}) return out.logits, None, state.get("intermediates", {}) if state else {} - fn = jax.jit(fwd) + fn = jax.jit(fwd_text) self._forward_cache[key] = fn return fn diff --git a/evalrx/models/backends/vllm_offline.py b/evalrx/models/backends/vllm_offline.py index 5d0020ad..fa27ffcc 100755 --- a/evalrx/models/backends/vllm_offline.py +++ b/evalrx/models/backends/vllm_offline.py @@ -30,7 +30,7 @@ class VLLMOfflineModel(Model): def __init__(self, spec, runtime: RuntimeConfig) -> None: self.spec = spec self.runtime = runtime - self._llm = None # lazy vllm.LLM + self._llm: Any = None # lazy vllm.LLM caps = {Capability.GENERATE, Capability.LOGPROBS} if spec.tool_calling: # conditional, like hf_local: needs a tool chat template caps.add(Capability.TOOL_CALLS) diff --git a/evalrx/models/blackbox/agent.py b/evalrx/models/blackbox/agent.py index aed2f71f..7eedaec2 100755 --- a/evalrx/models/blackbox/agent.py +++ b/evalrx/models/blackbox/agent.py @@ -8,7 +8,7 @@ from typing import Any from evalrx.core.capability import Capability -from evalrx.core.model import Trace +from evalrx.core.model import CaptureSpec, Trace from evalrx.models.base import BaseAgent @@ -24,7 +24,7 @@ def __init__(self, model_id: str, api_key: str | None = None) -> None: def generate(self, inputs: Any, **kwargs) -> str: raise NotImplementedError("BlackboxAgent is planned for Stage 2.") - def forward(self, inputs: Any, capture: set[Capability]) -> Trace: + def forward(self, inputs: Any, capture: set[Capability], spec: CaptureSpec | None = None) -> Trace: raise NotImplementedError("Black-box models expose no internals.") def step(self, observation: str, **kwargs) -> str: diff --git a/evalrx/models/blackbox/base.py b/evalrx/models/blackbox/base.py index 69b95ade..01192455 100755 --- a/evalrx/models/blackbox/base.py +++ b/evalrx/models/blackbox/base.py @@ -11,7 +11,7 @@ from typing import Any from evalrx.core.capability import Capability -from evalrx.core.model import Model, Trace +from evalrx.core.model import CaptureSpec, Model, Trace class BlackboxModel(Model): @@ -23,7 +23,7 @@ def __init__(self, model_id: str, api_key: str | None = None) -> None: self.model_id = model_id self.api_key = api_key - def forward(self, inputs: Any, capture: set[Capability]) -> Trace: + def forward(self, inputs: Any, capture: set[Capability], spec: CaptureSpec | None = None) -> Trace: raise NotImplementedError( "Black-box models expose no internals; only generate() is available." ) diff --git a/evalrx/models/paper_methods/tcd.py b/evalrx/models/paper_methods/tcd.py index d145f327..499e7c47 100644 --- a/evalrx/models/paper_methods/tcd.py +++ b/evalrx/models/paper_methods/tcd.py @@ -59,7 +59,7 @@ def hann_blur_waveform(waveform: Any, sample_rate: int, window_ms: float) -> Any global amplitude", Section 3.2). ``waveform`` is a 1-D mono float32 numpy array (matches - ``hf_local._resolve_audio``'s contract). Returns the blurred waveform at + ``evalrx.models._media.resolve_audio``'s contract). Returns the blurred waveform at the same length and sample rate — it is re-encoded through the SAME processor path as the original audio, not treated specially downstream. """ diff --git a/evalrx/models/paper_methods/vicrop.py b/evalrx/models/paper_methods/vicrop.py index 733b2f56..09b576a9 100644 --- a/evalrx/models/paper_methods/vicrop.py +++ b/evalrx/models/paper_methods/vicrop.py @@ -64,7 +64,7 @@ def sliding_window_box( for top in range(scores.shape[0]): for left in range(scores.shape[1]): scores[top, left] = relative_map[top : top + box_h, left : left + box_w].sum() - top, left = np.unravel_index(np.argmax(scores), scores.shape) + top, left = map(int, np.unravel_index(np.argmax(scores), scores.shape)) neighbors = [ float(scores[neighbor_top, neighbor_left]) for neighbor_top, neighbor_left in ( @@ -75,8 +75,8 @@ def sliding_window_box( contrast = (float(scores[top, left]) - float(np.mean(neighbors))) / (box_w * box_h) candidates.append((contrast, (left, top), (box_w, box_h), bbox_size * ratio)) _, (left, top), (box_w, box_h), selected_size = max(candidates, key=lambda item: item[0]) - center_x = int(left * block_width + block_width * box_w / 2) - center_y = int(top * block_height + block_height * box_h / 2) + center_x: float = int(left * block_width + block_width * box_w / 2) + center_y: float = int(top * block_height + block_height * box_h / 2) half = selected_size // 2 center_x = min(max(center_x, half), width - half) center_y = min(max(center_y, half), height - half) diff --git a/evalrx/models/tools/perception.py b/evalrx/models/tools/perception.py index ca9ccb67..4ecb6e9f 100644 --- a/evalrx/models/tools/perception.py +++ b/evalrx/models/tools/perception.py @@ -84,7 +84,7 @@ def ocr_tool( """ base = _to_pil(image) width, height = base.size - state = {"engine": engine} + state: dict[str, Any] = {"engine": engine} def _get_engine() -> Callable: if state["engine"] is None: @@ -242,7 +242,7 @@ def detect_tool( """ base = _to_pil(image) width, height = base.size - state = {"engine": engine} + state: dict[str, Any] = {"engine": engine} def _get_engine() -> Callable: if state["engine"] is None: diff --git a/evalrx/models/tools/visual.py b/evalrx/models/tools/visual.py index b8a2e168..6822bfd6 100644 --- a/evalrx/models/tools/visual.py +++ b/evalrx/models/tools/visual.py @@ -76,7 +76,7 @@ def _sanitize_bbox(bbox: Any, width: int, height: int) -> "tuple[list[float], st ) if fits_pixels: mode = "pixel" - scale = (width, height, width, height) + scale: tuple[float, float, float, float] = (width, height, width, height) else: # out of pixel bounds -> 0-1000 normalized grid mode = "grid_1000" scale = (1000.0, 1000.0, 1000.0, 1000.0) @@ -139,7 +139,7 @@ def _zoom(bbox, target: str = "") -> ToolResult: crop = crop.resize( (int(round(crop.size[0] * factor)), int(round(crop.size[1] * factor))), - Image.LANCZOS, + Image.LANCZOS, # type: ignore[attr-defined] # alias set dynamically by Pillow ) meta: dict = { diff --git a/evalrx/models/whitebox/__init__.py b/evalrx/models/whitebox/__init__.py index 35ec6162..843f2b8c 100755 --- a/evalrx/models/whitebox/__init__.py +++ b/evalrx/models/whitebox/__init__.py @@ -11,11 +11,11 @@ from evalrx.models.whitebox import qwen2_audio as _qwen2_audio from evalrx.models.whitebox import qwen_omni as _qwen_omni from evalrx.models.whitebox import qwen_vl as _qwen_vl -from evalrx.models.whitebox.qwen import * # noqa: F401,F403 (QwenLLM + qwen text factories) +from evalrx.models.whitebox.qwen import * # noqa: F401,F403 (qwen text factories) from evalrx.models.whitebox.qwen2_5_omni import * # noqa: F401,F403 (qwen2.5-omni factory) from evalrx.models.whitebox.qwen2_audio import * # noqa: F401,F403 (qwen2-audio factory) from evalrx.models.whitebox.qwen_omni import * # noqa: F401,F403 (qwen3-omni factories) -from evalrx.models.whitebox.qwen_vl import * # noqa: F401,F403 (QwenVL + qwen-vl factories) +from evalrx.models.whitebox.qwen_vl import * # noqa: F401,F403 (qwen-vl factories) __all__ = sorted( set(_qwen.__all__) diff --git a/evalrx/models/whitebox/agent.py b/evalrx/models/whitebox/agent.py index 28b06924..8ee83e7d 100755 --- a/evalrx/models/whitebox/agent.py +++ b/evalrx/models/whitebox/agent.py @@ -8,7 +8,7 @@ from typing import Any from evalrx.core.capability import Capability -from evalrx.core.model import Trace +from evalrx.core.model import CaptureSpec, Trace from evalrx.models.base import BaseAgent from evalrx.models.whitebox.base import WhiteboxModel @@ -24,7 +24,7 @@ def load(self) -> None: def generate(self, inputs: Any, **kwargs) -> str: raise NotImplementedError("WhiteboxAgent is planned for Stage 2.") - def forward(self, inputs: Any, capture: set[Capability]) -> Trace: + def forward(self, inputs: Any, capture: set[Capability], spec: CaptureSpec | None = None) -> Trace: raise NotImplementedError("WhiteboxAgent is planned for Stage 2.") def step(self, observation: str, **kwargs) -> str: diff --git a/evalrx/models/whitebox/qwen.py b/evalrx/models/whitebox/qwen.py index 56155c9a..ae37bdf9 100755 --- a/evalrx/models/whitebox/qwen.py +++ b/evalrx/models/whitebox/qwen.py @@ -10,13 +10,10 @@ from evalrx.models.whitebox.qwen import qwen3_8b model = qwen3_8b(device="cuda", dtype="bfloat16") # equivalent to: evalrx.load("qwen3-8b", backend="hf_local", ...) - -``QwenLLM(...)`` remains as a deprecated back-compat shim. """ from __future__ import annotations -import warnings from typing import Any # Spec keys exposed as factories (each must exist in evalrx.specs). @@ -45,17 +42,4 @@ def build(**runtime: Any): globals()[_k.replace("-", "_").replace(".", "_")] = _version_factory(_k) -def QwenLLM(checkpoint: str | None = None, device: str = "auto", dtype: str = "bfloat16", **runtime: Any): - """Deprecated. Use a version factory (e.g. ``qwen2_5_7b_instruct()``) or - ``evalrx.load('qwen2.5-7b-instruct')``.""" - warnings.warn( - "QwenLLM is deprecated; use a version factory (e.g. qwen2_5_7b_instruct()) " - "or evalrx.load('qwen2.5-7b-instruct').", - DeprecationWarning, stacklevel=2, - ) - from evalrx.models import load - return load("qwen2.5-7b-instruct", backend="hf_local", - checkpoint=checkpoint, device=device, dtype=dtype, **runtime) - - -__all__ = ["QwenLLM"] + [k.replace("-", "_").replace(".", "_") for k in _TEXT_KEYS] +__all__ = [k.replace("-", "_").replace(".", "_") for k in _TEXT_KEYS] diff --git a/evalrx/models/whitebox/qwen_vl.py b/evalrx/models/whitebox/qwen_vl.py index e0094125..a9c1e5ae 100755 --- a/evalrx/models/whitebox/qwen_vl.py +++ b/evalrx/models/whitebox/qwen_vl.py @@ -10,12 +10,10 @@ NOTE: text generation + logprobs work today; white-box forward-capture over image tokens (attention/hidden) uses the hf_local VLM path + ``core.tokentype.TokenTypeMap``. -``QwenVL(...)`` remains as a deprecated back-compat shim. """ from __future__ import annotations -import warnings from typing import Any # Spec keys exposed as factories (each must exist in evalrx.specs). @@ -46,17 +44,4 @@ def build(**runtime: Any): globals()[_k.replace("-", "_").replace(".", "_")] = _version_factory(_k) -def QwenVL(checkpoint: str | None = None, device: str = "auto", dtype: str = "bfloat16", **runtime: Any): - """Deprecated. Use a version factory (e.g. ``qwen3_vl_8b_instruct()``) or - ``evalrx.load('qwen2.5-vl-7b-instruct')``.""" - warnings.warn( - "QwenVL is deprecated; use a version factory (e.g. qwen3_vl_8b_instruct()) " - "or evalrx.load('qwen2.5-vl-7b-instruct').", - DeprecationWarning, stacklevel=2, - ) - from evalrx.models import load - return load("qwen2.5-vl-7b-instruct", backend="hf_local", - checkpoint=checkpoint, device=device, dtype=dtype, **runtime) - - -__all__ = ["QwenVL"] + [k.replace("-", "_").replace(".", "_") for k in _VL_KEYS] +__all__ = [k.replace("-", "_").replace(".", "_") for k in _VL_KEYS] diff --git a/evalrx/observability/envelope.py b/evalrx/observability/envelope.py index f9be9edf..bcb32bb4 100644 --- a/evalrx/observability/envelope.py +++ b/evalrx/observability/envelope.py @@ -63,7 +63,7 @@ def artifact_manifests_for_event(event: dict[str, Any], *, run_dir: str | Path) Event fields intentionally contain relative paths, never inline binary content. This small adapter gives the Langfuse writer a complete upload - manifest without changing the established JSONL event shapes. + manifest without changing the event shapes. """ root = Path(run_dir).resolve() candidates: list[tuple[str, str]] = [] diff --git a/evalrx/observability/outbox.py b/evalrx/observability/outbox.py index f54f76e3..1173ab02 100644 --- a/evalrx/observability/outbox.py +++ b/evalrx/observability/outbox.py @@ -1,9 +1,9 @@ """Durable, idempotent delivery queue for EvalRX observability events. -The outbox is deliberately a delivery mechanism, not another long-term run -format. A JSONL run log remains available during the migration, while this -SQLite database makes an interrupted or temporarily disconnected Langfuse -session resumable without dropping the events that happened in between. +The outbox is a delivery mechanism, not another run format: the run log is +the record. This SQLite database makes an interrupted or temporarily +disconnected Langfuse session resumable without dropping the events that +happened in between. """ from __future__ import annotations diff --git a/evalrx/observability/tracer.py b/evalrx/observability/tracer.py index 16a37bf1..39b3e7a1 100644 --- a/evalrx/observability/tracer.py +++ b/evalrx/observability/tracer.py @@ -60,12 +60,12 @@ def __init__( self.events: list[dict[str, Any]] = [] self.trace_metadata: dict[str, Any] = {} self._start_time = time.time() - requested_mode = (mode or os.getenv("EVALRX_LANGFUSE_MODE", "auto")).strip().lower() + requested_mode = (mode or os.environ.get("EVALRX_LANGFUSE_MODE", "auto")).strip().lower() if requested_mode not in {"auto", "live", "offline"}: raise ValueError("EVALRX_LANGFUSE_MODE must be one of: auto, live, offline") self.mode = requested_mode self._langfuse_client = None - self._live_root = None # root "chain" observation for the run + self._live_root: Any = None # root "chain" observation for the run self._live_obs: dict[str, Any] = {} # our span_id -> live observation wrapper self._warned: set[str] = set() # Every structured run-log event enters this durable queue before live @@ -127,8 +127,8 @@ def _apply_tags(self, tags: list[str]) -> None: def record_event(self, event: dict[str, Any], *, event_seq: int) -> None: """Queue one complete EvalRX event for durable Langfuse delivery. - This is called after the JSONL write has received its timestamp and - trace id. The deterministic event id makes repeated process startup + This is called after the run logger has stamped the event with its + timestamp and trace id. The deterministic event id makes repeated process startup and manual backfill safe. """ artifact_refs = ( @@ -469,10 +469,10 @@ def _resolve_trace_id(run_dir: Path, fingerprint: str) -> str: except Exception: pass try: - from evalrx.reporting.run_events import read_v2_events + from evalrx.reporting.run_events import read_run_events start = next( - (event for event in read_v2_events(run_dir) if event.get("event") == "run_start"), + (event for event in read_run_events(run_dir) if event.get("event") == "run_start"), {}, ) if start.get("trace_id"): @@ -672,13 +672,8 @@ def export_to_langfuse_bundle(run_dir: str | Path, out_json: str | Path | None = }, "input": {"candidates": [s.get("name") for s in m5_f["selection"]]}, "output": { - # Fix events written before PR #88 carry ``best`` as the candidate - # NAME, later ones as the candidate record: accept both. - "best_candidate": ( - (m5_f.get("best") or {}).get("name") - if isinstance(m5_f.get("best"), dict) else (m5_f.get("best") or None) - ) or (m5_f.get("confirm") or {}).get("name"), - "confirm": m5_f.get("confirm"), + "best_candidate": (m5_f.get("best") or {}).get("name"), + "confirm": m5_f.get("best"), }, }) if m5_f.get("prompt_template"): @@ -690,11 +685,11 @@ def export_to_langfuse_bundle(run_dir: str | Path, out_json: str | Path | None = "model": "Repair Search Agent", "prompt": "Synthesize targeted prompt patch based on diagnosed mechanism", "completion": m5_f["prompt_template"], - "metadata": {"candidate_name": (m5_f.get("confirm") or {}).get("name")}, + "metadata": {"candidate_name": (m5_f.get("best") or {}).get("name")}, }) # Global Key Evaluation Scores - cfm = m5_f.get("confirm") or {} + cfm = m5_f.get("best") or {} if cfm.get("n_baseline_correct") is not None and cfm.get("n_pairs"): scores.append({ "name": "baseline_accuracy", @@ -733,18 +728,18 @@ def export_to_langfuse_bundle(run_dir: str | Path, out_json: str | Path | None = def backfill_run_to_langfuse(run_dir: str | Path, *, dry_run: bool = False) -> dict[str, int | str]: """Queue an existing run for the same reliable Langfuse pipeline. - Existing ``event_seq`` values are preserved; older logs without one receive - their line order. Re-running the command is safe because envelope IDs are - deterministic and the outbox primary key de-duplicates them. + Each event keeps its ``event_seq``. Re-running the command is safe because + envelope IDs are deterministic and the outbox primary key de-duplicates + them. """ - from evalrx.reporting.run_events import read_v2_events, resolve_v2_root + from evalrx.reporting.run_events import read_run_events, resolve_run_root root = Path(run_dir) - v2_root = resolve_v2_root(root) + v2_root = resolve_run_root(root) if v2_root is None: raise FileNotFoundError(f"No run bundle (run.json) found under {run_dir}") root = v2_root - records: list[dict[str, Any]] = read_v2_events(root) + records: list[dict[str, Any]] = read_run_events(root) if not records: return {"trace_id": "", "events": 0, "pending": 0, "published": 0} @@ -761,8 +756,8 @@ def backfill_run_to_langfuse(run_dir: str | Path, *, dry_run: bool = False) -> d n_cases=int(run_start.get("n_cases") or 0), metadata=run_start, ) - for fallback_seq, record in enumerate(records, start=1): - tracer.record_event(record, event_seq=int(record.get("event_seq") or fallback_seq)) + for record in records: + tracer.record_event(record, event_seq=int(record["event_seq"])) pending_before = tracer.outbox.pending_count() tracer.flush() pending_after = tracer.outbox.pending_count() @@ -814,7 +809,7 @@ def _tags(client: "Langfuse", tags: list) -> None: obs_map: dict[str, Any] = {} for span in bundle["spans"]: - parent = obs_map.get(span.get("parent_id")) or root + parent: Any = obs_map.get(span.get("parent_id")) or root try: obs = parent.start_observation( name=span["name"], diff --git a/evalrx/probing/catalog.py b/evalrx/probing/catalog.py index 48749ffc..ef347abf 100644 --- a/evalrx/probing/catalog.py +++ b/evalrx/probing/catalog.py @@ -176,7 +176,7 @@ def _split_top_level(text: str) -> list[str]: return parts -def _params_of(cls: type) -> "tuple[ProbeParam, ...]": +def _params_of(cls: "type[Any]") -> "tuple[ProbeParam, ...]": try: signature = inspect.signature(cls.__init__) except (TypeError, ValueError): @@ -216,13 +216,16 @@ def _first_line(text: "str | None") -> str: return "" -def is_stub(cls: type) -> bool: +def is_stub(cls: "type[Any]") -> bool: """True when ``_run`` only raises ``NotImplementedError`` (a registered placeholder).""" try: tree = ast.parse(textwrap.dedent(inspect.getsource(cls._run))) except (OSError, TypeError, SyntaxError, AttributeError): return False - body = [n for n in tree.body[0].body + func = tree.body[0] + if not isinstance(func, (ast.FunctionDef, ast.AsyncFunctionDef)): + return False + body = [n for n in func.body if not (isinstance(n, ast.Expr) and isinstance(n.value, ast.Constant))] if len(body) != 1 or not isinstance(body[0], ast.Raise): return False diff --git a/evalrx/probing/toolbox.py b/evalrx/probing/toolbox.py index 943c7a21..9924da96 100644 --- a/evalrx/probing/toolbox.py +++ b/evalrx/probing/toolbox.py @@ -122,7 +122,7 @@ def build_probe(name: str, params: "Mapping[str, Any] | None" = None, *, f"{name}: the host must supply {list(spec.injected_params)} " "(pass a constructed analyzer via analyzer_overrides)", "unavailable", ) - return spec.analyzer_cls(**cleaned) + return registry.analyzers.get(name)(**cleaned) except ProbeCallError: raise except (TypeError, ValueError) as exc: @@ -172,6 +172,8 @@ def call(self, name: str, params: "Mapping[str, Any] | None" = None, batch = self.data if data is None else data if batch is None: raise ProbeCallError(f"{name}: no data to probe", "unavailable") + if self.model is None: + raise ProbeCallError(f"{name}: no model to probe", "unavailable") analyzer = build_probe(name, params, overrides=self.overrides) verdict = availability(spec_for(name), self.model, batch, overrides=self.overrides) if not verdict.available: diff --git a/evalrx/reporting/__init__.py b/evalrx/reporting/__init__.py index 7b029ae7..040241d3 100644 --- a/evalrx/reporting/__init__.py +++ b/evalrx/reporting/__init__.py @@ -1,28 +1,15 @@ -"""Claim/evidence diagnostic reporting.""" +"""Reports built from a run log.""" -from evalrx.reporting.compiler import compile_diagnostic_report from evalrx.reporting.dynamic import ( PublishedReport, ReportAgent, build_report_data, publish_report, ) -from evalrx.reporting.html_report import build_html_report -from evalrx.reporting.model import Claim, DiagnosticReport, Evidence, ReportStep -from evalrx.reporting.stages import STAGE_SPECS, StageSpec, stage_specs_as_dicts __all__ = [ - "Claim", - "DiagnosticReport", - "Evidence", - "ReportStep", - "STAGE_SPECS", - "StageSpec", - "build_html_report", "build_report_data", - "compile_diagnostic_report", "publish_report", "PublishedReport", "ReportAgent", - "stage_specs_as_dicts", ] diff --git a/evalrx/reporting/case_study.py b/evalrx/reporting/case_study.py index 102147d4..bcbadb74 100644 --- a/evalrx/reporting/case_study.py +++ b/evalrx/reporting/case_study.py @@ -344,7 +344,7 @@ class _Run: def __init__(self, root: Path, events: Sequence[Mapping[str, Any]]): root = Path(root) - if (root / "run.json").exists() or (root / "artifacts").is_dir(): + if (root / "run.json").exists(): self.logs, self.run_dir = root, root.parent else: self.logs = next((p for p in sorted(root.glob("logs*")) if p.is_dir()), root) @@ -358,11 +358,6 @@ def __init__(self, root: Path, events: Sequence[Mapping[str, Any]]): for event in self.events if event.get("event") == "case_record" and event.get("case_id") } - self.all_cases = { - case["id"]: case - for case in (_load(self.logs / "report" / "discovery_cases.json", []) or []) - if isinstance(case, dict) and "id" in case - } def event(self, name: str) -> "Mapping[str, Any] | None": return next((e for e in self.events if e.get("event") == name), None) @@ -370,44 +365,23 @@ def event(self, name: str) -> "Mapping[str, Any] | None": def events_of(self, name: str) -> "list[Mapping[str, Any]]": return [e for e in self.events if e.get("event") == name] - def per_case(self, analyzer: str, cycle_prefix: str = "c0") -> "list[dict[str, Any]]": - blob = _load(self.logs / "artifacts" / f"{cycle_prefix}_{analyzer}.result.json", {}) or {} - rows = (blob.get("findings") or {}).get("per_case") or [] - if not rows: - # V1 externalised each analyzer's result to artifacts/; RunLoggerV2 - # keeps every analyzer's findings inline on the M1 probe entry, - # one entry per pass (cycle 0 = explore, -1 = the held-out re-run). - want = -1 if cycle_prefix in ("c-1", "post") else 0 - for entry in self.events_of("probe"): - try: - cycle = int(entry.get("cycle") or 0) - except (TypeError, ValueError): - cycle = 0 - if cycle != want: - continue - findings = (entry.get("findings") or {}).get(analyzer) - if isinstance(findings, dict) and findings.get("per_case"): - rows = findings["per_case"] - break - return [row for row in rows if isinstance(row, dict)] - - def m2_files(self) -> "list[tuple[str, Path]]": - """[(phase, path)] for every M2 results file, explore before held-out.""" - artifacts = self.logs / "artifacts" - if not artifacts.is_dir(): - return [] - found = [] - for path in sorted(artifacts.glob("*_m2_stats_results.json")): - name = path.name - if name.startswith(("post_", "c-1_")): - phase = "heldout" - elif name.startswith("c0_"): - phase = "explore" - else: - phase = name.split("_m2_")[0] - found.append((phase, path)) - found.sort(key=lambda item: 0 if item[0] == "explore" else 1) - return found + def per_case(self, analyzer: str) -> "list[dict[str, Any]]": + """The analyzer's per-case rows from the explore pass (cycle 0). + + The logger keeps every analyzer's findings inline on the M1 probe + entry, one entry per pass. + """ + for entry in self.events_of("probe"): + try: + cycle = int(entry.get("cycle") or 0) + except (TypeError, ValueError): + cycle = 0 + if cycle != 0: + continue + findings = (entry.get("findings") or {}).get(analyzer) + if isinstance(findings, dict) and findings.get("per_case"): + return [row for row in findings["per_case"] if isinstance(row, dict)] + return [] def measurements(self, analyzers: Iterable[str]) -> "list[dict[str, Any]]": """Every numeric per-case field a probe produced, with why it was kept.""" @@ -607,17 +581,10 @@ def assign(value): def _m2_sources(run: _Run) -> "list[tuple[str, list]]": """[(phase, stats rows)], explore before held-out. - RunLoggerV2 keeps these rows inline as ``stats_results`` on the M2 + The logger keeps these rows inline as ``stats_results`` on the M2 ``analysis`` entry, with the pass told apart by cycle (0 = explore, -1 = - the held-out re-run). ``run.m2_files()`` (an externalised - ``artifacts/_m2_stats_results.json`` per pass) is a predecessor - format nothing currently produces; kept as a read path in case it's ever - reintroduced for oversized results, harmless since it degrades to the - inline fallback below when empty. + the held-out re-run). """ - files = run.m2_files() - if files: - return [(phase, _load(path, []) or []) for phase, path in files] found = [] for entry in run.events_of("analysis"): rows = entry.get("stats_results") @@ -837,17 +804,17 @@ def score(case_id: str) -> tuple: if not failing: return None case_id = max(failing, key=score) - case = run.all_cases.get(case_id, {}) - record = run.case_records.get(case_id, {}) + record = run.case_records.get(case_id) or {} + case = record.get("case") or {} return { "case_id": case_id, "split": "explore", - "question": case.get("prompt") or ((record.get("case") or {}).get("inputs") or {}).get("prompt"), + "question": (case.get("inputs") or {}).get("prompt"), "gold": case.get("expected"), "baseline_output": case.get("observed"), # what it answered, separately from everything it said on the way there "baseline_answer": final_answer(case.get("observed")), - "label": case.get("label") or (record.get("case") or {}).get("label"), + "label": case.get("label"), "signal": curve.get("signal") if curve else None, "signal_values": signals.get(case_id), "media_paths": record.get("media_paths") or [], @@ -930,7 +897,7 @@ def build_case_study( start = run.event("run_start") or {} # The benchmark harness writes `baseline_accuracy`; llm_benchmark's # summary.json nests the same number as `batch.accuracy`. - batch = run.summary.get("batch") if isinstance(run.summary.get("batch"), dict) else {} + batch = found if isinstance(found := run.summary.get("batch"), dict) else {} baseline = run.summary.get("baseline_accuracy") if baseline is None: baseline = batch.get("accuracy") @@ -958,7 +925,7 @@ def prefer(key: str) -> Any: "headline": { "model": prefer("model"), "dataset": prefer("dataset"), - "n_cases": run.summary.get("n_cases") or setting.get("n_cases") or len(run.all_cases), + "n_cases": run.summary.get("n_cases") or setting.get("n_cases") or len(run.case_records), "baseline_accuracy": baseline, # From the report's partition table when the caller built one: # ``case_records`` holds every partition the loop logged, so its @@ -966,8 +933,7 @@ def prefer(key: str) -> Any: "n_explore": (partition_n.get("explore") if partition_n else len(run.case_records)), "n_heldout": (sum(n for split, n in partition_n.items() if split and split != "explore") - if partition_n - else max(len(run.all_cases) - len(run.case_records), 0)), + if partition_n else 0), "judge": str(start.get("judge")) if start.get("judge") else None, "repair": (repair or {}).get("name"), "repair_tier": (repair or {}).get("tier"), diff --git a/evalrx/reporting/compiler.py b/evalrx/reporting/compiler.py index 443c658e..79304788 100644 --- a/evalrx/reporting/compiler.py +++ b/evalrx/reporting/compiler.py @@ -1,63 +1,10 @@ -"""Compile raw dashboard artifacts into a claim-first diagnostic report.""" +"""Compile a loaded run into the plain-language summary a report opens with.""" from __future__ import annotations from typing import Any -from evalrx.reporting.model import ( - Claim, - DiagnosticReport, - Evidence, - ReaderFinding, - ReaderReport, - ReportStep, -) -from evalrx.viz.labels import display_name - - -def compile_diagnostic_report( - story: dict[str, Any] | None, - explore_report: dict[str, Any] | None, -) -> DiagnosticReport: - """Build a semantic report from a loop story plus the Step-1 explore report. - - This compiler is deterministic. Agent-authored fields such as ``claims`` or - ``chart_readings`` are preserved when present, but host-confirmed signal - verdicts and loop outcomes remain the authoritative backbone. - """ - story = story or {} - explore_report = explore_report or {} - signals = _candidate_signals(explore_report) - evidence = _compile_evidence(explore_report, story) - claims = _compile_claims(explore_report, story, signals) - - # Analysis-phase (descriptive) mode: M2 ran with the e-BH validity verdict - # DEFERRED to the confirm phase, so the dashboard must NOT show - # supported/not-supported claims — only distributions, charts, and proposed - # hypotheses. Demote every signal claim to descriptive until confirmation. - descriptive_only = _is_descriptive_only(story) - caveats = [str(c) for c in (explore_report.get("caveats") or [])] - if descriptive_only: - claims = [_demote_to_descriptive(c) for c in claims] - caveats.insert(0, _DESCRIPTIVE_BANNER) - - answer = _answer(explore_report, claims) if not descriptive_only else _DESCRIPTIVE_ANSWER - confidence = _confidence(claims) - - return DiagnosticReport( - question=_fallback_question(explore_report, story), - answer=answer, - confidence=confidence, - claims=claims, - evidence=evidence, - timeline=_compile_timeline(story, explore_report), - visual_decisions=list(explore_report.get("visual_plan") or []), - chart_readings=list(explore_report.get("chart_readings") or []), - dashboard_storyboard=_dashboard_storyboard(explore_report, story, claims), - critique=_critique(explore_report, signals), - caveats=caveats, - next_actions=_next_actions(explore_report, claims), - ) +from evalrx.reporting.model import ReaderFinding, ReaderReport def compile_reader_report(data: dict[str, Any]) -> ReaderReport: @@ -82,7 +29,7 @@ def compile_reader_report(data: dict[str, Any]) -> ReaderReport: m4_ran = bool(m4.get("ran")) hypotheses = m3.get("hypotheses") or [] repair_ran = bool(m5_fix.get("ran")) - repair_effect = (m5_fix.get("confirm") or {}).get("effect") + repair_effect = (m5_fix.get("best") or {}).get("effect") if m4_ran: headline = "A possible explanation was checked on new cases." confidence = "Independently checked" @@ -187,401 +134,3 @@ def _reader_question(protocol: Any) -> str: if protocol: return str(protocol) return "What patterns are linked to the observed outcomes?" - - -_DESCRIPTIVE_BANNER = ( - "ANALYSIS PHASE (descriptive): distributions, charts, and proposed hypotheses " - "only — signal/hypothesis VALIDITY (e-BH + M4) is deferred to the confirm phase " - "and is not shown here." -) -_DESCRIPTIVE_ANSWER = ( - "Analysis phase — candidate signals and proposed hypotheses are shown without a " - "validity verdict; run the confirm phase to adjudicate them." -) - - -def _is_descriptive_only(story: dict[str, Any]) -> bool: - """True when every M2 analysis in the story deferred its validity verdict and - no confirmation (M4/surgery) has run yet — i.e. the loaded run is analysis-only. - - A single confirmatory M2 (``descriptive_only=False``, logged by the confirm - phase or the all-in-one loop) or any recorded surgery flips this off, so the - full validity rendering returns once the run is confirmed.""" - analyses = story.get("analyses") or [] - if not analyses: - return False - if not all(a.get("descriptive_only") for a in analyses): - return False - return not (story.get("surgeries") or []) - - -def _demote_to_descriptive(claim: Claim) -> Claim: - """Strip a claim's validity verdict (supported/inconclusive/refuted) to - descriptive for the analysis-phase view, preserving its text and evidence.""" - if claim.status == "descriptive": - return claim - note = "Association shown descriptively; validity is deferred to the confirm phase." - interp = (claim.interpretation + " " if claim.interpretation else "") + note - return Claim( - id=claim.id, - text=claim.text, - status="descriptive", - evidence_ids=list(claim.evidence_ids), - counter_evidence_ids=list(claim.counter_evidence_ids), - interpretation=interp.strip(), - do_not_infer=claim.do_not_infer, - downstream=list(claim.downstream), - ) - - -_GENERIC_QUESTION = "What distinguishes failures from passes?" - - -def _fallback_question(explore_report: dict[str, Any], story: dict[str, Any]) -> str: - """The explore report's own question wins; a loop/agentic run with no - explore_report artifact falls back to the protocol description logged at - run_start — otherwise a run with no explore report shows a question with - no connection to what it actually investigated.""" - question = str(explore_report.get("question") or "").strip() - if question: - return question - protocol = (story.get("run_start") or {}).get("protocol") or {} - return str(protocol.get("description") or "").strip() or _GENERIC_QUESTION - - -def _dashboard_storyboard( - explore_report: dict[str, Any], - story: dict[str, Any], - claims: list[Claim], -) -> list[dict[str, Any]]: - raw = explore_report.get("dashboard_storyboard") or explore_report.get("ui_panels") - if isinstance(raw, list) and all(isinstance(p, dict) for p in raw): - return [dict(p) for p in raw] - - supported = next((c.text for c in claims if c.status == "supported"), "") - observations = [str(x) for x in (explore_report.get("observations") or [])[:3]] - readings = [ - str(r.get("reading")) - for r in (explore_report.get("chart_readings") or []) - if isinstance(r, dict) and r.get("reading") - ][:3] - hypotheses = [] - for diag in story.get("diagnoses") or []: - for h in diag.get("hypotheses") or []: - hypotheses.append(str(h.get("statement") or h)) - - return [ - { - "id": "problem_setting", - "title": "Problem Setting", - "stages": ["M1"], - "summary": _fallback_question(explore_report, story), - "items": observations, - "artifact_refs": ["data_profile", "candidate_signals"], - }, - { - "id": "analysis", - "title": "Analysis", - "stages": ["M2"], - "summary": supported or str(explore_report.get("conclusion") or ""), - "items": readings, - "artifact_refs": ["candidate_signals", "charts", "chart_readings"], - }, - { - "id": "hypotheses_artifacts", - "title": "Hypotheses & Artifacts", - "stages": ["M3", "M4", "M5"], - "summary": "Hypotheses and downstream decisions generated from the analysis.", - "items": hypotheses[:5], - "artifact_refs": ["diagnoses", "surgeries", "fixes"], - }, - ] - - -def _candidate_signals(explore_report: dict[str, Any]) -> list[dict[str, Any]]: - return [ - s for s in (explore_report.get("candidate_signals") or []) - if isinstance(s, dict) - ] - - -def _compile_evidence(explore_report: dict[str, Any], story: dict[str, Any]) -> list[Evidence]: - evidence: list[Evidence] = [] - for idx, signal in enumerate(_candidate_signals(explore_report), start=1): - name = str(signal.get("name") or f"signal_{idx}") - evidence.append(Evidence( - id=f"signal:{name}", - kind="confirmed_signal", - title=str(signal.get("display_name") or display_name(name)), - summary=_signal_summary(signal), - artifact=signal, - )) - for idx, chart in enumerate(explore_report.get("charts") or [], start=1): - if not isinstance(chart, dict): - continue - raw_title = str(chart.get("display_name") or chart.get("title") or chart.get("name") or f"Chart {idx}") - title = display_name(raw_title) - evidence.append(Evidence( - id=f"chart:{_slug(title)}", - kind="chart", - title=title, - summary=str(chart.get("description") or chart.get("kind") or ""), - artifact=chart, - )) - for idx, analysis in enumerate(story.get("analyses") or [], start=1): - summary = str(analysis.get("conclusion") or analysis.get("narrative") or "") - evidence.append(Evidence( - id=f"analysis:{idx}", - kind="m2_analysis", - title=f"M2 analysis cycle {analysis.get('cycle', idx)}", - summary=summary, - artifact=analysis, - )) - return evidence - - -def _compile_claims( - explore_report: dict[str, Any], - story: dict[str, Any], - signals: list[dict[str, Any]], -) -> list[Claim]: - explicit = [ - _claim_from_agent(c, i) - for i, c in enumerate(explore_report.get("claims") or [], start=1) - if isinstance(c, dict) - ] - if explicit: - return explicit - - claims: list[Claim] = [] - for idx, signal in enumerate(signals, start=1): - name = str(signal.get("name") or f"signal_{idx}") - status = _signal_status(signal) - downstream = _downstream_for_signal(name, story) - claims.append(Claim( - id=f"C{idx}", - text=_claim_text(signal), - status=status, - evidence_ids=[f"signal:{name}", *_chart_evidence_for_signal(name, explore_report)], - interpretation=_signal_interpretation(signal), - do_not_infer=_do_not_infer(signal), - downstream=downstream, - )) - if not claims: - claims.append(Claim( - id="C0", - text="No candidate signal was confirmed in the loaded report.", - status="inconclusive", - interpretation="The run may still contain exploratory observations, but no supported " - "claim can be made from the available confirmation layer.", - do_not_infer="Do not treat exploratory plots as confirmed root causes.", - )) - return _sort_claims(claims) - - -def _claim_from_agent(raw: dict[str, Any], idx: int) -> Claim: - status = str(raw.get("status") or "descriptive").lower() - if status not in {"supported", "inconclusive", "refuted", "descriptive"}: - status = "descriptive" - return Claim( - id=str(raw.get("id") or f"C{idx}"), - text=str(raw.get("text") or raw.get("claim") or ""), - status=status, # type: ignore[arg-type] - evidence_ids=[str(x) for x in (raw.get("evidence_ids") or [])], - counter_evidence_ids=[str(x) for x in (raw.get("counter_evidence_ids") or [])], - interpretation=str(raw.get("interpretation") or ""), - do_not_infer=str(raw.get("do_not_infer") or ""), - downstream=[str(x) for x in (raw.get("downstream") or [])], - ) - - -def _compile_timeline(story: dict[str, Any], explore_report: dict[str, Any]) -> list[ReportStep]: - steps = [ - ReportStep( - stage="Explore", - title="Agent explored patterns and proposed visuals/signals", - summary=f"{len(explore_report.get('observations') or [])} observation(s), " - f"{len(explore_report.get('charts') or [])} chart(s), " - f"{len(explore_report.get('candidate_signals') or [])} signal(s).", - ) - ] - analyses = story.get("analyses") or [] - if analyses: - steps.append(ReportStep( - stage="M2", - title="Host confirmed signal associations", - summary=str(analyses[-1].get("conclusion") or analyses[-1].get("narrative") or ""), - artifact_ids=[f"analysis:{len(analyses)}"], - )) - diagnoses = story.get("diagnoses") or [] - if diagnoses: - n_h = sum(len(d.get("hypotheses") or []) for d in diagnoses) - steps.append(ReportStep( - stage="M3", - title="Agent formed falsifiable hypotheses", - summary=f"{n_h} hypothesis/hypotheses proposed from confirmed and exploratory context.", - )) - surgeries = story.get("surgeries") or [] - if surgeries: - steps.append(ReportStep( - stage="M4/M5", - title="Hypotheses were tested by interventions", - summary=f"{len(surgeries)} test/intervention event(s) recorded.", - )) - fixes = story.get("fixes") or [] - if fixes: - steps.append(ReportStep( - stage="Fix", - title="Fix candidates were adjudicated", - summary=f"{len(fixes)} fix event(s) recorded.", - )) - return steps - - -def _answer(explore_report: dict[str, Any], claims: list[Claim]) -> str: - supported = [c.text for c in claims if c.status == "supported"] - if supported: - leaky = sum(1 for c in claims if "sanity check" in c.do_not_infer.lower()) - suffix = f" ({leaky} {_plural(leaky, 'sanity check')} demoted.)" if leaky else "" - return supported[0] + suffix - conclusion = str(explore_report.get("conclusion") or "").strip() - if conclusion: - return conclusion - return "No supported diagnostic claim is available in the loaded report." - - -def _confidence(claims: list[Claim]) -> str: - if any(c.status == "supported" for c in claims): - return "medium" - if any(c.status == "descriptive" for c in claims): - return "low" - return "unknown" - - -def _signal_status(signal: dict[str, Any]) -> str: - if _is_leaky_signal(signal): - return "descriptive" - if signal.get("reject") is True: - return "supported" - if signal.get("reject") is False: - return "inconclusive" - return "descriptive" - - -def _signal_summary(signal: dict[str, Any]) -> str: - parts = [] - if signal.get("effect") is not None: - parts.append(f"effect={_fmt(signal.get('effect'))}") - ci = signal.get("ci") - if isinstance(ci, list | tuple) and len(ci) == 2: - parts.append(f"CI={_fmt(ci[0])}..{_fmt(ci[1])}") - if signal.get("e_value") is not None: - parts.append(f"e={_fmt(signal.get('e_value'))}") - verdict = "supported" if signal.get("reject") is True else "not supported" - return f"{verdict}" + (f" ({', '.join(parts)})" if parts else "") - - -def _claim_text(signal: dict[str, Any]) -> str: - name = str(signal.get("display_name") or display_name(signal.get("name") or "signal")) - if _is_leaky_signal(signal): - return f"{name} tracks the failure label and is treated as descriptive plumbing." - if signal.get("reject") is True: - return f"{name} is associated with FAIL cases on the confirmation split." - if signal.get("reject") is False: - return f"{name} did not produce a supported FAIL/PASS association." - return f"{name} is an exploratory signal without a host-confirmed verdict." - - -def _signal_interpretation(signal: dict[str, Any]) -> str: - if _is_leaky_signal(signal): - return "This is useful for auditing the pipeline, not for explaining the failure." - if signal.get("reject") is True: - return "Use this as a confirmed association that can motivate M3 hypotheses." - if signal.get("reject") is False: - return "Treat this as a negative or underpowered result unless new data changes it." - return "Treat this as descriptive only." - - -def _do_not_infer(signal: dict[str, Any]) -> str: - if _is_leaky_signal(signal): - return "Sanity check only: do not rank this as a root cause." - return "Do not infer causality from association without M4/M5 support." - - -def _plural(count: int, singular: str, plural: str | None = None) -> str: - return singular if count == 1 else (plural or f"{singular}s") - - -def _downstream_for_signal(name: str, story: dict[str, Any]) -> list[str]: - out = [] - needle = name.lower() - for diag in story.get("diagnoses") or []: - refs = " ".join(str(x) for x in (diag.get("referenced_charts") or [])).lower() - hyps = diag.get("hypotheses") or [] - if needle in refs or any(needle in str(h).lower() for h in hyps): - out.append(f"M3 cycle {diag.get('cycle')}: referenced in diagnosis context") - return out - - -def _chart_evidence_for_signal(name: str, explore_report: dict[str, Any]) -> list[str]: - out = [] - lname = name.lower() - for chart in explore_report.get("charts") or []: - if not isinstance(chart, dict): - continue - title = str(chart.get("title") or chart.get("name") or "") - blob = " ".join(str(chart.get(k, "")) for k in ("name", "title", "data")).lower() - if lname in blob or any(part and part in blob for part in lname.split("_")): - out.append(f"chart:{_slug(title)}") - return out[:3] - - -def _critique(explore_report: dict[str, Any], signals: list[dict[str, Any]]) -> list[str]: - raw = explore_report.get("critique") - if isinstance(raw, list): - return [str(x) for x in raw] - notes = [str(c) for c in (explore_report.get("caveats") or [])] - if any(_is_leaky_signal(s) for s in signals): - notes.append("One or more signals are sanity checks and are demoted to descriptive evidence.") - if not notes: - notes.append("No explicit critique was recorded; inspect raw artifacts before over-claiming.") - return notes - - -def _next_actions(explore_report: dict[str, Any], claims: list[Claim]) -> list[str]: - actions = [str(x) for x in (explore_report.get("recommended_confirmatory_tests") or [])] - if any(c.status == "supported" for c in claims): - actions.append("Inspect the linked M3/M4 outcomes before treating supported signals as causes.") - if not actions: - actions.append("Re-run with a larger held-out split or richer probes if no claim is supported.") - return actions - - -def _sort_claims(claims: list[Claim]) -> list[Claim]: - order = {"supported": 0, "inconclusive": 1, "refuted": 2, "descriptive": 3} - return sorted(claims, key=lambda c: (order.get(c.status, 9), c.id)) - - -def _is_leaky_signal(signal: dict[str, Any]) -> bool: - name = str(signal.get("name", "")).lower() - if name.startswith("probe1") or "false_detection" in name: - return True - eff = signal.get("effect") - ci = signal.get("ci") or [None, None] - try: - lo, hi = float(ci[0]), float(ci[1]) - return eff is not None and abs(float(eff)) >= 0.999 and (hi - lo) <= 1e-6 - except (TypeError, ValueError, IndexError): - return False - - -def _fmt(value: Any) -> str: - try: - return f"{float(value):+.3f}" - except (TypeError, ValueError): - return str(value) - - -def _slug(value: str) -> str: - text = "".join(ch.lower() if ch.isalnum() else "_" for ch in value).strip("_") - return text or "artifact" diff --git a/evalrx/reporting/dynamic.py b/evalrx/reporting/dynamic.py index 053270a4..eb3c2ccc 100644 --- a/evalrx/reporting/dynamic.py +++ b/evalrx/reporting/dynamic.py @@ -4,6 +4,12 @@ choose how to arrange a small, typed component catalog, but every value shown by the UI is resolved from :class:`ReportData`; the model cannot invent data or arbitrary executable UI. + +:func:`build_report_data` assembles that data from +:mod:`~evalrx.reporting.report_inputs` (what the run recorded), +:mod:`~evalrx.reporting.stage_views` (the per-stage views, with +:mod:`~evalrx.reporting.stage_figures` and :mod:`~evalrx.reporting.stage_examples`) +and :mod:`~evalrx.reporting.report_summary` (the top-line reading). """ from __future__ import annotations @@ -11,13 +17,36 @@ import base64 import hashlib import json -import os import re from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -from typing import Any, Iterable, Mapping, Sequence - +from typing import Any, Mapping, Sequence + +from evalrx.reporting.report_inputs import ( + _assign_partitions, + _contract_model_name, + _contract_payloads, + _media_index, + _normalise_case, + _repair_outcomes, +) +from evalrx.reporting.report_summary import _charts, _explore_metrics, _findings, _metrics, _repairs +from evalrx.reporting.stage_views import _stage_detail, _stages + +# 23: `case.choices` and `case.task` are read from the case metadata, and a +# case's media slots are paired with their in-run copies by file name. +# 22: every field is read from the run log. `case.repair` and M5's worked +# example, `setting.diagnosed_by`, the case study's example answers, M2's +# group rates and each M4 verdict's own evidence are filled again; +# `stage_detail.m3` drops `agent_response` / `unparsed_proposals` and +# partitions drop `inferred`. +# 21: `setting.finished` / `setting.last_event_at`, for a run still being +# written (the log's `run_end`, schema 7). +# 20: `setting.kind` (an explore output renders as its own report) and the +# explore agent's analysis on `stage_detail.m2.agent`. +# 19: the M5 confirmation joins the winning candidate the fix event records, and +# the "Cases repaired" tile reads it. # 18: `setting.partitions` + `case.split` — which band of the frozen batch # each case sat in (explore / held-out / confirm), so the Case Studio can # show the split the run was actually measured on. @@ -30,7 +59,7 @@ # makes an already-published run pick the change up — `report_is_current` # only tracks new EVENTS, so without the bump every existing run would # keep serving the labels its old compiler produced. -REPORT_DATA_VERSION = 19 +REPORT_DATA_VERSION = 23 REPORT_SCHEMA_VERSION = 1 JSON_RENDER_VERSION = "0.19.0" CATALOG_VERSION = "evalrx-report@2" @@ -43,15 +72,12 @@ "Journey", "FindingGrid", "ChartGrid", - "OutcomeCard", "CasePreview", "CaseStudySheet", "LoopFigure", "EvidenceIndex", } ) -# OutcomeCard stays in ALLOWED_COMPONENTS so layouts published before it was -# dropped from the page still validate; the renderer draws nothing for it. REQUIRED_COMPONENTS = frozenset({"SettingHero"}) # The page needs one picture of the M1-M5 loop: the plain stage strip, or the # loop figure that folds the case-study sheet into it. @@ -59,39 +85,6 @@ MAX_ELEMENTS = 40 MAX_DEPTH = 6 -# These labels are deliberately about the behaviour being measured, rather -# than the analyzer implementation that happened to measure it. Unknown keys -# still get a deterministic readable fallback and preserve their raw key in -# the audit-only fields below. -PLAIN_LABELS = { - "answer_extraction_audit": "Did the model give a usable answer?", - "calibration": "Is the model confident when it is wrong?", - "termination_audit": "Did the model stop before finishing?", - "format_sensitivity": "Does changing answer order change its choice?", - "selfcheck_consistency": "Does the model contradict itself?", - "coverage_verification_gap": "Can repeated attempts ever find the right answer?", - "logprob_entropy": "Does the model appear uncertain while answering?", - "self_consistency": "Does the answer stay the same across retries?", - "signal_label_assoc": "How strongly is this behavior linked to errors?", - "rank_corr": "Do more of this behavior and more errors move together?", - "single_rate_evalue": "Is this rate unlikely to be chance?", - "n_correct": "Number of correct attempts", - "any_correct": "At least one correct attempt", - "majority_correct": "Most attempts were correct", - "format_flip_rate": "Answer changed after reordering choices", - "positional_bias": "Tendency to favor one answer position", - "output_chars": "Length of the model answer", - "output_truncated": "Answer appears cut short", - "recovered_by_continuation": "Could continue to a usable answer", - "pass_at_k": "Share of retries that were correct", - "n_sentences": "Number of answer sentences checked", - "conf_logprob": "How certain the model appeared", - "label_disagrees": "Recorded answer disagrees with the label", - "has_answer_tag": "Used the requested answer format", - "extracted_answer": "Answer read from the output", - "labelled_fail": "This case was an error", -} - @dataclass(frozen=True) class PublishedReport: @@ -108,18 +101,13 @@ class ReportSpecError(ValueError): """Raised when a Report Agent emits an unsafe or invalid layout.""" -def build_report_data( - run_dir: str | Path, - *, - example_dir: str | Path | None = None, -) -> dict[str, Any]: +def build_report_data(run_dir: str | Path) -> dict[str, Any]: """Build the renderer-neutral data model for any completed EvalRX run.""" root = Path(run_dir).resolve() from evalrx.reporting.case_study import build_case_study from evalrx.reporting.run_data import extract_run_data - resolved_example = Path(example_dir).resolve() if example_dir else _infer_example_dir(root) - raw = extract_run_data(root, resolved_example) + raw = extract_run_data(root) events = _read_events(root) # The logger copies each case's media under artifacts/case_media/ and records # the RUN-RELATIVE path beside the case. Carry it onto the case: inputs. @@ -134,7 +122,7 @@ def build_report_data( if isinstance(case, dict): local = [p for p in (event.get("media_paths") or []) if isinstance(p, str)] # The partition the loop logged the case under (see - # RunLoggerV2.log_cases). Absent on runs from before it was recorded. + # RunLogger.log_cases). Absent on runs from before it was recorded. split = event.get("split") extra: dict[str, Any] = {} if local: @@ -142,7 +130,7 @@ def build_report_data( if isinstance(split, str) and split: extra["_split"] = split case_events.append({**case, **extra} if extra else case) - cases = [case for case in case_events if isinstance(case, dict)] or list(raw.get("cases") or []) + cases = case_events run = dict(raw.get("run") or {}) trace_id = str((events[-1] if events else {}).get("trace_id") or root.name) reader = dict(raw.get("reader_report") or {}) @@ -152,28 +140,22 @@ def build_report_data( contract = _contract_payloads(root) findings = _findings(reader, raw) charts = _charts(run, raw, contract) - repairs = _repairs(raw) media = _media_index(cases) normalized_cases = [_normalise_case(case, media) for case in cases if isinstance(case, dict)] - normalized_cases = _merge_recorded_case_evidence(normalized_cases, root) # Attach what M5's repair answered on each case, so "12 repaired, 1 broken" # is thirteen cases a reader can open rather than two numbers. - repairs = _repair_outcomes(root, contract) + repair_outcomes = _repair_outcomes(events) for case in normalized_cases: - hit = repairs.get(case["id"]) + hit = repair_outcomes.get(case["id"]) if hit: case["repair"] = hit # Which partition each case sat in -- explore for M1-M3, the withheld - # confirm / test pools for M4 and M5 -- read off the records when the run - # tagged them, inferred from the record order when it did not. - partitions = _assign_partitions( - normalized_cases, - logged_ids=[str(c.get("id") or c.get("case_id") or "") for c in case_events], - n_explore=run.get("n_cases"), - final_ids=set(repairs), - ) + # confirm / test pools for M4 and M5 -- as the run tagged them. + partitions = _assign_partitions(normalized_cases) stage_detail = _stage_detail(raw, root, normalized_cases, events) - stages = _stages(raw, stage_detail.get("m5") if isinstance(stage_detail, dict) else None) + m5_detail = stage_detail.get("m5") if isinstance(stage_detail, dict) else None + stages = _stages(raw, m5_detail) + repairs = _repairs(raw, m5_detail) setting = { "model": _contract_model_name(contract) or run.get("model") or "Target model", "dataset": run.get("benchmark_name") or "Evaluation dataset", @@ -197,17 +179,24 @@ def build_report_data( # repr() -- an unreadable line ending in a memory address. "model": _contract_model_name(contract) or run.get("model") or "Target model", "dataset": run.get("benchmark_name") or "Evaluation dataset", + # What produced the run: the diagnose loop, or an explore step + # on its own (no model was evaluated; only M2/M3 ran). + "kind": run.get("kind") or "loop", "question": reader.get("question") or "Why did the model fail, and can we fix it?", "protocol": run.get("protocol") or "", # Who drove the pipeline, as opposed to `model`, which is what # it was pointed at. Empty when the run recorded neither. - "diagnosed_by": _diagnosed_by(root, run), + "diagnosed_by": _diagnosed_by(run), + # Whether the run is over, and when it last logged anything: + # what the UI needs to say "in progress" without guessing. + "finished": _run_finished(events, root), + "last_event_at": max((str(e["ts"]) for e in events if e.get("ts")), default=None), # The cover figure the run shipped, if any — see _hero_image. "hero_image": _hero_image(root), "n_cases": int(run.get("n_cases") or len(normalized_cases)), # The frozen batch's partitions, in the order they are drawn: # explore, then what was withheld. Empty when the run recorded - # no split and none can be inferred. + # no split. "partitions": partitions, }, "summary": { @@ -216,9 +205,9 @@ def build_report_data( "confidence": reader.get("confidence") or "unknown", "stopped_by": run.get("stopped_by") or "completed", }, - "metrics": _metrics( - run, raw, normalized_cases, - stage_detail.get("m5") if isinstance(stage_detail, dict) else None, + "metrics": ( + _explore_metrics(stage_detail) if run.get("kind") == "explore" + else _metrics(run, raw, normalized_cases, m5_detail) ), "stages": stages, "findings": findings, @@ -390,13 +379,12 @@ def validate_spec(spec: Any, *, data: Mapping[str, Any] | None = None) -> dict[s def publish_report( run_dir: str | Path, *, - example_dir: str | Path | None = None, model: Any | None = None, run_logger: Any | None = None, ) -> PublishedReport: """Compile, compose, validate, cache, and optionally log a completed report.""" root = Path(run_dir).resolve() - data = build_report_data(root, example_dir=example_dir) + data = build_report_data(root) mode = "deterministic" model_name: str | None = None spec = fallback_spec(data) @@ -438,14 +426,6 @@ def load_published_report(run_dir: str | Path) -> tuple[dict[str, Any], dict[str root = run_root / "report" data = json.loads((root / "report_data.json").read_text(encoding="utf-8")) envelope = json.loads((root / "report_spec.json").read_text(encoding="utf-8")) - # Reports published before the explicit-props contract omitted `props` for - # simple catalog elements. Make those immutable artifacts viewable while - # newly generated layouts are rejected and repaired by ReportAgent. - spec = envelope.get("spec") - if isinstance(spec, dict) and isinstance(spec.get("elements"), dict): - for element in spec["elements"].values(): - if isinstance(element, dict): - element.setdefault("props", {}) # Do not make an old agent-composed layout disappear merely because the # renderer learned a richer data projection. Rebuild its data in memory; # the saved layout and its provenance remain untouched. @@ -470,7 +450,17 @@ def report_is_current(run_dir: str | Path) -> bool: ), default=0, ) - return cached_seq >= evidence_seq + if cached_seq < evidence_seq: + return False + # An explore output has no event log: a rerun shows only as a report file + # newer than the cached layout. + from evalrx.reporting.run_data import EXPLORE_REPORTS + + cached_at = (root / "report" / "report_spec.json").stat().st_mtime + return not any( + (root / name).is_file() and (root / name).stat().st_mtime > cached_at + for name in EXPLORE_REPORTS + ) #: CLI providers under the names their vendors use. A provider absent here is @@ -524,1449 +514,41 @@ def _hero_image(root: Path) -> str: return "" -def _diagnosed_by(root: Path, run: Mapping[str, Any]) -> str: +def _run_finished(events: Sequence[Mapping[str, Any]], root: Path) -> bool: + """Whether the run logged its completion signal. + + ``run_end`` is written when the logger closes. An output with no run log + at all (an explore step's report) is finished as written; a run log with + no readable events yet has just begun. + """ + if not events: + return not any((where / "run.json").is_file() for where in (root, root / "logs")) + return any(e.get("event") == "run_end" for e in events) + + +def _diagnosed_by(run: Mapping[str, Any]) -> str: """Which agent drove this run, as one display string, or "" if unrecorded. Two runs of the same benchmark against the same model differ ONLY in the - agent that drove them, and the report never said which — open both and they - are indistinguishable. The run manifest records the choice cleanly - (`judge_provider` / `judge_model`); the run_start event's `coder` - ("claude_code:opus") is the fallback for a run written before the manifest, - and its `judge` is a repr, so it is read only for its provider prefix. + agent that drove them, and without this the report never says which. The + run_start event records it as `coder` ("claude_code:claude-opus-5"). """ - config = _load_json(root / "manifest.json") - config = (config or {}).get("config") if isinstance(config, Mapping) else None - provider = model = "" - if isinstance(config, Mapping): - provider = str(config.get("judge_provider") or "") - model = str(config.get("judge_model") or "") - if not provider: - coder = str(run.get("coder") or "") - if ":" in coder: - provider, _, model = coder.partition(":") - else: - provider = coder + provider, _, model = str(run.get("coder") or "").partition(":") if not provider: return "" label = _AGENT_LABEL.get(provider.strip().lower(), provider.strip()) return f"{label} · {model.strip()}" if model.strip() else label -def _stages(raw: Mapping[str, Any], m5_detail: Mapping[str, Any] | None = None) -> list[dict[str, Any]]: - definitions = [ - ("M1", "Check behavior", "See what the model does differently when it succeeds or fails", raw.get("m1"), "results"), - ("M2", "Find patterns", "Look for behaviors that reliably appear alongside errors", raw.get("m2"), "stats"), - ("M3", "Suggest causes", "Turn the strongest patterns into ideas that can be tested", raw.get("m3"), "hypotheses"), - ("M4", "Test on new cases", "Check those ideas on evidence not used to create them", raw.get("m4"), "results"), - ("M5", "Try repairs", "Compare possible fixes with the unchanged model", raw.get("m5_fix"), "selection"), - ] - result = [] - for code, title, purpose, payload, evidence_key in definitions: - stage = dict(payload or {}) - evidence = stage.get(evidence_key) or [] - ran = bool(stage.get("ran")) if "ran" in stage else bool(evidence or stage.get("duration")) - status = "completed" if ran else "not-run" - if code == "M5" and m5_detail and m5_detail.get("skipped"): - status = "skipped" - if code == "M5" and ran: - status = "improved" if stage.get("fixed") else "no-improvement" - result.append({ - "id": code.lower(), "code": code, "title": title, "purpose": purpose, - "status": status, "evidence_count": len(evidence) if isinstance(evidence, list) else 1, - }) - return result - - -def _stage_detail( - raw: Mapping[str, Any], root: Path, cases: list[dict[str, Any]], events: list[Mapping[str, Any]] -) -> dict[str, Any]: - """Compile the mature stage-specific views into a bounded web contract. - - The shape is :class:`evalrx.contract.stage_detail.StageDetail`. It preserves - the old workbench's load-bearing distinctions: M2 is descriptive, M3 is - proposal-only, M4 owns held-out verdicts, and M5 compares every - intervention against the unchanged baseline. - """ - logs_dir = Path(raw.get("logs_dir") or root) - m2 = dict(raw.get("m2") or {}) - explore = dict(m2.get("explore") or {}) - # M3 starts from M2's evidence, so both stages read the same figures and stats. - figures = _m2_figures(raw, m2, explore, logs_dir, root) - stats = [ - _display_stat(item) - for item in _enrich_m2_stats( - [item for item in m2.get("stats") or [] if isinstance(item, Mapping)], logs_dir - ) - ] - return { - "m1": _m1_detail(dict(raw.get("m1") or {}), cases, events), - "m2": _m2_detail(m2, explore, figures, stats), - "m3": _m3_detail(raw, explore, figures, stats), - "m4": _m4_detail(dict(raw.get("m4") or {}), logs_dir, cases, events), - "m5": _m5_detail(raw, cases, events), - } - - -def _m1_detail( - m1: Mapping[str, Any], cases: list[dict[str, Any]], events: list[Mapping[str, Any]] -) -> dict[str, Any]: - probes = [] - for result in m1.get("results") or []: - if not isinstance(result, dict): - continue - rows = list(result.get("per_case") or []) - probes.append({ - "id": str(result.get("name") or "probe"), - # The plain question when the label table has one; otherwise the - # glossary's name ("Self-Repair on Re-ask"), never a Title-Cased id. - "title": (PLAIN_LABELS.get(str(result.get("name") or "")) - or str(result.get("display_name") or "") - or _plain_label(result.get("name") or "Probe")), - # The glossary's own name for the check ("Self-Repair on Re-ask"), - # as opposed to `title`, which is the plain question when one exists. - "display_name": str(result.get("display_name") or ""), - "raw_name": str(result.get("name") or ""), - "question": str(result.get("question") or ""), - "description": str(result.get("description") or ""), - # None when the analyzer reported no case count at all (a batch-level - # check such as self_consistency): "unknown" is not "zero". - "n_cases": result.get("n") if result.get("n") is not None else (len(rows) or None), - "metrics": list(result.get("headline") or []), - "finding_summary": _plain_mapping(_compact_mapping(result.get("findings"))), - "raw_finding_summary": _compact_mapping(result.get("findings")), - "sample_rows": rows[:12], - "n_sample_rows": len(rows), - }) - # Examples are a first-class, bounded evidence type. They are deliberately - # derived from recorded case I/O and per-case measurements, never written - # by the report agent. A single case makes a measurement legible; it does - # not establish the stage conclusion (the UI states that boundary too). - logged_examples = [ - item for event in events if event.get("event") == "probe" - for item in (event.get("examples") or []) if isinstance(item, Mapping) - ] - examples = [dict(item) for item in logged_examples[:2]] or _m1_examples(probes, cases) - calls, n_calls = _m1_calls(events) - return { - "duration": m1.get("duration"), "probes": probes, - "n_probes": len(probes), "n_measured": max((int(p.get("n_cases") or 0) for p in probes), default=0), - "examples": _attach_example_media(examples, cases), - # A trajectory is the only source allowed to say that an agent actually - # used an intermediate operation (zoom, crop, search, ...). Candidate - # specs are kept separately (M5's operation previews) because a - # proposed operation is not an executed one. - "operations": _operation_examples(cases), - # What each probe actually asked the model and what came back, - # grouped by analyzer: the audit trail behind the numbers above. - "calls": calls, "n_calls": n_calls, - } - - -def _m2_figures( - raw: Mapping[str, Any], m2: Mapping[str, Any], explore: Mapping[str, Any], - logs_dir: Path, root: Path, -) -> list[dict[str, Any]]: - figure_dir = Path(raw.get("explore_dir") or logs_dir.parent / "explore") / "figures" - figures = _explore_figures(explore, figure_dir, root) - if not figures: - # No explore/ directory beside the logs: a V2 run. RunLoggerV2 copied - # the explorer's figures into M2/artifacts/ under hashed names and - # kept the original name of each beside the copy; that name is what - # the takeaways cite, so the join runs on it. - figures = _snapshot_figures(explore, logs_dir, root) - if not figures: - # Neither (a run copied as logs/ alone, or one recorded before the - # snapshot kept names): the explore and analysis events still name - # their figures as paths under logs/. - return _logged_figures( - [*(explore.get("figures") or []), *(m2.get("figures") or [])], logs_dir, root) - # The analysis step's own chart sits beside the explorer's, as it did - # when both came off the events. - known = {figure["path"] for figure in figures} - return figures + [ - figure for figure in _logged_figures(m2.get("figures") or [], logs_dir, root) - if figure["path"] not in known - ] - - -def _m2_detail( - m2: Mapping[str, Any], explore: Mapping[str, Any], - figures: list[dict[str, Any]], stats: list[dict[str, Any]], -) -> dict[str, Any]: - takeaways = [ - {key: item.get(key) for key in ( - "plain_title", "title", "analysis", "caveat", "chart_names", "table_names", - )} - for item in explore.get("takeaways") or [] if isinstance(item, dict) - ] - return { - "mode": "descriptive", "conclusion": m2.get("conclusion") or "", - "narrative": m2.get("narrative") or "", "stats": stats, - "takeaways": takeaways, "figures": figures, - "observations": list(explore.get("observations") or []), - "caveats": list(explore.get("caveats") or []), - "candidate_signals": list(explore.get("candidate_signals") or []), - "recommended_tests": list(explore.get("recommended_confirmatory_tests") or []), - } - - -def _m3_detail( - raw: Mapping[str, Any], explore: Mapping[str, Any], - figures: list[dict[str, Any]], stats: list[dict[str, Any]], -) -> dict[str, Any]: - judges = list((raw.get("agents") or {}).get("judge_calls") or []) - m3_call = next((call for call in judges if "M3" in str(call.get("stage") or "")), {}) - agent_response = str(m3_call.get("response") or "") - m3 = dict(raw.get("m3") or {}) - hypotheses = list(m3.get("hypotheses") or explore.get("hypotheses") or []) - # Runs recorded before the log writer carried `plain_statement` on this list - # still have it on `proposed_hypotheses`, which the critic step copies from. - # Joining on the statement recovers the plain sentence the judge did write, - # instead of leaving the report showing only the technical line. A run with - # neither is left exactly as it is — nothing is paraphrased into existence. - proposed = {str(h.get("statement") or ""): h - for h in (m3.get("proposed_hypotheses") or []) if isinstance(h, Mapping)} - for h in hypotheses: - if isinstance(h, dict) and not h.get("plain_statement"): - recovered = proposed.get(str(h.get("statement") or ""), {}).get("plain_statement") - if recovered: - h["plain_statement"] = recovered - return { - "mode": "proposal", "hypotheses": hypotheses, - "unparsed_proposals": _recover_unparsed_hypotheses(agent_response) if not hypotheses else [], - "agent_response": agent_response, - "candidate_signals": list(explore.get("candidate_signals") or []), - "recommended_tests": list(explore.get("recommended_confirmatory_tests") or []), - "evidence_figures": figures[:3], "evidence_stats": stats[:6], - } - - -def _m4_detail( - m4: Mapping[str, Any], logs_dir: Path, cases: list[dict[str, Any]], - events: list[Mapping[str, Any]], -) -> dict[str, Any]: - saved = _load_json(logs_dir / "report" / "m4_results.json") - results = saved if isinstance(saved, list) and saved else list(m4.get("results") or []) - event = dict(m4.get("event") or {}) - logged = next(( - item for item in reversed(events) - if item.get("event") == "surgery" and item.get("module") == "m4" - ), {}) - return { - "ran": bool(m4.get("ran") or results), "mode": "confirmatory", - "results": results, "event": event, - "examples": _attach_example_media(_m4_examples(results, {**event, **logged}, cases), cases), - } - - -def _m5_detail( - raw: Mapping[str, Any], cases: list[dict[str, Any]], events: list[Mapping[str, Any]] -) -> dict[str, Any]: - m5 = dict(raw.get("m5_fix") or {}) - # extract_run_data may see an older sibling log when an example contains - # multiple attempts. The event stream is trace-filtered and is the source - # of truth for the run currently being rendered. - fix_event = next((event for event in reversed(events) if event.get("event") == "fix"), {}) - skipped_event = next(( - event for event in reversed(events) - if event.get("event") == "stage_skipped" and str(event.get("stage")) == "M5" - ), {}) - if fix_event: - attempted = [item for item in fix_event.get("attempted") or [] if isinstance(item, Mapping)] - # RunLoggerV2 records `best` as the whole winning candidate (older - # producers wrote its bare name); comparing that dict to a name never - # matched, so the confirmation stayed empty on every v2 run. - best_name = _repair_name(fix_event.get("best")) - best = next((item for item in attempted if item.get("name") == best_name), {}) if best_name else {} - if not best and best_name and isinstance(fix_event.get("best"), Mapping): - best = dict(fix_event["best"]) - m5.update({ - "ran": True, "fixed": bool(fix_event.get("fixed")), "selection": attempted, - "best": best, "confirm": best, "recommendation": fix_event.get("recommendation"), - }) - if skipped_event: - m5.update({ - "ran": False, - "skipped": True, - "skip_reason": skipped_event.get("reason_code") or "not_attempted", - "skip_detail": skipped_event.get("detail") or "", - }) - candidates = [_repair_candidate(item) for item in m5.get("selection") or [] if isinstance(item, dict)] - confirmation = _repair_candidate(m5.get("confirm") or {}) - if confirmation.get("name"): - existing = next((i for i, item in enumerate(candidates) if item.get("name") == confirmation["name"]), None) - if existing is None: - candidates.append(confirmation) - else: - candidates[existing] = {**candidates[existing], **confirmation} - return { - "ran": bool(m5.get("ran")), "fixed": bool(m5.get("fixed")), - "skipped": bool(m5.get("skipped")), - "skip_reason": str(m5.get("skip_reason") or ""), - "skip_detail": str(m5.get("skip_detail") or ""), - "candidates": candidates, "confirmation": confirmation, - "best": _repair_candidate(m5.get("best") or {}), - # The FixAgent's own verdict on the run — action + the sentence that - # justifies it ("underpowered: only 4 failing cases…"). This is the - # line the health card's promotion gate prints. - "recommendation": (dict(m5["recommendation"]) - if isinstance(m5.get("recommendation"), Mapping) else None), - "examples": _m5_examples(candidates, cases, list((raw.get("m1") or {}).get("results") or [])), - "operation_previews": _repair_operation_previews(candidates, cases), - "surgeries": list((raw.get("m5_surgery") or {}).get("surgeries") or []), - "prompt_template": str(m5.get("prompt_template") or ""), - } - - -def _m1_examples(probes: list[Mapping[str, Any]], cases: list[Mapping[str, Any]]) -> list[dict[str, Any]]: - """Pick recorded, human-readable M1 case walk-throughs. - - Recent loggers may include ``examples`` directly on a probe. Older runs - are reconstructed by joining a per-case measurement to the saved baseline - case record. The latter intentionally says *check result*, not - *after-answer*: many analyzers do not issue a second generation. - """ - case_by_id = {str(case.get("id")): case for case in cases} - result: list[dict[str, Any]] = [] - used: set[str] = set() - for probe in probes: - supplied = probe.get("examples") - if isinstance(supplied, list): - for item in supplied: - if isinstance(item, Mapping): - result.append(dict(item)) - if len(result) >= 2: - return result - rows = [row for row in probe.get("sample_rows") or [] if isinstance(row, Mapping)] - # Failures are most intuitive when available. A pass is still useful - # when the run has no labelled failures in this particular probe. - rows.sort(key=lambda row: 0 if str(case_by_id.get(str(row.get("sample_id")), {}).get("status")) == "fail" else 1) - for row in rows: - case_id = str(row.get("sample_id") or row.get("case_id") or "") - case = case_by_id.get(case_id) - if not case or case_id in used: - continue - measured = { - str(key).replace("_", " "): value - for key, value in row.items() - if key not in {"sample_id", "case_id"} and isinstance(value, (str, int, float, bool)) - } - if not measured: - continue - used.add(case_id) - result.append({ - "id": f"m1-{probe.get('id', 'probe')}-{case_id}", - "kind": "case_measurement", - "case_id": case_id, - "probe_title": probe.get("title") or "Behavioral check", - "probe_question": probe.get("question") or "", - "input": case.get("prompt") or "", - "baseline_output": case.get("observed"), - "expected": case.get("expected"), - "outcome": case.get("status") or "unknown", - "media_ids": list(case.get("media_ids") or []), - "check_result": measured, - "plain_reading": "This one case shows what the check records. The overall pattern comes from every measured case, not this example alone.", - "evidence_scope": "one recorded case within M1", - }) - break - if len(result) >= 2: - break - return result - - -def _attach_example_media(examples: list[dict[str, Any]], cases: list[Mapping[str, Any]]) -> list[dict[str, Any]]: - case_by_id = {str(case.get("id")): case for case in cases} - for example in examples: - if example.get("probe_title"): - example["probe_title"] = _plain_label(example["probe_title"]) - if example.get("media_ids"): - continue - case = case_by_id.get(str(example.get("case_id") or "")) - if case: - example["media_ids"] = list(case.get("media_ids") or []) - return examples - - -def _m4_examples( - results: list[Any], event: Mapping[str, Any], cases: list[Mapping[str, Any]] -) -> list[dict[str, Any]]: - """Return explicit validation examples, with a truthful aggregate fallback.""" - supplied = event.get("validation_examples") if isinstance(event, Mapping) else None - if isinstance(supplied, list): - first = next((item for item in results if isinstance(item, Mapping)), {}) - evidence = first.get("evidence") if isinstance(first.get("evidence"), Mapping) else {} - kept = [{ - **dict(item), - "hypothesis": item.get("hypothesis") or first.get("hypothesis") or first.get("statement"), - "test": item.get("test") or first.get("test_name") or evidence.get("chosen_tool"), - "status": item.get("status") or first.get("status"), - } for item in supplied if isinstance(item, Mapping)] - if kept: - return kept[:2] - if not results: - return [] - first = next((item for item in results if isinstance(item, Mapping)), None) - if first is None: - return [] - evidence = first.get("evidence") if isinstance(first.get("evidence"), Mapping) else {} - # Legacy M4 logs retain the frozen claim and the actual validation statistic - # but not a row-level verdict. That is still a concrete example of the - # validation operation; label it as an aggregate test rather than pretend a - # case was individually adjudicated. - return [{ - "id": "m4-validation-test-1", - "kind": "validation_test", - "hypothesis": first.get("hypothesis") or first.get("statement") or "Frozen hypothesis", - "test": first.get("test_name") or evidence.get("chosen_tool") or "held-out statistical test", - "effect": first.get("effect_size", evidence.get("effect_size")), - "interval": evidence.get("ci"), - "status": first.get("status") or "inconclusive", - "verdict": first.get("verdict") or evidence.get("m4_verdict") or "No validation explanation was retained.", - "plain_reading": "This is one frozen claim tested on the independent validation evidence. The verdict uses the full validation set, not a single hand-picked case.", - "evidence_scope": "aggregate independent-validation test", - }] - - -def _display_stat(value: Mapping[str, Any]) -> dict[str, Any]: - """Keep statistical evidence machine-auditable but primary labels human.""" - config = value.get("config") if isinstance(value.get("config"), Mapping) else {} - signal = str(config.get("signal") or value.get("signal") or value.get("tool") or "") - details = value.get("details") if isinstance(value.get("details"), Mapping) else {} - # A PAIRED tool compares two strategies and carries no `signal`, so `signal` - # falls through to the tool name and every such row was labelled with the - # same words ("Mcnemar Evalue"). Three identically-labelled bars is not a - # chart. The pair it actually compared is right there in the config, and it - # is the only thing that tells the rows apart. - groups = [str(name) for name in (config.get("strategies") or []) if name] - label = _stat_label(config, signal, value.get("tool")) - return { - "label": label, "raw_signal": signal, "groups": groups, - "effect": value.get("effect"), "ci": value.get("ci"), - "reject": bool(value.get("reject")), "underpowered": bool(value.get("underpowered")), - "summary": value.get("summary") or "", "p_value": value.get("p_value"), - "tool": value.get("tool"), "e_value": value.get("e_value"), - "fail_rate_signal": details.get("fail_rate_signal"), - "fail_rate_control": details.get("fail_rate_control"), - } - - -def _enrich_m2_stats(stats: list[Mapping[str, Any]], logs_dir: Path) -> list[dict[str, Any]]: - """Restore detailed M2 rate fields from durable tool-result artifacts. - - The compact HTML reader deliberately omits bulky ``details``. Its - omission used to leave the dynamic M2 view with only one generic effect - chart, despite the run already having stored the two groups needed for a - direct error-rate comparison. This is a local join keyed by the exact - test and signal; no values are re-computed or inferred. - """ - artifact_rows: dict[tuple[str, str], Mapping[str, Any]] = {} - for path in sorted((logs_dir / "artifacts").glob("*m2_stats_results*.json")): - value = _load_json(path) - if not isinstance(value, list): - continue - for item in value: - if not isinstance(item, Mapping): - continue - config = item.get("config") if isinstance(item.get("config"), Mapping) else {} - key = (str(item.get("tool") or ""), str(config.get("signal") or item.get("signal") or "")) - if key[1]: - artifact_rows[key] = item - result: list[dict[str, Any]] = [] - for item in stats: - config = item.get("config") if isinstance(item.get("config"), Mapping) else {} - key = (str(item.get("tool") or ""), str(config.get("signal") or item.get("signal") or "")) - saved = artifact_rows.get(key) - result.append({**dict(item), **({"details": saved.get("details")} if saved and saved.get("details") else {})}) - return result - - -def _operation_examples(cases: list[Mapping[str, Any]]) -> list[dict[str, Any]]: - """Project recorded agent tool trajectories into compact, case-linked UI cards. - - This intentionally ignores prompt text that *mentions* a tool. An action - appears only if a persisted trajectory step carries a structured - ``tool_call``. That preserves the distinction between an actual zoom and - an LLM merely proposing one. - """ - result: list[dict[str, Any]] = [] - for case in cases: - trajectory = case.get("trajectory") - if not isinstance(trajectory, Mapping): - continue - steps = trajectory.get("steps") - if not isinstance(steps, list): - continue - calls = [] - for step in steps: - if not isinstance(step, Mapping) or not isinstance(step.get("tool_call"), Mapping): - continue - call = step["tool_call"] - name = str(call.get("name") or "tool") - calls.append({ - "order": int(step.get("idx") or len(calls) + 1), - "action": _plain_operation(name), "raw_action": name, - "parameters": dict(call.get("args") or {}) if isinstance(call.get("args"), Mapping) else {}, - "thought": str(step.get("content") or "")[:500], - }) - if not calls: - continue - result.append({ - "id": f"operations-{case.get('id')}", "case_id": str(case.get("id") or ""), - "input": case.get("prompt") or "", "expected": case.get("expected"), - "observed": case.get("observed"), "outcome": case.get("status") or "unknown", - "media_ids": list(case.get("media_ids") or []), "steps": calls[:6], - "plain_reading": "These are the actions recorded in this agent's own trajectory for this case.", - }) - if len(result) >= 2: - break - return result - - -def _repair_operation_previews( - candidates: list[Mapping[str, Any]], cases: list[Mapping[str, Any]] -) -> list[dict[str, Any]]: - """Show what an image-operation repair *would* apply, without claiming execution. - - Older runs preserve a repair spec but not a per-call visual artifact. The - report can still pair its declared image operations with the original input - image for a representative case, as long as the card is explicitly marked - as a candidate preview. Actual execution is represented by - :func:`_operation_examples` instead. - """ - image_cases = [case for case in cases if case.get("media_ids")] - result: list[dict[str, Any]] = [] - for candidate in candidates: - payload = candidate.get("payload") if isinstance(candidate.get("payload"), Mapping) else {} - ops = [op for op in payload.get("image_ops") or [] if isinstance(op, Mapping) and op.get("tool")] - if not ops: - continue - preferred_ids = [str(item) for item in (candidate.get("fixed_cases") or candidate.get("broken_cases") or [])] - case = next((item for item in image_cases if str(item.get("id")) in preferred_ids), None) - case = case or next((item for item in image_cases if str(item.get("status")) == "fail"), None) - # A legacy run can retain its generated baseline answers in a separate - # artifact whose ids no longer line up with the saved image manifest. - # In that case an arbitrary corpus image is still useful to explain the - # *declared transform*, provided the UI calls it a preview and never a - # validated before/after result. - case = case or (image_cases[0] if image_cases else None) - if case is None: - continue - result.append({ - "id": f"repair-operations-{candidate.get('name')}", "candidate": candidate.get("name"), - "case_id": str(case.get("id") or ""), "input": case.get("prompt") or "", - "expected": case.get("expected"), "observed": case.get("observed"), - "media_ids": list(case.get("media_ids") or []), - "executed": bool(candidate.get("n_pairs")), - "operations": [{ - "action": _plain_operation(op.get("tool")), "raw_action": str(op.get("tool")), - "parameters": dict(op.get("params") or {}) if isinstance(op.get("params"), Mapping) else {}, - } for op in ops], - }) - if len(result) >= 2: - break - return result - - -def _plain_operation(value: Any) -> str: - names = { - "image_zoom_in": "Zoom in on part of the image", "zoom_center": "Zoom into the chart center", - "crop": "Crop the visual evidence", "crop_case_bbox": "Crop the relevant chart region", - "sharpen": "Sharpen chart details", "contrast": "Increase visual contrast", - "equalize": "Balance the image contrast", "detect": "Locate an object or region", - } - raw = str(value or "") - return names.get(raw, _plain_label(raw)) - - -def _m5_examples( - candidates: list[Mapping[str, Any]], cases: list[Mapping[str, Any]], probe_results: list[Any] -) -> list[dict[str, Any]]: - """Reconstruct a truthful before/after repair example — confirmed or not. - - A candidate that never cleared the significance bar is still what the - search actually tried, and a reader debugging a failed repair needs to - see a real case, not just "no candidate passed the repair gate". Prefer a - `fixed` winner (statistically significant, net-positive); when none - exists, fall back to the strongest attempt by effect size — the same - fallback `M5Detail` already uses for its own "best repair" KPI — and tag - the example `confirmed: False` so the UI can say plainly it is one - candidate's attempt, not an accepted repair. When that candidate never - flipped a case to correct either, fall back once more to a case it broke: - still evidence, just of the failure mode rather than the fix. - """ - winner = next((item for item in candidates if item.get("fixed")), None) - confirmed = winner is not None - if winner is None: - winner = max( - (item for item in candidates if isinstance(item.get("effect"), (int, float))), - key=lambda item: item["effect"], - default=(candidates[0] if candidates else None), - ) - if winner is None: - return [] - case_by_id = {str(case.get("id")): case for case in cases} - baseline_by_id: dict[str, Any] = {} - for probe in probe_results: - if not isinstance(probe, Mapping): - continue - for row in probe.get("per_case") or []: - if not isinstance(row, Mapping): - continue - case_id = str(row.get("sample_id") or row.get("case_id") or "") - output = row.get("extracted_answer", row.get("modal_answer")) - if case_id and output not in (None, ""): - baseline_by_id.setdefault(case_id, output) - - def _build(case_id: str, kind: str) -> "dict[str, Any] | None": - case = case_by_id.get(case_id) - if not case: - return None - # `case["observed"]` is the Stage-0 baseline, written once per case id - # (RunLoggerV2.log_cases dedupes by id) and never updated — it is NOT - # this candidate's repaired answer, no matter which case_record last - # touched it. The only place a candidate's own per-case output lives - # is `case["repair"]`, which build_report_data attached from that - # attempt's trial_root/outputs.jsonl (see _repair_outcomes). Confirm - # it is THIS candidate's repair, not some other one that also touched - # this case, before trusting it as "repaired". - repair_hit = case.get("repair") if isinstance(case.get("repair"), Mapping) else None - repaired = ( - repair_hit.get("output") - if repair_hit and repair_hit.get("candidate") == winner.get("name") - else None - ) - if repaired in (None, ""): - return None # no recorded per-case output for this candidate — nothing truthful to show - baseline = baseline_by_id.get(case_id) - if baseline in (None, ""): - baseline = case.get("observed") # the genuine Stage-0 answer, as a last resort - if confirmed: - reading = ("This case was counted as fixed in the paired repair evaluation. " - "The repair decision still depends on all tested cases and its " - "regression checks.") - elif kind == "fixed": - reading = ("This candidate flipped this case from wrong to right, but the " - "repair overall did not clear the significance bar against luck — " - "read it as one attempt worth inspecting, not a confirmed fix.") - else: - reading = ("This candidate did not clear the significance bar, and did not " - "flip any case to correct either — this is a case it broke instead, " - "shown so the failure mode is inspectable.") - return { - "id": f"m5-{winner.get('name', 'repair')}-{case_id}", "case_id": case_id, - "kind": kind, "confirmed": confirmed, - "repair_name": winner.get("name") or "Recorded repair", "input": case.get("prompt") or "", - "expected": case.get("expected"), "baseline_output": baseline, - "repaired_output": repaired, "media_ids": list(case.get("media_ids") or []), - "plain_reading": reading, - "baseline_available": baseline not in (None, ""), - } - - for case_id in [str(item) for item in winner.get("fixed_cases") or []]: - example = _build(case_id, "fixed") - if example: - return [example] - for case_id in [str(item) for item in winner.get("broken_cases") or []]: - example = _build(case_id, "broken") - if example: - return [example] - return [] - - -def _compact_mapping(value: Any, *, limit: int = 18) -> dict[str, Any]: - """Retain readable aggregate findings, excluding unbounded per-case maps.""" - if not isinstance(value, Mapping): - return {} - compact: dict[str, Any] = {} - for key, item in value.items(): - if key in {"per_case", "per_case_values", "case_values", "samples", "caveat"}: - continue - if isinstance(item, (str, int, float, bool)) or item is None: - compact[str(key)] = item - elif isinstance(item, list) and len(item) <= 12: - compact[str(key)] = item - elif isinstance(item, Mapping) and len(item) <= 12: - nested = {str(k): v for k, v in item.items() if isinstance(v, (str, int, float, bool)) or v is None} - if nested: - compact[str(key)] = nested - if len(compact) >= limit: - break - return compact - - -def _plain_label(value: Any) -> str: - raw = str(value or "").strip() - if not raw: - return "Recorded measurement" - if raw in PLAIN_LABELS: - return PLAIN_LABELS[raw] - return re.sub(r"\s+", " ", raw.replace("_", " ")).strip().capitalize() - - -def _stat_label(config: "Mapping[str, Any] | None", signal: Any, tool: Any) -> str: - """A name for what one statistical test measured, unique within a report. - - A signal test names its signal. A PAIRED test names none — it compares two - strategies — so the label used to fall through to the tool, and every paired - row in the report came out reading "Mcnemar Evalue". The pair it compared is - the thing that tells those rows apart, and it is already in the config. - """ - cfg = config if isinstance(config, Mapping) else {} - if cfg.get("signal"): - return _plain_signal(cfg["signal"]) - groups = [str(name) for name in (cfg.get("strategies") or []) if name] - if len(groups) >= 2: - return f"{_plain_label(groups[-1])} vs {_plain_label(groups[0])}" - return _plain_signal(signal or tool) - - -def _plain_signal(value: Any) -> str: - """Convert ``analyzer.metric`` into a question a non-expert can read.""" - raw = str(value or "") - if not raw: - return "Recorded behavior" - analyzer, _, metric = raw.partition(".") - if analyzer and metric: - return f"{_plain_label(analyzer)} — {_plain_label(metric)}" - return _plain_label(raw) - - -def _plain_mapping(value: Mapping[str, Any]) -> dict[str, Any]: - return {_plain_label(key): item for key, item in value.items()} - - -def _visual_key(value: Any) -> str: - return re.sub(r"[^a-z0-9]", "", Path(str(value or "")).stem.lower()) - - -def _logged_figures(paths: Iterable[Any], logs_dir: Path, root: Path) -> list[dict[str, Any]]: - """Figures the run logged by path (relative to logs/), that exist on disk.""" - result: list[dict[str, Any]] = [] - seen: set[Path] = set() - for item in paths: - if not isinstance(item, str) or not item.lower().endswith(".png"): - continue - candidate = (logs_dir / item).resolve() - if candidate in seen or not candidate.is_file(): - continue - seen.add(candidate) - stem = re.sub(r"_[0-9a-f]{8}$", "", candidate.stem) # the content-hash suffix V2 adds - result.append({ - "id": candidate.stem, "title": stem.replace("_", " ").strip().title(), - "question": "", "path": os.path.relpath(candidate, root), "reading": "", - "do_not_infer": "No agent-authored interpretation was saved for this figure.", - "disposition": "supporting", "not_promoted_reason": "", - }) - return result[:30] - - -#: The ordering prefix the host puts on the charts it renders -#: (``00_class_balance.png`` for the plan's ``class_balance``). -_ORDER_PREFIX = re.compile(r"^\d+_") - -_EXPLORE_FIGURE_SUFFIXES = (".png", ".jpg", ".jpeg", ".webp", ".svg") - - -def _explore_figures(explore: Mapping[str, Any], figure_dir: Path, root: Path) -> list[dict[str, Any]]: - """The explorer's figures from a V1 explore/figures/ directory.""" - files = sorted(figure_dir.glob("*.png")) if figure_dir.is_dir() else [] - return _planned_figures(explore, [(path.name, path) for path in files], root) - - -def _snapshot_figures(explore: Mapping[str, Any], logs_dir: Path, root: Path) -> list[dict[str, Any]]: - """The explorer's figures as RunLoggerV2 copied them into M2/artifacts/. - - ``media_files`` (see ``RunLoggerV2._inline_workspace``) pairs each sandbox - file -- ``figures/00_class_balance.png`` -- with its content-hashed copy - under logs/. The sandbox name is the one the takeaways cite and the visual - plan is keyed by; the copy is only where the bytes are. So the join runs - on the name and a figure's id here is a chart name, never a hash stem. - """ - pairs: list[tuple[str, Path]] = [] - for name, copied in (explore.get("media_files") or {}).items(): - if not isinstance(name, str) or not isinstance(copied, str): - continue - if not name.lower().endswith(_EXPLORE_FIGURE_SUFFIXES): - continue - candidate = (logs_dir / copied).resolve() - if candidate.is_file(): - pairs.append((Path(name).name, candidate)) - pairs.sort(key=lambda pair: pair[0]) - return _planned_figures(explore, pairs, root) - - -def _planned_figures( - explore: Mapping[str, Any], files: Sequence[tuple[str, Path]], root: Path, -) -> list[dict[str, Any]]: - """Figure records for *files*, each ``(name the explorer used, path on disk)``. - - A file the visual plan names gets the plan's reader-facing title and - question and the chart reading written for it; its id is the plan's name, - which is also what the takeaways cite. A file the plan does not name is - still shown, under its own stem minus the ordering prefix -- again the - name a takeaway would cite. - """ - plans = [item for item in explore.get("visual_plan") or [] if isinstance(item, Mapping)] - readings = [item for item in explore.get("chart_readings") or [] if isinstance(item, Mapping)] - result: list[dict[str, Any]] = [] - used: set[Path] = set() - ids: set[str] = set() - - def unique(candidate: str) -> str: - chosen, n = candidate, 2 - while chosen in ids: - chosen = f"{candidate}_{n}" - n += 1 - ids.add(chosen) - return chosen - - for plan in plans: - name = str(plan.get("name") or "") - key = _visual_key(name) - if not key: - continue - # An exact match after the ordering prefix comes off wins; only then a - # file whose name merely contains the plan's. Otherwise - # ``failrate_by_answer_length`` takes ``..._band``'s file whenever that - # one sorts first. - match = next((path for fname, path in files - if path not in used and _visual_key(_ORDER_PREFIX.sub("", fname)) == key), None) - if match is None: - match = next((path for fname, path in files - if path not in used and key in _visual_key(fname)), None) - if match is None: - continue - used.add(match) - reading = next((item for item in readings if _visual_key(item.get("chart")) == key), {}) - result.append({ - "id": unique(name), "title": str(plan.get("display_name") or name.replace("_", " ").title()), - "question": str(plan.get("question") or ""), "path": os.path.relpath(match, root), - "reading": str(reading.get("reading") or ""), - "do_not_infer": str(reading.get("do_not_infer") or ""), - "disposition": str(plan.get("disposition") or "supporting"), - "not_promoted_reason": str(plan.get("not_promoted_reason") or ""), - }) - for fname, path in files: - if path in used: - continue - stem = _ORDER_PREFIX.sub("", Path(fname).stem) - result.append({ - "id": unique(stem), "title": stem.replace("_", " ").title(), - "question": "", "path": os.path.relpath(path, root), "reading": "", - "do_not_infer": "No agent-authored interpretation was saved for this figure.", - "disposition": "audit", "not_promoted_reason": "Unlinked exploratory artifact", - }) - return result[:30] - - -def _recover_unparsed_hypotheses(response: str) -> list[dict[str, Any]]: - """Recover display-only proposals while preserving the parser failure state.""" - proposals = [] - for block in re.split(r"\n\s*\n", response.strip()): - fields: dict[str, str] = {} - for line in block.splitlines(): - if ":" not in line: - continue - key, value = line.split(":", 1) - fields[key.strip().lower()] = value.strip() - if fields.get("hypothesis"): - proposals.append({ - "statement": fields["hypothesis"], - "plain_statement": fields.get("plain_statement", ""), - "failure_mode": fields.get("failure_mode", ""), - "test_design": fields.get("test", ""), - "expected_association": fields.get("expected_association", ""), - "accepted_by_pipeline": False, - }) - return proposals[:12] - - -def _load_json(path: Path) -> Any: - try: - return json.loads(path.read_text(encoding="utf-8")) - except (OSError, ValueError, TypeError): - return None - - -def _repair_headline(value: Mapping[str, Any]) -> str: - """The candidate's own sentence, or the host's for a candidate it authored. - - Looking `visual_grounding` up in the fix agent's own table is not a - consumer guessing at a slug -- it is the package that named the candidate - saying what it does. Runs recorded before `headline` existed become - readable this way; a judge-invented name the host never heard of still - resolves to "" and renders blank. - """ - headline = " ".join(str(value.get("headline") or "").split()) - if headline: - return headline[:300] - try: - from evalrx.eval_agent.stages.fix.descriptions import BUILTIN_DESCRIPTIONS - except Exception: - return "" - return BUILTIN_DESCRIPTIONS.get(str(value.get("name") or ""), "") - - -def _repair_name(value: Any) -> str: - """A repair candidate's name from either shape a run records it in. - - Early runs wrote the winning candidate as its bare name; RunLoggerV2 and - the contract payloads write the whole candidate. Both name the same repair. - """ - if isinstance(value, Mapping): - return str(value.get("name") or "") - return str(value or "") - - -def _repair_candidate(value: Any) -> dict[str, Any]: - if not isinstance(value, Mapping): - return {} - fixed_cases = list(value.get("fixed_cases") or []) - broken_cases = list(value.get("broken_cases") or []) - payload = value.get("payload") if isinstance(value.get("payload"), Mapping) else {} - return { - "tier": value.get("tier"), "name": value.get("name"), "kind": value.get("kind"), - # `ref` and `headline` are what a reader sees; `name` is only the join - # key. Both are carried here so the legacy report path shows the same - # identifier and the same sentence as the contract-backed views. - "ref": value.get("ref") or "", "headline": _repair_headline(value), - "source": value.get("source"), "verdict": value.get("verdict"), - "n_pairs": value.get("n_pairs"), "n_baseline_correct": value.get("n_baseline_correct"), - "n_candidate_correct": value.get("n_candidate_correct"), - "n_fixed": value.get("n_fixed", len(fixed_cases)), "n_broken": value.get("n_broken", len(broken_cases)), - "effect": value.get("effect"), "e_value": value.get("e_value"), - "e_threshold": value.get("e_threshold"), - "coverage": value.get("coverage"), "reject": value.get("reject"), "fixed": value.get("fixed"), - "n_model_independent": value.get("n_model_independent"), - "n_unstable": value.get("n_unstable"), - "summary": value.get("summary"), "payload": dict(payload), - "fixed_cases": fixed_cases[:20], "broken_cases": broken_cases[:20], - } - - -def _findings(reader: Mapping[str, Any], raw: Mapping[str, Any]) -> list[dict[str, Any]]: - result = [] - for index, finding in enumerate(reader.get("key_findings") or []): - if isinstance(finding, dict): - result.append({"id": f"finding-{index + 1}", **finding}) - if result: - return result - hypotheses = (raw.get("m3") or {}).get("hypotheses") or [] - for index, hypothesis in enumerate(hypotheses[:3]): - if isinstance(hypothesis, dict): - result.append({ - "id": f"finding-{index + 1}", - "title": hypothesis.get("failure_mode") or "Candidate mechanism", - "summary": hypothesis.get("plain_statement") or hypothesis.get("statement") or "", - "evidence_level": hypothesis.get("status") or "Proposed", - "limitation": "See M4 for independent verification.", - }) - return result - - -def _charts(run: Mapping[str, Any], raw: Mapping[str, Any], - contract: "Mapping[str, Any] | None" = None) -> list[dict[str, Any]]: - charts: list[dict[str, Any]] = [] - labels = run.get("label_distribution") or {} - if isinstance(labels, dict) and labels: - charts.append({ - "id": "outcomes", "kind": "donut", "title": "Evaluation outcomes", - "series": [{"label": str(k).title(), "value": v} for k, v in labels.items() if isinstance(v, (int, float))], - }) - # Prefer the contract's rows: `measured` is a name for the SUBJECT and is - # unique across the report, so the axis cannot end up with two bars reading - # "Mcnemar evalue" (the tool) or several truncating to the same sentence. - contract_rows = _contract_stats(contract or {}) - effect_rows = [] - for item in contract_rows[:8]: - if isinstance(item.get("effect"), (int, float)): - signal = (item.get("config") or {}).get("signal") - effect_rows.append({ - "label": item.get("measured") or _plain_signal(signal or item.get("tool")), - # The analyzer's own sentence. Absent means undocumented, and the - # UI must say that rather than paraphrase the identifier. - "means": item.get("means") or "", - "raw_label": str(signal or item.get("analysis_key") or item.get("tool") or ""), - "value": item["effect"], "highlight": bool(item.get("fdr_corrected")), - }) - if not effect_rows: - stats = (raw.get("m2") or {}).get("stats") or [] - for item in stats[:8]: - if isinstance(item, dict) and isinstance(item.get("effect"), (int, float)): - signal = ((item.get("config") or {}).get("signal") if isinstance(item.get("config"), Mapping) else None) - effect_rows.append({ - "label": _stat_label(item.get("config"), signal, item.get("tool")), - "raw_label": str(signal or item.get("tool") or ""), - "value": item["effect"], "highlight": bool(item.get("reject")), - }) - if effect_rows: - charts.append({ - "id": "effects", "kind": "bar", "title": "Which behaviors appear most connected to errors?", - "subtitle": "A larger bar means a stronger observed pattern. It does not prove the behavior caused the error.", - "series": effect_rows, - }) - return charts - - -def _repairs(raw: Mapping[str, Any]) -> list[dict[str, Any]]: - fix = raw.get("m5_fix") or {} - if not fix.get("ran"): - return [] - confirm = fix.get("confirm") if isinstance(fix.get("confirm"), Mapping) else {} - # Early runs recorded the winning candidate as its bare name; later ones - # record the whole candidate. Both name the same repair. - best_name = _repair_name(fix.get("best")) - return [{ - "id": "repair-1", "fixed": bool(fix.get("fixed")), - "title": best_name or confirm.get("name") or "Targeted repair", - "effect": confirm.get("effect"), - "fixed_cases": len(confirm.get("fixed_cases") or []), - "broken_cases": len(confirm.get("broken_cases") or []), - }] - - -def _cases_repaired(cases: list[dict[str, Any]], m5_detail: Mapping[str, Any] | None) -> int: - """How many withheld cases the M5 repair turned from wrong to right. - - The stage's own confirmation -- the best candidate re-scored on the - confirm pool -- is what M5 prints as "21 repaired, 6 broken", and the - header tile has to say the same 21 whether or not that candidate cleared - the certification bar. Case status never carries a "fixed" value (it is - pass / fail), so counting it left the tile at 0 on every run that repaired - anything. Runs that recorded no confirmation fall back to the per-case - repair outcomes, then to the old status count. - """ - def _count(value: Any) -> int | None: - return int(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else None - - detail = m5_detail if isinstance(m5_detail, Mapping) else {} - confirmation = detail.get("confirmation") - if isinstance(confirmation, Mapping) and confirmation.get("name"): - n_fixed = _count(confirmation.get("n_fixed")) - if n_fixed is not None: - return n_fixed - # No named winner (the candidate missed the certification bar, so the fix - # event names none): the stage still scored its confirm-phase candidates on - # the withheld cases, and the strongest of those is the number it prints. - scored = [ - item for item in detail.get("candidates") or [] - if isinstance(item, Mapping) and _count(item.get("n_fixed")) is not None - ] - if scored: - top = max(scored, key=lambda item: (float(item.get("effect") or 0.0), float(item["n_fixed"]))) - return int(top["n_fixed"]) - per_case = sum( - 1 for case in cases - if isinstance(case.get("repair"), Mapping) and str(case["repair"].get("status")) == "fixed" - ) - if per_case: - return per_case - return sum(1 for case in cases if case.get("status") == "fixed") - - -def _metrics( - run: Mapping[str, Any], - raw: Mapping[str, Any], - cases: list[dict[str, Any]], - m5_detail: Mapping[str, Any] | None = None, -) -> list[dict[str, Any]]: - labels = run.get("label_distribution") or {} - failed = labels.get("fail", labels.get("FAIL", 0)) if isinstance(labels, dict) else 0 - verified = len((raw.get("m4") or {}).get("results") or []) - fixed = _cases_repaired(cases, m5_detail) - return [ - {"id": "evaluated", "label": "Cases evaluated", "value": int(run.get("n_cases") or len(cases))}, - {"id": "failed", "label": "Initial failures", "value": int(failed or 0)}, - {"id": "verified", "label": "Mechanisms checked", "value": verified}, - {"id": "fixed", "label": "Cases repaired", "value": fixed}, - ] - - -def _contract_payloads(root: Path) -> dict[str, Any]: - """The validated per-stage payloads a run emitted, keyed by span id. - - Passed through verbatim. ``stage_detail`` above is a hand-built view whose - every field access is a defensive ``.get(x) or y`` — it has to be, because - it reads whatever the run log happened to contain. These payloads were - validated against the wire models on the way out, so a frontend can decode - them with the generated TypeScript instead of re-deriving the shape. - - Absent for a run produced before contract emission existed, or one where the - ``contract`` extra was not installed. ``{}`` says "this run emitted none", - which a reader must not confuse with "this run had no stages". - """ - out: dict[str, Any] = {} - directory = root / "contract" - if not directory.is_dir(): - return out - for path in sorted(directory.glob("*.json")): - if path.name == "index.json": - continue - payload = _load_json(path) - if payload is None: - continue - # "c0.m1.json" -> "c0.m1"; ".invalid.json" keeps its suffix so a reader - # can see that a stage failed validation rather than silently missing it. - out[path.name[: -len(".json")]] = payload - for key, payload in out.items(): - if key.endswith("m5_fix"): - _backfill_repair_identity(payload) - return out - - -def _backfill_repair_identity(payload: Any) -> None: - """Give a pre-`ref` run the same numbering a current run would emit. - - Runs recorded before these fields existed carry neither, and a consumer - left to number rows itself gives the frozen candidate one number in the - sweep and another on its card. The assignment here is the emitter's, done - the emitter's way -- selection order first, one number per distinct name -- - so an old report and a new one read alike. - - It only ever FILLS BLANKS. What a producer actually wrote is never - overwritten, and a `headline` is only ever taken from the fix agent's table - of its own candidates: a judge-invented name nobody described stays blank, - because inventing a sentence for it here would be this file guessing. - """ - if not isinstance(payload, dict): - return - try: - from evalrx.eval_agent.stages.fix.descriptions import BUILTIN_DESCRIPTIONS - except Exception: - BUILTIN_DESCRIPTIONS = {} - refs: dict[str, str] = {} - for group in ("selection", "attempted"): - for row in payload.get(group) or []: - if not isinstance(row, dict): - continue - name = str(row.get("name") or "") - ref = refs.get(name) - if ref is None: - ref = f"R{len(refs) + 1}" - refs[name] = ref - row.setdefault("ref", "") - if not row["ref"]: - row["ref"] = ref - row.setdefault("headline", "") - if not row["headline"]: - row["headline"] = BUILTIN_DESCRIPTIONS.get(name, "") - - -def _repair_outcomes(root: Path, contract: Mapping[str, Any]) -> dict[str, dict[str, Any]]: - """What each repair candidate answered, per case. - - ``case_id -> {candidate, tier, status, output}``. The counts in M5 say twelve - cases were repaired and one broken; this is what lets a reader open those - thirteen and see what actually changed. Without it a repair is a number. - - Read from each attempt's ``trial_root/outputs.jsonl`` rather than the wire, - because it is one row per case per candidate — the contract points at the - file instead of inlining it, and this is the reader following the pointer. - Confirmation attempts only: the selection sweep chose the candidate and its - per-case results are not evidence about it. - """ - out: dict[str, dict[str, Any]] = {} - for key in sorted(contract): - if not key.endswith("m5_fix"): - continue - for attempt in (contract[key] or {}).get("attempted") or []: - trial = str(attempt.get("trial_root") or "") - if not trial: - continue - path = (root / trial / "outputs.jsonl") - if not path.is_file(): - path = Path(trial) / "outputs.jsonl" # a run read where it was produced - if not path.is_file(): - continue - for line in path.read_text(encoding="utf-8").splitlines(): - try: - row = json.loads(line) - except ValueError: - continue - cid = str(row.get("case_id") or "") - if not cid: - continue - out[cid] = { - "candidate": attempt.get("name"), - "tier": attempt.get("tier"), - "status": row.get("status"), - "output": row.get("output"), - } - return out - - -def _contract_model_name(contract: Mapping[str, Any]) -> str: - """The model's name from M1's payload, or "" for a run that emitted none.""" - for key in sorted(contract): - if not key.endswith(".m1"): - continue - ref = (contract[key] or {}).get("model") or {} - name = str(ref.get("name") or "").strip() - if name: - return name - return "" - - -def _contract_stats(contract: Mapping[str, Any]) -> list[Mapping[str, Any]]: - """M2's statistical rows from the newest cycle that has any.""" - for key in sorted(contract, reverse=True): - if not key.endswith(".m2"): - continue - rows = (contract[key] or {}).get("stats_results") - if isinstance(rows, list) and rows: - return rows - return [] - - -def _media_index(cases: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]: - """One entry per distinct media file, preferring the copy inside the run. - - ``inputs.`` is where the producer read the file from — an absolute path - on that host, and meaningless on any other. The run logger already copied the - file to ``artifacts/case_media/`` and recorded that relative path, so a run - unzipped elsewhere still has its media; index by that when it exists and keep - the original only as the fallback for runs that predate the copy. - """ - media: list[dict[str, Any]] = [] - seen: set[str] = set() - for case in cases: - inputs = case.get("inputs") if isinstance(case.get("inputs"), dict) else case - # Slots and copies are recorded in the same order, so they zip up. - local = [p for p in (case.get("_media_paths") or []) if isinstance(p, str)] - i = 0 - for kind in ("audio", "image", "video"): - source = inputs.get(kind) or inputs.get(f"{kind}_path") - if not isinstance(source, str) or not source or source.startswith("<"): - continue - path = local[i] if i < len(local) else source - i += 1 - if path in seen: - continue - seen.add(path) - media.append({"id": f"media-{len(media) + 1}", "kind": kind, - "path": path, "source": source}) - return media - - -def _normalise_case(case: Mapping[str, Any], media: list[dict[str, Any]]) -> dict[str, Any]: - inputs = case.get("inputs") if isinstance(case.get("inputs"), dict) else {} - prompt = inputs.get("prompt") or case.get("instruction") or case.get("prompt") or "" - # Match on either key: the index prefers the in-run copy, and a run without - # copies still resolves through the producer's original path. - media_by_path: dict[str, str] = {} - for item in media: - media_by_path[item["path"]] = item["id"] - if item.get("source"): - media_by_path[item["source"]] = item["id"] - media_ids = [] - for path in (case.get("_media_paths") or []): - if isinstance(path, str) and path in media_by_path and media_by_path[path] not in media_ids: - media_ids.append(media_by_path[path]) - for kind in ("audio", "image", "video"): - value = inputs.get(kind) or case.get(f"{kind}_path") or case.get(kind) - if isinstance(value, str) and value in media_by_path \ - and media_by_path[value] not in media_ids: - media_ids.append(media_by_path[value]) - return { - "id": str(case.get("id") or case.get("case_id") or f"case-{id(case)}"), - "status": str(case.get("status") or case.get("label") or "unknown").lower(), - "prompt": prompt, - "expected": case.get("expected"), - "observed": case.get("observed", case.get("output")), - "choices": case.get("choices") or [], - "tags": case.get("tags") or case.get("probe_flags") or [], - "task": case.get("task") or (case.get("metadata") or {}).get("category") or "", - "media_ids": media_ids, - "trajectory": case.get("trajectory"), - # explore / confirm / test, as the loop logged it; None until - # _assign_partitions has had a chance to infer it. - "split": case.get("_split") if isinstance(case.get("_split"), str) else None, - } - - -# What each partition was used for, in the words the loop figure draws them -# with: D_E on top, D_H, D_C at the bottom. The code is the subscript. -_EXPLORE_ROLE = ("M1-M3 mined patterns and hypotheses here. Anything measured on " - "these cases is a lead, not a verdict.") -_HELDOUT_ROLE = ("Withheld from M1-M3. M4 adjudicated the hypotheses here and M5 " - "developed its repair candidates on the same cases.") -_CONFIRM_ROLE = ("Withheld from every adaptive decision. The frozen repair was " - "scored exactly once here.") -_TWO_WAY_ROLE = ("Withheld from M1-M3. M4 adjudicated the hypotheses here and the " - "repair was scored on these same cases: one withheld pool " - "serving as both the held-out and the confirm set.") - - -def _assign_partitions( - cases: list[dict[str, Any]], - *, - logged_ids: "Sequence[str]", - n_explore: Any, - final_ids: "set[str]", -) -> list[dict[str, Any]]: - """Put every case in its partition and summarise the partitions. - - ``case["split"]`` is filled in place (``explore`` / ``confirm`` / ``test``) - and the summary rows come back in drawing order, each with the subscript - the loop figure uses (E, H, C), its size and what the run used it for. - - A run that tagged its case records is read as recorded. A run from before - the tag existed is inferred from what its log still says: ``run_start``'s - ``n_cases`` is the explore partition (the loop narrows ``data`` to it before - recording the start), and the loop logs explore first, then confirm, then - test -- so the first ``n_explore`` logged ids are explore and the rest were - withheld. Whether the withheld pool was further divided (train/val/test - mode) is recovered from M5's per-case scoring: the cases it scored the - frozen repair on are the test partition when they are a strict subset of - what was withheld, and the whole pool otherwise. Cases the report merged - in from a manifest rather than the log stay untagged -- their order says - nothing. - - Returns ``[]`` when there is no split to show: no case carries one and none - can be inferred (a run without a confirm split, or a legacy manifest). - """ - by_id = {str(case.get("id")): case for case in cases} - inferred = False - if not any(case.get("split") for case in cases): - ids = [cid for cid in logged_ids if cid and cid in by_id] - try: - n_head = int(n_explore or 0) - except (TypeError, ValueError): - n_head = 0 - if not ids or n_head <= 0 or n_head >= len(ids): - return [] - withheld = ids[n_head:] - final = {cid for cid in final_ids if cid in set(withheld)} - three_way = bool(final) and len(final) < len(withheld) - for cid in ids[:n_head]: - by_id[cid]["split"] = "explore" - for cid in withheld: - by_id[cid]["split"] = "test" if three_way and cid in final else "confirm" - inferred = True - - present = {str(case.get("split")) for case in cases if case.get("split")} - if not present: - return [] - three_way = "test" in present - - def row(split: str, code: str, label: str, role: str) -> dict[str, Any]: - return {"split": split, "code": code, "label": label, - "n": sum(1 for case in cases if case.get("split") == split), - "role": role, "inferred": inferred} - - rows = [row("explore", "E", "Explore", _EXPLORE_ROLE)] - if three_way: - rows.append(row("confirm", "H", "Held-out", _HELDOUT_ROLE)) - rows.append(row("test", "C", "Confirm", _CONFIRM_ROLE)) - elif "confirm" in present: - rows.append(row("confirm", "H/C", "Held-out / Confirm", _TWO_WAY_ROLE)) - n_unknown = sum(1 for case in cases if not case.get("split")) - if n_unknown: - rows.append({"split": "", "code": "?", "label": "Unrecorded", "n": n_unknown, - "role": "The run did not record which partition these came from.", - "inferred": False}) - return rows - - -def _merge_recorded_case_evidence(cases: list[dict[str, Any]], root: Path) -> list[dict[str, Any]]: - """Supplement legacy manifests with the run's recorded baseline I/O. - - Older benchmark exports often keep prompts/media in a manifest while - baseline answers live separately in ``report/discovery_cases.json``. This - is a generic run artifact, not a task-specific fallback. New JSONL case - records already contain both and therefore simply win when populated. - """ - snapshots: list[Mapping[str, Any]] = [] - for base in (root, root.parent): - value = _load_json(base / "report" / "discovery_cases.json") - if isinstance(value, list): - snapshots = [item for item in value if isinstance(item, Mapping)] - if snapshots: - break - if not snapshots: - return cases - existing = {str(case.get("id")): case for case in cases} - for raw_case in snapshots: - case_id = str(raw_case.get("id") or raw_case.get("case_id") or "") - if not case_id: - continue - update = _normalise_case(raw_case, []) - target = existing.get(case_id) - if target is None: - cases.append(update) - existing[case_id] = update - continue - for key in ("prompt", "expected", "observed"): - if not target.get(key) and update.get(key): - target[key] = update[key] - if target.get("status") in {"", "unknown", "unchanged"} and update.get("status"): - target["status"] = update["status"] - return cases - - def _read_events(root: Path) -> list[dict[str, Any]]: - from evalrx.reporting.run_events import read_v2_events - - return read_v2_events(root) + from evalrx.reporting.run_events import read_run_events - -def _infer_example_dir(root: Path) -> Path | None: - """Find a nearby legacy manifest; v4 case events do not need this join.""" - for candidate in (root, root.parent, root.parent.parent): - if any((candidate / "data").glob("*.jsonl")) or any((candidate / "data").glob("*.json")): - return candidate - return None - - -_CALL_TEXT_CAP = 3000 -_CALLS_PER_ANALYZER = 120 - - -def _call_text(value: Any) -> str: - """The prompt or the reply as text, cut so 500 calls stay a sane payload.""" - if isinstance(value, Mapping): - value = value.get("prompt") if "prompt" in value else json.dumps(value, ensure_ascii=False) - text = "" if value is None else str(value) - return text if len(text) <= _CALL_TEXT_CAP else text[:_CALL_TEXT_CAP] + f"… [+{len(text) - _CALL_TEXT_CAP} chars]" - - -def _m1_calls(events: Iterable[Mapping[str, Any]]) -> tuple[dict[str, list[dict[str, Any]]], int]: - """M1's model calls grouped by analyzer, oldest first, capped per analyzer.""" - grouped: dict[str, list[dict[str, Any]]] = {} - total = 0 - for event in events: - if str(event.get("event") or "") != "model_call" or str(event.get("stage") or "") != "M1": - continue - total += 1 - analyzer = str(event.get("analyzer") or event.get("role") or "model") - bucket = grouped.setdefault(analyzer, []) - if len(bucket) >= _CALLS_PER_ANALYZER: - continue - batch = event.get("batch_case_ids") - bucket.append({ - "seq": event.get("event_seq"), "cycle": event.get("cycle"), - "method": event.get("method") or event.get("operation") or "", - "case_id": event.get("case_id"), - "batch_case_ids": [str(item) for item in batch] if isinstance(batch, list) else [], - "duration_sec": event.get("duration_sec"), - "prompt": _call_text(event.get("inputs")), - "output": _call_text(event.get("output")), - "error": str(event.get("error")) if event.get("error") else None, - }) - return grouped, total + return read_run_events(root) def _debug_event(event: Mapping[str, Any]) -> dict[str, Any]: - event_type = str(event.get("event") or "") - inferred_stage = { - "probe": "M1", "explore": "M2", "analysis": "M2", "diagnosis": "M3", - "surgery": "M4" if event.get("module") == "m4" else "M5", - "experiment": "M5", "fix": "M5", "case_record": "DATA", - "report_published": "REPORT", - }.get(event_type, "RUN") return { - "event": event.get("event"), "stage": event.get("stage") or inferred_stage, "cycle": event.get("cycle"), + "event": event.get("event"), "stage": event.get("stage"), "cycle": event.get("cycle"), "event_seq": event.get("event_seq"), "ts": event.get("ts"), "span_id": event.get("span_id"), "summary": _event_summary(event), } diff --git a/evalrx/reporting/html_report.py b/evalrx/reporting/html_report.py deleted file mode 100644 index 802db6a3..00000000 --- a/evalrx/reporting/html_report.py +++ /dev/null @@ -1,1364 +0,0 @@ -"""Self-contained, tabbed, human-understandable HTML report generator for EvalRX. - -This module parses a finished diagnostic run (M1 through M4 and fixes) and -renders a single, zero-dependency, tabbed interactive HTML diagnostic report in English. - -Design Philosophy: -- Tabbed Navigation: Clean stage-by-stage tabs (Overview, M1, M2, M3, M4, M5, Cases) - allowing focused inspection without endless scrolling. -- Human-Friendly Header: Clean model and benchmark titles instead of raw code/debug dumps. -- Plain-English First: Clinical medical-checkup analogy with intuitive explanations. -- 100% Dynamic: Fully parsed from experiment artifacts without hardcoding. -- Multi-Modal: Inlines audio (AAC), images, and structured prompts. -""" - -from __future__ import annotations - -import argparse -import base64 -import html -import json -import re -import shutil -import subprocess -import tempfile -from concurrent.futures import ThreadPoolExecutor -from pathlib import Path -from typing import Any - -from evalrx.reporting.run_data import extract_run_data - -STAGE_METADATA: dict[str, dict[str, str]] = { - "overview": { - "code": "SUMMARY", - "name": "Executive Summary", - "short_role": "Overview & Key Findings", - "plain_desc": "High-level diagnostic summary: what was tested, what failure mechanism was diagnosed, and the final repair outcome.", - }, - "pre_m1": { - "code": "PRE-M1", - "name": "Case Synthesis", - "short_role": "Adversarial Probe Synthesis", - "plain_desc": "Evaluates whether the system automatically synthesised challenging edge cases or adversarial probes to uncover hidden blind spots. If skipped, testing ran on fixed benchmark data.", - }, - "m1": { - "code": "M1", - "name": "Checkup & Signals", - "short_role": "Multi-Dimensional Measurement", - "plain_desc": "Performs a multi-dimensional clinical checkup on the model, measuring vital signs (such as attention focus, overconfidence, order sensitivity, etc.) without pre-judging guilt.", - }, - "m2": { - "code": "M2", - "name": "Screening & EDA", - "short_role": "Statistical Association Screening", - "plain_desc": "Correlates vital signs with actual failure cases. Filters out noise and random coincidence using rigorous multiple-testing corrections (Benjamini–Hochberg FDR) to isolate prime suspects.", - }, - "m3": { - "code": "M3", - "name": "Root-Cause Diagnosis", - "short_role": "Falsifiable Mechanism Hypothesis", - "plain_desc": "An AI Diagnostician analyzes the screened evidence to propose specific, falsifiable root-cause hypotheses explaining exactly why and when the model fails.", - }, - "m4": { - "code": "M4", - "name": "Independent Adjudication", - "short_role": "Blind-Holdout Validation", - "plain_desc": "Blindly re-tests the AI Doctor's hypothesis on a held-out validation set the model has never seen before, determining whether the mechanism is confirmed or refuted.", - }, - "m5_surgery": { - "code": "M5-SURGERY", - "name": "Causal Surgery", - "short_role": "Internal Mechanism Intervention", - "plain_desc": "Directly intervenes in or ablates internal model components (such as attention heads or activation layers) to prove causal necessity.", - }, - "m5_fix": { - "code": "M5-FIX", - "name": "Targeted Repair", - "short_role": "Repair Search & Paired Confirmation", - "plain_desc": "Applies targeted treatments across intervention tiers (from prompt patches to decoding scaffolds). Validates on held-out test data by comparing cured cases against broken cases.", - }, - "case_book": { - "code": "CASE-STUDIO", - "name": "Interactive Case Studio", - "short_role": "Case-Level Inspection & Audio", - "plain_desc": "Inspect real failure vs repaired cases with before-and-after model answering comparisons and playable audio clips.", - }, - "agents": { - "code": "AGENTS", - "name": "Agent Trajectories", - "short_role": "Judge & Coder Agent I/O", - "plain_desc": "Every agent invocation behind the diagnosis, layer by layer: verbatim judge prompts and responses (M1 selection, M2 screening, M3 diagnosis, M4 adjudication), the explore coder-agent's raw CLI trajectory, and every synthesized tool's codegen attempt. This is the audit trail for debugging and case studies.", - }, -} - - -def embed_figures(explore_dir: Path | None, logs_dir: Path) -> dict[str, str]: - """Find all PNG charts and convert to base64 Data URIs.""" - out = {} - paths = [] - if explore_dir and (explore_dir / "figures").is_dir(): - paths += sorted((explore_dir / "figures").glob("*.png")) - # V1 writes M2 charts to logs_dir/figures; V2's RunContext.figures_dir - # maps the same role to logs_dir/M2/artifacts (see run_context.py). V2's - # explore-step figures are captured inline into M2/log.json rather than - # written as loose files, so the explore_dir branch above still finds - # nothing for a V2 run — a known follow-up, not covered here. - for candidate in (logs_dir / "figures", logs_dir / "M2" / "artifacts"): - if candidate.is_dir(): - paths += sorted(candidate.glob("*.png")) - - for p in paths: - key = p.stem - clean_key = re.sub(r"^\d+_", "", key) - try: - b64 = base64.b64encode(p.read_bytes()).decode("ascii") - out[clean_key] = f"data:image/png;base64,{b64}" - out[key] = f"data:image/png;base64,{b64}" - except Exception: - pass - return out - - -def embed_media(cases: list[dict], example_dir: Path, cache_dir: Path, no_audio: bool = False) -> tuple[dict[str, str], dict[str, str]]: - """Embed audio and image files as base64 data URIs concurrently.""" - audio_map: dict[str, str] = {} - image_map: dict[str, str] = {} - - has_ffmpeg = bool(shutil.which("ffmpeg")) - try: - cache_dir.mkdir(parents=True, exist_ok=True) - except Exception: - cache_dir = Path("/tmp/evalrx_media_cache") - cache_dir.mkdir(parents=True, exist_ok=True) - - def process_audio(c: dict) -> tuple[str, str] | None: - cid = c["id"] - if not no_audio and c.get("audio_path"): - src = example_dir / "data" / c["audio_path"] - if not src.exists() and (example_dir / c["audio_path"]).exists(): - src = example_dir / c["audio_path"] - - if src.exists(): - dst = cache_dir / f"{cid}.m4a" - if not dst.exists() and has_ffmpeg: - try: - subprocess.run( - ["ffmpeg", "-y", "-loglevel", "error", "-i", str(src), - "-ac", "1", "-ar", "16000", "-c:a", "aac", "-b:a", "48k", str(dst)], - capture_output=True, - timeout=10, - ) - except Exception: - pass - target = dst if dst.exists() else src - try: - mime = "audio/mp4" if target.suffix in (".m4a", ".aac") else "audio/wav" - b64 = base64.b64encode(target.read_bytes()).decode("ascii") - return cid, f"data:{mime};base64,{b64}" - except Exception: - pass - return None - - def process_image(c: dict) -> tuple[str, str] | None: - cid = c["id"] - if c.get("image_path"): - src = example_dir / "data" / c["image_path"] - if not src.exists() and (example_dir / c["image_path"]).exists(): - src = example_dir / c["image_path"] - if src.exists(): - try: - ext = src.suffix.lower().lstrip(".") - mime = f"image/{ext}" if ext in ("png", "jpeg", "webp", "gif") else "image/jpeg" - b64 = base64.b64encode(src.read_bytes()).decode("ascii") - return cid, f"data:{mime};base64,{b64}" - except Exception: - pass - return None - - with ThreadPoolExecutor(max_workers=16) as pool: - for res in pool.map(process_audio, cases): - if res: - audio_map[res[0]] = res[1] - for res in pool.map(process_image, cases): - if res: - image_map[res[0]] = res[1] - - return audio_map, image_map - - -def esc(s: Any) -> str: - if s is None: - return "" - return html.escape(str(s), quote=True) - - -def _json_for_script(value: Any) -> str: - """Serialize untrusted values safely inside an inline ``', - '', - '', - ] - return '\n'.join(html_lines) - - -# --------------------------------------------------------------------------- -# CLI Entry Point -# --------------------------------------------------------------------------- - -def open_in_browser(report: Path) -> None: - """Open a written report. It is self-contained, so no server is needed.""" - import webbrowser - - from evalrx.term_links import hyperlink - - print(f"Opening report: {hyperlink(report.as_uri())}") - webbrowser.open(report.as_uri()) - - -def build_html_report( - run_dir: str | Path, - example_dir: str | Path | None = None, - out_path: str | Path | None = None, - no_audio: bool = False, -) -> Path: - """Collect data from *run_dir* and write a self-contained HTML report.""" - run_dir = Path(run_dir).resolve() - example_dir = Path(example_dir).resolve() if example_dir else run_dir.parent - out_path = Path(out_path).resolve() if out_path else run_dir / "report.html" - - print(f"[*] Reading run artifacts from: {run_dir}") - data = extract_run_data(run_dir, example_dir) - logs_dir = Path(data["run"]["logs_dir"]) - explore_dir = data["explore_dir"] - - figures = embed_figures(explore_dir, logs_dir) - print(f"[*] Embedded {len(figures)} figures/charts") - - cache_dir = out_path.parent / ".media_cache" - audio_map, image_map = embed_media(data["cases"], example_dir, cache_dir, no_audio=no_audio) - print(f"[*] Embedded {len(audio_map)} audio clips and {len(image_map)} images ({len(data['cases'])} joined cases)") - - html_content = generate_html_report(data, figures, audio_map, image_map) - - out_path.parent.mkdir(parents=True, exist_ok=True) - # A report may be tens or hundreds of MB when it embeds case media. Write - # beside the destination and replace atomically so a browser never sees a - # partially generated diagnosis after an interruption or disk-full error. - fd, tmp_name = tempfile.mkstemp( - prefix=f".{out_path.stem}.", suffix=".tmp", dir=out_path.parent, - ) - tmp_path = Path(tmp_name) - try: - with open(fd, "w", encoding="utf-8", closefd=True) as handle: - handle.write(html_content) - tmp_path.replace(out_path) - finally: - if tmp_path.exists(): - tmp_path.unlink() - size_mb = out_path.stat().st_size / (1024 * 1024) - from evalrx.term_links import hyperlink - - print(f"[✓] Wrote self-contained HTML report to: {hyperlink(str(out_path))} ({size_mb:.2f} MB)") - return out_path - - -def main() -> None: - ap = argparse.ArgumentParser(description="Render a finished EvalRX diagnostic run as an interactive HTML page.") - ap.add_argument("run_dir", nargs="?", default="outputs", help="Run directory holding run.json or logs/") - ap.add_argument("--example-dir", default=None, help="Root holding data/ (default: parent of run_dir)") - ap.add_argument("--out", "-o", default=None, help="Output HTML file path (default: /report.html)") - ap.add_argument("--no-audio", action="store_true", help="Skip audio clip compression and embedding") - args = ap.parse_args() - - build_html_report( - run_dir=args.run_dir, - example_dir=args.example_dir, - out_path=args.out, - no_audio=args.no_audio, - ) - - -if __name__ == "__main__": - main() diff --git a/evalrx/reporting/langfuse_exporter.py b/evalrx/reporting/langfuse_exporter.py deleted file mode 100644 index 348919bc..00000000 --- a/evalrx/reporting/langfuse_exporter.py +++ /dev/null @@ -1,38 +0,0 @@ -"""Langfuse observability & exporter facade for backward compatibility.""" - -from __future__ import annotations - -from pathlib import Path - -from evalrx.observability.tracer import ( - DiagnosticTracer, - backfill_run_to_langfuse, - export_to_langfuse_bundle, - sync_to_langfuse_live, -) - -__all__ = [ - "DiagnosticTracer", - "backfill_run_to_langfuse", - "export_to_langfuse_bundle", - "sync_to_langfuse_live", -] - - -def main() -> None: - import argparse - ap = argparse.ArgumentParser(description="Export an EvalRX run into a Langfuse ingestion bundle.") - ap.add_argument("run_dir", nargs="?", default="outputs", help="Run directory.") - ap.add_argument("--out", "-o", default=None, help="Output JSON path.") - ap.add_argument("--sync", action="store_true", help="Push live to Langfuse API.") - args = ap.parse_args() - - if args.sync: - sync_to_langfuse_live(args.run_dir) - else: - out_p = args.out or (Path(args.run_dir) / "langfuse_trace.json") - export_to_langfuse_bundle(args.run_dir, out_p) - - -if __name__ == "__main__": - main() diff --git a/evalrx/reporting/langfuse_source.py b/evalrx/reporting/langfuse_source.py index 6c8f51a3..f2965b77 100644 --- a/evalrx/reporting/langfuse_source.py +++ b/evalrx/reporting/langfuse_source.py @@ -4,15 +4,15 @@ delivered through the outbox queue arrives as one EVENT observation per event (``input={"event": {...}}``); this adapter recovers the ordered stream from those without making the renderer understand Langfuse-specific response -types, then re-buckets it into a V2-shaped cache (:func:`materialize`) so the +types, then re-buckets it into a run-log-shaped cache (:func:`materialize`) so the normal ``run.json``/``M/log.json`` read path can render it. -Caveat: :class:`~evalrx.eval_agent.run_logger_v2.RunLoggerV2` does not +Caveat: :class:`~evalrx.eval_agent.run_logger.RunLogger` does not currently push structured events through that outbox (it relies on live -spans/generations instead), so a V2 run's recovered events presently carry +spans/generations instead), so a run's recovered events presently carry no ``stage`` tag and land in ``run.json``'s ``unrouted`` bucket rather than -a real ``M/log.json`` — full V2 support here is unfinished, not something -this module claims to solve. +a real ``M/log.json`` — recovering a full run this way is unfinished, not +something this module claims to solve. """ from __future__ import annotations @@ -74,7 +74,7 @@ def _raw_events(self, trace_id: str) -> list[dict[str, Any]]: def materialize(self, trace_id: str, destination: str | Path) -> Path: """Write a renderer-compatible cache; it is not a source of truth.""" - from evalrx.reporting.run_events import write_v2_bundle + from evalrx.reporting.run_events import write_run_bundle root = Path(destination) root.mkdir(parents=True, exist_ok=True) @@ -84,7 +84,7 @@ def materialize(self, trace_id: str, destination: str | Path) -> Path: raise LookupError(f"No EvalRX events found for Langfuse trace {trace_id!r}") for event in events: self._materialize_artifacts(event, root) - write_v2_bundle(root, [_public_event(event) for event in events]) + write_run_bundle(root, [_public_event(event) for event in events]) return root def _materialize_artifacts(self, event: dict[str, Any], root: Path) -> None: diff --git a/evalrx/reporting/model.py b/evalrx/reporting/model.py index f21582a3..d5355044 100644 --- a/evalrx/reporting/model.py +++ b/evalrx/reporting/model.py @@ -1,108 +1,9 @@ -"""Structured diagnostic report model for claim-first dashboards. - -The raw EvalRX artifacts are optimized for auditability: JSONL events, -candidate signal dicts, CSV tables, and rendered chart files. This module -defines the semantic layer above those artifacts. The dashboard should render -this model instead of re-interpreting raw logs ad hoc. -""" +"""The plain-language summary a report opens with.""" from __future__ import annotations from dataclasses import dataclass, field -from typing import Any, Literal - -ClaimStatus = Literal["supported", "inconclusive", "refuted", "descriptive"] -Confidence = Literal["high", "medium", "low", "unknown"] - - -@dataclass -class Evidence: - id: str - kind: str - title: str - summary: str = "" - artifact: dict[str, Any] = field(default_factory=dict) - - def to_dict(self) -> dict[str, Any]: - return { - "id": self.id, - "kind": self.kind, - "title": self.title, - "summary": self.summary, - "artifact": self.artifact, - } - - -@dataclass -class Claim: - id: str - text: str - status: ClaimStatus - evidence_ids: list[str] = field(default_factory=list) - counter_evidence_ids: list[str] = field(default_factory=list) - interpretation: str = "" - do_not_infer: str = "" - downstream: list[str] = field(default_factory=list) - - def to_dict(self) -> dict[str, Any]: - return { - "id": self.id, - "text": self.text, - "status": self.status, - "evidence_ids": self.evidence_ids, - "counter_evidence_ids": self.counter_evidence_ids, - "interpretation": self.interpretation, - "do_not_infer": self.do_not_infer, - "downstream": self.downstream, - } - - -@dataclass -class ReportStep: - stage: str - title: str - summary: str - artifact_ids: list[str] = field(default_factory=list) - - def to_dict(self) -> dict[str, Any]: - return { - "stage": self.stage, - "title": self.title, - "summary": self.summary, - "artifact_ids": self.artifact_ids, - } - - -@dataclass -class DiagnosticReport: - question: str = "" - answer: str = "" - confidence: Confidence = "unknown" - claims: list[Claim] = field(default_factory=list) - evidence: list[Evidence] = field(default_factory=list) - timeline: list[ReportStep] = field(default_factory=list) - visual_decisions: list[dict[str, Any]] = field(default_factory=list) - chart_readings: list[dict[str, Any]] = field(default_factory=list) - dashboard_storyboard: list[dict[str, Any]] = field(default_factory=list) - critique: list[str] = field(default_factory=list) - caveats: list[str] = field(default_factory=list) - next_actions: list[str] = field(default_factory=list) - - def to_dict(self) -> dict[str, Any]: - return { - "question": self.question, - "answer": self.answer, - "confidence": self.confidence, - "claims": [c.to_dict() for c in self.claims], - "evidence": [e.to_dict() for e in self.evidence], - "timeline": [s.to_dict() for s in self.timeline], - "visual_decisions": self.visual_decisions, - "chart_readings": self.chart_readings, - "dashboard_storyboard": self.dashboard_storyboard, - "critique": self.critique, - "caveats": self.caveats, - "next_actions": self.next_actions, - } +from typing import Any @dataclass diff --git a/evalrx/reporting/plain_labels.py b/evalrx/reporting/plain_labels.py new file mode 100644 index 00000000..60f72ad8 --- /dev/null +++ b/evalrx/reporting/plain_labels.py @@ -0,0 +1,80 @@ +"""Reader-facing names for the signals, tools and configs a run records.""" + +from __future__ import annotations + +import re +from typing import Any, Mapping + +# These labels are deliberately about the behaviour being measured, rather +# than the analyzer implementation that happened to measure it. Unknown keys +# still get a deterministic readable fallback and preserve their raw key in +# the audit-only fields below. +PLAIN_LABELS = { + "answer_extraction_audit": "Did the model give a usable answer?", + "calibration": "Is the model confident when it is wrong?", + "termination_audit": "Did the model stop before finishing?", + "format_sensitivity": "Does changing answer order change its choice?", + "selfcheck_consistency": "Does the model contradict itself?", + "coverage_verification_gap": "Can repeated attempts ever find the right answer?", + "logprob_entropy": "Does the model appear uncertain while answering?", + "self_consistency": "Does the answer stay the same across retries?", + "signal_label_assoc": "How strongly is this behavior linked to errors?", + "rank_corr": "Do more of this behavior and more errors move together?", + "single_rate_evalue": "Is this rate unlikely to be chance?", + "n_correct": "Number of correct attempts", + "any_correct": "At least one correct attempt", + "majority_correct": "Most attempts were correct", + "format_flip_rate": "Answer changed after reordering choices", + "positional_bias": "Tendency to favor one answer position", + "output_chars": "Length of the model answer", + "output_truncated": "Answer appears cut short", + "recovered_by_continuation": "Could continue to a usable answer", + "pass_at_k": "Share of retries that were correct", + "n_sentences": "Number of answer sentences checked", + "conf_logprob": "How certain the model appeared", + "label_disagrees": "Recorded answer disagrees with the label", + "has_answer_tag": "Used the requested answer format", + "extracted_answer": "Answer read from the output", + "labelled_fail": "This case was an error", +} + + +def _plain_label(value: Any) -> str: + raw = str(value or "").strip() + if not raw: + return "Recorded measurement" + if raw in PLAIN_LABELS: + return PLAIN_LABELS[raw] + return re.sub(r"\s+", " ", raw.replace("_", " ")).strip().capitalize() + + +def _stat_label(config: "Mapping[str, Any] | None", signal: Any, tool: Any) -> str: + """A name for what one statistical test measured, unique within a report. + + A signal test names its signal. A PAIRED test names none — it compares two + strategies — so the label used to fall through to the tool, and every paired + row in the report came out reading "Mcnemar Evalue". The pair it compared is + the thing that tells those rows apart, and it is already in the config. + """ + cfg = config if isinstance(config, Mapping) else {} + if cfg.get("signal"): + return _plain_signal(cfg["signal"]) + groups = [str(name) for name in (cfg.get("strategies") or []) if name] + if len(groups) >= 2: + return f"{_plain_label(groups[-1])} vs {_plain_label(groups[0])}" + return _plain_signal(signal or tool) + + +def _plain_signal(value: Any) -> str: + """Convert ``analyzer.metric`` into a question a non-expert can read.""" + raw = str(value or "") + if not raw: + return "Recorded behavior" + analyzer, _, metric = raw.partition(".") + if analyzer and metric: + return f"{_plain_label(analyzer)} — {_plain_label(metric)}" + return _plain_label(raw) + + +def _plain_mapping(value: Mapping[str, Any]) -> dict[str, Any]: + return {_plain_label(key): item for key, item in value.items()} diff --git a/evalrx/reporting/report_inputs.py b/evalrx/reporting/report_inputs.py new file mode 100644 index 00000000..17eb066d --- /dev/null +++ b/evalrx/reporting/report_inputs.py @@ -0,0 +1,225 @@ +"""What a run recorded, read for the report: its typed contract payloads, its +cases and their media, M5's per-case repair outcomes, and the partitions of +the frozen batch each case sat in. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Iterable, Mapping + + +def _load_json(path: Path) -> Any: + try: + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError, TypeError): + return None + + +def _contract_payloads(root: Path) -> dict[str, Any]: + """The validated per-stage payloads a run emitted, keyed by span id. + + Passed through verbatim. ``stage_detail`` above is a hand-built view whose + every field access is a defensive ``.get(x) or y`` — it has to be, because + it reads whatever the run log happened to contain. These payloads were + validated against the wire models on the way out, so a frontend can decode + them with the generated TypeScript instead of re-deriving the shape. + + Absent for a run produced before contract emission existed, or one where the + ``contract`` extra was not installed. ``{}`` says "this run emitted none", + which a reader must not confuse with "this run had no stages". + """ + out: dict[str, Any] = {} + directory = root / "contract" + if not directory.is_dir(): + return out + for path in sorted(directory.glob("*.json")): + if path.name == "index.json": + continue + payload = _load_json(path) + if payload is None: + continue + # "c0.m1.json" -> "c0.m1"; ".invalid.json" keeps its suffix so a reader + # can see that a stage failed validation rather than silently missing it. + out[path.name[: -len(".json")]] = payload + return out + + +def _repair_outcomes(events: Iterable[Mapping[str, Any]]) -> dict[str, dict[str, Any]]: + """What each repair candidate answered, per case. + + ``case_id -> {candidate, tier, status, output}``. The counts in M5 say twelve + cases were repaired and one broken; this is what lets a reader open those + thirteen and see what actually changed. Without it a repair is a number. + + Read from the fix event's confirmation attempts, which carry each + candidate's answer per case and the cases it fixed and broke. The + selection sweep chose the candidate, and its per-case results are not + evidence about it. + """ + out: dict[str, dict[str, Any]] = {} + for event in events: + if event.get("event") != "fix": + continue + for attempt in event.get("attempted") or []: + outputs = attempt.get("outputs") if isinstance(attempt, Mapping) else None + if not isinstance(outputs, Mapping): + continue + fixed = {str(cid) for cid in attempt.get("fixed_cases") or []} + broken = {str(cid) for cid in attempt.get("broken_cases") or []} + for cid, output in outputs.items(): + cid = str(cid) + out[cid] = { + "candidate": attempt.get("name"), + "tier": attempt.get("tier"), + "status": "fixed" if cid in fixed else "broken" if cid in broken else "unchanged", + "output": output, + } + return out + + +def _contract_model_name(contract: Mapping[str, Any]) -> str: + """The model's name from M1's payload, or "" for a run that emitted none.""" + for key in sorted(contract): + if not key.endswith(".m1"): + continue + ref = (contract[key] or {}).get("model") or {} + name = str(ref.get("name") or "").strip() + if name: + return name + return "" + + +def _contract_stats(contract: Mapping[str, Any]) -> list[Mapping[str, Any]]: + """M2's statistical rows from the newest cycle that has any.""" + for key in sorted(contract, reverse=True): + if not key.endswith(".m2"): + continue + rows = (contract[key] or {}).get("stats_results") + if isinstance(rows, list) and rows: + return rows + return [] + + +def _in_run_copy(source: str, copies: list[str]) -> str | None: + """The logger's copy of *source*, which it names ``_``.""" + name = Path(source).name + return next((c for c in copies if Path(c).name.partition("_")[2] == name), None) + + +def _media_index(cases: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]: + """One entry per distinct media file, preferring the copy inside the run. + + ``inputs.`` is where the producer read the file from — an absolute path + on that host, and meaningless on any other. The run logger already copied the + file into the run and recorded that relative path, so a run unzipped + elsewhere still has its media; index by that, and by the original path only + for a file the logger could not copy. + """ + media: list[dict[str, Any]] = [] + seen: set[str] = set() + for case in cases: + inputs = found if isinstance(found := case.get("inputs"), dict) else {} + copies = [p for p in (case.get("_media_paths") or []) if isinstance(p, str)] + for kind in ("audio", "image", "video"): + source = inputs.get(kind) + if not isinstance(source, str) or not source or source.startswith("<"): + continue + path = _in_run_copy(source, copies) or source + if path in seen: + continue + seen.add(path) + media.append({"id": f"media-{len(media) + 1}", "kind": kind, + "path": path, "source": source}) + return media + + +def _normalise_case(case: Mapping[str, Any], media: list[dict[str, Any]]) -> dict[str, Any]: + inputs = found if isinstance(found := case.get("inputs"), dict) else {} + metadata = found if isinstance(found := case.get("metadata"), dict) else {} + # Match on either key: the index prefers the in-run copy, and a file the + # logger could not copy still resolves through the producer's path. + media_by_path: dict[str, str] = {} + for item in media: + media_by_path[item["path"]] = item["id"] + if item.get("source"): + media_by_path[item["source"]] = item["id"] + media_ids = [] + for path in (case.get("_media_paths") or []): + if isinstance(path, str) and path in media_by_path and media_by_path[path] not in media_ids: + media_ids.append(media_by_path[path]) + for kind in ("audio", "image", "video"): + value = inputs.get(kind) + if isinstance(value, str) and value in media_by_path \ + and media_by_path[value] not in media_ids: + media_ids.append(media_by_path[value]) + return { + "id": str(case.get("id") or f"case-{id(case)}"), + "status": str(case.get("label") or "unknown").lower(), + "prompt": inputs.get("prompt") or "", + "expected": case.get("expected"), + "observed": case.get("observed"), + # The answer texts when the task has them, else the bare letters. + "choices": metadata.get("options") or metadata.get("choices") or [], + "tags": case.get("tags") or [], + # The case's own category where the dataset has one; the task kind is + # the same for every case in a run. + "task": str(metadata.get("category") or metadata.get("task") or ""), + "media_ids": media_ids, + "trajectory": case.get("trajectory"), + # explore / confirm / test, as the loop logged it; None when the run + # held nothing back. + "split": case.get("_split") if isinstance(case.get("_split"), str) else None, + } + + +# What each partition was used for, in the words the loop figure draws them +# with: D_E on top, D_H, D_C at the bottom. The code is the subscript. +_EXPLORE_ROLE = ("M1-M3 mined patterns and hypotheses here. Anything measured on " + "these cases is a lead, not a verdict.") + + +_HELDOUT_ROLE = ("Withheld from M1-M3. M4 adjudicated the hypotheses here and M5 " + "developed its repair candidates on the same cases.") + + +_CONFIRM_ROLE = ("Withheld from every adaptive decision. The frozen repair was " + "scored exactly once here.") + + +_TWO_WAY_ROLE = ("Withheld from M1-M3. M4 adjudicated the hypotheses here and the " + "repair was scored on these same cases: one withheld pool " + "serving as both the held-out and the confirm set.") + + +def _assign_partitions(cases: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Summarise the partitions the run put its cases in. + + The rows come back in drawing order, each with the subscript the loop + figure uses (E, H, C), its size and what the run used it for. With a + two-way split the withheld pool is both the held-out set M4 adjudicates on + and the confirm set M5 scores on, so it is one row labelled as both. + + Returns ``[]`` when there is no split to show: the run held nothing back. + """ + present = {str(case.get("split")) for case in cases if case.get("split")} + if not present: + return [] + three_way = "test" in present + + def row(split: str, code: str, label: str, role: str) -> dict[str, Any]: + return {"split": split, "code": code, "label": label, + "n": sum(1 for case in cases if case.get("split") == split), "role": role} + + rows = [row("explore", "E", "Explore", _EXPLORE_ROLE)] + if three_way: + rows.append(row("confirm", "H", "Held-out", _HELDOUT_ROLE)) + rows.append(row("test", "C", "Confirm", _CONFIRM_ROLE)) + elif "confirm" in present: + rows.append(row("confirm", "H/C", "Held-out / Confirm", _TWO_WAY_ROLE)) + n_unknown = sum(1 for case in cases if not case.get("split")) + if n_unknown: + rows.append({"split": "", "code": "?", "label": "Unrecorded", "n": n_unknown, + "role": "The run did not record which partition these came from."}) + return rows diff --git a/evalrx/reporting/report_summary.py b/evalrx/reporting/report_summary.py new file mode 100644 index 00000000..cd6ddc25 --- /dev/null +++ b/evalrx/reporting/report_summary.py @@ -0,0 +1,158 @@ +"""The report's top-line reading: findings, charts, the repair, and the header +metrics. +""" + +from __future__ import annotations + +from typing import Any, Mapping + +from evalrx.reporting.plain_labels import _plain_signal, _stat_label +from evalrx.reporting.report_inputs import _contract_stats + + +def _findings(reader: Mapping[str, Any], raw: Mapping[str, Any]) -> list[dict[str, Any]]: + result = [] + for index, finding in enumerate(reader.get("key_findings") or []): + if isinstance(finding, dict): + result.append({"id": f"finding-{index + 1}", **finding}) + if result: + return result + hypotheses = (raw.get("m3") or {}).get("hypotheses") or [] + for index, hypothesis in enumerate(hypotheses[:3]): + if isinstance(hypothesis, dict): + result.append({ + "id": f"finding-{index + 1}", + "title": hypothesis.get("failure_mode") or "Candidate mechanism", + "summary": hypothesis.get("plain_statement") or hypothesis.get("statement") or "", + "evidence_level": hypothesis.get("status") or "Proposed", + "limitation": "See M4 for independent verification.", + }) + return result + + +def _charts(run: Mapping[str, Any], raw: Mapping[str, Any], + contract: "Mapping[str, Any] | None" = None) -> list[dict[str, Any]]: + charts: list[dict[str, Any]] = [] + labels = run.get("label_distribution") or {} + if isinstance(labels, dict) and labels: + charts.append({ + "id": "outcomes", "kind": "donut", "title": "Evaluation outcomes", + "series": [{"label": str(k).title(), "value": v} for k, v in labels.items() if isinstance(v, (int, float))], + }) + # Prefer the contract's rows: `measured` is a name for the SUBJECT and is + # unique across the report, so the axis cannot end up with two bars reading + # "Mcnemar evalue" (the tool) or several truncating to the same sentence. + contract_rows = _contract_stats(contract or {}) + effect_rows = [] + for item in contract_rows[:8]: + if isinstance(item.get("effect"), (int, float)): + signal = (item.get("config") or {}).get("signal") + effect_rows.append({ + "label": item.get("measured") or _plain_signal(signal or item.get("tool")), + # The analyzer's own sentence. Absent means undocumented, and the + # UI must say that rather than paraphrase the identifier. + "means": item.get("means") or "", + "raw_label": str(signal or item.get("analysis_key") or item.get("tool") or ""), + "value": item["effect"], "highlight": bool(item.get("fdr_corrected")), + }) + if not effect_rows: + stats = (raw.get("m2") or {}).get("stats") or [] + for item in stats[:8]: + if isinstance(item, dict) and isinstance(item.get("effect"), (int, float)): + signal = ((item.get("config") or {}).get("signal") if isinstance(item.get("config"), Mapping) else None) + effect_rows.append({ + "label": _stat_label(item.get("config"), signal, item.get("tool")), + "raw_label": str(signal or item.get("tool") or ""), + "value": item["effect"], "highlight": bool(item.get("reject")), + }) + if effect_rows: + charts.append({ + "id": "effects", "kind": "bar", "title": "Which behaviors appear most connected to errors?", + "subtitle": "A larger bar means a stronger observed pattern. It does not prove the behavior caused the error.", + "series": effect_rows, + }) + return charts + + +def _repairs(raw: Mapping[str, Any], m5_detail: Mapping[str, Any] | None) -> list[dict[str, Any]]: + fix = raw.get("m5_fix") or {} + if not fix.get("ran"): + return [] + best = found if isinstance(found := fix.get("best"), Mapping) else {} + scored = _m5_scored(m5_detail) + return [{ + "id": "repair-1", "fixed": bool(fix.get("fixed")), + "title": best.get("name") or (scored or {}).get("name") or "Targeted repair", + "effect": (scored or best).get("effect"), + "fixed_cases": int(scored["n_fixed"]) if scored else len(best.get("fixed_cases") or []), + "broken_cases": int(scored.get("n_broken") or 0) if scored else len(best.get("broken_cases") or []), + }] + + +def _m5_scored(m5_detail: Mapping[str, Any] | None) -> Mapping[str, Any] | None: + """The repair M5 reports as its result, scored on the withheld cases. + + The stage's own confirmation -- the best candidate re-scored on the + confirm pool -- is what M5 prints as "21 repaired, 6 broken", whether or + not that candidate cleared the certification bar. With no named winner + (it missed the bar, so the fix event names none) the stage still scored + its confirm-phase candidates, and the strongest of those is what it + prints. None when M5 scored nothing. + """ + def _counted(item: Any) -> bool: + value = item.get("n_fixed") if isinstance(item, Mapping) else None + return isinstance(value, (int, float)) and not isinstance(value, bool) + + detail = m5_detail if isinstance(m5_detail, Mapping) else {} + confirmation = detail.get("confirmation") + if isinstance(confirmation, Mapping) and confirmation.get("name") and _counted(confirmation): + return confirmation + scored = [item for item in detail.get("candidates") or [] if _counted(item)] + if scored: + return max(scored, key=lambda item: (float(item.get("effect") or 0.0), float(item["n_fixed"]))) + return None + + +def _cases_repaired(cases: list[dict[str, Any]], m5_detail: Mapping[str, Any] | None) -> int: + """How many withheld cases the M5 repair turned from wrong to right. + + The header tile says what M5 printed (see :func:`_m5_scored`). Case status + never carries a "fixed" value (it is pass / fail), so counting it left the + tile at 0 on every run that repaired anything. Runs that scored no + candidate fall back to the per-case repair outcomes. + """ + scored = _m5_scored(m5_detail) + if scored: + return int(scored["n_fixed"]) + return sum( + 1 for case in cases + if isinstance(case.get("repair"), Mapping) and str(case["repair"].get("status")) == "fixed" + ) + + +def _metrics( + run: Mapping[str, Any], + raw: Mapping[str, Any], + cases: list[dict[str, Any]], + m5_detail: Mapping[str, Any] | None = None, +) -> list[dict[str, Any]]: + labels = run.get("label_distribution") or {} + failed = labels.get("fail", labels.get("FAIL", 0)) if isinstance(labels, dict) else 0 + verified = len((raw.get("m4") or {}).get("results") or []) + fixed = _cases_repaired(cases, m5_detail) + return [ + {"id": "evaluated", "label": "Cases evaluated", "value": int(run.get("n_cases") or len(cases))}, + {"id": "failed", "label": "Initial failures", "value": int(failed or 0)}, + {"id": "verified", "label": "Mechanisms checked", "value": verified}, + {"id": "fixed", "label": "Cases repaired", "value": fixed}, + ] + + +def _explore_metrics(stage_detail: Mapping[str, Any]) -> list[dict[str, Any]]: + """An explore run evaluated no model: count what it found instead.""" + m2, m3 = stage_detail.get("m2") or {}, stage_detail.get("m3") or {} + return [ + {"id": "takeaways", "label": "Patterns found", "value": len(m2.get("takeaways") or [])}, + {"id": "figures", "label": "Charts drawn", "value": len(m2.get("figures") or [])}, + {"id": "hypotheses", "label": "Causes proposed", "value": len(m3.get("hypotheses") or [])}, + ] diff --git a/evalrx/reporting/run_data.py b/evalrx/reporting/run_data.py index f837a4c2..8a30014a 100644 --- a/evalrx/reporting/run_data.py +++ b/evalrx/reporting/run_data.py @@ -1,9 +1,9 @@ """Read a finished run's artifacts into one dictionary. -:func:`extract_run_data` is the single reader behind every report renderer -(the dynamic UI in :mod:`evalrx.reporting.dynamic`, the legacy static page in -:mod:`evalrx.reporting.html_report`, the Langfuse bundle export). It knows the -on-disk run layout and the run log; it knows nothing about HTML. +:func:`extract_run_data` is the single reader behind every report (the UI's +data in :mod:`evalrx.reporting.dynamic`, the Langfuse bundle export). It knows +the on-disk layout of a loop run and of an explore output, and the run log; it +knows nothing about HTML. """ from __future__ import annotations @@ -13,132 +13,7 @@ from pathlib import Path from typing import Any -ANALYZER_GLOSSARY: dict[str, tuple[str, str, str, list[tuple[str, str, str]]]] = { - "answer_extraction_audit": ( - "Answer Extraction Audit", - "Did the model actually answer wrong, or did our parser fail to extract its response?", - "Checks whether formatting quirks (e.g. missing tags, preamble chatter) prevented the parser from extracting the answer even when the model understood the problem.", - [ - ("Extraction Failure Rate on Errors", "suspect_rate", "pct"), - ("Missing Format Tag Rate", "missing_tag_rate", "pct"), - ], - ), - "termination_audit": ( - "Truncation & Early Stop Audit", - "Did the model finish its thought, or was it abruptly cut off by length caps?", - "Identifies whether premature token limits or sudden EOS tokens clipped the model's reasoning chain mid-sentence.", - [ - ("Suspected Truncation Rate", "truncation_rate", "pct"), - ("Recovery Rate upon Continuation", "recovered_rate", "pct"), - ], - ), - "calibration": ( - "Confidence & Overconfidence (ECE)", - "When the model sounds certain, is its actual correctness probability truly high?", - "Measures Expected Calibration Error (ECE) across token logprobs and verbalized confidence. High ECE indicates dangerous overconfidence on incorrect answers.", - [ - ("Token Logprob Calibration Error (ECE)", "logprob_channel.ece", "num"), - ("Verbalized Confidence Error (ECE)", "verbalized_channel.ece", "num"), - ], - ), - "format_sensitivity": ( - "Option Order Sensitivity (Position Bias)", - "If we shuffle choices (A/B/C/D), does the model arbitrarily flip its answer?", - "Permutes multiple-choice options across variants. If answer flips across orderings, the model suffers from severe positional shortcutting rather than semantic understanding.", - [ - ("Answer Flip Rate after Shuffling", "mean_flip_rate", "pct"), - ], - ), - "coverage_verification_gap": ( - "Pass@k Knowledge Blindspot (Coverage)", - "Over 5 repeat attempts, does the model ever produce the right answer even once?", - "Samples temperature completions k=5 times. If pass@5 is 0%, the capability is completely missing from weights; if pass@5 is high but greedy fails, the model suffers from search/ranking misalignment.", - [ - ("Persistent Failure Rate (0/5 correct)", "no_coverage_rate", "pct"), - ("Pass@5 Coverage Rate", "mean_pass_at_k", "pct"), - ], - ), - "self_consistency": ( - "Sampling Consistency", - "When sampled repeatedly with temperature, does the answer waver wildly?", - "Measures whether model predictions stabilize on a single consensus choice or disperse across inconsistent alternatives.", - [ - ("Majority Answer Agreement Rate", "consistency", "pct"), - ], - ), - "self_repair": ( - "Self-Repair on Re-ask", - "When asked to check its own answer, does the model catch and fix its mistakes?", - "Asks the model to critique and revise its first answer. Reports how often it detects a real error, how often it raises a false alarm on a correct answer, and how often the revision actually repairs a failure.", - [ - ("Error Detection Accuracy", "detection_accuracy", "pct"), - ("False Alarm Rate on Correct Answers", "false_alarm_rate", "pct"), - ("Repair Rate on Failures", "repair_rate", "pct"), - ], - ), - "cot_faithfulness": ( - "Chain-of-Thought Faithfulness", - "Does the written reasoning actually drive the final answer, or is it decoration?", - "Compares the answer the model commits to early in its reasoning with the one it ends on: reasoning that drifts away from a correct early answer, or rescues a wrong one late, is unfaithful to the final output.", - [ - ("Early Answer Matches Final", "mean_early_match_rate", "pct"), - ("Drift-Away Rate", "drift_away_rate", "pct"), - ("Late Rescue Rate", "late_rescue_rate", "pct"), - ], - ), - "perturbation_battery": ( - "Perturbation Invariance", - "Do meaning-preserving edits to the prompt change the answer?", - "Rewrites each prompt in ways that should not change the answer (paraphrase, whitespace, ordering) and counts how often the answer breaks anyway; a no-op edit that breaks the answer points at memorisation or brittleness.", - [ - ("Invariance Break Rate", "mean_invariance_break_rate", "pct"), - ("No-op Break Rate", "noop_break_rate", "pct"), - ], - ), - "step_rollout_value": ( - "Step Rollout Value", - "At which reasoning step does the model's chance of finishing correctly collapse?", - "Rolls out completions from successive prefixes of the reasoning and scores each; the point where the success rate drops is where the reasoning went wrong.", - [ - ("Success Rate from the First Step", "mean_initial_value", "pct"), - ("Success Rate from the Last Step", "mean_final_value", "pct"), - ("Mean Break Depth", "mean_break_depth", "num"), - ], - ), - "logprob_entropy": ( - "Predictive Uncertainty (Output Entropy)", - "Is the model confident or internally hesitating when generating key tokens?", - "Computes Shannon entropy across the top candidate tokens to measure decision ambivalence.", - [ - ("Top-Token Prediction Entropy", "mean_top_entropy", "num"), - ("Model Perplexity", "perplexity", "num"), - ], - ), - "selfcheck_consistency": ( - "Self-Contradiction Detection", - "Does the model contradict its own claims across repeat samplings?", - "Probes whether the model generates assertions in one sample that directly contradict its claims in another sample.", - [ - ("Self-Contradiction Index", "mean_inconsistency", "num"), - ], - ), - "hallucination": ( - "Hallucination Probe", - "Does the model generate details unsupported by the source stimulus?", - "Measures semantic grounding against the audible stimulus to catch fabricated details.", - [ - ("Hallucination Deviation Score", "hallucination_score", "num"), - ], - ), - "qwen_attention": ( - "Attention Focus & Sparsity", - "Does model attention properly focus on critical prompt and media cues?", - "Examines cross-attention maps between audio tokens and query tokens to verify sensory uptake.", - [ - ("Core Cue Attention Share", "focus_share", "pct"), - ], - ), -} +from evalrx.reporting.run_probes import probe_section def clean_model_display_name(raw: str) -> str: @@ -156,9 +31,9 @@ def clean_model_display_name(raw: str) -> str: return clean or raw -def clean_benchmark_name(protocol: str, manifest_path: str) -> str: - """Extract a friendly benchmark name from protocol or manifest path.""" - text = (protocol + " " + manifest_path).lower() +def clean_benchmark_name(protocol: str) -> str: + """A friendly benchmark name for the benchmarks a protocol text names.""" + text = protocol.lower() if "mmau" in text: return "MMAU (Multi-Modal Audio Understanding)" if "chartqa" in text: @@ -174,17 +49,18 @@ def clean_benchmark_name(protocol: str, manifest_path: str) -> str: return "Evaluation Benchmark" -def _dig(d: dict, path: str) -> Any: - cur = d - for part in path.split("."): - if not isinstance(cur, dict): - return None - cur = cur.get(part) - return cur +#: What an explore step writes as its report: ``evalrx explore`` / run-codebase +#: write the first, a fused discover→confirm run the second. +EXPLORE_REPORTS = ("exploratory_report.json", "fused_report.json") + +def resolve_run_dirs(run_dir: Path) -> tuple[Path, Path | None]: + """Return (logs_dir, explore_dir). -def resolve_run_dirs(run_dir: Path) -> tuple[Path, Path | None, Path | None]: - """Return (logs_dir, explore_dir, fixes_dir).""" + A loop run keeps its log under ``logs/`` (or at the top). An explore + output (``evalrx explore``, run-codebase, a fused run) holds its report at + the top and is its own explore directory; a run without one has none. + """ run_dir = run_dir.resolve() logs_dir = run_dir if (run_dir / "logs" / "run.json").exists(): @@ -193,169 +69,55 @@ def resolve_run_dirs(run_dir: Path) -> tuple[Path, Path | None, Path | None]: for child in run_dir.glob("*/run.json"): logs_dir = child.parent break - - explore_dir = logs_dir / "explore" - if not explore_dir.is_dir() and (logs_dir.parent / "explore").is_dir(): - explore_dir = logs_dir.parent / "explore" - if not explore_dir.is_dir(): - explore_dir = None - - fixes_dir = logs_dir / "fixes" - if not fixes_dir.is_dir() and (logs_dir.parent / "fixes").is_dir(): - fixes_dir = logs_dir.parent / "fixes" - if not fixes_dir.is_dir(): - fixes_dir = None - - return logs_dir, explore_dir, fixes_dir - - -def find_manifest(example_dir: Path, logs_dir: Path) -> tuple[Path | None, dict[str, dict[str, Any]]]: - """Find and load benchmark manifest (.jsonl / .json).""" - candidates = [] - if example_dir: - candidates.extend(sorted(example_dir.glob("data/*.jsonl"))) - candidates.extend(sorted(example_dir.glob("data/*.json"))) - candidates.extend(sorted(example_dir.glob("*.jsonl"))) - candidates.extend(sorted(logs_dir.glob("data/*.jsonl"))) - candidates.extend(sorted(logs_dir.parent.glob("data/*.jsonl"))) - - for p in candidates: - if p.name.endswith(".result.json") or p.name.endswith("results.json"): - continue - try: - rows = {} - if p.suffix == ".jsonl": - for line in p.open(encoding="utf-8"): - line = line.strip() - if line: - obj = json.loads(line) - cid = str(obj.get("id") or obj.get("case_id") or "") - if cid: - rows[cid] = obj - elif p.suffix == ".json": - data = json.loads(p.read_text(encoding="utf-8")) - recs = data if isinstance(data, list) else (data.get("records") or data.get("cases") or []) - for obj in recs: - if isinstance(obj, dict): - cid = str(obj.get("id") or obj.get("case_id") or "") - if cid: - rows[cid] = obj - if rows: - return p, rows - except Exception: - continue - return None, {} + own_report = any((run_dir / name).is_file() for name in EXPLORE_REPORTS) + return logs_dir, run_dir if own_report else None + + +#: The explore coder-agent's own files, by the key the report shows them under. +_EXPLORE_AGENT_FILES = { + "raw_output": "agent_raw_output.txt", + "raw_streams": "agent_raw_streams.txt", + "code": "analysis.py", + "stdout": "stdout.txt", + "stderr": "stderr.txt", + "audit": "agent_audit.json", +} -def _extract_agent_layer(logs_dir: Path, explore_dir: "Path | None") -> dict[str, Any]: - """The agent layer of a run: verbatim judge I/O, the explore coder-agent's - trajectory, synthesized tool codegen attempts, and the Langfuse trace bundle. +def _explore_agent_files(explore_dir: "Path | None", explore_event: dict[str, Any]) -> dict[str, str]: + """The text of each explore-agent file that exists, by file name. - This is what makes the report drill below the pipeline stages: a reader who - sees a probe or a hypothesis and asks "what did the agent actually see and - say?" can expand down to the raw prompt/response text. + On disk for an explore output; for a loop run they are the files the + logger inlined on the explore event (``workspace_snapshot.files``). """ - agents: dict[str, Any] = { - "judge_calls": [], - "explore": {}, - "tool_codegen": [], - "langfuse": {}, - } - - # -- Verbatim judge calls (prompts/.prompt.txt + .response.txt) ---- - def _stage_of(stem: str) -> str: - if "_m1_" in stem: - return "M1 Analyzer Selection" - if "_m2_" in stem: - return "M2 Statistical Screening" - if "_m3_" in stem: - return "M3 AI Doctor Diagnosis" - if "_m4_" in stem: - return "M4 Protocol Consistency" - if "_m5_" in stem: - return "M5 Intervention" - if "_agent_decision" in stem: - return "Agentic Loop Decision" - return "Other" - - prompts_dir = logs_dir / "prompts" - if prompts_dir.exists(): - for pf in sorted(prompts_dir.glob("*.prompt.txt")): - stem = pf.name[: -len(".prompt.txt")] - rf = pf.with_name(stem + ".response.txt") - try: - prompt = pf.read_text(encoding="utf-8") - except Exception: - prompt = "" + files: dict[str, str] = {} + if explore_dir is not None: + for name in _EXPLORE_AGENT_FILES.values(): try: - response = rf.read_text(encoding="utf-8") if rf.exists() else "" - except Exception: - response = "" - if not prompt and not response: - continue - agents["judge_calls"].append({ - "stem": stem, - "stage": _stage_of(stem), - "prompt": prompt, - "response": response, - "prompt_chars": len(prompt), - "raw_chars": len(response), - }) - - # -- Explore coder-agent trajectory -------------------------------------- - exp: dict[str, Any] = {} - if explore_dir is not None and Path(explore_dir).exists(): - ed = Path(explore_dir) - for key, fname in ( - ("raw_output", "agent_raw_output.txt"), - ("raw_streams", "agent_raw_streams.txt"), - ("code", "analysis.py"), - ("stdout", "stdout.txt"), - ("stderr", "stderr.txt"), - ): - p = ed / fname - if p.exists(): - try: - exp[key] = p.read_text(encoding="utf-8") - except Exception: - pass - audit_p = ed / "agent_audit.json" - if audit_p.exists(): - try: - exp["audit"] = json.loads(audit_p.read_text(encoding="utf-8")) - except Exception: + files[name] = (Path(explore_dir) / name).read_text(encoding="utf-8") + except (OSError, UnicodeError): pass - agents["explore"] = exp - - # -- Synthesized tool codegen attempts (tools/) -------------------------- - tools_dir = logs_dir / "tools" - if tools_dir.exists(): - groups: dict[str, dict[str, str]] = {} - order: list[str] = [] - for f in sorted(tools_dir.iterdir()): - if not f.is_file(): - continue - name = f.name - for suffix, kind in ( - ("_code.py", "code"), ("_prompt.txt", "prompt"), - ("_agent_thinking.txt", "agent_thinking"), ("_stdout.txt", "stdout"), - ("_agent_raw_stream.txt", "raw_stream"), - ): - if name.endswith(suffix): - stem = name[: -len(suffix)] - if stem not in groups: - groups[stem] = {} - order.append(stem) - try: - groups[stem][kind] = f.read_text(encoding="utf-8") - except Exception: - pass - break - for stem in order: - if groups[stem]: - agents["tool_codegen"].append({"stem": stem, "files": groups[stem]}) - - # -- Langfuse trace bundle summary --------------------------------------- + return files + snapshot = explore_event.get("workspace_snapshot") + inlined = snapshot.get("files") if isinstance(snapshot, dict) else None + return {name: text for name, text in (inlined or {}).items() + if name in _EXPLORE_AGENT_FILES.values() and isinstance(text, str)} + + +def _extract_agent_layer( + logs_dir: Path, explore_dir: "Path | None", explore_event: dict[str, Any], +) -> dict[str, Any]: + """What sits below the pipeline stages: the explore coder-agent's code, + output and audit, and a summary of the Langfuse trace bundle.""" + files = _explore_agent_files(explore_dir, explore_event) + exp: dict[str, Any] = {key: files[name] for key, name in _EXPLORE_AGENT_FILES.items() if name in files} + if "audit" in exp: + try: + exp["audit"] = json.loads(exp["audit"]) + except ValueError: + del exp["audit"] + agents: dict[str, Any] = {"explore": exp, "langfuse": {}} + lf = logs_dir / "langfuse_trace.json" if lf.exists(): try: @@ -381,15 +143,15 @@ def _stage_of(stem: str) -> str: def _snapshot_explore_report(explore_event: dict[str, Any]) -> dict[str, Any]: - """The explore step's own report, read back out of a V2 explore event. + """The explore step's own report, read back out of the explore event. - RunLoggerV2 keeps no explore/ directory beside the logs. It inlines the + RunLogger keeps no explore/ directory beside the logs. It inlines the coder-agent's whole working directory on the explore event (``workspace_snapshot.files``) and copies every figure into M2/artifacts/ under a content-hashed name, recording the original -> copied path pairs - as ``media_files``. The inlined ``exploratory_report.json`` is the very - document V1 wrote to explore/: the ranked takeaways with the charts each - one cites, the visual plan, the chart readings. Without it the M2 record + as ``media_files``. The inlined ``exploratory_report.json`` is the + explorer's own document: the ranked takeaways with the charts each one + cites, the visual plan, the chart readings. Without it the M2 record fell back to the event's observation sentences, which cite nothing, and every finding rendered as "referenced visual evidence was not found" with all of its charts filed under supporting material. @@ -427,50 +189,31 @@ def _snapshot_explore_report(explore_event: dict[str, Any]) -> dict[str, Any]: return report -def extract_run_data(run_dir: Path, example_dir: Path | None = None) -> dict[str, Any]: - """Parse all run artifacts dynamically into a unified dictionary.""" - logs_dir, explore_dir, fixes_dir = resolve_run_dirs(run_dir) - manifest_path, manifest = find_manifest(example_dir or logs_dir.parent, logs_dir) - - from evalrx.reporting.run_events import read_v2_events +def _latest_run_events(logs_dir: Path) -> list[dict[str, Any]]: + """The run log's events, from the latest run only when a directory was reused.""" + from evalrx.reporting.run_events import read_run_events - events: list[dict[str, Any]] = read_v2_events(logs_dir) + events: list[dict[str, Any]] = read_run_events(logs_dir) + run_starts = [e for e in events if e.get("event") == "run_start"] + if not run_starts: + return events + trace_id = run_starts[-1].get("trace_id") + return [e for e in events if e.get("trace_id") == trace_id] - all_run_starts = [e for e in events if e.get("event") == "run_start"] - run_start = all_run_starts[-1] if all_run_starts else {} - active_trace_id = run_start.get("trace_id") - # Directories are commonly reused. Keep a report internally consistent by - # selecting the events from the latest run's trace only. - if active_trace_id: - scoped_events = [e for e in events if e.get("trace_id") == active_trace_id] - # Keep compatibility with pre-trace legacy logs, where only run_start - # may have a trace id (or none of the events do). - if len(scoped_events) > 1: - events = scoped_events - def by_event(event: str) -> list[dict[str, Any]]: - return [e for e in events if e.get("event") == event] - - loop_end = by_event("loop_end")[-1] if by_event("loop_end") else {} - manifest_json = logs_dir / "manifest.json" - cfg = json.loads(manifest_json.read_text()) if manifest_json.exists() else {} - - raw_model_name = ( - run_start.get("model") - or cfg.get("model") - or cfg.get("config", {}).get("model") - or "Target Model" - ) +def _run_section( + run_start: dict[str, Any], loop_end: dict[str, Any], logs_dir: Path, +) -> dict[str, Any]: + """What ran: the model, the benchmark, its size and how the loop ended.""" + raw_model_name = run_start.get("model") or "Target Model" clean_model = clean_model_display_name(raw_model_name) - n_cases = run_start.get("n_cases") or len(manifest) or 0 - label_dist = run_start.get("label_distribution") or {} protocol = run_start.get("protocol") or {} protocol_desc = ( protocol.get("description") or "" if isinstance(protocol, dict) else str(protocol) ) - benchmark_name = clean_benchmark_name(protocol_desc, str(manifest_path or "")) + benchmark_name = clean_benchmark_name(protocol_desc) # The run's own summary.json (written by run_pipeline beside logs/) names # the model and dataset the way the user typed them — "qwen3.5-2b", # "bbh_word_sorting". It beats both a stringified Model repr and the @@ -493,129 +236,31 @@ def by_event(event: str) -> list[dict[str, Any]]: or (folder if folder not in {"outputs", "logs", ""} else "") or benchmark_name ) + return { + # "loop" for a diagnose loop's run log, "explore" for the report + # an explore step wrote on its own. + "kind": "loop", + "model": clean_model, + "raw_model": raw_model_name, + "benchmark_name": benchmark_name, + "n_cases": run_start.get("n_cases") or 0, + "label_distribution": run_start.get("label_distribution") or {}, + "protocol": protocol_desc, + "cycles": loop_end.get("cycles", 1), + "stopped_by": loop_end.get("stopped_by", "completed"), + "duration_sec": loop_end.get("total_duration_sec", 0), + "version": run_start.get("evalrx_version", "0.2.0"), + "data_fingerprint": run_start.get("data_fingerprint", ""), + "coder": run_start.get("coder") or "", + "logs_dir": str(logs_dir), + } - # Pre-M1 - probe_searches = by_event("probe_search") - pre_m1_ran = bool(probe_searches) - pre_m1_cases = probe_searches[0].get("n_synthesized") if pre_m1_ran else 0 - - # Probe Case Map for reverse-lookup of anomalies per sample - probe_case_flags: dict[str, list[str]] = {} - - # M1: Measurements & Per-case probe drilldowns - probes = by_event("probe") - p0 = probes[-1] if probes else {} - m1_cycle = int(p0.get("cycle", 0) or 0) - analyzers = p0.get("analyzers") or p0.get("selected_analyzers") or [] - m1_duration = p0.get("duration_sec") - - # An agent-written probe ("generated:probe1") has no glossary entry; the - # need it was written for is the only description that exists, and the - # codegen event carries it verbatim. - generated_need: dict[str, str] = {} - for event in by_event("tool_codegen"): - tool = str(event.get("tool_name") or "") - if tool and event.get("need"): - generated_need[tool] = str(event["need"]) - m1_results = [] - for name in analyzers: - result_paths = p0.get("result_paths") or {} - p = logs_dir / str(result_paths.get(name) or f"artifacts/c{m1_cycle}_{name}.result.json") - findings, n = {}, None - per_case_rows = [] - # V1 externalised each analyzer's result to artifacts/; RunLoggerV2 - # keeps the findings inline on the probe entry itself. - inline = (p0.get("findings") or {}).get(name) - if not p.exists() and isinstance(inline, dict): - findings = inline - n = findings.get("n_cases") or findings.get("n_scored") - per_case_rows = findings.get("per_case") or [] - if p.exists(): - try: - raw = json.loads(p.read_text()) - findings = raw.get("findings") or {} - n = findings.get("n_cases") or findings.get("n_scored") - per_case_rows = findings.get("per_case") or [] - for pc in per_case_rows: - sid = str(pc.get("sample_id", "")) - if sid: - if sid not in probe_case_flags: - probe_case_flags[sid] = [] - if pc.get("format_flip_rate", 0) > 0: - probe_case_flags[sid].append(f"Option Order Flip ({pc['format_flip_rate']:.0%})") - if pc.get("conf_logprob", 0) > 0.8 and pc.get("correct") == 0: - probe_case_flags[sid].append(f"Overconfident on Error ({pc['conf_logprob']:.0%})") - if pc.get("pass_at_k") == 1.0: - probe_case_flags[sid].append("Pass@5 Capable") - elif pc.get("pass_at_k") == 0.0: - probe_case_flags[sid].append("Pass@5 Zero-Coverage") - except Exception: - pass - meta = ANALYZER_GLOSSARY.get( - name, (name.replace("_", " ").title(), "Measures model behavior across this dimension", "Standard diagnostic probe.", []) - ) - if name.startswith("generated:"): - # No glossary can know a probe the agent wrote during this run: the - # need it was written for is its question (first sentence up front, - # the whole brief as the description), and its headline is whatever - # scalar findings it reported, under their own names. - need = generated_need.get(name.split(":", 1)[1], "") - first = re.split(r"(?<=[.;])\s+", need.strip(), maxsplit=1)[0] if need else "Agent-written probe" - if len(first) > 180: - first = first[:177].rstrip() + "…" - scalar = [ - (key.replace("_", " "), key, "pct" if key.endswith(("_rate", "_frac")) else "num") - for key, value in findings.items() - if isinstance(value, (int, float)) and not isinstance(value, bool) - and key not in {"n_cases", "n_scored", "n_graded", "n_samples"} - ][:5] - meta = (f"Agent-written probe · {name.split(':', 1)[1]}", first, need or "Agent-written probe.", scalar) - headline = [] - for label, path, fmt in meta[3]: - v = _dig(findings, path) - if isinstance(v, (int, float)): - headline.append({ - "label": label, - "value": f"{v:.1%}" if fmt == "pct" else f"{v:.3f}".rstrip("0").rstrip("."), - }) - else: - headline.append({"label": label, "value": None}) - m1_results.append({ - "name": name, - "display_name": meta[0], - "question": meta[1], - "description": meta[2], - "n": n, - "headline": headline, - "findings": findings, - "per_case": per_case_rows, - }) - m1_results.sort(key=lambda r: -(r["n"] or 0)) - - # M2: Explore & Screening - analyses = by_event("analysis") - a0 = analyses[-1] if analyses else {} - m2_conclusion = a0.get("conclusion") or "" - m2_narrative = a0.get("narrative") or "" - m2_severity = a0.get("severity") or "medium" - m2_duration = a0.get("duration_sec") - - m2_cycle = int(a0.get("cycle", m1_cycle) or 0) - stats_path = logs_dir / f"artifacts/c{m2_cycle}_m2_stats_results.json" - stats_ref = a0.get("stats_results") - if isinstance(stats_ref, dict) and stats_ref.get("path"): - stats_path = logs_dir / str(stats_ref["path"]) - try: - raw_stats = json.loads(stats_path.read_text()) if stats_path.exists() else [] - except (OSError, json.JSONDecodeError): - raw_stats = [] - if not raw_stats and isinstance(stats_ref, list): - # RunLoggerV2 keeps the M2 rows inline on the analysis entry rather - # than externalising them to artifacts/. - raw_stats = [row for row in stats_ref if isinstance(row, dict)] - stats = [] - for s in raw_stats: - stats.append({ + +def _m2_stats(analysis: dict[str, Any]) -> list[dict[str, Any]]: + """The analysis step's test rows, rejected nulls first, largest effect first.""" + rows = analysis.get("stats_results") + stats: list[dict[str, Any]] = [ + { "tool": s.get("tool"), "config": s.get("config") or {}, "summary": s.get("summary") or "", @@ -624,315 +269,186 @@ def by_event(event: str) -> list[dict[str, Any]]: "reject": bool(s.get("reject")), "p_value": s.get("p_value"), "underpowered": bool(s.get("underpowered")), - }) + # The two group rates behind an effect, for the rate comparison chart. + "details": s.get("details") or {}, + } + for s in (rows if isinstance(rows, list) else []) + if isinstance(s, dict) + ] stats.sort(key=lambda s: (not s["reject"], -abs(s.get("effect") or 0))) + return stats + + +def _explore_from_sentences(explore_event: dict[str, Any], analysis: dict[str, Any]) -> dict[str, Any]: + """An explore report shaped from what the run log kept as sentences. + + With no report to read, the events still carry observations and caveats + as sentences and figures as paths under logs/. Shaping those the way the + explore report is shaped lets the M2 record render either. + """ + takeaways = [] + for text in analysis.get("findings") or []: + if isinstance(text, str) and text.strip(): + # "[MEDIUM] self_consistency.consistency=0.2 < 0.5: low self-consistency — …" + body = re.sub(r"^\[[A-Z]+\]\s*", "", text.strip()) + head = body.split(": ", 1)[1] if ": " in body else body + takeaways.append({"title": head[:110], "plain_title": head[:110], + "analysis": body, "chart_names": [], "table_names": []}) + for text in explore_event.get("observations") or []: + if isinstance(text, str) and text.strip(): + head = text.strip().split(";")[0].split(". ")[0] + takeaways.append({"title": head[:90], "plain_title": head[:90], + "analysis": text.strip(), "chart_names": [], "table_names": []}) + if not (takeaways or explore_event): + return {} + return { + "takeaways": takeaways, + "caveats": [c for c in explore_event.get("caveats") or [] if isinstance(c, str)], + "observations": [o for o in explore_event.get("observations") or [] if isinstance(o, str)], + "figures": [f for f in explore_event.get("figures") or [] if isinstance(f, str)], + "adjudication": explore_event.get("adjudication") or {}, + "candidate_signals": [], "hypotheses": [], + } - explore_data: dict[str, Any] = {} - if explore_dir and (explore_dir / "exploratory_report.json").exists(): - try: - explore_data = json.loads((explore_dir / "exploratory_report.json").read_text()) - except Exception: - pass - # RunLoggerV2 records the explore step as an M2 event; both fallbacks - # below read from it. - explores = by_event("explore") - e0 = explores[-1] if explores else {} - if not explore_data: - # The explorer's own report -- takeaways and the charts they cite -- - # rides along inlined in the event's workspace snapshot; read that - # back first. - explore_data = _snapshot_explore_report(e0) - if not explore_data: - # No snapshot report: the event still carries observations and caveats - # as sentences and figures as paths under logs/. Shape those the way - # the explore report is shaped, so the M2 record renders either. - takeaways = [] - for text in a0.get("findings") or []: - if isinstance(text, str) and text.strip(): - # "[MEDIUM] self_consistency.consistency=0.2 < 0.5: low self-consistency — …" - body = re.sub(r"^\[[A-Z]+\]\s*", "", text.strip()) - head = body.split(": ", 1)[1] if ": " in body else body - takeaways.append({"title": head[:110], "plain_title": head[:110], - "analysis": body, "chart_names": [], "table_names": []}) - for text in e0.get("observations") or []: - if isinstance(text, str) and text.strip(): - head = text.strip().split(";")[0].split(". ")[0] - takeaways.append({"title": head[:90], "plain_title": head[:90], - "analysis": text.strip(), "chart_names": [], "table_names": []}) - if takeaways or e0: - explore_data = { - "takeaways": takeaways, - "caveats": [c for c in e0.get("caveats") or [] if isinstance(c, str)], - "observations": [o for o in e0.get("observations") or [] if isinstance(o, str)], - "figures": [f for f in e0.get("figures") or [] if isinstance(f, str)], - "adjudication": e0.get("adjudication") or {}, - "candidate_signals": [], "hypotheses": [], - } - # M3: Hypotheses - diagnoses = by_event("diagnosis") - dg = diagnoses[-1] if diagnoses else {} - hypotheses = dg.get("hypotheses") or [] - if not hypotheses and (logs_dir / "report" / "hypotheses.json").exists(): +def _explore_report( + explore_dir: Path | None, explore_event: dict[str, Any], analysis: dict[str, Any], +) -> dict[str, Any]: + """The explore step's report, from the best source the run has. + + The report file it wrote, else the copy inlined in the explore event's + workspace snapshot (RunLogger records the explore step as an M2 event), + else the events' own sentences. + """ + report: dict[str, Any] = {} + report_path = next((explore_dir / name for name in EXPLORE_REPORTS + if explore_dir and (explore_dir / name).exists()), None) + if report_path is not None: try: - hypotheses = json.loads((logs_dir / "report" / "hypotheses.json").read_text()) + report = json.loads(report_path.read_text()) except Exception: pass + return report or _snapshot_explore_report(explore_event) or _explore_from_sentences(explore_event, analysis) + + +def _m4_results(m4_surgeries: list[dict[str, Any]]) -> list[dict[str, Any]]: + """One verdict row per hypothesis M4 adjudicated. + + One hypothesis can be tested more than once across cycles — every + hypothesis this run actually adjudicated belongs here, not just the most + recent verdict, otherwise a 3-hypothesis M4 pass reports as if only 1 ran. + """ + return [{ + "hypothesis_id": event.get("hypothesis_id"), + "hypothesis": event.get("hypothesis"), + "status": event.get("status"), + "effect_size": (event.get("evidence") or {}).get("m4_effect_size"), + "confidence": event.get("confidence_score"), + "verdict": (event.get("evidence") or {}).get("m4_verdict"), + "evidence_grade": (event.get("evidence") or {}).get("m4_evidence_grade"), + "protocol_consistent": (event.get("evidence") or {}).get("m4_protocol_consistent"), + # Each verdict's own test statistics; a card must not borrow another's. + "evidence": event.get("evidence") or {}, + } for event in m4_surgeries] + + +def _mark_explore_output(data: dict[str, Any], report: dict[str, Any]) -> None: + """Describe ``data`` as an explore output rather than a loop run. + + Its report sits at the top with no run log, so the stages that ran, the + question and the data explored are all read off the report. + """ + data["m2"]["ran"] = True + data["m3"]["ran"] = bool(report.get("hypotheses")) + profile = report.get("data_profile") or {} + source = Path(str(profile.get("source_path") or "")).name + data["run"].update( + kind="explore", + benchmark_name=source or data["run"]["benchmark_name"], + protocol=data["run"]["protocol"] or str( + report.get("plain_question") or report.get("question") or ""), + ) + + +def _m3_error(events: list[dict[str, Any]]) -> str: + """The last M3 failure the loop logged (``role="diagnosis"``).""" + return next(( + str(e["error"]) for e in reversed(events) + if e.get("event") == "model_call" and e.get("role") == "diagnosis" and e.get("error") + ), "M3 gave no usable answer.") + + +def extract_run_data(run_dir: Path) -> dict[str, Any]: + """Read a run's log, or an explore output's report, into one dictionary.""" + logs_dir, explore_dir = resolve_run_dirs(run_dir) + events = _latest_run_events(logs_dir) + + def named(event: str) -> list[dict[str, Any]]: + return [e for e in events if e.get("event") == event] - # M4: Adjudication - surgeries = by_event("surgery") + def last(event: str) -> dict[str, Any]: + found = named(event) + return found[-1] if found else {} + + run = _run_section(last("run_start"), last("loop_end"), logs_dir) + probe_searches = named("probe_search") + probe, analysis, diagnosis, fix = last("probe"), last("analysis"), last("diagnosis"), last("fix") + m1 = probe_section(probe, named("tool_codegen")) + explore_report = _explore_report(explore_dir, last("explore"), analysis) + surgeries = named("surgery") m4_surgeries = [s for s in surgeries if s.get("module") == "m4" or s.get("adjudication")] - m4_results_file = logs_dir / "report" / "m4_results.json" - try: - m4_results = json.loads(m4_results_file.read_text()) if m4_results_file.exists() else [] - except (OSError, json.JSONDecodeError): - m4_results = [] - m4_event = m4_surgeries[-1] if m4_surgeries else {} - if m4_surgeries: - # The JSONL event is trace-scoped; a report artifact can be stale when - # the same run directory is appended to later. One hypothesis can be - # tested more than once across cycles — every hypothesis this run - # actually adjudicated belongs here, not just the most recent verdict, - # otherwise a 3-hypothesis M4 pass reports as if only 1 ran. - m4_results = [{ - "hypothesis_id": event.get("hypothesis_id"), - "hypothesis": event.get("hypothesis"), - "status": event.get("status"), - "effect_size": (event.get("evidence") or {}).get("m4_effect_size"), - "confidence": event.get("confidence_score"), - "verdict": (event.get("evidence") or {}).get("m4_verdict"), - "evidence_grade": (event.get("evidence") or {}).get("m4_evidence_grade"), - "protocol_consistent": (event.get("evidence") or {}).get("m4_protocol_consistent"), - } for event in m4_surgeries] - - # M5-Surgery + m4_results = _m4_results(m4_surgeries) m5_surgeries = [s for s in surgeries if s.get("module") != "m4"] - m5_surgery_ran = bool(m5_surgeries) - - # M5-Fix: Repair - fixes = by_event("fix") - f0 = fixes[-1] if fixes else {} - best_fix = f0.get("best") or {} - fix_attempts = f0.get("selection_attempted") or f0.get("attempted") or [] - - confirmed_fix: dict[str, Any] = {} - fix_dir = None - if fixes_dir: - cand_dirs = sorted(fixes_dir.glob("*/result.json")) - if cand_dirs: - picked = cand_dirs[-1] - for cd in cand_dirs: - try: - res_j = json.loads(cd.read_text()) - if res_j.get("fixed"): - picked = cd - break - except Exception: - pass - fix_dir = picked.parent - try: - confirmed_fix = json.loads(picked.read_text()) - except Exception: - pass + best_fix = fix.get("best") or {} - if not confirmed_fix and isinstance(best_fix, dict): - confirmed_fix = best_fix - - cases: list[dict[str, Any]] = [] - output_files = [] - if fix_dir and (fix_dir / "outputs.jsonl").exists(): - output_files.append(fix_dir / "outputs.jsonl") - output_files.extend(sorted(logs_dir.glob("**/outputs.jsonl"))) - if logs_dir.parent != logs_dir: - output_files.extend(sorted(logs_dir.parent.glob("**/outputs.jsonl"))) - - seen_case_ids = set() - if output_files: - target_out = output_files[0] - for line in target_out.open(encoding="utf-8"): - line = line.strip() - if line: - try: - r = json.loads(line) - cid = str(r.get("case_id") or r.get("id") or "") - if not cid: - continue - seen_case_ids.add(cid) - m = manifest.get(cid) or {} - instruction = ( - m.get("instruction") - or m.get("question") - or m.get("prompt") - or m.get("query") - or "" - ) - choices = m.get("choices") or m.get("options") or m.get("candidates") or [] - expected = m.get("expected") or m.get("answer") or m.get("label") or m.get("gt") or "" - audio_p = ( - m.get("audio_path") - or m.get("audio") - or m.get("wav_path") - or m.get("audio_file") - or "" - ) - image_p = ( - m.get("image") - or m.get("image_path") - or m.get("image_file") - or "" - ) - if isinstance(image_p, (list, tuple)): - image_p = image_p[0] if image_p else "" - - cases.append({ - "id": cid, - "status": r.get("status", "unchanged"), - "output": str(r.get("output", "")), - "instruction": instruction, - "choices": choices, - "expected": str(expected), - "audio_path": audio_p, - "image_path": image_p, - "duration": float(m.get("duration_sec") or 0.0), - "task": (m.get("metadata") or {}).get("mmau_task") or (m.get("metadata") or {}).get("category") or "", - "probe_flags": probe_case_flags.get(cid, []), - }) - except Exception: - pass - - # Fallback to manifest + baseline - if not cases and manifest: - fixed_set = set(confirmed_fix.get("fixed_cases") or []) - broken_set = set(confirmed_fix.get("broken_cases") or []) - baseline_map = {} - for bp in [logs_dir / "artifacts" / "baseline.json", *logs_dir.glob("**/baseline.json")]: - if bp.exists(): - try: - bdata = json.loads(bp.read_text()) - for bc in (bdata.get("cases") or []): - if isinstance(bc, dict) and bc.get("id"): - baseline_map[str(bc["id"])] = bc - except Exception: - pass - - for cid, m in manifest.items(): - st = "unchanged" - if cid in fixed_set: - st = "fixed" - elif cid in broken_set: - st = "broken" - - b_out = baseline_map.get(cid, {}).get("output", "") - instruction = ( - m.get("instruction") - or m.get("question") - or m.get("prompt") - or m.get("query") - or "" - ) - choices = m.get("choices") or m.get("options") or m.get("candidates") or [] - expected = m.get("expected") or m.get("answer") or m.get("label") or m.get("gt") or "" - audio_p = ( - m.get("audio_path") - or m.get("audio") - or m.get("wav_path") - or m.get("audio_file") - or "" - ) - image_p = ( - m.get("image") - or m.get("image_path") - or m.get("image_file") - or "" - ) - if isinstance(image_p, (list, tuple)): - image_p = image_p[0] if image_p else "" - - cases.append({ - "id": cid, - "status": st, - "output": str(b_out), - "instruction": instruction, - "choices": choices, - "expected": str(expected), - "audio_path": audio_p, - "image_path": image_p, - "duration": float(m.get("duration_sec") or 0.0), - "task": (m.get("metadata") or {}).get("mmau_task") or (m.get("metadata") or {}).get("category") or "", - "probe_flags": probe_case_flags.get(cid, []), - }) - - order = {"fixed": 0, "broken": 1, "unchanged": 2, "untested": 3} - cases.sort(key=lambda c: (order.get(c["status"], 9), c["id"])) - - data = { - "run": { - "model": clean_model, - "raw_model": raw_model_name, - "benchmark_name": benchmark_name, - "n_cases": n_cases, - "label_distribution": label_dist, - "protocol": protocol_desc, - "cycles": loop_end.get("cycles", 1), - "stopped_by": loop_end.get("stopped_by", "completed"), - "duration_sec": loop_end.get("total_duration_sec", 0), - "version": run_start.get("evalrx_version", "0.2.0"), - "data_fingerprint": run_start.get("data_fingerprint", ""), - "logs_dir": str(logs_dir), - "manifest_path": str(manifest_path) if manifest_path else "", - }, + data: dict[str, Any] = { + "run": run, "pre_m1": { - "ran": pre_m1_ran, - "n_cases": pre_m1_cases, - }, - "m1": { - "analyzers": analyzers, - "duration": m1_duration, - "results": m1_results, + "ran": bool(probe_searches), + "n_cases": probe_searches[0].get("n_synthesized") if probe_searches else 0, }, + "m1": m1, "m2": { - "conclusion": m2_conclusion, - "narrative": m2_narrative, - "severity": m2_severity, - "duration": m2_duration, - "stats": stats, - "explore": explore_data, - # The analysis step's own figures (V2 paths under logs/). - "figures": [f for f in a0.get("figures") or [] if isinstance(f, str)], + "conclusion": analysis.get("conclusion") or "", + "narrative": analysis.get("narrative") or "", + "severity": analysis.get("severity") or "medium", + "duration": analysis.get("duration_sec"), + "stats": _m2_stats(analysis), + "explore": explore_report, + # The analysis step's own figures (paths under logs/). + "figures": [f for f in analysis.get("figures") or [] if isinstance(f, str)], }, "m3": { - "hypotheses": hypotheses, - # The proposer's own list, kept beside the (possibly reordered and - # critic-annotated) accepted list. It is the only place a run - # recorded before the log writer carried `plain_statement` on - # `hypotheses` still has the judge's plain sentence, and the report - # compiler joins the two on the statement to recover it. - "proposed_hypotheses": dg.get("proposed_hypotheses") or [], - "duration": dg.get("duration_sec"), + "hypotheses": diagnosis.get("hypotheses") or [], + "duration": diagnosis.get("duration_sec"), + # Why M3 gave nothing when the run stopped on it (judge unreadable, + # unavailable or out of quota after its retries). + "error": _m3_error(events) if run["stopped_by"] == "diagnosis_error" else None, }, "m4": { "ran": bool(m4_surgeries or m4_results), "results": m4_results, - "event": m4_event, + "event": m4_surgeries[-1] if m4_surgeries else {}, }, "m5_surgery": { - "ran": m5_surgery_ran, + "ran": bool(m5_surgeries), "surgeries": m5_surgeries, }, "m5_fix": { - "ran": bool(fixes or confirmed_fix), - "fixed": bool(f0.get("fixed") or confirmed_fix.get("fixed")), - "selection": fix_attempts, - "confirm": confirmed_fix, + "ran": bool(fix), + "fixed": bool(fix.get("fixed") or best_fix.get("fixed")), + "selection": fix.get("selection_attempted") or fix.get("attempted") or [], "best": best_fix, - "prompt_template": (confirmed_fix.get("payload") or {}).get("prompt_template") or "", + "prompt_template": (best_fix.get("payload") or {}).get("prompt_template") or "", }, - "cases": cases, - "agents": _extract_agent_layer(logs_dir, explore_dir), + "agents": _extract_agent_layer(logs_dir, explore_dir, last("explore")), "logs_dir": logs_dir, "explore_dir": explore_dir, - "example_dir": example_dir or logs_dir.parent, } + if not events and explore_report and explore_dir == logs_dir: + # A loop run's explore/ child is not an explore output; only a report + # at the top of a directory with no run log is. + _mark_explore_output(data, explore_report) # Keep the audience-first semantic layer independent from HTML. The same # object can later drive a different renderer without reinterpreting logs. from evalrx.reporting.compiler import compile_reader_report diff --git a/evalrx/reporting/run_events.py b/evalrx/reporting/run_events.py index 81e747b9..66a4c47f 100644 --- a/evalrx/reporting/run_events.py +++ b/evalrx/reporting/run_events.py @@ -1,4 +1,4 @@ -"""Read tidy RunLoggerV2 documents through the existing event-view contract.""" +"""Read tidy RunLogger documents through the existing event-view contract.""" from __future__ import annotations @@ -9,8 +9,8 @@ _STAGES = ("M1", "M2", "M3", "M4", "M5") -def resolve_v2_root(root: str | Path) -> Path | None: - """Return the directory containing V2 ``run.json`` and stage folders.""" +def resolve_run_root(root: str | Path) -> Path | None: + """Return the directory containing ``run.json`` and the stage folders.""" root = Path(root).resolve() candidates = (root, root / "logs") for candidate in candidates: @@ -21,18 +21,17 @@ def resolve_v2_root(root: str | Path) -> Path | None: return None -def read_v2_events(root: str | Path) -> list[dict[str, Any]]: - """Flatten V2 bucketed documents into the legacy read-only event view. +def read_run_events(root: str | Path) -> list[dict[str, Any]]: + """A run's events as one flat list, in the order they were logged. - The V2 files remain authoritative and are never rewritten by this adapter. - It exists so current report/UI code can migrate independently from the - storage layout. + The log stores them bucketed (``run.json`` plus one document per stage); + report code reads this flat view and never rewrites the files. """ - v2_root = resolve_v2_root(root) - if v2_root is None: + run_root = resolve_run_root(root) + if run_root is None: return [] try: - run = json.loads((v2_root / "run.json").read_text(encoding="utf-8")) + run = json.loads((run_root / "run.json").read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): return [] @@ -43,14 +42,11 @@ def append(event: str, payload: Any, *, stage: str = "RUN") -> None: if not isinstance(payload, dict): return record = dict(payload) + # The bucket a record sits in says which event and stage it is, and + # the run names its trace once; a bundle rebuilt by write_run_bundle + # from recovered events may carry none of the three on the record. record.setdefault("event", event) record.setdefault("stage", stage) - # Older V2 bundles encode this only in the folder name. Existing - # case-study/report consumers still use the V1 module discriminator. - if event == "surgery": - record.setdefault("module", stage.lower()) - elif event == "fix": - record.setdefault("module", "fix") if trace_id: record.setdefault("trace_id", trace_id) events.append(record) @@ -59,7 +55,7 @@ def append(event: str, payload: Any, *, stage: str = "RUN") -> None: for row in run.get("cases") or []: append("case_record", row) for key in ( - "report_published", "diagnose_reports", "loop_end", + "report_published", "diagnose_reports", "loop_end", "run_end", "agent_decisions", "agent_tool_calls", "unrouted", ): event_name = { @@ -72,7 +68,7 @@ def append(event: str, payload: Any, *, stage: str = "RUN") -> None: append(event_name, row) for stage in _STAGES: - path = v2_root / stage / "log.json" + path = run_root / stage / "log.json" if not path.is_file(): continue try: @@ -87,22 +83,18 @@ def append(event: str, payload: Any, *, stage: str = "RUN") -> None: for row in rows: append("model_call" if event == "model_calls" else event, row, stage=stage) - # New bundles persist a global sequence at write time, even when calls - # finish concurrently or the wall clock moves backwards. Legacy bundles - # retain timestamp ordering; never replace a persisted event identity. - if all(isinstance(event.get("event_seq"), int) for event in events): - events.sort(key=lambda event: event["event_seq"]) - else: - events.sort(key=lambda event: str(event.get("ts") or "")) - seq = max((event.get("event_seq", 0) for event in events), default=0) - for event in events: - if "event_seq" not in event: - seq += 1 - event["event_seq"] = seq + # The logger stamps a global sequence at write time, so the order holds + # even when calls finish concurrently or the wall clock moves backwards. + if any(not isinstance(event.get("event_seq"), int) for event in events): + raise ValueError( + f"{run_root} is not a readable run log: its events carry no event_seq, " + "so it was written by an earlier log format. Re-run it to open it here." + ) + events.sort(key=lambda event: event["event_seq"]) return events -# Inverse of the RUN-stage bucket mapping `read_v2_events` flattens — event +# Inverse of the RUN-stage bucket mapping `read_run_events` flattens — event # name -> run.json key. These names are always RUN-level regardless of any # "stage" tag on the recovered event. _RUN_EVENT_TO_KEY = { @@ -112,14 +104,15 @@ def append(event: str, payload: Any, *, stage: str = "RUN") -> None: "agent_tool": "agent_tool_calls", "report_published": "report_published", "loop_end": "loop_end", + "run_end": "run_end", } # A source that recovers events out-of-band (e.g. Langfuse observations # reconstructed from a durable-outbox delivery, which predates per-event # "stage" tagging) may hand back events with no "stage" field at all. Route # by the event's own name to its canonical stage rather than dumping it into -# run.json's "unrouted" bucket, where `resolve_v2_root` would never find it -# (it requires at least one real M/log.json to recognize a V2 root). +# run.json's "unrouted" bucket, where `resolve_run_root` would never find it +# (it requires at least one real M/log.json to recognize a run root). _NAME_TO_STAGE = { "probe": "M1", "analysis": "M2", "explore": "M2", @@ -139,13 +132,13 @@ def _fallback_stage(name: "str | None", row: dict[str, Any]) -> "str | None": return _NAME_TO_STAGE.get(name or "") -def write_v2_bundle(root: str | Path, events: list[dict[str, Any]]) -> None: +def write_run_bundle(root: str | Path, events: list[dict[str, Any]]) -> None: """Reconstruct ``run.json`` + ``M/log.json`` from a flat event list. - The exact inverse of :func:`read_v2_events`'s bucketing, for callers that + The exact inverse of :func:`read_run_events`'s bucketing, for callers that recover events from an out-of-band source (e.g. Langfuse) and need to - write a V2-shaped cache directory back for the report/dashboard's - normal V2-only read path to find. + write a run-log-shaped cache directory back for the report's normal + read path to find. """ root = Path(root) run_doc: dict[str, Any] = {} @@ -181,4 +174,4 @@ def write_v2_bundle(root: str | Path, events: list[dict[str, Any]]) -> None: ) -__all__ = ["read_v2_events", "resolve_v2_root", "write_v2_bundle"] +__all__ = ["read_run_events", "resolve_run_root", "write_run_bundle"] diff --git a/evalrx/reporting/run_probes.py b/evalrx/reporting/run_probes.py new file mode 100644 index 00000000..2e1b91cf --- /dev/null +++ b/evalrx/reporting/run_probes.py @@ -0,0 +1,216 @@ +"""M1's probe results as a report shows them. + +One entry per analyzer the probe step ran: what it asks, its headline numbers +and the findings the probe event recorded for it. +""" + +from __future__ import annotations + +import re +from typing import Any + +ANALYZER_GLOSSARY: dict[str, tuple[str, str, str, list[tuple[str, str, str]]]] = { + "answer_extraction_audit": ( + "Answer Extraction Audit", + "Did the model actually answer wrong, or did our parser fail to extract its response?", + "Checks whether formatting quirks (e.g. missing tags, preamble chatter) prevented the parser from extracting the answer even when the model understood the problem.", + [ + ("Extraction Failure Rate on Errors", "suspect_rate", "pct"), + ("Missing Format Tag Rate", "missing_tag_rate", "pct"), + ], + ), + "termination_audit": ( + "Truncation & Early Stop Audit", + "Did the model finish its thought, or was it abruptly cut off by length caps?", + "Identifies whether premature token limits or sudden EOS tokens clipped the model's reasoning chain mid-sentence.", + [ + ("Suspected Truncation Rate", "truncation_rate", "pct"), + ("Recovery Rate upon Continuation", "recovered_rate", "pct"), + ], + ), + "calibration": ( + "Confidence & Overconfidence (ECE)", + "When the model sounds certain, is its actual correctness probability truly high?", + "Measures Expected Calibration Error (ECE) across token logprobs and verbalized confidence. High ECE indicates dangerous overconfidence on incorrect answers.", + [ + ("Token Logprob Calibration Error (ECE)", "logprob_channel.ece", "num"), + ("Verbalized Confidence Error (ECE)", "verbalized_channel.ece", "num"), + ], + ), + "format_sensitivity": ( + "Option Order Sensitivity (Position Bias)", + "If we shuffle choices (A/B/C/D), does the model arbitrarily flip its answer?", + "Permutes multiple-choice options across variants. If answer flips across orderings, the model suffers from severe positional shortcutting rather than semantic understanding.", + [ + ("Answer Flip Rate after Shuffling", "mean_flip_rate", "pct"), + ], + ), + "coverage_verification_gap": ( + "Pass@k Knowledge Blindspot (Coverage)", + "Over 5 repeat attempts, does the model ever produce the right answer even once?", + "Samples temperature completions k=5 times. If pass@5 is 0%, the capability is completely missing from weights; if pass@5 is high but greedy fails, the model suffers from search/ranking misalignment.", + [ + ("Persistent Failure Rate (0/5 correct)", "no_coverage_rate", "pct"), + ("Pass@5 Coverage Rate", "mean_pass_at_k", "pct"), + ], + ), + "self_consistency": ( + "Sampling Consistency", + "When sampled repeatedly with temperature, does the answer waver wildly?", + "Measures whether model predictions stabilize on a single consensus choice or disperse across inconsistent alternatives.", + [ + ("Majority Answer Agreement Rate", "consistency", "pct"), + ], + ), + "self_repair": ( + "Self-Repair on Re-ask", + "When asked to check its own answer, does the model catch and fix its mistakes?", + "Asks the model to critique and revise its first answer. Reports how often it detects a real error, how often it raises a false alarm on a correct answer, and how often the revision actually repairs a failure.", + [ + ("Error Detection Accuracy", "detection_accuracy", "pct"), + ("False Alarm Rate on Correct Answers", "false_alarm_rate", "pct"), + ("Repair Rate on Failures", "repair_rate", "pct"), + ], + ), + "cot_faithfulness": ( + "Chain-of-Thought Faithfulness", + "Does the written reasoning actually drive the final answer, or is it decoration?", + "Compares the answer the model commits to early in its reasoning with the one it ends on: reasoning that drifts away from a correct early answer, or rescues a wrong one late, is unfaithful to the final output.", + [ + ("Early Answer Matches Final", "mean_early_match_rate", "pct"), + ("Drift-Away Rate", "drift_away_rate", "pct"), + ("Late Rescue Rate", "late_rescue_rate", "pct"), + ], + ), + "perturbation_battery": ( + "Perturbation Invariance", + "Do meaning-preserving edits to the prompt change the answer?", + "Rewrites each prompt in ways that should not change the answer (paraphrase, whitespace, ordering) and counts how often the answer breaks anyway; a no-op edit that breaks the answer points at memorisation or brittleness.", + [ + ("Invariance Break Rate", "mean_invariance_break_rate", "pct"), + ("No-op Break Rate", "noop_break_rate", "pct"), + ], + ), + "step_rollout_value": ( + "Step Rollout Value", + "At which reasoning step does the model's chance of finishing correctly collapse?", + "Rolls out completions from successive prefixes of the reasoning and scores each; the point where the success rate drops is where the reasoning went wrong.", + [ + ("Success Rate from the First Step", "mean_initial_value", "pct"), + ("Success Rate from the Last Step", "mean_final_value", "pct"), + ("Mean Break Depth", "mean_break_depth", "num"), + ], + ), + "logprob_entropy": ( + "Predictive Uncertainty (Output Entropy)", + "Is the model confident or internally hesitating when generating key tokens?", + "Computes Shannon entropy across the top candidate tokens to measure decision ambivalence.", + [ + ("Top-Token Prediction Entropy", "mean_top_entropy", "num"), + ("Model Perplexity", "perplexity", "num"), + ], + ), + "selfcheck_consistency": ( + "Self-Contradiction Detection", + "Does the model contradict its own claims across repeat samplings?", + "Probes whether the model generates assertions in one sample that directly contradict its claims in another sample.", + [ + ("Self-Contradiction Index", "mean_inconsistency", "num"), + ], + ), + "hallucination": ( + "Hallucination Probe", + "Does the model generate details unsupported by the source stimulus?", + "Measures semantic grounding against the audible stimulus to catch fabricated details.", + [ + ("Hallucination Deviation Score", "hallucination_score", "num"), + ], + ), + "qwen_attention": ( + "Attention Focus & Sparsity", + "Does model attention properly focus on critical prompt and media cues?", + "Examines cross-attention maps between audio tokens and query tokens to verify sensory uptake.", + [ + ("Core Cue Attention Share", "focus_share", "pct"), + ], + ), +} + + +def _dig(d: dict, path: str) -> Any: + cur: Any = d + for part in path.split("."): + if not isinstance(cur, dict): + return None + cur = cur.get(part) + return cur + + +def _generated_meta(tool: str, need: str, findings: dict[str, Any]) -> tuple[str, str, str, list[tuple[str, str, str]]]: + """Glossary-shaped entry for a probe the agent wrote during this run. + + No glossary can know it: the need it was written for is its question + (first sentence up front, the whole brief as the description), and its + headline is whatever scalar findings it reported, under their own names. + """ + first = re.split(r"(?<=[.;])\s+", need.strip(), maxsplit=1)[0] if need else "Agent-written probe" + if len(first) > 180: + first = first[:177].rstrip() + "…" + scalar = [ + (key.replace("_", " "), key, "pct" if key.endswith(("_rate", "_frac")) else "num") + for key, value in findings.items() + if isinstance(value, (int, float)) and not isinstance(value, bool) + and key not in {"n_cases", "n_scored", "n_graded", "n_samples"} + ][:5] + return (f"Agent-written probe · {tool}", first, need or "Agent-written probe.", scalar) + + +def _headline(findings: dict[str, Any], fields: list[tuple[str, str, str]]) -> list[dict[str, Any]]: + headline: list[dict[str, Any]] = [] + for label, path, fmt in fields: + v = _dig(findings, path) + if isinstance(v, (int, float)): + headline.append({ + "label": label, + "value": f"{v:.1%}" if fmt == "pct" else f"{v:.3f}".rstrip("0").rstrip("."), + }) + else: + headline.append({"label": label, "value": None}) + return headline + + +def probe_section(probe: dict[str, Any], codegen_events: list[dict[str, Any]]) -> dict[str, Any]: + """The M1 section for a run's probe event, largest sample first.""" + # An agent-written probe ("generated:probe1") has no glossary entry; the + # need it was written for is the only description that exists, and the + # codegen event carries it verbatim. + generated_need: dict[str, str] = {} + for event in codegen_events: + tool = str(event.get("tool_name") or "") + if tool and event.get("need"): + generated_need[tool] = str(event["need"]) + + analyzers = probe.get("analyzers") or probe.get("selected_analyzers") or [] + results = [] + for name in analyzers: + inline = (probe.get("findings") or {}).get(name) + findings: dict[str, Any] = inline if isinstance(inline, dict) else {} + if name.startswith("generated:"): + tool = name.split(":", 1)[1] + meta = _generated_meta(tool, generated_need.get(tool, ""), findings) + else: + meta = ANALYZER_GLOSSARY.get( + name, (name.replace("_", " ").title(), "Measures model behavior across this dimension", "Standard diagnostic probe.", []) + ) + results.append({ + "name": name, + "display_name": meta[0], + "question": meta[1], + "description": meta[2], + "n": findings.get("n_cases") or findings.get("n_scored"), + "headline": _headline(findings, meta[3]), + "findings": findings, + "per_case": findings.get("per_case") or [], + }) + results.sort(key=lambda r: -(r["n"] or 0)) + return {"analyzers": analyzers, "duration": probe.get("duration_sec"), "results": results} diff --git a/evalrx/reporting/server.py b/evalrx/reporting/server.py index 917d6bac..95e8aa83 100644 --- a/evalrx/reporting/server.py +++ b/evalrx/reporting/server.py @@ -8,9 +8,10 @@ import os import re import tempfile +import time from datetime import datetime, timezone from pathlib import Path -from typing import Any +from typing import Any, Callable, Iterator from evalrx.reporting.dynamic import ( CATALOG_VERSION, @@ -27,7 +28,7 @@ # module globals — a function-local import of UploadFile would not be seen. from fastapi import File, UploadFile except ImportError: # pragma: no cover - create_app reports the missing extra - File = UploadFile = None # type: ignore[assignment] + File = UploadFile = None # type: ignore[assignment,misc] # A dropped archive is a whole run directory, which for a media-carrying # benchmark is mostly audio/video. The workbench default (1 GiB) is the same @@ -114,9 +115,9 @@ def _run_label(root: Path) -> str: return f"{root.parent.name}/{root.name}" if root.name == "logs" else root.name -#: RunLoggerV2's per-stage documents (evalrx/eval_agent/run_logger_v2.py). +#: RunLogger's per-stage documents (evalrx/eval_agent/run_logger.py). #: A run.json + at least one of these is its on-disk signature, matching -#: find_run_root's marker and reporting/run_events.py's resolve_v2_root. +#: find_run_root's marker and reporting/run_events.py's resolve_run_root. _STAGES = ("M1", "M2", "M3", "M4", "M5") @@ -247,26 +248,89 @@ def find_run_root(base: Path) -> Path | None: def _compile_report(root: Path) -> tuple[dict[str, Any], dict[str, Any]]: - """Publish the run's report cache when writable, else compile in memory.""" + """Publish the run's report cache when writable, else compile in memory. + + A run still being written is compiled in memory too: its directory + belongs to the logger until the run ends, and it is published then. + """ try: - if not report_is_current(root): - publish_report(root) + if report_is_current(root): + return load_published_report(root) + data = build_report_data(root) + if not data["setting"]["finished"]: + return data, _in_memory_envelope(data, "deterministic-live") + publish_report(root) return load_published_report(root) except PermissionError: # Historical/shared runs are often intentionally read-only. Serving a # report must not require mutating its evidence directory. data = build_report_data(root) - envelope = { - "schema_version": REPORT_SCHEMA_VERSION, - "format": "json-render", - "json_render_version": JSON_RENDER_VERSION, - "catalog_version": CATALOG_VERSION, - "trace_id": data["trace_id"], - "source_event_seq": data["source_event_seq"], - "generated_by": {"mode": "deterministic-read-only", "model": None}, - "spec": fallback_spec(data), - } - return data, envelope + return data, _in_memory_envelope(data, "deterministic-read-only") + + +def _in_memory_envelope(data: dict[str, Any], mode: str) -> dict[str, Any]: + return { + "schema_version": REPORT_SCHEMA_VERSION, + "format": "json-render", + "json_render_version": JSON_RENDER_VERSION, + "catalog_version": CATALOG_VERSION, + "trace_id": data["trace_id"], + "source_event_seq": data["source_event_seq"], + "generated_by": {"mode": mode, "model": None}, + "spec": fallback_spec(data), + } + + +def _log_signature(root: Path) -> tuple[tuple[str, int, int], ...]: + """What changes whenever the run's log is rewritten: each document's + mtime and size. Cheaper than re-reading the log on every poll, and it + sees a second logger that restarts ``event_seq`` in the same directory.""" + stamps = [] + for doc in (root / "run.json", *(root / stage / "log.json" for stage in _STAGES)): + try: + stat = doc.stat() + except OSError: + continue + stamps.append((doc.name if doc.parent == root else doc.parent.name, stat.st_mtime_ns, stat.st_size)) + return tuple(stamps) + + +def follow_run( + runs: "RunRegistry", + key: str, + *, + poll_sec: float = 2.0, + max_sec: float = 600.0, + sleep: Callable[[float], None] = time.sleep, +) -> Iterator[str]: + """Server-sent events for a run being written: ``update`` whenever its log + is rewritten (the run is recompiled first), ``done`` once it has finished. + + The stream ends after *max_sec* without ``done`` while the run goes on, and + the browser's EventSource reconnects; only ``done`` tells it to stop. A + compile that fails on a half-written document keeps the last good report + and is retried on the next poll. + """ + run = runs.get(key) + seen = _log_signature(run.root) + waited = 0.0 + while not run.data["setting"].get("finished", True): + if waited >= max_sec: + return + sleep(poll_sec) + waited += poll_sec + signature = _log_signature(run.root) + if signature == seen: + yield ": waiting\n\n" + continue + try: + run = runs.open(key) + except Exception: # noqa: BLE001 - a document mid-rewrite; try again + continue + seen = signature + payload = json.dumps({"source_event_seq": run.data.get("source_event_seq")}) + yield f"event: update\ndata: {payload}\n\n" + yield "event: done\ndata: {}\n\n" def create_app( @@ -287,7 +351,7 @@ def create_app( """ try: from fastapi import FastAPI, HTTPException, Query - from fastapi.responses import FileResponse + from fastapi.responses import FileResponse, StreamingResponse from fastapi.staticfiles import StaticFiles except ImportError as exc: raise ImportError( @@ -366,6 +430,16 @@ def get_report(run_id: str) -> dict[str, Any]: run = loaded(run_id) return {"id": run_id, "label": run.label, "root": str(run.root), **run.payload} + @app.get("/api/runs/{run_id}/live") + def follow(run_id: str) -> Any: + """Follow a run still being written (server-sent events; see follow_run).""" + loaded(run_id) + return StreamingResponse( + follow_run(runs, run_id), + media_type="text/event-stream", + headers={"Cache-Control": "no-store"}, + ) + @app.get("/api/runs/{run_id}/stages/{stage_id}") def get_stage(run_id: str, stage_id: str) -> dict[str, Any]: data = loaded(run_id).data @@ -420,10 +494,8 @@ def get_media(run_id: str, media_id: str) -> Any: if item is None: raise HTTPException(status_code=404, detail="Unknown media") # A media id is selected from the report's fixed evidence index, not a - # caller-provided path. It may safely resolve into the example's - # adjacent data directory (where VLM images / ALLM audio conventionally - # live), while the generic artifact endpoint remains run-confined. - path = _resolve_indexed_media(run.root, str(item.get("path") or "")) + # caller-provided path; the logger copied the file into the run. + path = _resolve_media(run.root, str(item.get("path") or "")) if path is None: raise HTTPException(status_code=404, detail="Media is not available in the local cache") return FileResponse(path, media_type=mimetypes.guess_type(path.name)[0]) @@ -521,7 +593,6 @@ def _resolve_media(root: Path, value: str) -> Path | None: possibilities = [candidate] if candidate.is_absolute() else [ root / candidate, root.parent / candidate, - root.parent / "data" / candidate, ] for possibility in possibilities: try: @@ -536,31 +607,3 @@ def _resolve_media(root: Path, value: str) -> Path | None: if any(resolved == base or base in resolved.parents for base in allowed_roots): return resolved return None - - -def _resolve_indexed_media(root: Path, value: str) -> Path | None: - """Resolve report-indexed case media without opening arbitrary paths. - - Case assets may live at ``/data`` while a run writes its log to - ``/outputs*/logs``. The media index was built from saved case - records, so this endpoint permits only that nearby data directory in - addition to the usual run-owned roots. The artifact route deliberately - does not use this broader resolver. - """ - resolved = _resolve_media(root, value) - if resolved is not None: - return resolved - candidate = Path(value) - possibilities = [candidate] if candidate.is_absolute() else [ - root.parent / "data" / candidate, - root.parent.parent / "data" / candidate, - ] - allowed_roots = [root.parent / "data", root.parent.parent / "data"] - for possibility in possibilities: - try: - path = possibility.resolve() - except OSError: - continue - if path.is_file() and any(base.resolve() in path.parents for base in allowed_roots if base.is_dir()): - return path - return None diff --git a/evalrx/reporting/stage_examples.py b/evalrx/reporting/stage_examples.py new file mode 100644 index 00000000..89c2f084 --- /dev/null +++ b/evalrx/reporting/stage_examples.py @@ -0,0 +1,230 @@ +"""The worked examples each stage view shows: probe outputs (M1), held-out cases +(M4), and what a repair changed on real cases (M5). +""" + +from __future__ import annotations + +from typing import Any, Mapping, Sequence + +from evalrx.reporting.plain_labels import _plain_label + + +def _attach_example_media(examples: list[dict[str, Any]], cases: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]: + case_by_id = {str(case.get("id")): case for case in cases} + for example in examples: + if example.get("probe_title"): + example["probe_title"] = _plain_label(example["probe_title"]) + if example.get("media_ids"): + continue + case = case_by_id.get(str(example.get("case_id") or "")) + if case: + example["media_ids"] = list(case.get("media_ids") or []) + return examples + + +def _m4_examples( + results: list[Any], event: Mapping[str, Any], cases: Sequence[Mapping[str, Any]] +) -> list[dict[str, Any]]: + """The validation cases the M4 event recorded, named for the hypothesis tested.""" + supplied = event.get("validation_examples") if isinstance(event, Mapping) else None + if not isinstance(supplied, list): + return [] + first: Mapping[str, Any] = next((item for item in results if isinstance(item, Mapping)), {}) + evidence = found if isinstance(found := first.get("evidence"), Mapping) else {} + return [{ + **dict(item), + "hypothesis": item.get("hypothesis") or first.get("hypothesis") or first.get("statement"), + "test": item.get("test") or first.get("test_name") or evidence.get("chosen_tool"), + "status": item.get("status") or first.get("status"), + } for item in supplied if isinstance(item, Mapping)][:2] + + +def _operation_examples(cases: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]: + """Project recorded agent tool trajectories into compact, case-linked UI cards. + + This intentionally ignores prompt text that *mentions* a tool. An action + appears only if a persisted trajectory step carries a structured + ``tool_call``. That preserves the distinction between an actual zoom and + an LLM merely proposing one. + """ + result: list[dict[str, Any]] = [] + for case in cases: + trajectory = case.get("trajectory") + if not isinstance(trajectory, Mapping): + continue + steps = trajectory.get("steps") + if not isinstance(steps, list): + continue + calls: list[dict[str, Any]] = [] + for step in steps: + if not isinstance(step, Mapping) or not isinstance(step.get("tool_call"), Mapping): + continue + call = step["tool_call"] + name = str(call.get("name") or "tool") + calls.append({ + "order": int(step.get("idx") or len(calls) + 1), + "action": _plain_operation(name), "raw_action": name, + "parameters": dict(call.get("args") or {}) if isinstance(call.get("args"), Mapping) else {}, + "thought": str(step.get("content") or "")[:500], + }) + if not calls: + continue + result.append({ + "id": f"operations-{case.get('id')}", "case_id": str(case.get("id") or ""), + "input": case.get("prompt") or "", "expected": case.get("expected"), + "observed": case.get("observed"), "outcome": case.get("status") or "unknown", + "media_ids": list(case.get("media_ids") or []), "steps": calls[:6], + "plain_reading": "These are the actions recorded in this agent's own trajectory for this case.", + }) + if len(result) >= 2: + break + return result + + +def _repair_operation_previews( + candidates: Sequence[Mapping[str, Any]], cases: Sequence[Mapping[str, Any]] +) -> list[dict[str, Any]]: + """Show what an image-operation repair *would* apply, without claiming execution. + + Older runs preserve a repair spec but not a per-call visual artifact. The + report can still pair its declared image operations with the original input + image for a representative case, as long as the card is explicitly marked + as a candidate preview. Actual execution is represented by + :func:`_operation_examples` instead. + """ + image_cases = [case for case in cases if case.get("media_ids")] + result: list[dict[str, Any]] = [] + for candidate in candidates: + payload = found if isinstance(found := candidate.get("payload"), Mapping) else {} + ops = [op for op in payload.get("image_ops") or [] if isinstance(op, Mapping) and op.get("tool")] + if not ops: + continue + preferred_ids = [str(item) for item in (candidate.get("fixed_cases") or candidate.get("broken_cases") or [])] + case = next((item for item in image_cases if str(item.get("id")) in preferred_ids), None) + case = case or next((item for item in image_cases if str(item.get("status")) == "fail"), None) + # With no failing image case to show, an arbitrary corpus image is + # still useful to explain the *declared transform*, provided the UI + # calls it a preview and never a validated before/after result. + case = case or (image_cases[0] if image_cases else None) + if case is None: + continue + result.append({ + "id": f"repair-operations-{candidate.get('name')}", "candidate": candidate.get("name"), + "case_id": str(case.get("id") or ""), "input": case.get("prompt") or "", + "expected": case.get("expected"), "observed": case.get("observed"), + "media_ids": list(case.get("media_ids") or []), + "executed": bool(candidate.get("n_pairs")), + "operations": [{ + "action": _plain_operation(op.get("tool")), "raw_action": str(op.get("tool")), + "parameters": dict(op.get("params") or {}) if isinstance(op.get("params"), Mapping) else {}, + } for op in ops], + }) + if len(result) >= 2: + break + return result + + +def _plain_operation(value: Any) -> str: + names = { + "image_zoom_in": "Zoom in on part of the image", "zoom_center": "Zoom into the chart center", + "crop": "Crop the visual evidence", "crop_case_bbox": "Crop the relevant chart region", + "sharpen": "Sharpen chart details", "contrast": "Increase visual contrast", + "equalize": "Balance the image contrast", "detect": "Locate an object or region", + } + raw = str(value or "") + return names.get(raw, _plain_label(raw)) + + +def _m5_examples( + candidates: Sequence[Mapping[str, Any]], cases: Sequence[Mapping[str, Any]], probe_results: list[Any] +) -> list[dict[str, Any]]: + """Reconstruct a truthful before/after repair example — confirmed or not. + + A candidate that never cleared the significance bar is still what the + search actually tried, and a reader debugging a failed repair needs to + see a real case, not just "no candidate passed the repair gate". Prefer a + `fixed` winner (statistically significant, net-positive); when none + exists, fall back to the strongest attempt by effect size — the same + fallback `M5Detail` already uses for its own "best repair" KPI — and tag + the example `confirmed: False` so the UI can say plainly it is one + candidate's attempt, not an accepted repair. When that candidate never + flipped a case to correct either, fall back once more to a case it broke: + still evidence, just of the failure mode rather than the fix. + """ + winner = next((item for item in candidates if item.get("fixed")), None) + confirmed = winner is not None + if winner is None: + winner = max( + (item for item in candidates if isinstance(item.get("effect"), (int, float))), + key=lambda item: item["effect"], + default=(candidates[0] if candidates else None), + ) + if winner is None: + return [] + case_by_id = {str(case.get("id")): case for case in cases} + baseline_by_id: dict[str, Any] = {} + for probe in probe_results: + if not isinstance(probe, Mapping): + continue + for row in probe.get("per_case") or []: + if not isinstance(row, Mapping): + continue + case_id = str(row.get("sample_id") or row.get("case_id") or "") + output = row.get("extracted_answer", row.get("modal_answer")) + if case_id and output not in (None, ""): + baseline_by_id.setdefault(case_id, output) + + def _build(case_id: str, kind: str) -> "dict[str, Any] | None": + case = case_by_id.get(case_id) + if not case: + return None + # `case["observed"]` is the Stage-0 baseline, written once per case id + # (RunLogger.log_cases dedupes by id) and never updated — it is NOT + # this candidate's repaired answer, no matter which case_record last + # touched it. The only place a candidate's own per-case output lives + # is `case["repair"]`, which build_report_data attached from the fix + # event's confirmation attempts (see _repair_outcomes). Confirm + # it is THIS candidate's repair, not some other one that also touched + # this case, before trusting it as "repaired". + repair_hit = case.get("repair") if isinstance(case.get("repair"), Mapping) else None + repaired = ( + repair_hit.get("output") + if repair_hit and repair_hit.get("candidate") == winner.get("name") + else None + ) + if repaired in (None, ""): + return None # no recorded per-case output for this candidate — nothing truthful to show + baseline = baseline_by_id.get(case_id) + if baseline in (None, ""): + baseline = case.get("observed") # the genuine Stage-0 answer, as a last resort + if confirmed: + reading = ("This case was counted as fixed in the paired repair evaluation. " + "The repair decision still depends on all tested cases and its " + "regression checks.") + elif kind == "fixed": + reading = ("This candidate flipped this case from wrong to right, but the " + "repair overall did not clear the significance bar against luck — " + "read it as one attempt worth inspecting, not a confirmed fix.") + else: + reading = ("This candidate did not clear the significance bar, and did not " + "flip any case to correct either — this is a case it broke instead, " + "shown so the failure mode is inspectable.") + return { + "id": f"m5-{winner.get('name', 'repair')}-{case_id}", "case_id": case_id, + "kind": kind, "confirmed": confirmed, + "repair_name": winner.get("name") or "Recorded repair", "input": case.get("prompt") or "", + "expected": case.get("expected"), "baseline_output": baseline, + "repaired_output": repaired, "media_ids": list(case.get("media_ids") or []), + "plain_reading": reading, + "baseline_available": baseline not in (None, ""), + } + + for case_id in [str(item) for item in winner.get("fixed_cases") or []]: + example = _build(case_id, "fixed") + if example: + return [example] + for case_id in [str(item) for item in winner.get("broken_cases") or []]: + example = _build(case_id, "broken") + if example: + return [example] + return [] diff --git a/evalrx/reporting/stage_figures.py b/evalrx/reporting/stage_figures.py new file mode 100644 index 00000000..e2652a66 --- /dev/null +++ b/evalrx/reporting/stage_figures.py @@ -0,0 +1,162 @@ +"""The figures M2 and M3 cite: logged by the run, rendered by the explore step, +or planned in its snapshot report. +""" + +from __future__ import annotations + +import os +import re +from pathlib import Path +from typing import Any, Iterable, Mapping, Sequence + + +def _m2_figures( + raw: Mapping[str, Any], m2: Mapping[str, Any], explore: Mapping[str, Any], + logs_dir: Path, root: Path, +) -> list[dict[str, Any]]: + # An explore output keeps its figures in figures/ beside its report. + explore_dir = raw.get("explore_dir") + figures = _explore_figures(explore, Path(explore_dir) / "figures", root) if explore_dir else [] + if not figures: + # A loop run: the logger copied the explorer's figures into + # M2/artifacts/ under hashed names and kept the original name of each + # beside the copy; that name is what the takeaways cite, so the join + # runs on it. + figures = _snapshot_figures(explore, logs_dir, root) + if not figures: + # No explore report to join against: the explore and analysis events + # still name their figures as paths under logs/. + return _logged_figures( + [*(explore.get("figures") or []), *(m2.get("figures") or [])], logs_dir, root) + # The analysis step's own chart sits beside the explorer's, as it did + # when both came off the events. + known = {figure["path"] for figure in figures} + return figures + [ + figure for figure in _logged_figures(m2.get("figures") or [], logs_dir, root) + if figure["path"] not in known + ] + + +def _visual_key(value: Any) -> str: + return re.sub(r"[^a-z0-9]", "", Path(str(value or "")).stem.lower()) + + +def _logged_figures(paths: Iterable[Any], logs_dir: Path, root: Path) -> list[dict[str, Any]]: + """Figures the run logged by path (relative to logs/), that exist on disk.""" + result: list[dict[str, Any]] = [] + seen: set[Path] = set() + for item in paths: + if not isinstance(item, str) or not item.lower().endswith(".png"): + continue + candidate = (logs_dir / item).resolve() + if candidate in seen or not candidate.is_file(): + continue + seen.add(candidate) + stem = re.sub(r"_[0-9a-f]{8}$", "", candidate.stem) # the content-hash suffix the logger adds + result.append({ + "id": candidate.stem, "title": stem.replace("_", " ").strip().title(), + "question": "", "path": os.path.relpath(candidate, root), "reading": "", + "do_not_infer": "No agent-authored interpretation was saved for this figure.", + "disposition": "supporting", "not_promoted_reason": "", + }) + return result[:30] + + +#: The ordering prefix the host puts on the charts it renders +#: (``00_class_balance.png`` for the plan's ``class_balance``). +_ORDER_PREFIX = re.compile(r"^\d+_") + + +_EXPLORE_FIGURE_SUFFIXES = (".png", ".jpg", ".jpeg", ".webp", ".svg") + + +def _explore_figures(explore: Mapping[str, Any], figure_dir: Path, root: Path) -> list[dict[str, Any]]: + """The explorer's figures from the figures/ directory of an explore output.""" + files = sorted(figure_dir.glob("*.png")) if figure_dir.is_dir() else [] + return _planned_figures(explore, [(path.name, path) for path in files], root) + + +def _snapshot_figures(explore: Mapping[str, Any], logs_dir: Path, root: Path) -> list[dict[str, Any]]: + """The explorer's figures as RunLogger copied them into M2/artifacts/. + + ``media_files`` (see ``run_log_files.inline_workspace``) pairs each sandbox + file -- ``figures/00_class_balance.png`` -- with its content-hashed copy + under logs/. The sandbox name is the one the takeaways cite and the visual + plan is keyed by; the copy is only where the bytes are. So the join runs + on the name and a figure's id here is a chart name, never a hash stem. + """ + pairs: list[tuple[str, Path]] = [] + for name, copied in (explore.get("media_files") or {}).items(): + if not isinstance(name, str) or not isinstance(copied, str): + continue + if not name.lower().endswith(_EXPLORE_FIGURE_SUFFIXES): + continue + candidate = (logs_dir / copied).resolve() + if candidate.is_file(): + pairs.append((Path(name).name, candidate)) + pairs.sort(key=lambda pair: pair[0]) + return _planned_figures(explore, pairs, root) + + +def _planned_figures( + explore: Mapping[str, Any], files: Sequence[tuple[str, Path]], root: Path, +) -> list[dict[str, Any]]: + """Figure records for *files*, each ``(name the explorer used, path on disk)``. + + A file the visual plan names gets the plan's reader-facing title and + question and the chart reading written for it; its id is the plan's name, + which is also what the takeaways cite. A file the plan does not name is + still shown, under its own stem minus the ordering prefix -- again the + name a takeaway would cite. + """ + plans = [item for item in explore.get("visual_plan") or [] if isinstance(item, Mapping)] + readings = [item for item in explore.get("chart_readings") or [] if isinstance(item, Mapping)] + result: list[dict[str, Any]] = [] + used: set[Path] = set() + ids: set[str] = set() + + def unique(candidate: str) -> str: + chosen, n = candidate, 2 + while chosen in ids: + chosen = f"{candidate}_{n}" + n += 1 + ids.add(chosen) + return chosen + + for plan in plans: + name = str(plan.get("name") or "") + key = _visual_key(name) + if not key: + continue + # An exact match after the ordering prefix comes off wins; only then a + # file whose name merely contains the plan's. Otherwise + # ``failrate_by_answer_length`` takes ``..._band``'s file whenever that + # one sorts first. + match = next((path for fname, path in files + if path not in used and _visual_key(_ORDER_PREFIX.sub("", fname)) == key), None) + if match is None: + match = next((path for fname, path in files + if path not in used and key in _visual_key(fname)), None) + if match is None: + continue + used.add(match) + reading = next((item for item in readings if _visual_key(item.get("chart")) == key), {}) + result.append({ + "id": unique(name), "title": str(plan.get("display_name") or name.replace("_", " ").title()), + "question": str(plan.get("question") or ""), "path": os.path.relpath(match, root), + "reading": str(reading.get("reading") or ""), + "do_not_infer": str(reading.get("do_not_infer") or ""), + "disposition": str(plan.get("disposition") or "supporting"), + "not_promoted_reason": str(plan.get("not_promoted_reason") or ""), + }) + for fname, path in files: + if path in used: + continue + stem = _ORDER_PREFIX.sub("", Path(fname).stem) + result.append({ + "id": unique(stem), "title": stem.replace("_", " ").title(), + "question": "", "path": os.path.relpath(path, root), "reading": "", + "do_not_infer": "No agent-authored interpretation was saved for this figure.", + "disposition": "audit", "not_promoted_reason": "Unlinked exploratory artifact", + }) + return result[:30] diff --git a/evalrx/reporting/stage_views.py b/evalrx/reporting/stage_views.py new file mode 100644 index 00000000..0000e97f --- /dev/null +++ b/evalrx/reporting/stage_views.py @@ -0,0 +1,383 @@ +"""Per-stage views of a run: the stage rail and the bounded ``stage_detail`` +contract (:class:`evalrx.contract.stage_detail.StageDetail`) the UI renders. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, Iterable, Mapping, Sequence + +from evalrx.reporting.plain_labels import PLAIN_LABELS, _plain_label, _plain_mapping, _stat_label +from evalrx.reporting.stage_examples import ( + _attach_example_media, + _m4_examples, + _m5_examples, + _operation_examples, + _repair_operation_previews, +) +from evalrx.reporting.stage_figures import _m2_figures + + +def _stages(raw: Mapping[str, Any], m5_detail: Mapping[str, Any] | None = None) -> list[dict[str, Any]]: + definitions = [ + ("M1", "Check behavior", "See what the model does differently when it succeeds or fails", raw.get("m1"), "results"), + ("M2", "Find patterns", "Look for behaviors that reliably appear alongside errors", raw.get("m2"), "stats"), + ("M3", "Suggest causes", "Turn the strongest patterns into ideas that can be tested", raw.get("m3"), "hypotheses"), + ("M4", "Test on new cases", "Check those ideas on evidence not used to create them", raw.get("m4"), "results"), + ("M5", "Try repairs", "Compare possible fixes with the unchanged model", raw.get("m5_fix"), "selection"), + ] + result = [] + for code, title, purpose, payload, evidence_key in definitions: + stage = dict(payload or {}) + evidence = stage.get(evidence_key) or [] + ran = bool(stage.get("ran")) if "ran" in stage else bool(evidence or stage.get("duration")) + status = "completed" if ran else "not-run" + if code == "M3" and stage.get("error"): + status = "failed" + if code == "M5" and m5_detail and m5_detail.get("skipped"): + status = "skipped" + if code == "M5" and ran: + status = "improved" if stage.get("fixed") else "no-improvement" + result.append({ + "id": code.lower(), "code": code, "title": title, "purpose": purpose, + "status": status, "evidence_count": len(evidence) if isinstance(evidence, list) else 1, + }) + return result + + +def _stage_detail( + raw: Mapping[str, Any], root: Path, cases: list[dict[str, Any]], events: Sequence[Mapping[str, Any]] +) -> dict[str, Any]: + """Compile the mature stage-specific views into a bounded web contract. + + The shape is :class:`evalrx.contract.stage_detail.StageDetail`. It preserves + the old workbench's load-bearing distinctions: M2 is descriptive, M3 is + proposal-only, M4 owns held-out verdicts, and M5 compares every + intervention against the unchanged baseline. + """ + logs_dir = Path(raw.get("logs_dir") or root) + m2 = dict(raw.get("m2") or {}) + explore = dict(m2.get("explore") or {}) + # M3 starts from M2's evidence, so both stages read the same figures and stats. + figures = _m2_figures(raw, m2, explore, logs_dir, root) + stats = [_display_stat(item) for item in m2.get("stats") or [] if isinstance(item, Mapping)] + return { + "m1": _m1_detail(dict(raw.get("m1") or {}), cases, events), + "m2": _m2_detail(m2, explore, figures, stats, (raw.get("agents") or {}).get("explore")), + "m3": _m3_detail(raw, explore, figures, stats), + "m4": _m4_detail(dict(raw.get("m4") or {}), cases, events), + "m5": _m5_detail(raw, cases, events), + } + + +def _m1_detail( + m1: Mapping[str, Any], cases: list[dict[str, Any]], events: Sequence[Mapping[str, Any]] +) -> dict[str, Any]: + probes: list[dict[str, Any]] = [] + for result in m1.get("results") or []: + if not isinstance(result, dict): + continue + rows = list(result.get("per_case") or []) + probes.append({ + "id": str(result.get("name") or "probe"), + # The plain question when the label table has one; otherwise the + # glossary's name ("Self-Repair on Re-ask"), never a Title-Cased id. + "title": (PLAIN_LABELS.get(str(result.get("name") or "")) + or str(result.get("display_name") or "") + or _plain_label(result.get("name") or "Probe")), + # The glossary's own name for the check ("Self-Repair on Re-ask"), + # as opposed to `title`, which is the plain question when one exists. + "display_name": str(result.get("display_name") or ""), + "raw_name": str(result.get("name") or ""), + "question": str(result.get("question") or ""), + "description": str(result.get("description") or ""), + # None when the analyzer reported no case count at all (a batch-level + # check such as self_consistency): "unknown" is not "zero". + "n_cases": result.get("n") if result.get("n") is not None else (len(rows) or None), + "metrics": list(result.get("headline") or []), + "finding_summary": _plain_mapping(_compact_mapping(result.get("findings"))), + "raw_finding_summary": _compact_mapping(result.get("findings")), + "sample_rows": rows[:12], + "n_sample_rows": len(rows), + }) + # Examples are a first-class, bounded evidence type. They are deliberately + # derived from recorded case I/O and per-case measurements, never written + # by the report agent. A single case makes a measurement legible; it does + # not establish the stage conclusion (the UI states that boundary too). + logged_examples = [ + item for event in events if event.get("event") == "probe" + for item in (event.get("examples") or []) if isinstance(item, Mapping) + ] + examples = [dict(item) for item in logged_examples[:2]] + calls, n_calls = _m1_calls(events) + return { + "duration": m1.get("duration"), "probes": probes, + "n_probes": len(probes), "n_measured": max((int(p.get("n_cases") or 0) for p in probes), default=0), + "examples": _attach_example_media(examples, cases), + # A trajectory is the only source allowed to say that an agent actually + # used an intermediate operation (zoom, crop, search, ...). Candidate + # specs are kept separately (M5's operation previews) because a + # proposed operation is not an executed one. + "operations": _operation_examples(cases), + # What each probe actually asked the model and what came back, + # grouped by analyzer: the audit trail behind the numbers above. + "calls": calls, "n_calls": n_calls, + } + + +def _m2_detail( + m2: Mapping[str, Any], explore: Mapping[str, Any], + figures: list[dict[str, Any]], stats: list[dict[str, Any]], + agent: Mapping[str, Any] | None, +) -> dict[str, Any]: + takeaways = [ + {key: item.get(key) for key in ( + "plain_title", "title", "analysis", "caveat", "chart_names", "table_names", + )} + for item in explore.get("takeaways") or [] if isinstance(item, dict) + ] + return { + "mode": "descriptive", "conclusion": m2.get("conclusion") or "", + "narrative": m2.get("narrative") or "", "stats": stats, + "takeaways": takeaways, "figures": figures, + "observations": list(explore.get("observations") or []), + "caveats": list(explore.get("caveats") or []), + "candidate_signals": list(explore.get("candidate_signals") or []), + "recommended_tests": list(explore.get("recommended_confirmatory_tests") or []), + "agent": _explore_agent(agent), + } + + +#: The explore agent's CLI trajectory runs to megabytes on a long session; +#: the report carries its head, the run directory the whole file. +_TRANSCRIPT_CAP = 200_000 + + +def _explore_agent(agent: Mapping[str, Any] | None) -> dict[str, Any] | None: + """The analysis the explore agent wrote and ran, or None if it left nothing.""" + if not agent: + return None + transcript = str(agent.get("raw_streams") or agent.get("raw_output") or "") + return { + "code": agent.get("code"), "stdout": agent.get("stdout"), "stderr": agent.get("stderr"), + "transcript": transcript[:_TRANSCRIPT_CAP] or None, + "transcript_truncated": len(transcript) > _TRANSCRIPT_CAP, + "audit": agent.get("audit"), + } + + +def _m3_detail( + raw: Mapping[str, Any], explore: Mapping[str, Any], + figures: list[dict[str, Any]], stats: list[dict[str, Any]], +) -> dict[str, Any]: + m3 = dict(raw.get("m3") or {}) + hypotheses = list(m3.get("hypotheses") or explore.get("hypotheses") or []) + return { + "mode": "proposal", "hypotheses": hypotheses, "error": m3.get("error"), + "candidate_signals": list(explore.get("candidate_signals") or []), + "recommended_tests": list(explore.get("recommended_confirmatory_tests") or []), + "evidence_figures": figures[:3], "evidence_stats": stats[:6], + } + + +def _m4_detail( + m4: Mapping[str, Any], cases: list[dict[str, Any]], events: Sequence[Mapping[str, Any]], +) -> dict[str, Any]: + results = list(m4.get("results") or []) + event = dict(m4.get("event") or {}) + logged: Mapping[str, Any] = next(( + item for item in reversed(events) + if item.get("event") == "surgery" and item.get("module") == "m4" + ), {}) + return { + "ran": bool(m4.get("ran") or results), "mode": "confirmatory", + "results": results, "event": event, + "examples": _attach_example_media(_m4_examples(results, {**event, **logged}, cases), cases), + } + + +def _m5_detail( + raw: Mapping[str, Any], cases: list[dict[str, Any]], events: Sequence[Mapping[str, Any]] +) -> dict[str, Any]: + m5 = dict(raw.get("m5_fix") or {}) + # extract_run_data may see an older sibling log when an example contains + # multiple attempts. The event stream is trace-filtered and is the source + # of truth for the run currently being rendered. + fix_event: Mapping[str, Any] = next((event for event in reversed(events) if event.get("event") == "fix"), {}) + skipped_event: Mapping[str, Any] = next(( + event for event in reversed(events) + if event.get("event") == "stage_skipped" and str(event.get("stage")) == "M5" + ), {}) + if fix_event: + attempted = [item for item in fix_event.get("attempted") or [] if isinstance(item, Mapping)] + # The fix event records `best` as the whole winning candidate; the + # attempt of the same name carries what it scored on the confirm pool. + winner = found if isinstance(found := fix_event.get("best"), Mapping) else {} + best_name = str(winner.get("name") or "") + best = next((item for item in attempted if item.get("name") == best_name), {}) if best_name else {} + m5.update({ + "ran": True, "fixed": bool(fix_event.get("fixed")), "selection": attempted, + "best": best or dict(winner), "recommendation": fix_event.get("recommendation"), + }) + if skipped_event: + m5.update({ + "ran": False, + "skipped": True, + "skip_reason": skipped_event.get("reason_code") or "not_attempted", + "skip_detail": skipped_event.get("detail") or "", + }) + candidates = [_repair_candidate(item) for item in m5.get("selection") or [] if isinstance(item, dict)] + confirmation = _repair_candidate(m5.get("best") or {}) + if confirmation.get("name"): + existing = next((i for i, item in enumerate(candidates) if item.get("name") == confirmation["name"]), None) + if existing is None: + candidates.append(confirmation) + else: + candidates[existing] = {**candidates[existing], **confirmation} + return { + "ran": bool(m5.get("ran")), "fixed": bool(m5.get("fixed")), + "skipped": bool(m5.get("skipped")), + "skip_reason": str(m5.get("skip_reason") or ""), + "skip_detail": str(m5.get("skip_detail") or ""), + "candidates": candidates, "confirmation": confirmation, + "best": _repair_candidate(m5.get("best") or {}), + # The FixAgent's own verdict on the run — action + the sentence that + # justifies it ("underpowered: only 4 failing cases…"). This is the + # line the health card's promotion gate prints. + "recommendation": (dict(m5["recommendation"]) + if isinstance(m5.get("recommendation"), Mapping) else None), + "examples": _m5_examples(candidates, cases, list((raw.get("m1") or {}).get("results") or [])), + "operation_previews": _repair_operation_previews(candidates, cases), + "surgeries": list((raw.get("m5_surgery") or {}).get("surgeries") or []), + "prompt_template": str(m5.get("prompt_template") or ""), + } + + +def _display_stat(value: Mapping[str, Any]) -> dict[str, Any]: + """Keep statistical evidence machine-auditable but primary labels human.""" + config = found if isinstance(found := value.get("config"), Mapping) else {} + signal = str(config.get("signal") or value.get("signal") or value.get("tool") or "") + details = found if isinstance(found := value.get("details"), Mapping) else {} + # A PAIRED tool compares two strategies and carries no `signal`, so `signal` + # falls through to the tool name and every such row was labelled with the + # same words ("Mcnemar Evalue"). Three identically-labelled bars is not a + # chart. The pair it actually compared is right there in the config, and it + # is the only thing that tells the rows apart. + groups = [str(name) for name in (config.get("strategies") or []) if name] + label = _stat_label(config, signal, value.get("tool")) + return { + "label": label, "raw_signal": signal, "groups": groups, + "effect": value.get("effect"), "ci": value.get("ci"), + "reject": bool(value.get("reject")), "underpowered": bool(value.get("underpowered")), + "summary": value.get("summary") or "", "p_value": value.get("p_value"), + "tool": value.get("tool"), "e_value": value.get("e_value"), + "fail_rate_signal": details.get("fail_rate_signal"), + "fail_rate_control": details.get("fail_rate_control"), + } + + +def _compact_mapping(value: Any, *, limit: int = 18) -> dict[str, Any]: + """Retain readable aggregate findings, excluding unbounded per-case maps.""" + if not isinstance(value, Mapping): + return {} + compact: dict[str, Any] = {} + for key, item in value.items(): + if key in {"per_case", "per_case_values", "case_values", "samples", "caveat"}: + continue + if isinstance(item, (str, int, float, bool)) or item is None: + compact[str(key)] = item + elif isinstance(item, list) and len(item) <= 12: + compact[str(key)] = item + elif isinstance(item, Mapping) and len(item) <= 12: + nested = {str(k): v for k, v in item.items() if isinstance(v, (str, int, float, bool)) or v is None} + if nested: + compact[str(key)] = nested + if len(compact) >= limit: + break + return compact + + +def _repair_headline(value: Mapping[str, Any]) -> str: + """The candidate's own sentence, or the host's for a candidate it authored. + + Looking `visual_grounding` up in the fix agent's own table is not a + consumer guessing at a slug -- it is the package that named the candidate + saying what it does. Runs recorded before `headline` existed become + readable this way; a judge-invented name the host never heard of still + resolves to "" and renders blank. + """ + headline = " ".join(str(value.get("headline") or "").split()) + if headline: + return headline[:300] + try: + from evalrx.eval_agent.stages.fix.descriptions import BUILTIN_DESCRIPTIONS + except Exception: + return "" + return BUILTIN_DESCRIPTIONS.get(str(value.get("name") or ""), "") + + +def _repair_candidate(value: Any) -> dict[str, Any]: + if not isinstance(value, Mapping): + return {} + fixed_cases = list(value.get("fixed_cases") or []) + broken_cases = list(value.get("broken_cases") or []) + payload = found if isinstance(found := value.get("payload"), Mapping) else {} + return { + "tier": value.get("tier"), "name": value.get("name"), "kind": value.get("kind"), + # `ref` and `headline` are what a reader sees; `name` is only the join + # key. Both are carried here so the stage view shows the same + # identifier and the same sentence as the contract-backed views. + "ref": value.get("ref") or "", "headline": _repair_headline(value), + "source": value.get("source"), "verdict": value.get("verdict"), + "n_pairs": value.get("n_pairs"), "n_baseline_correct": value.get("n_baseline_correct"), + "n_candidate_correct": value.get("n_candidate_correct"), + "n_fixed": value.get("n_fixed", len(fixed_cases)), "n_broken": value.get("n_broken", len(broken_cases)), + "effect": value.get("effect"), "e_value": value.get("e_value"), + "e_threshold": value.get("e_threshold"), + "coverage": value.get("coverage"), "reject": value.get("reject"), "fixed": value.get("fixed"), + "n_model_independent": value.get("n_model_independent"), + "n_unstable": value.get("n_unstable"), + "summary": value.get("summary"), "payload": dict(payload), + "fixed_cases": fixed_cases[:20], "broken_cases": broken_cases[:20], + } + + +_CALL_TEXT_CAP = 3000 + + +_CALLS_PER_ANALYZER = 120 + + +def _call_text(value: Any) -> str: + """The prompt or the reply as text, cut so 500 calls stay a sane payload.""" + if isinstance(value, Mapping): + value = value.get("prompt") if "prompt" in value else json.dumps(value, ensure_ascii=False) + text = "" if value is None else str(value) + return text if len(text) <= _CALL_TEXT_CAP else text[:_CALL_TEXT_CAP] + f"… [+{len(text) - _CALL_TEXT_CAP} chars]" + + +def _m1_calls(events: Iterable[Mapping[str, Any]]) -> tuple[dict[str, list[dict[str, Any]]], int]: + """M1's model calls grouped by analyzer, oldest first, capped per analyzer.""" + grouped: dict[str, list[dict[str, Any]]] = {} + total = 0 + for event in events: + if str(event.get("event") or "") != "model_call" or str(event.get("stage") or "") != "M1": + continue + total += 1 + analyzer = str(event.get("analyzer") or event.get("role") or "model") + bucket = grouped.setdefault(analyzer, []) + if len(bucket) >= _CALLS_PER_ANALYZER: + continue + batch = event.get("batch_case_ids") + bucket.append({ + "seq": event.get("event_seq"), "cycle": event.get("cycle"), + "method": event.get("method") or event.get("operation") or "", + "case_id": event.get("case_id"), + "batch_case_ids": [str(item) for item in batch] if isinstance(batch, list) else [], + "duration_sec": event.get("duration_sec"), + "prompt": _call_text(event.get("inputs")), + "output": _call_text(event.get("output")), + "error": str(event.get("error")) if event.get("error") else None, + }) + return grouped, total diff --git a/evalrx/reporting/stages.py b/evalrx/reporting/stages.py deleted file mode 100644 index 301707ef..00000000 --- a/evalrx/reporting/stages.py +++ /dev/null @@ -1,58 +0,0 @@ -"""Stage semantics for EvalRX diagnostic reports.""" - -from __future__ import annotations - -from dataclasses import dataclass - - -@dataclass(frozen=True) -class StageSpec: - id: str - name: str - question: str - artifacts: str - dashboard_role: str - - -STAGE_SPECS: tuple[StageSpec, ...] = ( - StageSpec( - id="M1", - name="Measurement", - question="What per-case signals did the evaluators/analyzers extract?", - artifacts="Frozen per-case feature matrix, analyzer outputs, attention/probe artifacts.", - dashboard_role="Problem Setting: defines the dataset and available signals.", - ), - StageSpec( - id="M2", - name="Exploratory analysis", - question="Which signals are worth investigating, and how do they relate to the outcome?", - artifacts="Effect sizes, relationship charts/tables — descriptive, no validity verdict.", - dashboard_role="Analysis: method, evidence, chart, and takeaway (no supported/not-supported " - "claim; a confirm phase with e-BH/FDR is a separate, currently out-of-scope step).", - ), - StageSpec( - id="M3", - name="Hypothesis generation", - question="What falsifiable failure mechanisms explain the confirmed signals?", - artifacts="Hypotheses, failure modes, cited M2 charts/observations.", - dashboard_role="Hypotheses: candidate mechanisms linked back to evidence.", - ), - StageSpec( - id="M4", - name="Hypothesis validation", - question="Does corrected statistical evidence and protocol consistency support the hypothesis?", - artifacts="Held-out verdicts, adjudication records, and evidence grades.", - dashboard_role="Validate hypotheses: the gate before intervention or repair.", - ), - StageSpec( - id="M5", - name="Intervention & repair", - question="Does a targeted intervention repair failures without unacceptable regressions?", - artifacts="Intervention records, repair candidates, paired outcome comparisons.", - dashboard_role="Intervene & repair: causal experiments and the repair sweep after validation.", - ), -) - - -def stage_specs_as_dicts() -> list[dict[str, str]]: - return [spec.__dict__.copy() for spec in STAGE_SPECS] diff --git a/evalrx/reporting/static_export.py b/evalrx/reporting/static_export.py index 7d8353e8..e9900da0 100644 --- a/evalrx/reporting/static_export.py +++ b/evalrx/reporting/static_export.py @@ -17,6 +17,7 @@ report_is_current, ) from evalrx.reporting.server import _resolve_media, _resolve_report_root +from evalrx.term_links import hyperlink EmbedMedia = Literal["representative", "all", "none"] @@ -25,7 +26,6 @@ def export_static_report( run_dir: str | Path, *, out_path: str | Path | None = None, - example_dir: str | Path | None = None, embed_media: EmbedMedia = "representative", model: object | None = None, audio_bitrate: str | None = "48k", @@ -38,7 +38,7 @@ def export_static_report( # that drove the run). One resolver for both entry points. root = _resolve_report_root(Path(run_dir).resolve()) if model is not None or not report_is_current(root): - publish_report(root, example_dir=example_dir, model=model) + publish_report(root, model=model) data, layout = load_published_report(root) _embed_media(root, data, mode=embed_media, audio_bitrate=audio_bitrate) _embed_stage_figures(root, data) @@ -55,6 +55,30 @@ def export_static_report( return destination +def write_report(out_dir: Path, *, open_report: bool = False) -> Path | None: + """Write ``out_dir/report.html`` and open it when asked. + + An installed package carries the renderer; a source checkout that has not + built it gets a note instead of a failed run, since the outputs are intact. + """ + try: + written = export_static_report(out_dir, out_path=out_dir / "report.html") + except FileNotFoundError as exc: + print(f"report.html not written: {exc}") + return None + if open_report: + open_in_browser(written) + return written + + +def open_in_browser(report: Path) -> None: + """Open a written report. It is self-contained, so no server is needed.""" + import webbrowser + + print(f"Opening report: {hyperlink(report.as_uri())}") + webbrowser.open(report.as_uri()) + + #: Lossless audio the runs record (16 kHz mono WAV, ~380 KB per 10 s clip). #: Inlined as-is, an audio run's every-case export lands well past GitHub's #: 100 MB per-file limit (mmau/demo192: 256 clips, 97 MB, ~130 MB in base64); diff --git a/evalrx/reporting/web/eslint.config.js b/evalrx/reporting/web/eslint.config.js index 401fbb1b..9f2ff170 100644 --- a/evalrx/reporting/web/eslint.config.js +++ b/evalrx/reporting/web/eslint.config.js @@ -17,7 +17,7 @@ export default defineConfig([ // Compiler, so the compiler-specific rules in `recommended` do not apply. "react-hooks/rules-of-hooks": "error", "react-hooks/exhaustive-deps": "error", - "@typescript-eslint/no-explicit-any": "warn", + "@typescript-eslint/no-explicit-any": "error", }, }, ]); diff --git a/evalrx/reporting/web/fixtures/chartqa-gemini.json b/evalrx/reporting/web/fixtures/chartqa-gemini.json index 340cf01b..31549fbf 100644 --- a/evalrx/reporting/web/fixtures/chartqa-gemini.json +++ b/evalrx/reporting/web/fixtures/chartqa-gemini.json @@ -1 +1 @@ -{"data": {"version": 19, "trace_id": "a9822626-af4d-43ea-b5cc-486232b73048", "source_event_seq": 196, "generated_at": "FIXED", "setting": {"model": "gemini-3.6-flash", "dataset": "ChartQA (Chart Visual Reasoning)", "question": "Evaluate a vision-language model (gemini-3.6-flash, spec gemini-3.6-flash = api:gemini-3.6-flash) on the human-authored ChartQA test split. Questions require reading chart marks and labels, comparing quantities, and performing arithmetic or logical reasoning. Diagnose whether errors reflect answer extraction, unstable visual evidence, or failure to verify a candidate answer.", "protocol": "Evaluate a vision-language model (gemini-3.6-flash, spec gemini-3.6-flash = api:gemini-3.6-flash) on the human-authored ChartQA test split. Questions require reading chart marks and labels, comparing quantities, and performing arithmetic or logical reasoning. Diagnose whether errors reflect answer extraction, unstable visual evidence, or failure to verify a candidate answer.", "diagnosed_by": "", "hero_image": "", "n_cases": 16, "partitions": [{"split": "explore", "code": "E", "label": "Explore", "n": 16, "role": "M1-M3 mined patterns and hypotheses here. Anything measured on these cases is a lead, not a verdict.", "inferred": false}, {"split": "confirm", "code": "H/C", "label": "Held-out / Confirm", "n": 16, "role": "Withheld from M1-M3. M4 adjudicated the hypotheses here and the repair was scored on these same cases: one withheld pool serving as both the held-out and the confirm set.", "inferred": false}]}, "summary": {"headline": "A possible explanation was checked on new cases.", "answer": "This report separates observed patterns from independently checked results.", "confidence": "Independently checked", "stopped_by": "criteria_met"}, "metrics": [{"id": "evaluated", "label": "Cases evaluated", "value": 16}, {"id": "failed", "label": "Initial failures", "value": 5}, {"id": "verified", "label": "Mechanisms checked", "value": 3}, {"id": "fixed", "label": "Cases repaired", "value": 3}], "stages": [{"id": "m1", "code": "M1", "title": "Check behavior", "purpose": "See what the model does differently when it succeeds or fails", "status": "completed", "evidence_count": 3}, {"id": "m2", "code": "M2", "title": "Find patterns", "purpose": "Look for behaviors that reliably appear alongside errors", "status": "completed", "evidence_count": 20}, {"id": "m3", "code": "M3", "title": "Suggest causes", "purpose": "Turn the strongest patterns into ideas that can be tested", "status": "completed", "evidence_count": 3}, {"id": "m4", "code": "M4", "title": "Test on new cases", "purpose": "Check those ideas on evidence not used to create them", "status": "completed", "evidence_count": 3}, {"id": "m5", "code": "M5", "title": "Try repairs", "purpose": "Compare possible fixes with the unchanged model", "status": "no-improvement", "evidence_count": 15}], "findings": [{"id": "finding-1", "title": "Verification sample disagreement", "summary": "Flags cases where repeated samples failed to reach unanimous agreement, indicating visual ambiguity or reasoning instability.", "why_it_matters": "", "evidence_level": "Independently checked", "limitation": "Interpret alongside the independent-check details."}, {"id": "finding-2", "title": "Verbose extraction output", "summary": "Flags cases where the model output exceeds 8 characters, indicative of rambling explanations rather than extracted chart values.", "why_it_matters": "", "evidence_level": "Independently checked", "limitation": "Interpret alongside the independent-check details."}], "charts": [{"id": "outcomes", "kind": "donut", "title": "Evaluation outcomes", "series": [{"label": "Pass", "value": 11}, {"label": "Fail", "value": 5}]}, {"id": "effects", "kind": "bar", "title": "Which behaviors appear most connected to errors?", "subtitle": "A larger bar means a stronger observed pattern. It does not prove the behavior caused the error.", "series": [{"label": "Can repeated attempts ever find the right answer? — N unique", "raw_label": "coverage_verification_gap.n_unique", "value": 0.9166666666666666, "highlight": true}, {"label": "Does the model contradict itself? — Number of answer sentences checked", "raw_label": "selfcheck_consistency.n_sentences", "value": 0.5833333333333334, "highlight": true}, {"label": "Did the model give a usable answer? — Length of the model answer", "raw_label": "answer_extraction_audit.output_chars", "value": 0.4603174603174603, "highlight": true}, {"label": "Did the model give a usable answer? — Answered yes", "raw_label": "answer_extraction_audit.answered_yes", "value": -0.3333333333333333, "highlight": true}, {"label": "Did the model give a usable answer? — Gold yes", "raw_label": "answer_extraction_audit.gold_yes", "value": -0.3333333333333333, "highlight": true}, {"label": "Does the model contradict itself? — Selfcheck inconsistency", "raw_label": "selfcheck_consistency.selfcheck_inconsistency", "value": 0.5, "highlight": false}, {"label": "Does the model contradict itself? — Selfcheck worst sentence", "raw_label": "selfcheck_consistency.selfcheck_worst_sentence", "value": 0.5, "highlight": false}, {"label": "Can repeated attempts ever find the right answer? — N unique", "raw_label": "coverage_verification_gap.n_unique", "value": 0.3667, "highlight": false}]}], "repairs": {}, "stage_detail": {"m1": {"duration": 91.815, "probes": [{"id": "answer_extraction_audit", "title": "Did the model give a usable answer?", "display_name": "Answer Extraction Audit", "raw_name": "answer_extraction_audit", "question": "Did the model actually answer wrong, or did our parser fail to extract its response?", "description": "Checks whether formatting quirks (e.g. missing tags, preamble chatter) prevented the parser from extracting the answer even when the model understood the problem.", "n_cases": 16, "metrics": [{"label": "Extraction Failure Rate on Errors", "value": "60.0%"}, {"label": "Missing Format Tag Rate", "value": "100.0%"}], "finding_summary": {"N cases": 16, "N gradable": 16, "N labelled fail": 5, "N extraction suspect": 3, "Suspect rate": 0.6, "N reasked": 0, "N reask confirmed": null, "N extraction point miss": 0, "Missing tag rate": 1.0, "Caveat": "suspect_rate is the fraction of FAIL cases whose gold answer sits in the ANSWER REGION of the output (tail window or a tagged/boxed span) — HARNESS failures wearing a model-failure label. gold_in_output is the loose upper bound and over-counts: it fires on a gold that only appears as an intermediate quantity, so never read it as the suspect rate. Above ~5% the labels feeding M2 are contaminated and every other probe's correlations should be re-read after fixing extraction (or after dropping extraction_suspect==1 cases). This probe is OBSERVATIONAL by default: it re-reads stored outputs and introduces no new sampling. With reask=True the reask_* columns are interventional and must be re-run for held-out confirmation. On yes/no (true/false) tasks answered_yes and gold_yes are the answer's and the gold's DIRECTION, two separate marginals (not re-grades): a directional hypothesis is tested on them, e.g. answered_yes HIGHER on failing cases."}, "raw_finding_summary": {"n_cases": 16, "n_gradable": 16, "n_labelled_fail": 5, "n_extraction_suspect": 3, "suspect_rate": 0.6, "n_reasked": 0, "n_reask_confirmed": null, "n_extraction_point_miss": 0, "missing_tag_rate": 1.0, "_caveat": "suspect_rate is the fraction of FAIL cases whose gold answer sits in the ANSWER REGION of the output (tail window or a tagged/boxed span) — HARNESS failures wearing a model-failure label. gold_in_output is the loose upper bound and over-counts: it fires on a gold that only appears as an intermediate quantity, so never read it as the suspect rate. Above ~5% the labels feeding M2 are contaminated and every other probe's correlations should be re-read after fixing extraction (or after dropping extraction_suspect==1 cases). This probe is OBSERVATIONAL by default: it re-reads stored outputs and introduces no new sampling. With reask=True the reask_* columns are interventional and must be re-run for held-out confirmation. On yes/no (true/false) tasks answered_yes and gold_yes are the answer's and the gold's DIRECTION, two separate marginals (not re-grades): a directional hypothesis is tested on them, e.g. answered_yes HIGHER on failing cases."}, "sample_rows": [{"sample_id": "chartqa-human-445", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 4, "labelled_fail": 0, "strict_match": 1, "gold_in_output": 1, "gold_in_answer_region": 1, "extracted_answer": "U.S.", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 0}, {"sample_id": "chartqa-human-86", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 19, "labelled_fail": 1, "strict_match": 1, "gold_in_output": 1, "gold_in_answer_region": 1, "extracted_answer": "77 and 77 (in 2006)", "extraction_suspect": 1, "extraction_point_miss": 0, "label_disagrees": 1}, {"sample_id": "chartqa-human-45", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 4, "labelled_fail": 0, "strict_match": 0, "gold_in_output": 0, "gold_in_answer_region": 0, "extracted_answer": "28.7", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 1}, {"sample_id": "chartqa-human-1122", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 6, "labelled_fail": 0, "strict_match": 1, "gold_in_output": 1, "gold_in_answer_region": 1, "extracted_answer": "Russia", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 0}, {"sample_id": "chartqa-human-740", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 5, "labelled_fail": 0, "strict_match": 1, "gold_in_output": 1, "gold_in_answer_region": 1, "extracted_answer": "Texas", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 0}, {"sample_id": "chartqa-human-89", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 5, "labelled_fail": 1, "strict_match": 0, "gold_in_output": 0, "gold_in_answer_region": 0, "extracted_answer": "20:13", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 0}, {"sample_id": "chartqa-human-406", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 3, "labelled_fail": 0, "strict_match": 1, "gold_in_output": 1, "gold_in_answer_region": 1, "extracted_answer": "Yes", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 0, "gold_yes": 1, "answered_yes": 1}, {"sample_id": "chartqa-human-1195", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 26, "labelled_fail": 1, "strict_match": 1, "gold_in_output": 1, "gold_in_answer_region": 1, "extracted_answer": "4.9 billion British pounds", "extraction_suspect": 1, "extraction_point_miss": 0, "label_disagrees": 1}, {"sample_id": "chartqa-human-1032", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 7, "labelled_fail": 0, "strict_match": 1, "gold_in_output": 1, "gold_in_answer_region": 1, "extracted_answer": "Hungary", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 0}, {"sample_id": "chartqa-human-325", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 10, "labelled_fail": 0, "strict_match": 1, "gold_in_output": 1, "gold_in_answer_region": 1, "extracted_answer": "$14,153.35", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 0}, {"sample_id": "chartqa-human-365", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 7, "labelled_fail": 1, "strict_match": 0, "gold_in_output": 0, "gold_in_answer_region": 0, "extracted_answer": "Magenta", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 0}, {"sample_id": "chartqa-human-532", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 3, "labelled_fail": 0, "strict_match": 1, "gold_in_output": 1, "gold_in_answer_region": 1, "extracted_answer": "4.2", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 0}], "n_sample_rows": 16}, {"id": "selfcheck_consistency", "title": "Does the model contradict itself?", "display_name": "Self-Contradiction Detection", "raw_name": "selfcheck_consistency", "question": "Does the model contradict its own claims across repeat samplings?", "description": "Probes whether the model generates assertions in one sample that directly contradict its claims in another sample.", "n_cases": 16, "metrics": [{"label": "Self-Contradiction Index", "value": "0.402"}], "finding_summary": {"N cases": 16, "N samples": 4, "Degenerate sampling": false, "Gen kwargs": {"temperature": 1.0}, "Mean inconsistency": 0.4018, "Caveat": "Unigram-containment proxy for SelfCheckGPT (no NLI model): paraphrases inflate the score, verbatim repetition of a wrong fact deflates it. Requires stochastic sampling — with temperature 0 the resamples repeat one greedy generation and the column degenerates to baseline-vs-greedy disagreement (degenerate_sampling flags this). selfcheck_inconsistency / selfcheck_worst_sentence are numeric M2 columns; treat them as signals to correlate with the outcome label, never as a hallucination verdict."}, "raw_finding_summary": {"n_cases": 16, "n_samples": 4, "degenerate_sampling": false, "gen_kwargs": {"temperature": 1.0}, "mean_inconsistency": 0.4018, "_caveat": "Unigram-containment proxy for SelfCheckGPT (no NLI model): paraphrases inflate the score, verbatim repetition of a wrong fact deflates it. Requires stochastic sampling — with temperature 0 the resamples repeat one greedy generation and the column degenerates to baseline-vs-greedy disagreement (degenerate_sampling flags this). selfcheck_inconsistency / selfcheck_worst_sentence are numeric M2 columns; treat them as signals to correlate with the outcome label, never as a hallucination verdict."}, "sample_rows": [{"sample_id": "chartqa-human-445", "baseline_from": "observed", "n_sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}, {"sample_id": "chartqa-human-86", "baseline_from": "observed", "n_sentences": 1, "selfcheck_inconsistency": 0.75, "selfcheck_worst_sentence": 0.75, "worst_sentence_text": "77 and 77 (in 2006)"}, {"sample_id": "chartqa-human-45", "baseline_from": "observed", "n_sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}, {"sample_id": "chartqa-human-1122", "baseline_from": "observed", "n_sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}, {"sample_id": "chartqa-human-740", "baseline_from": "observed", "n_sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}, {"sample_id": "chartqa-human-89", "baseline_from": "observed", "n_sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}, {"sample_id": "chartqa-human-406", "baseline_from": "observed", "n_sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}, {"sample_id": "chartqa-human-1195", "baseline_from": "observed", "n_sentences": 1, "selfcheck_inconsistency": 0.0, "selfcheck_worst_sentence": 0.0, "worst_sentence_text": "4.9 billion British pounds"}, {"sample_id": "chartqa-human-1032", "baseline_from": "observed", "n_sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}, {"sample_id": "chartqa-human-325", "baseline_from": "observed", "n_sentences": 1, "selfcheck_inconsistency": 0.0, "selfcheck_worst_sentence": 0.0, "worst_sentence_text": "$14,153.35"}, {"sample_id": "chartqa-human-365", "baseline_from": "observed", "n_sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}, {"sample_id": "chartqa-human-532", "baseline_from": "observed", "n_sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}], "n_sample_rows": 16}, {"id": "coverage_verification_gap", "title": "Can repeated attempts ever find the right answer?", "display_name": "Pass@k Knowledge Blindspot (Coverage)", "raw_name": "coverage_verification_gap", "question": "Over 5 repeat attempts, does the model ever produce the right answer even once?", "description": "Samples temperature completions k=5 times. If pass@5 is 0%, the capability is completely missing from weights; if pass@5 is high but greedy fails, the model suffers from search/ranking misalignment.", "n_cases": 16, "metrics": [{"label": "Persistent Failure Rate (0/5 correct)", "value": "12.5%"}, {"label": "Pass@5 Coverage Rate", "value": "87.5%"}], "finding_summary": {"N cases": 16, "N scored": 16, "K": 5, "Mean pass at k": 0.875, "Mean majority correct": 0.875, "Coverage gap rate": 0.0, "Mean verify correct": null, "No coverage rate": 0.125, "Degenerate sampling": false, "Caveat": "coverage_gap = 'the answer was in the pool, the vote missed it' ⇒ a selection defect, fixable at L1/L2 with a verifier or reranker. no_coverage_rate = 'never produced once in k' ⇒ a capability defect no scaffold reaches; do not let a headline pass@k hide which of the two dominates. REQUIRES sampling: degenerate_sampling=true means every sample was identical (temperature 0 or a deterministic backend) and the gap is structurally zero, not measured. pass_at_k here uses the unbiased estimator over exactly k draws, so with k small its variance is large per case — read the batch rate. INTERVENTIONAL: held-out confirmation must re-sample."}, "raw_finding_summary": {"n_cases": 16, "n_scored": 16, "k": 5, "mean_pass_at_k": 0.875, "mean_majority_correct": 0.875, "coverage_gap_rate": 0.0, "mean_verify_correct": null, "no_coverage_rate": 0.125, "degenerate_sampling": false, "_caveat": "coverage_gap = 'the answer was in the pool, the vote missed it' ⇒ a selection defect, fixable at L1/L2 with a verifier or reranker. no_coverage_rate = 'never produced once in k' ⇒ a capability defect no scaffold reaches; do not let a headline pass@k hide which of the two dominates. REQUIRES sampling: degenerate_sampling=true means every sample was identical (temperature 0 or a deterministic backend) and the gap is structurally zero, not measured. pass_at_k here uses the unbiased estimator over exactly k draws, so with k small its variance is large per case — read the batch rate. INTERVENTIONAL: held-out confirmation must re-sample."}, "sample_rows": [{"sample_id": "chartqa-human-445", "n_samples": 5, "n_graded": 5, "n_correct": 5, "n_unique": 1, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 1.0, "coverage_gap": 0, "modal_answer": "u.s"}, {"sample_id": "chartqa-human-86", "n_samples": 5, "n_graded": 5, "n_correct": 5, "n_unique": 3, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 0.4, "coverage_gap": 0, "modal_answer": "77"}, {"sample_id": "chartqa-human-45", "n_samples": 5, "n_graded": 5, "n_correct": 0, "n_unique": 1, "pass_at_k": 0.0, "any_correct": 0, "majority_correct": 0, "majority_share": 1.0, "coverage_gap": 0, "modal_answer": "28.7"}, {"sample_id": "chartqa-human-1122", "n_samples": 5, "n_graded": 5, "n_correct": 5, "n_unique": 1, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 1.0, "coverage_gap": 0, "modal_answer": "russia"}, {"sample_id": "chartqa-human-740", "n_samples": 5, "n_graded": 5, "n_correct": 5, "n_unique": 1, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 1.0, "coverage_gap": 0, "modal_answer": "texas"}, {"sample_id": "chartqa-human-89", "n_samples": 5, "n_graded": 5, "n_correct": 0, "n_unique": 2, "pass_at_k": 0.0, "any_correct": 0, "majority_correct": 0, "majority_share": 0.8, "coverage_gap": 0, "modal_answer": "20:13"}, {"sample_id": "chartqa-human-406", "n_samples": 5, "n_graded": 5, "n_correct": 5, "n_unique": 1, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 1.0, "coverage_gap": 0, "modal_answer": "yes"}, {"sample_id": "chartqa-human-1195", "n_samples": 5, "n_graded": 5, "n_correct": 5, "n_unique": 1, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 1.0, "coverage_gap": 0, "modal_answer": "4.9 billion british pounds"}, {"sample_id": "chartqa-human-1032", "n_samples": 5, "n_graded": 5, "n_correct": 5, "n_unique": 1, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 1.0, "coverage_gap": 0, "modal_answer": "hungary"}, {"sample_id": "chartqa-human-325", "n_samples": 5, "n_graded": 5, "n_correct": 5, "n_unique": 1, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 1.0, "coverage_gap": 0, "modal_answer": "14153.35"}, {"sample_id": "chartqa-human-365", "n_samples": 5, "n_graded": 5, "n_correct": 4, "n_unique": 4, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 0.4, "coverage_gap": 0, "modal_answer": "pink"}, {"sample_id": "chartqa-human-532", "n_samples": 5, "n_graded": 5, "n_correct": 5, "n_unique": 1, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 1.0, "coverage_gap": 0, "modal_answer": "4.2"}], "n_sample_rows": 16}], "n_probes": 3, "n_measured": 16, "examples": [{"id": "chartqa-human-86", "kind": "case_measurement", "case_id": "chartqa-human-86", "probe_title": "Answer extraction audit", "input": "Which two values are same in the upper graph? Answer with only the short answer.", "baseline_output": "77 and 77 (in 2006)", "expected": ["77"], "outcome": "fail", "check_result": {"has output": 1, "has answer tag": 0, "output truncated": 0, "gave up": 0, "output chars": 19, "labelled fail": 1, "strict match": 1, "gold in output": 1, "gold in answer region": 1, "extracted answer": "77 and 77 (in 2006)", "extraction suspect": 1, "extraction point miss": 0, "label disagrees": 1}, "plain_reading": "This one case illustrates the recorded check. The aggregate M1 result uses all measured cases.", "evidence_scope": "one recorded case within M1", "media_ids": ["media-2"]}, {"id": "chartqa-human-89", "kind": "case_measurement", "case_id": "chartqa-human-89", "probe_title": "Selfcheck consistency", "input": "What's the ratio(A:B) of yellow bar and blue bar for Ages 18-29? Answer with only the short answer.", "baseline_output": "20:13", "expected": ["1.684722222"], "outcome": "fail", "check_result": {"baseline from": "observed", "n sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}, "plain_reading": "This one case illustrates the recorded check. The aggregate M1 result uses all measured cases.", "evidence_scope": "one recorded case within M1", "media_ids": ["media-6"]}], "operations": [], "calls": {"case_discovery": [{"seq": 1, "cycle": -1, "method": "generate", "case_id": "chartqa-human-445", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.0105, "prompt": "In which country the difference between blue and green bar is maximum? Answer with only the short answer.", "output": "U.S.", "error": null}, {"seq": 2, "cycle": -1, "method": "generate", "case_id": "chartqa-human-1142", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.0148, "prompt": "Work out the ratio of the bigger segment to the smaller one? Answer with only the short answer.", "output": "153:97", "error": null}, {"seq": 3, "cycle": -1, "method": "generate", "case_id": "chartqa-human-709", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.156, "prompt": "What is the value of the highest point? Answer with only the short answer.", "output": "19.7%", "error": null}, {"seq": 4, "cycle": -1, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.8547, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77 and 77 (in 2006)", "error": null}, {"seq": 5, "cycle": -1, "method": "generate", "case_id": "chartqa-human-1122", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.3691, "prompt": "Which category the three bars value is above 25% ? Answer with only the short answer.", "output": "Russia", "error": null}, {"seq": 6, "cycle": -1, "method": "generate", "case_id": "chartqa-human-576", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.6466, "prompt": "Which country does the green line represent? Answer with only the short answer.", "output": "Spain", "error": null}, {"seq": 7, "cycle": -1, "method": "generate", "case_id": "chartqa-human-45", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.7678, "prompt": "What's the average of last three values in green graph (round to one decimal)? Answer with only the short answer.", "output": "28.7", "error": null}, {"seq": 8, "cycle": -1, "method": "generate", "case_id": "chartqa-human-428", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.3308, "prompt": "How many countries are shown in the graph? Answer with only the short answer.", "output": "3 countries are shown in the graph.", "error": null}, {"seq": 9, "cycle": -1, "method": "generate", "case_id": "chartqa-human-698", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 2.1307, "prompt": "Which is represented by yellow color? Answer with only the short answer.", "output": "Denmark", "error": null}, {"seq": 10, "cycle": -1, "method": "generate", "case_id": "chartqa-human-228", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.6068, "prompt": "Which country has longest bar? Answer with only the short answer.", "output": "Lithuania", "error": null}, {"seq": 11, "cycle": -1, "method": "generate", "case_id": "chartqa-human-475", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.5544, "prompt": "How many 'Very' bars have a value lower than 40? Answer with only the short answer.", "output": "3", "error": null}, {"seq": 12, "cycle": -1, "method": "generate", "case_id": "chartqa-human-740", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.7109, "prompt": "What state has the 3rd most physicians in 2021? Answer with only the short answer.", "output": "Texas", "error": null}, {"seq": 13, "cycle": -1, "method": "generate", "case_id": "chartqa-human-406", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.5931, "prompt": "Is the starting value of China in the graph greater than 40%? Answer with only the short answer.", "output": "Yes", "error": null}, {"seq": 14, "cycle": -1, "method": "generate", "case_id": "chartqa-human-89", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.6726, "prompt": "What's the ratio(A:B) of yellow bar and blue bar for Ages 18-29? Answer with only the short answer.", "output": "20:13", "error": null}, {"seq": 15, "cycle": -1, "method": "generate", "case_id": "chartqa-human-799", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 2.146, "prompt": "What is the value , if we add top 2 bars and bottom 2 bars ? Answer with only the short answer.", "output": "93", "error": null}, {"seq": 16, "cycle": -1, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.509, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 17, "cycle": -1, "method": "generate", "case_id": "chartqa-human-1032", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.648, "prompt": "What countries data shown in green color? Answer with only the short answer.", "output": "Hungary", "error": null}, {"seq": 18, "cycle": -1, "method": "generate", "case_id": "chartqa-human-864", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.9576, "prompt": "Which year showed the largest difference in the data points between the two lines Answer with only the short answer.", "output": "2019", "error": null}, {"seq": 19, "cycle": -1, "method": "generate", "case_id": "chartqa-human-583", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 2.1683, "prompt": "Which year recorded the highest native born employment in Slovenia? Answer with only the short answer.", "output": "2008", "error": null}, {"seq": 20, "cycle": -1, "method": "generate", "case_id": "chartqa-human-372", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.2132, "prompt": "How many countries are included in the chart? Answer with only the short answer.", "output": "2", "error": null}, {"seq": 21, "cycle": -1, "method": "generate", "case_id": "chartqa-human-365", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.4067, "prompt": "Which color bar represents the highest value in the graph? Answer with only the short answer.", "output": "Magenta", "error": null}, {"seq": 22, "cycle": -1, "method": "generate", "case_id": "chartqa-human-875", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.8203, "prompt": "The highest percent of Not sure minus the smallest percent of Mostly trust gives what Answer with only the short answer.", "output": "53%", "error": null}, {"seq": 23, "cycle": -1, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 2.1856, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 24, "cycle": -1, "method": "generate", "case_id": "chartqa-human-355", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.7173, "prompt": "Which country data below 80% for the last five years ? Answer with only the short answer.", "output": "Sudan", "error": null}, {"seq": 25, "cycle": -1, "method": "generate", "case_id": "chartqa-human-379", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.2667, "prompt": "For how many years is the value of the Philippines lower than the one of Nepal? Answer with only the short answer.", "output": "3", "error": null}, {"seq": 26, "cycle": -1, "method": "generate", "case_id": "chartqa-human-532", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.3788, "prompt": "What is the value of the red bar? Answer with only the short answer.", "output": "4.2", "error": null}, {"seq": 27, "cycle": -1, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.7775, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No (185% is not greater than 233%)", "error": null}, {"seq": 28, "cycle": -1, "method": "generate", "case_id": "chartqa-human-452", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 2.3051, "prompt": "What's the value of the gray bar in Donald Trump category? Answer with only the short answer.", "output": "15", "error": null}, {"seq": 29, "cycle": -1, "method": "generate", "case_id": "chartqa-human-293", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.8326, "prompt": "Is the sum of all the last three places is more then Oceania? Answer with only the short answer.", "output": "Yes", "error": null}, {"seq": 30, "cycle": -1, "method": "generate", "case_id": "chartqa-human-1107", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.7026, "prompt": "What is the value of Hulu? Answer with only the short answer.", "output": "9.2%", "error": null}, {"seq": 31, "cycle": -1, "method": "generate", "case_id": "chartqa-human-352", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.4236, "prompt": "What is represents in the red line bar ? Answer with only the short answer.", "output": "Belize", "error": null}, {"seq": 32, "cycle": -1, "method": "generate", "case_id": "chartqa-human-95", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 2.965, "prompt": "Which country received the higher Country Programmable aid, Jamaica or Tonga? Answer with only the short answer.", "output": "Jamaica", "error": null}], "coverage_verification_gap": [{"seq": 66, "cycle": 0, "method": "generate", "case_id": "chartqa-human-445", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0488, "prompt": "In which country the difference between blue and green bar is maximum? Answer with only the short answer.", "output": "U.S.", "error": null}, {"seq": 69, "cycle": 0, "method": "generate", "case_id": "chartqa-human-445", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1997, "prompt": "In which country the difference between blue and green bar is maximum? Answer with only the short answer.", "output": "U.S.", "error": null}, {"seq": 71, "cycle": 0, "method": "generate", "case_id": "chartqa-human-445", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0772, "prompt": "In which country the difference between blue and green bar is maximum? Answer with only the short answer.", "output": "U.S.", "error": null}, {"seq": 73, "cycle": 0, "method": "generate", "case_id": "chartqa-human-445", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.5685, "prompt": "In which country the difference between blue and green bar is maximum? Answer with only the short answer.", "output": "U.S.", "error": null}, {"seq": 75, "cycle": 0, "method": "generate", "case_id": "chartqa-human-445", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0175, "prompt": "In which country the difference between blue and green bar is maximum? Answer with only the short answer.", "output": "U.S.", "error": null}, {"seq": 77, "cycle": 0, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1135, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77", "error": null}, {"seq": 79, "cycle": 0, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.2257, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77, 77", "error": null}, {"seq": 81, "cycle": 0, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9241, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77, 77", "error": null}, {"seq": 83, "cycle": 0, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0173, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77 and 77 (in 2006)", "error": null}, {"seq": 85, "cycle": 0, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.024, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77", "error": null}, {"seq": 87, "cycle": 0, "method": "generate", "case_id": "chartqa-human-45", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9307, "prompt": "What's the average of last three values in green graph (round to one decimal)? Answer with only the short answer.", "output": "28.7", "error": null}, {"seq": 89, "cycle": 0, "method": "generate", "case_id": "chartqa-human-45", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.03, "prompt": "What's the average of last three values in green graph (round to one decimal)? Answer with only the short answer.", "output": "28.7", "error": null}, {"seq": 90, "cycle": 0, "method": "generate", "case_id": "chartqa-human-45", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.8832, "prompt": "What's the average of last three values in green graph (round to one decimal)? Answer with only the short answer.", "output": "28.7", "error": null}, {"seq": 92, "cycle": 0, "method": "generate", "case_id": "chartqa-human-45", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0137, "prompt": "What's the average of last three values in green graph (round to one decimal)? Answer with only the short answer.", "output": "28.7", "error": null}, {"seq": 95, "cycle": 0, "method": "generate", "case_id": "chartqa-human-45", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 2.0479, "prompt": "What's the average of last three values in green graph (round to one decimal)? Answer with only the short answer.", "output": "28.7", "error": null}, {"seq": 96, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1122", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.029, "prompt": "Which category the three bars value is above 25% ? Answer with only the short answer.", "output": "Russia", "error": null}, {"seq": 98, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1122", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9927, "prompt": "Which category the three bars value is above 25% ? Answer with only the short answer.", "output": "Russia", "error": null}, {"seq": 99, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1122", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.8118, "prompt": "Which category the three bars value is above 25% ? Answer with only the short answer.", "output": "Russia", "error": null}, {"seq": 100, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1122", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.88, "prompt": "Which category the three bars value is above 25% ? Answer with only the short answer.", "output": "Russia", "error": null}, {"seq": 101, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1122", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0978, "prompt": "Which category the three bars value is above 25% ? Answer with only the short answer.", "output": "Russia", "error": null}, {"seq": 102, "cycle": 0, "method": "generate", "case_id": "chartqa-human-740", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9649, "prompt": "What state has the 3rd most physicians in 2021? Answer with only the short answer.", "output": "Texas", "error": null}, {"seq": 103, "cycle": 0, "method": "generate", "case_id": "chartqa-human-740", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.4342, "prompt": "What state has the 3rd most physicians in 2021? Answer with only the short answer.", "output": "Texas", "error": null}, {"seq": 104, "cycle": 0, "method": "generate", "case_id": "chartqa-human-740", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0613, "prompt": "What state has the 3rd most physicians in 2021? Answer with only the short answer.", "output": "Texas", "error": null}, {"seq": 105, "cycle": 0, "method": "generate", "case_id": "chartqa-human-740", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1489, "prompt": "What state has the 3rd most physicians in 2021? Answer with only the short answer.", "output": "Texas", "error": null}, {"seq": 106, "cycle": 0, "method": "generate", "case_id": "chartqa-human-740", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.3786, "prompt": "What state has the 3rd most physicians in 2021? Answer with only the short answer.", "output": "Texas", "error": null}, {"seq": 107, "cycle": 0, "method": "generate", "case_id": "chartqa-human-89", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9052, "prompt": "What's the ratio(A:B) of yellow bar and blue bar for Ages 18-29? Answer with only the short answer.", "output": "20:13", "error": null}, {"seq": 108, "cycle": 0, "method": "generate", "case_id": "chartqa-human-89", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0613, "prompt": "What's the ratio(A:B) of yellow bar and blue bar for Ages 18-29? Answer with only the short answer.", "output": "20:13", "error": null}, {"seq": 109, "cycle": 0, "method": "generate", "case_id": "chartqa-human-89", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9371, "prompt": "What's the ratio(A:B) of yellow bar and blue bar for Ages 18-29? Answer with only the short answer.", "output": "20:13", "error": null}, {"seq": 110, "cycle": 0, "method": "generate", "case_id": "chartqa-human-89", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0913, "prompt": "What's the ratio(A:B) of yellow bar and blue bar for Ages 18-29? Answer with only the short answer.", "output": "40:26", "error": null}, {"seq": 111, "cycle": 0, "method": "generate", "case_id": "chartqa-human-89", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0417, "prompt": "What's the ratio(A:B) of yellow bar and blue bar for Ages 18-29? Answer with only the short answer.", "output": "20:13", "error": null}, {"seq": 112, "cycle": 0, "method": "generate", "case_id": "chartqa-human-406", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.124, "prompt": "Is the starting value of China in the graph greater than 40%? Answer with only the short answer.", "output": "Yes", "error": null}, {"seq": 113, "cycle": 0, "method": "generate", "case_id": "chartqa-human-406", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.073, "prompt": "Is the starting value of China in the graph greater than 40%? Answer with only the short answer.", "output": "Yes", "error": null}, {"seq": 114, "cycle": 0, "method": "generate", "case_id": "chartqa-human-406", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.8281, "prompt": "Is the starting value of China in the graph greater than 40%? Answer with only the short answer.", "output": "Yes", "error": null}, {"seq": 115, "cycle": 0, "method": "generate", "case_id": "chartqa-human-406", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.6216, "prompt": "Is the starting value of China in the graph greater than 40%? Answer with only the short answer.", "output": "Yes", "error": null}, {"seq": 116, "cycle": 0, "method": "generate", "case_id": "chartqa-human-406", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.8078, "prompt": "Is the starting value of China in the graph greater than 40%? Answer with only the short answer.", "output": "Yes", "error": null}, {"seq": 117, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1765, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 118, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0971, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 119, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9761, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 120, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1603, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 121, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0735, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 122, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1032", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0787, "prompt": "What countries data shown in green color? Answer with only the short answer.", "output": "Hungary", "error": null}, {"seq": 123, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1032", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9694, "prompt": "What countries data shown in green color? Answer with only the short answer.", "output": "Hungary", "error": null}, {"seq": 124, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1032", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9681, "prompt": "What countries data shown in green color? Answer with only the short answer.", "output": "Hungary", "error": null}, {"seq": 125, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1032", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1443, "prompt": "What countries data shown in green color? Answer with only the short answer.", "output": "Hungary", "error": null}, {"seq": 126, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1032", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.3872, "prompt": "What countries data shown in green color? Answer with only the short answer.", "output": "Hungary", "error": null}, {"seq": 127, "cycle": 0, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0955, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 128, "cycle": 0, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0447, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 129, "cycle": 0, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.3765, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 130, "cycle": 0, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.3347, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 131, "cycle": 0, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9855, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 132, "cycle": 0, "method": "generate", "case_id": "chartqa-human-365", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9648, "prompt": "Which color bar represents the highest value in the graph? Answer with only the short answer.", "output": "**Magenta** (representing South Eastern Asia)", "error": null}, {"seq": 133, "cycle": 0, "method": "generate", "case_id": "chartqa-human-365", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0231, "prompt": "Which color bar represents the highest value in the graph? Answer with only the short answer.", "output": "Pink", "error": null}, {"seq": 134, "cycle": 0, "method": "generate", "case_id": "chartqa-human-365", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1938, "prompt": "Which color bar represents the highest value in the graph? Answer with only the short answer.", "output": "Pink", "error": null}, {"seq": 135, "cycle": 0, "method": "generate", "case_id": "chartqa-human-365", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0667, "prompt": "Which color bar represents the highest value in the graph? Answer with only the short answer.", "output": "The **magenta/pink** line (labeled **South Eastern Asia**) represents the highest value in the graph.", "error": null}, {"seq": 136, "cycle": 0, "method": "generate", "case_id": "chartqa-human-365", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9781, "prompt": "Which color bar represents the highest value in the graph? Answer with only the short answer.", "output": "Pink (or Magenta/Red-purple)", "error": null}, {"seq": 137, "cycle": 0, "method": "generate", "case_id": "chartqa-human-532", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9858, "prompt": "What is the value of the red bar? Answer with only the short answer.", "output": "4.2", "error": null}, {"seq": 138, "cycle": 0, "method": "generate", "case_id": "chartqa-human-532", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.5384, "prompt": "What is the value of the red bar? Answer with only the short answer.", "output": "4.2", "error": null}, {"seq": 139, "cycle": 0, "method": "generate", "case_id": "chartqa-human-532", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1485, "prompt": "What is the value of the red bar? Answer with only the short answer.", "output": "4.2", "error": null}, {"seq": 140, "cycle": 0, "method": "generate", "case_id": "chartqa-human-532", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1996, "prompt": "What is the value of the red bar? Answer with only the short answer.", "output": "4.2", "error": null}, {"seq": 141, "cycle": 0, "method": "generate", "case_id": "chartqa-human-532", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.5142, "prompt": "What is the value of the red bar? Answer with only the short answer.", "output": "4.2", "error": null}, {"seq": 142, "cycle": 0, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0336, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No", "error": null}, {"seq": 143, "cycle": 0, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0128, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No", "error": null}, {"seq": 144, "cycle": 0, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1054, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No", "error": null}, {"seq": 145, "cycle": 0, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9871, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No (185% is not greater than 233%)", "error": null}, {"seq": 146, "cycle": 0, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.2812, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No", "error": null}, {"seq": 147, "cycle": 0, "method": "generate", "case_id": "chartqa-human-95", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0843, "prompt": "Which country received the higher Country Programmable aid, Jamaica or Tonga? Answer with only the short answer.", "output": "Jamaica", "error": null}, {"seq": 148, "cycle": 0, "method": "generate", "case_id": "chartqa-human-95", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1491, "prompt": "Which country received the higher Country Programmable aid, Jamaica or Tonga? Answer with only the short answer.", "output": "Jamaica", "error": null}, {"seq": 149, "cycle": 0, "method": "generate", "case_id": "chartqa-human-95", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.3956, "prompt": "Which country received the higher Country Programmable aid, Jamaica or Tonga? Answer with only the short answer.", "output": "Jamaica", "error": null}, {"seq": 150, "cycle": 0, "method": "generate", "case_id": "chartqa-human-95", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.7598, "prompt": "Which country received the higher Country Programmable aid, Jamaica or Tonga? Answer with only the short answer.", "output": "Jamaica", "error": null}, {"seq": 151, "cycle": 0, "method": "generate", "case_id": "chartqa-human-95", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.8921, "prompt": "Which country received the higher Country Programmable aid, Jamaica or Tonga? Answer with only the short answer.", "output": "Jamaica", "error": null}, {"seq": 152, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1107", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.974, "prompt": "What is the value of Hulu? Answer with only the short answer.", "output": "9.2%", "error": null}, {"seq": 153, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1107", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0183, "prompt": "What is the value of Hulu? Answer with only the short answer.", "output": "9.2%", "error": null}, {"seq": 154, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1107", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0289, "prompt": "What is the value of Hulu? Answer with only the short answer.", "output": "9.2%", "error": null}, {"seq": 155, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1107", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.8908, "prompt": "What is the value of Hulu? Answer with only the short answer.", "output": "9.2%", "error": null}, {"seq": 156, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1107", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.8758, "prompt": "What is the value of Hulu? Answer with only the short answer.", "output": "9.2%", "error": null}, {"seq": 157, "cycle": 0, "method": "generate", "case_id": "chartqa-human-352", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1367, "prompt": "What is represents in the red line bar ? Answer with only the short answer.", "output": "Belize", "error": null}, {"seq": 158, "cycle": 0, "method": "generate", "case_id": "chartqa-human-352", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9751, "prompt": "What is represents in the red line bar ? Answer with only the short answer.", "output": "**Belize**", "error": null}, {"seq": 159, "cycle": 0, "method": "generate", "case_id": "chartqa-human-352", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1829, "prompt": "What is represents in the red line bar ? Answer with only the short answer.", "output": "Belize", "error": null}, {"seq": 160, "cycle": 0, "method": "generate", "case_id": "chartqa-human-352", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.3047, "prompt": "What is represents in the red line bar ? Answer with only the short answer.", "output": "Belize", "error": null}, {"seq": 161, "cycle": 0, "method": "generate", "case_id": "chartqa-human-352", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.8974, "prompt": "What is represents in the red line bar ? Answer with only the short answer.", "output": "Belize", "error": null}], "selfcheck_consistency": [{"seq": 67, "cycle": 0, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1265, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77, 77", "error": null}, {"seq": 68, "cycle": 0, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.995, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77", "error": null}, {"seq": 70, "cycle": 0, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1171, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77, 77", "error": null}, {"seq": 72, "cycle": 0, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.4084, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77", "error": null}, {"seq": 74, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9816, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 76, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0812, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 78, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0378, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 80, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.8546, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 82, "cycle": 0, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1187, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 84, "cycle": 0, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.098, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 86, "cycle": 0, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1188, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 88, "cycle": 0, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.2426, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 91, "cycle": 0, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0403, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No", "error": null}, {"seq": 93, "cycle": 0, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0856, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No", "error": null}, {"seq": 94, "cycle": 0, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.4088, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No", "error": null}, {"seq": 97, "cycle": 0, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.5389, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No", "error": null}]}, "n_calls": 128}, "m2": {"mode": "descriptive", "conclusion": "The evaluation harness is incorrectly marking correct model answers as failures because the model includes conversational context or explanatory units alongside its answers, while genuine model errors stem from a lack of visual coverage rather than selection mistakes. Specifically, 3 of the 5 failing cases (60%) contained the exact gold target right inside the extracted answer region—such as writing \"4.9 billion British pounds\" or giving explanatory reasoning like \"No (185% is not greater than 233%)\"—which the strict normalization harness failed to parse. Meanwhile, among the true errors, the model completely failed to generate the correct answer across all repeated attempts in 2 of the 16 evaluated cases (12.5%), showing zero instances where a correct answer was generated in the candidate pool but passed over by voting. What this evidence does not settle is whether the model's true perceptual misses on complex chart marks can be resolved with visual prompt modifications or if they represent hard resolution limits for the vision encoder.", "narrative": "Model: APIModel(key='gemini-3.6-flash', caps=['generate', 'tool_calls'])\nAnalyzers run: answer_extraction_audit, coverage_verification_gap, selfcheck_consistency\n\n2 metric(s) measured NOTHING — absence of evidence, NOT evidence of health:\n answer_extraction_audit.n_extraction_point_miss = 0 (analyzer ran but examined no items)\n answer_extraction_audit.n_reasked = 0 (analyzer ran but examined no items)\nNo anomalies detected among the metrics that DID measure something; the zero-count metrics above are not evidence either way.", "stats": [{"label": "Can repeated attempts ever find the right answer? — N unique", "raw_signal": "coverage_verification_gap.n_unique", "groups": [], "effect": 0.9166666666666666, "ci": [0.75, 1.0], "reject": true, "underpowered": false, "summary": "signal 'coverage_verification_gap.n_unique' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.9167 (B>A) CI=+0.7500..+1.0000 -> REJECT H0", "p_value": 0.0027472527472527475, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Does the model contradict itself? — Number of answer sentences checked", "raw_signal": "selfcheck_consistency.n_sentences", "groups": [], "effect": 0.5833333333333334, "ci": [0.08333333333333334, 1.0], "reject": true, "underpowered": false, "summary": "signal 'selfcheck_consistency.n_sentences' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.5833 (B>A) CI=+0.0833..+1.0000 -> REJECT H0", "p_value": 0.06318681318681318, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Did the model give a usable answer? — Length of the model answer", "raw_signal": "answer_extraction_audit.output_chars", "groups": [], "effect": 0.4603174603174603, "ci": [0.031746031746031744, 0.8571428571428571], "reject": true, "underpowered": false, "summary": "signal 'answer_extraction_audit.output_chars' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.4603 (B>A) CI=+0.0317..+0.8571 -> REJECT H0", "p_value": 0.10576923076923077, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Did the model give a usable answer? — Answered yes", "raw_signal": "answer_extraction_audit.answered_yes", "groups": [], "effect": -0.3333333333333333, "ci": [-0.6, -0.13333333333333333], "reject": true, "underpowered": false, "summary": "signal 'answer_extraction_audit.answered_yes' vs FAIL: [clustered bootstrap (unpaired)] effect=-0.3333 (A>B) CI=-0.6000..-0.1333 -> REJECT H0", "p_value": 1.0, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Did the model give a usable answer? — Gold yes", "raw_signal": "answer_extraction_audit.gold_yes", "groups": [], "effect": -0.3333333333333333, "ci": [-0.6, -0.13333333333333333], "reject": true, "underpowered": false, "summary": "signal 'answer_extraction_audit.gold_yes' vs FAIL: [clustered bootstrap (unpaired)] effect=-0.3333 (A>B) CI=-0.6000..-0.1333 -> REJECT H0", "p_value": 1.0, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Does the model contradict itself? — Selfcheck inconsistency", "raw_signal": "selfcheck_consistency.selfcheck_inconsistency", "groups": [], "effect": 0.5, "ci": [0.0, 1.0], "reject": false, "underpowered": false, "summary": "signal 'selfcheck_consistency.selfcheck_inconsistency' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.5000 (B>A) CI=+0.0000..+1.0000 -> inconclusive", "p_value": 1.0, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Does the model contradict itself? — Selfcheck worst sentence", "raw_signal": "selfcheck_consistency.selfcheck_worst_sentence", "groups": [], "effect": 0.5, "ci": [0.0, 1.0], "reject": false, "underpowered": false, "summary": "signal 'selfcheck_consistency.selfcheck_worst_sentence' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.5000 (B>A) CI=+0.0000..+1.0000 -> inconclusive", "p_value": 1.0, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Can repeated attempts ever find the right answer? — N unique", "raw_signal": "coverage_verification_gap.n_unique", "groups": [], "effect": 0.3667, "ci": [null, null], "reject": false, "underpowered": false, "summary": "Kendall τ between 'coverage_verification_gap.n_unique' and FAIL = +0.367 (n=16)", "p_value": null, "tool": "rank_corr", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Can repeated attempts ever find the right answer? — Majority share", "raw_signal": "coverage_verification_gap.majority_share", "groups": [], "effect": -0.3667, "ci": [null, null], "reject": false, "underpowered": false, "summary": "Kendall τ between 'coverage_verification_gap.majority_share' and FAIL = -0.367 (n=16)", "p_value": null, "tool": "rank_corr", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Did the model give a usable answer? — Length of the model answer", "raw_signal": "answer_extraction_audit.output_chars", "groups": [], "effect": 0.3333, "ci": [null, null], "reject": false, "underpowered": false, "summary": "Kendall τ between 'answer_extraction_audit.output_chars' and FAIL = +0.333 (n=16)", "p_value": null, "tool": "rank_corr", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Does the model contradict itself? — Selfcheck inconsistency", "raw_signal": "selfcheck_consistency.selfcheck_inconsistency", "groups": [], "effect": 0.3333, "ci": [null, null], "reject": false, "underpowered": false, "summary": "Kendall τ between 'selfcheck_consistency.selfcheck_inconsistency' and FAIL = +0.333 (n=4)", "p_value": null, "tool": "rank_corr", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Does the model contradict itself? — Selfcheck worst sentence", "raw_signal": "selfcheck_consistency.selfcheck_worst_sentence", "groups": [], "effect": 0.3333, "ci": [null, null], "reject": false, "underpowered": false, "summary": "Kendall τ between 'selfcheck_consistency.selfcheck_worst_sentence' and FAIL = +0.333 (n=4)", "p_value": null, "tool": "rank_corr", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Can repeated attempts ever find the right answer? — Majority share", "raw_signal": "coverage_verification_gap.majority_share", "groups": [], "effect": null, "ci": [null, null], "reject": false, "underpowered": false, "summary": "signal_label_assoc: degenerate split", "p_value": null, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Did the model give a usable answer? — Gave up", "raw_signal": "answer_extraction_audit.gave_up", "groups": [], "effect": null, "ci": [null, null], "reject": false, "underpowered": false, "summary": "signal_label_assoc: degenerate split", "p_value": null, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Did the model give a usable answer? — Used the requested answer format", "raw_signal": "answer_extraction_audit.has_answer_tag", "groups": [], "effect": null, "ci": [null, null], "reject": false, "underpowered": false, "summary": "signal_label_assoc: degenerate split", "p_value": null, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Did the model give a usable answer? — Has output", "raw_signal": "answer_extraction_audit.has_output", "groups": [], "effect": null, "ci": [null, null], "reject": false, "underpowered": false, "summary": "signal_label_assoc: degenerate split", "p_value": null, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Did the model give a usable answer? — Answer appears cut short", "raw_signal": "answer_extraction_audit.output_truncated", "groups": [], "effect": null, "ci": [null, null], "reject": false, "underpowered": false, "summary": "signal_label_assoc: degenerate split", "p_value": null, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Can repeated attempts ever find the right answer? — Coverage gap", "raw_signal": "coverage_verification_gap.coverage_gap", "groups": [], "effect": null, "ci": [null, null], "reject": false, "underpowered": false, "summary": "signal_label_assoc: degenerate split", "p_value": null, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Can repeated attempts ever find the right answer? — N graded", "raw_signal": "coverage_verification_gap.n_graded", "groups": [], "effect": null, "ci": [null, null], "reject": false, "underpowered": false, "summary": "signal_label_assoc: degenerate split", "p_value": null, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Can repeated attempts ever find the right answer? — N samples", "raw_signal": "coverage_verification_gap.n_samples", "groups": [], "effect": null, "ci": [null, null], "reject": false, "underpowered": false, "summary": "signal_label_assoc: degenerate split", "p_value": null, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}], "takeaways": [{"plain_title": "Cases with split consensus across repeated attempts failed four out of four times.", "title": "Verification consensus below 100% (majority share < 1.0) was linked with a 100% failure rate (4 of 4 cases), compared with 8% (1 of 12 cases) when unanimous.", "analysis": "Across 16 evaluated cases, 12 cases achieved unanimous agreement across all 5 verification samples and failed in only 1 case (8%). In contrast, all 4 cases where the majority share fell to 0.8 or 0.4 resulted in a FAIL outcome (100%). This matters because lack of internal consensus directly signals visual reasoning or reading difficulty. It remains uncertain whether consensus alone is sufficient on larger test sets, as only 4 cases exhibited split consensus.", "caveat": "Descriptive pattern on 16 cases; does not prove sample disagreement caused the error.", "chart_names": ["failrate_by_majority_share", "majority_share_distribution"], "table_names": ["tables/failrate_by_majority_share.csv"]}, {"plain_title": "Answers longer than eight characters failed every time, while concise answers almost always passed.", "title": "Output length exceeding 8 characters was associated with an 80% failure rate (4 of 5 cases), compared with 9% (1 of 11 cases) for shorter outputs.", "analysis": "Evaluating response length showed that 10 of 11 concise outputs (8 characters or fewer) passed, with an average length of 5.1 characters. Meanwhile, verbose outputs (10 to 34 characters) failed in 4 of 5 instances, reflecting discursive extraction attempts when the model could not produce a direct value. This highlights that verbose responses often indicate difficulty isolating the chart mark. Because sample size is modest (5 verbose cases), threshold boundaries should be tested on held-out splits.", "caveat": "Length thresholds were observed on these 16 exploration records and need held-out evaluation.", "chart_names": ["failrate_by_output_chars", "output_chars_distribution"], "table_names": ["tables/failrate_by_output_chars.csv"]}, {"plain_title": "Verification consensus and output length stand out as the top two signals separating passes from failures.", "title": "Majority consensus share (standardized difference 1.54) and distinct candidate count (1.31) lead all predictors in distinguishing FAIL from PASS.", "analysis": "Comparing standardized mean differences across all 6 variable predictors reveals that verification consistency measures show the highest contrast between outcomes. PASS cases averaged 1.0 distinct answer and 100% consensus, whereas FAIL cases averaged 2.4 distinct answers and 68% consensus. This indicates that self-consistency metrics capture visual ambiguity better than single-turn flags. What remains uncertain is whether verification failures stem from mark misreading or arithmetic steps.", "caveat": "Small sample size (n=16) produces wide confidence bounds around separation rankings.", "chart_names": ["top_discriminators", "top_discriminators_ranked"], "table_names": ["tables/top_discriminators.csv"]}, {"plain_title": "Combining verification consensus with output length captures every single failure.", "title": "A frozen recipe flagging cases with majority share under 1.0 or length over 8 characters captured 5 of 5 FAIL cases (100% sensitivity) with only 1 false alarm.", "analysis": "When combining the two primary signals into a single frozen rule, all 5 failure cases were flagged: 3 cases failed both criteria, 1 failed due to low consensus alone, and 1 failed due to long output alone. Among the 11 PASS cases, 10 remained unflagged, yielding an overall precision of 83% (5 of 6 flagged cases failing). This rule provides an explicit operational recipe for downstream testing. However, the exact cut-offs were tuned to these 16 cases and may experience boundary drift on new data.", "caveat": "The composite recipe was derived from the current exploratory sample and requires confirmatory testing on held-out data.", "chart_names": ["composite_recipe_performance", "verification_vs_output_chars_scatter"], "table_names": ["tables/composite_recipe_performance.csv"]}, {"plain_title": "The extraction suspect audit flag flagged only failures, but missed two out of five errors.", "title": "The extraction suspect flag was present in 3 of 5 FAIL cases (60%) and 0 of 11 PASS cases (0%).", "analysis": "The analyzer's extraction suspect flag occurred in 3 cases, all of which were FAIL outcomes (100% failure rate when flagged). However, 2 failed cases showed an extraction suspect value of 0.0, indicating that while specific, this flag misses visual reasoning failures that occur without obvious extraction anomalies. This shows that extraction auditing alone is insufficient without consistency verification. Missingness in other audit fields (like answered_yes with 14 missing rows) limits further single-turn extraction diagnosis.", "caveat": "High specificity on 3 cases does not guarantee zero false positives on broader distributions.", "chart_names": ["failrate_by_extraction_suspect"], "table_names": ["tables/failrate_by_extraction_suspect.csv"]}], "figures": [{"id": "class_balance", "title": "Overall Outcome Balance", "question": "What is the balance between FAIL and PASS cases?", "path": "logs/M2/artifacts/00_class_balance_30bfb1d91789.png", "reading": "Of the 16 evaluated cases, 11 (68.8%) passed and 5 (31.2%) failed.", "do_not_infer": "Baseline balance in this 16-case subset may differ from the full benchmark distribution.", "disposition": "primary", "not_promoted_reason": ""}, {"id": "top_discriminators", "title": "Top Discriminating Signals", "question": "Which signals exhibit the greatest separation between FAIL and PASS outcomes?", "path": "logs/M2/artifacts/01_top_discriminators_94ef3c56b442.png", "reading": "Majority consensus share and number of unique sampled answers display the highest standardized separation between FAIL and PASS cases.", "do_not_infer": "Separation ranking reflects this small exploratory sample and does not prove causal dominance.", "disposition": "primary", "not_promoted_reason": ""}, {"id": "failrate_by_majority_share", "title": "Failure Rate by Verification Consensus", "question": "How does consistency across sampled answers relate to failure rate?", "path": "logs/M2/artifacts/02_failrate_by_majority_share_c6d46b38e3b5.png", "reading": "Failure rate is 8% (1 of 12) at unanimous consensus (1.0), but jumps to 100% (4 of 4) when consensus drops to 0.8 or 0.4.", "do_not_infer": "Does not prove that lack of consensus causes the error; only shows high co-occurrence.", "disposition": "primary", "not_promoted_reason": ""}, {"id": "failrate_by_unique_answers", "title": "Failure Rate by Distinct Sampled Answers", "question": "Does generating multiple distinct answer candidates link to failure?", "path": "logs/M2/artifacts/03_failrate_by_unique_answers_bea383878c84.png", "reading": "Cases with 1 unique answer have an 8% failure rate (1 of 12), rising to 100% (4 of 4) when 2 to 4 unique answers are generated.", "do_not_infer": "Candidate dispersion could reflect prompt ambiguity rather than model deficiency alone.", "disposition": "primary", "not_promoted_reason": ""}, {"id": "failrate_by_output_chars", "title": "Failure Rate by Response Character Length", "question": "Are longer model outputs more likely to be incorrect?", "path": "logs/M2/artifacts/04_failrate_by_output_chars_37bc2e21ba8c.png", "reading": "Outputs with 8 characters or fewer fail at 9% (1 of 11), while outputs exceeding 15 characters fail at 100% (3 of 3).", "do_not_infer": "Short answers can still be incorrect; length is an indicator of difficulty, not a direct cause.", "disposition": "primary", "not_promoted_reason": ""}, {"id": "failrate_by_extraction_suspect", "title": "Failure Rate by Extraction Suspect Flag", "question": "How often does an extraction suspect flag coincide with a failed case?", "path": "logs/M2/artifacts/05_failrate_by_extraction_suspect_3670517073cb.png", "reading": "Cases flagged as extraction suspect fail 100% of the time (3 of 3), while unflagged cases fail 15% of the time (2 of 13).", "do_not_infer": "Failing to flag does not guarantee correctness, as 2 failures went unflagged.", "disposition": "primary", "not_promoted_reason": ""}, {"id": "composite_recipe_performance", "title": "Candidate Combined Recipe Coverage", "question": "Does combining low verification consensus and verbose length flag all failures?", "path": "logs/M2/artifacts/06_composite_recipe_performance_dfb53be593ae.png", "reading": "The combined rule flags 6 cases in total, identifying all 5 FAIL cases and only 1 PASS case.", "do_not_infer": "Rule thresholds were selected on this dataset and must be verified on fresh data.", "disposition": "primary", "not_promoted_reason": ""}, {"id": "leakage_label_disagrees", "title": "Label Disagreement Audit Check", "question": "Does the label disagreement predictor reflect evaluation leakage or noise?", "path": "logs/M2/artifacts/07_leakage_label_disagrees_7def4c3590a6.png", "reading": "The label_disagrees field flags 3 of 5 FAIL cases and 1 of 11 PASS cases.", "do_not_infer": "High outcome overlap suggests this field may incorporate ground-truth label information.", "disposition": "supporting", "not_promoted_reason": "Evaluated as an audit check for potential data leakage rather than a standard model predictor."}, {"id": "majority_share_distribution", "title": "Majority Share Distribution", "question": "", "path": "logs/M2/artifacts/majority_share_distribution_266c6ad7edb4.png", "reading": "", "do_not_infer": "No agent-authored interpretation was saved for this figure.", "disposition": "audit", "not_promoted_reason": "Unlinked exploratory artifact"}, {"id": "output_chars_distribution", "title": "Output Chars Distribution", "question": "", "path": "logs/M2/artifacts/output_chars_distribution_1b357fafc6b6.png", "reading": "", "do_not_infer": "No agent-authored interpretation was saved for this figure.", "disposition": "audit", "not_promoted_reason": "Unlinked exploratory artifact"}, {"id": "signal_correlation_heatmap", "title": "Signal Correlation Heatmap", "question": "", "path": "logs/M2/artifacts/signal_correlation_heatmap_81fd726c5c3a.png", "reading": "", "do_not_infer": "No agent-authored interpretation was saved for this figure.", "disposition": "audit", "not_promoted_reason": "Unlinked exploratory artifact"}, {"id": "top_discriminators_ranked", "title": "Top Discriminators Ranked", "question": "", "path": "logs/M2/artifacts/top_discriminators_ranked_2a8223acfe97.png", "reading": "", "do_not_infer": "No agent-authored interpretation was saved for this figure.", "disposition": "audit", "not_promoted_reason": "Unlinked exploratory artifact"}, {"id": "verification_vs_output_chars_scatter", "title": "Verification Vs Output Chars Scatter", "question": "", "path": "logs/M2/artifacts/verification_vs_output_chars_scatter_bf822c4e5d0a.png", "reading": "", "do_not_infer": "No agent-authored interpretation was saved for this figure.", "disposition": "audit", "not_promoted_reason": "Unlinked exploratory artifact"}, {"id": "m2_effects", "title": "M2 Effects", "question": "", "path": "logs/M2/artifacts/m2_effects.png", "reading": "", "do_not_infer": "No agent-authored interpretation was saved for this figure.", "disposition": "supporting", "not_promoted_reason": ""}], "observations": ["Loaded 16 evaluated cases from the human-authored ChartQA benchmark.", "There are 5 FAIL cases (31.25%) and 11 PASS cases (68.75%).", "Verification instability (majority share < 1.0) and verbose outputs (> 8 characters) strongly separate FAIL from PASS cases.", "Extraction suspect flags appear exclusively on FAIL cases, while gold/answered yes flags are present on only 2 cases.", "The label_disagrees column exhibits circular overlap with the outcome (flags 3 FAIL cases and 1 PASS case)."], "caveats": ["Sample size is limited to 16 cases (5 FAIL, 11 PASS), so confidence intervals are wide.", "Numeric thresholds (majority share < 1.0, output characters > 8) were discovered on these exploration rows and must be verified on held-out test splits.", "Several audit predictors (such as answer_extraction_audit_gold_yes) have 14 missing values (87.5% missing) and were excluded from ranking.", "Eight columns are completely constant across all 16 rows and provide no discriminative information."], "candidate_signals": [{"name": "verification_disagreement", "display_name": "Verification sample disagreement", "rationale": "Flags cases where repeated samples failed to reach unanimous agreement, indicating visual ambiguity or reasoning instability.", "suggested_test": "Evaluate failure rate difference on held-out ChartQA test split.", "sufficient": null, "recipe": {"name": "verification_disagreement", "kind": "expr", "expr": "coverage_verification_gap_majority_share < 1.0"}, "effect": null, "ci": null, "e_value": null, "reject": false, "underpowered": false, "host_adjudicated": false, "fdr_corrected": false, "descriptive_only": true}, {"name": "verbose_extraction_attempt", "display_name": "Verbose extraction output", "rationale": "Flags cases where the model output exceeds 8 characters, indicative of rambling explanations rather than extracted chart values.", "suggested_test": "Check whether length threshold holds across different prompt instructions.", "sufficient": null, "recipe": {"name": "verbose_extraction_attempt", "kind": "expr", "expr": "answer_extraction_audit_output_chars > 8.0"}, "effect": null, "ci": null, "e_value": null, "reject": false, "underpowered": false, "host_adjudicated": false, "fdr_corrected": false, "descriptive_only": true}, {"name": "unstable_or_verbose_recipe", "display_name": "Combined instability and verbosity recipe", "rationale": "Combines sample disagreement and verbosity into a frozen composite recipe to maximize failure coverage.", "suggested_test": "Test sensitivity and specificity of the composite recipe on held-out cases.", "sufficient": null, "recipe": {"name": "unstable_or_verbose_recipe", "kind": "expr", "expr": "(coverage_verification_gap_majority_share < 1.0) or (answer_extraction_audit_output_chars > 8.0)"}, "effect": null, "ci": null, "e_value": null, "reject": false, "underpowered": false, "host_adjudicated": false, "fdr_corrected": false, "descriptive_only": true}], "recommended_tests": ["Test the composite rule '(coverage_verification_gap_majority_share < 1.0) or (answer_extraction_audit_output_chars > 8.0)' on held-out ChartQA test cases.", "Perform a two-sample permutation test on majority consensus share between FAIL and PASS cases on the full split.", "Evaluate whether length-based error association persists under strict output formatting prompts."]}, "m3": {"mode": "proposal", "hypotheses": [{"id": "h-128623e9ab1b", "statement": "Evaluation failures are predominantly caused by strict string normalization in the evaluation harness rejecting verbose responses that append units or parenthetical explanations to otherwise correct answers.", "plain_statement": "The benchmark grader mistakenly marks answers as wrong because the model explains its reasoning or includes units like \"billion British pounds\" instead of printing just the raw number.", "failure_mode": "answer_extraction", "status": "proposed", "test_design": "answer_extraction_audit.output_chars HIGHER on failing cases", "critic": "keep", "critic_reason": "The evidence directly supports this claim, showing 60% of all failure cases (3 of 5) contained the gold target within the answer region rejected solely by rigid matching."}, {"id": "h-6d78ceb0d12c", "statement": "Model failures on visual queries with low consensus across repeated samples stem from candidate answer dispersion where majority voting drops the correct solution present in the candidate pool.", "plain_statement": "When the model is uncertain and generates multiple different answers across repeated tries, the final majority vote fails to pick the correct answer even though it was found during the attempts.", "failure_mode": "selection_failure", "status": "proposed", "test_design": "coverage_verification_gap.n_unique HIGHER on failing cases", "critic": "reject", "critic_reason": "Unsupported claim directly contradicted by the evidence: the coverage gap rate was 0.0% with zero instances where a correct candidate answer was generated but dropped by majority voting."}, {"id": "h-17b34a38f36c", "statement": "Genuine visual reasoning failures on fine-grained chart elements represent encoder coverage deficits where the model consistently fails to extract required numeric data across repeated sampling attempts.", "plain_statement": "For true visual misses, the model completely fails to read the relevant data points or chart marks, never finding the right answer even after trying five separate times.", "failure_mode": "knowledge_gap", "status": "proposed", "test_design": "coverage_verification_gap.majority_share LOWER on failing cases", "critic": "reject", "critic_reason": "Overgeneralisation and unsupported claim: attributing all genuine visual reasoning failures strictly to encoder coverage deficits of numeric data over-extrapolates from only two failures, one of which failed on a non-numeric chart mark (\"Magenta\")."}], "unparsed_proposals": [], "agent_response": "", "candidate_signals": [{"name": "verification_disagreement", "display_name": "Verification sample disagreement", "rationale": "Flags cases where repeated samples failed to reach unanimous agreement, indicating visual ambiguity or reasoning instability.", "suggested_test": "Evaluate failure rate difference on held-out ChartQA test split.", "sufficient": null, "recipe": {"name": "verification_disagreement", "kind": "expr", "expr": "coverage_verification_gap_majority_share < 1.0"}, "effect": null, "ci": null, "e_value": null, "reject": false, "underpowered": false, "host_adjudicated": false, "fdr_corrected": false, "descriptive_only": true}, {"name": "verbose_extraction_attempt", "display_name": "Verbose extraction output", "rationale": "Flags cases where the model output exceeds 8 characters, indicative of rambling explanations rather than extracted chart values.", "suggested_test": "Check whether length threshold holds across different prompt instructions.", "sufficient": null, "recipe": {"name": "verbose_extraction_attempt", "kind": "expr", "expr": "answer_extraction_audit_output_chars > 8.0"}, "effect": null, "ci": null, "e_value": null, "reject": false, "underpowered": false, "host_adjudicated": false, "fdr_corrected": false, "descriptive_only": true}, {"name": "unstable_or_verbose_recipe", "display_name": "Combined instability and verbosity recipe", "rationale": "Combines sample disagreement and verbosity into a frozen composite recipe to maximize failure coverage.", "suggested_test": "Test sensitivity and specificity of the composite recipe on held-out cases.", "sufficient": null, "recipe": {"name": "unstable_or_verbose_recipe", "kind": "expr", "expr": "(coverage_verification_gap_majority_share < 1.0) or (answer_extraction_audit_output_chars > 8.0)"}, "effect": null, "ci": null, "e_value": null, "reject": false, "underpowered": false, "host_adjudicated": false, "fdr_corrected": false, "descriptive_only": true}], "recommended_tests": ["Test the composite rule '(coverage_verification_gap_majority_share < 1.0) or (answer_extraction_audit_output_chars > 8.0)' on held-out ChartQA test cases.", "Perform a two-sample permutation test on majority consensus share between FAIL and PASS cases on the full split.", "Evaluate whether length-based error association persists under strict output formatting prompts."], "evidence_figures": [{"id": "class_balance", "title": "Overall Outcome Balance", "question": "What is the balance between FAIL and PASS cases?", "path": "logs/M2/artifacts/00_class_balance_30bfb1d91789.png", "reading": "Of the 16 evaluated cases, 11 (68.8%) passed and 5 (31.2%) failed.", "do_not_infer": "Baseline balance in this 16-case subset may differ from the full benchmark distribution.", "disposition": "primary", "not_promoted_reason": ""}, {"id": "top_discriminators", "title": "Top Discriminating Signals", "question": "Which signals exhibit the greatest separation between FAIL and PASS outcomes?", "path": "logs/M2/artifacts/01_top_discriminators_94ef3c56b442.png", "reading": "Majority consensus share and number of unique sampled answers display the highest standardized separation between FAIL and PASS cases.", "do_not_infer": "Separation ranking reflects this small exploratory sample and does not prove causal dominance.", "disposition": "primary", "not_promoted_reason": ""}, {"id": "failrate_by_majority_share", "title": "Failure Rate by Verification Consensus", "question": "How does consistency across sampled answers relate to failure rate?", "path": "logs/M2/artifacts/02_failrate_by_majority_share_c6d46b38e3b5.png", "reading": "Failure rate is 8% (1 of 12) at unanimous consensus (1.0), but jumps to 100% (4 of 4) when consensus drops to 0.8 or 0.4.", "do_not_infer": "Does not prove that lack of consensus causes the error; only shows high co-occurrence.", "disposition": "primary", "not_promoted_reason": ""}], "evidence_stats": [{"label": "Can repeated attempts ever find the right answer? — N unique", "raw_signal": "coverage_verification_gap.n_unique", "groups": [], "effect": 0.9166666666666666, "ci": [0.75, 1.0], "reject": true, "underpowered": false, "summary": "signal 'coverage_verification_gap.n_unique' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.9167 (B>A) CI=+0.7500..+1.0000 -> REJECT H0", "p_value": 0.0027472527472527475, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Does the model contradict itself? — Number of answer sentences checked", "raw_signal": "selfcheck_consistency.n_sentences", "groups": [], "effect": 0.5833333333333334, "ci": [0.08333333333333334, 1.0], "reject": true, "underpowered": false, "summary": "signal 'selfcheck_consistency.n_sentences' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.5833 (B>A) CI=+0.0833..+1.0000 -> REJECT H0", "p_value": 0.06318681318681318, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Did the model give a usable answer? — Length of the model answer", "raw_signal": "answer_extraction_audit.output_chars", "groups": [], "effect": 0.4603174603174603, "ci": [0.031746031746031744, 0.8571428571428571], "reject": true, "underpowered": false, "summary": "signal 'answer_extraction_audit.output_chars' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.4603 (B>A) CI=+0.0317..+0.8571 -> REJECT H0", "p_value": 0.10576923076923077, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Did the model give a usable answer? — Answered yes", "raw_signal": "answer_extraction_audit.answered_yes", "groups": [], "effect": -0.3333333333333333, "ci": [-0.6, -0.13333333333333333], "reject": true, "underpowered": false, "summary": "signal 'answer_extraction_audit.answered_yes' vs FAIL: [clustered bootstrap (unpaired)] effect=-0.3333 (A>B) CI=-0.6000..-0.1333 -> REJECT H0", "p_value": 1.0, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Did the model give a usable answer? — Gold yes", "raw_signal": "answer_extraction_audit.gold_yes", "groups": [], "effect": -0.3333333333333333, "ci": [-0.6, -0.13333333333333333], "reject": true, "underpowered": false, "summary": "signal 'answer_extraction_audit.gold_yes' vs FAIL: [clustered bootstrap (unpaired)] effect=-0.3333 (A>B) CI=-0.6000..-0.1333 -> REJECT H0", "p_value": 1.0, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Does the model contradict itself? — Selfcheck inconsistency", "raw_signal": "selfcheck_consistency.selfcheck_inconsistency", "groups": [], "effect": 0.5, "ci": [0.0, 1.0], "reject": false, "underpowered": false, "summary": "signal 'selfcheck_consistency.selfcheck_inconsistency' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.5000 (B>A) CI=+0.0000..+1.0000 -> inconclusive", "p_value": 1.0, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}]}, "m4": {"ran": true, "mode": "confirmatory", "results": [{"hypothesis_id": "h-128623e9ab1b", "hypothesis": "Evaluation failures are predominantly caused by strict string normalization in the evaluation harness rejecting verbose responses that append units or parenthetical explanations to otherwise correct answers.", "status": "inconclusive", "effect_size": 0.4603174603174603, "confidence": 0.358, "verdict": "No significant M2 result (best: signal 'answer_extraction_audit.output_chars' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.4603 (B>A) CI=+0.0317..+0.8571 -> REJECT H0 [BH: NOT survived, p=0.106, n_signal=7])", "evidence_grade": "observational", "protocol_consistent": true}, {"hypothesis_id": "h-6d78ceb0d12c", "hypothesis": "Model failures on visual queries with low consensus across repeated samples stem from candidate answer dispersion where majority voting drops the correct solution present in the candidate pool.", "status": "supported", "effect_size": 0.9166666666666666, "confidence": 0.786, "verdict": "signal_label_assoc: signal 'coverage_verification_gap.n_unique' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.9167 (B>A) CI=+0.7500..+1.0000 -> REJECT H0 [BH: survived, p=0.00275, n_signal=4] [hypothesis predicts the signal HIGHER on failures; observed effect +0.917 -> consistent]", "evidence_grade": "observational", "protocol_consistent": true}, {"hypothesis_id": "h-17b34a38f36c", "hypothesis": "Genuine visual reasoning failures on fine-grained chart elements represent encoder coverage deficits where the model consistently fails to extract required numeric data across repeated sampling attempts.", "status": "inconclusive", "effect_size": null, "confidence": 0.0, "verdict": "designated evidence not measured this cycle: the test design names coverage_verification_gap.majority_share but M2 has no result for them — not judged on unrelated signals (next cycle's M1 targets the design)", "evidence_grade": "none", "protocol_consistent": true}], "event": {"ts": "2026-10-12T17:09:28.648167+00:00", "cycle": 0, "module": "m4", "hypothesis_id": "h-17b34a38f36c", "hypothesis": "Genuine visual reasoning failures on fine-grained chart elements represent encoder coverage deficits where the model consistently fails to extract required numeric data across repeated sampling attempts.", "failure_mode": "knowledge_gap", "status": "inconclusive", "fixed": false, "confidence_score": 0.0, "evidence_dimensions": {}, "evidence": {"m4_test_name": "stats_results", "m4_effect_size": null, "m4_confidence": 0.0, "m4_protocol_consistent": true, "m4_verdict": "designated evidence not measured this cycle: the test design names coverage_verification_gap.majority_share but M2 has no result for them — not judged on unrelated signals (next cycle's M1 targets the design)", "m4_evidence_grade": "none", "source": "m2_stats_results", "consulted_tools": ["rank_corr", "rank_corr", "rank_corr", "rank_corr", "rank_corr"], "routed_by": "test_design_unmet", "designated": ["coverage_verification_gap.majority_share"]}, "n_refocused_cases": null, "validation_examples": [{"id": "chartqa-human-86", "kind": "validation_case", "case_id": "chartqa-human-86", "input": "Which two values are same in the upper graph? Answer with only the short answer.", "baseline_output": "77 and 77 (in 2006)", "expected": ["77"], "outcome": "fail", "plain_reading": "This is one case in the independent validation pool. The verdict is determined from the full pool, not this case alone.", "evidence_scope": "one case in the independent validation pool"}], "judge_prompt": "Experiment protocol:\n{\n \"description\": \"Evaluate a vision-language model (gemini-3.6-flash, spec gemini-3.6-flash = api:gemini-3.6-flash) on the human-authored ChartQA test split. Questions require reading chart marks and labels, comparing quantities, and performing arithmetic or logical reasoning. Diagnose whether errors reflect answer extraction, unstable visual evidence, or failure to verify a candidate answer.\",\n \"task_domain\": \"chart visual question answering\",\n \"success_criteria\": \"The short answer must match an official ChartQA label after normalization; numeric answers use ChartQA's relaxed five-percent tolerance.\",\n \"failure_patterns\": \"\",\n \"target_modalities\": [\n \"image\",\n \"text\"\n ],\n \"output_contract\": {},\n \"metadata\": {}\n}\n\nHypothesis under review:\nStatement: Genuine visual reasoning failures on fine-grained chart elements represent encoder coverage deficits where the model consistently fails to extract required numeric data across repeated sampling attempts.\nPredicted failure mode: knowledge_gap\n\nDoes this hypothesis address a failure mode that is relevant to the experiment protocol above?\nAnswer YES or NO on the first line, then give a one-sentence reason.\n\nAnswer YES if the hypothesis explains a failure that the protocol would care about.\nAnswer NO if the hypothesis is about something the protocol does not mention or test.", "judge_response": "YES\nThe experiment protocol explicitly tasks the evaluation with reading chart marks/labels and diagnosing whether errors stem from answer extraction or visual evidence failures, which directly aligns with testing whether repeated failures to extract numeric data from fine-grained chart elements represent visual encoder coverage deficits.", "duration_sec": 13.307, "event": "surgery", "schema_version": 6, "trace_id": "a9822626-af4d-43ea-b5cc-486232b73048", "event_seq": 174, "stage": "M4", "span_id": "c0.m4"}, "examples": [{"id": "chartqa-human-86", "kind": "validation_case", "case_id": "chartqa-human-86", "input": "Which two values are same in the upper graph? Answer with only the short answer.", "baseline_output": "77 and 77 (in 2006)", "expected": ["77"], "outcome": "fail", "plain_reading": "This is one case in the independent validation pool. The verdict is determined from the full pool, not this case alone.", "evidence_scope": "one case in the independent validation pool", "hypothesis": "Evaluation failures are predominantly caused by strict string normalization in the evaluation harness rejecting verbose responses that append units or parenthetical explanations to otherwise correct answers.", "test": null, "status": "inconclusive", "media_ids": ["media-2"]}]}, "m5": {"ran": true, "fixed": false, "skipped": false, "skip_reason": "", "skip_detail": "", "candidates": [{"tier": "L1", "name": "strict_minimal_answer", "kind": "template", "ref": "", "headline": "", "source": "judge", "verdict": "partial", "n_pairs": 16, "n_baseline_correct": 11, "n_candidate_correct": 14, "n_fixed": 3, "n_broken": 0, "effect": 0.1875, "e_value": 2.0000000000000018, "e_threshold": 20.0, "coverage": 1.0, "reject": false, "fixed": false, "n_model_independent": 0, "n_unstable": 0, "summary": "[mcnemar + e-value (paired binary)] effect=+0.1875 (B>A) CI=+0.0000..+0.3750, e=2.00 -> inconclusive [partial, coverage=100%]", "payload": {"prompt_template": "{prompt}\n\nImportant: Output ONLY the exact value, number, or name. Do not include units, symbols, years, or explanatory text in parentheses."}, "fixed_cases": ["chartqa-human-475", "chartqa-human-428", "chartqa-human-293"], "broken_cases": []}], "confirmation": {"tier": null, "name": null, "kind": null, "ref": "", "headline": "", "source": null, "verdict": null, "n_pairs": null, "n_baseline_correct": null, "n_candidate_correct": null, "n_fixed": 0, "n_broken": 0, "effect": null, "e_value": null, "e_threshold": null, "coverage": null, "reject": null, "fixed": null, "n_model_independent": null, "n_unstable": null, "summary": null, "payload": {}, "fixed_cases": [], "broken_cases": []}, "best": {"tier": null, "name": null, "kind": null, "ref": "", "headline": "", "source": null, "verdict": null, "n_pairs": null, "n_baseline_correct": null, "n_candidate_correct": null, "n_fixed": 0, "n_broken": 0, "effect": null, "e_value": null, "e_threshold": null, "coverage": null, "reject": null, "fixed": null, "n_model_independent": null, "n_unstable": null, "summary": null, "payload": {}, "fixed_cases": [], "broken_cases": []}, "recommendation": {"recommend_tier": null, "action": "gather_more_failures", "reason": "the candidate selected on EXPLORE did not validate on untouched CONFIRM; underpowered by design: only 5 failure case(s) — even a perfect fix tops out at e=5.3 (< 20 needed). 'strict_minimal_answer' already helps net 3 case(s); collect >= 8 failing cases and re-validate before escalating the tier."}, "examples": [], "operation_previews": [], "surgeries": [], "prompt_template": ""}}, "case_study": {"modules": [{"code": "M1", "name": "Suspicious behavior detection", "subtitle": "Run the probing library, find per-case suspicious behaviors."}, {"code": "M2", "name": "Statistical screening", "subtitle": "Using plots to explain, statistical tests to decide."}, {"code": "M3", "name": "Hypothesis formation", "subtitle": "Explore the reason behind the signals."}, {"code": "M4", "name": "Held-out verification", "subtitle": "Confirm the hypothesis over cases it never saw."}, {"code": "M5", "name": "Validated repair", "subtitle": "Climb the repair ladder until something holds."}], "headline": {"model": "gemini-3.6-flash", "dataset": "chartqa", "n_cases": 32, "baseline_accuracy": 0.6875, "n_explore": 16, "n_heldout": 16, "judge": "AgyModel(binary='/usr/local/bin/agy')", "repair": null, "repair_tier": null, "delta": null}, "m1": {"selection_mode": "pinned", "selected_analyzers": ["answer_extraction_audit", "selfcheck_consistency", "coverage_verification_gap"], "families": [{"family": "black_box_behavior", "label": "BLACK-BOX", "selected": true, "analyzers": ["answer_extraction_audit", "selfcheck_consistency", "coverage_verification_gap"], "probes": [{"phrase": "consistency across 5 resamples", "used": true, "analyzers": ["selfcheck_consistency"], "confirmed": false}, {"phrase": "coverage / verification gap", "used": true, "analyzers": ["coverage_verification_gap"], "confirmed": true}, {"phrase": "answer-extraction audit", "used": true, "analyzers": ["answer_extraction_audit"], "confirmed": false}]}, {"family": "internal_white_box", "label": "INTERNAL / WHITE-BOX", "selected": false, "analyzers": [], "probes": [{"phrase": "attention & attribution", "used": false, "analyzers": [], "confirmed": false}, {"phrase": "logits & representations", "used": false, "analyzers": [], "confirmed": false}, {"phrase": "causal interventions", "used": false, "analyzers": [], "confirmed": false}]}, {"family": "multimodal", "label": "MULTIMODAL", "selected": false, "analyzers": [], "probes": [{"phrase": "grounding & hallucination", "used": false, "analyzers": [], "confirmed": false}, {"phrase": "modality attribution", "used": false, "analyzers": [], "confirmed": false}]}], "questions": [{"question": "Did it produce anything at all?", "analyzers": ["answer_extraction_audit"], "n_measurements": 1, "n_candidates": 0}, {"question": "Did it answer in the form we asked for?", "analyzers": ["answer_extraction_audit"], "n_measurements": 1, "n_candidates": 0}, {"question": "Did it give up answering?", "analyzers": ["answer_extraction_audit"], "n_measurements": 1, "n_candidates": 0}, {"question": "Did it stop, or keep talking?", "analyzers": ["answer_extraction_audit"], "n_measurements": 2, "n_candidates": 1}, {"question": "Same question five times, same answer?", "analyzers": ["coverage_verification_gap"], "n_measurements": 4, "n_candidates": 2}, {"question": "Asked to check itself, does it change?", "analyzers": ["selfcheck_consistency"], "n_measurements": 3, "n_candidates": 1}, {"question": "Does it lean to one answer regardless?", "analyzers": ["answer_extraction_audit"], "n_measurements": 2, "n_candidates": 0}, {"question": "Did it ever produce the right answer?", "analyzers": ["coverage_verification_gap"], "n_measurements": 1, "n_candidates": 0}], "n_analyzers": 3, "n_measured": 26, "dropped": {"saw_the_answer_key": 11, "never_varied": 7, "partial_coverage": 4}, "note": "each case is answered five times; the probes never see the answer key", "n_forwarded": 7, "signal_curve": {"signal": "coverage_verification_gap.n_unique", "analyzer": "coverage_verification_gap", "field": "n_unique", "phase": "explore", "binning": "levels", "bins": [{"label": "n_unique = 1", "value": 1, "n_cases": 12, "n_fail": 1, "failure_rate": 0.0833}, {"label": "n_unique = 2", "value": 2, "n_cases": 2, "n_fail": 2, "failure_rate": 1.0}, {"label": "n_unique = 3", "value": 3, "n_cases": 1, "n_fail": 1, "failure_rate": 1.0}, {"label": "n_unique = 4", "value": 4, "n_cases": 1, "n_fail": 1, "failure_rate": 1.0}], "n_cases": 16, "all_surviving_signals": ["coverage_verification_gap.n_unique"], "n_surviving_signals": 1}}, "m2": {"explore": {"tests": [{"signal": "answer_extraction_audit.output_chars", "effect": 0.4603174603174603, "ci": [0.031746031746031744, 0.8571428571428571], "p_value": 0.10576923076923077, "survives_correction": false, "degenerate": false, "in_correction_family": true}, {"signal": "coverage_verification_gap.n_unique", "effect": 0.9166666666666666, "ci": [0.75, 1.0], "p_value": 0.0027472527472527475, "survives_correction": true, "degenerate": false, "in_correction_family": true}, {"signal": "selfcheck_consistency.n_sentences", "effect": 0.5833333333333334, "ci": [0.08333333333333334, 1.0], "p_value": 0.06318681318681318, "survives_correction": false, "degenerate": false, "in_correction_family": true}, {"signal": "coverage_verification_gap.majority_share", "effect": null, "ci": null, "p_value": null, "survives_correction": false, "degenerate": true, "in_correction_family": false}, {"signal": "answer_extraction_audit.answered_yes", "effect": -0.3333333333333333, "ci": [-0.6, -0.13333333333333333], "p_value": 1.0, "survives_correction": false, "degenerate": false, "in_correction_family": true}, {"signal": "answer_extraction_audit.gold_yes", "effect": -0.3333333333333333, "ci": [-0.6, -0.13333333333333333], "p_value": 1.0, "survives_correction": false, "degenerate": false, "in_correction_family": true}, {"signal": "selfcheck_consistency.selfcheck_inconsistency", "effect": 0.5, "ci": [0.0, 1.0], "p_value": 1.0, "survives_correction": false, "degenerate": false, "in_correction_family": true}, {"signal": "selfcheck_consistency.selfcheck_worst_sentence", "effect": 0.5, "ci": [0.0, 1.0], "p_value": 1.0, "survives_correction": false, "degenerate": false, "in_correction_family": true}, {"signal": "answer_extraction_audit.gave_up", "effect": null, "ci": null, "p_value": null, "survives_correction": false, "degenerate": true, "in_correction_family": false}, {"signal": "answer_extraction_audit.has_answer_tag", "effect": null, "ci": null, "p_value": null, "survives_correction": false, "degenerate": true, "in_correction_family": false}, {"signal": "answer_extraction_audit.has_output", "effect": null, "ci": null, "p_value": null, "survives_correction": false, "degenerate": true, "in_correction_family": false}, {"signal": "answer_extraction_audit.output_truncated", "effect": null, "ci": null, "p_value": null, "survives_correction": false, "degenerate": true, "in_correction_family": false}, {"signal": "coverage_verification_gap.coverage_gap", "effect": null, "ci": null, "p_value": null, "survives_correction": false, "degenerate": true, "in_correction_family": false}, {"signal": "coverage_verification_gap.n_graded", "effect": null, "ci": null, "p_value": null, "survives_correction": false, "degenerate": true, "in_correction_family": false}, {"signal": "coverage_verification_gap.n_samples", "effect": null, "ci": null, "p_value": null, "survives_correction": false, "degenerate": true, "in_correction_family": false}], "n_in_correction_family": 7, "n_degenerate": 8, "correction_method": "BH", "survivors": ["coverage_verification_gap.n_unique"]}}, "m3": [{"id": "H1", "failure_mode": "answer_extraction", "statement": "Evaluation failures are predominantly caused by strict string normalization in the evaluation harness rejecting verbose responses that append units or parenthetical explanations to otherwise correct answers.", "expected_direction": null}, {"id": "H2", "failure_mode": "selection_failure", "statement": "Model failures on visual queries with low consensus across repeated samples stem from candidate answer dispersion where majority voting drops the correct solution present in the candidate pool.", "expected_direction": null}, {"id": "H3", "failure_mode": "knowledge_gap", "statement": "Genuine visual reasoning failures on fine-grained chart elements represent encoder coverage deficits where the model consistently fails to extract required numeric data across repeated sampling attempts.", "expected_direction": null}], "m4": [{"id": "H1", "failure_mode": "answer_extraction", "status": "inconclusive", "statement": "Evaluation failures are predominantly caused by strict string normalization in the evaluation harness rejecting verbose responses that append units or parenthetical explanations to otherwise correct answers.", "test_name": "signal_label_assoc", "effect": 0.4603174603174603, "ci": [0.031746031746031744, 0.8571428571428571], "evidence_grade": "observational", "underpowered": false}, {"id": "H2", "failure_mode": "selection_failure", "status": "supported", "statement": "Model failures on visual queries with low consensus across repeated samples stem from candidate answer dispersion where majority voting drops the correct solution present in the candidate pool.", "test_name": "signal_label_assoc", "effect": 0.9166666666666666, "ci": [0.75, 1.0], "evidence_grade": "observational", "underpowered": false}, {"id": "H3", "failure_mode": "knowledge_gap", "status": "inconclusive", "statement": "Genuine visual reasoning failures on fine-grained chart elements represent encoder coverage deficits where the model consistently fails to extract required numeric data across repeated sampling attempts.", "test_name": "stats_results", "effect": null, "ci": null, "evidence_grade": "none", "underpowered": null}], "m5": {"ladder": [{"tier": "L1", "label": "Prompt / instructions", "n_candidates": 6, "best_effect": 0.1875, "best_candidate": "strict_minimal_answer", "status": "not_selected", "within_cap": true, "tier_cap": "L2"}, {"tier": "L2", "label": "Scaffold / tools / multi-call", "n_candidates": 9, "best_effect": 0.1875, "best_candidate": "consensus_stripped_vote", "status": "not_selected", "within_cap": true, "tier_cap": "L2"}, {"tier": "L3", "label": "Internals / read & write", "n_candidates": 0, "best_effect": null, "best_candidate": null, "status": "untouched", "within_cap": false, "tier_cap": "L2"}, {"tier": "L4", "label": "Re-training", "n_candidates": 0, "best_effect": null, "best_candidate": null, "status": "untouched", "within_cap": false, "tier_cap": "L2"}], "candidates": [{"name": "visual_grounding", "tier": "L1", "effect": 0.125, "n_fixed": 2, "n_broken": 0, "verdict": "partial", "selected": false}, {"name": "strict_minimal_answer", "tier": "L1", "effect": 0.1875, "n_fixed": 3, "n_broken": 0, "verdict": "partial", "selected": false}, {"name": "read_marks_then_answer", "tier": "L1", "effect": 0.1875, "n_fixed": 4, "n_broken": 1, "verdict": "partial", "selected": false}, {"name": "strip_units_and_parentheses", "tier": "L1", "effect": 0.1875, "n_fixed": 3, "n_broken": 0, "verdict": "partial", "selected": false}, {"name": "scratchpad_isolated_answer", "tier": "L1", "effect": 0.125, "n_fixed": 3, "n_broken": 1, "verdict": "partial", "selected": false}, {"name": "candidate_recheck_then_extract", "tier": "L1", "effect": 0.125, "n_fixed": 2, "n_broken": 0, "verdict": "partial", "selected": false}, {"name": "sharpen_and_verified_clean_answer", "tier": "L2", "effect": -0.4375, "n_fixed": 0, "n_broken": 7, "verdict": "unsafe", "selected": false}, {"name": "upscale_least_to_most_extraction", "tier": "L2", "effect": -0.5, "n_fixed": 0, "n_broken": 8, "verdict": "regressed", "selected": false}, {"name": "contrast_enhanced_self_refined_tag", "tier": "L2", "effect": -0.6875, "n_fixed": 0, "n_broken": 11, "verdict": "regressed", "selected": false}, {"name": "self_consistency_5", "tier": "L2", "effect": 0.0625, "n_fixed": 1, "n_broken": 0, "verdict": "partial", "selected": false}, {"name": "coded_pipeline", "tier": "L2", "effect": 0.125, "n_fixed": 2, "n_broken": 0, "verdict": "partial", "selected": false}, {"name": "bare_value_extractor", "tier": "L2", "effect": 0.125, "n_fixed": 2, "n_broken": 0, "verdict": "partial", "selected": false}, {"name": "boxed_clean_tag", "tier": "L2", "effect": -0.6875, "n_fixed": 0, "n_broken": 11, "verdict": "regressed", "selected": false}, {"name": "consensus_stripped_vote", "tier": "L2", "effect": 0.1875, "n_fixed": 3, "n_broken": 0, "verdict": "partial", "selected": false}, {"name": "coded_pipeline", "tier": "L2", "effect": 0.125, "n_fixed": 2, "n_broken": 0, "verdict": "partial", "selected": false}], "confirmed": [{"name": "strict_minimal_answer", "tier": "L1", "effect": 0.1875, "n_fixed": 3, "n_broken": 0, "verdict": "partial", "selected": false}]}, "repair": null, "validation": null, "example_case": {"case_id": "chartqa-human-365", "split": "explore", "question": "Which color bar represents the highest value in the graph? Answer with only the short answer.", "gold": null, "baseline_output": null, "baseline_answer": null, "label": "fail", "signal": "coverage_verification_gap.n_unique", "signal_values": {"sample_id": "chartqa-human-365", "n_samples": 5, "n_graded": 5, "n_correct": 4, "n_unique": 4, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 0.4, "coverage_gap": 0, "modal_answer": "pink"}, "media_paths": ["media/978a9fba2d8e0f58_chartqa-00365.png"]}, "qa_flags": [{"level": "note", "code": "example_case_from_explore", "detail": "the illustrative case comes from the explore split; its output is the unchanged model's, not a measured repaired result"}]}, "contract": {}, "cases": [{"id": "chartqa-human-445", "status": "pass", "prompt": "In which country the difference between blue and green bar is maximum? Answer with only the short answer.", "expected": ["U.S."], "observed": "U.S.", "choices": [], "tags": [], "task": "", "media_ids": ["media-1"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-86", "status": "fail", "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "expected": ["77"], "observed": "77 and 77 (in 2006)", "choices": [], "tags": [], "task": "", "media_ids": ["media-2"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-45", "status": "pass", "prompt": "What's the average of last three values in green graph (round to one decimal)? Answer with only the short answer.", "expected": ["28.6"], "observed": "28.7", "choices": [], "tags": [], "task": "", "media_ids": ["media-3"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-1122", "status": "pass", "prompt": "Which category the three bars value is above 25% ? Answer with only the short answer.", "expected": ["Russia"], "observed": "Russia", "choices": [], "tags": [], "task": "", "media_ids": ["media-4"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-740", "status": "pass", "prompt": "What state has the 3rd most physicians in 2021? Answer with only the short answer.", "expected": ["Texas"], "observed": "Texas", "choices": [], "tags": [], "task": "", "media_ids": ["media-5"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-89", "status": "fail", "prompt": "What's the ratio(A:B) of yellow bar and blue bar for Ages 18-29? Answer with only the short answer.", "expected": ["1.684722222"], "observed": "20:13", "choices": [], "tags": [], "task": "", "media_ids": ["media-6"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-406", "status": "pass", "prompt": "Is the starting value of China in the graph greater than 40%? Answer with only the short answer.", "expected": ["Yes"], "observed": "Yes", "choices": [], "tags": [], "task": "", "media_ids": ["media-7"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-1195", "status": "fail", "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "expected": ["4.9"], "observed": "4.9 billion British pounds", "choices": [], "tags": [], "task": "", "media_ids": ["media-8"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-1032", "status": "pass", "prompt": "What countries data shown in green color? Answer with only the short answer.", "expected": ["Hungary"], "observed": "Hungary", "choices": [], "tags": [], "task": "", "media_ids": ["media-9"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-325", "status": "pass", "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "expected": ["14153.35"], "observed": "$14,153.35", "choices": [], "tags": [], "task": "", "media_ids": ["media-10"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-365", "status": "fail", "prompt": "Which color bar represents the highest value in the graph? Answer with only the short answer.", "expected": ["Pink"], "observed": "Magenta", "choices": [], "tags": [], "task": "", "media_ids": ["media-11"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-532", "status": "pass", "prompt": "What is the value of the red bar? Answer with only the short answer.", "expected": ["4.2"], "observed": "4.2", "choices": [], "tags": [], "task": "", "media_ids": ["media-12"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-19", "status": "fail", "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "expected": ["No"], "observed": "No (185% is not greater than 233%)", "choices": [], "tags": [], "task": "", "media_ids": ["media-13"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-95", "status": "pass", "prompt": "Which country received the higher Country Programmable aid, Jamaica or Tonga? Answer with only the short answer.", "expected": ["Jamaica"], "observed": "Jamaica", "choices": [], "tags": [], "task": "", "media_ids": ["media-14"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-1107", "status": "pass", "prompt": "What is the value of Hulu? Answer with only the short answer.", "expected": ["9.2"], "observed": "9.2%", "choices": [], "tags": [], "task": "", "media_ids": ["media-15"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-352", "status": "pass", "prompt": "What is represents in the red line bar ? Answer with only the short answer.", "expected": ["Belize"], "observed": "Belize", "choices": [], "tags": [], "task": "", "media_ids": ["media-16"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-228", "status": "pass", "prompt": "Which country has longest bar? Answer with only the short answer.", "expected": ["Lithuania"], "observed": "Lithuania", "choices": [], "tags": [], "task": "", "media_ids": ["media-17"], "trajectory": null, "split": "confirm"}, {"id": "chartqa-human-875", "status": "pass", "prompt": "The highest percent of Not sure minus the smallest percent of Mostly trust gives what Answer with only the short answer.", "expected": ["53"], "observed": "53%", "choices": [], "tags": [], "task": "", "media_ids": ["media-18"], "trajectory": null, "split": "confirm"}, {"id": "chartqa-human-475", "status": "fail", "prompt": "How many 'Very' bars have a value lower than 40? Answer with only the short answer.", "expected": ["1"], "observed": "3", "choices": [], "tags": [], "task": "", "media_ids": ["media-19"], "trajectory": null, "split": "confirm"}, {"id": "chartqa-human-428", "status": "fail", "prompt": "How many countries are shown in the graph? Answer with only the short answer.", "expected": ["3"], "observed": "3 countries are shown in the graph.", "choices": [], "tags": [], "task": "", "media_ids": ["media-20"], "trajectory": null, "split": "confirm"}, {"id": "chartqa-human-799", "status": "pass", "prompt": "What is the value , if we add top 2 bars and bottom 2 bars ? Answer with only the short answer.", "expected": ["93"], "observed": "93", "choices": [], "tags": [], "task": "", "media_ids": ["media-21"], "trajectory": null, "split": "confirm"}, {"id": "chartqa-human-709", "status": "pass", "prompt": "What is the value of the highest point? Answer with only the short answer.", "expected": ["19.7"], "observed": "19.7%", "choices": [], "tags": [], "task": "", "media_ids": ["media-22"], "trajectory": null, "split": "confirm"}, {"id": "chartqa-human-293", "status": "fail", "prompt": "Is the sum of all the last three places is more then Oceania? Answer with only the short answer.", "expected": ["No"], "observed": "Yes", "choices": [], "tags": [], "task": "", "media_ids": ["media-23"], "trajectory": null, "split": "confirm"}, {"id": "chartqa-human-372", "status": "pass", "prompt": "How many countries are included in the chart? Answer with only the short answer.", "expected": ["2"], "observed": "2", "choices": [], "tags": [], "task": "", "media_ids": ["media-24"], "trajectory": null, "split": "confirm"}, {"id": "chartqa-human-576", "status": "pass", "prompt": "Which country does the green line represent? Answer with only the short answer.", "expected": ["Spain"], "observed": "Spain", "choices": [], "tags": [], "task": "", "media_ids": ["media-25"], "trajectory": null, "split": "confirm"}, {"id": "chartqa-human-355", "status": "pass", "prompt": "Which country data below 80% for the last five years ? Answer with only the short answer.", "expected": ["Sudan"], "observed": "Sudan", "choices": [], "tags": [], "task": "", "media_ids": ["media-26"], "trajectory": null, "split": "confirm"}, {"id": "chartqa-human-379", "status": "pass", "prompt": "For how many years is the value of the Philippines lower than the one of Nepal? Answer with only the short answer.", "expected": ["3"], "observed": "3", "choices": [], "tags": [], "task": "", "media_ids": ["media-27"], "trajectory": null, "split": "confirm"}, {"id": "chartqa-human-698", "status": "fail", "prompt": "Which is represented by yellow color? Answer with only the short answer.", "expected": ["Netherlands"], "observed": "Denmark", "choices": [], "tags": [], "task": "", "media_ids": ["media-28"], "trajectory": null, "split": "confirm"}, {"id": "chartqa-human-1142", "status": "fail", "prompt": "Work out the ratio of the bigger segment to the smaller one? Answer with only the short answer.", "expected": ["1.577"], "observed": "153:97", "choices": [], "tags": [], "task": "", "media_ids": ["media-29"], "trajectory": null, "split": "confirm"}, {"id": "chartqa-human-452", "status": "pass", "prompt": "What's the value of the gray bar in Donald Trump category? Answer with only the short answer.", "expected": ["15"], "observed": "15", "choices": [], "tags": [], "task": "", "media_ids": ["media-30"], "trajectory": null, "split": "confirm"}, {"id": "chartqa-human-864", "status": "pass", "prompt": "Which year showed the largest difference in the data points between the two lines Answer with only the short answer.", "expected": ["2019"], "observed": "2019", "choices": [], "tags": [], "task": "", "media_ids": ["media-31"], "trajectory": null, "split": "confirm"}, {"id": "chartqa-human-583", "status": "pass", "prompt": "Which year recorded the highest native born employment in Slovenia? Answer with only the short answer.", "expected": ["2008"], "observed": "2008", "choices": [], "tags": [], "task": "", "media_ids": ["media-32"], "trajectory": null, "split": "confirm"}], "media": [{"id": "media-1", "kind": "image", "path": "media/7c0cc9aa72ae00ec_chartqa-00445.png", "source": "/app/work/data/chartqa/images/chartqa-00445.png"}, {"id": "media-2", "kind": "image", "path": "media/89091ba9c24e6b24_chartqa-00086.png", "source": "/app/work/data/chartqa/images/chartqa-00086.png"}, {"id": "media-3", "kind": "image", "path": "media/4c75d7a421a17eae_chartqa-00045.png", "source": "/app/work/data/chartqa/images/chartqa-00045.png"}, {"id": "media-4", "kind": "image", "path": "media/0a7f5db0a64fdb75_chartqa-01122.png", "source": "/app/work/data/chartqa/images/chartqa-01122.png"}, {"id": "media-5", "kind": "image", "path": "media/aa7b06415a7a9670_chartqa-00740.png", "source": "/app/work/data/chartqa/images/chartqa-00740.png"}, {"id": "media-6", "kind": "image", "path": "media/7126ecf5dd418ef9_chartqa-00089.png", "source": "/app/work/data/chartqa/images/chartqa-00089.png"}, {"id": "media-7", "kind": "image", "path": "media/61f97becb8a35950_chartqa-00406.png", "source": "/app/work/data/chartqa/images/chartqa-00406.png"}, {"id": "media-8", "kind": "image", "path": "media/536b625870ff0138_chartqa-01195.png", "source": "/app/work/data/chartqa/images/chartqa-01195.png"}, {"id": "media-9", "kind": "image", "path": "media/1ed7b4c821a357bc_chartqa-01032.png", "source": "/app/work/data/chartqa/images/chartqa-01032.png"}, {"id": "media-10", "kind": "image", "path": "media/00dacfe9e99200e3_chartqa-00325.png", "source": "/app/work/data/chartqa/images/chartqa-00325.png"}, {"id": "media-11", "kind": "image", "path": "media/978a9fba2d8e0f58_chartqa-00365.png", "source": "/app/work/data/chartqa/images/chartqa-00365.png"}, {"id": "media-12", "kind": "image", "path": "media/a35dd0e402626e87_chartqa-00532.png", "source": "/app/work/data/chartqa/images/chartqa-00532.png"}, {"id": "media-13", "kind": "image", "path": "media/9347ae6d3668c0e1_chartqa-00019.png", "source": "/app/work/data/chartqa/images/chartqa-00019.png"}, {"id": "media-14", "kind": "image", "path": "media/dc07513b41a9945d_chartqa-00095.png", "source": "/app/work/data/chartqa/images/chartqa-00095.png"}, {"id": "media-15", "kind": "image", "path": "media/0449e0c949144823_chartqa-01107.png", "source": "/app/work/data/chartqa/images/chartqa-01107.png"}, {"id": "media-16", "kind": "image", "path": "media/05c8b3414d0d87aa_chartqa-00352.png", "source": "/app/work/data/chartqa/images/chartqa-00352.png"}, {"id": "media-17", "kind": "image", "path": "media/d00227b661563a9a_chartqa-00228.png", "source": "/app/work/data/chartqa/images/chartqa-00228.png"}, {"id": "media-18", "kind": "image", "path": "media/9c045de577046c0a_chartqa-00875.png", "source": "/app/work/data/chartqa/images/chartqa-00875.png"}, {"id": "media-19", "kind": "image", "path": "media/a8a1e6f00f522dbb_chartqa-00475.png", "source": "/app/work/data/chartqa/images/chartqa-00475.png"}, {"id": "media-20", "kind": "image", "path": "media/c9575f259488d12d_chartqa-00428.png", "source": "/app/work/data/chartqa/images/chartqa-00428.png"}, {"id": "media-21", "kind": "image", "path": "media/e5bb0b6d1dbcff8d_chartqa-00799.png", "source": "/app/work/data/chartqa/images/chartqa-00799.png"}, {"id": "media-22", "kind": "image", "path": "media/6d00c2a752880019_chartqa-00709.png", "source": "/app/work/data/chartqa/images/chartqa-00709.png"}, {"id": "media-23", "kind": "image", "path": "media/fb01a6e997c39773_chartqa-00293.png", "source": "/app/work/data/chartqa/images/chartqa-00293.png"}, {"id": "media-24", "kind": "image", "path": "media/970880ffb25c36c6_chartqa-00372.png", "source": "/app/work/data/chartqa/images/chartqa-00372.png"}, {"id": "media-25", "kind": "image", "path": "media/0dcdc117d0691d09_chartqa-00576.png", "source": "/app/work/data/chartqa/images/chartqa-00576.png"}, {"id": "media-26", "kind": "image", "path": "media/b45db7b27e1ec636_chartqa-00355.png", "source": "/app/work/data/chartqa/images/chartqa-00355.png"}, {"id": "media-27", "kind": "image", "path": "media/6db7fc96deb09e04_chartqa-00379.png", "source": "/app/work/data/chartqa/images/chartqa-00379.png"}, {"id": "media-28", "kind": "image", "path": "media/372cbb4f4aac7a99_chartqa-00698.png", "source": "/app/work/data/chartqa/images/chartqa-00698.png"}, {"id": "media-29", "kind": "image", "path": "media/af398fbef42b31e9_chartqa-01142.png", "source": "/app/work/data/chartqa/images/chartqa-01142.png"}, {"id": "media-30", "kind": "image", "path": "media/951b9ca9949f882c_chartqa-00452.png", "source": "/app/work/data/chartqa/images/chartqa-00452.png"}, {"id": "media-31", "kind": "image", "path": "media/942f75d54fe3c75b_chartqa-00864.png", "source": "/app/work/data/chartqa/images/chartqa-00864.png"}, {"id": "media-32", "kind": "image", "path": "media/53149749f771c4fc_chartqa-00583.png", "source": "/app/work/data/chartqa/images/chartqa-00583.png"}], "debug": {"event_count": 196, "events": [{"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 1, "ts": "2026-10-12T17:05:47.528371+00:00", "span_id": "m1.model_call.1", "summary": "case_discovery · generate · 32 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 2, "ts": "2026-10-12T17:05:47.532051+00:00", "span_id": "m1.model_call.2", "summary": "case_discovery · generate · 32 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 3, "ts": "2026-10-12T17:05:47.674746+00:00", "span_id": "m1.model_call.3", "summary": "case_discovery · generate · 32 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 4, "ts": "2026-10-12T17:05:48.374492+00:00", "span_id": "m1.model_call.4", "summary": "case_discovery · generate · 32 cases · 1.9s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 5, "ts": "2026-10-12T17:05:49.078731+00:00", "span_id": "m1.model_call.5", "summary": "case_discovery · generate · 32 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 6, "ts": "2026-10-12T17:05:49.180925+00:00", "span_id": "m1.model_call.6", "summary": "case_discovery · generate · 32 cases · 1.6s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 7, "ts": "2026-10-12T17:05:49.305748+00:00", "span_id": "m1.model_call.7", "summary": "case_discovery · generate · 32 cases · 1.8s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 8, "ts": "2026-10-12T17:05:50.458085+00:00", "span_id": "m1.model_call.8", "summary": "case_discovery · generate · 32 cases · 1.3s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 9, "ts": "2026-10-12T17:05:50.540156+00:00", "span_id": "m1.model_call.9", "summary": "case_discovery · generate · 32 cases · 2.1s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 10, "ts": "2026-10-12T17:05:50.795471+00:00", "span_id": "m1.model_call.10", "summary": "case_discovery · generate · 32 cases · 1.6s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 11, "ts": "2026-10-12T17:05:50.863360+00:00", "span_id": "m1.model_call.11", "summary": "case_discovery · generate · 32 cases · 1.6s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 12, "ts": "2026-10-12T17:05:52.254624+00:00", "span_id": "m1.model_call.12", "summary": "case_discovery · generate · 32 cases · 1.7s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 13, "ts": "2026-10-12T17:05:52.460079+00:00", "span_id": "m1.model_call.13", "summary": "case_discovery · generate · 32 cases · 1.6s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 14, "ts": "2026-10-12T17:05:52.471550+00:00", "span_id": "m1.model_call.14", "summary": "case_discovery · generate · 32 cases · 1.7s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 15, "ts": "2026-10-12T17:05:52.606618+00:00", "span_id": "m1.model_call.15", "summary": "case_discovery · generate · 32 cases · 2.1s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 16, "ts": "2026-10-12T17:05:53.767235+00:00", "span_id": "m1.model_call.16", "summary": "case_discovery · generate · 32 cases · 1.5s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 17, "ts": "2026-10-12T17:05:54.258308+00:00", "span_id": "m1.model_call.17", "summary": "case_discovery · generate · 32 cases · 1.6s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 18, "ts": "2026-10-12T17:05:54.432607+00:00", "span_id": "m1.model_call.18", "summary": "case_discovery · generate · 32 cases · 2.0s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 19, "ts": "2026-10-12T17:05:54.632100+00:00", "span_id": "m1.model_call.19", "summary": "case_discovery · generate · 32 cases · 2.2s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 20, "ts": "2026-10-12T17:05:54.984446+00:00", "span_id": "m1.model_call.20", "summary": "case_discovery · generate · 32 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 21, "ts": "2026-10-12T17:05:56.043288+00:00", "span_id": "m1.model_call.21", "summary": "case_discovery · generate · 32 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 22, "ts": "2026-10-12T17:05:56.082529+00:00", "span_id": "m1.model_call.22", "summary": "case_discovery · generate · 32 cases · 1.8s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 23, "ts": "2026-10-12T17:05:56.622077+00:00", "span_id": "m1.model_call.23", "summary": "case_discovery · generate · 32 cases · 2.2s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 24, "ts": "2026-10-12T17:05:56.710012+00:00", "span_id": "m1.model_call.24", "summary": "case_discovery · generate · 32 cases · 1.7s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 25, "ts": "2026-10-12T17:05:57.314388+00:00", "span_id": "m1.model_call.25", "summary": "case_discovery · generate · 32 cases · 1.3s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 26, "ts": "2026-10-12T17:05:57.466042+00:00", "span_id": "m1.model_call.26", "summary": "case_discovery · generate · 32 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 27, "ts": "2026-10-12T17:05:58.492117+00:00", "span_id": "m1.model_call.27", "summary": "case_discovery · generate · 32 cases · 1.8s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 28, "ts": "2026-10-12T17:05:58.931805+00:00", "span_id": "m1.model_call.28", "summary": "case_discovery · generate · 32 cases · 2.3s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 29, "ts": "2026-10-12T17:05:59.151943+00:00", "span_id": "m1.model_call.29", "summary": "case_discovery · generate · 32 cases · 1.8s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 30, "ts": "2026-10-12T17:06:00.199512+00:00", "span_id": "m1.model_call.30", "summary": "case_discovery · generate · 32 cases · 1.7s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 31, "ts": "2026-10-12T17:06:00.382106+00:00", "span_id": "m1.model_call.31", "summary": "case_discovery · generate · 32 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 32, "ts": "2026-10-12T17:06:00.435807+00:00", "span_id": "m1.model_call.32", "summary": "case_discovery · generate · 32 cases · 3.0s"}, {"event": "run_start", "stage": "RUN", "cycle": null, "event_seq": 33, "ts": "2026-10-12T17:06:00.449307+00:00", "span_id": "run_start", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 34, "ts": "2026-10-12T17:06:00.454457+00:00", "span_id": "run.case_record.34", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 35, "ts": "2026-10-12T17:06:00.457907+00:00", "span_id": "run.case_record.35", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 36, "ts": "2026-10-12T17:06:00.461713+00:00", "span_id": "run.case_record.36", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 37, "ts": "2026-10-12T17:06:00.465939+00:00", "span_id": "run.case_record.37", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 38, "ts": "2026-10-12T17:06:00.470274+00:00", "span_id": "run.case_record.38", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 39, "ts": "2026-10-12T17:06:00.476019+00:00", "span_id": "run.case_record.39", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 40, "ts": "2026-10-12T17:06:00.481224+00:00", "span_id": "run.case_record.40", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 41, "ts": "2026-10-12T17:06:00.486860+00:00", "span_id": "run.case_record.41", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 42, "ts": "2026-10-12T17:06:00.492065+00:00", "span_id": "run.case_record.42", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 43, "ts": "2026-10-12T17:06:00.498870+00:00", "span_id": "run.case_record.43", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 44, "ts": "2026-10-12T17:06:00.503701+00:00", "span_id": "run.case_record.44", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 45, "ts": "2026-10-12T17:06:00.508601+00:00", "span_id": "run.case_record.45", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 46, "ts": "2026-10-12T17:06:00.513932+00:00", "span_id": "run.case_record.46", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 47, "ts": "2026-10-12T17:06:00.519163+00:00", "span_id": "run.case_record.47", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 48, "ts": "2026-10-12T17:06:00.524556+00:00", "span_id": "run.case_record.48", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 49, "ts": "2026-10-12T17:06:00.529834+00:00", "span_id": "run.case_record.49", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 50, "ts": "2026-10-12T17:06:00.535009+00:00", "span_id": "run.case_record.50", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 51, "ts": "2026-10-12T17:06:00.541380+00:00", "span_id": "run.case_record.51", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 52, "ts": "2026-10-12T17:06:00.549109+00:00", "span_id": "run.case_record.52", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 53, "ts": "2026-10-12T17:06:00.554693+00:00", "span_id": "run.case_record.53", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 54, "ts": "2026-10-12T17:06:00.560433+00:00", "span_id": "run.case_record.54", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 55, "ts": "2026-10-12T17:06:00.569233+00:00", "span_id": "run.case_record.55", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 56, "ts": "2026-10-12T17:06:00.575849+00:00", "span_id": "run.case_record.56", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 57, "ts": "2026-10-12T17:06:00.584139+00:00", "span_id": "run.case_record.57", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 58, "ts": "2026-10-12T17:06:00.593740+00:00", "span_id": "run.case_record.58", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 59, "ts": "2026-10-12T17:06:00.601747+00:00", "span_id": "run.case_record.59", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 60, "ts": "2026-10-12T17:06:00.611877+00:00", "span_id": "run.case_record.60", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 61, "ts": "2026-10-12T17:06:00.621469+00:00", "span_id": "run.case_record.61", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 62, "ts": "2026-10-12T17:06:00.630363+00:00", "span_id": "run.case_record.62", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 63, "ts": "2026-10-12T17:06:00.641631+00:00", "span_id": "run.case_record.63", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 64, "ts": "2026-10-12T17:06:00.650082+00:00", "span_id": "run.case_record.64", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 65, "ts": "2026-10-12T17:06:00.658444+00:00", "span_id": "run.case_record.65", "summary": "Recorded pipeline event"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 66, "ts": "2026-10-12T17:06:01.721640+00:00", "span_id": "m1.model_call.66", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 67, "ts": "2026-10-12T17:06:01.798932+00:00", "span_id": "m1.model_call.67", "summary": "selfcheck_consistency · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 68, "ts": "2026-10-12T17:06:02.799736+00:00", "span_id": "m1.model_call.68", "summary": "selfcheck_consistency · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 69, "ts": "2026-10-12T17:06:02.957582+00:00", "span_id": "m1.model_call.69", "summary": "coverage_verification_gap · generate · 16 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 70, "ts": "2026-10-12T17:06:03.965946+00:00", "span_id": "m1.model_call.70", "summary": "selfcheck_consistency · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 71, "ts": "2026-10-12T17:06:04.040460+00:00", "span_id": "m1.model_call.71", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 72, "ts": "2026-10-12T17:06:05.380247+00:00", "span_id": "m1.model_call.72", "summary": "selfcheck_consistency · generate · 16 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 73, "ts": "2026-10-12T17:06:05.614827+00:00", "span_id": "m1.model_call.73", "summary": "coverage_verification_gap · generate · 16 cases · 1.6s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 74, "ts": "2026-10-12T17:06:06.401290+00:00", "span_id": "m1.model_call.74", "summary": "selfcheck_consistency · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 75, "ts": "2026-10-12T17:06:06.638115+00:00", "span_id": "m1.model_call.75", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 76, "ts": "2026-10-12T17:06:07.488622+00:00", "span_id": "m1.model_call.76", "summary": "selfcheck_consistency · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 77, "ts": "2026-10-12T17:06:07.758210+00:00", "span_id": "m1.model_call.77", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 78, "ts": "2026-10-12T17:06:08.533033+00:00", "span_id": "m1.model_call.78", "summary": "selfcheck_consistency · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 79, "ts": "2026-10-12T17:06:09.021776+00:00", "span_id": "m1.model_call.79", "summary": "coverage_verification_gap · generate · 16 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 80, "ts": "2026-10-12T17:06:09.393749+00:00", "span_id": "m1.model_call.80", "summary": "selfcheck_consistency · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 81, "ts": "2026-10-12T17:06:09.952187+00:00", "span_id": "m1.model_call.81", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 82, "ts": "2026-10-12T17:06:10.519267+00:00", "span_id": "m1.model_call.82", "summary": "selfcheck_consistency · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 83, "ts": "2026-10-12T17:06:11.005529+00:00", "span_id": "m1.model_call.83", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 84, "ts": "2026-10-12T17:06:11.651488+00:00", "span_id": "m1.model_call.84", "summary": "selfcheck_consistency · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 85, "ts": "2026-10-12T17:06:12.037117+00:00", "span_id": "m1.model_call.85", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 86, "ts": "2026-10-12T17:06:12.777177+00:00", "span_id": "m1.model_call.86", "summary": "selfcheck_consistency · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 87, "ts": "2026-10-12T17:06:13.006920+00:00", "span_id": "m1.model_call.87", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 88, "ts": "2026-10-12T17:06:14.026651+00:00", "span_id": "m1.model_call.88", "summary": "selfcheck_consistency · generate · 16 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 89, "ts": "2026-10-12T17:06:14.042962+00:00", "span_id": "m1.model_call.89", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 90, "ts": "2026-10-12T17:06:14.958653+00:00", "span_id": "m1.model_call.90", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 91, "ts": "2026-10-12T17:06:15.107717+00:00", "span_id": "m1.model_call.91", "summary": "selfcheck_consistency · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 92, "ts": "2026-10-12T17:06:15.980557+00:00", "span_id": "m1.model_call.92", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 93, "ts": "2026-10-12T17:06:16.200668+00:00", "span_id": "m1.model_call.93", "summary": "selfcheck_consistency · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 94, "ts": "2026-10-12T17:06:17.617002+00:00", "span_id": "m1.model_call.94", "summary": "selfcheck_consistency · generate · 16 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 95, "ts": "2026-10-12T17:06:18.080573+00:00", "span_id": "m1.model_call.95", "summary": "coverage_verification_gap · generate · 16 cases · 2.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 96, "ts": "2026-10-12T17:06:19.117831+00:00", "span_id": "m1.model_call.96", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 97, "ts": "2026-10-12T17:06:19.163102+00:00", "span_id": "m1.model_call.97", "summary": "selfcheck_consistency · generate · 16 cases · 1.5s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 98, "ts": "2026-10-12T17:06:20.151814+00:00", "span_id": "m1.model_call.98", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 99, "ts": "2026-10-12T17:06:21.971987+00:00", "span_id": "m1.model_call.99", "summary": "coverage_verification_gap · generate · 16 cases · 1.8s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 100, "ts": "2026-10-12T17:06:22.859605+00:00", "span_id": "m1.model_call.100", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 101, "ts": "2026-10-12T17:06:23.962308+00:00", "span_id": "m1.model_call.101", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 102, "ts": "2026-10-12T17:06:24.934472+00:00", "span_id": "m1.model_call.102", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 103, "ts": "2026-10-12T17:06:26.391852+00:00", "span_id": "m1.model_call.103", "summary": "coverage_verification_gap · generate · 16 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 104, "ts": "2026-10-12T17:06:27.460708+00:00", "span_id": "m1.model_call.104", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 105, "ts": "2026-10-12T17:06:28.617524+00:00", "span_id": "m1.model_call.105", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 106, "ts": "2026-10-12T17:06:30.003967+00:00", "span_id": "m1.model_call.106", "summary": "coverage_verification_gap · generate · 16 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 107, "ts": "2026-10-12T17:06:30.933920+00:00", "span_id": "m1.model_call.107", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 108, "ts": "2026-10-12T17:06:32.003639+00:00", "span_id": "m1.model_call.108", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 109, "ts": "2026-10-12T17:06:32.948963+00:00", "span_id": "m1.model_call.109", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 110, "ts": "2026-10-12T17:06:34.048443+00:00", "span_id": "m1.model_call.110", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 111, "ts": "2026-10-12T17:06:35.130180+00:00", "span_id": "m1.model_call.111", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 112, "ts": "2026-10-12T17:06:36.264428+00:00", "span_id": "m1.model_call.112", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 113, "ts": "2026-10-12T17:06:37.360629+00:00", "span_id": "m1.model_call.113", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 114, "ts": "2026-10-12T17:06:38.199568+00:00", "span_id": "m1.model_call.114", "summary": "coverage_verification_gap · generate · 16 cases · 0.8s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 115, "ts": "2026-10-12T17:06:39.830217+00:00", "span_id": "m1.model_call.115", "summary": "coverage_verification_gap · generate · 16 cases · 1.6s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 116, "ts": "2026-10-12T17:06:40.646914+00:00", "span_id": "m1.model_call.116", "summary": "coverage_verification_gap · generate · 16 cases · 0.8s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 117, "ts": "2026-10-12T17:06:41.862511+00:00", "span_id": "m1.model_call.117", "summary": "coverage_verification_gap · generate · 16 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 118, "ts": "2026-10-12T17:06:42.998581+00:00", "span_id": "m1.model_call.118", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 119, "ts": "2026-10-12T17:06:43.984581+00:00", "span_id": "m1.model_call.119", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 120, "ts": "2026-10-12T17:06:45.186322+00:00", "span_id": "m1.model_call.120", "summary": "coverage_verification_gap · generate · 16 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 121, "ts": "2026-10-12T17:06:46.269546+00:00", "span_id": "m1.model_call.121", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 122, "ts": "2026-10-12T17:06:47.387140+00:00", "span_id": "m1.model_call.122", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 123, "ts": "2026-10-12T17:06:48.400427+00:00", "span_id": "m1.model_call.123", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 124, "ts": "2026-10-12T17:06:49.377619+00:00", "span_id": "m1.model_call.124", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 125, "ts": "2026-10-12T17:06:50.531403+00:00", "span_id": "m1.model_call.125", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 126, "ts": "2026-10-12T17:06:51.928716+00:00", "span_id": "m1.model_call.126", "summary": "coverage_verification_gap · generate · 16 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 127, "ts": "2026-10-12T17:06:53.058776+00:00", "span_id": "m1.model_call.127", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 128, "ts": "2026-10-12T17:06:54.144625+00:00", "span_id": "m1.model_call.128", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 129, "ts": "2026-10-12T17:06:55.559213+00:00", "span_id": "m1.model_call.129", "summary": "coverage_verification_gap · generate · 16 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 130, "ts": "2026-10-12T17:06:56.933614+00:00", "span_id": "m1.model_call.130", "summary": "coverage_verification_gap · generate · 16 cases · 1.3s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 131, "ts": "2026-10-12T17:06:57.959218+00:00", "span_id": "m1.model_call.131", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 132, "ts": "2026-10-12T17:06:58.963529+00:00", "span_id": "m1.model_call.132", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 133, "ts": "2026-10-12T17:06:59.996189+00:00", "span_id": "m1.model_call.133", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 134, "ts": "2026-10-12T17:07:01.230745+00:00", "span_id": "m1.model_call.134", "summary": "coverage_verification_gap · generate · 16 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 135, "ts": "2026-10-12T17:07:02.336988+00:00", "span_id": "m1.model_call.135", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 136, "ts": "2026-10-12T17:07:03.324826+00:00", "span_id": "m1.model_call.136", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 137, "ts": "2026-10-12T17:07:04.322035+00:00", "span_id": "m1.model_call.137", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 138, "ts": "2026-10-12T17:07:05.905176+00:00", "span_id": "m1.model_call.138", "summary": "coverage_verification_gap · generate · 16 cases · 1.5s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 139, "ts": "2026-10-12T17:07:07.091899+00:00", "span_id": "m1.model_call.139", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 140, "ts": "2026-10-12T17:07:08.332099+00:00", "span_id": "m1.model_call.140", "summary": "coverage_verification_gap · generate · 16 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 141, "ts": "2026-10-12T17:07:09.887857+00:00", "span_id": "m1.model_call.141", "summary": "coverage_verification_gap · generate · 16 cases · 1.5s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 142, "ts": "2026-10-12T17:07:10.965214+00:00", "span_id": "m1.model_call.142", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 143, "ts": "2026-10-12T17:07:11.998667+00:00", "span_id": "m1.model_call.143", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 144, "ts": "2026-10-12T17:07:13.114857+00:00", "span_id": "m1.model_call.144", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 145, "ts": "2026-10-12T17:07:14.144542+00:00", "span_id": "m1.model_call.145", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 146, "ts": "2026-10-12T17:07:15.466515+00:00", "span_id": "m1.model_call.146", "summary": "coverage_verification_gap · generate · 16 cases · 1.3s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 147, "ts": "2026-10-12T17:07:16.591232+00:00", "span_id": "m1.model_call.147", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 148, "ts": "2026-10-12T17:07:17.751351+00:00", "span_id": "m1.model_call.148", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 149, "ts": "2026-10-12T17:07:19.158435+00:00", "span_id": "m1.model_call.149", "summary": "coverage_verification_gap · generate · 16 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 150, "ts": "2026-10-12T17:07:20.930327+00:00", "span_id": "m1.model_call.150", "summary": "coverage_verification_gap · generate · 16 cases · 1.8s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 151, "ts": "2026-10-12T17:07:21.863470+00:00", "span_id": "m1.model_call.151", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 152, "ts": "2026-10-12T17:07:22.849215+00:00", "span_id": "m1.model_call.152", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 153, "ts": "2026-10-12T17:07:23.878871+00:00", "span_id": "m1.model_call.153", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 154, "ts": "2026-10-12T17:07:24.961399+00:00", "span_id": "m1.model_call.154", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 155, "ts": "2026-10-12T17:07:25.864704+00:00", "span_id": "m1.model_call.155", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 156, "ts": "2026-10-12T17:07:26.751689+00:00", "span_id": "m1.model_call.156", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 157, "ts": "2026-10-12T17:07:27.929224+00:00", "span_id": "m1.model_call.157", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 158, "ts": "2026-10-12T17:07:28.949975+00:00", "span_id": "m1.model_call.158", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 159, "ts": "2026-10-12T17:07:30.144724+00:00", "span_id": "m1.model_call.159", "summary": "coverage_verification_gap · generate · 16 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 160, "ts": "2026-10-12T17:07:31.493928+00:00", "span_id": "m1.model_call.160", "summary": "coverage_verification_gap · generate · 16 cases · 1.3s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 161, "ts": "2026-10-12T17:07:32.436325+00:00", "span_id": "m1.model_call.161", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "probe", "stage": "M1", "cycle": 0, "event_seq": 162, "ts": "2026-10-12T17:07:32.482260+00:00", "span_id": "c0.m1", "summary": "Selected 3 analyzer(s) (answer_extraction_audit, selfcheck_consistency, coverage_verification_gap) by capability matching."}, {"event": "explore", "stage": "M2", "cycle": 0, "event_seq": 163, "ts": "2026-10-12T17:08:52.969339+00:00", "span_id": "c0.explore", "summary": "Recorded pipeline event"}, {"event": "model_call", "stage": "M2", "cycle": 0, "event_seq": 164, "ts": "2026-10-12T17:08:52.978771+00:00", "span_id": "m2.model_call.164", "summary": "explore_cli_coder · write_code · 76.6s"}, {"event": "analysis", "stage": "M2", "cycle": 0, "event_seq": 165, "ts": "2026-10-12T17:09:04.471841+00:00", "span_id": "c0.m2", "summary": "The evaluation harness is incorrectly marking correct model answers as failures because the model includes conversational context or explanatory units alongside its answers, while genuine model errors stem from a lack of visual coverage rather than selection mistakes. Specificall"}, {"event": "model_call", "stage": "M2", "cycle": 0, "event_seq": 166, "ts": "2026-10-12T17:09:04.519793+00:00", "span_id": "m2.model_call.166", "summary": "statistics_judge · generate · 11.5s"}, {"event": "diagnosis", "stage": "M3", "cycle": 0, "event_seq": 167, "ts": "2026-10-12T17:09:15.252184+00:00", "span_id": "c0.m3", "summary": "Recorded pipeline event"}, {"event": "model_call", "stage": "M3", "cycle": 0, "event_seq": 168, "ts": "2026-10-12T17:09:15.257522+00:00", "span_id": "m3.model_call.168", "summary": "diagnosis_judge · generate · 5.6s"}, {"event": "model_call", "stage": "M3", "cycle": 0, "event_seq": 169, "ts": "2026-10-12T17:09:15.291478+00:00", "span_id": "m3.model_call.169", "summary": "hypothesis_critic · generate · 5.1s"}, {"event": "surgery", "stage": "M4", "cycle": 0, "event_seq": 170, "ts": "2026-10-12T17:09:28.608592+00:00", "span_id": "c0.m4", "summary": "inconclusive"}, {"event": "model_call", "stage": "M4", "cycle": 0, "event_seq": 171, "ts": "2026-10-12T17:09:28.611802+00:00", "span_id": "m4.model_call.171", "summary": "protocol_consistency_judge · generate · 13.3s"}, {"event": "surgery", "stage": "M4", "cycle": 0, "event_seq": 172, "ts": "2026-10-12T17:09:28.641613+00:00", "span_id": "c0.m4", "summary": "supported"}, {"event": "model_call", "stage": "M4", "cycle": 0, "event_seq": 173, "ts": "2026-10-12T17:09:28.644943+00:00", "span_id": "m4.model_call.173", "summary": "protocol_consistency_judge · generate · 13.3s"}, {"event": "surgery", "stage": "M4", "cycle": 0, "event_seq": 174, "ts": "2026-10-12T17:09:28.648167+00:00", "span_id": "c0.m4", "summary": "inconclusive"}, {"event": "model_call", "stage": "M4", "cycle": 0, "event_seq": 175, "ts": "2026-10-12T17:09:28.650889+00:00", "span_id": "m4.model_call.175", "summary": "protocol_consistency_judge · generate · 13.3s"}, {"event": "loop_end", "stage": "RUN", "cycle": null, "event_seq": 176, "ts": "2026-10-12T17:09:28.655438+00:00", "span_id": "run.loop_end.176", "summary": "criteria_met"}, {"event": "diagnose_report", "stage": "RUN", "cycle": null, "event_seq": 177, "ts": "2026-10-12T17:09:28.660355+00:00", "span_id": "run.diagnose_report.177", "summary": "criteria_met"}, {"event": "experiment", "stage": "M5", "cycle": -1, "event_seq": 178, "ts": "2026-10-12T17:09:44.130774+00:00", "span_id": "m5.experiment.178", "summary": "inconclusive"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 179, "ts": "2026-10-12T17:09:44.133300+00:00", "span_id": "m5.model_call.179", "summary": "experiment_coder · cli:antigravity · 15.4s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 180, "ts": "2026-10-12T17:16:49.312251+00:00", "span_id": "m5.model_call.180", "summary": "target_model · template_candidate · 0.9s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 181, "ts": "2026-10-12T17:16:49.509915+00:00", "span_id": "m5.model_call.181", "summary": "target_model · template_candidate · 1.1s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 182, "ts": "2026-10-12T17:16:49.538106+00:00", "span_id": "m5.model_call.182", "summary": "target_model · template_candidate · 1.1s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 183, "ts": "2026-10-12T17:16:49.764570+00:00", "span_id": "m5.model_call.183", "summary": "target_model · template_candidate · 1.4s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 184, "ts": "2026-10-12T17:16:50.408545+00:00", "span_id": "m5.model_call.184", "summary": "target_model · template_candidate · 1.1s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 185, "ts": "2026-10-12T17:16:50.535527+00:00", "span_id": "m5.model_call.185", "summary": "target_model · template_candidate · 1.0s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 186, "ts": "2026-10-12T17:16:50.537501+00:00", "span_id": "m5.model_call.186", "summary": "target_model · template_candidate · 1.0s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 187, "ts": "2026-10-12T17:16:51.209855+00:00", "span_id": "m5.model_call.187", "summary": "target_model · template_candidate · 1.4s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 188, "ts": "2026-10-12T17:16:51.442355+00:00", "span_id": "m5.model_call.188", "summary": "target_model · template_candidate · 1.0s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 189, "ts": "2026-10-12T17:16:51.725617+00:00", "span_id": "m5.model_call.189", "summary": "target_model · template_candidate · 1.2s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 190, "ts": "2026-10-12T17:16:52.247358+00:00", "span_id": "m5.model_call.190", "summary": "target_model · template_candidate · 1.0s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 191, "ts": "2026-10-12T17:16:52.387486+00:00", "span_id": "m5.model_call.191", "summary": "target_model · template_candidate · 1.8s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 192, "ts": "2026-10-12T17:16:52.542706+00:00", "span_id": "m5.model_call.192", "summary": "target_model · template_candidate · 1.1s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 193, "ts": "2026-10-12T17:16:52.900726+00:00", "span_id": "m5.model_call.193", "summary": "target_model · template_candidate · 1.1s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 194, "ts": "2026-10-12T17:16:53.103762+00:00", "span_id": "m5.model_call.194", "summary": "target_model · template_candidate · 0.8s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 195, "ts": "2026-10-12T17:16:53.531741+00:00", "span_id": "m5.model_call.195", "summary": "target_model · template_candidate · 1.1s"}, {"event": "fix", "stage": "M5", "cycle": -1, "event_seq": 196, "ts": "2026-10-12T17:16:53.636209+00:00", "span_id": "fix", "summary": "Recorded pipeline event"}]}}, "layout": {"spec": {"root": "page", "elements": {"page": {"type": "ReportPage", "props": {}, "children": ["setting", "metrics", "loop", "evidence"]}, "setting": {"type": "SettingHero", "props": {}}, "metrics": {"type": "MetricStrip", "props": {}}, "evidence": {"type": "EvidenceIndex", "props": {}}, "loop": {"type": "LoopFigure", "props": {}}}}, "generated_by": {"mode": "deterministic", "model": null}}} \ No newline at end of file +{"data": {"version": 23, "trace_id": "a9822626-af4d-43ea-b5cc-486232b73048", "source_event_seq": 197, "generated_at": "FIXED", "setting": {"model": "gemini-3.6-flash", "dataset": "ChartQA (Chart Visual Reasoning)", "kind": "loop", "question": "Evaluate a vision-language model (gemini-3.6-flash, spec gemini-3.6-flash = api:gemini-3.6-flash) on the human-authored ChartQA test split. Questions require reading chart marks and labels, comparing quantities, and performing arithmetic or logical reasoning. Diagnose whether errors reflect answer extraction, unstable visual evidence, or failure to verify a candidate answer.", "protocol": "Evaluate a vision-language model (gemini-3.6-flash, spec gemini-3.6-flash = api:gemini-3.6-flash) on the human-authored ChartQA test split. Questions require reading chart marks and labels, comparing quantities, and performing arithmetic or logical reasoning. Diagnose whether errors reflect answer extraction, unstable visual evidence, or failure to verify a candidate answer.", "diagnosed_by": "Antigravity · gemini-3.6-flash", "finished": true, "last_event_at": "2026-10-12T17:16:53.636209+00:00", "hero_image": "", "n_cases": 16, "partitions": [{"split": "explore", "code": "E", "label": "Explore", "n": 16, "role": "M1-M3 mined patterns and hypotheses here. Anything measured on these cases is a lead, not a verdict."}, {"split": "confirm", "code": "H/C", "label": "Held-out / Confirm", "n": 16, "role": "Withheld from M1-M3. M4 adjudicated the hypotheses here and the repair was scored on these same cases: one withheld pool serving as both the held-out and the confirm set."}]}, "summary": {"headline": "A possible explanation was checked on new cases.", "answer": "This report separates observed patterns from independently checked results.", "confidence": "Independently checked", "stopped_by": "criteria_met"}, "metrics": [{"id": "evaluated", "label": "Cases evaluated", "value": 16}, {"id": "failed", "label": "Initial failures", "value": 5}, {"id": "verified", "label": "Mechanisms checked", "value": 3}, {"id": "fixed", "label": "Cases repaired", "value": 3}], "stages": [{"id": "m1", "code": "M1", "title": "Check behavior", "purpose": "See what the model does differently when it succeeds or fails", "status": "completed", "evidence_count": 3}, {"id": "m2", "code": "M2", "title": "Find patterns", "purpose": "Look for behaviors that reliably appear alongside errors", "status": "completed", "evidence_count": 20}, {"id": "m3", "code": "M3", "title": "Suggest causes", "purpose": "Turn the strongest patterns into ideas that can be tested", "status": "completed", "evidence_count": 3}, {"id": "m4", "code": "M4", "title": "Test on new cases", "purpose": "Check those ideas on evidence not used to create them", "status": "completed", "evidence_count": 3}, {"id": "m5", "code": "M5", "title": "Try repairs", "purpose": "Compare possible fixes with the unchanged model", "status": "no-improvement", "evidence_count": 15}], "findings": [{"id": "finding-1", "title": "Verification sample disagreement", "summary": "Flags cases where repeated samples failed to reach unanimous agreement, indicating visual ambiguity or reasoning instability.", "why_it_matters": "", "evidence_level": "Independently checked", "limitation": "Interpret alongside the independent-check details."}, {"id": "finding-2", "title": "Verbose extraction output", "summary": "Flags cases where the model output exceeds 8 characters, indicative of rambling explanations rather than extracted chart values.", "why_it_matters": "", "evidence_level": "Independently checked", "limitation": "Interpret alongside the independent-check details."}], "charts": [{"id": "outcomes", "kind": "donut", "title": "Evaluation outcomes", "series": [{"label": "Pass", "value": 11}, {"label": "Fail", "value": 5}]}, {"id": "effects", "kind": "bar", "title": "Which behaviors appear most connected to errors?", "subtitle": "A larger bar means a stronger observed pattern. It does not prove the behavior caused the error.", "series": [{"label": "Can repeated attempts ever find the right answer? — N unique", "raw_label": "coverage_verification_gap.n_unique", "value": 0.9166666666666666, "highlight": true}, {"label": "Does the model contradict itself? — Number of answer sentences checked", "raw_label": "selfcheck_consistency.n_sentences", "value": 0.5833333333333334, "highlight": true}, {"label": "Did the model give a usable answer? — Length of the model answer", "raw_label": "answer_extraction_audit.output_chars", "value": 0.4603174603174603, "highlight": true}, {"label": "Did the model give a usable answer? — Answered yes", "raw_label": "answer_extraction_audit.answered_yes", "value": -0.3333333333333333, "highlight": true}, {"label": "Did the model give a usable answer? — Gold yes", "raw_label": "answer_extraction_audit.gold_yes", "value": -0.3333333333333333, "highlight": true}, {"label": "Does the model contradict itself? — Selfcheck inconsistency", "raw_label": "selfcheck_consistency.selfcheck_inconsistency", "value": 0.5, "highlight": false}, {"label": "Does the model contradict itself? — Selfcheck worst sentence", "raw_label": "selfcheck_consistency.selfcheck_worst_sentence", "value": 0.5, "highlight": false}, {"label": "Can repeated attempts ever find the right answer? — N unique", "raw_label": "coverage_verification_gap.n_unique", "value": 0.3667, "highlight": false}]}], "repairs": [{"id": "repair-1", "fixed": false, "title": "strict_minimal_answer", "effect": 0.1875, "fixed_cases": 3, "broken_cases": 0}], "stage_detail": {"m1": {"duration": 91.815, "probes": [{"id": "answer_extraction_audit", "title": "Did the model give a usable answer?", "display_name": "Answer Extraction Audit", "raw_name": "answer_extraction_audit", "question": "Did the model actually answer wrong, or did our parser fail to extract its response?", "description": "Checks whether formatting quirks (e.g. missing tags, preamble chatter) prevented the parser from extracting the answer even when the model understood the problem.", "n_cases": 16, "metrics": [{"label": "Extraction Failure Rate on Errors", "value": "60.0%"}, {"label": "Missing Format Tag Rate", "value": "100.0%"}], "finding_summary": {"N cases": 16, "N gradable": 16, "N labelled fail": 5, "N extraction suspect": 3, "Suspect rate": 0.6, "N reasked": 0, "N reask confirmed": null, "N extraction point miss": 0, "Missing tag rate": 1.0, "Caveat": "suspect_rate is the fraction of FAIL cases whose gold answer sits in the ANSWER REGION of the output (tail window or a tagged/boxed span) — HARNESS failures wearing a model-failure label. gold_in_output is the loose upper bound and over-counts: it fires on a gold that only appears as an intermediate quantity, so never read it as the suspect rate. Above ~5% the labels feeding M2 are contaminated and every other probe's correlations should be re-read after fixing extraction (or after dropping extraction_suspect==1 cases). This probe is OBSERVATIONAL by default: it re-reads stored outputs and introduces no new sampling. With reask=True the reask_* columns are interventional and must be re-run for held-out confirmation. On yes/no (true/false) tasks answered_yes and gold_yes are the answer's and the gold's DIRECTION, two separate marginals (not re-grades): a directional hypothesis is tested on them, e.g. answered_yes HIGHER on failing cases."}, "raw_finding_summary": {"n_cases": 16, "n_gradable": 16, "n_labelled_fail": 5, "n_extraction_suspect": 3, "suspect_rate": 0.6, "n_reasked": 0, "n_reask_confirmed": null, "n_extraction_point_miss": 0, "missing_tag_rate": 1.0, "_caveat": "suspect_rate is the fraction of FAIL cases whose gold answer sits in the ANSWER REGION of the output (tail window or a tagged/boxed span) — HARNESS failures wearing a model-failure label. gold_in_output is the loose upper bound and over-counts: it fires on a gold that only appears as an intermediate quantity, so never read it as the suspect rate. Above ~5% the labels feeding M2 are contaminated and every other probe's correlations should be re-read after fixing extraction (or after dropping extraction_suspect==1 cases). This probe is OBSERVATIONAL by default: it re-reads stored outputs and introduces no new sampling. With reask=True the reask_* columns are interventional and must be re-run for held-out confirmation. On yes/no (true/false) tasks answered_yes and gold_yes are the answer's and the gold's DIRECTION, two separate marginals (not re-grades): a directional hypothesis is tested on them, e.g. answered_yes HIGHER on failing cases."}, "sample_rows": [{"sample_id": "chartqa-human-445", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 4, "labelled_fail": 0, "strict_match": 1, "gold_in_output": 1, "gold_in_answer_region": 1, "extracted_answer": "U.S.", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 0}, {"sample_id": "chartqa-human-86", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 19, "labelled_fail": 1, "strict_match": 1, "gold_in_output": 1, "gold_in_answer_region": 1, "extracted_answer": "77 and 77 (in 2006)", "extraction_suspect": 1, "extraction_point_miss": 0, "label_disagrees": 1}, {"sample_id": "chartqa-human-45", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 4, "labelled_fail": 0, "strict_match": 0, "gold_in_output": 0, "gold_in_answer_region": 0, "extracted_answer": "28.7", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 1}, {"sample_id": "chartqa-human-1122", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 6, "labelled_fail": 0, "strict_match": 1, "gold_in_output": 1, "gold_in_answer_region": 1, "extracted_answer": "Russia", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 0}, {"sample_id": "chartqa-human-740", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 5, "labelled_fail": 0, "strict_match": 1, "gold_in_output": 1, "gold_in_answer_region": 1, "extracted_answer": "Texas", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 0}, {"sample_id": "chartqa-human-89", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 5, "labelled_fail": 1, "strict_match": 0, "gold_in_output": 0, "gold_in_answer_region": 0, "extracted_answer": "20:13", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 0}, {"sample_id": "chartqa-human-406", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 3, "labelled_fail": 0, "strict_match": 1, "gold_in_output": 1, "gold_in_answer_region": 1, "extracted_answer": "Yes", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 0, "gold_yes": 1, "answered_yes": 1}, {"sample_id": "chartqa-human-1195", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 26, "labelled_fail": 1, "strict_match": 1, "gold_in_output": 1, "gold_in_answer_region": 1, "extracted_answer": "4.9 billion British pounds", "extraction_suspect": 1, "extraction_point_miss": 0, "label_disagrees": 1}, {"sample_id": "chartqa-human-1032", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 7, "labelled_fail": 0, "strict_match": 1, "gold_in_output": 1, "gold_in_answer_region": 1, "extracted_answer": "Hungary", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 0}, {"sample_id": "chartqa-human-325", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 10, "labelled_fail": 0, "strict_match": 1, "gold_in_output": 1, "gold_in_answer_region": 1, "extracted_answer": "$14,153.35", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 0}, {"sample_id": "chartqa-human-365", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 7, "labelled_fail": 1, "strict_match": 0, "gold_in_output": 0, "gold_in_answer_region": 0, "extracted_answer": "Magenta", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 0}, {"sample_id": "chartqa-human-532", "has_output": 1, "has_answer_tag": 0, "output_truncated": 0, "gave_up": 0, "output_chars": 3, "labelled_fail": 0, "strict_match": 1, "gold_in_output": 1, "gold_in_answer_region": 1, "extracted_answer": "4.2", "extraction_suspect": 0, "extraction_point_miss": 0, "label_disagrees": 0}], "n_sample_rows": 16}, {"id": "selfcheck_consistency", "title": "Does the model contradict itself?", "display_name": "Self-Contradiction Detection", "raw_name": "selfcheck_consistency", "question": "Does the model contradict its own claims across repeat samplings?", "description": "Probes whether the model generates assertions in one sample that directly contradict its claims in another sample.", "n_cases": 16, "metrics": [{"label": "Self-Contradiction Index", "value": "0.402"}], "finding_summary": {"N cases": 16, "N samples": 4, "Degenerate sampling": false, "Gen kwargs": {"temperature": 1.0}, "Mean inconsistency": 0.4018, "Caveat": "Unigram-containment proxy for SelfCheckGPT (no NLI model): paraphrases inflate the score, verbatim repetition of a wrong fact deflates it. Requires stochastic sampling — with temperature 0 the resamples repeat one greedy generation and the column degenerates to baseline-vs-greedy disagreement (degenerate_sampling flags this). selfcheck_inconsistency / selfcheck_worst_sentence are numeric M2 columns; treat them as signals to correlate with the outcome label, never as a hallucination verdict."}, "raw_finding_summary": {"n_cases": 16, "n_samples": 4, "degenerate_sampling": false, "gen_kwargs": {"temperature": 1.0}, "mean_inconsistency": 0.4018, "_caveat": "Unigram-containment proxy for SelfCheckGPT (no NLI model): paraphrases inflate the score, verbatim repetition of a wrong fact deflates it. Requires stochastic sampling — with temperature 0 the resamples repeat one greedy generation and the column degenerates to baseline-vs-greedy disagreement (degenerate_sampling flags this). selfcheck_inconsistency / selfcheck_worst_sentence are numeric M2 columns; treat them as signals to correlate with the outcome label, never as a hallucination verdict."}, "sample_rows": [{"sample_id": "chartqa-human-445", "baseline_from": "observed", "n_sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}, {"sample_id": "chartqa-human-86", "baseline_from": "observed", "n_sentences": 1, "selfcheck_inconsistency": 0.75, "selfcheck_worst_sentence": 0.75, "worst_sentence_text": "77 and 77 (in 2006)"}, {"sample_id": "chartqa-human-45", "baseline_from": "observed", "n_sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}, {"sample_id": "chartqa-human-1122", "baseline_from": "observed", "n_sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}, {"sample_id": "chartqa-human-740", "baseline_from": "observed", "n_sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}, {"sample_id": "chartqa-human-89", "baseline_from": "observed", "n_sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}, {"sample_id": "chartqa-human-406", "baseline_from": "observed", "n_sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}, {"sample_id": "chartqa-human-1195", "baseline_from": "observed", "n_sentences": 1, "selfcheck_inconsistency": 0.0, "selfcheck_worst_sentence": 0.0, "worst_sentence_text": "4.9 billion British pounds"}, {"sample_id": "chartqa-human-1032", "baseline_from": "observed", "n_sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}, {"sample_id": "chartqa-human-325", "baseline_from": "observed", "n_sentences": 1, "selfcheck_inconsistency": 0.0, "selfcheck_worst_sentence": 0.0, "worst_sentence_text": "$14,153.35"}, {"sample_id": "chartqa-human-365", "baseline_from": "observed", "n_sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}, {"sample_id": "chartqa-human-532", "baseline_from": "observed", "n_sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}], "n_sample_rows": 16}, {"id": "coverage_verification_gap", "title": "Can repeated attempts ever find the right answer?", "display_name": "Pass@k Knowledge Blindspot (Coverage)", "raw_name": "coverage_verification_gap", "question": "Over 5 repeat attempts, does the model ever produce the right answer even once?", "description": "Samples temperature completions k=5 times. If pass@5 is 0%, the capability is completely missing from weights; if pass@5 is high but greedy fails, the model suffers from search/ranking misalignment.", "n_cases": 16, "metrics": [{"label": "Persistent Failure Rate (0/5 correct)", "value": "12.5%"}, {"label": "Pass@5 Coverage Rate", "value": "87.5%"}], "finding_summary": {"N cases": 16, "N scored": 16, "K": 5, "Mean pass at k": 0.875, "Mean majority correct": 0.875, "Coverage gap rate": 0.0, "Mean verify correct": null, "No coverage rate": 0.125, "Degenerate sampling": false, "Caveat": "coverage_gap = 'the answer was in the pool, the vote missed it' ⇒ a selection defect, fixable at L1/L2 with a verifier or reranker. no_coverage_rate = 'never produced once in k' ⇒ a capability defect no scaffold reaches; do not let a headline pass@k hide which of the two dominates. REQUIRES sampling: degenerate_sampling=true means every sample was identical (temperature 0 or a deterministic backend) and the gap is structurally zero, not measured. pass_at_k here uses the unbiased estimator over exactly k draws, so with k small its variance is large per case — read the batch rate. INTERVENTIONAL: held-out confirmation must re-sample."}, "raw_finding_summary": {"n_cases": 16, "n_scored": 16, "k": 5, "mean_pass_at_k": 0.875, "mean_majority_correct": 0.875, "coverage_gap_rate": 0.0, "mean_verify_correct": null, "no_coverage_rate": 0.125, "degenerate_sampling": false, "_caveat": "coverage_gap = 'the answer was in the pool, the vote missed it' ⇒ a selection defect, fixable at L1/L2 with a verifier or reranker. no_coverage_rate = 'never produced once in k' ⇒ a capability defect no scaffold reaches; do not let a headline pass@k hide which of the two dominates. REQUIRES sampling: degenerate_sampling=true means every sample was identical (temperature 0 or a deterministic backend) and the gap is structurally zero, not measured. pass_at_k here uses the unbiased estimator over exactly k draws, so with k small its variance is large per case — read the batch rate. INTERVENTIONAL: held-out confirmation must re-sample."}, "sample_rows": [{"sample_id": "chartqa-human-445", "n_samples": 5, "n_graded": 5, "n_correct": 5, "n_unique": 1, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 1.0, "coverage_gap": 0, "modal_answer": "u.s"}, {"sample_id": "chartqa-human-86", "n_samples": 5, "n_graded": 5, "n_correct": 5, "n_unique": 3, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 0.4, "coverage_gap": 0, "modal_answer": "77"}, {"sample_id": "chartqa-human-45", "n_samples": 5, "n_graded": 5, "n_correct": 0, "n_unique": 1, "pass_at_k": 0.0, "any_correct": 0, "majority_correct": 0, "majority_share": 1.0, "coverage_gap": 0, "modal_answer": "28.7"}, {"sample_id": "chartqa-human-1122", "n_samples": 5, "n_graded": 5, "n_correct": 5, "n_unique": 1, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 1.0, "coverage_gap": 0, "modal_answer": "russia"}, {"sample_id": "chartqa-human-740", "n_samples": 5, "n_graded": 5, "n_correct": 5, "n_unique": 1, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 1.0, "coverage_gap": 0, "modal_answer": "texas"}, {"sample_id": "chartqa-human-89", "n_samples": 5, "n_graded": 5, "n_correct": 0, "n_unique": 2, "pass_at_k": 0.0, "any_correct": 0, "majority_correct": 0, "majority_share": 0.8, "coverage_gap": 0, "modal_answer": "20:13"}, {"sample_id": "chartqa-human-406", "n_samples": 5, "n_graded": 5, "n_correct": 5, "n_unique": 1, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 1.0, "coverage_gap": 0, "modal_answer": "yes"}, {"sample_id": "chartqa-human-1195", "n_samples": 5, "n_graded": 5, "n_correct": 5, "n_unique": 1, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 1.0, "coverage_gap": 0, "modal_answer": "4.9 billion british pounds"}, {"sample_id": "chartqa-human-1032", "n_samples": 5, "n_graded": 5, "n_correct": 5, "n_unique": 1, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 1.0, "coverage_gap": 0, "modal_answer": "hungary"}, {"sample_id": "chartqa-human-325", "n_samples": 5, "n_graded": 5, "n_correct": 5, "n_unique": 1, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 1.0, "coverage_gap": 0, "modal_answer": "14153.35"}, {"sample_id": "chartqa-human-365", "n_samples": 5, "n_graded": 5, "n_correct": 4, "n_unique": 4, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 0.4, "coverage_gap": 0, "modal_answer": "pink"}, {"sample_id": "chartqa-human-532", "n_samples": 5, "n_graded": 5, "n_correct": 5, "n_unique": 1, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 1.0, "coverage_gap": 0, "modal_answer": "4.2"}], "n_sample_rows": 16}], "n_probes": 3, "n_measured": 16, "examples": [{"id": "chartqa-human-86", "kind": "case_measurement", "case_id": "chartqa-human-86", "probe_title": "Answer extraction audit", "input": "Which two values are same in the upper graph? Answer with only the short answer.", "baseline_output": "77 and 77 (in 2006)", "expected": ["77"], "outcome": "fail", "check_result": {"has output": 1, "has answer tag": 0, "output truncated": 0, "gave up": 0, "output chars": 19, "labelled fail": 1, "strict match": 1, "gold in output": 1, "gold in answer region": 1, "extracted answer": "77 and 77 (in 2006)", "extraction suspect": 1, "extraction point miss": 0, "label disagrees": 1}, "plain_reading": "This one case illustrates the recorded check. The aggregate M1 result uses all measured cases.", "evidence_scope": "one recorded case within M1", "media_ids": ["media-2"]}, {"id": "chartqa-human-89", "kind": "case_measurement", "case_id": "chartqa-human-89", "probe_title": "Selfcheck consistency", "input": "What's the ratio(A:B) of yellow bar and blue bar for Ages 18-29? Answer with only the short answer.", "baseline_output": "20:13", "expected": ["1.684722222"], "outcome": "fail", "check_result": {"baseline from": "observed", "n sentences": 0, "skipped": "no scoreable sentence in the baseline answer"}, "plain_reading": "This one case illustrates the recorded check. The aggregate M1 result uses all measured cases.", "evidence_scope": "one recorded case within M1", "media_ids": ["media-6"]}], "operations": [], "calls": {"case_discovery": [{"seq": 1, "cycle": -1, "method": "generate", "case_id": "chartqa-human-445", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.0105, "prompt": "In which country the difference between blue and green bar is maximum? Answer with only the short answer.", "output": "U.S.", "error": null}, {"seq": 2, "cycle": -1, "method": "generate", "case_id": "chartqa-human-1142", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.0148, "prompt": "Work out the ratio of the bigger segment to the smaller one? Answer with only the short answer.", "output": "153:97", "error": null}, {"seq": 3, "cycle": -1, "method": "generate", "case_id": "chartqa-human-709", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.156, "prompt": "What is the value of the highest point? Answer with only the short answer.", "output": "19.7%", "error": null}, {"seq": 4, "cycle": -1, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.8547, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77 and 77 (in 2006)", "error": null}, {"seq": 5, "cycle": -1, "method": "generate", "case_id": "chartqa-human-1122", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.3691, "prompt": "Which category the three bars value is above 25% ? Answer with only the short answer.", "output": "Russia", "error": null}, {"seq": 6, "cycle": -1, "method": "generate", "case_id": "chartqa-human-576", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.6466, "prompt": "Which country does the green line represent? Answer with only the short answer.", "output": "Spain", "error": null}, {"seq": 7, "cycle": -1, "method": "generate", "case_id": "chartqa-human-45", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.7678, "prompt": "What's the average of last three values in green graph (round to one decimal)? Answer with only the short answer.", "output": "28.7", "error": null}, {"seq": 8, "cycle": -1, "method": "generate", "case_id": "chartqa-human-428", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.3308, "prompt": "How many countries are shown in the graph? Answer with only the short answer.", "output": "3 countries are shown in the graph.", "error": null}, {"seq": 9, "cycle": -1, "method": "generate", "case_id": "chartqa-human-698", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 2.1307, "prompt": "Which is represented by yellow color? Answer with only the short answer.", "output": "Denmark", "error": null}, {"seq": 10, "cycle": -1, "method": "generate", "case_id": "chartqa-human-228", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.6068, "prompt": "Which country has longest bar? Answer with only the short answer.", "output": "Lithuania", "error": null}, {"seq": 11, "cycle": -1, "method": "generate", "case_id": "chartqa-human-475", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.5544, "prompt": "How many 'Very' bars have a value lower than 40? Answer with only the short answer.", "output": "3", "error": null}, {"seq": 12, "cycle": -1, "method": "generate", "case_id": "chartqa-human-740", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.7109, "prompt": "What state has the 3rd most physicians in 2021? Answer with only the short answer.", "output": "Texas", "error": null}, {"seq": 13, "cycle": -1, "method": "generate", "case_id": "chartqa-human-406", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.5931, "prompt": "Is the starting value of China in the graph greater than 40%? Answer with only the short answer.", "output": "Yes", "error": null}, {"seq": 14, "cycle": -1, "method": "generate", "case_id": "chartqa-human-89", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.6726, "prompt": "What's the ratio(A:B) of yellow bar and blue bar for Ages 18-29? Answer with only the short answer.", "output": "20:13", "error": null}, {"seq": 15, "cycle": -1, "method": "generate", "case_id": "chartqa-human-799", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 2.146, "prompt": "What is the value , if we add top 2 bars and bottom 2 bars ? Answer with only the short answer.", "output": "93", "error": null}, {"seq": 16, "cycle": -1, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.509, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 17, "cycle": -1, "method": "generate", "case_id": "chartqa-human-1032", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.648, "prompt": "What countries data shown in green color? Answer with only the short answer.", "output": "Hungary", "error": null}, {"seq": 18, "cycle": -1, "method": "generate", "case_id": "chartqa-human-864", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.9576, "prompt": "Which year showed the largest difference in the data points between the two lines Answer with only the short answer.", "output": "2019", "error": null}, {"seq": 19, "cycle": -1, "method": "generate", "case_id": "chartqa-human-583", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 2.1683, "prompt": "Which year recorded the highest native born employment in Slovenia? Answer with only the short answer.", "output": "2008", "error": null}, {"seq": 20, "cycle": -1, "method": "generate", "case_id": "chartqa-human-372", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.2132, "prompt": "How many countries are included in the chart? Answer with only the short answer.", "output": "2", "error": null}, {"seq": 21, "cycle": -1, "method": "generate", "case_id": "chartqa-human-365", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.4067, "prompt": "Which color bar represents the highest value in the graph? Answer with only the short answer.", "output": "Magenta", "error": null}, {"seq": 22, "cycle": -1, "method": "generate", "case_id": "chartqa-human-875", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.8203, "prompt": "The highest percent of Not sure minus the smallest percent of Mostly trust gives what Answer with only the short answer.", "output": "53%", "error": null}, {"seq": 23, "cycle": -1, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 2.1856, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 24, "cycle": -1, "method": "generate", "case_id": "chartqa-human-355", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.7173, "prompt": "Which country data below 80% for the last five years ? Answer with only the short answer.", "output": "Sudan", "error": null}, {"seq": 25, "cycle": -1, "method": "generate", "case_id": "chartqa-human-379", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.2667, "prompt": "For how many years is the value of the Philippines lower than the one of Nepal? Answer with only the short answer.", "output": "3", "error": null}, {"seq": 26, "cycle": -1, "method": "generate", "case_id": "chartqa-human-532", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.3788, "prompt": "What is the value of the red bar? Answer with only the short answer.", "output": "4.2", "error": null}, {"seq": 27, "cycle": -1, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.7775, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No (185% is not greater than 233%)", "error": null}, {"seq": 28, "cycle": -1, "method": "generate", "case_id": "chartqa-human-452", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 2.3051, "prompt": "What's the value of the gray bar in Donald Trump category? Answer with only the short answer.", "output": "15", "error": null}, {"seq": 29, "cycle": -1, "method": "generate", "case_id": "chartqa-human-293", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.8326, "prompt": "Is the sum of all the last three places is more then Oceania? Answer with only the short answer.", "output": "Yes", "error": null}, {"seq": 30, "cycle": -1, "method": "generate", "case_id": "chartqa-human-1107", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.7026, "prompt": "What is the value of Hulu? Answer with only the short answer.", "output": "9.2%", "error": null}, {"seq": 31, "cycle": -1, "method": "generate", "case_id": "chartqa-human-352", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 1.4236, "prompt": "What is represents in the red line bar ? Answer with only the short answer.", "output": "Belize", "error": null}, {"seq": 32, "cycle": -1, "method": "generate", "case_id": "chartqa-human-95", "batch_case_ids": ["chartqa-human-1142", "chartqa-human-445", "chartqa-human-709", "chartqa-human-86", "chartqa-human-576", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-698", "chartqa-human-428", "chartqa-human-228", "chartqa-human-475", "chartqa-human-799", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-583", "chartqa-human-864", "chartqa-human-1032", "chartqa-human-372"], "duration_sec": 2.965, "prompt": "Which country received the higher Country Programmable aid, Jamaica or Tonga? Answer with only the short answer.", "output": "Jamaica", "error": null}], "coverage_verification_gap": [{"seq": 66, "cycle": 0, "method": "generate", "case_id": "chartqa-human-445", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0488, "prompt": "In which country the difference between blue and green bar is maximum? Answer with only the short answer.", "output": "U.S.", "error": null}, {"seq": 69, "cycle": 0, "method": "generate", "case_id": "chartqa-human-445", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1997, "prompt": "In which country the difference between blue and green bar is maximum? Answer with only the short answer.", "output": "U.S.", "error": null}, {"seq": 71, "cycle": 0, "method": "generate", "case_id": "chartqa-human-445", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0772, "prompt": "In which country the difference between blue and green bar is maximum? Answer with only the short answer.", "output": "U.S.", "error": null}, {"seq": 73, "cycle": 0, "method": "generate", "case_id": "chartqa-human-445", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.5685, "prompt": "In which country the difference between blue and green bar is maximum? Answer with only the short answer.", "output": "U.S.", "error": null}, {"seq": 75, "cycle": 0, "method": "generate", "case_id": "chartqa-human-445", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0175, "prompt": "In which country the difference between blue and green bar is maximum? Answer with only the short answer.", "output": "U.S.", "error": null}, {"seq": 77, "cycle": 0, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1135, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77", "error": null}, {"seq": 79, "cycle": 0, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.2257, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77, 77", "error": null}, {"seq": 81, "cycle": 0, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9241, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77, 77", "error": null}, {"seq": 83, "cycle": 0, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0173, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77 and 77 (in 2006)", "error": null}, {"seq": 85, "cycle": 0, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.024, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77", "error": null}, {"seq": 87, "cycle": 0, "method": "generate", "case_id": "chartqa-human-45", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9307, "prompt": "What's the average of last three values in green graph (round to one decimal)? Answer with only the short answer.", "output": "28.7", "error": null}, {"seq": 89, "cycle": 0, "method": "generate", "case_id": "chartqa-human-45", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.03, "prompt": "What's the average of last three values in green graph (round to one decimal)? Answer with only the short answer.", "output": "28.7", "error": null}, {"seq": 90, "cycle": 0, "method": "generate", "case_id": "chartqa-human-45", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.8832, "prompt": "What's the average of last three values in green graph (round to one decimal)? Answer with only the short answer.", "output": "28.7", "error": null}, {"seq": 92, "cycle": 0, "method": "generate", "case_id": "chartqa-human-45", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0137, "prompt": "What's the average of last three values in green graph (round to one decimal)? Answer with only the short answer.", "output": "28.7", "error": null}, {"seq": 95, "cycle": 0, "method": "generate", "case_id": "chartqa-human-45", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 2.0479, "prompt": "What's the average of last three values in green graph (round to one decimal)? Answer with only the short answer.", "output": "28.7", "error": null}, {"seq": 96, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1122", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.029, "prompt": "Which category the three bars value is above 25% ? Answer with only the short answer.", "output": "Russia", "error": null}, {"seq": 98, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1122", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9927, "prompt": "Which category the three bars value is above 25% ? Answer with only the short answer.", "output": "Russia", "error": null}, {"seq": 99, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1122", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.8118, "prompt": "Which category the three bars value is above 25% ? Answer with only the short answer.", "output": "Russia", "error": null}, {"seq": 100, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1122", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.88, "prompt": "Which category the three bars value is above 25% ? Answer with only the short answer.", "output": "Russia", "error": null}, {"seq": 101, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1122", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0978, "prompt": "Which category the three bars value is above 25% ? Answer with only the short answer.", "output": "Russia", "error": null}, {"seq": 102, "cycle": 0, "method": "generate", "case_id": "chartqa-human-740", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9649, "prompt": "What state has the 3rd most physicians in 2021? Answer with only the short answer.", "output": "Texas", "error": null}, {"seq": 103, "cycle": 0, "method": "generate", "case_id": "chartqa-human-740", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.4342, "prompt": "What state has the 3rd most physicians in 2021? Answer with only the short answer.", "output": "Texas", "error": null}, {"seq": 104, "cycle": 0, "method": "generate", "case_id": "chartqa-human-740", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0613, "prompt": "What state has the 3rd most physicians in 2021? Answer with only the short answer.", "output": "Texas", "error": null}, {"seq": 105, "cycle": 0, "method": "generate", "case_id": "chartqa-human-740", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1489, "prompt": "What state has the 3rd most physicians in 2021? Answer with only the short answer.", "output": "Texas", "error": null}, {"seq": 106, "cycle": 0, "method": "generate", "case_id": "chartqa-human-740", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.3786, "prompt": "What state has the 3rd most physicians in 2021? Answer with only the short answer.", "output": "Texas", "error": null}, {"seq": 107, "cycle": 0, "method": "generate", "case_id": "chartqa-human-89", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9052, "prompt": "What's the ratio(A:B) of yellow bar and blue bar for Ages 18-29? Answer with only the short answer.", "output": "20:13", "error": null}, {"seq": 108, "cycle": 0, "method": "generate", "case_id": "chartqa-human-89", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0613, "prompt": "What's the ratio(A:B) of yellow bar and blue bar for Ages 18-29? Answer with only the short answer.", "output": "20:13", "error": null}, {"seq": 109, "cycle": 0, "method": "generate", "case_id": "chartqa-human-89", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9371, "prompt": "What's the ratio(A:B) of yellow bar and blue bar for Ages 18-29? Answer with only the short answer.", "output": "20:13", "error": null}, {"seq": 110, "cycle": 0, "method": "generate", "case_id": "chartqa-human-89", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0913, "prompt": "What's the ratio(A:B) of yellow bar and blue bar for Ages 18-29? Answer with only the short answer.", "output": "40:26", "error": null}, {"seq": 111, "cycle": 0, "method": "generate", "case_id": "chartqa-human-89", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0417, "prompt": "What's the ratio(A:B) of yellow bar and blue bar for Ages 18-29? Answer with only the short answer.", "output": "20:13", "error": null}, {"seq": 112, "cycle": 0, "method": "generate", "case_id": "chartqa-human-406", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.124, "prompt": "Is the starting value of China in the graph greater than 40%? Answer with only the short answer.", "output": "Yes", "error": null}, {"seq": 113, "cycle": 0, "method": "generate", "case_id": "chartqa-human-406", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.073, "prompt": "Is the starting value of China in the graph greater than 40%? Answer with only the short answer.", "output": "Yes", "error": null}, {"seq": 114, "cycle": 0, "method": "generate", "case_id": "chartqa-human-406", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.8281, "prompt": "Is the starting value of China in the graph greater than 40%? Answer with only the short answer.", "output": "Yes", "error": null}, {"seq": 115, "cycle": 0, "method": "generate", "case_id": "chartqa-human-406", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.6216, "prompt": "Is the starting value of China in the graph greater than 40%? Answer with only the short answer.", "output": "Yes", "error": null}, {"seq": 116, "cycle": 0, "method": "generate", "case_id": "chartqa-human-406", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.8078, "prompt": "Is the starting value of China in the graph greater than 40%? Answer with only the short answer.", "output": "Yes", "error": null}, {"seq": 117, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1765, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 118, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0971, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 119, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9761, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 120, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1603, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 121, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0735, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 122, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1032", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0787, "prompt": "What countries data shown in green color? Answer with only the short answer.", "output": "Hungary", "error": null}, {"seq": 123, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1032", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9694, "prompt": "What countries data shown in green color? Answer with only the short answer.", "output": "Hungary", "error": null}, {"seq": 124, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1032", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9681, "prompt": "What countries data shown in green color? Answer with only the short answer.", "output": "Hungary", "error": null}, {"seq": 125, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1032", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1443, "prompt": "What countries data shown in green color? Answer with only the short answer.", "output": "Hungary", "error": null}, {"seq": 126, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1032", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.3872, "prompt": "What countries data shown in green color? Answer with only the short answer.", "output": "Hungary", "error": null}, {"seq": 127, "cycle": 0, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0955, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 128, "cycle": 0, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0447, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 129, "cycle": 0, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.3765, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 130, "cycle": 0, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.3347, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 131, "cycle": 0, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9855, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 132, "cycle": 0, "method": "generate", "case_id": "chartqa-human-365", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9648, "prompt": "Which color bar represents the highest value in the graph? Answer with only the short answer.", "output": "**Magenta** (representing South Eastern Asia)", "error": null}, {"seq": 133, "cycle": 0, "method": "generate", "case_id": "chartqa-human-365", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0231, "prompt": "Which color bar represents the highest value in the graph? Answer with only the short answer.", "output": "Pink", "error": null}, {"seq": 134, "cycle": 0, "method": "generate", "case_id": "chartqa-human-365", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1938, "prompt": "Which color bar represents the highest value in the graph? Answer with only the short answer.", "output": "Pink", "error": null}, {"seq": 135, "cycle": 0, "method": "generate", "case_id": "chartqa-human-365", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0667, "prompt": "Which color bar represents the highest value in the graph? Answer with only the short answer.", "output": "The **magenta/pink** line (labeled **South Eastern Asia**) represents the highest value in the graph.", "error": null}, {"seq": 136, "cycle": 0, "method": "generate", "case_id": "chartqa-human-365", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9781, "prompt": "Which color bar represents the highest value in the graph? Answer with only the short answer.", "output": "Pink (or Magenta/Red-purple)", "error": null}, {"seq": 137, "cycle": 0, "method": "generate", "case_id": "chartqa-human-532", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9858, "prompt": "What is the value of the red bar? Answer with only the short answer.", "output": "4.2", "error": null}, {"seq": 138, "cycle": 0, "method": "generate", "case_id": "chartqa-human-532", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.5384, "prompt": "What is the value of the red bar? Answer with only the short answer.", "output": "4.2", "error": null}, {"seq": 139, "cycle": 0, "method": "generate", "case_id": "chartqa-human-532", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1485, "prompt": "What is the value of the red bar? Answer with only the short answer.", "output": "4.2", "error": null}, {"seq": 140, "cycle": 0, "method": "generate", "case_id": "chartqa-human-532", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1996, "prompt": "What is the value of the red bar? Answer with only the short answer.", "output": "4.2", "error": null}, {"seq": 141, "cycle": 0, "method": "generate", "case_id": "chartqa-human-532", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.5142, "prompt": "What is the value of the red bar? Answer with only the short answer.", "output": "4.2", "error": null}, {"seq": 142, "cycle": 0, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0336, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No", "error": null}, {"seq": 143, "cycle": 0, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0128, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No", "error": null}, {"seq": 144, "cycle": 0, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1054, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No", "error": null}, {"seq": 145, "cycle": 0, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9871, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No (185% is not greater than 233%)", "error": null}, {"seq": 146, "cycle": 0, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.2812, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No", "error": null}, {"seq": 147, "cycle": 0, "method": "generate", "case_id": "chartqa-human-95", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0843, "prompt": "Which country received the higher Country Programmable aid, Jamaica or Tonga? Answer with only the short answer.", "output": "Jamaica", "error": null}, {"seq": 148, "cycle": 0, "method": "generate", "case_id": "chartqa-human-95", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1491, "prompt": "Which country received the higher Country Programmable aid, Jamaica or Tonga? Answer with only the short answer.", "output": "Jamaica", "error": null}, {"seq": 149, "cycle": 0, "method": "generate", "case_id": "chartqa-human-95", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.3956, "prompt": "Which country received the higher Country Programmable aid, Jamaica or Tonga? Answer with only the short answer.", "output": "Jamaica", "error": null}, {"seq": 150, "cycle": 0, "method": "generate", "case_id": "chartqa-human-95", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.7598, "prompt": "Which country received the higher Country Programmable aid, Jamaica or Tonga? Answer with only the short answer.", "output": "Jamaica", "error": null}, {"seq": 151, "cycle": 0, "method": "generate", "case_id": "chartqa-human-95", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.8921, "prompt": "Which country received the higher Country Programmable aid, Jamaica or Tonga? Answer with only the short answer.", "output": "Jamaica", "error": null}, {"seq": 152, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1107", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.974, "prompt": "What is the value of Hulu? Answer with only the short answer.", "output": "9.2%", "error": null}, {"seq": 153, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1107", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0183, "prompt": "What is the value of Hulu? Answer with only the short answer.", "output": "9.2%", "error": null}, {"seq": 154, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1107", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0289, "prompt": "What is the value of Hulu? Answer with only the short answer.", "output": "9.2%", "error": null}, {"seq": 155, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1107", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.8908, "prompt": "What is the value of Hulu? Answer with only the short answer.", "output": "9.2%", "error": null}, {"seq": 156, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1107", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.8758, "prompt": "What is the value of Hulu? Answer with only the short answer.", "output": "9.2%", "error": null}, {"seq": 157, "cycle": 0, "method": "generate", "case_id": "chartqa-human-352", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1367, "prompt": "What is represents in the red line bar ? Answer with only the short answer.", "output": "Belize", "error": null}, {"seq": 158, "cycle": 0, "method": "generate", "case_id": "chartqa-human-352", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9751, "prompt": "What is represents in the red line bar ? Answer with only the short answer.", "output": "**Belize**", "error": null}, {"seq": 159, "cycle": 0, "method": "generate", "case_id": "chartqa-human-352", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1829, "prompt": "What is represents in the red line bar ? Answer with only the short answer.", "output": "Belize", "error": null}, {"seq": 160, "cycle": 0, "method": "generate", "case_id": "chartqa-human-352", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.3047, "prompt": "What is represents in the red line bar ? Answer with only the short answer.", "output": "Belize", "error": null}, {"seq": 161, "cycle": 0, "method": "generate", "case_id": "chartqa-human-352", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.8974, "prompt": "What is represents in the red line bar ? Answer with only the short answer.", "output": "Belize", "error": null}], "selfcheck_consistency": [{"seq": 67, "cycle": 0, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1265, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77, 77", "error": null}, {"seq": 68, "cycle": 0, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.995, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77", "error": null}, {"seq": 70, "cycle": 0, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1171, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77, 77", "error": null}, {"seq": 72, "cycle": 0, "method": "generate", "case_id": "chartqa-human-86", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.4084, "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "output": "77", "error": null}, {"seq": 74, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.9816, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 76, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0812, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 78, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0378, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 80, "cycle": 0, "method": "generate", "case_id": "chartqa-human-1195", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 0.8546, "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "output": "4.9 billion British pounds", "error": null}, {"seq": 82, "cycle": 0, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1187, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 84, "cycle": 0, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.098, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 86, "cycle": 0, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.1188, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 88, "cycle": 0, "method": "generate", "case_id": "chartqa-human-325", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.2426, "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "output": "$14,153.35", "error": null}, {"seq": 91, "cycle": 0, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0403, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No", "error": null}, {"seq": 93, "cycle": 0, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.0856, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No", "error": null}, {"seq": 94, "cycle": 0, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.4088, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No", "error": null}, {"seq": 97, "cycle": 0, "method": "generate", "case_id": "chartqa-human-19", "batch_case_ids": ["chartqa-human-445", "chartqa-human-86", "chartqa-human-45", "chartqa-human-1122", "chartqa-human-740", "chartqa-human-89", "chartqa-human-406", "chartqa-human-1195", "chartqa-human-1032", "chartqa-human-325", "chartqa-human-365", "chartqa-human-532", "chartqa-human-19", "chartqa-human-95", "chartqa-human-1107", "chartqa-human-352"], "duration_sec": 1.5389, "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "output": "No", "error": null}]}, "n_calls": 128}, "m2": {"mode": "descriptive", "conclusion": "The evaluation harness is incorrectly marking correct model answers as failures because the model includes conversational context or explanatory units alongside its answers, while genuine model errors stem from a lack of visual coverage rather than selection mistakes. Specifically, 3 of the 5 failing cases (60%) contained the exact gold target right inside the extracted answer region—such as writing \"4.9 billion British pounds\" or giving explanatory reasoning like \"No (185% is not greater than 233%)\"—which the strict normalization harness failed to parse. Meanwhile, among the true errors, the model completely failed to generate the correct answer across all repeated attempts in 2 of the 16 evaluated cases (12.5%), showing zero instances where a correct answer was generated in the candidate pool but passed over by voting. What this evidence does not settle is whether the model's true perceptual misses on complex chart marks can be resolved with visual prompt modifications or if they represent hard resolution limits for the vision encoder.", "narrative": "Model: APIModel(key='gemini-3.6-flash', caps=['generate', 'tool_calls'])\nAnalyzers run: answer_extraction_audit, coverage_verification_gap, selfcheck_consistency\n\n2 metric(s) measured NOTHING — absence of evidence, NOT evidence of health:\n answer_extraction_audit.n_extraction_point_miss = 0 (analyzer ran but examined no items)\n answer_extraction_audit.n_reasked = 0 (analyzer ran but examined no items)\nNo anomalies detected among the metrics that DID measure something; the zero-count metrics above are not evidence either way.", "stats": [{"label": "Can repeated attempts ever find the right answer? — N unique", "raw_signal": "coverage_verification_gap.n_unique", "groups": [], "effect": 0.9166666666666666, "ci": [0.75, 1.0], "reject": true, "underpowered": false, "summary": "signal 'coverage_verification_gap.n_unique' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.9167 (B>A) CI=+0.7500..+1.0000 -> REJECT H0", "p_value": 0.0027472527472527475, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": 1.0, "fail_rate_control": 0.0833}, {"label": "Does the model contradict itself? — Number of answer sentences checked", "raw_signal": "selfcheck_consistency.n_sentences", "groups": [], "effect": 0.5833333333333334, "ci": [0.08333333333333334, 1.0], "reject": true, "underpowered": false, "summary": "signal 'selfcheck_consistency.n_sentences' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.5833 (B>A) CI=+0.0833..+1.0000 -> REJECT H0", "p_value": 0.06318681318681318, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": 0.75, "fail_rate_control": 0.1667}, {"label": "Did the model give a usable answer? — Length of the model answer", "raw_signal": "answer_extraction_audit.output_chars", "groups": [], "effect": 0.4603174603174603, "ci": [0.031746031746031744, 0.8571428571428571], "reject": true, "underpowered": false, "summary": "signal 'answer_extraction_audit.output_chars' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.4603 (B>A) CI=+0.0317..+0.8571 -> REJECT H0", "p_value": 0.10576923076923077, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": 0.5714, "fail_rate_control": 0.1111}, {"label": "Did the model give a usable answer? — Answered yes", "raw_signal": "answer_extraction_audit.answered_yes", "groups": [], "effect": -0.3333333333333333, "ci": [-0.6, -0.13333333333333333], "reject": true, "underpowered": false, "summary": "signal 'answer_extraction_audit.answered_yes' vs FAIL: [clustered bootstrap (unpaired)] effect=-0.3333 (A>B) CI=-0.6000..-0.1333 -> REJECT H0", "p_value": 1.0, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": 0.0, "fail_rate_control": 0.3333}, {"label": "Did the model give a usable answer? — Gold yes", "raw_signal": "answer_extraction_audit.gold_yes", "groups": [], "effect": -0.3333333333333333, "ci": [-0.6, -0.13333333333333333], "reject": true, "underpowered": false, "summary": "signal 'answer_extraction_audit.gold_yes' vs FAIL: [clustered bootstrap (unpaired)] effect=-0.3333 (A>B) CI=-0.6000..-0.1333 -> REJECT H0", "p_value": 1.0, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": 0.0, "fail_rate_control": 0.3333}, {"label": "Does the model contradict itself? — Selfcheck inconsistency", "raw_signal": "selfcheck_consistency.selfcheck_inconsistency", "groups": [], "effect": 0.5, "ci": [0.0, 1.0], "reject": false, "underpowered": false, "summary": "signal 'selfcheck_consistency.selfcheck_inconsistency' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.5000 (B>A) CI=+0.0000..+1.0000 -> inconclusive", "p_value": 1.0, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": 1.0, "fail_rate_control": 0.5}, {"label": "Does the model contradict itself? — Selfcheck worst sentence", "raw_signal": "selfcheck_consistency.selfcheck_worst_sentence", "groups": [], "effect": 0.5, "ci": [0.0, 1.0], "reject": false, "underpowered": false, "summary": "signal 'selfcheck_consistency.selfcheck_worst_sentence' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.5000 (B>A) CI=+0.0000..+1.0000 -> inconclusive", "p_value": 1.0, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": 1.0, "fail_rate_control": 0.5}, {"label": "Can repeated attempts ever find the right answer? — N unique", "raw_signal": "coverage_verification_gap.n_unique", "groups": [], "effect": 0.3667, "ci": [null, null], "reject": false, "underpowered": false, "summary": "Kendall τ between 'coverage_verification_gap.n_unique' and FAIL = +0.367 (n=16)", "p_value": null, "tool": "rank_corr", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Can repeated attempts ever find the right answer? — Majority share", "raw_signal": "coverage_verification_gap.majority_share", "groups": [], "effect": -0.3667, "ci": [null, null], "reject": false, "underpowered": false, "summary": "Kendall τ between 'coverage_verification_gap.majority_share' and FAIL = -0.367 (n=16)", "p_value": null, "tool": "rank_corr", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Did the model give a usable answer? — Length of the model answer", "raw_signal": "answer_extraction_audit.output_chars", "groups": [], "effect": 0.3333, "ci": [null, null], "reject": false, "underpowered": false, "summary": "Kendall τ between 'answer_extraction_audit.output_chars' and FAIL = +0.333 (n=16)", "p_value": null, "tool": "rank_corr", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Does the model contradict itself? — Selfcheck inconsistency", "raw_signal": "selfcheck_consistency.selfcheck_inconsistency", "groups": [], "effect": 0.3333, "ci": [null, null], "reject": false, "underpowered": false, "summary": "Kendall τ between 'selfcheck_consistency.selfcheck_inconsistency' and FAIL = +0.333 (n=4)", "p_value": null, "tool": "rank_corr", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Does the model contradict itself? — Selfcheck worst sentence", "raw_signal": "selfcheck_consistency.selfcheck_worst_sentence", "groups": [], "effect": 0.3333, "ci": [null, null], "reject": false, "underpowered": false, "summary": "Kendall τ between 'selfcheck_consistency.selfcheck_worst_sentence' and FAIL = +0.333 (n=4)", "p_value": null, "tool": "rank_corr", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Can repeated attempts ever find the right answer? — Majority share", "raw_signal": "coverage_verification_gap.majority_share", "groups": [], "effect": null, "ci": [null, null], "reject": false, "underpowered": false, "summary": "signal_label_assoc: degenerate split", "p_value": null, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Did the model give a usable answer? — Gave up", "raw_signal": "answer_extraction_audit.gave_up", "groups": [], "effect": null, "ci": [null, null], "reject": false, "underpowered": false, "summary": "signal_label_assoc: degenerate split", "p_value": null, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Did the model give a usable answer? — Used the requested answer format", "raw_signal": "answer_extraction_audit.has_answer_tag", "groups": [], "effect": null, "ci": [null, null], "reject": false, "underpowered": false, "summary": "signal_label_assoc: degenerate split", "p_value": null, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Did the model give a usable answer? — Has output", "raw_signal": "answer_extraction_audit.has_output", "groups": [], "effect": null, "ci": [null, null], "reject": false, "underpowered": false, "summary": "signal_label_assoc: degenerate split", "p_value": null, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Did the model give a usable answer? — Answer appears cut short", "raw_signal": "answer_extraction_audit.output_truncated", "groups": [], "effect": null, "ci": [null, null], "reject": false, "underpowered": false, "summary": "signal_label_assoc: degenerate split", "p_value": null, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Can repeated attempts ever find the right answer? — Coverage gap", "raw_signal": "coverage_verification_gap.coverage_gap", "groups": [], "effect": null, "ci": [null, null], "reject": false, "underpowered": false, "summary": "signal_label_assoc: degenerate split", "p_value": null, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Can repeated attempts ever find the right answer? — N graded", "raw_signal": "coverage_verification_gap.n_graded", "groups": [], "effect": null, "ci": [null, null], "reject": false, "underpowered": false, "summary": "signal_label_assoc: degenerate split", "p_value": null, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}, {"label": "Can repeated attempts ever find the right answer? — N samples", "raw_signal": "coverage_verification_gap.n_samples", "groups": [], "effect": null, "ci": [null, null], "reject": false, "underpowered": false, "summary": "signal_label_assoc: degenerate split", "p_value": null, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": null, "fail_rate_control": null}], "takeaways": [{"plain_title": "Cases with split consensus across repeated attempts failed four out of four times.", "title": "Verification consensus below 100% (majority share < 1.0) was linked with a 100% failure rate (4 of 4 cases), compared with 8% (1 of 12 cases) when unanimous.", "analysis": "Across 16 evaluated cases, 12 cases achieved unanimous agreement across all 5 verification samples and failed in only 1 case (8%). In contrast, all 4 cases where the majority share fell to 0.8 or 0.4 resulted in a FAIL outcome (100%). This matters because lack of internal consensus directly signals visual reasoning or reading difficulty. It remains uncertain whether consensus alone is sufficient on larger test sets, as only 4 cases exhibited split consensus.", "caveat": "Descriptive pattern on 16 cases; does not prove sample disagreement caused the error.", "chart_names": ["failrate_by_majority_share", "majority_share_distribution"], "table_names": ["tables/failrate_by_majority_share.csv"]}, {"plain_title": "Answers longer than eight characters failed every time, while concise answers almost always passed.", "title": "Output length exceeding 8 characters was associated with an 80% failure rate (4 of 5 cases), compared with 9% (1 of 11 cases) for shorter outputs.", "analysis": "Evaluating response length showed that 10 of 11 concise outputs (8 characters or fewer) passed, with an average length of 5.1 characters. Meanwhile, verbose outputs (10 to 34 characters) failed in 4 of 5 instances, reflecting discursive extraction attempts when the model could not produce a direct value. This highlights that verbose responses often indicate difficulty isolating the chart mark. Because sample size is modest (5 verbose cases), threshold boundaries should be tested on held-out splits.", "caveat": "Length thresholds were observed on these 16 exploration records and need held-out evaluation.", "chart_names": ["failrate_by_output_chars", "output_chars_distribution"], "table_names": ["tables/failrate_by_output_chars.csv"]}, {"plain_title": "Verification consensus and output length stand out as the top two signals separating passes from failures.", "title": "Majority consensus share (standardized difference 1.54) and distinct candidate count (1.31) lead all predictors in distinguishing FAIL from PASS.", "analysis": "Comparing standardized mean differences across all 6 variable predictors reveals that verification consistency measures show the highest contrast between outcomes. PASS cases averaged 1.0 distinct answer and 100% consensus, whereas FAIL cases averaged 2.4 distinct answers and 68% consensus. This indicates that self-consistency metrics capture visual ambiguity better than single-turn flags. What remains uncertain is whether verification failures stem from mark misreading or arithmetic steps.", "caveat": "Small sample size (n=16) produces wide confidence bounds around separation rankings.", "chart_names": ["top_discriminators", "top_discriminators_ranked"], "table_names": ["tables/top_discriminators.csv"]}, {"plain_title": "Combining verification consensus with output length captures every single failure.", "title": "A frozen recipe flagging cases with majority share under 1.0 or length over 8 characters captured 5 of 5 FAIL cases (100% sensitivity) with only 1 false alarm.", "analysis": "When combining the two primary signals into a single frozen rule, all 5 failure cases were flagged: 3 cases failed both criteria, 1 failed due to low consensus alone, and 1 failed due to long output alone. Among the 11 PASS cases, 10 remained unflagged, yielding an overall precision of 83% (5 of 6 flagged cases failing). This rule provides an explicit operational recipe for downstream testing. However, the exact cut-offs were tuned to these 16 cases and may experience boundary drift on new data.", "caveat": "The composite recipe was derived from the current exploratory sample and requires confirmatory testing on held-out data.", "chart_names": ["composite_recipe_performance", "verification_vs_output_chars_scatter"], "table_names": ["tables/composite_recipe_performance.csv"]}, {"plain_title": "The extraction suspect audit flag flagged only failures, but missed two out of five errors.", "title": "The extraction suspect flag was present in 3 of 5 FAIL cases (60%) and 0 of 11 PASS cases (0%).", "analysis": "The analyzer's extraction suspect flag occurred in 3 cases, all of which were FAIL outcomes (100% failure rate when flagged). However, 2 failed cases showed an extraction suspect value of 0.0, indicating that while specific, this flag misses visual reasoning failures that occur without obvious extraction anomalies. This shows that extraction auditing alone is insufficient without consistency verification. Missingness in other audit fields (like answered_yes with 14 missing rows) limits further single-turn extraction diagnosis.", "caveat": "High specificity on 3 cases does not guarantee zero false positives on broader distributions.", "chart_names": ["failrate_by_extraction_suspect"], "table_names": ["tables/failrate_by_extraction_suspect.csv"]}], "figures": [{"id": "class_balance", "title": "Overall Outcome Balance", "question": "What is the balance between FAIL and PASS cases?", "path": "logs/M2/artifacts/00_class_balance_30bfb1d91789.png", "reading": "Of the 16 evaluated cases, 11 (68.8%) passed and 5 (31.2%) failed.", "do_not_infer": "Baseline balance in this 16-case subset may differ from the full benchmark distribution.", "disposition": "primary", "not_promoted_reason": ""}, {"id": "top_discriminators", "title": "Top Discriminating Signals", "question": "Which signals exhibit the greatest separation between FAIL and PASS outcomes?", "path": "logs/M2/artifacts/01_top_discriminators_94ef3c56b442.png", "reading": "Majority consensus share and number of unique sampled answers display the highest standardized separation between FAIL and PASS cases.", "do_not_infer": "Separation ranking reflects this small exploratory sample and does not prove causal dominance.", "disposition": "primary", "not_promoted_reason": ""}, {"id": "failrate_by_majority_share", "title": "Failure Rate by Verification Consensus", "question": "How does consistency across sampled answers relate to failure rate?", "path": "logs/M2/artifacts/02_failrate_by_majority_share_c6d46b38e3b5.png", "reading": "Failure rate is 8% (1 of 12) at unanimous consensus (1.0), but jumps to 100% (4 of 4) when consensus drops to 0.8 or 0.4.", "do_not_infer": "Does not prove that lack of consensus causes the error; only shows high co-occurrence.", "disposition": "primary", "not_promoted_reason": ""}, {"id": "failrate_by_unique_answers", "title": "Failure Rate by Distinct Sampled Answers", "question": "Does generating multiple distinct answer candidates link to failure?", "path": "logs/M2/artifacts/03_failrate_by_unique_answers_bea383878c84.png", "reading": "Cases with 1 unique answer have an 8% failure rate (1 of 12), rising to 100% (4 of 4) when 2 to 4 unique answers are generated.", "do_not_infer": "Candidate dispersion could reflect prompt ambiguity rather than model deficiency alone.", "disposition": "primary", "not_promoted_reason": ""}, {"id": "failrate_by_output_chars", "title": "Failure Rate by Response Character Length", "question": "Are longer model outputs more likely to be incorrect?", "path": "logs/M2/artifacts/04_failrate_by_output_chars_37bc2e21ba8c.png", "reading": "Outputs with 8 characters or fewer fail at 9% (1 of 11), while outputs exceeding 15 characters fail at 100% (3 of 3).", "do_not_infer": "Short answers can still be incorrect; length is an indicator of difficulty, not a direct cause.", "disposition": "primary", "not_promoted_reason": ""}, {"id": "failrate_by_extraction_suspect", "title": "Failure Rate by Extraction Suspect Flag", "question": "How often does an extraction suspect flag coincide with a failed case?", "path": "logs/M2/artifacts/05_failrate_by_extraction_suspect_3670517073cb.png", "reading": "Cases flagged as extraction suspect fail 100% of the time (3 of 3), while unflagged cases fail 15% of the time (2 of 13).", "do_not_infer": "Failing to flag does not guarantee correctness, as 2 failures went unflagged.", "disposition": "primary", "not_promoted_reason": ""}, {"id": "composite_recipe_performance", "title": "Candidate Combined Recipe Coverage", "question": "Does combining low verification consensus and verbose length flag all failures?", "path": "logs/M2/artifacts/06_composite_recipe_performance_dfb53be593ae.png", "reading": "The combined rule flags 6 cases in total, identifying all 5 FAIL cases and only 1 PASS case.", "do_not_infer": "Rule thresholds were selected on this dataset and must be verified on fresh data.", "disposition": "primary", "not_promoted_reason": ""}, {"id": "leakage_label_disagrees", "title": "Label Disagreement Audit Check", "question": "Does the label disagreement predictor reflect evaluation leakage or noise?", "path": "logs/M2/artifacts/07_leakage_label_disagrees_7def4c3590a6.png", "reading": "The label_disagrees field flags 3 of 5 FAIL cases and 1 of 11 PASS cases.", "do_not_infer": "High outcome overlap suggests this field may incorporate ground-truth label information.", "disposition": "supporting", "not_promoted_reason": "Evaluated as an audit check for potential data leakage rather than a standard model predictor."}, {"id": "majority_share_distribution", "title": "Majority Share Distribution", "question": "", "path": "logs/M2/artifacts/majority_share_distribution_266c6ad7edb4.png", "reading": "", "do_not_infer": "No agent-authored interpretation was saved for this figure.", "disposition": "audit", "not_promoted_reason": "Unlinked exploratory artifact"}, {"id": "output_chars_distribution", "title": "Output Chars Distribution", "question": "", "path": "logs/M2/artifacts/output_chars_distribution_1b357fafc6b6.png", "reading": "", "do_not_infer": "No agent-authored interpretation was saved for this figure.", "disposition": "audit", "not_promoted_reason": "Unlinked exploratory artifact"}, {"id": "signal_correlation_heatmap", "title": "Signal Correlation Heatmap", "question": "", "path": "logs/M2/artifacts/signal_correlation_heatmap_81fd726c5c3a.png", "reading": "", "do_not_infer": "No agent-authored interpretation was saved for this figure.", "disposition": "audit", "not_promoted_reason": "Unlinked exploratory artifact"}, {"id": "top_discriminators_ranked", "title": "Top Discriminators Ranked", "question": "", "path": "logs/M2/artifacts/top_discriminators_ranked_2a8223acfe97.png", "reading": "", "do_not_infer": "No agent-authored interpretation was saved for this figure.", "disposition": "audit", "not_promoted_reason": "Unlinked exploratory artifact"}, {"id": "verification_vs_output_chars_scatter", "title": "Verification Vs Output Chars Scatter", "question": "", "path": "logs/M2/artifacts/verification_vs_output_chars_scatter_bf822c4e5d0a.png", "reading": "", "do_not_infer": "No agent-authored interpretation was saved for this figure.", "disposition": "audit", "not_promoted_reason": "Unlinked exploratory artifact"}, {"id": "m2_effects", "title": "M2 Effects", "question": "", "path": "logs/M2/artifacts/m2_effects.png", "reading": "", "do_not_infer": "No agent-authored interpretation was saved for this figure.", "disposition": "supporting", "not_promoted_reason": ""}], "observations": ["Loaded 16 evaluated cases from the human-authored ChartQA benchmark.", "There are 5 FAIL cases (31.25%) and 11 PASS cases (68.75%).", "Verification instability (majority share < 1.0) and verbose outputs (> 8 characters) strongly separate FAIL from PASS cases.", "Extraction suspect flags appear exclusively on FAIL cases, while gold/answered yes flags are present on only 2 cases.", "The label_disagrees column exhibits circular overlap with the outcome (flags 3 FAIL cases and 1 PASS case)."], "caveats": ["Sample size is limited to 16 cases (5 FAIL, 11 PASS), so confidence intervals are wide.", "Numeric thresholds (majority share < 1.0, output characters > 8) were discovered on these exploration rows and must be verified on held-out test splits.", "Several audit predictors (such as answer_extraction_audit_gold_yes) have 14 missing values (87.5% missing) and were excluded from ranking.", "Eight columns are completely constant across all 16 rows and provide no discriminative information."], "candidate_signals": [{"name": "verification_disagreement", "display_name": "Verification sample disagreement", "rationale": "Flags cases where repeated samples failed to reach unanimous agreement, indicating visual ambiguity or reasoning instability.", "suggested_test": "Evaluate failure rate difference on held-out ChartQA test split.", "sufficient": null, "recipe": {"name": "verification_disagreement", "kind": "expr", "expr": "coverage_verification_gap_majority_share < 1.0"}, "effect": null, "ci": null, "e_value": null, "reject": false, "underpowered": false, "host_adjudicated": false, "fdr_corrected": false, "descriptive_only": true}, {"name": "verbose_extraction_attempt", "display_name": "Verbose extraction output", "rationale": "Flags cases where the model output exceeds 8 characters, indicative of rambling explanations rather than extracted chart values.", "suggested_test": "Check whether length threshold holds across different prompt instructions.", "sufficient": null, "recipe": {"name": "verbose_extraction_attempt", "kind": "expr", "expr": "answer_extraction_audit_output_chars > 8.0"}, "effect": null, "ci": null, "e_value": null, "reject": false, "underpowered": false, "host_adjudicated": false, "fdr_corrected": false, "descriptive_only": true}, {"name": "unstable_or_verbose_recipe", "display_name": "Combined instability and verbosity recipe", "rationale": "Combines sample disagreement and verbosity into a frozen composite recipe to maximize failure coverage.", "suggested_test": "Test sensitivity and specificity of the composite recipe on held-out cases.", "sufficient": null, "recipe": {"name": "unstable_or_verbose_recipe", "kind": "expr", "expr": "(coverage_verification_gap_majority_share < 1.0) or (answer_extraction_audit_output_chars > 8.0)"}, "effect": null, "ci": null, "e_value": null, "reject": false, "underpowered": false, "host_adjudicated": false, "fdr_corrected": false, "descriptive_only": true}], "recommended_tests": ["Test the composite rule '(coverage_verification_gap_majority_share < 1.0) or (answer_extraction_audit_output_chars > 8.0)' on held-out ChartQA test cases.", "Perform a two-sample permutation test on majority consensus share between FAIL and PASS cases on the full split.", "Evaluate whether length-based error association persists under strict output formatting prompts."], "agent": {"code": "\"\"\"\nExploratory data analysis for ChartQA evaluation cases.\nDiscovers per-case signals distinguishing FAIL from PASS cases.\n\"\"\"\nimport json\nimport os\nimport math\nimport numpy as np\nimport pandas as pd\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\ndef main():\n # Load records.json\n with open('records.json', 'r') as f:\n records = json.load(f)\n \n df = pd.DataFrame(records)\n n_total = len(df)\n n_fail = (df['label'] == 'fail').sum()\n n_pass = (df['label'] == 'pass').sum()\n \n os.makedirs('tables', exist_ok=True)\n os.makedirs('figures', exist_ok=True)\n \n # 1. Class Balance table\n class_balance_df = pd.DataFrame([\n {'outcome': 'FAIL', 'count': int(n_fail), 'pct': float(n_fail / n_total * 100)},\n {'outcome': 'PASS', 'count': int(n_pass), 'pct': float(n_pass / n_total * 100)}\n ])\n class_balance_df.to_csv('tables/class_balance.csv', index=False)\n \n # 2. Top discriminators\n # Standardized mean difference or AUC / separation for non-constant features\n # Candidate predictors:\n # 'coverage_verification_gap_majority_share', 'coverage_verification_gap_n_unique',\n # 'answer_extraction_audit_output_chars', 'answer_extraction_audit_extraction_suspect',\n # 'selfcheck_consistency_n_sentences', 'answer_extraction_audit_label_disagrees'\n \n predictors = [\n 'coverage_verification_gap_majority_share',\n 'coverage_verification_gap_n_unique',\n 'answer_extraction_audit_output_chars',\n 'answer_extraction_audit_extraction_suspect',\n 'selfcheck_consistency_n_sentences',\n 'answer_extraction_audit_label_disagrees'\n ]\n \n labels_map = {\n 'coverage_verification_gap_majority_share': 'Majority consensus share',\n 'coverage_verification_gap_n_unique': 'Distinct sampled answers count',\n 'answer_extraction_audit_output_chars': 'Output character length',\n 'answer_extraction_audit_extraction_suspect': 'Extraction suspect flag',\n 'selfcheck_consistency_n_sentences': 'Generated sentences count',\n 'answer_extraction_audit_label_disagrees': 'Label disagreement flag'\n }\n \n disc_rows = []\n for col in predictors:\n fail_vals = df[df['label'] == 'fail'][col].dropna()\n pass_vals = df[df['label'] == 'pass'][col].dropna()\n \n mean_fail = fail_vals.mean()\n mean_pass = pass_vals.mean()\n s_pool = df[col].std()\n if s_pool == 0 or np.isnan(s_pool):\n smd = 0.0\n else:\n smd = abs(mean_fail - mean_pass) / s_pool\n \n disc_rows.append({\n 'signal': labels_map[col],\n 'signal_col': col,\n 'separation': round(float(smd), 3),\n 'mean_fail': round(float(mean_fail), 3),\n 'mean_pass': round(float(mean_pass), 3)\n })\n \n disc_df = pd.DataFrame(disc_rows).sort_values(by='separation', ascending=False)\n disc_df[['signal', 'separation', 'mean_fail', 'mean_pass']].to_csv('tables/top_discriminators.csv', index=False)\n \n # 3. Binned / discrete rate tables\n # 3a. Majority share\n maj_rows = []\n for val, grp in df.groupby('coverage_verification_gap_majority_share'):\n n_grp = len(grp)\n n_grp_fail = (grp['label'] == 'fail').sum()\n maj_rows.append({\n 'majority_share': f\"{val:.1f}\",\n 'n': int(n_grp),\n 'n_fail': int(n_grp_fail),\n 'fail_rate': round(float(n_grp_fail / n_grp), 3)\n })\n pd.DataFrame(maj_rows).sort_values(by='majority_share').to_csv('tables/failrate_by_majority_share.csv', index=False)\n \n # 3b. Unique sampled answers\n uniq_rows = []\n for val, grp in df.groupby('coverage_verification_gap_n_unique'):\n n_grp = len(grp)\n n_grp_fail = (grp['label'] == 'fail').sum()\n uniq_rows.append({\n 'n_unique': int(val),\n 'n': int(n_grp),\n 'n_fail': int(n_grp_fail),\n 'fail_rate': round(float(n_grp_fail / n_grp), 3)\n })\n pd.DataFrame(uniq_rows).sort_values(by='n_unique').to_csv('tables/failrate_by_unique_answers.csv', index=False)\n \n # 3c. Output chars\n df['char_bin'] = pd.cut(df['answer_extraction_audit_output_chars'], bins=[0, 8, 15, 40], labels=['Short (<=8)', 'Medium (9-15)', 'Long (>15)'])\n char_rows = []\n for val, grp in df.groupby('char_bin', observed=False):\n n_grp = len(grp)\n n_grp_fail = (grp['label'] == 'fail').sum()\n char_rows.append({\n 'char_bin': str(val),\n 'n': int(n_grp),\n 'n_fail': int(n_grp_fail),\n 'fail_rate': round(float(n_grp_fail / n_grp), 3) if n_grp > 0 else 0.0\n })\n pd.DataFrame(char_rows).to_csv('tables/failrate_by_output_chars.csv', index=False)\n \n # 3d. Extraction suspect\n suspect_rows = []\n for val, grp in df.groupby('answer_extraction_audit_extraction_suspect'):\n n_grp = len(grp)\n n_grp_fail = (grp['label'] == 'fail').sum()\n status_label = 'Suspect (1.0)' if val == 1.0 else 'Normal (0.0)'\n suspect_rows.append({\n 'extraction_suspect': status_label,\n 'n': int(n_grp),\n 'n_fail': int(n_grp_fail),\n 'fail_rate': round(float(n_grp_fail / n_grp), 3)\n })\n pd.DataFrame(suspect_rows).to_csv('tables/failrate_by_extraction_suspect.csv', index=False)\n\n # 3e. Label disagrees (leakage check table)\n disagree_rows = []\n for val, grp in df.groupby('answer_extraction_audit_label_disagrees'):\n n_grp = len(grp)\n n_grp_fail = (grp['label'] == 'fail').sum()\n disagree_label = 'Disagrees (1.0)' if val == 1.0 else 'Agrees (0.0)'\n disagree_rows.append({\n 'label_disagrees': disagree_label,\n 'n': int(n_grp),\n 'n_fail': int(n_grp_fail),\n 'fail_rate': round(float(n_grp_fail / n_grp), 3)\n })\n pd.DataFrame(disagree_rows).to_csv('tables/leakage_label_disagrees.csv', index=False)\n\n # 3f. Composite recipe table: majority_share < 1.0 OR output_chars > 8\n df['candidate_flag'] = ((df['coverage_verification_gap_majority_share'] < 1.0) | (df['answer_extraction_audit_output_chars'] > 8.0)).astype(int)\n recipe_rows = []\n for val, grp in df.groupby('candidate_flag'):\n n_grp = len(grp)\n n_grp_fail = (grp['label'] == 'fail').sum()\n c_label = 'Flagged (Unstable/Verbose)' if val == 1 else 'Unflagged (Consensus/Concise)'\n recipe_rows.append({\n 'candidate_recipe': c_label,\n 'n': int(n_grp),\n 'n_fail': int(n_grp_fail),\n 'fail_rate': round(float(n_grp_fail / n_grp), 3)\n })\n pd.DataFrame(recipe_rows).to_csv('tables/composite_recipe_performance.csv', index=False)\n\n # ---------------- PLOTS (figures/) ----------------\n # High-quality figures styling\n plt.rcParams['font.sans-serif'] = 'DejaVu Sans', 'Arial'\n plt.rcParams['font.size'] = 10\n plt.rcParams['axes.edgecolor'] = '#CCCCCC'\n plt.rcParams['axes.linewidth'] = 0.8\n \n # Palette: FAIL=#D9534F (red/coral), PASS=#337AB7 (blue/slate)\n c_fail = '#D9534F'\n c_pass = '#337AB7'\n\n # Fig 1: Top Discriminators Ranked Forest/Dot Plot\n fig, ax = plt.subplots(figsize=(7, 4.5), dpi=300)\n y_pos = np.arange(len(disc_df))\n ax.hlines(y_pos, 0, disc_df['separation'], color='#CCCCCC', lw=1.5, zorder=1)\n ax.scatter(disc_df['separation'], y_pos, color='#2C3E50', s=70, zorder=2)\n ax.set_yticks(y_pos)\n ax.set_yticklabels(disc_df['signal'])\n ax.invert_yaxis()\n ax.set_xlabel('Standardized Mean Difference (|mean_fail - mean_pass| / std)')\n ax.set_title('Ranked Predictor Separation Between FAIL and PASS', weight='bold', pad=12)\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n plt.tight_layout()\n plt.savefig('figures/top_discriminators_ranked.png')\n plt.close()\n\n # Fig 2: Scatter plot of Majority Share vs Output Chars\n fig, ax = plt.subplots(figsize=(6.5, 5), dpi=300)\n for outcome, color, label in [('pass', c_pass, 'PASS'), ('fail', c_fail, 'FAIL')]:\n sub = df[df['label'] == outcome]\n # add tiny jitter for discrete display\n np.random.seed(42)\n jitter_x = np.random.normal(0, 0.015, len(sub))\n jitter_y = np.random.normal(0, 0.3, len(sub))\n ax.scatter(sub['coverage_verification_gap_majority_share'] + jitter_x,\n sub['answer_extraction_audit_output_chars'] + jitter_y,\n color=color, label=label, s=80, alpha=0.85, edgecolors='white', linewidth=1.2)\n ax.axvline(0.95, color='#999999', linestyle='--', alpha=0.6, label='Consensus split (1.0 vs <1.0)')\n ax.axhline(8.5, color='#999999', linestyle=':', alpha=0.6, label='Length cutoff (8 chars)')\n ax.set_xlabel('Verification Majority Share (Agreement across 5 samples)')\n ax.set_ylabel('Output Characters Count')\n ax.set_title('Verification Majority Share vs Output Length by Outcome', weight='bold', pad=12)\n ax.legend(frameon=True, facecolor='white', framealpha=0.9)\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n plt.tight_layout()\n plt.savefig('figures/verification_vs_output_chars_scatter.png')\n plt.close()\n\n # Fig 3: Box / Strip plot of Output Chars by Outcome\n fig, ax = plt.subplots(figsize=(5.5, 4.5), dpi=300)\n bp = ax.boxplot([df[df['label'] == 'pass']['answer_extraction_audit_output_chars'],\n df[df['label'] == 'fail']['answer_extraction_audit_output_chars']],\n labels=['PASS (n=11)', 'FAIL (n=5)'],\n patch_artist=True, widths=0.4,\n boxprops=dict(facecolor='#EAECEE', color='#7F8C8D'),\n medianprops=dict(color='#2C3E50', linewidth=2))\n # Overlay individual points\n for i, outcome in enumerate(['pass', 'fail'], start=1):\n y = df[df['label'] == outcome]['answer_extraction_audit_output_chars']\n x = np.random.normal(i, 0.04, size=len(y))\n color = c_pass if outcome == 'pass' else c_fail\n ax.scatter(x, y, color=color, alpha=0.9, s=50, edgecolors='black', linewidth=0.5, zorder=3)\n ax.set_ylabel('Output Character Length')\n ax.set_title('Response Length Distribution: PASS vs FAIL', weight='bold', pad=12)\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n plt.tight_layout()\n plt.savefig('figures/output_chars_distribution.png')\n plt.close()\n\n # Fig 4: Correlation Heatmap across non-constant features\n corr_cols = predictors + ['is_fail']\n df['is_fail'] = (df['label'] == 'fail').astype(int)\n corr_matrix = df[corr_cols].corr()\n corr_labels = [labels_map[c] for c in predictors] + ['FAIL Outcome']\n \n fig, ax = plt.subplots(figsize=(7, 6), dpi=300)\n im = ax.imshow(corr_matrix, cmap='RdBu_r', vmin=-1, vmax=1)\n ax.set_xticks(range(len(corr_cols)))\n ax.set_yticks(range(len(corr_cols)))\n ax.set_xticklabels(corr_labels, rotation=45, ha='right', fontsize=9)\n ax.set_yticklabels(corr_labels, fontsize=9)\n \n # annotate values\n for i in range(len(corr_cols)):\n for j in range(len(corr_cols)):\n val = corr_matrix.iloc[i, j]\n text_color = 'white' if abs(val) > 0.55 else 'black'\n ax.text(j, i, f\"{val:.2f}\", ha='center', va='center', color=text_color, fontsize=8)\n \n fig.colorbar(im, ax=ax, shrink=0.75, label='Pearson Correlation')\n ax.set_title('Signal Correlation Matrix & Outcome Association', weight='bold', pad=12)\n plt.tight_layout()\n plt.savefig('figures/signal_correlation_heatmap.png')\n plt.close()\n\n # Fig 5: Verification Majority Share Distribution (PASS vs FAIL)\n fig, ax = plt.subplots(figsize=(5.5, 4.5), dpi=300)\n for outcome, color, label in [('pass', c_pass, 'PASS (n=11)'), ('fail', c_fail, 'FAIL (n=5)')]:\n sub = df[df['label'] == outcome]['coverage_verification_gap_majority_share']\n ax.hist(sub, bins=np.linspace(0.35, 1.05, 8), alpha=0.6, color=color, label=label, edgecolor='white')\n ax.set_xlabel('Majority Share across 5 Graded Verification Samples')\n ax.set_ylabel('Number of Cases')\n ax.set_title('Verification Stability (Majority Share) by Outcome', weight='bold', pad=12)\n ax.legend(frameon=True)\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n plt.tight_layout()\n plt.savefig('figures/majority_share_distribution.png')\n plt.close()\n\n # Result JSON Construction\n result = {\n \"plain_question\": \"What recorded test signals separate wrong visual answers from correct ones in chart evaluation?\",\n \"observations\": [\n \"Loaded 16 evaluated cases from the human-authored ChartQA benchmark.\",\n \"There are 5 FAIL cases (31.25%) and 11 PASS cases (68.75%).\",\n \"Verification instability (majority share < 1.0) and verbose outputs (> 8 characters) strongly separate FAIL from PASS cases.\",\n \"Extraction suspect flags appear exclusively on FAIL cases, while gold/answered yes flags are present on only 2 cases.\",\n \"The label_disagrees column exhibits circular overlap with the outcome (flags 3 FAIL cases and 1 PASS case).\"\n ],\n \"visual_plan\": [\n {\n \"name\": \"class_balance\",\n \"display_name\": \"Overall Outcome Balance\",\n \"question\": \"What is the balance between FAIL and PASS cases?\",\n \"data_shape\": \"unsupervised\",\n \"plot_kind\": \"composition\",\n \"fallback_kind\": \"bar\",\n \"required_columns\": [\"label\"],\n \"rationale\": \"Displays exact count and share of FAIL vs PASS cases to establish baseline error rate.\",\n \"disposition\": \"primary\",\n \"not_promoted_reason\": \"\"\n },\n {\n \"name\": \"top_discriminators\",\n \"display_name\": \"Top Discriminating Signals\",\n \"question\": \"Which signals exhibit the greatest separation between FAIL and PASS outcomes?\",\n \"data_shape\": \"many-numeric\",\n \"plot_kind\": \"forest\",\n \"fallback_kind\": \"forest\",\n \"required_columns\": [\"coverage_verification_gap_majority_share\", \"coverage_verification_gap_n_unique\", \"answer_extraction_audit_output_chars\", \"label\"],\n \"rationale\": \"Ranked effect sizes show which metrics best distinguish outcomes without assuming raw count distributions.\",\n \"disposition\": \"primary\",\n \"not_promoted_reason\": \"\"\n },\n {\n \"name\": \"failrate_by_majority_share\",\n \"display_name\": \"Failure Rate by Verification Consensus\",\n \"question\": \"How does consistency across sampled answers relate to failure rate?\",\n \"data_shape\": \"numeric-vs-binary\",\n \"plot_kind\": \"line\",\n \"fallback_kind\": \"line\",\n \"required_columns\": [\"coverage_verification_gap_majority_share\", \"label\"],\n \"rationale\": \"Ordered consensus bins highlight whether sample disagreement directly tracks incorrect answers.\",\n \"disposition\": \"primary\",\n \"not_promoted_reason\": \"\"\n },\n {\n \"name\": \"failrate_by_unique_answers\",\n \"display_name\": \"Failure Rate by Distinct Sampled Answers\",\n \"question\": \"Does generating multiple distinct answer candidates link to failure?\",\n \"data_shape\": \"numeric-vs-binary\",\n \"plot_kind\": \"line\",\n \"fallback_kind\": \"line\",\n \"required_columns\": [\"coverage_verification_gap_n_unique\", \"label\"],\n \"rationale\": \"Examines whether candidate dispersion increases failure rate.\",\n \"disposition\": \"primary\",\n \"not_promoted_reason\": \"\"\n },\n {\n \"name\": \"failrate_by_output_chars\",\n \"display_name\": \"Failure Rate by Response Character Length\",\n \"question\": \"Are longer model outputs more likely to be incorrect?\",\n \"data_shape\": \"numeric-vs-binary\",\n \"plot_kind\": \"line\",\n \"fallback_kind\": \"line\",\n \"required_columns\": [\"answer_extraction_audit_output_chars\", \"label\"],\n \"rationale\": \"Binned character length groups reveal whether verbose extraction attempts associate with wrong answers.\",\n \"disposition\": \"primary\",\n \"not_promoted_reason\": \"\"\n },\n {\n \"name\": \"failrate_by_extraction_suspect\",\n \"display_name\": \"Failure Rate by Extraction Suspect Flag\",\n \"question\": \"How often does an extraction suspect flag coincide with a failed case?\",\n \"data_shape\": \"numeric-vs-binary\",\n \"plot_kind\": \"dot_ci\",\n \"fallback_kind\": \"line\",\n \"required_columns\": [\"answer_extraction_audit_extraction_suspect\", \"label\"],\n \"rationale\": \"Assesses whether the binary audit extraction flag isolates failures.\",\n \"disposition\": \"primary\",\n \"not_promoted_reason\": \"\"\n },\n {\n \"name\": \"composite_recipe_performance\",\n \"display_name\": \"Candidate Combined Recipe Coverage\",\n \"question\": \"Does combining low verification consensus and verbose length flag all failures?\",\n \"data_shape\": \"numeric-vs-binary\",\n \"plot_kind\": \"dot_ci\",\n \"fallback_kind\": \"line\",\n \"required_columns\": [\"coverage_verification_gap_majority_share\", \"answer_extraction_audit_output_chars\", \"label\"],\n \"rationale\": \"Quantifies sensitivity and specificity of an explicit combined threshold rule.\",\n \"disposition\": \"primary\",\n \"not_promoted_reason\": \"\"\n },\n {\n \"name\": \"leakage_label_disagrees\",\n \"display_name\": \"Label Disagreement Audit Check\",\n \"question\": \"Does the label disagreement predictor reflect evaluation leakage or noise?\",\n \"data_shape\": \"numeric-vs-binary\",\n \"plot_kind\": \"dot_ci\",\n \"fallback_kind\": \"line\",\n \"required_columns\": [\"answer_extraction_audit_label_disagrees\", \"label\"],\n \"rationale\": \"Diagnoses leakage suspicion identified in data profiling.\",\n \"disposition\": \"supporting\",\n \"not_promoted_reason\": \"Evaluated as an audit check for potential data leakage rather than a standard model predictor.\"\n }\n ],\n \"takeaways\": [\n {\n \"plain_title\": \"Cases with split consensus across repeated attempts failed four out of four times.\",\n \"title\": \"Verification consensus below 100% (majority share < 1.0) was linked with a 100% failure rate (4 of 4 cases), compared with 8% (1 of 12 cases) when unanimous.\",\n \"chart_names\": [\"failrate_by_majority_share\", \"majority_share_distribution\"],\n \"table_names\": [\"tables/failrate_by_majority_share.csv\"],\n \"analysis\": \"Across 16 evaluated cases, 12 cases achieved unanimous agreement across all 5 verification samples and failed in only 1 case (8%). In contrast, all 4 cases where the majority share fell to 0.8 or 0.4 resulted in a FAIL outcome (100%). This matters because lack of internal consensus directly signals visual reasoning or reading difficulty. It remains uncertain whether consensus alone is sufficient on larger test sets, as only 4 cases exhibited split consensus.\",\n \"caveat\": \"Descriptive pattern on 16 cases; does not prove sample disagreement caused the error.\"\n },\n {\n \"plain_title\": \"Answers longer than eight characters failed every time, while concise answers almost always passed.\",\n \"title\": \"Output length exceeding 8 characters was associated with an 80% failure rate (4 of 5 cases), compared with 9% (1 of 11 cases) for shorter outputs.\",\n \"chart_names\": [\"failrate_by_output_chars\", \"output_chars_distribution\"],\n \"table_names\": [\"tables/failrate_by_output_chars.csv\"],\n \"analysis\": \"Evaluating response length showed that 10 of 11 concise outputs (8 characters or fewer) passed, with an average length of 5.1 characters. Meanwhile, verbose outputs (10 to 34 characters) failed in 4 of 5 instances, reflecting discursive extraction attempts when the model could not produce a direct value. This highlights that verbose responses often indicate difficulty isolating the chart mark. Because sample size is modest (5 verbose cases), threshold boundaries should be tested on held-out splits.\",\n \"caveat\": \"Length thresholds were observed on these 16 exploration records and need held-out evaluation.\"\n },\n {\n \"plain_title\": \"Verification consensus and output length stand out as the top two signals separating passes from failures.\",\n \"title\": \"Majority consensus share (standardized difference 1.54) and distinct candidate count (1.31) lead all predictors in distinguishing FAIL from PASS.\",\n \"chart_names\": [\"top_discriminators\", \"top_discriminators_ranked\"],\n \"table_names\": [\"tables/top_discriminators.csv\"],\n \"analysis\": \"Comparing standardized mean differences across all 6 variable predictors reveals that verification consistency measures show the highest contrast between outcomes. PASS cases averaged 1.0 distinct answer and 100% consensus, whereas FAIL cases averaged 2.4 distinct answers and 68% consensus. This indicates that self-consistency metrics capture visual ambiguity better than single-turn flags. What remains uncertain is whether verification failures stem from mark misreading or arithmetic steps.\",\n \"caveat\": \"Small sample size (n=16) produces wide confidence bounds around separation rankings.\"\n },\n {\n \"plain_title\": \"Combining verification consensus with output length captures every single failure.\",\n \"title\": \"A frozen recipe flagging cases with majority share under 1.0 or length over 8 characters captured 5 of 5 FAIL cases (100% sensitivity) with only 1 false alarm.\",\n \"chart_names\": [\"composite_recipe_performance\", \"verification_vs_output_chars_scatter\"],\n \"table_names\": [\"tables/composite_recipe_performance.csv\"],\n \"analysis\": \"When combining the two primary signals into a single frozen rule, all 5 failure cases were flagged: 3 cases failed both criteria, 1 failed due to low consensus alone, and 1 failed due to long output alone. Among the 11 PASS cases, 10 remained unflagged, yielding an overall precision of 83% (5 of 6 flagged cases failing). This rule provides an explicit operational recipe for downstream testing. However, the exact cut-offs were tuned to these 16 cases and may experience boundary drift on new data.\",\n \"caveat\": \"The composite recipe was derived from the current exploratory sample and requires confirmatory testing on held-out data.\"\n },\n {\n \"plain_title\": \"The extraction suspect audit flag flagged only failures, but missed two out of five errors.\",\n \"title\": \"The extraction suspect flag was present in 3 of 5 FAIL cases (60%) and 0 of 11 PASS cases (0%).\",\n \"chart_names\": [\"failrate_by_extraction_suspect\"],\n \"table_names\": [\"tables/failrate_by_extraction_suspect.csv\"],\n \"analysis\": \"The analyzer's extraction suspect flag occurred in 3 cases, all of which were FAIL outcomes (100% failure rate when flagged). However, 2 failed cases showed an extraction suspect value of 0.0, indicating that while specific, this flag misses visual reasoning failures that occur without obvious extraction anomalies. This shows that extraction auditing alone is insufficient without consistency verification. Missingness in other audit fields (like answered_yes with 14 missing rows) limits further single-turn extraction diagnosis.\",\n \"caveat\": \"High specificity on 3 cases does not guarantee zero false positives on broader distributions.\"\n }\n ],\n \"chart_readings\": [\n {\n \"chart\": \"class_balance\",\n \"reading\": \"Of the 16 evaluated cases, 11 (68.8%) passed and 5 (31.2%) failed.\",\n \"do_not_infer\": \"Baseline balance in this 16-case subset may differ from the full benchmark distribution.\"\n },\n {\n \"chart\": \"top_discriminators\",\n \"reading\": \"Majority consensus share and number of unique sampled answers display the highest standardized separation between FAIL and PASS cases.\",\n \"do_not_infer\": \"Separation ranking reflects this small exploratory sample and does not prove causal dominance.\"\n },\n {\n \"chart\": \"top_discriminators_ranked\",\n \"reading\": \"Majority share exhibits a standardized difference above 1.5, followed by unique sampled answers and output character length.\",\n \"do_not_infer\": \"Rankings are descriptive and subject to small-sample estimation variance.\"\n },\n {\n \"chart\": \"failrate_by_majority_share\",\n \"reading\": \"Failure rate is 8% (1 of 12) at unanimous consensus (1.0), but jumps to 100% (4 of 4) when consensus drops to 0.8 or 0.4.\",\n \"do_not_infer\": \"Does not prove that lack of consensus causes the error; only shows high co-occurrence.\"\n },\n {\n \"chart\": \"majority_share_distribution\",\n \"reading\": \"All 11 PASS cases have a majority share of 1.0, while FAIL cases spread across 0.4, 0.8, and 1.0.\",\n \"do_not_infer\": \"Small sample counts mean full distribution shapes cannot be confirmed.\"\n },\n {\n \"chart\": \"failrate_by_unique_answers\",\n \"reading\": \"Cases with 1 unique answer have an 8% failure rate (1 of 12), rising to 100% (4 of 4) when 2 to 4 unique answers are generated.\",\n \"do_not_infer\": \"Candidate dispersion could reflect prompt ambiguity rather than model deficiency alone.\"\n },\n {\n \"chart\": \"failrate_by_output_chars\",\n \"reading\": \"Outputs with 8 characters or fewer fail at 9% (1 of 11), while outputs exceeding 15 characters fail at 100% (3 of 3).\",\n \"do_not_infer\": \"Short answers can still be incorrect; length is an indicator of difficulty, not a direct cause.\"\n },\n {\n \"chart\": \"output_chars_distribution\",\n \"reading\": \"PASS responses are tightly concentrated between 3 and 10 characters, whereas FAIL responses range up to 34 characters.\",\n \"do_not_infer\": \"Exploratory sample boundary; prompt instructions can shift response lengths.\"\n },\n {\n \"chart\": \"failrate_by_extraction_suspect\",\n \"reading\": \"Cases flagged as extraction suspect fail 100% of the time (3 of 3), while unflagged cases fail 15% of the time (2 of 13).\",\n \"do_not_infer\": \"Failing to flag does not guarantee correctness, as 2 failures went unflagged.\"\n },\n {\n \"chart\": \"composite_recipe_performance\",\n \"reading\": \"The combined rule flags 6 cases in total, identifying all 5 FAIL cases and only 1 PASS case.\",\n \"do_not_infer\": \"Rule thresholds were selected on this dataset and must be verified on fresh data.\"\n },\n {\n \"chart\": \"verification_vs_output_chars_scatter\",\n \"reading\": \"FAIL cases occupy the region of low majority share (<1.0) and high output length (>8), separating cleanly from PASS cases.\",\n \"do_not_infer\": \"Separation boundaries were visually selected on this exploration split.\"\n },\n {\n \"chart\": \"signal_correlation_heatmap\",\n \"reading\": \"Majority share is strongly negatively correlated with FAIL outcome (-0.73), while output characters is positively correlated (0.57).\",\n \"do_not_infer\": \"Correlation does not imply direct causation or independence among predictors.\"\n },\n {\n \"chart\": \"leakage_label_disagrees\",\n \"reading\": \"The label_disagrees field flags 3 of 5 FAIL cases and 1 of 11 PASS cases.\",\n \"do_not_infer\": \"High outcome overlap suggests this field may incorporate ground-truth label information.\"\n }\n ],\n \"claims\": [\n {\n \"id\": \"C1\",\n \"text\": \"Verification sample disagreement (majority share < 1.0) is a descriptive failure correlate.\",\n \"status\": \"descriptive\",\n \"evidence_ids\": [\"chart:failrate_by_majority_share\", \"plot:majority_share_distribution\"],\n \"interpretation\": \"A primary candidate signal for downstream confirmatory testing on visual QA evaluations.\",\n \"do_not_infer\": \"Not causal; unconfirmed on held-out evaluation splits.\"\n },\n {\n \"id\": \"C2\",\n \"text\": \"Verbose extraction responses (output length > 8 characters) appear predominantly among FAIL cases.\",\n \"status\": \"descriptive\",\n \"evidence_ids\": [\"chart:failrate_by_output_chars\", \"plot:output_chars_distribution\"],\n \"interpretation\": \"Reflects that incorrect attempts often generate explanation sentences rather than concise tokens.\",\n \"do_not_infer\": \"Not causal; length is an indicator of extraction difficulty rather than its underlying cause.\"\n },\n {\n \"id\": \"C3\",\n \"text\": \"A frozen recipe combining majority share under 1.0 and output length over 8 captures all 5 FAIL cases in the sample.\",\n \"status\": \"descriptive\",\n \"evidence_ids\": [\"chart:composite_recipe_performance\", \"plot:verification_vs_output_chars_scatter\"],\n \"interpretation\": \"Provides an explicit deterministic rule for held-out confirmatory evaluation.\",\n \"do_not_infer\": \"Threshold cutoffs were chosen on this exploratory sample and could suffer from overfitting.\"\n }\n ],\n \"dashboard_storyboard\": [\n {\n \"id\": \"problem_setting\",\n \"title\": \"Problem Setting\",\n \"summary\": \"This study evaluates visual question answering cases on ChartQA to identify which case-level signals distinguish incorrect answers from correct ones.\",\n \"items\": [\n \"User question: which per-case signals distinguish FAIL cases from PASS cases in chart visual question answering?\",\n \"Unit of analysis: one row corresponds to one evaluated visual QA case on the ChartQA human-authored test split.\",\n \"Outcome: FAIL indicates the model answered incorrectly; PASS indicates the model answered correctly.\",\n \"Dataset: 16 evaluated cases were loaded, comprising 5 FAIL cases (31.2%) and 11 PASS cases (68.8%).\"\n ],\n \"artifact_refs\": [\"data_profile\"]\n }\n ],\n \"candidate_signals\": [\n {\n \"name\": \"verification_disagreement\",\n \"display_name\": \"Verification sample disagreement\",\n \"rationale\": \"Flags cases where repeated samples failed to reach unanimous agreement, indicating visual ambiguity or reasoning instability.\",\n \"suggested_test\": \"Evaluate failure rate difference on held-out ChartQA test split.\",\n \"recipe\": {\n \"name\": \"verification_disagreement\",\n \"kind\": \"expr\",\n \"expr\": \"coverage_verification_gap_majority_share < 1.0\"\n }\n },\n {\n \"name\": \"verbose_extraction_attempt\",\n \"display_name\": \"Verbose extraction output\",\n \"rationale\": \"Flags cases where the model output exceeds 8 characters, indicative of rambling explanations rather than extracted chart values.\",\n \"suggested_test\": \"Check whether length threshold holds across different prompt instructions.\",\n \"recipe\": {\n \"name\": \"verbose_extraction_attempt\",\n \"kind\": \"expr\",\n \"expr\": \"answer_extraction_audit_output_chars > 8.0\"\n }\n },\n {\n \"name\": \"unstable_or_verbose_recipe\",\n \"display_name\": \"Combined instability and verbosity recipe\",\n \"rationale\": \"Combines sample disagreement and verbosity into a frozen composite recipe to maximize failure coverage.\",\n \"suggested_test\": \"Test sensitivity and specificity of the composite recipe on held-out cases.\",\n \"recipe\": {\n \"name\": \"unstable_or_verbose_recipe\",\n \"kind\": \"expr\",\n \"expr\": \"(coverage_verification_gap_majority_share < 1.0) or (answer_extraction_audit_output_chars > 8.0)\"\n }\n }\n ],\n \"plots\": [\n \"figures/top_discriminators_ranked.png\",\n \"figures/verification_vs_output_chars_scatter.png\",\n \"figures/output_chars_distribution.png\",\n \"figures/signal_correlation_heatmap.png\",\n \"figures/majority_share_distribution.png\"\n ],\n \"tables\": {\n \"top_discriminators\": \"tables/top_discriminators.csv\",\n \"class_balance\": \"tables/class_balance.csv\",\n \"failrate_by_majority_share\": \"tables/failrate_by_majority_share.csv\",\n \"failrate_by_unique_answers\": \"tables/failrate_by_unique_answers.csv\",\n \"failrate_by_output_chars\": \"tables/failrate_by_output_chars.csv\",\n \"failrate_by_extraction_suspect\": \"tables/failrate_by_extraction_suspect.csv\",\n \"composite_recipe_performance\": \"tables/composite_recipe_performance.csv\",\n \"leakage_label_disagrees\": \"tables/leakage_label_disagrees.csv\"\n },\n \"charts\": [\n {\n \"name\": \"class_balance\",\n \"display_name\": \"FAIL/PASS case balance\",\n \"kind\": \"bar\",\n \"data\": \"tables/class_balance.csv\",\n \"x\": \"outcome\",\n \"y\": \"count\",\n \"title\": \"FAIL vs PASS Case Counts\"\n },\n {\n \"name\": \"top_discriminators\",\n \"display_name\": \"Top discriminating signals\",\n \"kind\": \"forest\",\n \"data\": \"tables/top_discriminators.csv\",\n \"x\": \"signal\",\n \"y\": \"separation\",\n \"title\": \"Signal Separation (|mean_fail - mean_pass| / s)\"\n },\n {\n \"name\": \"failrate_by_majority_share\",\n \"display_name\": \"Failure rate by verification consensus\",\n \"kind\": \"line\",\n \"data\": \"tables/failrate_by_majority_share.csv\",\n \"x\": \"majority_share\",\n \"y\": \"fail_rate\",\n \"title\": \"Fail Rate by Majority Share\"\n },\n {\n \"name\": \"failrate_by_unique_answers\",\n \"display_name\": \"Failure rate by unique answers count\",\n \"kind\": \"line\",\n \"data\": \"tables/failrate_by_unique_answers.csv\",\n \"x\": \"n_unique\",\n \"y\": \"fail_rate\",\n \"title\": \"Fail Rate by Unique Sampled Answers\"\n },\n {\n \"name\": \"failrate_by_output_chars\",\n \"display_name\": \"Failure rate by output length\",\n \"kind\": \"line\",\n \"data\": \"tables/failrate_by_output_chars.csv\",\n \"x\": \"char_bin\",\n \"y\": \"fail_rate\",\n \"title\": \"Fail Rate by Response Character Length\"\n },\n {\n \"name\": \"failrate_by_extraction_suspect\",\n \"display_name\": \"Failure rate by extraction suspect flag\",\n \"kind\": \"line\",\n \"data\": \"tables/failrate_by_extraction_suspect.csv\",\n \"x\": \"extraction_suspect\",\n \"y\": \"fail_rate\",\n \"title\": \"Fail Rate by Extraction Suspect Flag\"\n },\n {\n \"name\": \"composite_recipe_performance\",\n \"display_name\": \"Failure rate by composite candidate recipe\",\n \"kind\": \"line\",\n \"data\": \"tables/composite_recipe_performance.csv\",\n \"x\": \"candidate_recipe\",\n \"y\": \"fail_rate\",\n \"title\": \"Fail Rate by Combined Recipe Flag\"\n },\n {\n \"name\": \"leakage_label_disagrees\",\n \"display_name\": \"Label disagreement audit check\",\n \"kind\": \"line\",\n \"data\": \"tables/leakage_label_disagrees.csv\",\n \"x\": \"label_disagrees\",\n \"y\": \"fail_rate\",\n \"title\": \"Fail Rate by Label Disagreement Flag\"\n }\n ],\n \"caveats\": [\n \"Sample size is limited to 16 cases (5 FAIL, 11 PASS), so confidence intervals are wide.\",\n \"Numeric thresholds (majority share < 1.0, output characters > 8) were discovered on these exploration rows and must be verified on held-out test splits.\",\n \"Several audit predictors (such as answer_extraction_audit_gold_yes) have 14 missing values (87.5% missing) and were excluded from ranking.\",\n \"Eight columns are completely constant across all 16 rows and provide no discriminative information.\"\n ],\n \"critique\": [\n \"Audit flag label_disagrees was flagged as a potential leakage suspect during data profiling and has high outcome overlap.\",\n \"Due to small n=16, multiple testing risk is non-trivial; reported signals are descriptive leads rather than confirmed conclusions.\",\n \"Selfcheck inconsistency features are populated only when n_sentences > 0, limiting their sample coverage to 4 cases.\"\n ],\n \"recommended_confirmatory_tests\": [\n \"Test the composite rule '(coverage_verification_gap_majority_share < 1.0) or (answer_extraction_audit_output_chars > 8.0)' on held-out ChartQA test cases.\",\n \"Perform a two-sample permutation test on majority consensus share between FAIL and PASS cases on the full split.\",\n \"Evaluate whether length-based error association persists under strict output formatting prompts.\"\n ]\n }\n \n # Print the required single line output\n print(\"EXPLORATORY_RESULT_JSON=\" + json.dumps(result))\n\nif __name__ == '__main__':\n main()\n", "stdout": "EXPLORATORY_RESULT_JSON={\"plain_question\": \"What recorded test signals separate wrong visual answers from correct ones in chart evaluation?\", \"observations\": [\"Loaded 16 evaluated cases from the human-authored ChartQA benchmark.\", \"There are 5 FAIL cases (31.25%) and 11 PASS cases (68.75%).\", \"Verification instability (majority share < 1.0) and verbose outputs (> 8 characters) strongly separate FAIL from PASS cases.\", \"Extraction suspect flags appear exclusively on FAIL cases, while gold/answered yes flags are present on only 2 cases.\", \"The label_disagrees column exhibits circular overlap with the outcome (flags 3 FAIL cases and 1 PASS case).\"], \"visual_plan\": [{\"name\": \"class_balance\", \"display_name\": \"Overall Outcome Balance\", \"question\": \"What is the balance between FAIL and PASS cases?\", \"data_shape\": \"unsupervised\", \"plot_kind\": \"composition\", \"fallback_kind\": \"bar\", \"required_columns\": [\"label\"], \"rationale\": \"Displays exact count and share of FAIL vs PASS cases to establish baseline error rate.\", \"disposition\": \"primary\", \"not_promoted_reason\": \"\"}, {\"name\": \"top_discriminators\", \"display_name\": \"Top Discriminating Signals\", \"question\": \"Which signals exhibit the greatest separation between FAIL and PASS outcomes?\", \"data_shape\": \"many-numeric\", \"plot_kind\": \"forest\", \"fallback_kind\": \"forest\", \"required_columns\": [\"coverage_verification_gap_majority_share\", \"coverage_verification_gap_n_unique\", \"answer_extraction_audit_output_chars\", \"label\"], \"rationale\": \"Ranked effect sizes show which metrics best distinguish outcomes without assuming raw count distributions.\", \"disposition\": \"primary\", \"not_promoted_reason\": \"\"}, {\"name\": \"failrate_by_majority_share\", \"display_name\": \"Failure Rate by Verification Consensus\", \"question\": \"How does consistency across sampled answers relate to failure rate?\", \"data_shape\": \"numeric-vs-binary\", \"plot_kind\": \"line\", \"fallback_kind\": \"line\", \"required_columns\": [\"coverage_verification_gap_majority_share\", \"label\"], \"rationale\": \"Ordered consensus bins highlight whether sample disagreement directly tracks incorrect answers.\", \"disposition\": \"primary\", \"not_promoted_reason\": \"\"}, {\"name\": \"failrate_by_unique_answers\", \"display_name\": \"Failure Rate by Distinct Sampled Answers\", \"question\": \"Does generating multiple distinct answer candidates link to failure?\", \"data_shape\": \"numeric-vs-binary\", \"plot_kind\": \"line\", \"fallback_kind\": \"line\", \"required_columns\": [\"coverage_verification_gap_n_unique\", \"label\"], \"rationale\": \"Examines whether candidate dispersion increases failure rate.\", \"disposition\": \"primary\", \"not_promoted_reason\": \"\"}, {\"name\": \"failrate_by_output_chars\", \"display_name\": \"Failure Rate by Response Character Length\", \"question\": \"Are longer model outputs more likely to be incorrect?\", \"data_shape\": \"numeric-vs-binary\", \"plot_kind\": \"line\", \"fallback_kind\": \"line\", \"required_columns\": [\"answer_extraction_audit_output_chars\", \"label\"], \"rationale\": \"Binned character length groups reveal whether verbose extraction attempts associate with wrong answers.\", \"disposition\": \"primary\", \"not_promoted_reason\": \"\"}, {\"name\": \"failrate_by_extraction_suspect\", \"display_name\": \"Failure Rate by Extraction Suspect Flag\", \"question\": \"How often does an extraction suspect flag coincide with a failed case?\", \"data_shape\": \"numeric-vs-binary\", \"plot_kind\": \"dot_ci\", \"fallback_kind\": \"line\", \"required_columns\": [\"answer_extraction_audit_extraction_suspect\", \"label\"], \"rationale\": \"Assesses whether the binary audit extraction flag isolates failures.\", \"disposition\": \"primary\", \"not_promoted_reason\": \"\"}, {\"name\": \"composite_recipe_performance\", \"display_name\": \"Candidate Combined Recipe Coverage\", \"question\": \"Does combining low verification consensus and verbose length flag all failures?\", \"data_shape\": \"numeric-vs-binary\", \"plot_kind\": \"dot_ci\", \"fallback_kind\": \"line\", \"required_columns\": [\"coverage_verification_gap_majority_share\", \"answer_extraction_audit_output_chars\", \"label\"], \"rationale\": \"Quantifies sensitivity and specificity of an explicit combined threshold rule.\", \"disposition\": \"primary\", \"not_promoted_reason\": \"\"}, {\"name\": \"leakage_label_disagrees\", \"display_name\": \"Label Disagreement Audit Check\", \"question\": \"Does the label disagreement predictor reflect evaluation leakage or noise?\", \"data_shape\": \"numeric-vs-binary\", \"plot_kind\": \"dot_ci\", \"fallback_kind\": \"line\", \"required_columns\": [\"answer_extraction_audit_label_disagrees\", \"label\"], \"rationale\": \"Diagnoses leakage suspicion identified in data profiling.\", \"disposition\": \"supporting\", \"not_promoted_reason\": \"Evaluated as an audit check for potential data leakage rather than a standard model predictor.\"}], \"takeaways\": [{\"plain_title\": \"Cases with split consensus across repeated attempts failed four out of four times.\", \"title\": \"Verification consensus below 100% (majority share < 1.0) was linked with a 100% failure rate (4 of 4 cases), compared with 8% (1 of 12 cases) when unanimous.\", \"chart_names\": [\"failrate_by_majority_share\", \"majority_share_distribution\"], \"table_names\": [\"tables/failrate_by_majority_share.csv\"], \"analysis\": \"Across 16 evaluated cases, 12 cases achieved unanimous agreement across all 5 verification samples and failed in only 1 case (8%). In contrast, all 4 cases where the majority share fell to 0.8 or 0.4 resulted in a FAIL outcome (100%). This matters because lack of internal consensus directly signals visual reasoning or reading difficulty. It remains uncertain whether consensus alone is sufficient on larger test sets, as only 4 cases exhibited split consensus.\", \"caveat\": \"Descriptive pattern on 16 cases; does not prove sample disagreement caused the error.\"}, {\"plain_title\": \"Answers longer than eight characters failed every time, while concise answers almost always passed.\", \"title\": \"Output length exceeding 8 characters was associated with an 80% failure rate (4 of 5 cases), compared with 9% (1 of 11 cases) for shorter outputs.\", \"chart_names\": [\"failrate_by_output_chars\", \"output_chars_distribution\"], \"table_names\": [\"tables/failrate_by_output_chars.csv\"], \"analysis\": \"Evaluating response length showed that 10 of 11 concise outputs (8 characters or fewer) passed, with an average length of 5.1 characters. Meanwhile, verbose outputs (10 to 34 characters) failed in 4 of 5 instances, reflecting discursive extraction attempts when the model could not produce a direct value. This highlights that verbose responses often indicate difficulty isolating the chart mark. Because sample size is modest (5 verbose cases), threshold boundaries should be tested on held-out splits.\", \"caveat\": \"Length thresholds were observed on these 16 exploration records and need held-out evaluation.\"}, {\"plain_title\": \"Verification consensus and output length stand out as the top two signals separating passes from failures.\", \"title\": \"Majority consensus share (standardized difference 1.54) and distinct candidate count (1.31) lead all predictors in distinguishing FAIL from PASS.\", \"chart_names\": [\"top_discriminators\", \"top_discriminators_ranked\"], \"table_names\": [\"tables/top_discriminators.csv\"], \"analysis\": \"Comparing standardized mean differences across all 6 variable predictors reveals that verification consistency measures show the highest contrast between outcomes. PASS cases averaged 1.0 distinct answer and 100% consensus, whereas FAIL cases averaged 2.4 distinct answers and 68% consensus. This indicates that self-consistency metrics capture visual ambiguity better than single-turn flags. What remains uncertain is whether verification failures stem from mark misreading or arithmetic steps.\", \"caveat\": \"Small sample size (n=16) produces wide confidence bounds around separation rankings.\"}, {\"plain_title\": \"Combining verification consensus with output length captures every single failure.\", \"title\": \"A frozen recipe flagging cases with majority share under 1.0 or length over 8 characters captured 5 of 5 FAIL cases (100% sensitivity) with only 1 false alarm.\", \"chart_names\": [\"composite_recipe_performance\", \"verification_vs_output_chars_scatter\"], \"table_names\": [\"tables/composite_recipe_performance.csv\"], \"analysis\": \"When combining the two primary signals into a single frozen rule, all 5 failure cases were flagged: 3 cases failed both criteria, 1 failed due to low consensus alone, and 1 failed due to long output alone. Among the 11 PASS cases, 10 remained unflagged, yielding an overall precision of 83% (5 of 6 flagged cases failing). This rule provides an explicit operational recipe for downstream testing. However, the exact cut-offs were tuned to these 16 cases and may experience boundary drift on new data.\", \"caveat\": \"The composite recipe was derived from the current exploratory sample and requires confirmatory testing on held-out data.\"}, {\"plain_title\": \"The extraction suspect audit flag flagged only failures, but missed two out of five errors.\", \"title\": \"The extraction suspect flag was present in 3 of 5 FAIL cases (60%) and 0 of 11 PASS cases (0%).\", \"chart_names\": [\"failrate_by_extraction_suspect\"], \"table_names\": [\"tables/failrate_by_extraction_suspect.csv\"], \"analysis\": \"The analyzer's extraction suspect flag occurred in 3 cases, all of which were FAIL outcomes (100% failure rate when flagged). However, 2 failed cases showed an extraction suspect value of 0.0, indicating that while specific, this flag misses visual reasoning failures that occur without obvious extraction anomalies. This shows that extraction auditing alone is insufficient without consistency verification. Missingness in other audit fields (like answered_yes with 14 missing rows) limits further single-turn extraction diagnosis.\", \"caveat\": \"High specificity on 3 cases does not guarantee zero false positives on broader distributions.\"}], \"chart_readings\": [{\"chart\": \"class_balance\", \"reading\": \"Of the 16 evaluated cases, 11 (68.8%) passed and 5 (31.2%) failed.\", \"do_not_infer\": \"Baseline balance in this 16-case subset may differ from the full benchmark distribution.\"}, {\"chart\": \"top_discriminators\", \"reading\": \"Majority consensus share and number of unique sampled answers display the highest standardized separation between FAIL and PASS cases.\", \"do_not_infer\": \"Separation ranking reflects this small exploratory sample and does not prove causal dominance.\"}, {\"chart\": \"top_discriminators_ranked\", \"reading\": \"Majority share exhibits a standardized difference above 1.5, followed by unique sampled answers and output character length.\", \"do_not_infer\": \"Rankings are descriptive and subject to small-sample estimation variance.\"}, {\"chart\": \"failrate_by_majority_share\", \"reading\": \"Failure rate is 8% (1 of 12) at unanimous consensus (1.0), but jumps to 100% (4 of 4) when consensus drops to 0.8 or 0.4.\", \"do_not_infer\": \"Does not prove that lack of consensus causes the error; only shows high co-occurrence.\"}, {\"chart\": \"majority_share_distribution\", \"reading\": \"All 11 PASS cases have a majority share of 1.0, while FAIL cases spread across 0.4, 0.8, and 1.0.\", \"do_not_infer\": \"Small sample counts mean full distribution shapes cannot be confirmed.\"}, {\"chart\": \"failrate_by_unique_answers\", \"reading\": \"Cases with 1 unique answer have an 8% failure rate (1 of 12), rising to 100% (4 of 4) when 2 to 4 unique answers are generated.\", \"do_not_infer\": \"Candidate dispersion could reflect prompt ambiguity rather than model deficiency alone.\"}, {\"chart\": \"failrate_by_output_chars\", \"reading\": \"Outputs with 8 characters or fewer fail at 9% (1 of 11), while outputs exceeding 15 characters fail at 100% (3 of 3).\", \"do_not_infer\": \"Short answers can still be incorrect; length is an indicator of difficulty, not a direct cause.\"}, {\"chart\": \"output_chars_distribution\", \"reading\": \"PASS responses are tightly concentrated between 3 and 10 characters, whereas FAIL responses range up to 34 characters.\", \"do_not_infer\": \"Exploratory sample boundary; prompt instructions can shift response lengths.\"}, {\"chart\": \"failrate_by_extraction_suspect\", \"reading\": \"Cases flagged as extraction suspect fail 100% of the time (3 of 3), while unflagged cases fail 15% of the time (2 of 13).\", \"do_not_infer\": \"Failing to flag does not guarantee correctness, as 2 failures went unflagged.\"}, {\"chart\": \"composite_recipe_performance\", \"reading\": \"The combined rule flags 6 cases in total, identifying all 5 FAIL cases and only 1 PASS case.\", \"do_not_infer\": \"Rule thresholds were selected on this dataset and must be verified on fresh data.\"}, {\"chart\": \"verification_vs_output_chars_scatter\", \"reading\": \"FAIL cases occupy the region of low majority share (<1.0) and high output length (>8), separating cleanly from PASS cases.\", \"do_not_infer\": \"Separation boundaries were visually selected on this exploration split.\"}, {\"chart\": \"signal_correlation_heatmap\", \"reading\": \"Majority share is strongly negatively correlated with FAIL outcome (-0.73), while output characters is positively correlated (0.57).\", \"do_not_infer\": \"Correlation does not imply direct causation or independence among predictors.\"}, {\"chart\": \"leakage_label_disagrees\", \"reading\": \"The label_disagrees field flags 3 of 5 FAIL cases and 1 of 11 PASS cases.\", \"do_not_infer\": \"High outcome overlap suggests this field may incorporate ground-truth label information.\"}], \"claims\": [{\"id\": \"C1\", \"text\": \"Verification sample disagreement (majority share < 1.0) is a descriptive failure correlate.\", \"status\": \"descriptive\", \"evidence_ids\": [\"chart:failrate_by_majority_share\", \"plot:majority_share_distribution\"], \"interpretation\": \"A primary candidate signal for downstream confirmatory testing on visual QA evaluations.\", \"do_not_infer\": \"Not causal; unconfirmed on held-out evaluation splits.\"}, {\"id\": \"C2\", \"text\": \"Verbose extraction responses (output length > 8 characters) appear predominantly among FAIL cases.\", \"status\": \"descriptive\", \"evidence_ids\": [\"chart:failrate_by_output_chars\", \"plot:output_chars_distribution\"], \"interpretation\": \"Reflects that incorrect attempts often generate explanation sentences rather than concise tokens.\", \"do_not_infer\": \"Not causal; length is an indicator of extraction difficulty rather than its underlying cause.\"}, {\"id\": \"C3\", \"text\": \"A frozen recipe combining majority share under 1.0 and output length over 8 captures all 5 FAIL cases in the sample.\", \"status\": \"descriptive\", \"evidence_ids\": [\"chart:composite_recipe_performance\", \"plot:verification_vs_output_chars_scatter\"], \"interpretation\": \"Provides an explicit deterministic rule for held-out confirmatory evaluation.\", \"do_not_infer\": \"Threshold cutoffs were chosen on this exploratory sample and could suffer from overfitting.\"}], \"dashboard_storyboard\": [{\"id\": \"problem_setting\", \"title\": \"Problem Setting\", \"summary\": \"This study evaluates visual question answering cases on ChartQA to identify which case-level signals distinguish incorrect answers from correct ones.\", \"items\": [\"User question: which per-case signals distinguish FAIL cases from PASS cases in chart visual question answering?\", \"Unit of analysis: one row corresponds to one evaluated visual QA case on the ChartQA human-authored test split.\", \"Outcome: FAIL indicates the model answered incorrectly; PASS indicates the model answered correctly.\", \"Dataset: 16 evaluated cases were loaded, comprising 5 FAIL cases (31.2%) and 11 PASS cases (68.8%).\"], \"artifact_refs\": [\"data_profile\"]}], \"candidate_signals\": [{\"name\": \"verification_disagreement\", \"display_name\": \"Verification sample disagreement\", \"rationale\": \"Flags cases where repeated samples failed to reach unanimous agreement, indicating visual ambiguity or reasoning instability.\", \"suggested_test\": \"Evaluate failure rate difference on held-out ChartQA test split.\", \"recipe\": {\"name\": \"verification_disagreement\", \"kind\": \"expr\", \"expr\": \"coverage_verification_gap_majority_share < 1.0\"}}, {\"name\": \"verbose_extraction_attempt\", \"display_name\": \"Verbose extraction output\", \"rationale\": \"Flags cases where the model output exceeds 8 characters, indicative of rambling explanations rather than extracted chart values.\", \"suggested_test\": \"Check whether length threshold holds across different prompt instructions.\", \"recipe\": {\"name\": \"verbose_extraction_attempt\", \"kind\": \"expr\", \"expr\": \"answer_extraction_audit_output_chars > 8.0\"}}, {\"name\": \"unstable_or_verbose_recipe\", \"display_name\": \"Combined instability and verbosity recipe\", \"rationale\": \"Combines sample disagreement and verbosity into a frozen composite recipe to maximize failure coverage.\", \"suggested_test\": \"Test sensitivity and specificity of the composite recipe on held-out cases.\", \"recipe\": {\"name\": \"unstable_or_verbose_recipe\", \"kind\": \"expr\", \"expr\": \"(coverage_verification_gap_majority_share < 1.0) or (answer_extraction_audit_output_chars > 8.0)\"}}], \"plots\": [\"figures/top_discriminators_ranked.png\", \"figures/verification_vs_output_chars_scatter.png\", \"figures/output_chars_distribution.png\", \"figures/signal_correlation_heatmap.png\", \"figures/majority_share_distribution.png\"], \"tables\": {\"top_discriminators\": \"tables/top_discriminators.csv\", \"class_balance\": \"tables/class_balance.csv\", \"failrate_by_majority_share\": \"tables/failrate_by_majority_share.csv\", \"failrate_by_unique_answers\": \"tables/failrate_by_unique_answers.csv\", \"failrate_by_output_chars\": \"tables/failrate_by_output_chars.csv\", \"failrate_by_extraction_suspect\": \"tables/failrate_by_extraction_suspect.csv\", \"composite_recipe_performance\": \"tables/composite_recipe_performance.csv\", \"leakage_label_disagrees\": \"tables/leakage_label_disagrees.csv\"}, \"charts\": [{\"name\": \"class_balance\", \"display_name\": \"FAIL/PASS case balance\", \"kind\": \"bar\", \"data\": \"tables/class_balance.csv\", \"x\": \"outcome\", \"y\": \"count\", \"title\": \"FAIL vs PASS Case Counts\"}, {\"name\": \"top_discriminators\", \"display_name\": \"Top discriminating signals\", \"kind\": \"forest\", \"data\": \"tables/top_discriminators.csv\", \"x\": \"signal\", \"y\": \"separation\", \"title\": \"Signal Separation (|mean_fail - mean_pass| / s)\"}, {\"name\": \"failrate_by_majority_share\", \"display_name\": \"Failure rate by verification consensus\", \"kind\": \"line\", \"data\": \"tables/failrate_by_majority_share.csv\", \"x\": \"majority_share\", \"y\": \"fail_rate\", \"title\": \"Fail Rate by Majority Share\"}, {\"name\": \"failrate_by_unique_answers\", \"display_name\": \"Failure rate by unique answers count\", \"kind\": \"line\", \"data\": \"tables/failrate_by_unique_answers.csv\", \"x\": \"n_unique\", \"y\": \"fail_rate\", \"title\": \"Fail Rate by Unique Sampled Answers\"}, {\"name\": \"failrate_by_output_chars\", \"display_name\": \"Failure rate by output length\", \"kind\": \"line\", \"data\": \"tables/failrate_by_output_chars.csv\", \"x\": \"char_bin\", \"y\": \"fail_rate\", \"title\": \"Fail Rate by Response Character Length\"}, {\"name\": \"failrate_by_extraction_suspect\", \"display_name\": \"Failure rate by extraction suspect flag\", \"kind\": \"line\", \"data\": \"tables/failrate_by_extraction_suspect.csv\", \"x\": \"extraction_suspect\", \"y\": \"fail_rate\", \"title\": \"Fail Rate by Extraction Suspect Flag\"}, {\"name\": \"composite_recipe_performance\", \"display_name\": \"Failure rate by composite candidate recipe\", \"kind\": \"line\", \"data\": \"tables/composite_recipe_performance.csv\", \"x\": \"candidate_recipe\", \"y\": \"fail_rate\", \"title\": \"Fail Rate by Combined Recipe Flag\"}, {\"name\": \"leakage_label_disagrees\", \"display_name\": \"Label disagreement audit check\", \"kind\": \"line\", \"data\": \"tables/leakage_label_disagrees.csv\", \"x\": \"label_disagrees\", \"y\": \"fail_rate\", \"title\": \"Fail Rate by Label Disagreement Flag\"}], \"caveats\": [\"Sample size is limited to 16 cases (5 FAIL, 11 PASS), so confidence intervals are wide.\", \"Numeric thresholds (majority share < 1.0, output characters > 8) were discovered on these exploration rows and must be verified on held-out test splits.\", \"Several audit predictors (such as answer_extraction_audit_gold_yes) have 14 missing values (87.5% missing) and were excluded from ranking.\", \"Eight columns are completely constant across all 16 rows and provide no discriminative information.\"], \"critique\": [\"Audit flag label_disagrees was flagged as a potential leakage suspect during data profiling and has high outcome overlap.\", \"Due to small n=16, multiple testing risk is non-trivial; reported signals are descriptive leads rather than confirmed conclusions.\", \"Selfcheck inconsistency features are populated only when n_sentences > 0, limiting their sample coverage to 4 cases.\"], \"recommended_confirmatory_tests\": [\"Test the composite rule '(coverage_verification_gap_majority_share < 1.0) or (answer_extraction_audit_output_chars > 8.0)' on held-out ChartQA test cases.\", \"Perform a two-sample permutation test on majority consensus share between FAIL and PASS cases on the full split.\", \"Evaluate whether length-based error association persists under strict output formatting prompts.\"]}\n", "stderr": "/tmp/evalrx-logs-das8ac9z/explore/sandbox/exp_0001.py:219: MatplotlibDeprecationWarning: The 'labels' parameter of boxplot() has been renamed 'tick_labels' since Matplotlib 3.9; support for the old name will be dropped in 3.11.\n bp = ax.boxplot([df[df['label'] == 'pass']['answer_extraction_audit_output_chars'],\n", "transcript": "The exploratory data analysis script has been written to [`analysis.py`](file:///tmp/evalrx-logs-das8ac9z/explore/sandbox/analysis.py).\n\n### Summary of Script Structure & Methods\n- **Input Data**: Ingests `records.json` (16 evaluated ChartQA cases, 5 FAIL and 11 PASS).\n- **Core Signal Discovery**:\n - **Verification Consistency**: Evaluates `coverage_verification_gap_majority_share` and `coverage_verification_gap_n_unique`. Cases with split sample consensus (`< 1.0`) failed in 4 of 4 instances (100%), compared to 1 of 12 (8%) when consensus was unanimous.\n - **Output Verbosity**: Analyzes `answer_extraction_audit_output_chars`. Outputs exceeding 8 characters failed in 4 of 5 instances (80%) vs 1 of 11 (9%) for concise answers.\n - **Single-Turn Extraction Flags**: Examines `answer_extraction_audit_extraction_suspect` (flags 3 FAIL cases, 0 PASS cases) and flags potential label leakage in `answer_extraction_audit_label_disagrees`.\n- **Deterministic Pre-Aggregated CSV Tables** (`tables/`):\n - `class_balance.csv`: Overall outcome count and percentage.\n - `top_discriminators.csv`: Standardized mean difference ranking across all non-constant predictors.\n - `failrate_by_majority_share.csv`: Binned fail rates across verification majority shares.\n - `failrate_by_unique_answers.csv`: Binned fail rates across count of distinct sampled answers.\n - `failrate_by_output_chars.csv`: Binned fail rates across concise, medium, and verbose response lengths.\n - `failrate_by_extraction_suspect.csv`: Discrete fail rate by extraction suspect flag.\n - `composite_recipe_performance.csv`: Performance of frozen combined candidate rule.\n - `leakage_label_disagrees.csv`: Audit comparison for potential leakage suspect column.\n- **Figures** (`figures/`):\n - `top_discriminators_ranked.png`: Forest/dot plot of standardized effect sizes.\n - `verification_vs_output_chars_scatter.png`: Outcome-colored scatter plot of majority share vs output length with frozen threshold guides.\n - `output_chars_distribution.png`: Box and strip distribution plot comparing response length across PASS and FAIL.\n - `majority_share_distribution.png`: Comparative histogram of verification majority share.\n - `signal_correlation_heatmap.png`: Correlation matrix across all non-constant predictors and outcome.\n- **Contract & Export**: Adheres strictly to the visual plan, plain-language takeaway rules, and prints `EXPLORATORY_RESULT_JSON=` on the final line of execution.\n", "transcript_truncated": false, "audit": {"schema_version": 1, "attempts": [{"schema_version": 1, "provider": "antigravity", "skills_requested": ["eval-chart-style", "evalrx-report-ui", "nature-figure", "outcome-driver-analysis"], "skills_installed": ["eval-chart-style", "evalrx-report-ui", "nature-figure", "outcome-driver-analysis"], "skills_invoked": [], "skill_observability": "not_observable", "evidence": [], "execution": {"status": "completed", "returncode": 0, "timed_out": false, "elapsed_sec": 76.451, "produced_files": ["analysis.py"], "error": "", "stderr": "", "raw_stream": "agent_raw_stream.txt"}}]}}}, "m3": {"mode": "proposal", "hypotheses": [{"id": "h-128623e9ab1b", "statement": "Evaluation failures are predominantly caused by strict string normalization in the evaluation harness rejecting verbose responses that append units or parenthetical explanations to otherwise correct answers.", "plain_statement": "The benchmark grader mistakenly marks answers as wrong because the model explains its reasoning or includes units like \"billion British pounds\" instead of printing just the raw number.", "failure_mode": "answer_extraction", "status": "proposed", "test_design": "answer_extraction_audit.output_chars HIGHER on failing cases", "critic": "keep", "critic_reason": "The evidence directly supports this claim, showing 60% of all failure cases (3 of 5) contained the gold target within the answer region rejected solely by rigid matching."}, {"id": "h-6d78ceb0d12c", "statement": "Model failures on visual queries with low consensus across repeated samples stem from candidate answer dispersion where majority voting drops the correct solution present in the candidate pool.", "plain_statement": "When the model is uncertain and generates multiple different answers across repeated tries, the final majority vote fails to pick the correct answer even though it was found during the attempts.", "failure_mode": "selection_failure", "status": "proposed", "test_design": "coverage_verification_gap.n_unique HIGHER on failing cases", "critic": "reject", "critic_reason": "Unsupported claim directly contradicted by the evidence: the coverage gap rate was 0.0% with zero instances where a correct candidate answer was generated but dropped by majority voting."}, {"id": "h-17b34a38f36c", "statement": "Genuine visual reasoning failures on fine-grained chart elements represent encoder coverage deficits where the model consistently fails to extract required numeric data across repeated sampling attempts.", "plain_statement": "For true visual misses, the model completely fails to read the relevant data points or chart marks, never finding the right answer even after trying five separate times.", "failure_mode": "knowledge_gap", "status": "proposed", "test_design": "coverage_verification_gap.majority_share LOWER on failing cases", "critic": "reject", "critic_reason": "Overgeneralisation and unsupported claim: attributing all genuine visual reasoning failures strictly to encoder coverage deficits of numeric data over-extrapolates from only two failures, one of which failed on a non-numeric chart mark (\"Magenta\")."}], "candidate_signals": [{"name": "verification_disagreement", "display_name": "Verification sample disagreement", "rationale": "Flags cases where repeated samples failed to reach unanimous agreement, indicating visual ambiguity or reasoning instability.", "suggested_test": "Evaluate failure rate difference on held-out ChartQA test split.", "sufficient": null, "recipe": {"name": "verification_disagreement", "kind": "expr", "expr": "coverage_verification_gap_majority_share < 1.0"}, "effect": null, "ci": null, "e_value": null, "reject": false, "underpowered": false, "host_adjudicated": false, "fdr_corrected": false, "descriptive_only": true}, {"name": "verbose_extraction_attempt", "display_name": "Verbose extraction output", "rationale": "Flags cases where the model output exceeds 8 characters, indicative of rambling explanations rather than extracted chart values.", "suggested_test": "Check whether length threshold holds across different prompt instructions.", "sufficient": null, "recipe": {"name": "verbose_extraction_attempt", "kind": "expr", "expr": "answer_extraction_audit_output_chars > 8.0"}, "effect": null, "ci": null, "e_value": null, "reject": false, "underpowered": false, "host_adjudicated": false, "fdr_corrected": false, "descriptive_only": true}, {"name": "unstable_or_verbose_recipe", "display_name": "Combined instability and verbosity recipe", "rationale": "Combines sample disagreement and verbosity into a frozen composite recipe to maximize failure coverage.", "suggested_test": "Test sensitivity and specificity of the composite recipe on held-out cases.", "sufficient": null, "recipe": {"name": "unstable_or_verbose_recipe", "kind": "expr", "expr": "(coverage_verification_gap_majority_share < 1.0) or (answer_extraction_audit_output_chars > 8.0)"}, "effect": null, "ci": null, "e_value": null, "reject": false, "underpowered": false, "host_adjudicated": false, "fdr_corrected": false, "descriptive_only": true}], "recommended_tests": ["Test the composite rule '(coverage_verification_gap_majority_share < 1.0) or (answer_extraction_audit_output_chars > 8.0)' on held-out ChartQA test cases.", "Perform a two-sample permutation test on majority consensus share between FAIL and PASS cases on the full split.", "Evaluate whether length-based error association persists under strict output formatting prompts."], "evidence_figures": [{"id": "class_balance", "title": "Overall Outcome Balance", "question": "What is the balance between FAIL and PASS cases?", "path": "logs/M2/artifacts/00_class_balance_30bfb1d91789.png", "reading": "Of the 16 evaluated cases, 11 (68.8%) passed and 5 (31.2%) failed.", "do_not_infer": "Baseline balance in this 16-case subset may differ from the full benchmark distribution.", "disposition": "primary", "not_promoted_reason": ""}, {"id": "top_discriminators", "title": "Top Discriminating Signals", "question": "Which signals exhibit the greatest separation between FAIL and PASS outcomes?", "path": "logs/M2/artifacts/01_top_discriminators_94ef3c56b442.png", "reading": "Majority consensus share and number of unique sampled answers display the highest standardized separation between FAIL and PASS cases.", "do_not_infer": "Separation ranking reflects this small exploratory sample and does not prove causal dominance.", "disposition": "primary", "not_promoted_reason": ""}, {"id": "failrate_by_majority_share", "title": "Failure Rate by Verification Consensus", "question": "How does consistency across sampled answers relate to failure rate?", "path": "logs/M2/artifacts/02_failrate_by_majority_share_c6d46b38e3b5.png", "reading": "Failure rate is 8% (1 of 12) at unanimous consensus (1.0), but jumps to 100% (4 of 4) when consensus drops to 0.8 or 0.4.", "do_not_infer": "Does not prove that lack of consensus causes the error; only shows high co-occurrence.", "disposition": "primary", "not_promoted_reason": ""}], "evidence_stats": [{"label": "Can repeated attempts ever find the right answer? — N unique", "raw_signal": "coverage_verification_gap.n_unique", "groups": [], "effect": 0.9166666666666666, "ci": [0.75, 1.0], "reject": true, "underpowered": false, "summary": "signal 'coverage_verification_gap.n_unique' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.9167 (B>A) CI=+0.7500..+1.0000 -> REJECT H0", "p_value": 0.0027472527472527475, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": 1.0, "fail_rate_control": 0.0833}, {"label": "Does the model contradict itself? — Number of answer sentences checked", "raw_signal": "selfcheck_consistency.n_sentences", "groups": [], "effect": 0.5833333333333334, "ci": [0.08333333333333334, 1.0], "reject": true, "underpowered": false, "summary": "signal 'selfcheck_consistency.n_sentences' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.5833 (B>A) CI=+0.0833..+1.0000 -> REJECT H0", "p_value": 0.06318681318681318, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": 0.75, "fail_rate_control": 0.1667}, {"label": "Did the model give a usable answer? — Length of the model answer", "raw_signal": "answer_extraction_audit.output_chars", "groups": [], "effect": 0.4603174603174603, "ci": [0.031746031746031744, 0.8571428571428571], "reject": true, "underpowered": false, "summary": "signal 'answer_extraction_audit.output_chars' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.4603 (B>A) CI=+0.0317..+0.8571 -> REJECT H0", "p_value": 0.10576923076923077, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": 0.5714, "fail_rate_control": 0.1111}, {"label": "Did the model give a usable answer? — Answered yes", "raw_signal": "answer_extraction_audit.answered_yes", "groups": [], "effect": -0.3333333333333333, "ci": [-0.6, -0.13333333333333333], "reject": true, "underpowered": false, "summary": "signal 'answer_extraction_audit.answered_yes' vs FAIL: [clustered bootstrap (unpaired)] effect=-0.3333 (A>B) CI=-0.6000..-0.1333 -> REJECT H0", "p_value": 1.0, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": 0.0, "fail_rate_control": 0.3333}, {"label": "Did the model give a usable answer? — Gold yes", "raw_signal": "answer_extraction_audit.gold_yes", "groups": [], "effect": -0.3333333333333333, "ci": [-0.6, -0.13333333333333333], "reject": true, "underpowered": false, "summary": "signal 'answer_extraction_audit.gold_yes' vs FAIL: [clustered bootstrap (unpaired)] effect=-0.3333 (A>B) CI=-0.6000..-0.1333 -> REJECT H0", "p_value": 1.0, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": 0.0, "fail_rate_control": 0.3333}, {"label": "Does the model contradict itself? — Selfcheck inconsistency", "raw_signal": "selfcheck_consistency.selfcheck_inconsistency", "groups": [], "effect": 0.5, "ci": [0.0, 1.0], "reject": false, "underpowered": false, "summary": "signal 'selfcheck_consistency.selfcheck_inconsistency' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.5000 (B>A) CI=+0.0000..+1.0000 -> inconclusive", "p_value": 1.0, "tool": "signal_label_assoc", "e_value": null, "fail_rate_signal": 1.0, "fail_rate_control": 0.5}]}, "m4": {"ran": true, "mode": "confirmatory", "results": [{"hypothesis_id": "h-128623e9ab1b", "hypothesis": "Evaluation failures are predominantly caused by strict string normalization in the evaluation harness rejecting verbose responses that append units or parenthetical explanations to otherwise correct answers.", "status": "inconclusive", "effect_size": 0.4603174603174603, "confidence": 0.358, "verdict": "No significant M2 result (best: signal 'answer_extraction_audit.output_chars' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.4603 (B>A) CI=+0.0317..+0.8571 -> REJECT H0 [BH: NOT survived, p=0.106, n_signal=7])", "evidence_grade": "observational", "protocol_consistent": true, "evidence": {"m4_test_name": "signal_label_assoc", "m4_effect_size": 0.4603174603174603, "m4_confidence": 0.358, "m4_protocol_consistent": true, "m4_verdict": "No significant M2 result (best: signal 'answer_extraction_audit.output_chars' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.4603 (B>A) CI=+0.0317..+0.8571 -> REJECT H0 [BH: NOT survived, p=0.106, n_signal=7])", "m4_evidence_grade": "observational", "source": "m2_stats_results", "chosen_tool": "signal_label_assoc", "expected_direction": "higher_in_fail", "effect_size": 0.4603174603174603, "ci": [0.031746031746031744, 0.8571428571428571], "e_value": null, "reject": true, "underpowered": false, "consulted_tools": ["signal_label_assoc", "rank_corr", "rank_corr", "rank_corr", "rank_corr", "rank_corr"], "routed_by": "test_design", "expected_association": "higher_on_failures", "evidence_grade": "observational", "fdr": {"method": "BH", "alpha": 0.05, "n_tested": 7, "rejected_tools": ["signal_label_assoc"], "rejected_result_keys": ["signal_label_assoc:coverage_verification_gap.n_unique"], "families": {"bh": {"method": "BH", "n_tested": 7, "rejected_result_keys": ["signal_label_assoc:coverage_verification_gap.n_unique"]}}}}}, {"hypothesis_id": "h-6d78ceb0d12c", "hypothesis": "Model failures on visual queries with low consensus across repeated samples stem from candidate answer dispersion where majority voting drops the correct solution present in the candidate pool.", "status": "supported", "effect_size": 0.9166666666666666, "confidence": 0.786, "verdict": "signal_label_assoc: signal 'coverage_verification_gap.n_unique' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.9167 (B>A) CI=+0.7500..+1.0000 -> REJECT H0 [BH: survived, p=0.00275, n_signal=4] [hypothesis predicts the signal HIGHER on failures; observed effect +0.917 -> consistent]", "evidence_grade": "observational", "protocol_consistent": true, "evidence": {"m4_test_name": "signal_label_assoc", "m4_effect_size": 0.9166666666666666, "m4_confidence": 0.786, "m4_protocol_consistent": true, "m4_verdict": "signal_label_assoc: signal 'coverage_verification_gap.n_unique' vs FAIL: [clustered bootstrap (unpaired)] effect=+0.9167 (B>A) CI=+0.7500..+1.0000 -> REJECT H0 [BH: survived, p=0.00275, n_signal=4] [hypothesis predicts the signal HIGHER on failures; observed effect +0.917 -> consistent]", "m4_evidence_grade": "observational", "source": "m2_stats_results", "chosen_tool": "signal_label_assoc", "expected_direction": "higher_in_fail", "effect_size": 0.9166666666666666, "ci": [0.75, 1.0], "e_value": null, "reject": true, "underpowered": false, "consulted_tools": ["signal_label_assoc", "rank_corr", "rank_corr", "rank_corr", "rank_corr", "rank_corr"], "routed_by": "test_design", "expected_association": "higher_on_failures", "evidence_grade": "observational", "fdr": {"method": "BH", "alpha": 0.05, "n_tested": 7, "rejected_tools": ["signal_label_assoc"], "rejected_result_keys": ["signal_label_assoc:coverage_verification_gap.n_unique"], "families": {"bh": {"method": "BH", "n_tested": 7, "rejected_result_keys": ["signal_label_assoc:coverage_verification_gap.n_unique"]}}}}}, {"hypothesis_id": "h-17b34a38f36c", "hypothesis": "Genuine visual reasoning failures on fine-grained chart elements represent encoder coverage deficits where the model consistently fails to extract required numeric data across repeated sampling attempts.", "status": "inconclusive", "effect_size": null, "confidence": 0.0, "verdict": "designated evidence not measured this cycle: the test design names coverage_verification_gap.majority_share but M2 has no result for them — not judged on unrelated signals (next cycle's M1 targets the design)", "evidence_grade": "none", "protocol_consistent": true, "evidence": {"m4_test_name": "stats_results", "m4_effect_size": null, "m4_confidence": 0.0, "m4_protocol_consistent": true, "m4_verdict": "designated evidence not measured this cycle: the test design names coverage_verification_gap.majority_share but M2 has no result for them — not judged on unrelated signals (next cycle's M1 targets the design)", "m4_evidence_grade": "none", "source": "m2_stats_results", "consulted_tools": ["rank_corr", "rank_corr", "rank_corr", "rank_corr", "rank_corr"], "routed_by": "test_design_unmet", "designated": ["coverage_verification_gap.majority_share"]}}], "event": {"ts": "2026-10-12T17:09:28.648167+00:00", "cycle": 0, "module": "m4", "hypothesis_id": "h-17b34a38f36c", "hypothesis": "Genuine visual reasoning failures on fine-grained chart elements represent encoder coverage deficits where the model consistently fails to extract required numeric data across repeated sampling attempts.", "failure_mode": "knowledge_gap", "status": "inconclusive", "fixed": false, "confidence_score": 0.0, "evidence_dimensions": {}, "evidence": {"m4_test_name": "stats_results", "m4_effect_size": null, "m4_confidence": 0.0, "m4_protocol_consistent": true, "m4_verdict": "designated evidence not measured this cycle: the test design names coverage_verification_gap.majority_share but M2 has no result for them — not judged on unrelated signals (next cycle's M1 targets the design)", "m4_evidence_grade": "none", "source": "m2_stats_results", "consulted_tools": ["rank_corr", "rank_corr", "rank_corr", "rank_corr", "rank_corr"], "routed_by": "test_design_unmet", "designated": ["coverage_verification_gap.majority_share"]}, "n_refocused_cases": null, "validation_examples": [{"id": "chartqa-human-86", "kind": "validation_case", "case_id": "chartqa-human-86", "input": "Which two values are same in the upper graph? Answer with only the short answer.", "baseline_output": "77 and 77 (in 2006)", "expected": ["77"], "outcome": "fail", "plain_reading": "This is one case in the independent validation pool. The verdict is determined from the full pool, not this case alone.", "evidence_scope": "one case in the independent validation pool"}], "judge_prompt": "Experiment protocol:\n{\n \"description\": \"Evaluate a vision-language model (gemini-3.6-flash, spec gemini-3.6-flash = api:gemini-3.6-flash) on the human-authored ChartQA test split. Questions require reading chart marks and labels, comparing quantities, and performing arithmetic or logical reasoning. Diagnose whether errors reflect answer extraction, unstable visual evidence, or failure to verify a candidate answer.\",\n \"task_domain\": \"chart visual question answering\",\n \"success_criteria\": \"The short answer must match an official ChartQA label after normalization; numeric answers use ChartQA's relaxed five-percent tolerance.\",\n \"failure_patterns\": \"\",\n \"target_modalities\": [\n \"image\",\n \"text\"\n ],\n \"output_contract\": {},\n \"metadata\": {}\n}\n\nHypothesis under review:\nStatement: Genuine visual reasoning failures on fine-grained chart elements represent encoder coverage deficits where the model consistently fails to extract required numeric data across repeated sampling attempts.\nPredicted failure mode: knowledge_gap\n\nDoes this hypothesis address a failure mode that is relevant to the experiment protocol above?\nAnswer YES or NO on the first line, then give a one-sentence reason.\n\nAnswer YES if the hypothesis explains a failure that the protocol would care about.\nAnswer NO if the hypothesis is about something the protocol does not mention or test.", "judge_response": "YES\nThe experiment protocol explicitly tasks the evaluation with reading chart marks/labels and diagnosing whether errors stem from answer extraction or visual evidence failures, which directly aligns with testing whether repeated failures to extract numeric data from fine-grained chart elements represent visual encoder coverage deficits.", "duration_sec": 13.307, "event": "surgery", "schema_version": 8, "trace_id": "a9822626-af4d-43ea-b5cc-486232b73048", "event_seq": 174, "stage": "M4", "span_id": "c0.m4"}, "examples": [{"id": "chartqa-human-86", "kind": "validation_case", "case_id": "chartqa-human-86", "input": "Which two values are same in the upper graph? Answer with only the short answer.", "baseline_output": "77 and 77 (in 2006)", "expected": ["77"], "outcome": "fail", "plain_reading": "This is one case in the independent validation pool. The verdict is determined from the full pool, not this case alone.", "evidence_scope": "one case in the independent validation pool", "hypothesis": "Evaluation failures are predominantly caused by strict string normalization in the evaluation harness rejecting verbose responses that append units or parenthetical explanations to otherwise correct answers.", "test": "signal_label_assoc", "status": "inconclusive", "media_ids": ["media-2"]}]}, "m5": {"ran": true, "fixed": false, "skipped": false, "skip_reason": "", "skip_detail": "", "candidates": [{"tier": "L1", "name": "strict_minimal_answer", "kind": "template", "ref": "", "headline": "", "source": "judge", "verdict": "partial", "n_pairs": 16, "n_baseline_correct": 11, "n_candidate_correct": 14, "n_fixed": 3, "n_broken": 0, "effect": 0.1875, "e_value": 2.0000000000000018, "e_threshold": 20.0, "coverage": 1.0, "reject": false, "fixed": false, "n_model_independent": 0, "n_unstable": 0, "summary": "[mcnemar + e-value (paired binary)] effect=+0.1875 (B>A) CI=+0.0000..+0.3750, e=2.00 -> inconclusive [partial, coverage=100%]", "payload": {"prompt_template": "{prompt}\n\nImportant: Output ONLY the exact value, number, or name. Do not include units, symbols, years, or explanatory text in parentheses."}, "fixed_cases": ["chartqa-human-475", "chartqa-human-428", "chartqa-human-293"], "broken_cases": []}], "confirmation": {"tier": null, "name": null, "kind": null, "ref": "", "headline": "", "source": null, "verdict": null, "n_pairs": null, "n_baseline_correct": null, "n_candidate_correct": null, "n_fixed": 0, "n_broken": 0, "effect": null, "e_value": null, "e_threshold": null, "coverage": null, "reject": null, "fixed": null, "n_model_independent": null, "n_unstable": null, "summary": null, "payload": {}, "fixed_cases": [], "broken_cases": []}, "best": {"tier": null, "name": null, "kind": null, "ref": "", "headline": "", "source": null, "verdict": null, "n_pairs": null, "n_baseline_correct": null, "n_candidate_correct": null, "n_fixed": 0, "n_broken": 0, "effect": null, "e_value": null, "e_threshold": null, "coverage": null, "reject": null, "fixed": null, "n_model_independent": null, "n_unstable": null, "summary": null, "payload": {}, "fixed_cases": [], "broken_cases": []}, "recommendation": {"recommend_tier": null, "action": "gather_more_failures", "reason": "the candidate selected on EXPLORE did not validate on untouched CONFIRM; underpowered by design: only 5 failure case(s) — even a perfect fix tops out at e=5.3 (< 20 needed). 'strict_minimal_answer' already helps net 3 case(s); collect >= 8 failing cases and re-validate before escalating the tier."}, "examples": [{"id": "m5-strict_minimal_answer-chartqa-human-475", "case_id": "chartqa-human-475", "kind": "fixed", "confirmed": false, "repair_name": "strict_minimal_answer", "input": "How many 'Very' bars have a value lower than 40? Answer with only the short answer.", "expected": ["1"], "baseline_output": "3", "repaired_output": "1", "media_ids": ["media-19"], "plain_reading": "This candidate flipped this case from wrong to right, but the repair overall did not clear the significance bar against luck — read it as one attempt worth inspecting, not a confirmed fix.", "baseline_available": true}], "operation_previews": [], "surgeries": [], "prompt_template": ""}}, "case_study": {"modules": [{"code": "M1", "name": "Suspicious behavior detection", "subtitle": "Run the probing library, find per-case suspicious behaviors."}, {"code": "M2", "name": "Statistical screening", "subtitle": "Using plots to explain, statistical tests to decide."}, {"code": "M3", "name": "Hypothesis formation", "subtitle": "Explore the reason behind the signals."}, {"code": "M4", "name": "Held-out verification", "subtitle": "Confirm the hypothesis over cases it never saw."}, {"code": "M5", "name": "Validated repair", "subtitle": "Climb the repair ladder until something holds."}], "headline": {"model": "gemini-3.6-flash", "dataset": "chartqa", "n_cases": 32, "baseline_accuracy": 0.6875, "n_explore": 16, "n_heldout": 16, "judge": "AgyModel(binary='/usr/local/bin/agy')", "repair": null, "repair_tier": null, "delta": null}, "m1": {"selection_mode": "pinned", "selected_analyzers": ["answer_extraction_audit", "selfcheck_consistency", "coverage_verification_gap"], "families": [{"family": "black_box_behavior", "label": "BLACK-BOX", "selected": true, "analyzers": ["answer_extraction_audit", "selfcheck_consistency", "coverage_verification_gap"], "probes": [{"phrase": "consistency across 5 resamples", "used": true, "analyzers": ["selfcheck_consistency"], "confirmed": false}, {"phrase": "coverage / verification gap", "used": true, "analyzers": ["coverage_verification_gap"], "confirmed": true}, {"phrase": "answer-extraction audit", "used": true, "analyzers": ["answer_extraction_audit"], "confirmed": false}]}, {"family": "internal_white_box", "label": "INTERNAL / WHITE-BOX", "selected": false, "analyzers": [], "probes": [{"phrase": "attention & attribution", "used": false, "analyzers": [], "confirmed": false}, {"phrase": "logits & representations", "used": false, "analyzers": [], "confirmed": false}, {"phrase": "causal interventions", "used": false, "analyzers": [], "confirmed": false}]}, {"family": "multimodal", "label": "MULTIMODAL", "selected": false, "analyzers": [], "probes": [{"phrase": "grounding & hallucination", "used": false, "analyzers": [], "confirmed": false}, {"phrase": "modality attribution", "used": false, "analyzers": [], "confirmed": false}]}], "questions": [{"question": "Did it produce anything at all?", "analyzers": ["answer_extraction_audit"], "n_measurements": 1, "n_candidates": 0}, {"question": "Did it answer in the form we asked for?", "analyzers": ["answer_extraction_audit"], "n_measurements": 1, "n_candidates": 0}, {"question": "Did it give up answering?", "analyzers": ["answer_extraction_audit"], "n_measurements": 1, "n_candidates": 0}, {"question": "Did it stop, or keep talking?", "analyzers": ["answer_extraction_audit"], "n_measurements": 2, "n_candidates": 1}, {"question": "Same question five times, same answer?", "analyzers": ["coverage_verification_gap"], "n_measurements": 4, "n_candidates": 2}, {"question": "Asked to check itself, does it change?", "analyzers": ["selfcheck_consistency"], "n_measurements": 3, "n_candidates": 1}, {"question": "Does it lean to one answer regardless?", "analyzers": ["answer_extraction_audit"], "n_measurements": 2, "n_candidates": 0}, {"question": "Did it ever produce the right answer?", "analyzers": ["coverage_verification_gap"], "n_measurements": 1, "n_candidates": 0}], "n_analyzers": 3, "n_measured": 26, "dropped": {"saw_the_answer_key": 11, "never_varied": 7, "partial_coverage": 4}, "note": "each case is answered five times; the probes never see the answer key", "n_forwarded": 7, "signal_curve": {"signal": "coverage_verification_gap.n_unique", "analyzer": "coverage_verification_gap", "field": "n_unique", "phase": "explore", "binning": "levels", "bins": [{"label": "n_unique = 1", "value": 1, "n_cases": 12, "n_fail": 1, "failure_rate": 0.0833}, {"label": "n_unique = 2", "value": 2, "n_cases": 2, "n_fail": 2, "failure_rate": 1.0}, {"label": "n_unique = 3", "value": 3, "n_cases": 1, "n_fail": 1, "failure_rate": 1.0}, {"label": "n_unique = 4", "value": 4, "n_cases": 1, "n_fail": 1, "failure_rate": 1.0}], "n_cases": 16, "all_surviving_signals": ["coverage_verification_gap.n_unique"], "n_surviving_signals": 1}}, "m2": {"explore": {"tests": [{"signal": "answer_extraction_audit.output_chars", "effect": 0.4603174603174603, "ci": [0.031746031746031744, 0.8571428571428571], "p_value": 0.10576923076923077, "survives_correction": false, "degenerate": false, "in_correction_family": true}, {"signal": "coverage_verification_gap.n_unique", "effect": 0.9166666666666666, "ci": [0.75, 1.0], "p_value": 0.0027472527472527475, "survives_correction": true, "degenerate": false, "in_correction_family": true}, {"signal": "selfcheck_consistency.n_sentences", "effect": 0.5833333333333334, "ci": [0.08333333333333334, 1.0], "p_value": 0.06318681318681318, "survives_correction": false, "degenerate": false, "in_correction_family": true}, {"signal": "coverage_verification_gap.majority_share", "effect": null, "ci": null, "p_value": null, "survives_correction": false, "degenerate": true, "in_correction_family": false}, {"signal": "answer_extraction_audit.answered_yes", "effect": -0.3333333333333333, "ci": [-0.6, -0.13333333333333333], "p_value": 1.0, "survives_correction": false, "degenerate": false, "in_correction_family": true}, {"signal": "answer_extraction_audit.gold_yes", "effect": -0.3333333333333333, "ci": [-0.6, -0.13333333333333333], "p_value": 1.0, "survives_correction": false, "degenerate": false, "in_correction_family": true}, {"signal": "selfcheck_consistency.selfcheck_inconsistency", "effect": 0.5, "ci": [0.0, 1.0], "p_value": 1.0, "survives_correction": false, "degenerate": false, "in_correction_family": true}, {"signal": "selfcheck_consistency.selfcheck_worst_sentence", "effect": 0.5, "ci": [0.0, 1.0], "p_value": 1.0, "survives_correction": false, "degenerate": false, "in_correction_family": true}, {"signal": "answer_extraction_audit.gave_up", "effect": null, "ci": null, "p_value": null, "survives_correction": false, "degenerate": true, "in_correction_family": false}, {"signal": "answer_extraction_audit.has_answer_tag", "effect": null, "ci": null, "p_value": null, "survives_correction": false, "degenerate": true, "in_correction_family": false}, {"signal": "answer_extraction_audit.has_output", "effect": null, "ci": null, "p_value": null, "survives_correction": false, "degenerate": true, "in_correction_family": false}, {"signal": "answer_extraction_audit.output_truncated", "effect": null, "ci": null, "p_value": null, "survives_correction": false, "degenerate": true, "in_correction_family": false}, {"signal": "coverage_verification_gap.coverage_gap", "effect": null, "ci": null, "p_value": null, "survives_correction": false, "degenerate": true, "in_correction_family": false}, {"signal": "coverage_verification_gap.n_graded", "effect": null, "ci": null, "p_value": null, "survives_correction": false, "degenerate": true, "in_correction_family": false}, {"signal": "coverage_verification_gap.n_samples", "effect": null, "ci": null, "p_value": null, "survives_correction": false, "degenerate": true, "in_correction_family": false}], "n_in_correction_family": 7, "n_degenerate": 8, "correction_method": "BH", "survivors": ["coverage_verification_gap.n_unique"]}}, "m3": [{"id": "H1", "failure_mode": "answer_extraction", "statement": "Evaluation failures are predominantly caused by strict string normalization in the evaluation harness rejecting verbose responses that append units or parenthetical explanations to otherwise correct answers.", "expected_direction": null}, {"id": "H2", "failure_mode": "selection_failure", "statement": "Model failures on visual queries with low consensus across repeated samples stem from candidate answer dispersion where majority voting drops the correct solution present in the candidate pool.", "expected_direction": null}, {"id": "H3", "failure_mode": "knowledge_gap", "statement": "Genuine visual reasoning failures on fine-grained chart elements represent encoder coverage deficits where the model consistently fails to extract required numeric data across repeated sampling attempts.", "expected_direction": null}], "m4": [{"id": "H1", "failure_mode": "answer_extraction", "status": "inconclusive", "statement": "Evaluation failures are predominantly caused by strict string normalization in the evaluation harness rejecting verbose responses that append units or parenthetical explanations to otherwise correct answers.", "test_name": "signal_label_assoc", "effect": 0.4603174603174603, "ci": [0.031746031746031744, 0.8571428571428571], "evidence_grade": "observational", "underpowered": false}, {"id": "H2", "failure_mode": "selection_failure", "status": "supported", "statement": "Model failures on visual queries with low consensus across repeated samples stem from candidate answer dispersion where majority voting drops the correct solution present in the candidate pool.", "test_name": "signal_label_assoc", "effect": 0.9166666666666666, "ci": [0.75, 1.0], "evidence_grade": "observational", "underpowered": false}, {"id": "H3", "failure_mode": "knowledge_gap", "status": "inconclusive", "statement": "Genuine visual reasoning failures on fine-grained chart elements represent encoder coverage deficits where the model consistently fails to extract required numeric data across repeated sampling attempts.", "test_name": "stats_results", "effect": null, "ci": null, "evidence_grade": "none", "underpowered": null}], "m5": {"ladder": [{"tier": "L1", "label": "Prompt / instructions", "n_candidates": 6, "best_effect": 0.1875, "best_candidate": "strict_minimal_answer", "status": "not_selected", "within_cap": true, "tier_cap": "L2"}, {"tier": "L2", "label": "Scaffold / tools / multi-call", "n_candidates": 9, "best_effect": 0.1875, "best_candidate": "consensus_stripped_vote", "status": "not_selected", "within_cap": true, "tier_cap": "L2"}, {"tier": "L3", "label": "Internals / read & write", "n_candidates": 0, "best_effect": null, "best_candidate": null, "status": "untouched", "within_cap": false, "tier_cap": "L2"}, {"tier": "L4", "label": "Re-training", "n_candidates": 0, "best_effect": null, "best_candidate": null, "status": "untouched", "within_cap": false, "tier_cap": "L2"}], "candidates": [{"name": "visual_grounding", "tier": "L1", "effect": 0.125, "n_fixed": 2, "n_broken": 0, "verdict": "partial", "selected": false}, {"name": "strict_minimal_answer", "tier": "L1", "effect": 0.1875, "n_fixed": 3, "n_broken": 0, "verdict": "partial", "selected": false}, {"name": "read_marks_then_answer", "tier": "L1", "effect": 0.1875, "n_fixed": 4, "n_broken": 1, "verdict": "partial", "selected": false}, {"name": "strip_units_and_parentheses", "tier": "L1", "effect": 0.1875, "n_fixed": 3, "n_broken": 0, "verdict": "partial", "selected": false}, {"name": "scratchpad_isolated_answer", "tier": "L1", "effect": 0.125, "n_fixed": 3, "n_broken": 1, "verdict": "partial", "selected": false}, {"name": "candidate_recheck_then_extract", "tier": "L1", "effect": 0.125, "n_fixed": 2, "n_broken": 0, "verdict": "partial", "selected": false}, {"name": "sharpen_and_verified_clean_answer", "tier": "L2", "effect": -0.4375, "n_fixed": 0, "n_broken": 7, "verdict": "unsafe", "selected": false}, {"name": "upscale_least_to_most_extraction", "tier": "L2", "effect": -0.5, "n_fixed": 0, "n_broken": 8, "verdict": "regressed", "selected": false}, {"name": "contrast_enhanced_self_refined_tag", "tier": "L2", "effect": -0.6875, "n_fixed": 0, "n_broken": 11, "verdict": "regressed", "selected": false}, {"name": "self_consistency_5", "tier": "L2", "effect": 0.0625, "n_fixed": 1, "n_broken": 0, "verdict": "partial", "selected": false}, {"name": "coded_pipeline", "tier": "L2", "effect": 0.125, "n_fixed": 2, "n_broken": 0, "verdict": "partial", "selected": false}, {"name": "bare_value_extractor", "tier": "L2", "effect": 0.125, "n_fixed": 2, "n_broken": 0, "verdict": "partial", "selected": false}, {"name": "boxed_clean_tag", "tier": "L2", "effect": -0.6875, "n_fixed": 0, "n_broken": 11, "verdict": "regressed", "selected": false}, {"name": "consensus_stripped_vote", "tier": "L2", "effect": 0.1875, "n_fixed": 3, "n_broken": 0, "verdict": "partial", "selected": false}, {"name": "coded_pipeline", "tier": "L2", "effect": 0.125, "n_fixed": 2, "n_broken": 0, "verdict": "partial", "selected": false}], "confirmed": [{"name": "strict_minimal_answer", "tier": "L1", "effect": 0.1875, "n_fixed": 3, "n_broken": 0, "verdict": "partial", "selected": false}]}, "repair": null, "validation": null, "example_case": {"case_id": "chartqa-human-365", "split": "explore", "question": "Which color bar represents the highest value in the graph? Answer with only the short answer.", "gold": ["Pink"], "baseline_output": "Magenta", "baseline_answer": "Magenta", "label": "fail", "signal": "coverage_verification_gap.n_unique", "signal_values": {"sample_id": "chartqa-human-365", "n_samples": 5, "n_graded": 5, "n_correct": 4, "n_unique": 4, "pass_at_k": 1.0, "any_correct": 1, "majority_correct": 1, "majority_share": 0.4, "coverage_gap": 0, "modal_answer": "pink"}, "media_paths": ["media/978a9fba2d8e0f58_chartqa-00365.png"]}, "qa_flags": [{"level": "note", "code": "example_case_from_explore", "detail": "the illustrative case comes from the explore split; its output is the unchanged model's, not a measured repaired result"}]}, "contract": {}, "cases": [{"id": "chartqa-human-445", "status": "pass", "prompt": "In which country the difference between blue and green bar is maximum? Answer with only the short answer.", "expected": ["U.S."], "observed": "U.S.", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-1"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-86", "status": "fail", "prompt": "Which two values are same in the upper graph? Answer with only the short answer.", "expected": ["77"], "observed": "77 and 77 (in 2006)", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-2"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-45", "status": "pass", "prompt": "What's the average of last three values in green graph (round to one decimal)? Answer with only the short answer.", "expected": ["28.6"], "observed": "28.7", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-3"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-1122", "status": "pass", "prompt": "Which category the three bars value is above 25% ? Answer with only the short answer.", "expected": ["Russia"], "observed": "Russia", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-4"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-740", "status": "pass", "prompt": "What state has the 3rd most physicians in 2021? Answer with only the short answer.", "expected": ["Texas"], "observed": "Texas", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-5"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-89", "status": "fail", "prompt": "What's the ratio(A:B) of yellow bar and blue bar for Ages 18-29? Answer with only the short answer.", "expected": ["1.684722222"], "observed": "20:13", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-6"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-406", "status": "pass", "prompt": "Is the starting value of China in the graph greater than 40%? Answer with only the short answer.", "expected": ["Yes"], "observed": "Yes", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-7"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-1195", "status": "fail", "prompt": "What is the difference between the new car market in 2007 and 2008? Answer with only the short answer.", "expected": ["4.9"], "observed": "4.9 billion British pounds", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-8"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-1032", "status": "pass", "prompt": "What countries data shown in green color? Answer with only the short answer.", "expected": ["Hungary"], "observed": "Hungary", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-9"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-325", "status": "pass", "prompt": "What is the sum of lowest value and second lowest value in the bar? Answer with only the short answer.", "expected": ["14153.35"], "observed": "$14,153.35", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-10"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-365", "status": "fail", "prompt": "Which color bar represents the highest value in the graph? Answer with only the short answer.", "expected": ["Pink"], "observed": "Magenta", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-11"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-532", "status": "pass", "prompt": "What is the value of the red bar? Answer with only the short answer.", "expected": ["4.2"], "observed": "4.2", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-12"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-19", "status": "fail", "prompt": "Is the sum of largest two bars is greater then the sum of smallest 3 bars? Answer with only the short answer.", "expected": ["No"], "observed": "No (185% is not greater than 233%)", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-13"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-95", "status": "pass", "prompt": "Which country received the higher Country Programmable aid, Jamaica or Tonga? Answer with only the short answer.", "expected": ["Jamaica"], "observed": "Jamaica", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-14"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-1107", "status": "pass", "prompt": "What is the value of Hulu? Answer with only the short answer.", "expected": ["9.2"], "observed": "9.2%", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-15"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-352", "status": "pass", "prompt": "What is represents in the red line bar ? Answer with only the short answer.", "expected": ["Belize"], "observed": "Belize", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-16"], "trajectory": null, "split": "explore"}, {"id": "chartqa-human-228", "status": "pass", "prompt": "Which country has longest bar? Answer with only the short answer.", "expected": ["Lithuania"], "observed": "Lithuania", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-17"], "trajectory": null, "split": "confirm", "repair": {"candidate": "strict_minimal_answer", "tier": "L1", "status": "unchanged", "output": "Lithuania"}}, {"id": "chartqa-human-875", "status": "pass", "prompt": "The highest percent of Not sure minus the smallest percent of Mostly trust gives what Answer with only the short answer.", "expected": ["53"], "observed": "53%", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-18"], "trajectory": null, "split": "confirm", "repair": {"candidate": "strict_minimal_answer", "tier": "L1", "status": "unchanged", "output": "53%"}}, {"id": "chartqa-human-475", "status": "fail", "prompt": "How many 'Very' bars have a value lower than 40? Answer with only the short answer.", "expected": ["1"], "observed": "3", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-19"], "trajectory": null, "split": "confirm", "repair": {"candidate": "strict_minimal_answer", "tier": "L1", "status": "fixed", "output": "1"}}, {"id": "chartqa-human-428", "status": "fail", "prompt": "How many countries are shown in the graph? Answer with only the short answer.", "expected": ["3"], "observed": "3 countries are shown in the graph.", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-20"], "trajectory": null, "split": "confirm", "repair": {"candidate": "strict_minimal_answer", "tier": "L1", "status": "fixed", "output": "3"}}, {"id": "chartqa-human-799", "status": "pass", "prompt": "What is the value , if we add top 2 bars and bottom 2 bars ? Answer with only the short answer.", "expected": ["93"], "observed": "93", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-21"], "trajectory": null, "split": "confirm", "repair": {"candidate": "strict_minimal_answer", "tier": "L1", "status": "unchanged", "output": "89"}}, {"id": "chartqa-human-709", "status": "pass", "prompt": "What is the value of the highest point? Answer with only the short answer.", "expected": ["19.7"], "observed": "19.7%", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-22"], "trajectory": null, "split": "confirm", "repair": {"candidate": "strict_minimal_answer", "tier": "L1", "status": "unchanged", "output": "19.7%"}}, {"id": "chartqa-human-293", "status": "fail", "prompt": "Is the sum of all the last three places is more then Oceania? Answer with only the short answer.", "expected": ["No"], "observed": "Yes", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-23"], "trajectory": null, "split": "confirm", "repair": {"candidate": "strict_minimal_answer", "tier": "L1", "status": "fixed", "output": "No"}}, {"id": "chartqa-human-372", "status": "pass", "prompt": "How many countries are included in the chart? Answer with only the short answer.", "expected": ["2"], "observed": "2", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-24"], "trajectory": null, "split": "confirm", "repair": {"candidate": "strict_minimal_answer", "tier": "L1", "status": "unchanged", "output": "2"}}, {"id": "chartqa-human-576", "status": "pass", "prompt": "Which country does the green line represent? Answer with only the short answer.", "expected": ["Spain"], "observed": "Spain", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-25"], "trajectory": null, "split": "confirm", "repair": {"candidate": "strict_minimal_answer", "tier": "L1", "status": "unchanged", "output": "Spain"}}, {"id": "chartqa-human-355", "status": "pass", "prompt": "Which country data below 80% for the last five years ? Answer with only the short answer.", "expected": ["Sudan"], "observed": "Sudan", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-26"], "trajectory": null, "split": "confirm", "repair": {"candidate": "strict_minimal_answer", "tier": "L1", "status": "unchanged", "output": "Sudan"}}, {"id": "chartqa-human-379", "status": "pass", "prompt": "For how many years is the value of the Philippines lower than the one of Nepal? Answer with only the short answer.", "expected": ["3"], "observed": "3", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-27"], "trajectory": null, "split": "confirm", "repair": {"candidate": "strict_minimal_answer", "tier": "L1", "status": "unchanged", "output": "3"}}, {"id": "chartqa-human-698", "status": "fail", "prompt": "Which is represented by yellow color? Answer with only the short answer.", "expected": ["Netherlands"], "observed": "Denmark", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-28"], "trajectory": null, "split": "confirm", "repair": {"candidate": "strict_minimal_answer", "tier": "L1", "status": "unchanged", "output": "Denmark"}}, {"id": "chartqa-human-1142", "status": "fail", "prompt": "Work out the ratio of the bigger segment to the smaller one? Answer with only the short answer.", "expected": ["1.577"], "observed": "153:97", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-29"], "trajectory": null, "split": "confirm", "repair": {"candidate": "strict_minimal_answer", "tier": "L1", "status": "unchanged", "output": "153:97"}}, {"id": "chartqa-human-452", "status": "pass", "prompt": "What's the value of the gray bar in Donald Trump category? Answer with only the short answer.", "expected": ["15"], "observed": "15", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-30"], "trajectory": null, "split": "confirm", "repair": {"candidate": "strict_minimal_answer", "tier": "L1", "status": "unchanged", "output": "15"}}, {"id": "chartqa-human-864", "status": "pass", "prompt": "Which year showed the largest difference in the data points between the two lines Answer with only the short answer.", "expected": ["2019"], "observed": "2019", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-31"], "trajectory": null, "split": "confirm", "repair": {"candidate": "strict_minimal_answer", "tier": "L1", "status": "unchanged", "output": "2019"}}, {"id": "chartqa-human-583", "status": "pass", "prompt": "Which year recorded the highest native born employment in Slovenia? Answer with only the short answer.", "expected": ["2008"], "observed": "2008", "choices": [], "tags": [], "task": "exact_or_numeric", "media_ids": ["media-32"], "trajectory": null, "split": "confirm", "repair": {"candidate": "strict_minimal_answer", "tier": "L1", "status": "unchanged", "output": "2008"}}], "media": [{"id": "media-1", "kind": "image", "path": "media/7c0cc9aa72ae00ec_chartqa-00445.png", "source": "/app/work/data/chartqa/images/chartqa-00445.png"}, {"id": "media-2", "kind": "image", "path": "media/89091ba9c24e6b24_chartqa-00086.png", "source": "/app/work/data/chartqa/images/chartqa-00086.png"}, {"id": "media-3", "kind": "image", "path": "media/4c75d7a421a17eae_chartqa-00045.png", "source": "/app/work/data/chartqa/images/chartqa-00045.png"}, {"id": "media-4", "kind": "image", "path": "media/0a7f5db0a64fdb75_chartqa-01122.png", "source": "/app/work/data/chartqa/images/chartqa-01122.png"}, {"id": "media-5", "kind": "image", "path": "media/aa7b06415a7a9670_chartqa-00740.png", "source": "/app/work/data/chartqa/images/chartqa-00740.png"}, {"id": "media-6", "kind": "image", "path": "media/7126ecf5dd418ef9_chartqa-00089.png", "source": "/app/work/data/chartqa/images/chartqa-00089.png"}, {"id": "media-7", "kind": "image", "path": "media/61f97becb8a35950_chartqa-00406.png", "source": "/app/work/data/chartqa/images/chartqa-00406.png"}, {"id": "media-8", "kind": "image", "path": "media/536b625870ff0138_chartqa-01195.png", "source": "/app/work/data/chartqa/images/chartqa-01195.png"}, {"id": "media-9", "kind": "image", "path": "media/1ed7b4c821a357bc_chartqa-01032.png", "source": "/app/work/data/chartqa/images/chartqa-01032.png"}, {"id": "media-10", "kind": "image", "path": "media/00dacfe9e99200e3_chartqa-00325.png", "source": "/app/work/data/chartqa/images/chartqa-00325.png"}, {"id": "media-11", "kind": "image", "path": "media/978a9fba2d8e0f58_chartqa-00365.png", "source": "/app/work/data/chartqa/images/chartqa-00365.png"}, {"id": "media-12", "kind": "image", "path": "media/a35dd0e402626e87_chartqa-00532.png", "source": "/app/work/data/chartqa/images/chartqa-00532.png"}, {"id": "media-13", "kind": "image", "path": "media/9347ae6d3668c0e1_chartqa-00019.png", "source": "/app/work/data/chartqa/images/chartqa-00019.png"}, {"id": "media-14", "kind": "image", "path": "media/dc07513b41a9945d_chartqa-00095.png", "source": "/app/work/data/chartqa/images/chartqa-00095.png"}, {"id": "media-15", "kind": "image", "path": "media/0449e0c949144823_chartqa-01107.png", "source": "/app/work/data/chartqa/images/chartqa-01107.png"}, {"id": "media-16", "kind": "image", "path": "media/05c8b3414d0d87aa_chartqa-00352.png", "source": "/app/work/data/chartqa/images/chartqa-00352.png"}, {"id": "media-17", "kind": "image", "path": "media/d00227b661563a9a_chartqa-00228.png", "source": "/app/work/data/chartqa/images/chartqa-00228.png"}, {"id": "media-18", "kind": "image", "path": "media/9c045de577046c0a_chartqa-00875.png", "source": "/app/work/data/chartqa/images/chartqa-00875.png"}, {"id": "media-19", "kind": "image", "path": "media/a8a1e6f00f522dbb_chartqa-00475.png", "source": "/app/work/data/chartqa/images/chartqa-00475.png"}, {"id": "media-20", "kind": "image", "path": "media/c9575f259488d12d_chartqa-00428.png", "source": "/app/work/data/chartqa/images/chartqa-00428.png"}, {"id": "media-21", "kind": "image", "path": "media/e5bb0b6d1dbcff8d_chartqa-00799.png", "source": "/app/work/data/chartqa/images/chartqa-00799.png"}, {"id": "media-22", "kind": "image", "path": "media/6d00c2a752880019_chartqa-00709.png", "source": "/app/work/data/chartqa/images/chartqa-00709.png"}, {"id": "media-23", "kind": "image", "path": "media/fb01a6e997c39773_chartqa-00293.png", "source": "/app/work/data/chartqa/images/chartqa-00293.png"}, {"id": "media-24", "kind": "image", "path": "media/970880ffb25c36c6_chartqa-00372.png", "source": "/app/work/data/chartqa/images/chartqa-00372.png"}, {"id": "media-25", "kind": "image", "path": "media/0dcdc117d0691d09_chartqa-00576.png", "source": "/app/work/data/chartqa/images/chartqa-00576.png"}, {"id": "media-26", "kind": "image", "path": "media/b45db7b27e1ec636_chartqa-00355.png", "source": "/app/work/data/chartqa/images/chartqa-00355.png"}, {"id": "media-27", "kind": "image", "path": "media/6db7fc96deb09e04_chartqa-00379.png", "source": "/app/work/data/chartqa/images/chartqa-00379.png"}, {"id": "media-28", "kind": "image", "path": "media/372cbb4f4aac7a99_chartqa-00698.png", "source": "/app/work/data/chartqa/images/chartqa-00698.png"}, {"id": "media-29", "kind": "image", "path": "media/af398fbef42b31e9_chartqa-01142.png", "source": "/app/work/data/chartqa/images/chartqa-01142.png"}, {"id": "media-30", "kind": "image", "path": "media/951b9ca9949f882c_chartqa-00452.png", "source": "/app/work/data/chartqa/images/chartqa-00452.png"}, {"id": "media-31", "kind": "image", "path": "media/942f75d54fe3c75b_chartqa-00864.png", "source": "/app/work/data/chartqa/images/chartqa-00864.png"}, {"id": "media-32", "kind": "image", "path": "media/53149749f771c4fc_chartqa-00583.png", "source": "/app/work/data/chartqa/images/chartqa-00583.png"}], "debug": {"event_count": 197, "events": [{"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 1, "ts": "2026-10-12T17:05:47.528371+00:00", "span_id": "m1.model_call.1", "summary": "case_discovery · generate · 32 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 2, "ts": "2026-10-12T17:05:47.532051+00:00", "span_id": "m1.model_call.2", "summary": "case_discovery · generate · 32 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 3, "ts": "2026-10-12T17:05:47.674746+00:00", "span_id": "m1.model_call.3", "summary": "case_discovery · generate · 32 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 4, "ts": "2026-10-12T17:05:48.374492+00:00", "span_id": "m1.model_call.4", "summary": "case_discovery · generate · 32 cases · 1.9s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 5, "ts": "2026-10-12T17:05:49.078731+00:00", "span_id": "m1.model_call.5", "summary": "case_discovery · generate · 32 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 6, "ts": "2026-10-12T17:05:49.180925+00:00", "span_id": "m1.model_call.6", "summary": "case_discovery · generate · 32 cases · 1.6s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 7, "ts": "2026-10-12T17:05:49.305748+00:00", "span_id": "m1.model_call.7", "summary": "case_discovery · generate · 32 cases · 1.8s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 8, "ts": "2026-10-12T17:05:50.458085+00:00", "span_id": "m1.model_call.8", "summary": "case_discovery · generate · 32 cases · 1.3s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 9, "ts": "2026-10-12T17:05:50.540156+00:00", "span_id": "m1.model_call.9", "summary": "case_discovery · generate · 32 cases · 2.1s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 10, "ts": "2026-10-12T17:05:50.795471+00:00", "span_id": "m1.model_call.10", "summary": "case_discovery · generate · 32 cases · 1.6s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 11, "ts": "2026-10-12T17:05:50.863360+00:00", "span_id": "m1.model_call.11", "summary": "case_discovery · generate · 32 cases · 1.6s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 12, "ts": "2026-10-12T17:05:52.254624+00:00", "span_id": "m1.model_call.12", "summary": "case_discovery · generate · 32 cases · 1.7s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 13, "ts": "2026-10-12T17:05:52.460079+00:00", "span_id": "m1.model_call.13", "summary": "case_discovery · generate · 32 cases · 1.6s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 14, "ts": "2026-10-12T17:05:52.471550+00:00", "span_id": "m1.model_call.14", "summary": "case_discovery · generate · 32 cases · 1.7s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 15, "ts": "2026-10-12T17:05:52.606618+00:00", "span_id": "m1.model_call.15", "summary": "case_discovery · generate · 32 cases · 2.1s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 16, "ts": "2026-10-12T17:05:53.767235+00:00", "span_id": "m1.model_call.16", "summary": "case_discovery · generate · 32 cases · 1.5s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 17, "ts": "2026-10-12T17:05:54.258308+00:00", "span_id": "m1.model_call.17", "summary": "case_discovery · generate · 32 cases · 1.6s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 18, "ts": "2026-10-12T17:05:54.432607+00:00", "span_id": "m1.model_call.18", "summary": "case_discovery · generate · 32 cases · 2.0s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 19, "ts": "2026-10-12T17:05:54.632100+00:00", "span_id": "m1.model_call.19", "summary": "case_discovery · generate · 32 cases · 2.2s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 20, "ts": "2026-10-12T17:05:54.984446+00:00", "span_id": "m1.model_call.20", "summary": "case_discovery · generate · 32 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 21, "ts": "2026-10-12T17:05:56.043288+00:00", "span_id": "m1.model_call.21", "summary": "case_discovery · generate · 32 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 22, "ts": "2026-10-12T17:05:56.082529+00:00", "span_id": "m1.model_call.22", "summary": "case_discovery · generate · 32 cases · 1.8s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 23, "ts": "2026-10-12T17:05:56.622077+00:00", "span_id": "m1.model_call.23", "summary": "case_discovery · generate · 32 cases · 2.2s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 24, "ts": "2026-10-12T17:05:56.710012+00:00", "span_id": "m1.model_call.24", "summary": "case_discovery · generate · 32 cases · 1.7s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 25, "ts": "2026-10-12T17:05:57.314388+00:00", "span_id": "m1.model_call.25", "summary": "case_discovery · generate · 32 cases · 1.3s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 26, "ts": "2026-10-12T17:05:57.466042+00:00", "span_id": "m1.model_call.26", "summary": "case_discovery · generate · 32 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 27, "ts": "2026-10-12T17:05:58.492117+00:00", "span_id": "m1.model_call.27", "summary": "case_discovery · generate · 32 cases · 1.8s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 28, "ts": "2026-10-12T17:05:58.931805+00:00", "span_id": "m1.model_call.28", "summary": "case_discovery · generate · 32 cases · 2.3s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 29, "ts": "2026-10-12T17:05:59.151943+00:00", "span_id": "m1.model_call.29", "summary": "case_discovery · generate · 32 cases · 1.8s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 30, "ts": "2026-10-12T17:06:00.199512+00:00", "span_id": "m1.model_call.30", "summary": "case_discovery · generate · 32 cases · 1.7s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 31, "ts": "2026-10-12T17:06:00.382106+00:00", "span_id": "m1.model_call.31", "summary": "case_discovery · generate · 32 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": -1, "event_seq": 32, "ts": "2026-10-12T17:06:00.435807+00:00", "span_id": "m1.model_call.32", "summary": "case_discovery · generate · 32 cases · 3.0s"}, {"event": "run_start", "stage": "RUN", "cycle": null, "event_seq": 33, "ts": "2026-10-12T17:06:00.449307+00:00", "span_id": "run_start", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 34, "ts": "2026-10-12T17:06:00.454457+00:00", "span_id": "run.case_record.34", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 35, "ts": "2026-10-12T17:06:00.457907+00:00", "span_id": "run.case_record.35", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 36, "ts": "2026-10-12T17:06:00.461713+00:00", "span_id": "run.case_record.36", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 37, "ts": "2026-10-12T17:06:00.465939+00:00", "span_id": "run.case_record.37", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 38, "ts": "2026-10-12T17:06:00.470274+00:00", "span_id": "run.case_record.38", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 39, "ts": "2026-10-12T17:06:00.476019+00:00", "span_id": "run.case_record.39", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 40, "ts": "2026-10-12T17:06:00.481224+00:00", "span_id": "run.case_record.40", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 41, "ts": "2026-10-12T17:06:00.486860+00:00", "span_id": "run.case_record.41", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 42, "ts": "2026-10-12T17:06:00.492065+00:00", "span_id": "run.case_record.42", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 43, "ts": "2026-10-12T17:06:00.498870+00:00", "span_id": "run.case_record.43", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 44, "ts": "2026-10-12T17:06:00.503701+00:00", "span_id": "run.case_record.44", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 45, "ts": "2026-10-12T17:06:00.508601+00:00", "span_id": "run.case_record.45", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 46, "ts": "2026-10-12T17:06:00.513932+00:00", "span_id": "run.case_record.46", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 47, "ts": "2026-10-12T17:06:00.519163+00:00", "span_id": "run.case_record.47", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 48, "ts": "2026-10-12T17:06:00.524556+00:00", "span_id": "run.case_record.48", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 49, "ts": "2026-10-12T17:06:00.529834+00:00", "span_id": "run.case_record.49", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 50, "ts": "2026-10-12T17:06:00.535009+00:00", "span_id": "run.case_record.50", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 51, "ts": "2026-10-12T17:06:00.541380+00:00", "span_id": "run.case_record.51", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 52, "ts": "2026-10-12T17:06:00.549109+00:00", "span_id": "run.case_record.52", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 53, "ts": "2026-10-12T17:06:00.554693+00:00", "span_id": "run.case_record.53", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 54, "ts": "2026-10-12T17:06:00.560433+00:00", "span_id": "run.case_record.54", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 55, "ts": "2026-10-12T17:06:00.569233+00:00", "span_id": "run.case_record.55", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 56, "ts": "2026-10-12T17:06:00.575849+00:00", "span_id": "run.case_record.56", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 57, "ts": "2026-10-12T17:06:00.584139+00:00", "span_id": "run.case_record.57", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 58, "ts": "2026-10-12T17:06:00.593740+00:00", "span_id": "run.case_record.58", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 59, "ts": "2026-10-12T17:06:00.601747+00:00", "span_id": "run.case_record.59", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 60, "ts": "2026-10-12T17:06:00.611877+00:00", "span_id": "run.case_record.60", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 61, "ts": "2026-10-12T17:06:00.621469+00:00", "span_id": "run.case_record.61", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 62, "ts": "2026-10-12T17:06:00.630363+00:00", "span_id": "run.case_record.62", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 63, "ts": "2026-10-12T17:06:00.641631+00:00", "span_id": "run.case_record.63", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 64, "ts": "2026-10-12T17:06:00.650082+00:00", "span_id": "run.case_record.64", "summary": "Recorded pipeline event"}, {"event": "case_record", "stage": "RUN", "cycle": null, "event_seq": 65, "ts": "2026-10-12T17:06:00.658444+00:00", "span_id": "run.case_record.65", "summary": "Recorded pipeline event"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 66, "ts": "2026-10-12T17:06:01.721640+00:00", "span_id": "m1.model_call.66", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 67, "ts": "2026-10-12T17:06:01.798932+00:00", "span_id": "m1.model_call.67", "summary": "selfcheck_consistency · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 68, "ts": "2026-10-12T17:06:02.799736+00:00", "span_id": "m1.model_call.68", "summary": "selfcheck_consistency · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 69, "ts": "2026-10-12T17:06:02.957582+00:00", "span_id": "m1.model_call.69", "summary": "coverage_verification_gap · generate · 16 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 70, "ts": "2026-10-12T17:06:03.965946+00:00", "span_id": "m1.model_call.70", "summary": "selfcheck_consistency · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 71, "ts": "2026-10-12T17:06:04.040460+00:00", "span_id": "m1.model_call.71", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 72, "ts": "2026-10-12T17:06:05.380247+00:00", "span_id": "m1.model_call.72", "summary": "selfcheck_consistency · generate · 16 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 73, "ts": "2026-10-12T17:06:05.614827+00:00", "span_id": "m1.model_call.73", "summary": "coverage_verification_gap · generate · 16 cases · 1.6s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 74, "ts": "2026-10-12T17:06:06.401290+00:00", "span_id": "m1.model_call.74", "summary": "selfcheck_consistency · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 75, "ts": "2026-10-12T17:06:06.638115+00:00", "span_id": "m1.model_call.75", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 76, "ts": "2026-10-12T17:06:07.488622+00:00", "span_id": "m1.model_call.76", "summary": "selfcheck_consistency · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 77, "ts": "2026-10-12T17:06:07.758210+00:00", "span_id": "m1.model_call.77", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 78, "ts": "2026-10-12T17:06:08.533033+00:00", "span_id": "m1.model_call.78", "summary": "selfcheck_consistency · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 79, "ts": "2026-10-12T17:06:09.021776+00:00", "span_id": "m1.model_call.79", "summary": "coverage_verification_gap · generate · 16 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 80, "ts": "2026-10-12T17:06:09.393749+00:00", "span_id": "m1.model_call.80", "summary": "selfcheck_consistency · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 81, "ts": "2026-10-12T17:06:09.952187+00:00", "span_id": "m1.model_call.81", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 82, "ts": "2026-10-12T17:06:10.519267+00:00", "span_id": "m1.model_call.82", "summary": "selfcheck_consistency · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 83, "ts": "2026-10-12T17:06:11.005529+00:00", "span_id": "m1.model_call.83", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 84, "ts": "2026-10-12T17:06:11.651488+00:00", "span_id": "m1.model_call.84", "summary": "selfcheck_consistency · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 85, "ts": "2026-10-12T17:06:12.037117+00:00", "span_id": "m1.model_call.85", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 86, "ts": "2026-10-12T17:06:12.777177+00:00", "span_id": "m1.model_call.86", "summary": "selfcheck_consistency · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 87, "ts": "2026-10-12T17:06:13.006920+00:00", "span_id": "m1.model_call.87", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 88, "ts": "2026-10-12T17:06:14.026651+00:00", "span_id": "m1.model_call.88", "summary": "selfcheck_consistency · generate · 16 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 89, "ts": "2026-10-12T17:06:14.042962+00:00", "span_id": "m1.model_call.89", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 90, "ts": "2026-10-12T17:06:14.958653+00:00", "span_id": "m1.model_call.90", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 91, "ts": "2026-10-12T17:06:15.107717+00:00", "span_id": "m1.model_call.91", "summary": "selfcheck_consistency · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 92, "ts": "2026-10-12T17:06:15.980557+00:00", "span_id": "m1.model_call.92", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 93, "ts": "2026-10-12T17:06:16.200668+00:00", "span_id": "m1.model_call.93", "summary": "selfcheck_consistency · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 94, "ts": "2026-10-12T17:06:17.617002+00:00", "span_id": "m1.model_call.94", "summary": "selfcheck_consistency · generate · 16 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 95, "ts": "2026-10-12T17:06:18.080573+00:00", "span_id": "m1.model_call.95", "summary": "coverage_verification_gap · generate · 16 cases · 2.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 96, "ts": "2026-10-12T17:06:19.117831+00:00", "span_id": "m1.model_call.96", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 97, "ts": "2026-10-12T17:06:19.163102+00:00", "span_id": "m1.model_call.97", "summary": "selfcheck_consistency · generate · 16 cases · 1.5s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 98, "ts": "2026-10-12T17:06:20.151814+00:00", "span_id": "m1.model_call.98", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 99, "ts": "2026-10-12T17:06:21.971987+00:00", "span_id": "m1.model_call.99", "summary": "coverage_verification_gap · generate · 16 cases · 1.8s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 100, "ts": "2026-10-12T17:06:22.859605+00:00", "span_id": "m1.model_call.100", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 101, "ts": "2026-10-12T17:06:23.962308+00:00", "span_id": "m1.model_call.101", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 102, "ts": "2026-10-12T17:06:24.934472+00:00", "span_id": "m1.model_call.102", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 103, "ts": "2026-10-12T17:06:26.391852+00:00", "span_id": "m1.model_call.103", "summary": "coverage_verification_gap · generate · 16 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 104, "ts": "2026-10-12T17:06:27.460708+00:00", "span_id": "m1.model_call.104", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 105, "ts": "2026-10-12T17:06:28.617524+00:00", "span_id": "m1.model_call.105", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 106, "ts": "2026-10-12T17:06:30.003967+00:00", "span_id": "m1.model_call.106", "summary": "coverage_verification_gap · generate · 16 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 107, "ts": "2026-10-12T17:06:30.933920+00:00", "span_id": "m1.model_call.107", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 108, "ts": "2026-10-12T17:06:32.003639+00:00", "span_id": "m1.model_call.108", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 109, "ts": "2026-10-12T17:06:32.948963+00:00", "span_id": "m1.model_call.109", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 110, "ts": "2026-10-12T17:06:34.048443+00:00", "span_id": "m1.model_call.110", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 111, "ts": "2026-10-12T17:06:35.130180+00:00", "span_id": "m1.model_call.111", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 112, "ts": "2026-10-12T17:06:36.264428+00:00", "span_id": "m1.model_call.112", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 113, "ts": "2026-10-12T17:06:37.360629+00:00", "span_id": "m1.model_call.113", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 114, "ts": "2026-10-12T17:06:38.199568+00:00", "span_id": "m1.model_call.114", "summary": "coverage_verification_gap · generate · 16 cases · 0.8s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 115, "ts": "2026-10-12T17:06:39.830217+00:00", "span_id": "m1.model_call.115", "summary": "coverage_verification_gap · generate · 16 cases · 1.6s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 116, "ts": "2026-10-12T17:06:40.646914+00:00", "span_id": "m1.model_call.116", "summary": "coverage_verification_gap · generate · 16 cases · 0.8s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 117, "ts": "2026-10-12T17:06:41.862511+00:00", "span_id": "m1.model_call.117", "summary": "coverage_verification_gap · generate · 16 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 118, "ts": "2026-10-12T17:06:42.998581+00:00", "span_id": "m1.model_call.118", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 119, "ts": "2026-10-12T17:06:43.984581+00:00", "span_id": "m1.model_call.119", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 120, "ts": "2026-10-12T17:06:45.186322+00:00", "span_id": "m1.model_call.120", "summary": "coverage_verification_gap · generate · 16 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 121, "ts": "2026-10-12T17:06:46.269546+00:00", "span_id": "m1.model_call.121", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 122, "ts": "2026-10-12T17:06:47.387140+00:00", "span_id": "m1.model_call.122", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 123, "ts": "2026-10-12T17:06:48.400427+00:00", "span_id": "m1.model_call.123", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 124, "ts": "2026-10-12T17:06:49.377619+00:00", "span_id": "m1.model_call.124", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 125, "ts": "2026-10-12T17:06:50.531403+00:00", "span_id": "m1.model_call.125", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 126, "ts": "2026-10-12T17:06:51.928716+00:00", "span_id": "m1.model_call.126", "summary": "coverage_verification_gap · generate · 16 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 127, "ts": "2026-10-12T17:06:53.058776+00:00", "span_id": "m1.model_call.127", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 128, "ts": "2026-10-12T17:06:54.144625+00:00", "span_id": "m1.model_call.128", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 129, "ts": "2026-10-12T17:06:55.559213+00:00", "span_id": "m1.model_call.129", "summary": "coverage_verification_gap · generate · 16 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 130, "ts": "2026-10-12T17:06:56.933614+00:00", "span_id": "m1.model_call.130", "summary": "coverage_verification_gap · generate · 16 cases · 1.3s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 131, "ts": "2026-10-12T17:06:57.959218+00:00", "span_id": "m1.model_call.131", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 132, "ts": "2026-10-12T17:06:58.963529+00:00", "span_id": "m1.model_call.132", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 133, "ts": "2026-10-12T17:06:59.996189+00:00", "span_id": "m1.model_call.133", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 134, "ts": "2026-10-12T17:07:01.230745+00:00", "span_id": "m1.model_call.134", "summary": "coverage_verification_gap · generate · 16 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 135, "ts": "2026-10-12T17:07:02.336988+00:00", "span_id": "m1.model_call.135", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 136, "ts": "2026-10-12T17:07:03.324826+00:00", "span_id": "m1.model_call.136", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 137, "ts": "2026-10-12T17:07:04.322035+00:00", "span_id": "m1.model_call.137", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 138, "ts": "2026-10-12T17:07:05.905176+00:00", "span_id": "m1.model_call.138", "summary": "coverage_verification_gap · generate · 16 cases · 1.5s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 139, "ts": "2026-10-12T17:07:07.091899+00:00", "span_id": "m1.model_call.139", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 140, "ts": "2026-10-12T17:07:08.332099+00:00", "span_id": "m1.model_call.140", "summary": "coverage_verification_gap · generate · 16 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 141, "ts": "2026-10-12T17:07:09.887857+00:00", "span_id": "m1.model_call.141", "summary": "coverage_verification_gap · generate · 16 cases · 1.5s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 142, "ts": "2026-10-12T17:07:10.965214+00:00", "span_id": "m1.model_call.142", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 143, "ts": "2026-10-12T17:07:11.998667+00:00", "span_id": "m1.model_call.143", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 144, "ts": "2026-10-12T17:07:13.114857+00:00", "span_id": "m1.model_call.144", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 145, "ts": "2026-10-12T17:07:14.144542+00:00", "span_id": "m1.model_call.145", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 146, "ts": "2026-10-12T17:07:15.466515+00:00", "span_id": "m1.model_call.146", "summary": "coverage_verification_gap · generate · 16 cases · 1.3s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 147, "ts": "2026-10-12T17:07:16.591232+00:00", "span_id": "m1.model_call.147", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 148, "ts": "2026-10-12T17:07:17.751351+00:00", "span_id": "m1.model_call.148", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 149, "ts": "2026-10-12T17:07:19.158435+00:00", "span_id": "m1.model_call.149", "summary": "coverage_verification_gap · generate · 16 cases · 1.4s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 150, "ts": "2026-10-12T17:07:20.930327+00:00", "span_id": "m1.model_call.150", "summary": "coverage_verification_gap · generate · 16 cases · 1.8s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 151, "ts": "2026-10-12T17:07:21.863470+00:00", "span_id": "m1.model_call.151", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 152, "ts": "2026-10-12T17:07:22.849215+00:00", "span_id": "m1.model_call.152", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 153, "ts": "2026-10-12T17:07:23.878871+00:00", "span_id": "m1.model_call.153", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 154, "ts": "2026-10-12T17:07:24.961399+00:00", "span_id": "m1.model_call.154", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 155, "ts": "2026-10-12T17:07:25.864704+00:00", "span_id": "m1.model_call.155", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 156, "ts": "2026-10-12T17:07:26.751689+00:00", "span_id": "m1.model_call.156", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 157, "ts": "2026-10-12T17:07:27.929224+00:00", "span_id": "m1.model_call.157", "summary": "coverage_verification_gap · generate · 16 cases · 1.1s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 158, "ts": "2026-10-12T17:07:28.949975+00:00", "span_id": "m1.model_call.158", "summary": "coverage_verification_gap · generate · 16 cases · 1.0s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 159, "ts": "2026-10-12T17:07:30.144724+00:00", "span_id": "m1.model_call.159", "summary": "coverage_verification_gap · generate · 16 cases · 1.2s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 160, "ts": "2026-10-12T17:07:31.493928+00:00", "span_id": "m1.model_call.160", "summary": "coverage_verification_gap · generate · 16 cases · 1.3s"}, {"event": "model_call", "stage": "M1", "cycle": 0, "event_seq": 161, "ts": "2026-10-12T17:07:32.436325+00:00", "span_id": "m1.model_call.161", "summary": "coverage_verification_gap · generate · 16 cases · 0.9s"}, {"event": "probe", "stage": "M1", "cycle": 0, "event_seq": 162, "ts": "2026-10-12T17:07:32.482260+00:00", "span_id": "c0.m1", "summary": "Selected 3 analyzer(s) (answer_extraction_audit, selfcheck_consistency, coverage_verification_gap) by capability matching."}, {"event": "explore", "stage": "M2", "cycle": 0, "event_seq": 163, "ts": "2026-10-12T17:08:52.969339+00:00", "span_id": "c0.explore", "summary": "Recorded pipeline event"}, {"event": "model_call", "stage": "M2", "cycle": 0, "event_seq": 164, "ts": "2026-10-12T17:08:52.978771+00:00", "span_id": "m2.model_call.164", "summary": "explore_cli_coder · write_code · 76.6s"}, {"event": "analysis", "stage": "M2", "cycle": 0, "event_seq": 165, "ts": "2026-10-12T17:09:04.471841+00:00", "span_id": "c0.m2", "summary": "The evaluation harness is incorrectly marking correct model answers as failures because the model includes conversational context or explanatory units alongside its answers, while genuine model errors stem from a lack of visual coverage rather than selection mistakes. Specificall"}, {"event": "model_call", "stage": "M2", "cycle": 0, "event_seq": 166, "ts": "2026-10-12T17:09:04.519793+00:00", "span_id": "m2.model_call.166", "summary": "statistics_judge · generate · 11.5s"}, {"event": "diagnosis", "stage": "M3", "cycle": 0, "event_seq": 167, "ts": "2026-10-12T17:09:15.252184+00:00", "span_id": "c0.m3", "summary": "Recorded pipeline event"}, {"event": "model_call", "stage": "M3", "cycle": 0, "event_seq": 168, "ts": "2026-10-12T17:09:15.257522+00:00", "span_id": "m3.model_call.168", "summary": "diagnosis_judge · generate · 5.6s"}, {"event": "model_call", "stage": "M3", "cycle": 0, "event_seq": 169, "ts": "2026-10-12T17:09:15.291478+00:00", "span_id": "m3.model_call.169", "summary": "hypothesis_critic · generate · 5.1s"}, {"event": "surgery", "stage": "M4", "cycle": 0, "event_seq": 170, "ts": "2026-10-12T17:09:28.608592+00:00", "span_id": "c0.m4", "summary": "inconclusive"}, {"event": "model_call", "stage": "M4", "cycle": 0, "event_seq": 171, "ts": "2026-10-12T17:09:28.611802+00:00", "span_id": "m4.model_call.171", "summary": "protocol_consistency_judge · generate · 13.3s"}, {"event": "surgery", "stage": "M4", "cycle": 0, "event_seq": 172, "ts": "2026-10-12T17:09:28.641613+00:00", "span_id": "c0.m4", "summary": "supported"}, {"event": "model_call", "stage": "M4", "cycle": 0, "event_seq": 173, "ts": "2026-10-12T17:09:28.644943+00:00", "span_id": "m4.model_call.173", "summary": "protocol_consistency_judge · generate · 13.3s"}, {"event": "surgery", "stage": "M4", "cycle": 0, "event_seq": 174, "ts": "2026-10-12T17:09:28.648167+00:00", "span_id": "c0.m4", "summary": "inconclusive"}, {"event": "model_call", "stage": "M4", "cycle": 0, "event_seq": 175, "ts": "2026-10-12T17:09:28.650889+00:00", "span_id": "m4.model_call.175", "summary": "protocol_consistency_judge · generate · 13.3s"}, {"event": "loop_end", "stage": "RUN", "cycle": null, "event_seq": 176, "ts": "2026-10-12T17:09:28.655438+00:00", "span_id": "run.loop_end.176", "summary": "criteria_met"}, {"event": "diagnose_report", "stage": "RUN", "cycle": null, "event_seq": 177, "ts": "2026-10-12T17:09:28.660355+00:00", "span_id": "run.diagnose_report.177", "summary": "criteria_met"}, {"event": "experiment", "stage": "M5", "cycle": -1, "event_seq": 178, "ts": "2026-10-12T17:09:44.130774+00:00", "span_id": "m5.experiment.178", "summary": "inconclusive"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 179, "ts": "2026-10-12T17:09:44.133300+00:00", "span_id": "m5.model_call.179", "summary": "experiment_coder · cli:antigravity · 15.4s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 180, "ts": "2026-10-12T17:16:49.312251+00:00", "span_id": "m5.model_call.180", "summary": "target_model · template_candidate · 0.9s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 181, "ts": "2026-10-12T17:16:49.509915+00:00", "span_id": "m5.model_call.181", "summary": "target_model · template_candidate · 1.1s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 182, "ts": "2026-10-12T17:16:49.538106+00:00", "span_id": "m5.model_call.182", "summary": "target_model · template_candidate · 1.1s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 183, "ts": "2026-10-12T17:16:49.764570+00:00", "span_id": "m5.model_call.183", "summary": "target_model · template_candidate · 1.4s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 184, "ts": "2026-10-12T17:16:50.408545+00:00", "span_id": "m5.model_call.184", "summary": "target_model · template_candidate · 1.1s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 185, "ts": "2026-10-12T17:16:50.535527+00:00", "span_id": "m5.model_call.185", "summary": "target_model · template_candidate · 1.0s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 186, "ts": "2026-10-12T17:16:50.537501+00:00", "span_id": "m5.model_call.186", "summary": "target_model · template_candidate · 1.0s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 187, "ts": "2026-10-12T17:16:51.209855+00:00", "span_id": "m5.model_call.187", "summary": "target_model · template_candidate · 1.4s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 188, "ts": "2026-10-12T17:16:51.442355+00:00", "span_id": "m5.model_call.188", "summary": "target_model · template_candidate · 1.0s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 189, "ts": "2026-10-12T17:16:51.725617+00:00", "span_id": "m5.model_call.189", "summary": "target_model · template_candidate · 1.2s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 190, "ts": "2026-10-12T17:16:52.247358+00:00", "span_id": "m5.model_call.190", "summary": "target_model · template_candidate · 1.0s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 191, "ts": "2026-10-12T17:16:52.387486+00:00", "span_id": "m5.model_call.191", "summary": "target_model · template_candidate · 1.8s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 192, "ts": "2026-10-12T17:16:52.542706+00:00", "span_id": "m5.model_call.192", "summary": "target_model · template_candidate · 1.1s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 193, "ts": "2026-10-12T17:16:52.900726+00:00", "span_id": "m5.model_call.193", "summary": "target_model · template_candidate · 1.1s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 194, "ts": "2026-10-12T17:16:53.103762+00:00", "span_id": "m5.model_call.194", "summary": "target_model · template_candidate · 0.8s"}, {"event": "model_call", "stage": "M5", "cycle": 0, "event_seq": 195, "ts": "2026-10-12T17:16:53.531741+00:00", "span_id": "m5.model_call.195", "summary": "target_model · template_candidate · 1.1s"}, {"event": "fix", "stage": "M5", "cycle": -1, "event_seq": 196, "ts": "2026-10-12T17:16:53.636209+00:00", "span_id": "fix", "summary": "Recorded pipeline event"}, {"event": "run_end", "stage": "RUN", "cycle": null, "event_seq": 197, "ts": "2026-10-12T17:16:53.636209+00:00", "span_id": "run.run_end.197", "summary": "Recorded pipeline event"}]}}, "layout": {"spec": {"root": "page", "elements": {"page": {"type": "ReportPage", "props": {}, "children": ["setting", "metrics", "loop", "evidence"]}, "setting": {"type": "SettingHero", "props": {}}, "metrics": {"type": "MetricStrip", "props": {}}, "evidence": {"type": "EvidenceIndex", "props": {}}, "loop": {"type": "LoopFigure", "props": {}}}}, "generated_by": {"mode": "deterministic", "model": null}}} \ No newline at end of file diff --git a/evalrx/reporting/web/src/App.tsx b/evalrx/reporting/web/src/App.tsx index d4b96fce..25f09fdb 100644 --- a/evalrx/reporting/web/src/App.tsx +++ b/evalrx/reporting/web/src/App.tsx @@ -1,6 +1,6 @@ import { useEffect, useState } from "react"; import { JSONUIProvider, Renderer } from "@json-render/react"; -import { Activity, Bot, FolderClock, Moon, Sun } from "lucide-react"; +import { Activity, Bot, Columns2, FolderClock, Moon, Sun } from "lucide-react"; import { applyTheme, initialTheme, type Theme } from "./theme"; import { registry, ReportProviders } from "./reportCatalog"; import type { LayoutEnvelope, ReportData } from "./types"; @@ -11,8 +11,10 @@ import { RunsPanel } from "./runsPanel"; import { CasesView } from "./casesView"; import { DebugView } from "./debugView"; import { EvidenceView } from "./evidenceView"; +import { CompareView } from "./compareView"; import { navigate, parseRoute, runFromHash, withRun, type Route } from "./route"; import { api, RunIdContext } from "./api"; +import { runStatus } from "./runStatus"; type Payload = { data: ReportData; layout: LayoutEnvelope }; @@ -44,7 +46,29 @@ export function App() { // Empty when no server holds the run (an export, or an archive read in the // static build). const [runId, setRunId] = useState(""); + // The server's name for that run (its folder), to tell two runs of one + // model on one dataset apart. + const [runLabel, setRunLabel] = useState(""); useEffect(() => applyTheme(theme), [theme]); + // A run still being written is followed: the server streams an event each + // time its log grows, and the report on screen is swapped for the new one + // in place, on whatever view the reader is on. + const following = Boolean(runId && payload && !payload.data.setting.finished); + useEffect(() => { + if (!following) return; + const source = new EventSource(api.live(runId)); + const refresh = () => + fetch(api.report(runId)) + .then((res) => (res.ok ? res.json() : null)) + .then((run) => run && setPayload({ data: run.data, layout: run.layout })) + .catch(() => undefined); + source.addEventListener("update", refresh); + source.addEventListener("done", () => { + source.close(); + refresh(); + }); + return () => source.close(); + }, [following, runId]); useEffect(() => { const follow = () => setRoute(parseRoute(window.location.hash)); window.addEventListener("hashchange", follow); @@ -74,6 +98,7 @@ export function App() { const run = await res.json(); setPayload({ data: run.data, layout: run.layout }); setRunId(id); + setRunLabel(run.label ?? ""); setActiveRoot(run.root ?? null); if (id !== named) { // Another run than the hash named: its view of that run means nothing here. @@ -94,6 +119,7 @@ export function App() { const load = (run: UploadedRun, root: string | null = null) => { setPayload({ data: run.data, layout: run.layout }); setRunId(run.id || ""); + setRunLabel(run.label || ""); setNeedsRun(false); setError(""); navigate({ view: "overview" }, { run: run.id ?? null }); @@ -123,7 +149,7 @@ export function App() { // opens the same way whether it was found on the overview, a stage // brief or the full record, and the detail views all return past the // topbar below. - renderReport(payload, route, embedded, load) + renderReport(payload, route, embedded, load, { id: runId, label: runLabel }) ); return ( <> @@ -167,8 +193,22 @@ function renderReport( route: Route, embedded: boolean, load: (run: UploadedRun, root?: string | null) => void, + run: { id: string; label: string }, ) { + const runId = run.id; const back = () => navigate({ view: "overview" }); + if (route.view === "compare" && runId) { + return ( + + ); + } if (route.view === "evidence") { return ; } @@ -187,15 +227,22 @@ function renderReport( EvalRX {!embedded && } + {runId && ( + + Compare + + )} {payload.data.setting.diagnosed_by && (
{payload.data.setting.diagnosed_by}
)} -
- report complete -
+ {payload.data.trace_id.slice(0, 8)} @@ -211,3 +258,19 @@ function renderReport( ); } + +/** The run's state in the top bar, re-read each minute so "quiet" can arrive. */ +function RunStatusBadge({ setting }: { setting: ReportData["setting"] }) { + const [now, setNow] = useState(() => Date.now()); + useEffect(() => { + if (setting.finished) return; + const timer = window.setInterval(() => setNow(Date.now()), 60_000); + return () => window.clearInterval(timer); + }, [setting.finished]); + const status = runStatus(setting, now); + return ( +
+ {status.label} +
+ ); +} diff --git a/evalrx/reporting/web/src/api.ts b/evalrx/reporting/web/src/api.ts index ccfae40b..7c1206d0 100644 --- a/evalrx/reporting/web/src/api.ts +++ b/evalrx/reporting/web/src/api.ts @@ -15,10 +15,26 @@ export const api = { upload: "/api/upload", open: (runId: string) => `/api/runs/${part(runId)}/open`, report: (runId: string) => `/api/runs/${part(runId)}/report`, + live: (runId: string) => `/api/runs/${part(runId)}/live`, media: (runId: string, mediaId: string) => `/api/runs/${part(runId)}/media/${part(mediaId)}`, artifact: (runId: string, path: string) => `/api/runs/${part(runId)}/artifact?path=${part(path)}`, }; +/** POST to the report server and return its JSON; a failure throws the server's `detail`. */ +export async function postJson(url: string, body?: BodyInit): Promise { + const res = await fetch(url, { method: "POST", body }); + const text = await res.text(); + let parsed: unknown = null; + try { + parsed = JSON.parse(text); + } catch { + /* an error page, not JSON */ + } + if (!res.ok) + throw new Error((parsed as { detail?: string } | null)?.detail || `HTTP ${res.status}`); + return parsed as T; +} + /** * The server-side id of the run on screen. Empty for a report with no server * behind it (a portable export, or an archive read in the static build): its diff --git a/evalrx/reporting/web/src/brief.tsx b/evalrx/reporting/web/src/brief.tsx index 63671334..f59684d3 100644 --- a/evalrx/reporting/web/src/brief.tsx +++ b/evalrx/reporting/web/src/brief.tsx @@ -19,7 +19,7 @@ * existed. Derivation has the opposite failure mode: it degrades to a shorter * sentence instead of a blank one. Each stage's builder (`briefMx` in * `stages/mx.tsx`) reads `stage_detail` (present on every run) first and treats - * `contract` (absent on older runs, and on runs whose emission failed) as + * `contract` (absent on a run that emitted none or whose emission failed) as * enrichment it can do without. * * This module is the rendering the builders share. diff --git a/evalrx/reporting/web/src/casesView.tsx b/evalrx/reporting/web/src/casesView.tsx index 0a53e277..8f708791 100644 --- a/evalrx/reporting/web/src/casesView.tsx +++ b/evalrx/reporting/web/src/casesView.tsx @@ -159,11 +159,6 @@ export function CasesView({ ))} - {partitions.some((p) => p.inferred) && ( - - split inferred from the record order - - )} )}
@@ -325,18 +320,25 @@ function CaseDetail({ item, data }: { item?: Case; data: ReportData }) { ); } -function TrajectoryPanel({ trajectory }: { trajectory: any }) { - const steps = Array.isArray(trajectory?.steps) ? trajectory.steps : []; - const calls = steps.filter((step: any) => step?.tool_call); +/** One recorded step of an agent trajectory, as far as the panel reads it. */ +type TrajectoryStep = { + tool_call?: { name?: string; args?: unknown } | null; + observation?: unknown; +}; + +function TrajectoryPanel({ trajectory }: { trajectory: unknown }) { + const recorded = (trajectory as { steps?: unknown } | null)?.steps; + const steps: TrajectoryStep[] = Array.isArray(recorded) ? recorded : []; + const calls = steps.filter((step) => step?.tool_call); if (!calls.length) return null; return (
Recorded intermediate agent actions ({calls.length}) - {calls.map((step: any, index: number) => ( + {calls.map((step, index) => (
{plainOperation(step.tool_call?.name)} {formatCompact(step.tool_call?.args)} - {step.observation &&

{formatCompact(step.observation)}

} + {Boolean(step.observation) &&

{formatCompact(step.observation)}

}
))}
diff --git a/evalrx/reporting/web/src/compare.test.ts b/evalrx/reporting/web/src/compare.test.ts new file mode 100644 index 00000000..30c09ba0 --- /dev/null +++ b/evalrx/reporting/web/src/compare.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from "vitest"; +import { compareRuns } from "./compare"; +import type { ReportData } from "./types"; + +function run(overrides: { + dataset?: string; + kind?: "loop" | "explore"; + metrics?: Array<[string, number]>; + stages?: Array<[string, string]>; + cases?: Array<[string, string]>; +}): ReportData { + return { + setting: { dataset: overrides.dataset ?? "chartqa", kind: overrides.kind ?? "loop" }, + metrics: (overrides.metrics ?? []).map(([id, value]) => ({ id, label: id, value })), + stages: (overrides.stages ?? []).map(([id, status]) => ({ id, title: id, status })), + cases: (overrides.cases ?? []).map(([id, status]) => ({ id, status })), + } as unknown as ReportData; +} + +describe("comparing two runs", () => { + it("joins cases by id and lists the ones whose outcome changed", () => { + const a = run({ + cases: [ + ["c1", "fail"], + ["c2", "pass"], + ["c3", "fail"], + ["only-a", "fail"], + ], + }); + const b = run({ + cases: [ + ["c1", "pass"], + ["c2", "fail"], + ["c3", "fail"], + ["only-b", "pass"], + ], + }); + expect(compareRuns(a, b).cases).toEqual({ + shared: 3, + onlyA: 1, + onlyB: 1, + nowPass: ["c1"], + nowFail: ["c2"], + }); + }); + + it("does not read a status other than pass or fail as a change", () => { + const a = run({ cases: [["c1", "unchanged"]] }); + const b = run({ cases: [["c1", "pass"]] }); + expect(compareRuns(a, b).cases).toMatchObject({ shared: 1, nowPass: [], nowFail: [] }); + }); + + it("joins metrics by id and keeps the ones only one run has", () => { + const a = run({ + metrics: [ + ["evaluated", 32], + ["fixed", 3], + ], + }); + const b = run({ + kind: "explore", + metrics: [ + ["evaluated", 30], + ["takeaways", 7], + ], + }); + const result = compareRuns(a, b); + expect(result.metrics.map((m) => [m.id, m.a, m.b])).toEqual([ + ["evaluated", 32, 30], + ["fixed", 3, null], + ["takeaways", null, 7], + ]); + expect(result.sameKind).toBe(false); + expect(result.sameDataset).toBe(true); + }); + + it("lines up each stage's status", () => { + const a = run({ + stages: [ + ["m1", "completed"], + ["m5", "improved"], + ], + }); + const b = run({ dataset: "other", stages: [["m1", "completed"]] }); + const result = compareRuns(a, b); + expect(result.stages.map((s) => [s.id, s.a, s.b])).toEqual([ + ["m1", "completed", "completed"], + ["m5", "improved", null], + ]); + expect(result.sameDataset).toBe(false); + }); +}); diff --git a/evalrx/reporting/web/src/compare.ts b/evalrx/reporting/web/src/compare.ts new file mode 100644 index 00000000..946c3ca5 --- /dev/null +++ b/evalrx/reporting/web/src/compare.ts @@ -0,0 +1,76 @@ +/** + * Two runs side by side: what each measured, how far each got, and which of + * the cases they share changed outcome. Pure, so the joins are testable. + * + * Runs are joined on what they have in common — metrics by id, stages by id, + * cases by id — and the comparison says how much was joined, so a reader can + * tell two runs of one benchmark from two runs that merely sit side by side. + */ +import type { ReportData } from "./types"; + +type Value = string | number | null; + +export type Comparison = { + sameDataset: boolean; + sameKind: boolean; + metrics: Array<{ id: string; label: string; a: Value; b: Value }>; + stages: Array<{ id: string; title: string; a: string | null; b: string | null }>; + cases: { + /** Case ids both runs evaluated. */ + shared: number; + onlyA: number; + onlyB: number; + /** Shared cases that failed in A and passed in B, and the reverse. */ + nowPass: string[]; + nowFail: string[]; + }; +}; + +const OUTCOMES = new Set(["pass", "fail"]); + +export function compareRuns(a: ReportData, b: ReportData): Comparison { + const metricsB = new Map(b.metrics.map((m) => [m.id, m])); + const metrics = [ + ...a.metrics.map((m) => ({ + id: m.id, + label: m.label, + a: m.value, + b: metricsB.get(m.id)?.value ?? null, + })), + ...b.metrics + .filter((m) => !a.metrics.some((other) => other.id === m.id)) + .map((m) => ({ id: m.id, label: m.label, a: null, b: m.value })), + ]; + const stagesB = new Map(b.stages.map((s) => [s.id, s])); + const stages = a.stages.map((s) => ({ + id: s.id, + title: s.title, + a: s.status, + b: stagesB.get(s.id)?.status ?? null, + })); + const statusB = new Map(b.cases.map((c) => [c.id, c.status])); + const idsA = new Set(a.cases.map((c) => c.id)); + const nowPass: string[] = []; + const nowFail: string[] = []; + let shared = 0; + for (const c of a.cases) { + const other = statusB.get(c.id); + if (other === undefined) continue; + shared += 1; + if (!OUTCOMES.has(c.status) || !OUTCOMES.has(other) || c.status === other) continue; + (other === "pass" ? nowPass : nowFail).push(c.id); + } + return { + sameDataset: a.setting.dataset === b.setting.dataset, + sameKind: a.setting.kind === b.setting.kind, + metrics, + stages, + cases: { + shared, + onlyA: a.cases.length - shared, + onlyB: b.cases.filter((c) => !idsA.has(c.id)).length, + nowPass, + nowFail, + }, + }; +} diff --git a/evalrx/reporting/web/src/compareView.tsx b/evalrx/reporting/web/src/compareView.tsx new file mode 100644 index 00000000..fc49bdeb --- /dev/null +++ b/evalrx/reporting/web/src/compareView.tsx @@ -0,0 +1,209 @@ +/** + * This run beside another one the server holds (`#/compare/`). + * + * Only on a served report: an export or the static build has one run and no + * server to open a second. The second run is opened by the id the server + * handed out; ids do not survive a server restart, so an id it no longer + * knows falls back to picking the run again. + */ +import { useEffect, useState } from "react"; +import { compareRuns } from "./compare"; +import { DetailShell } from "./detail"; +import { fetchRuns, openRun, type RunListItem } from "./runsPanel"; +import { routeHash, withRun, type Navigate } from "./route"; +import type { ReportData } from "./types"; +import type { UploadedRun } from "./upload"; + +function describe(data: ReportData): string { + return data.setting.kind === "explore" + ? `Exploratory analysis of ${data.setting.dataset}` + : `${data.setting.model} on ${data.setting.dataset}`; +} + +export function CompareView({ + data, + run, + otherId, + back, + navigate, + open, +}: { + data: ReportData; + run: { id: string; label: string }; + otherId?: string; + back: () => void; + navigate: Navigate; + open: (run: UploadedRun) => void; +}) { + const [other, setOther] = useState(null); + const [error, setError] = useState(""); + useEffect(() => { + setOther(null); + setError(""); + if (!otherId) return; + openRun(otherId) + .then(setOther) + .catch((err) => setError(err instanceof Error ? err.message : String(err))); + }, [otherId]); + return ( + + {!otherId || error ? ( + navigate({ view: "compare", with: id })} + /> + ) : !other ? ( +

Opening the other run…

+ ) : ( + + )} +
+ ); +} + +function RunPicker({ + runId, + error, + pick, +}: { + runId: string; + error: string; + pick: (id: string) => void; +}) { + const [items, setItems] = useState(null); + const [listError, setListError] = useState(""); + useEffect(() => { + fetchRuns() + .then((res) => setItems(res.items.filter((item) => item.id !== runId))) + .catch((err) => setListError(err instanceof Error ? err.message : String(err))); + }, [runId]); + return ( +
+ {error && ( +

That run could not be opened ({error}); pick it again.

+ )} +

Compare with

+ {listError &&

{listError}

} + {items && !items.length && ( +

No other run was found beside this one.

+ )} +
    + {items?.map((item) => ( +
  • + +
  • + ))} +
+
+ ); +} + +function ComparisonTable({ + a, + run, + b, + open, +}: { + a: ReportData; + run: { id: string; label: string }; + b: UploadedRun; + open: (run: UploadedRun) => void; +}) { + const result = compareRuns(a, b.data); + const caseLink = (id: string) => withRun(routeHash({ view: "cases", caseId: id }), run.id); + const shown = (value: string | number | null) => (value === null ? "—" : String(value)); + return ( + <> +
+
+ This run + {describe(a)} + {run.label && {run.label}} +
+
+ Compared with + {describe(b.data)} + {b.label && {b.label}} + +
+
+ {(!result.sameDataset || !result.sameKind) && ( +

+ {!result.sameKind + ? "One is an exploratory analysis and the other a diagnosis run, so only what both recorded lines up." + : "These runs used different datasets, so their numbers are not measured on the same cases."} +

+ )} +
+ + + + + + + + + {result.metrics.map((row) => ( + + + + + + ))} + {result.stages.map((row) => ( + + + + + + ))} + +
+ This runCompared with
{row.label}{shown(row.a)}{shown(row.b)}
+ {row.id.toUpperCase()} · {row.title} + {shown(row.a)}{shown(row.b)}
+
+
+

Cases both runs evaluated: {result.cases.shared}

+

+ {result.cases.onlyA} only in this run, {result.cases.onlyB} only in the other. +

+ + +
+ + ); +} + +function CaseList({ + title, + ids, + link, +}: { + title: string; + ids: string[]; + link: (id: string) => string; +}) { + return ( +
+

+ {title} ({ids.length}) +

+ {ids.map((id) => ( + + {id} + + ))} +
+ ); +} diff --git a/evalrx/reporting/web/src/contract/contract.d.ts b/evalrx/reporting/web/src/contract/contract.d.ts index 3c2146cd..f50d82c2 100644 --- a/evalrx/reporting/web/src/contract/contract.d.ts +++ b/evalrx/reporting/web/src/contract/contract.d.ts @@ -126,6 +126,21 @@ export interface CorrectedRejections { */ export type EvidenceGrade = "intervention" | "observational" | "none"; +/** + * What the explore coding agent left: the analysis it wrote and ran. + * + * ``transcript`` is its CLI trajectory, cut to the report's budget; the run + * directory keeps the whole file. + */ +export interface ExploreAgentView { + code: string | null; + stdout: string | null; + stderr: string | null; + transcript: string | null; + transcript_truncated: boolean; + audit: unknown; +} + /** * Descriptive EDA notes from the optional explore side-path. * @@ -212,7 +227,7 @@ export interface FixAttemptWire { /** * The reader-facing identifier, e.g. `R3`. Assigned by the producer over the whole run and STABLE across `selection` and `attempted`, so a reader who sees R3 in the sweep can find R3's card and know it is the same repair. * - * This exists because `name` cannot do the job. Consumers that numbered rows by list position gave the same repair two different numbers in the two lists, which is worse than no number at all. Empty means the producer assigned none; a consumer may then number by position, but only within one list and never as a cross-list identity. + * This exists because `name` cannot do the job. Consumers that numbered rows by list position gave the same repair two different numbers in the two lists, which is worse than no number at all. */ ref?: string; /** @@ -415,13 +430,13 @@ export interface M2StageDetail { caveats: (unknown)[]; candidate_signals: (CandidateSignalView)[]; recommended_tests: (unknown)[]; + agent: ExploreAgentView | null; } export interface M3StageDetail { mode: string; hypotheses: (HypothesisView)[]; - unparsed_proposals: (UnparsedProposal)[]; - agent_response: string; + error?: string | null; candidate_signals: (CandidateSignalView)[]; recommended_tests: (unknown)[]; evidence_figures: (FigureView)[]; @@ -899,19 +914,6 @@ export interface TestEvidence { details?: { [key: string]: unknown }; } -/** - * A proposal recovered from the judge's raw reply after the parser - * rejected it. Shown for audit only; it never reached M4. - */ -export interface UnparsedProposal { - statement: string; - plain_statement: string; - failure_mode: string; - test_design: string; - expected_association: string; - accepted_by_pipeline: boolean; -} - /** * M4's raw log record. Verdict cards fall back to it when a result * lacks a field. diff --git a/evalrx/reporting/web/src/debugView.tsx b/evalrx/reporting/web/src/debugView.tsx index 6bfad594..8b5f526f 100644 --- a/evalrx/reporting/web/src/debugView.tsx +++ b/evalrx/reporting/web/src/debugView.tsx @@ -1,7 +1,6 @@ /** The raw agent event stream, for auditing a run step by step. */ import { useRef, useState } from "react"; import { useVirtualizer } from "@tanstack/react-virtual"; -import { stageCode } from "./reportAccess"; import type { DebugEvent, ReportData } from "./types"; import { DetailShell } from "./detail"; @@ -66,7 +65,7 @@ function EventRow({ event }: { event: DebugEvent }) { {event.event}
- {stageCode(event.stage) || "RUN"} + {event.stage || "RUN"} {event.cycle !== undefined && event.cycle !== null ? ` · cycle ${event.cycle}` : ""}

{event.summary}

diff --git a/evalrx/reporting/web/src/evidenceView.tsx b/evalrx/reporting/web/src/evidenceView.tsx index a817051d..19cd4b87 100644 --- a/evalrx/reporting/web/src/evidenceView.tsx +++ b/evalrx/reporting/web/src/evidenceView.tsx @@ -1,6 +1,5 @@ /** A stage's evidence: the stage list beside the selected stage's brief or full record. */ -import { stageCode } from "./reportAccess"; import { ChevronRight } from "lucide-react"; import type { ReportData } from "./types"; import type { Navigate, Route } from "./route"; @@ -58,7 +57,7 @@ export function EvidenceView({ key={item.id} onClick={() => show(item.id)} > - {stageCode(item.code)} + {item.code}
{item.title} {item.status.replaceAll("-", " ")} @@ -71,7 +70,7 @@ export function EvidenceView({
- {stageCode(stage?.code)} · {stage?.status?.replaceAll("-", " ")} + {stage?.code} · {stage?.status?.replaceAll("-", " ")}

{stage?.title}

{stage?.purpose}

diff --git a/evalrx/reporting/web/src/loopFigure.tsx b/evalrx/reporting/web/src/loopFigure.tsx index 59fd2a29..ff6a261f 100644 --- a/evalrx/reporting/web/src/loopFigure.tsx +++ b/evalrx/reporting/web/src/loopFigure.tsx @@ -23,6 +23,7 @@ const STATUS_WORD: Record = { skipped: "skipped", improved: "improved", "no-improvement": "no improvement", + failed: "failed", }; /** One hover tooltip: what entered the stage and what left it. */ diff --git a/evalrx/reporting/web/src/reportAccess.test.ts b/evalrx/reporting/web/src/reportAccess.test.ts index 803eab9d..30b1b9c0 100644 --- a/evalrx/reporting/web/src/reportAccess.test.ts +++ b/evalrx/reporting/web/src/reportAccess.test.ts @@ -14,7 +14,6 @@ import { plural, pointsGap, restAfterFirstSentence, - stageCode, stageDetail, stripMarkdown, } from "./reportAccess"; @@ -149,8 +148,6 @@ describe("numbers", () => { expect(chartPercent(0.256)).toBe("25.6%"); expect(chartPercent(null)).toBe("0.0%"); expect(chartPercent("x")).toBe("—"); - expect(stageCode("m4")).toBe("m4"); - expect(stageCode(undefined)).toBe(""); }); it("colours outcome slices by meaning, not position", () => { diff --git a/evalrx/reporting/web/src/reportAccess.ts b/evalrx/reporting/web/src/reportAccess.ts index 3c23a366..65fa28e9 100644 --- a/evalrx/reporting/web/src/reportAccess.ts +++ b/evalrx/reporting/web/src/reportAccess.ts @@ -4,9 +4,9 @@ * Every helper here takes the whole `ReportData` and returns something safe for * an empty run: a `ReportData` is the union of what five stages MIGHT emit, and * any given run fills a different subset of it. An `alm` run has no image - * figures, a run that stopped at M3 has no verdicts, a run that predates - * contract emission has no `contract` at all — and every one of those must - * render as an honest blank rather than throwing. + * figures, a run that stopped at M3 has no verdicts, a run with no contract + * emitter has no `contract` at all — and every one of those must render as an + * honest blank rather than throwing. */ import type { ReportData, StageDetail } from "./types"; @@ -14,9 +14,9 @@ import type { ReportData, StageDetail } from "./types"; * The newest contract payload for a stage, across cycles. * * Spans are "c.", so the last key in sort order is the last cycle - * that ran. Returns undefined for a run that predates contract emission — the - * caller must render without it rather than showing an error, since those runs - * are still perfectly readable through stage_detail. + * that ran. Returns undefined for a run that emitted no contract — the caller + * must render without it rather than showing an error, since the run is still + * readable through stage_detail. */ export function findContract(report: ReportData, stage: string): T | undefined { const payloads = report.contract; @@ -29,8 +29,8 @@ export function findContract(report: ReportData, stage: string): T | undefine } /** - * A stage's `stage_detail` block, or `{}` for a stage this run never reached. - * Partial because an older payload can lack any of its keys. + * A stage's `stage_detail` block, or `{}` for a stage this run never reached + * (hence Partial). */ export function stageDetail( report: ReportData, @@ -51,7 +51,7 @@ export function metric(report: ReportData, id: string): number | undefined { * * An e-value IS odds against the null: e=45 means the evidence runs about 45 to * 1 against this being luck. "Reject at 0.05" is the same statement in a - * dialect nobody outside the field speaks. RunLoggerV2's console narration is + * dialect nobody outside the field speaks. RunLogger's console narration is * a simplified one-line summary with no equivalent phrasing helper, so this * formatter is this report's own source of truth for that phrasing. */ @@ -245,16 +245,3 @@ export function chartPercent(value: unknown): string { const n = Number(value); return Number.isFinite(n) ? `${(n * 100).toFixed(1)}%` : "—"; } - -/** - * Screen numbering for a stage code. - * - * Since contract schema version 5 the stage ids follow the presentation - * order — m4 (held-out validation) runs, and is shown, before m5 (repair) — - * so display codes equal stage ids and this is an identity. It stays as the - * single seam for any future divergence; note that reports written before the - * renumbering (schema ≤ 4) carry the old ids and will display under them. - */ -export function stageCode(code: unknown): string { - return String(code ?? ""); -} diff --git a/evalrx/reporting/web/src/reportCatalog.tsx b/evalrx/reporting/web/src/reportCatalog.tsx index 9424fd92..33a2f8c6 100644 --- a/evalrx/reporting/web/src/reportCatalog.tsx +++ b/evalrx/reporting/web/src/reportCatalog.tsx @@ -22,7 +22,7 @@ import type { Chart, ReportData, Stage } from "./types"; import { ZoomableImage } from "./lightbox"; import { CaseStudySheet as CaseStudySection } from "./caseStudy"; import { LoopFigureView } from "./loopFigure"; -import { chartValue, outcomeColors, stageCode } from "./reportAccess"; +import { chartValue, outcomeColors } from "./reportAccess"; const ids = z.array(z.string()).optional(); export const reportCatalog = defineCatalog(schema, { @@ -36,7 +36,6 @@ export const reportCatalog = defineCatalog(schema, { description: "At most three evidence findings", }, ChartGrid: { props: z.object({ chartIds: ids }), description: "At most two evidence charts" }, - OutcomeCard: { props: z.object({}), description: "What was learned and whether repair worked" }, CasePreview: { props: z.object({ caseIds: ids }), description: "Representative model I/O" }, CaseStudySheet: { props: z.object({}), @@ -82,7 +81,7 @@ function StageNode({ data }: NodeProps>) { return (
-
{stageCode(stage.code)}
+
{stage.code}
{stage.title} {stage.status.replaceAll("-", " ")} @@ -187,7 +186,10 @@ export const { registry } = defineRegistry(reportCatalog, { return (
- {data.setting.model} model's diagnosis and fixing recipe report + {" "} + {data.setting.kind === "explore" + ? "Exploratory analysis report" + : `${data.setting.model} model's diagnosis and fixing recipe report`}

{data.setting.question}

{hero && ( @@ -204,7 +206,8 @@ export const { registry } = defineRegistry(reportCatalog, { in the agent that drove them — named when the run recorded it, never guessed. */}

- Evaluated on dataset {data.setting.dataset}. + {data.setting.kind === "explore" ? "Explored " : "Evaluated on dataset "} + {data.setting.dataset}. {data.setting.diagnosed_by && ( <> {" "} @@ -315,10 +318,6 @@ export const { registry } = defineRegistry(reportCatalog, {

); }, - // Dropped from the page (2026-09-10): it restated the loop figure's health - // card. Layouts published before then still name it, so it renders nothing - // rather than failing as an unknown type. - OutcomeCard: () => null, CasePreview: ({ props }) => { const data = useReport(); const navigate = useContext(NavContext); diff --git a/evalrx/reporting/web/src/route.test.ts b/evalrx/reporting/web/src/route.test.ts index 4baa526a..48685f43 100644 --- a/evalrx/reporting/web/src/route.test.ts +++ b/evalrx/reporting/web/src/route.test.ts @@ -12,6 +12,8 @@ describe("routes", () => { [{ view: "cases", split: "heldout" }, "#/cases?split=heldout"], [{ view: "cases", caseId: "a/b c", split: "" }, "#/cases/a%2Fb%20c?split="], [{ view: "debug" }, "#/debug"], + [{ view: "compare" }, "#/compare"], + [{ view: "compare", with: "run 2" }, "#/compare/run%202"], ]; it.each(cases)("round-trips %j", (route, hash) => { diff --git a/evalrx/reporting/web/src/route.ts b/evalrx/reporting/web/src/route.ts index 56078f12..a90b4635 100644 --- a/evalrx/reporting/web/src/route.ts +++ b/evalrx/reporting/web/src/route.ts @@ -10,6 +10,7 @@ * #/evidence/m3 a stage's brief; #/evidence/m3/full its full record * #/cases/?split=E the case studio, on one case and/or one partition * #/debug the raw event log + * #/compare/ this run beside another one the server holds * * On a served report the hash also names the run (`?run=`), so a reload * or a link reopens the run that was on screen, not the server's start-up run. @@ -18,7 +19,8 @@ export type Route = | { view: "overview" } | { view: "evidence"; stage?: string; full?: boolean } | { view: "cases"; caseId?: string; split?: string } - | { view: "debug" }; + | { view: "debug" } + | { view: "compare"; with?: string }; export type Navigate = (route: Route, options?: { replace?: boolean; run?: string | null }) => void; @@ -37,6 +39,7 @@ export function parseRoute(hash: string): Route { return { view, ...(rest[0] ? { caseId: rest[0] } : {}), ...(split !== null ? { split } : {}) }; } if (view === "debug") return { view }; + if (view === "compare") return { view, ...(rest[0] ? { with: rest[0] } : {}) }; return { view: "overview" }; } @@ -52,6 +55,8 @@ export function routeHash(route: Route): string { } case "debug": return "#/debug"; + case "compare": + return `#/compare${route.with ? `/${part(route.with)}` : ""}`; default: return "#/"; } diff --git a/evalrx/reporting/web/src/runStatus.test.ts b/evalrx/reporting/web/src/runStatus.test.ts new file mode 100644 index 00000000..2a0c0dbc --- /dev/null +++ b/evalrx/reporting/web/src/runStatus.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; +import { QUIET_AFTER_MS, runStatus } from "./runStatus"; +import type { ReportData } from "./types"; + +const at = (fields: Partial) => fields as ReportData["setting"]; +const now = Date.parse("2026-11-13T12:00:00Z"); + +describe("the run status", () => { + it("is complete once the run logged its end", () => { + expect(runStatus(at({ finished: true }), now).state).toBe("complete"); + }); + + it("is live while an unfinished run keeps logging", () => { + const recent = new Date(now - QUIET_AFTER_MS + 1000).toISOString(); + expect(runStatus(at({ finished: false, last_event_at: recent }), now)).toEqual({ + state: "live", + label: "run in progress", + }); + expect(runStatus(at({ finished: false, last_event_at: null }), now).state).toBe("live"); + }); + + it("describes a quiet unfinished run without calling it crashed", () => { + const old = new Date(now - 3 * 3600_000).toISOString(); + expect(runStatus(at({ finished: false, last_event_at: old }), now)).toEqual({ + state: "quiet", + label: "unfinished · no new events for 3h", + }); + }); +}); diff --git a/evalrx/reporting/web/src/runStatus.ts b/evalrx/reporting/web/src/runStatus.ts new file mode 100644 index 00000000..9d244142 --- /dev/null +++ b/evalrx/reporting/web/src/runStatus.ts @@ -0,0 +1,29 @@ +/** + * What the top bar says about a run: complete, still being written, or + * unfinished and quiet. Read off the report alone, so an export says the same. + * + * A run that stops logging is not known to have crashed (a long M5 step can + * be quiet for minutes), so a quiet run is described, not judged. + */ +import type { ReportData } from "./types"; + +/** How long a run may go without logging before it reads as quiet. */ +export const QUIET_AFTER_MS = 5 * 60_000; + +export type RunStatus = { state: "complete" | "live" | "quiet"; label: string }; + +export function runStatus(setting: ReportData["setting"], now: number): RunStatus { + if (setting.finished) return { state: "complete", label: "report complete" }; + const last = setting.last_event_at ? Date.parse(setting.last_event_at) : NaN; + if (Number.isNaN(last) || now - last < QUIET_AFTER_MS) { + return { state: "live", label: "run in progress" }; + } + return { state: "quiet", label: `unfinished · no new events for ${age(now - last)}` }; +} + +function age(ms: number): string { + const minutes = Math.round(ms / 60_000); + if (minutes < 60) return `${minutes}m`; + const hours = Math.round(minutes / 60); + return hours < 48 ? `${hours}h` : `${Math.round(hours / 24)}d`; +} diff --git a/evalrx/reporting/web/src/runsPanel.tsx b/evalrx/reporting/web/src/runsPanel.tsx index 52f8e899..be977540 100644 --- a/evalrx/reporting/web/src/runsPanel.tsx +++ b/evalrx/reporting/web/src/runsPanel.tsx @@ -10,7 +10,7 @@ import { useCallback, useEffect, useState } from "react"; import { FolderClock, RefreshCw, X } from "lucide-react"; import type { UploadedRun } from "./upload"; -import { api } from "./api"; +import { api, postJson } from "./api"; export type RunListItem = { id: string; @@ -25,24 +25,19 @@ export type RunListItem = { modified_at: string | null; }; -async function fetchRuns(): Promise<{ root: string; items: RunListItem[]; truncated: boolean }> { +export async function fetchRuns(): Promise<{ + root: string; + items: RunListItem[]; + truncated: boolean; +}> { const res = await fetch(api.runs); if (!res.ok) throw new Error((await res.json().catch(() => null))?.detail || `HTTP ${res.status}`); return res.json(); } -async function openRun(id: string): Promise { - const res = await fetch(api.open(id), { method: "POST" }); - const text = await res.text(); - let parsed: any = null; - try { - parsed = JSON.parse(text); - } catch { - /* an error page, not JSON */ - } - if (!res.ok) throw new Error(parsed?.detail || `HTTP ${res.status}`); - return parsed as UploadedRun; +export function openRun(id: string): Promise { + return postJson(api.open(id)); } function relativeTime(iso: string | null): string { diff --git a/evalrx/reporting/web/src/stages/evidence.tsx b/evalrx/reporting/web/src/stages/evidence.tsx index eeb0abd6..2f0b81c0 100644 --- a/evalrx/reporting/web/src/stages/evidence.tsx +++ b/evalrx/reporting/web/src/stages/evidence.tsx @@ -1,5 +1,6 @@ /** M2's evidence — its figures and its statistical screens — which M3 shows again as its starting point. */ import ReactECharts from "echarts-for-react"; +import type { ECharts, ElementEvent, TooltipComponentFormatterCallbackParams } from "echarts"; import { tc } from "../theme"; import { ZoomableImage } from "../lightbox"; import { useFigureSource } from "../api"; @@ -128,13 +129,14 @@ function escapeHtml(text: string): string { * hovered dataIndex reads straight out of it. */ function namedTooltip(names: string[], format: (value: unknown) => string) { - return (params: any) => { + return (params: TooltipComponentFormatterCallbackParams) => { const series = Array.isArray(params) ? params : [params]; - const first = series[0] || {}; - const head = escapeHtml(String(names[first.dataIndex] ?? first.name ?? "")); + const first: Partial<(typeof series)[number]> & { axisValue?: unknown } = series[0] || {}; + const named = first.dataIndex === undefined ? undefined : names[first.dataIndex]; + const head = escapeHtml(String(named ?? first.name ?? "")); const lines = series .map( - (row: any) => + (row) => `
` + `${row.marker} ${escapeHtml(String(row.seriesName || ""))}` + `${escapeHtml(format(row.value))}
`, @@ -149,7 +151,7 @@ function namedTooltip(names: string[], format: (value: unknown) => string) { /** Hovering a label opens its row's tooltip — the axis alone no longer names it. */ function labelHoverTooltip(rowCount: number) { - return (chart: any) => { + return (chart: ECharts) => { const zr = chart.getZr?.(); if (!zr) return; let shown = -1; @@ -174,7 +176,7 @@ function labelHoverTooltip(rowCount: number) { } return NaN; }; - zr.on("mousemove", (event: any) => { + zr.on("mousemove", (event: ElementEvent) => { if (event.offsetX >= AXIS_GUTTER) return hide(); const index = rowAt(event.offsetX, event.offsetY); if (!Number.isFinite(index) || index < 0 || index >= rowCount) return hide(); diff --git a/evalrx/reporting/web/src/stages/m2.tsx b/evalrx/reporting/web/src/stages/m2.tsx index 477eac82..6009f43a 100644 --- a/evalrx/reporting/web/src/stages/m2.tsx +++ b/evalrx/reporting/web/src/stages/m2.tsx @@ -108,6 +108,41 @@ export function M2Detail({ data }: { data: Partial }) { )} + {data.agent && } + + ); +} + +/** The analysis the explore agent wrote and ran: how to reproduce M2. */ +function ExploreAgent({ agent }: { agent: NonNullable }) { + const parts: Array<[string, string | null]> = [ + ["Analysis code it wrote and ran", agent.code], + ["What the analysis printed", agent.stdout], + ["Errors the analysis printed", agent.stderr], + [ + agent.transcript_truncated + ? "Agent trajectory (first part; the run directory keeps the whole file)" + : "Agent trajectory", + agent.transcript, + ], + ]; + return ( + <> + {parts.map( + ([title, text]) => + text && ( +
+ {title} +
{text}
+
+ ), + )} + {agent.audit != null && ( +
+ Agent audit +
{JSON.stringify(agent.audit, null, 2)}
+
+ )} ); } diff --git a/evalrx/reporting/web/src/stages/m3.tsx b/evalrx/reporting/web/src/stages/m3.tsx index 4afa1905..9857899f 100644 --- a/evalrx/reporting/web/src/stages/m3.tsx +++ b/evalrx/reporting/web/src/stages/m3.tsx @@ -25,9 +25,7 @@ function isRoutable(design?: string): boolean { } export function M3Detail({ data, report }: { data: Partial; report: ReportData }) { - const accepted = data.hypotheses || []; - const recovered = data.unparsed_proposals || []; - const hypotheses: Proposal[] = accepted.length ? accepted : recovered; + const hypotheses: Proposal[] = data.hypotheses || []; const m3 = findContract(report, "m3"); const untestable = m3 ? (m3.hypotheses || []).filter((h) => !h.test_design?.trim()) : []; const unroutable = m3 @@ -35,6 +33,25 @@ export function M3Detail({ data, report }: { data: Partial; repor : []; return ( <> + {data.error && ( +
+ +
+ + {hypotheses.length + ? "The last attempt at this step failed, and the run stopped there." + : "This step failed, and the run stopped here."} + +

+ The judge gave no usable answer after its retries + {hypotheses.length + ? "; the explanations below come from an earlier cycle." + : ", so no explanation was put forward."}{" "} + The run log has every exchange. Reason: {data.error} +

+
+
+ )} M3 turns M2 leads into explanations that could be proven wrong. These cards are proposals; validation status belongs exclusively to M4. @@ -77,23 +94,13 @@ export function M3Detail({ data, report }: { data: Partial; repor )} item.test_design).length, }, ]} /> - {!accepted.length && recovered.length > 0 && ( -
- -
- The AI Doctor proposed hypotheses, but the pipeline parser rejected their format. -

They are shown below for audit only and did not unlock M4 or M5.

-
-
- )} {!!data.evidence_figures?.length && (
@@ -124,7 +131,7 @@ export function M3Detail({ data, report }: { data: Partial; repor
H{index + 1} - {accepted.length ? "IDEA TO TEST" : "NOT YET USABLE"} + IDEA TO TEST

{hypothesis.plain_statement || hypothesis.statement || hypothesis.hypothesis}

{hypothesis.statement && @@ -178,21 +185,24 @@ export function M3Detail({ data, report }: { data: Partial; repor ))} )} - {data.agent_response && ( -
- AI Doctor raw response -
{data.agent_response}
-
- )} ); } // ── M3 brief (L2) ────────────────────────────────────────────────────────── export function briefM3(report: ReportData, detail: Partial): Brief { - const accepted = detail.hypotheses || []; - const recovered = detail.unparsed_proposals || []; - const list: Proposal[] = accepted.length ? accepted : recovered; + if (detail.error && !(detail.hypotheses || []).length) { + return { + verdict: "This step failed, and the run stopped here.", + lead: + "The judge gave no usable answer after its retries, so no explanation was put " + + "forward. The patterns from the previous step still stand. Reason: " + + detail.error, + kpis: [], + points: [], + }; + } + const list: Proposal[] = detail.hypotheses || []; const m3 = findContract(report, "m3"); const untestable = (m3?.hypotheses || []).filter((h) => !h.test_design?.trim()); const withTest = list.filter((h) => String(h.test_design || "").trim()).length; @@ -232,11 +242,10 @@ export function briefM3(report: ReportData, detail: Partial): Bri }); const caveatParts: string[] = []; - if (!accepted.length && recovered.length) { + if (detail.error) { caveatParts.push( - "The agent did propose explanations, but the pipeline could not read " + - "the format it wrote them in, so they never reached the held-out check. They are " + - "shown for audit only.", + "The last attempt at this step failed and the run stopped there; these " + + `explanations come from an earlier cycle. Reason: ${detail.error}`, ); } if (untestable.length) { @@ -261,15 +270,6 @@ export function briefM3(report: ReportData, detail: Partial): Bri value: withTest, note: withTest < list.length ? `${list.length - withTest} without` : "all of them", }, - ...(recovered.length && !accepted.length - ? [ - { - label: "Read for audit only", - value: recovered.length, - note: "the pipeline could not parse these", - }, - ] - : []), ], // Only a figure this step produced. Borrowing the previous step's chart // would put the same picture on two screens in a row, which is exactly the diff --git a/evalrx/reporting/web/src/stages/m4.tsx b/evalrx/reporting/web/src/stages/m4.tsx index 3e7947c9..fc0321c5 100644 --- a/evalrx/reporting/web/src/stages/m4.tsx +++ b/evalrx/reporting/web/src/stages/m4.tsx @@ -35,8 +35,8 @@ import { StageBanner, StageKpis, ExampleSection, ExampleMedia } from "./layout"; /** * Hypotheses M3 proposed with no test_design, from the contract. * - * The legacy card renders "No test design was retained", which says the design - * existed and was lost. It did not exist: the judge proposed a mechanism and no + * A card saying "No test design was retained" would say the design existed + * and was lost. It did not exist: the judge proposed a mechanism and no * way to be wrong about it. That distinction decides how to read M4 — such a * claim returns INCONCLUSIVE however much evidence the next cycle gathers, and * without saying so the reader concludes "needs more data" and runs it again. diff --git a/evalrx/reporting/web/src/stages/m5.tsx b/evalrx/reporting/web/src/stages/m5.tsx index 9dd4822b..27c2d1f6 100644 --- a/evalrx/reporting/web/src/stages/m5.tsx +++ b/evalrx/reporting/web/src/stages/m5.tsx @@ -51,10 +51,7 @@ function repairRefs(report: ReportData): Map { function refFor(report: ReportData, name?: string | null) { if (!name) return ""; - const row = repairRefs(report).get(name); - if (row?.ref) return row.ref; - const order = [...repairRefs(report).keys()].indexOf(name); - return order >= 0 ? `R${order + 1}` : ""; + return repairRefs(report).get(name)?.ref || ""; } function headlineFor(report: ReportData, name?: string | null) { @@ -64,10 +61,10 @@ function headlineFor(report: ReportData, name?: string | null) { /** * The candidates a run tried while CHOOSING one, from the contract. * - * These never reached the legacy stage view, which carries only what was - * confirmed. A run that swept seven candidates across L1 and L2 and confirmed - * one L1 therefore displayed a single L1 row, and every reader concluded L2 was - * never attempted. What got ruled out is part of what the run found. + * The stage view carries only what was confirmed. Shown alone, a run that + * swept seven candidates across L1 and L2 and confirmed one L1 displays a + * single L1 row, and every reader concludes L2 was never attempted. What got + * ruled out is part of what the run found. * * Kept visually apart from the confirmation, and labelled, because these * numbers CHOSE the candidate and so cannot also test it — presenting them in @@ -143,7 +140,7 @@ function SelectionSweep({ report }: { report: ReportData }) { - {r.ref || `R${i + 1}`} + {r.ref} {r.tier} {anyHeadline && ( {r.headline || not described} @@ -635,7 +632,7 @@ export function briefM5(report: ReportData, detail: Partial): Bri : [], points: sweep .slice(0, 4) - .map((row) => `${row.ref || row.name}${row.headline ? ` — ${row.headline}` : ""}`), + .map((row) => `${row.ref}${row.headline ? ` — ${row.headline}` : ""}`), }; } @@ -651,7 +648,7 @@ export function briefM5(report: ReportData, detail: Partial): Bri const pairs = Number(winner?.n_pairs || 0); const odds = oddsPhrase(winner?.e_value); // The e-value gate this candidate was judged against (1/alpha), when the - // run recorded it; older runs did not, and the note then names no bar. + // run recorded it; without it the note names no bar. const gate = oddsValue(winner?.e_threshold); // The plain description of a repair can live in either place. A "floor" // candidate carries it on the stage row; one the judge authored carries it diff --git a/evalrx/reporting/web/src/staticRun.ts b/evalrx/reporting/web/src/staticRun.ts index 6f7607fc..74e88d25 100644 --- a/evalrx/reporting/web/src/staticRun.ts +++ b/evalrx/reporting/web/src/staticRun.ts @@ -61,7 +61,7 @@ export async function readRunArchive(file: File): Promise { // simple catalog elements (mirrors dynamic.load_published_report). const elements = layout?.spec?.elements; if (elements && typeof elements === "object") { - for (const element of Object.values(elements) as any[]) { + for (const element of Object.values(elements) as Array | null>) { if (element && typeof element === "object" && !("props" in element)) element.props = {}; } } @@ -106,12 +106,13 @@ export async function readRunArchive(file: File): Promise { if (url) item.data_uri = url; } } - const attachFigures = async (node: any): Promise => { - if (Array.isArray(node)) { - for (const value of node) await attachFigures(value); + const attachFigures = async (value: unknown): Promise => { + if (Array.isArray(value)) { + for (const item of value) await attachFigures(item); return; } - if (!node || typeof node !== "object") return; + if (!value || typeof value !== "object") return; + const node = value as Record; const raw = node.path; if ( typeof raw === "string" && @@ -121,7 +122,7 @@ export async function readRunArchive(file: File): Promise { const url = await resolve(raw); if (url) node.data_uri = url; } - for (const value of Object.values(node)) await attachFigures(value); + for (const child of Object.values(node)) await attachFigures(child); }; // Figures are cited from several trees (stage briefs, findings, charts); // cases/media/debug are large and carry none, so they are skipped. diff --git a/evalrx/reporting/web/src/styles.css b/evalrx/reporting/web/src/styles.css index bd0741b2..558aa955 100644 --- a/evalrx/reporting/web/src/styles.css +++ b/evalrx/reporting/web/src/styles.css @@ -546,6 +546,9 @@ h1 span { opacity: 0.45; border-style: dashed; } +.stage-failed { + border-color: var(--c-755449); +} .stage-no-improvement { border-color: var(--c-755449); } @@ -4538,6 +4541,10 @@ footer small { color: var(--green); border-color: rgba(107, 216, 173, 0.3); } +.lf-status-failed { + color: var(--c-f4ca72, #f4ca72); + border-color: var(--c-6a5932); +} .lf-status-no-improvement { color: var(--c-f4ca72, #f4ca72); border-color: var(--c-6a5932); @@ -5710,3 +5717,94 @@ footer small { .landing-drop .load-state { min-height: 0; } + +/* Compare runs (#/compare/) */ +.topbar a.compare-toggle { + margin-right: 0; + gap: 6px; + color: var(--green); + font-size: 12px; + letter-spacing: 0.05em; + text-transform: uppercase; +} +.compare-head { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 16px; + margin: 28px 0 16px; +} +.compare-head > div { + display: grid; + gap: 6px; + padding: 16px; + border: 1px solid var(--line); + background: var(--card); +} +.compare-head span, +.compare-note { + color: var(--muted); + font-size: 13px; +} +.compare-head button, +.compare-picker button { + justify-self: start; + border: 1px solid var(--line); + background: transparent; + color: var(--green); + padding: 6px 10px; + cursor: pointer; +} +.compare-picker ul { + list-style: none; + padding: 0; + display: grid; + gap: 8px; +} +.compare-picker button { + display: grid; + gap: 4px; + width: 100%; + text-align: left; + padding: 12px 14px; +} +.compare-picker button span { + color: var(--muted); + font-size: 12px; +} +.compare-cases { + margin-top: 28px; +} +.compare-case-list { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-bottom: 18px; +} +.compare-case-list h3 { + flex-basis: 100%; + margin: 8px 0 0; + font-size: 14px; +} +.compare-case-list a { + color: var(--green); + font-family: ui-monospace, monospace; + font-size: 12px; +} +@media (max-width: 720px) { + .compare-head { + grid-template-columns: 1fr; + } +} +.compare-head code { + color: var(--muted); + font-size: 12px; +} +.run-status { + display: flex; + align-items: center; + gap: 6px; +} +.run-status-quiet .live-dot { + background: var(--muted); + box-shadow: none; +} diff --git a/evalrx/reporting/web/src/types.ts b/evalrx/reporting/web/src/types.ts index f75703f5..60c6b5c2 100644 --- a/evalrx/reporting/web/src/types.ts +++ b/evalrx/reporting/web/src/types.ts @@ -51,18 +51,13 @@ export type { StageDetail, StatView, StatsReportWire, - UnparsedProposal, ValidationEventView, ValidationEvidence, ValidationExample, ValidationResultView, } from "./contract/contract"; -/** - * What a hypothesis card reads. M3 shows its accepted hypotheses, or -- when - * the parser rejected them all -- the proposals recovered from the judge's - * reply, and the card reads the same fields from either. - */ +/** What a hypothesis card reads. */ export type Proposal = { statement?: string | null; plain_statement?: string | null; @@ -120,7 +115,7 @@ export type Case = { trajectory?: unknown; /** The partition the loop put this case in: "explore" (M1-M3), "confirm" * (withheld for M4 / M5), "test" (the frozen final gate in train/val/test - * mode). Null when the run recorded none and none could be inferred. */ + * mode). Null when the run held nothing back. */ split?: string | null; /** What M5's confirmed repair answered on this case, when it was one of the * held-out cases the repair was validated on. */ @@ -312,8 +307,6 @@ export type Partition = { n: number; /** What the run used this partition for, one sentence. */ role: string; - /** True when read off the record order rather than a recorded tag. */ - inferred?: boolean; }; export type ReportData = { @@ -326,6 +319,14 @@ export type ReportData = { question: string; protocol: string; n_cases: number; + /** `explore` when an explore step wrote the run on its own: no model was + * evaluated, only M2/M3 ran. */ + kind: "loop" | "explore"; + /** Whether the run logged its end (`run_end`); false while it is still + * being written. */ + finished: boolean; + /** When the run last logged anything (ISO time), or null. */ + last_event_at?: string | null; diagnosed_by?: string; /** The cover figure the run shipped (`evalrx_main.*` at its root), as a data URI. */ hero_image?: string; @@ -347,9 +348,9 @@ export type ReportData = { broken_cases: number; }>; /** The full record behind each stage, compiled from the run's logs. Read it - * through `stageDetail()`: older payloads can lack any block or key. */ + * through `stageDetail()`: a run that stopped early lacks the later blocks. */ stage_detail?: StageDetail; - /** Contract-validated stage payloads. Absent on runs from before emission existed. */ + /** Contract-validated stage payloads. Absent on a run that emitted none. */ contract?: ContractPayloads; /** The run as one sheet. Null when it produced no probe or stats artifacts. */ case_study?: CaseStudy | null; diff --git a/evalrx/reporting/web/src/upload.tsx b/evalrx/reporting/web/src/upload.tsx index 35cccf6d..6641ef8c 100644 --- a/evalrx/reporting/web/src/upload.tsx +++ b/evalrx/reporting/web/src/upload.tsx @@ -9,10 +9,11 @@ import { useRef, useState } from "react"; import { FolderUp, Upload } from "lucide-react"; import { readRunArchive } from "./staticRun"; -import { api } from "./api"; +import { api, postJson } from "./api"; +import type { LayoutEnvelope, ReportData } from "./types"; /** A run handed to the page. `id` is the server's id for it; absent for an archive read in the browser. */ -export type UploadedRun = { id?: string; label?: string; data: any; layout: any }; +export type UploadedRun = { id?: string; label?: string; data: ReportData; layout: LayoutEnvelope }; /** The GitHub Pages build: no server, archives are read in the browser (staticRun.ts). */ export const STATIC_MODE = import.meta.env.VITE_STATIC === "1"; @@ -20,16 +21,7 @@ export const STATIC_MODE = import.meta.env.VITE_STATIC === "1"; async function postRun(file: File): Promise { const body = new FormData(); body.append("file", file); - const res = await fetch(api.upload, { method: "POST", body }); - const text = await res.text(); - let parsed: any = null; - try { - parsed = JSON.parse(text); - } catch { - /* an error page, not JSON */ - } - if (!res.ok) throw new Error(parsed?.detail || `HTTP ${res.status}`); - return parsed as UploadedRun; + return postJson(api.upload, body); } function useRunUpload(onLoaded: (run: UploadedRun) => void) { diff --git a/evalrx/specs.py b/evalrx/specs.py index a7654de9..019f3c87 100755 --- a/evalrx/specs.py +++ b/evalrx/specs.py @@ -42,7 +42,6 @@ def list_specs() -> list[str]: hf_repo="Qwen/Qwen2.5-7B-Instruct", auto_class="AutoModelForCausalLM", processor_class="AutoTokenizer", min_transformers="4.43.0", tool_calling=True, module_paths=ModulePaths(decoder_layers="model.layers"), - caveats=("matches the legacy QwenLLM default checkpoint",), )) _add(ModelSpec( key="qwen3-4b", family="qwen3", model_type="qwen3", @@ -708,7 +707,7 @@ def list_specs() -> list[str]: # ---------------------------------------------------------------------- # examples/benchmark family: Gemini (Google Gen AI API, closed weights) (2026-08-25) # ---------------------------------------------------------------------- -# ``api_only``: the ``api`` backend with ``gemini_compat.gemini_runtime`` (the +# ``api_only``: the ``api`` backend with ``backends.api.gemini.gemini_runtime`` (the # official google-genai SDK); the spec key IS the API model id (``hf_repo`` is # empty, ``APIModel`` sends ``spec.hf_repo or spec.key``). Every model below # lists text, image, video, audio and PDF as inputs on its model card, so one diff --git a/evalrx/stats/__init__.py b/evalrx/stats/__init__.py index 8edf8972..e14bb28f 100755 --- a/evalrx/stats/__init__.py +++ b/evalrx/stats/__init__.py @@ -8,7 +8,6 @@ from evalrx.stats.api import ( MultiCompareResult, StatResult, - ab_test, compare, compare_multiple, compare_paired_rates, @@ -19,7 +18,7 @@ from evalrx.stats.friedman import chi2_sf, friedman_test, nemenyi_cd, nemenyi_pairs from evalrx.stats.mcnemar import mcnemar from evalrx.stats.multiplicity import MultiplicityReport, bh, correct_results -from evalrx.stats.subset_sampling import kendall_tau, sample_subset, stratified_subset +from evalrx.stats.subset_sampling import kendall_tau, stratified_subset __all__ = [ "compare", @@ -27,7 +26,6 @@ "compare_multiple", "compare_paired_rates", "MultiCompareResult", - "ab_test", "mcnemar", "clustered_bootstrap_diff", "evalue_bernoulli", @@ -43,5 +41,4 @@ "MultiplicityReport", "stratified_subset", "kendall_tau", - "sample_subset", ] diff --git a/evalrx/stats/api.py b/evalrx/stats/api.py index cb4d006f..d5164823 100755 --- a/evalrx/stats/api.py +++ b/evalrx/stats/api.py @@ -145,11 +145,6 @@ def compare_paired_rates( ) -def ab_test(success_a: Sequence, success_b: Sequence, **kwargs) -> StatResult: - """Back-compat alias: pass per-example success vectors (bools/0-1).""" - return compare(success_a, success_b, **kwargs) - - @dataclass class MultiCompareResult: """Omnibus (Friedman) + post-hoc (Nemenyi) verdict for >2 strategies.""" diff --git a/evalrx/stats/multiplicity.py b/evalrx/stats/multiplicity.py index 821ebe44..eada63a4 100644 --- a/evalrx/stats/multiplicity.py +++ b/evalrx/stats/multiplicity.py @@ -37,7 +37,6 @@ class MultiplicityReport: method: str alpha: float n_tested: int - rejected_tools: list[str] = field(default_factory=list) rejected_result_keys: list[str] = field(default_factory=list) families: dict[str, dict[str, Any]] = field(default_factory=dict) note: str = "" @@ -47,7 +46,6 @@ def to_dict(self) -> dict[str, Any]: "method": self.method, "alpha": self.alpha, "n_tested": self.n_tested, - "rejected_tools": self.rejected_tools, "rejected_result_keys": self.rejected_result_keys, "families": self.families, } @@ -138,7 +136,6 @@ def correct_results(results: list[Any], *, alpha: float = 0.05) -> dict[str, Any result.fdr_corrected = False result.correction_method = "BH" - rejected_tools = sorted({str(getattr(results[i], "tool", "")) for i in rejected_indices}) rejected_keys = [_result_key(results[i], i) for i in sorted(rejected_indices)] n_tested = len(e_family) + len(p_family) method = ( @@ -152,7 +149,6 @@ def correct_results(results: list[Any], *, alpha: float = 0.05) -> dict[str, Any method=method, alpha=alpha, n_tested=n_tested, - rejected_tools=rejected_tools, rejected_result_keys=rejected_keys, families=family_reports, note=note, diff --git a/evalrx/stats/subset_sampling.py b/evalrx/stats/subset_sampling.py index da50891d..b102cd39 100755 --- a/evalrx/stats/subset_sampling.py +++ b/evalrx/stats/subset_sampling.py @@ -49,7 +49,3 @@ def kendall_tau(x: Sequence[float], y: Sequence[float]) -> float: disc += 1 denom = n * (n - 1) / 2 return (conc - disc) / denom if denom else 1.0 - - -def sample_subset(items, key, n, seed: int = 0): # back-compat alias - return stratified_subset(items, key, n, seed) diff --git a/evalrx/viz/prompts.py b/evalrx/viz/prompts.py deleted file mode 100644 index 5b5241c8..00000000 --- a/evalrx/viz/prompts.py +++ /dev/null @@ -1,39 +0,0 @@ -"""Prompt contract text for exploratory visualization and dashboard outputs.""" - -VISUALIZATION_OUTPUT_CONTRACT = """\ -Before writing plotting code, emit a visual_plan. For every deterministic chart, -write its plotted data as CSV under tables/ and report a chart spec with -{name, display_name, kind, data, x, y, title}. The host renders chart specs from CSV only. -Also emit chart_readings that describe what a human should see and what the -chart cannot prove. -""" - -DASHBOARD_STORYBOARD_SYSTEM_PROMPT = """\ -You are generating an EvalRX diagnostic report/dashboard, not a raw artifact -browser. Structure the output as three reader-facing panels: - -1. Problem Setting (M1 + run context) - - What data/cases were provided? - - What is FAIL vs PASS? - - Which analyzers/probes/signals are available? - - What split or confirmation policy will be used? - -2. Analysis (M2) - - For each analysis method, produce: method, evidence/chart, takeaway. - - Lead with held-out confirmatory findings, not exploratory observations. - - Demote probe-derived or label-reconstructing fields to sanity checks. - - Every chart needs a human title and a one-sentence reading. - -3. Hypotheses & Artifacts (M3-M5) - - Convert M2 findings into falsifiable M3 hypotheses. - - Link hypotheses to cited evidence. - - Summarize M4/M5 intervention/fix outcomes when present. - - Keep raw artifacts available for inspection, but do not make them the main - reading path. - -Never assume raw field names are user-facing language. Include display_name for -signals/charts and keep raw identifiers only as drill-down provenance. - -Emit the panels as `dashboard_storyboard` in the run JSON. The host dashboard is -a stable renderer; the run-specific narrative must come from this storyboard. -""" diff --git a/evalrx/viz/renderer.py b/evalrx/viz/renderer.py index 25e527f6..c9791300 100644 --- a/evalrx/viz/renderer.py +++ b/evalrx/viz/renderer.py @@ -22,7 +22,7 @@ import logging import re from pathlib import Path -from typing import Any +from typing import Any, Sequence, cast from evalrx.viz.labels import display_name from evalrx.viz.style import ( @@ -268,18 +268,17 @@ def _render_one(plt, spec, rows, x, y, out_dir, idx, style) -> Path: if kind not in _KINDS: kind = "bar" xs_raw = [r.get(x, "") for r in rows] - ys = [_to_float(r.get(y, "")) for r in rows] - keep = [i for i, yv in enumerate(ys) if yv is not None] + ys_raw = [_to_float(r.get(y, "")) for r in rows] + keep = [i for i, yv in enumerate(ys_raw) if yv is not None] if not keep: raise ValueError(f"y column {y!r} has no numeric values") rows = [rows[i] for i in keep] xs_raw = [xs_raw[i] for i in keep] - ys = [ys[i] for i in keep] + ys = [yv for yv in ys_raw if yv is not None] xs_num = [_to_float(v) for v in xs_raw] x_is_num = all(v is not None for v in xs_num) - ns = _n_values(rows, y) + ns: Sequence[float | None] | None = _n_values(rows, y) scale = _rate_scale(y, ys) - rate = scale is not None rc = (style or {}).get("rc", {}) colors = (style or {}).get("colors") or NATURE_COLORS_FALLBACK accent = SEMANTIC_PALETTE["ACCENT"] @@ -391,7 +390,7 @@ def _render_one(plt, spec, rows, x, y, out_dir, idx, style) -> Path: if kind in {"bar", "line", "timeseries"}: ax.grid(axis="y", linewidth=0.6, alpha=0.25, zorder=0) ax.set_axisbelow(True) - if rate and kind != "scatter": + if scale is not None and kind != "scatter": from matplotlib.ticker import PercentFormatter ax.yaxis.set_major_formatter(PercentFormatter(scale, decimals=0)) ax.set_xlabel(xlabel) @@ -413,7 +412,7 @@ def _n_values(rows, y) -> "list[float] | None": if cand in cols and cand != y: vals = [_to_float(r.get(cand, "")) for r in rows] if all(v is not None for v in vals): - return vals + return cast("list[float]", vals) return None @@ -424,7 +423,7 @@ def _ci_values(rows) -> "tuple[list[float], list[float]] | None": los = [_to_float(r.get(lo, "")) for r in rows] his = [_to_float(r.get(hi, "")) for r in rows] if all(v is not None for v in los + his): - return los, his + return cast("list[float]", los), cast("list[float]", his) return None @@ -457,7 +456,7 @@ def _numerator_values(rows, y, ns) -> "list[float] | None": continue vals = [_to_float(r.get(col, "")) for r in rows] if all(v is not None and 0 <= v <= n for v, n in zip(vals, ns)): - return vals + return cast("list[float]", vals) return None diff --git a/evalrx/viz/schema.py b/evalrx/viz/schema.py deleted file mode 100644 index 2432ed16..00000000 --- a/evalrx/viz/schema.py +++ /dev/null @@ -1,36 +0,0 @@ -"""Typed contracts for EvalRX exploratory visualization artifacts.""" - -from __future__ import annotations - -from typing import Any, Literal, TypedDict - -ChartKind = Literal["bar", "line", "scatter", "timeseries"] - - -class ChartSpec(TypedDict, total=False): - name: str - kind: ChartKind - data: str | list[dict[str, Any]] - x: str - y: str - title: str - description: str - figure_path: str - render_skipped: str - - -class VisualPlan(TypedDict, total=False): - name: str - question: str - data_shape: str - plot_kind: str - fallback_kind: ChartKind - required_columns: list[str] - rationale: str - - -class ChartReading(TypedDict, total=False): - chart: str - reading: str - do_not_infer: str - diff --git a/evalrx/wsp/direction.py b/evalrx/wsp/direction.py index 4aa73983..8fee7f6e 100644 --- a/evalrx/wsp/direction.py +++ b/evalrx/wsp/direction.py @@ -301,7 +301,7 @@ def collect_continuation_stats( sequences, skipped = encode_continuations( model, cases, groups=groups, repeat_ngram=repeat_ngram, max_tokens=max_tokens) - sums = {g: {s.layer: {"in": None, "out": None, "n": 0} for s in sites} for g in names} + sums: dict[str, dict[int, dict[str, Any]]] = {g: {s.layer: {"in": None, "out": None, "n": 0} for s in sites} for g in names} current: dict[str, Any] = {} def make(layer: int): diff --git a/evalrx/wsp/edit.py b/evalrx/wsp/edit.py index 219a9c34..e975f783 100644 --- a/evalrx/wsp/edit.py +++ b/evalrx/wsp/edit.py @@ -109,7 +109,7 @@ def __post_init__(self) -> None: self.values = self.values.reshape(-1) if (self.index is None) != (self.values is None): raise ValueError(f"{self.name}: index and values must be given together") - if self.index is not None and len(self.index) != len(self.values): + if self.index is not None and self.values is not None and len(self.index) != len(self.values): raise ValueError(f"{self.name}: index and values differ in length") if (self.a is None) != (self.b is None): raise ValueError(f"{self.name}: low-rank factors a and b must be given together") @@ -163,11 +163,11 @@ def t(x: np.ndarray) -> Any: raise ValueError(f"{self.name}: column index out of range") sub = w[:, cols] w[:, cols] = sub - self.alpha * torch.outer(u, u @ sub) - if self.a is not None: + if self.a is not None and self.b is not None: w = w + (t(self.a) @ t(self.b)).reshape(w.shape) if self.delta is not None: w = w + t(self.delta).reshape(w.shape) - if self.index is not None: + if self.index is not None and self.values is not None: flat = w.reshape(-1).clone() idx = torch.from_numpy(self.index).to(dev) if int(idx.max()) >= flat.numel() or int(idx.min()) < 0: @@ -261,7 +261,10 @@ def from_state_dicts(cls, base: Mapping[str, Any], edited: Mapping[str, Any], *, for key, w0 in base.items(): if key not in edited: continue - d = _f32(edited[key]).astype(np.float64) - _f32(w0).astype(np.float64) + new, old = _f32(edited[key]), _f32(w0) + if new is None or old is None: + continue + d = new.astype(np.float64) - old.astype(np.float64) if d.shape and float(np.abs(d).max(initial=0.0)) > atol: tensors.append(TensorEdit(name=key, form="delta", delta=d.astype(np.float32), shape=tuple(d.shape))) @@ -284,7 +287,7 @@ def as_delta(self, module: Any) -> "WeightEdit": def save(self, directory: str) -> str: """Write ``manifest.json`` + ``edit.npz`` to *directory*; return the directory.""" os.makedirs(directory, exist_ok=True) - arrays: dict[str, np.ndarray] = {} + arrays: dict[str, Any] = {} manifest: dict[str, Any] = { "format": "evalrx.weight_edit", "version": FORMAT_VERSION, "name": self.name, "metadata": self.metadata, "tensors": [], diff --git a/examples/benchmark/readme_jax.md b/examples/benchmark/readme_jax.md index b4f4fd56..5530db59 100644 --- a/examples/benchmark/readme_jax.md +++ b/examples/benchmark/readme_jax.md @@ -473,7 +473,7 @@ toy adapter; point its fixtures at yours for a cheap first check, then a real weights check with `--limit 2 --device cpu`. After the adapter: a `ModelSpec` with `jax=JaxSpec(framework=..., checkpoint=..., -tokenizer=..., adapter="evalrx.models.jax.:make_adapter")`, then steps +tokenizer=..., adapter="evalrx.models.backends.jax.adapters.:make_adapter")`, then steps 2 to 4 of case A. If the model is not Gemma, its runtime stack probably differs too; the design rule in `README.md` is one Dockerfile stage per stack, so give it a stage and a leaf of its own rather than growing `gemma_jax`. diff --git a/examples/benchmark/tools/extract_figure_data.py b/examples/benchmark/tools/extract_figure_data.py index f9bd09b4..01b80536 100644 --- a/examples/benchmark/tools/extract_figure_data.py +++ b/examples/benchmark/tools/extract_figure_data.py @@ -73,7 +73,7 @@ def load_json(path: str, default: Any = None) -> Any: _STAGES = ("M1", "M2", "M3", "M4", "M5") # RUN-stage bucket name -> flattened event name (mirrors -# evalrx.reporting.run_events.read_v2_events; duplicated here rather than +# evalrx.reporting.run_events.read_run_events; duplicated here rather than # imported so this tool stays usable standalone, without the evalrx package # installed, against a bare run directory). _RUN_KEY_TO_EVENT = { @@ -88,7 +88,7 @@ def load_json(path: str, default: Any = None) -> Any: def load_v2_events(logs_dir: str) -> List[dict]: - """Flatten RunLoggerV2's ``run.json`` + ``M/log.json`` into the same + """Flatten RunLogger's ``run.json`` + ``M/log.json`` into the same ordered, flat event-dict list this tool used to get from ``run_log.jsonl``.""" run = load_json(os.path.join(logs_dir, "run.json"), {}) or {} events: List[dict] = [] @@ -161,7 +161,7 @@ def __init__(self, root: str): self.summary = load_json(os.path.join(self.root, "summary.json"), {}) or {} run_doc = load_json(os.path.join(self.logs, "run.json"), {}) or {} - # manifest lives inline in run.json under RunLoggerV2 (no separate + # manifest lives inline in run.json under RunLogger (no separate # manifest.json file) — same {"run_id", "config", "files"} shape. self.manifest = run_doc.get("manifest") or {} self.config = self.manifest.get("config", {}) or {} @@ -172,7 +172,7 @@ def __init__(self, root: str): self.manifest_run_id = self.manifest.get("run_id") # every case in the batch, with prompt / gold / baseline output / label. - # RunLoggerV2 inlines this into the diagnose_reports entry it wrote + # RunLogger inlines this into the diagnose_reports entry it wrote # (no separate report/discovery_cases.json file). diagnose_reports = run_doc.get("diagnose_reports") or [] discovery = diagnose_reports[-1].get("discovery") if diagnose_reports else [] @@ -244,7 +244,7 @@ def m2_phases(self) -> List[tuple]: Convention: cycle 0 is the discovery cycle ("explore"), cycle -1 is the held-out confirmation pass ("heldout"); any other cycle keeps its - own ``cN`` label. RunLoggerV2 inlines ``stats_results`` directly on + own ``cN`` label. RunLogger inlines ``stats_results`` directly on the ``analysis`` entry — no sibling ``*_m2_stats_results.json`` file. """ out = [] @@ -299,7 +299,7 @@ def analyzer_per_case(self, analyzer: str, cycle_prefix: str) -> List[dict]: """Per-case rows for *analyzer* at the probe cycle named by *cycle_prefix* (``"c0"``, ``"c1"``, ..., ``"post"``/``"c-1"``). - RunLoggerV2 inlines every analyzer's complete result (including + RunLogger inlines every analyzer's complete result (including ``findings.per_case``) into its ``M1/log.json`` probe entry — no sibling ``_.result.json`` file to read. """ diff --git a/examples/benchmark/tools/replay_narrate.py b/examples/benchmark/tools/replay_narrate.py index 045d90f9..8f6db8e2 100644 --- a/examples/benchmark/tools/replay_narrate.py +++ b/examples/benchmark/tools/replay_narrate.py @@ -1,11 +1,11 @@ #!/usr/bin/env python3 -"""Replay a finished benchmark run's console narration from its V2 logs. +"""Replay a finished benchmark run's console narration from its run log. Usage: python replay_narrate.py [--color] is an outputs//[.]/ directory holding -logs/run.json + logs/M*/log.json (RunLoggerV2 layout) and, optionally, +logs/run.json + logs/M*/log.json (RunLogger layout) and, optionally, summary.json + baseline.json for the runner's own context lines. Nothing is simulated: every narrated line is rendered by the same @@ -37,7 +37,7 @@ def main() -> int: logs = args.run_dir / "logs" if not (logs / "run.json").exists(): - sys.exit(f"{logs}/run.json not found — not a RunLoggerV2 run (V1 layouts can't be replayed)") + sys.exit(f"{logs}/run.json not found — not a run log") run = load(logs / "run.json") summary = load(args.run_dir / "summary.json") if (args.run_dir / "summary.json").exists() else {} diff --git a/examples/dataset_selection/llm_benchmark/README.md b/examples/dataset_selection/llm_benchmark/README.md index 16b988d5..fc9cdc65 100644 --- a/examples/dataset_selection/llm_benchmark/README.md +++ b/examples/dataset_selection/llm_benchmark/README.md @@ -30,7 +30,7 @@ git clone <你的远端地址> evalsmith cd evalsmith/evalrx # 有 pyproject.toml 的那一层 # (a) 评测环境 —— 跑本目录的脚本 -python3 -m venv .venv # 需要 python >= 3.10 +python3 -m venv .venv # 需要 python >= 3.11 .venv/bin/pip install -U pip .venv/bin/pip install -e ".[stats,viz,ui]" .venv/bin/pip install requests @@ -101,7 +101,7 @@ GPU 空闲显存够不够这个尺寸、磁盘够不够放权重、datasets-serv 以及数据集名能否解析。**每条 FAIL 都直接给出该敲的安装命令。** ``` - OK python 3.12.13 (>=3.10) + OK python 3.12.13 (>=3.11) FAIL missing module statsmodels — needed for M2 statistics -> pip install -e ".[stats]" OK claude CLI 2.1.181 (Claude Code) @@ -811,7 +811,7 @@ outputs/ │ ├── figures/*.png # host 从 spec + csv 渲染的图(M3 看到的就是这些) │ ├── analysis.py # coder 生成的分析代码(可审计、可重跑) │ └── sandbox/ # 该步的工作目录 - └── logs/ # RunLoggerV2:M1-M5 逐阶段轨迹(run.json + M/log.json,无 run_log.jsonl) + └── logs/ # RunLogger:M1-M5 逐阶段轨迹(run.json + M/log.json,无 run_log.jsonl) ├── run.json # 运行级事件(run_start / cases / diagnose_reports / …) ├── M1/log.json … M5/log.json # 每阶段一个文件;`explore` 事件在 M2 里(计数 + 路径,描述性) ├── artifacts/ # M2 统计结果 JSON(c0_m2_stats_results.json 等) diff --git a/examples/dataset_selection/llm_benchmark/preflight.py b/examples/dataset_selection/llm_benchmark/preflight.py index bc25737f..00cebf57 100755 --- a/examples/dataset_selection/llm_benchmark/preflight.py +++ b/examples/dataset_selection/llm_benchmark/preflight.py @@ -60,11 +60,11 @@ def warn(msg: str, fix: str = "") -> None: def check_python() -> None: v = sys.version_info - if (v.major, v.minor) >= (3, 10): - ok(f"python {v.major}.{v.minor}.{v.micro} (>=3.10)") + if (v.major, v.minor) >= (3, 11): + ok(f"python {v.major}.{v.minor}.{v.micro} (>=3.11)") else: bad(f"python {v.major}.{v.minor} is too old", - "evalrx requires >=3.10; make a new venv") + "evalrx requires >=3.11; make a new venv") def check_imports() -> None: diff --git a/examples/dataset_selection/llm_benchmark/run_pipeline.py b/examples/dataset_selection/llm_benchmark/run_pipeline.py index 39c860a3..f83918e1 100644 --- a/examples/dataset_selection/llm_benchmark/run_pipeline.py +++ b/examples/dataset_selection/llm_benchmark/run_pipeline.py @@ -573,8 +573,8 @@ def build_analyzer_overrides(max_cases: int, model=None, verbose: bool = True) - def _stats_report_from(diagnosis: dict, analysis: dict, raw_results: dict, logs_dir: Path): - """Shared V1/V2 tail of :func:`load_prior_run`: rebuild the - ``StatsAnalysisReport`` once the per-version reader has produced plain + """The tail of :func:`load_prior_run`: rebuild the + ``StatsAnalysisReport`` once the reader has produced plain dicts for the last M3 diagnosis / M2 analysis / M1 probe events.""" from evalrx.analysis.stats_agent import StatsAnalysisReport from evalrx.analysis.stats_tools import StatsToolResult @@ -612,7 +612,7 @@ def _stats_report_from(diagnosis: dict, analysis: dict, raw_results: dict, logs_ def _load_prior_run_v2(logs_dir: Path): - """RunLoggerV2 layout: one JSON document per stage, same-event arrays. + """RunLogger layout: one JSON document per stage, same-event arrays. M1/M2/M3 each keep every cycle's entry in an array under their own key (``probe`` / ``analysis`` / ``diagnosis``); the last entry is the latest cycle. Nothing here is externalized to a sibling file (v2 inlines @@ -786,7 +786,7 @@ def main() -> None: from evalrx.eval_agent import ( ExperimentWriterConfig, FixAgent, - RunLoggerV2, + RunLogger, SurgeryAgent, VLDiagnoseLoop, ) @@ -850,9 +850,9 @@ def main() -> None: overrides = (build_analyzer_overrides(args.analyzer_max_cases, model=model) if args.analyzer_max_cases > 0 else {}) # A confirm-only pass logs beside the analysis it reuses, never over it. - # RunLoggerV2 writes run.json + one JSON per M-stage (M1/log.json .. - # M5/log.json) under this dir — see evalrx/eval_agent/RUN_LOGGER_V2.md. - logger = RunLoggerV2(run_dir=out / ("logs_confirm" if args.confirm_only else "logs"), + # RunLogger writes run.json + one JSON per M-stage (M1/log.json .. + # M5/log.json) under this dir — see evalrx/eval_agent/RUN_LOGGER.md. + logger = RunLogger(run_dir=out / ("logs_confirm" if args.confirm_only else "logs"), verbose=True) # max_cases_per_analyzer is the BACKSTOP for analyzer_overrides: the @@ -998,7 +998,7 @@ def main() -> None: else bool(CFG.get("fix_on_unverified", True))), "fix_candidate_repeats": int(CFG.get("fix_candidate_repeats", 1)), "n_hypotheses": len(getattr(report, "hypotheses", None) - or getattr(report, "all_hypotheses", None) or []), + or getattr(report, "final_hypotheses", None) or []), "n_verified": len(getattr(report, "verified_hypotheses", []) or []), "model_calls": model.n_calls, "model_truncated": model.n_truncated, diff --git a/examples/m1_m3/qwen_loop_agy/run.py b/examples/m1_m3/qwen_loop_agy/run.py index 09bafeef..0a0e6d25 100755 --- a/examples/m1_m3/qwen_loop_agy/run.py +++ b/examples/m1_m3/qwen_loop_agy/run.py @@ -413,7 +413,6 @@ def _run_smoke_test(args) -> None: HypothesisTester, RunContext, StatsAnalysisAgent, - StatsToolAgent, SurgeryAgent, VLDiagnoseLoop, ) @@ -440,7 +439,7 @@ def _run_smoke_test(args) -> None: model=model, protocol=protocol, probe_agent=_SmokeProbe(), - stats_agent=StatsAnalysisAgent(stats_tool_agent=StatsToolAgent(max_tools=3)), + stats_agent=StatsAnalysisAgent(), diagnosis_agent=_SmokeDiagnosisAgent(), hypothesis_tester=HypothesisTester(min_effect=0.05), surgery_agent=SurgeryAgent(), @@ -652,12 +651,12 @@ def main() -> None: _m1_codegen = args.allow_codegen and not args.analysis_only if args.analyzers.strip(): # Pinned analyzer list — deterministic M1 for reproducible experiments. - from evalrx.eval_agent import StrategyProbe + from evalrx.eval_agent import ModelKind, StrategyProbe pinned = [a.strip() for a in args.analyzers.split(",") if a.strip()] print(f" M1 pinned analyzers: {pinned}") probe_agent = ProbeAgent( - probe=StrategyProbe(priority_override={k: pinned for k in ("vlm", "agent", "llm")}), + probe=StrategyProbe(priority_override={kind: pinned for kind in ModelKind}), judge=None, # bypass LLM selection max_analyzers=len(pinned), ) @@ -742,7 +741,7 @@ def main() -> None: print(f"\n{'='*64}") print(f"LOOP RESULT stopped_by={report.stopped_by} cycles={report.cycles}") print(f"{'='*64}") - print(f" total hypotheses proposed : {len(report.all_hypotheses)}") + print(f" total hypotheses proposed : {len(report.final_hypotheses)}") print(f" verified (protocol-consistent + statistically supported): " f"{len(report.verified_hypotheses)}") for vr in report.verified_hypotheses: diff --git a/examples/m1_m3/qwen_video_temporal/run.py b/examples/m1_m3/qwen_video_temporal/run.py index 6a5dee52..300504aa 100755 --- a/examples/m1_m3/qwen_video_temporal/run.py +++ b/examples/m1_m3/qwen_video_temporal/run.py @@ -325,7 +325,6 @@ def _run_smoke_test(args) -> None: HypothesisTester, RunContext, StatsAnalysisAgent, - StatsToolAgent, SurgeryAgent, VLDiagnoseLoop, ) @@ -354,7 +353,7 @@ def _run_smoke_test(args) -> None: model=model, protocol=protocol, probe_agent=_SmokeProbe(), - stats_agent=StatsAnalysisAgent(stats_tool_agent=StatsToolAgent(max_tools=3)), + stats_agent=StatsAnalysisAgent(), diagnosis_agent=_SmokeDiagnosisAgent(), hypothesis_tester=HypothesisTester(min_effect=0.05), surgery_agent=SurgeryAgent(), @@ -548,7 +547,7 @@ def main() -> None: print(f"\n{'='*64}") print(f"LOOP RESULT stopped_by={report.stopped_by} cycles={report.cycles}") print(f"{'='*64}") - print(f" total hypotheses proposed : {len(report.all_hypotheses)}") + print(f" total hypotheses proposed : {len(report.final_hypotheses)}") print(f" verified : {len(report.verified_hypotheses)}") for vr in report.verified_hypotheses: print(f" [{vr.status.value}] {vr.hypothesis.statement}") diff --git a/examples/m1_m3/vlm_research_topics/run.py b/examples/m1_m3/vlm_research_topics/run.py index 52f84474..9f1fbe6f 100755 --- a/examples/m1_m3/vlm_research_topics/run.py +++ b/examples/m1_m3/vlm_research_topics/run.py @@ -644,7 +644,6 @@ def _run_smoke_test(args, scenario: str) -> None: HypothesisTester, RunContext, StatsAnalysisAgent, - StatsToolAgent, SurgeryAgent, VLDiagnoseLoop, ) @@ -679,7 +678,7 @@ def _run_smoke_test(args, scenario: str) -> None: model=model, protocol=protocol, probe_agent=_SmokeProbe(), - stats_agent=StatsAnalysisAgent(stats_tool_agent=StatsToolAgent(max_tools=3)), + stats_agent=StatsAnalysisAgent(), diagnosis_agent=_SmokeDiagnosis(scenario), hypothesis_tester=HypothesisTester(min_effect=0.05), surgery_agent=SurgeryAgent(), @@ -903,7 +902,7 @@ def main() -> None: print(f"\n{'='*64}") print(f"LOOP RESULT stopped_by={report.stopped_by} cycles={report.cycles}") - print(f" total hypotheses : {len(getattr(report, 'all_hypotheses', []))}") + print(f" total hypotheses : {len(getattr(report, 'final_hypotheses', []))}") print(f" verified hypotheses: {len(getattr(report, 'verified_hypotheses', []))}") for vr in getattr(report, "verified_hypotheses", []): print(f" [{vr.status.value}] {vr.hypothesis.statement}") diff --git a/examples/m1_m5/audiocaps_hallucination_qwen2_audio/run.py b/examples/m1_m5/audiocaps_hallucination_qwen2_audio/run.py index f70f54d3..f4f48515 100644 --- a/examples/m1_m5/audiocaps_hallucination_qwen2_audio/run.py +++ b/examples/m1_m5/audiocaps_hallucination_qwen2_audio/run.py @@ -221,7 +221,6 @@ def _run_smoke_test(args: argparse.Namespace) -> None: ProbingSchema, RunContext, StatsAnalysisAgent, - StatsToolAgent, VLDiagnoseLoop, ) @@ -323,7 +322,7 @@ def diagnose(self, analysis, prior_cycles=None): target_modalities=frozenset({"text", "audio"}), ), probe_agent=_SmokeProbe(), - stats_agent=StatsAnalysisAgent(stats_tool_agent=StatsToolAgent(max_tools=3)), + stats_agent=StatsAnalysisAgent(), diagnosis_agent=_SmokeDiagnosisAgent(), hypothesis_tester=HypothesisTester(min_effect=0.05), fix_agent=FixAgent( @@ -472,6 +471,7 @@ def baseline_generate(row: dict[str, Any]) -> str: DiagnosisAgent, FixAgent, HypothesisTester, + ModelKind, ProbeAgent, RunContext, StatsAnalysisAgent, @@ -502,7 +502,7 @@ def baseline_generate(row: dict[str, Any]) -> str: # M1 pinned static selection -- see PINNED_M1_ANALYZERS' comment above for why. probe_agent = ProbeAgent( - probe=StrategyProbe(priority_override={k: PINNED_M1_ANALYZERS for k in ("vlm", "agent", "llm")}), + probe=StrategyProbe(priority_override={kind: PINNED_M1_ANALYZERS for kind in ModelKind}), judge=None, max_analyzers=args.max_analyzers, ) @@ -586,7 +586,7 @@ def baseline_generate(row: dict[str, Any]) -> str: ctx.write_diagnose_report(report, cases) print(f"\n{'='*64}\nLOOP RESULT stopped_by={report.stopped_by} cycles={report.cycles}\n{'='*64}") - print(f" total hypotheses proposed : {len(report.all_hypotheses)}") + print(f" total hypotheses proposed : {len(report.final_hypotheses)}") print(f" verified (protocol-consistent + statistically supported): " f"{len(report.verified_hypotheses)}") for vr in report.verified_hypotheses: diff --git a/examples/m1_m5/deco_hallu/Dockerfile b/examples/m1_m5/deco_hallu/Dockerfile index ab51afda..120b91cf 100644 --- a/examples/m1_m5/deco_hallu/Dockerfile +++ b/examples/m1_m5/deco_hallu/Dockerfile @@ -1,3 +1,12 @@ +# The report renderer is built from source: web_dist/ is gitignored, so a +# fresh clone has none and the explore step's report.html needs it. +FROM node:22-slim AS web +WORKDIR /src/evalrx/reporting/web +COPY evalrx/reporting/web/package.json evalrx/reporting/web/package-lock.json ./ +RUN npm ci +COPY evalrx/reporting/web/ ./ +RUN npm run build + FROM python:3.11-slim WORKDIR /app @@ -6,6 +15,7 @@ RUN pip install --no-cache-dir \ torch torchvision --index-url https://download.pytorch.org/whl/cu124 COPY . /evalrx +COPY --from=web /src/evalrx/reporting/web_dist /evalrx/evalrx/reporting/web_dist RUN pip install --no-cache-dir "/evalrx[local,data]" PyYAML WORKDIR /app/example diff --git a/examples/m1_m5/deco_hallu/run.py b/examples/m1_m5/deco_hallu/run.py index 0195f572..d3aedd38 100755 --- a/examples/m1_m5/deco_hallu/run.py +++ b/examples/m1_m5/deco_hallu/run.py @@ -226,7 +226,7 @@ def main() -> None: CliAgentConfig, ExperimentWriterConfig, FixAgent, - RunLoggerV2, + RunLogger, SurgeryAgent, VLDiagnoseLoop, ) @@ -255,7 +255,7 @@ def main() -> None: extra_args=(("--effort", codegen_effort) if codegen_effort else ()), ) print(f"codegen: claude_code model={codegen.model} effort={codegen_effort or 'default'}") - run_logger = RunLoggerV2(run_dir=OUT / "logs", narrate=True) + run_logger = RunLogger(run_dir=OUT / "logs", narrate=True) loop = VLDiagnoseLoop( model=model, probe_agent=ProbeAgent(judge=judge, max_analyzers=args.max_analyzers, @@ -286,6 +286,7 @@ def main() -> None: print("m5:", fix) outcome = loop.run_fix(report, cases) print("fix outcome:", getattr(outcome, "recommendation", None) or outcome) + run_logger.close() if __name__ == "__main__": diff --git a/examples/m1_m5/deco_hallu/run_analysis.py b/examples/m1_m5/deco_hallu/run_analysis.py index 4090cd31..007b8aeb 100644 --- a/examples/m1_m5/deco_hallu/run_analysis.py +++ b/examples/m1_m5/deco_hallu/run_analysis.py @@ -71,7 +71,7 @@ def main() -> None: from evalrx.analysis.stats_agent import StatsAnalysisAgent from evalrx.eval_agent import ( CliAgentConfig, - RunLoggerV2, + RunLogger, VLDiagnoseLoop, ) from evalrx.eval_agent.hypothesis import hypothesis_to_dict @@ -101,7 +101,7 @@ def main() -> None: f"{len(explore_report.get('charts') or [])} chart(s), " f"{len(explore_report.get('observations') or [])} observation(s)") - run_logger = RunLoggerV2(run_dir=OUT / "logs_analysis", narrate=True) + run_logger = RunLogger(run_dir=OUT / "logs_analysis", narrate=True) loop = VLDiagnoseLoop( model=model, protocol=run.build_protocol(), @@ -119,13 +119,13 @@ def main() -> None: run_logger.close() print(f"\nstopped_by={report.stopped_by} " - f"proposed={len(report.all_hypotheses)} (UNCONFIRMED — no M4/M5/Fix yet)") - for h in report.all_hypotheses: + f"proposed={len(report.final_hypotheses)} (UNCONFIRMED — no M4/M5/Fix yet)") + for h in report.final_hypotheses: print(f" - [{h.predicted_failure_mode}] {h.statement[:110]}") # ── Persist the artifacts PHASE 2 reuses (same hypotheses + same stats) ── ANALYSIS_DIR.mkdir(parents=True, exist_ok=True) - hyp_dicts = [hypothesis_to_dict(h) for h in report.all_hypotheses] + hyp_dicts = [hypothesis_to_dict(h) for h in report.final_hypotheses] (ANALYSIS_DIR / "proposed_hypotheses.json").write_text( json.dumps(hyp_dicts, indent=2), encoding="utf-8") diff --git a/examples/m1_m5/deco_hallu/run_confirm_fix.py b/examples/m1_m5/deco_hallu/run_confirm_fix.py index da5cdd7d..394f1367 100644 --- a/examples/m1_m5/deco_hallu/run_confirm_fix.py +++ b/examples/m1_m5/deco_hallu/run_confirm_fix.py @@ -86,7 +86,7 @@ def main() -> None: CliAgentConfig, ExperimentWriterConfig, FixAgent, - RunLoggerV2, + RunLogger, SurgeryAgent, VLDiagnoseLoop, ) @@ -99,7 +99,7 @@ def main() -> None: Capability.ATTENTION}) codegen: CliAgentConfig = run.build_codegen(args.backend) - run_logger = RunLoggerV2(run_dir=OUT / "logs_confirm_fix", narrate=True) + run_logger = RunLogger(run_dir=OUT / "logs_confirm_fix", narrate=True) loop = VLDiagnoseLoop( model=model, protocol=run.build_protocol(), diff --git a/examples/m1_m5/deco_hallu/run_fused.py b/examples/m1_m5/deco_hallu/run_fused.py index 7a90accd..f28b8a97 100644 --- a/examples/m1_m5/deco_hallu/run_fused.py +++ b/examples/m1_m5/deco_hallu/run_fused.py @@ -141,9 +141,9 @@ def main() -> None: "run_m2-5.py --explore-report outputs/fused/fused_report.json)") if args.serve_report: - from evalrx.reporting.html_report import build_html_report, open_in_browser + from evalrx.reporting.static_export import write_report - open_in_browser(build_html_report(FUSED_DIR, out_path=FUSED_DIR / "report.html")) + write_report(FUSED_DIR, open_report=True) if __name__ == "__main__": diff --git a/examples/m1_m5/deco_hallu/run_m1.py b/examples/m1_m5/deco_hallu/run_m1.py index 73c43d0d..59f41ab7 100755 --- a/examples/m1_m5/deco_hallu/run_m1.py +++ b/examples/m1_m5/deco_hallu/run_m1.py @@ -39,7 +39,7 @@ def main() -> None: from evalrx import compose from evalrx.core.capability import Capability - from evalrx.eval_agent import CliAgentConfig, RunLoggerV2 + from evalrx.eval_agent import CliAgentConfig, RunLogger from evalrx.eval_agent.stages.probe_agent import ProbeAgent from evalrx.models.backends.base import RuntimeConfig @@ -63,7 +63,7 @@ def main() -> None: extra_args=(("--effort", codegen_effort) if codegen_effort else ()), ) protocol = run.build_protocol() - run_logger = RunLoggerV2(run_dir=OUT / "logs_m1", narrate=True) + run_logger = RunLogger(run_dir=OUT / "logs_m1", narrate=True) probe_agent = ProbeAgent(judge=judge, max_analyzers=args.max_analyzers, allow_codegen=True, codegen_config=codegen, run_logger=run_logger) diff --git a/examples/m1_m5/deco_hallu/run_m2-5.py b/examples/m1_m5/deco_hallu/run_m2-5.py index 0be4742d..c857839f 100755 --- a/examples/m1_m5/deco_hallu/run_m2-5.py +++ b/examples/m1_m5/deco_hallu/run_m2-5.py @@ -73,7 +73,7 @@ def main() -> None: from evalrx.eval_agent import ( ExperimentWriterConfig, FixAgent, - RunLoggerV2, + RunLogger, SurgeryAgent, VLDiagnoseLoop, ) @@ -110,7 +110,7 @@ def main() -> None: n_obs = len(explore_report.get("observations") or []) print(f"feeding explore context to M3: {n_charts} chart(s), {n_obs} observation(s)") - run_logger = RunLoggerV2(run_dir=OUT / "logs_m2_5", narrate=True) + run_logger = RunLogger(run_dir=OUT / "logs_m2_5", narrate=True) loop = VLDiagnoseLoop( model=model, probe_agent=ReplayProbeAgent(state), # M1 short-circuited diff --git a/examples/m1_m5/mllms_hallucination/run.py b/examples/m1_m5/mllms_hallucination/run.py index 5b3e84eb..360627a7 100755 --- a/examples/m1_m5/mllms_hallucination/run.py +++ b/examples/m1_m5/mllms_hallucination/run.py @@ -357,7 +357,7 @@ def main() -> None: n_verified = len(report.verified_hypotheses) _bar(f"DIAGNOSIS {report.cycles} cycle(s) / stopped: {report.stopped_by}") - print(f" {len(report.all_hypotheses)} hypothesis/es generated / {n_verified} verified") + print(f" {len(report.final_hypotheses)} hypothesis/es generated / {n_verified} verified") for vr in report.verified_hypotheses: stmt = textwrap.shorten(vr.hypothesis.statement, width=90, placeholder="...") print(f"\n SUPPORTED: {stmt}") diff --git a/examples/m1_m5/mllms_small_object/run.py b/examples/m1_m5/mllms_small_object/run.py index 996d16e5..cba215be 100755 --- a/examples/m1_m5/mllms_small_object/run.py +++ b/examples/m1_m5/mllms_small_object/run.py @@ -408,7 +408,7 @@ def main() -> None: n_verified = len(report.verified_hypotheses) _bar(f"DIAGNOSIS {report.cycles} cycle(s) / stopped: {report.stopped_by}") - print(f" {len(report.all_hypotheses)} hypothesis/es generated / {n_verified} verified") + print(f" {len(report.final_hypotheses)} hypothesis/es generated / {n_verified} verified") for vr in report.verified_hypotheses: stmt = textwrap.shorten(vr.hypothesis.statement, width=90, placeholder="...") print(f"\n SUPPORTED: {stmt}") diff --git a/examples/m1_m5/mmau_qwen2_audio/README.md b/examples/m1_m5/mmau_qwen2_audio/README.md index 7b91c5f8..6e186e37 100644 --- a/examples/m1_m5/mmau_qwen2_audio/README.md +++ b/examples/m1_m5/mmau_qwen2_audio/README.md @@ -231,22 +231,17 @@ included and hoped-for. ## Case study: listen to the clips, answer them yourself ```bash -evalrx report examples/m1_m5/mmau_qwen2_audio/outputs \ - --example-dir examples/m1_m5/mmau_qwen2_audio +evalrx report examples/m1_m5/mmau_qwen2_audio/outputs evalrx serve examples/m1_m5/mmau_qwen2_audio/outputs ``` -The report re-joins case ids to -`data/mmau_test_mini.jsonl`, so each case shows up with its `.wav` in an -audio player, its question and its four options. Requires `./data` to be -populated — playback needs the audio files `download_mmau.py` fetched. +The run log keeps every case with a copy of its `.wav`, so each case shows up +with an audio player and its question. ## Demo page: the whole loop as one shareable HTML file ```bash -evalrx report outputs \ - --example-dir . \ - --out demo_page/index.html +evalrx report outputs --out demo_page/index.html ``` This renders one finished run as a single self-contained page (every figure and diff --git a/examples/m1_m5/mmau_qwen2_audio/run.py b/examples/m1_m5/mmau_qwen2_audio/run.py index 8612365c..bded3e6d 100644 --- a/examples/m1_m5/mmau_qwen2_audio/run.py +++ b/examples/m1_m5/mmau_qwen2_audio/run.py @@ -250,7 +250,6 @@ def _run_smoke_test(args: argparse.Namespace) -> None: ProbingSchema, RunContext, StatsAnalysisAgent, - StatsToolAgent, VLDiagnoseLoop, ) @@ -354,7 +353,7 @@ def generate(self, prompt, **kwargs) -> str: target_modalities=frozenset({"text", "audio"}), ), probe_agent=_SmokeProbe(), - stats_agent=StatsAnalysisAgent(stats_tool_agent=StatsToolAgent(max_tools=3)), + stats_agent=StatsAnalysisAgent(), diagnosis_agent=_SmokeDiagnosisAgent(), hypothesis_tester=HypothesisTester(min_effect=0.05), fix_agent=FixAgent( @@ -568,14 +567,13 @@ def _run_tcd_confirmation(args: argparse.Namespace) -> int: ebh_survivors=[candidate.name] if validation.fixed else [], ) ctx.logger.log_fix(outcome) - ctx.publish_report(example_dir=HERE) + ctx.publish_report() ctx.finalize() from evalrx.reporting.static_export import export_static_report report_html_path = Path(args.run_dir).resolve() / "report.html" export_static_report( ctx.root, - example_dir=HERE, out_path=report_html_path, embed_media="all" if args.report_media == "inline" else "none", ) @@ -737,6 +735,7 @@ def baseline_generate(row: dict[str, Any]) -> str: DiagnosisAgent, FixAgent, HypothesisTester, + ModelKind, ProbeAgent, RunContext, StatsAnalysisAgent, @@ -767,7 +766,7 @@ def baseline_generate(row: dict[str, Any]) -> str: # M1 pinned static selection -- see PINNED_M1_ANALYZERS' comment above for why. probe_agent = ProbeAgent( - probe=StrategyProbe(priority_override={k: PINNED_M1_ANALYZERS for k in ("vlm", "agent", "llm")}), + probe=StrategyProbe(priority_override={kind: PINNED_M1_ANALYZERS for kind in ModelKind}), judge=None, max_analyzers=args.max_analyzers, ) @@ -854,7 +853,7 @@ def baseline_generate(row: dict[str, Any]) -> str: ctx.write_diagnose_report(report, cases) print(f"\n{'='*64}\nLOOP RESULT stopped_by={report.stopped_by} cycles={report.cycles}\n{'='*64}") - print(f" total hypotheses proposed : {len(report.all_hypotheses)}") + print(f" total hypotheses proposed : {len(report.final_hypotheses)}") print(f" verified (protocol-consistent + statistically supported): " f"{len(report.verified_hypotheses)}") for vr in report.verified_hypotheses: @@ -904,14 +903,13 @@ def baseline_generate(row: dict[str, Any]) -> str: else: print(f" VERDICT : not fixed; already at the highest tier ({args.fix_max_tier})") - loop.publish_report(example_dir=HERE) + loop.publish_report() ctx.finalize() from evalrx.reporting.static_export import export_static_report report_html_path = Path(args.run_dir).resolve() / "report.html" export_static_report( ctx.root, - example_dir=HERE, out_path=report_html_path, embed_media="all" if args.report_media == "inline" else "none", ) diff --git a/examples/m1_m5/musicavqa_videollama2/run.py b/examples/m1_m5/musicavqa_videollama2/run.py index e82079e0..55493e56 100644 --- a/examples/m1_m5/musicavqa_videollama2/run.py +++ b/examples/m1_m5/musicavqa_videollama2/run.py @@ -157,7 +157,7 @@ def main() -> None: ) from evalrx.eval_agent.stages.diagnosis import DiagnosisAgent from evalrx.eval_agent.stages.probe_agent import ProbeAgent - from evalrx.eval_agent.stages.probe import StrategyProbe + from evalrx.eval_agent.stages.probe import ModelKind, StrategyProbe from evalrx.analysis.stats_agent import StatsAnalysisAgent judge = build_judge(args.judge_model, args.judge_effort) # probe BEFORE weights load @@ -186,7 +186,7 @@ def main() -> None: loop = VLDiagnoseLoop( model=model, probe_agent=ProbeAgent( - probe=StrategyProbe(priority_override={k: PINNED_M1_ANALYZERS for k in ("vlm", "agent", "llm")}), + probe=StrategyProbe(priority_override={kind: PINNED_M1_ANALYZERS for kind in ModelKind}), judge=None, # pinned static selection -- see PINNED_M1_ANALYZERS above max_analyzers=len(PINNED_M1_ANALYZERS), ), diff --git a/examples/m1_m5/qwen_loop_claude/run.py b/examples/m1_m5/qwen_loop_claude/run.py index 645f22a5..152267e1 100755 --- a/examples/m1_m5/qwen_loop_claude/run.py +++ b/examples/m1_m5/qwen_loop_claude/run.py @@ -492,7 +492,6 @@ def _run_smoke_test(args) -> None: HypothesisTester, RunContext, StatsAnalysisAgent, - StatsToolAgent, SurgeryAgent, VLDiagnoseLoop, ) @@ -519,7 +518,7 @@ def _run_smoke_test(args) -> None: model=model, protocol=protocol, probe_agent=_SmokeProbe(), - stats_agent=StatsAnalysisAgent(stats_tool_agent=StatsToolAgent(max_tools=3)), + stats_agent=StatsAnalysisAgent(), diagnosis_agent=_SmokeDiagnosisAgent(), hypothesis_tester=HypothesisTester(min_effect=0.05), surgery_agent=SurgeryAgent(), @@ -755,12 +754,12 @@ def main() -> None: _m1_codegen = args.allow_codegen and not args.analysis_only if args.analyzers.strip(): # Pinned analyzer list — deterministic M1 for reproducible experiments. - from evalrx.eval_agent import StrategyProbe + from evalrx.eval_agent import ModelKind, StrategyProbe pinned = [a.strip() for a in args.analyzers.split(",") if a.strip()] print(f" M1 pinned analyzers: {pinned}") probe_agent = ProbeAgent( - probe=StrategyProbe(priority_override={k: pinned for k in ("vlm", "agent", "llm")}), + probe=StrategyProbe(priority_override={kind: pinned for kind in ModelKind}), judge=None, # bypass LLM selection max_analyzers=len(pinned), ) @@ -865,7 +864,7 @@ def main() -> None: print(f"\n{'='*64}") print(f"LOOP RESULT stopped_by={report.stopped_by} cycles={report.cycles}") print(f"{'='*64}") - print(f" total hypotheses proposed : {len(report.all_hypotheses)}") + print(f" total hypotheses proposed : {len(report.final_hypotheses)}") print(f" verified (protocol-consistent + statistically supported): " f"{len(report.verified_hypotheses)}") for vr in report.verified_hypotheses: diff --git a/examples/m1_m5/vlm_benchmark_common.py b/examples/m1_m5/vlm_benchmark_common.py index fe4cd208..a46b53d8 100644 --- a/examples/m1_m5/vlm_benchmark_common.py +++ b/examples/m1_m5/vlm_benchmark_common.py @@ -186,6 +186,7 @@ def main(config: BenchmarkConfig) -> None: ExperimentProtocol, FixAgent, HypothesisTester, + ModelKind, ProbeAgent, RunContext, StatsAnalysisAgent, @@ -280,7 +281,7 @@ def main(config: BenchmarkConfig) -> None: "coverage_verification_gap", ] probe_agent = ProbeAgent( - probe=StrategyProbe(priority_override={key: pinned for key in ("vlm", "agent", "llm")}), + probe=StrategyProbe(priority_override={kind: pinned for kind in ModelKind}), judge=None, max_analyzers=len(pinned), ) diff --git a/examples/m2_m3/deco_hallu_explore/Dockerfile b/examples/m2_m3/deco_hallu_explore/Dockerfile index 70bf135d..89160ffe 100644 --- a/examples/m2_m3/deco_hallu_explore/Dockerfile +++ b/examples/m2_m3/deco_hallu_explore/Dockerfile @@ -1,9 +1,19 @@ +# The report renderer is built from source: web_dist/ is gitignored, so a +# fresh clone has none and the explore step's report.html needs it. +FROM node:22-slim AS web +WORKDIR /src/evalrx/reporting/web +COPY evalrx/reporting/web/package.json evalrx/reporting/web/package-lock.json ./ +RUN npm ci +COPY evalrx/reporting/web/ ./ +RUN npm run build + FROM python:3.11-slim WORKDIR /app COPY . /evalrx -RUN pip install --no-cache-dir "/evalrx[dashboard,viz]" +COPY --from=web /src/evalrx/reporting/web_dist /evalrx/evalrx/reporting/web_dist +RUN pip install --no-cache-dir "/evalrx[viz]" WORKDIR /app/example COPY examples/m2_m3/deco_hallu_explore/ . diff --git a/examples/m2_m3/deco_hallu_explore/README.md b/examples/m2_m3/deco_hallu_explore/README.md index a5e91562..244229f6 100644 --- a/examples/m2_m3/deco_hallu_explore/README.md +++ b/examples/m2_m3/deco_hallu_explore/README.md @@ -22,7 +22,7 @@ cd examples/m2_m3/deco_hallu_explore && docker compose up Or directly (needs a local coding-agent CLI, e.g. `claude`): ```bash -pip install -e ".[dashboard,viz]" +pip install -e ".[viz]" bash run.sh ``` @@ -52,7 +52,9 @@ M3 hypotheses proposed from these findings (not validated): affirmative answers) between checkpoints, rather than a genuine capability regression with scale. -Open the dashboard to see the charts and hypothesis cards: +Open the report to see the charts and hypothesis cards: `outputs/report.html` +opens straight from disk, and `evalrx serve` (needs the `ui` extra, +`pip install -e ".[ui]"`) shows it live: ```bash evalrx serve outputs @@ -100,7 +102,7 @@ full propose → held-out-test → repair arc, ending in one five-tab web report **Prerequisites** -- `pip install -e ".[dashboard,viz,stats]"` (`stats` powers the +- `pip install -e ".[viz,stats]"` (`stats` powers the outcome-driver-analysis skill's regression path); - a local `claude` CLI on PATH (phase 1 explorer, phase 2 judge, phase 3 codegen all run through it); diff --git a/examples/m2_m3/deco_hallu_explore/run_surgery.py b/examples/m2_m3/deco_hallu_explore/run_surgery.py index 3707008d..6cb24c2c 100644 --- a/examples/m2_m3/deco_hallu_explore/run_surgery.py +++ b/examples/m2_m3/deco_hallu_explore/run_surgery.py @@ -63,10 +63,10 @@ def _lean_fix(event: dict) -> dict: def _fix_event_from_logs(run_dir: Path) -> dict | None: - from evalrx.reporting.run_events import read_v2_events + from evalrx.reporting.run_events import read_run_events event = None - for o in read_v2_events(run_dir): + for o in read_run_events(run_dir): if o.get("event") == "fix": event = o # keep the last fix event return event @@ -161,7 +161,7 @@ def main() -> None: SurgeryAgent, VLDiagnoseLoop, ) - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.models.backends.base import RuntimeConfig judge = loop_run.build_judge(loop_run.CFG.get("judge_model", "claude-opus-4-8"), @@ -172,7 +172,7 @@ def main() -> None: Capability.ATTENTION}) codegen: CliAgentConfig = loop_run.build_codegen(args.backend) - run_logger = RunLoggerV2(run_dir=root / "3_surgery" / "logs", verbose=True) + run_logger = RunLogger(run_dir=root / "3_surgery" / "logs", verbose=True) loop = VLDiagnoseLoop( model=model, protocol=loop_run.build_protocol(), diff --git a/examples/m2_m3/synthetic_yield_explore/Dockerfile b/examples/m2_m3/synthetic_yield_explore/Dockerfile index 0623f45c..1e68a79b 100644 --- a/examples/m2_m3/synthetic_yield_explore/Dockerfile +++ b/examples/m2_m3/synthetic_yield_explore/Dockerfile @@ -1,9 +1,19 @@ +# The report renderer is built from source: web_dist/ is gitignored, so a +# fresh clone has none and the explore step's report.html needs it. +FROM node:22-slim AS web +WORKDIR /src/evalrx/reporting/web +COPY evalrx/reporting/web/package.json evalrx/reporting/web/package-lock.json ./ +RUN npm ci +COPY evalrx/reporting/web/ ./ +RUN npm run build + FROM python:3.11-slim WORKDIR /app COPY . /evalrx -RUN pip install --no-cache-dir "/evalrx[dashboard,viz]" +COPY --from=web /src/evalrx/reporting/web_dist /evalrx/evalrx/reporting/web_dist +RUN pip install --no-cache-dir "/evalrx[viz]" WORKDIR /app/example COPY examples/m2_m3/synthetic_yield_explore/ . diff --git a/examples/m2_m3/synthetic_yield_explore/README.md b/examples/m2_m3/synthetic_yield_explore/README.md index 442752ca..494e0ab1 100644 --- a/examples/m2_m3/synthetic_yield_explore/README.md +++ b/examples/m2_m3/synthetic_yield_explore/README.md @@ -15,12 +15,13 @@ cd examples/m2_m3/synthetic_yield_explore && docker compose up Or directly (needs a local coding-agent CLI, e.g. `claude`): ```bash -pip install -e ".[dashboard,viz]" +pip install -e ".[viz]" bash run.sh ``` Env overrides: `CODER_PROVIDER` (default `claude_code`), `CODER_MODEL`, -`OUT_DIR` (default `outputs`), `TIMEOUT_SEC`. +`OUT_DIR` (default `outputs`), `TIMEOUT_SEC` (default 900: with its skills the +agent took longer than 300 s to write the analysis on 2026-11-20). ## What it demonstrates @@ -47,7 +48,9 @@ From an actual run (temperature r=0.86 with yield, the strongest association): mass-transfer/gas-solubility limited across the operating window tested — pressure's true effect, if any, lies outside the range sampled. -Open the dashboard to see the charts and hypothesis cards: +Open the report to see the charts and hypothesis cards: `outputs/report.html` +opens straight from disk, and `evalrx serve` (needs the `ui` extra, +`pip install -e ".[ui]"`) shows it live: ```bash evalrx serve outputs diff --git a/examples/m2_m3/synthetic_yield_explore/run.sh b/examples/m2_m3/synthetic_yield_explore/run.sh index 48d4190e..8657e25f 100755 --- a/examples/m2_m3/synthetic_yield_explore/run.sh +++ b/examples/m2_m3/synthetic_yield_explore/run.sh @@ -17,7 +17,7 @@ cmd=( --outcome-col yield_pct --out "$OUT_DIR" -q "What predicts yield_pct? Explore how temperature, pressure, and catalyst each relate to yield, how they relate to each other, and produce a variety of chart types." - --timeout-sec "${TIMEOUT_SEC:-300}" + --timeout-sec "${TIMEOUT_SEC:-900}" ) if [[ -n "$CODER_MODEL" ]]; then diff --git a/examples/m2_m3/vtcbench_diagnosis/Dockerfile b/examples/m2_m3/vtcbench_diagnosis/Dockerfile index e9b77fd6..db0fed78 100644 --- a/examples/m2_m3/vtcbench_diagnosis/Dockerfile +++ b/examples/m2_m3/vtcbench_diagnosis/Dockerfile @@ -1,3 +1,12 @@ +# The report renderer is built from source: web_dist/ is gitignored, so a +# fresh clone has none and the explore step's report.html needs it. +FROM node:22-slim AS web +WORKDIR /src/evalrx/reporting/web +COPY evalrx/reporting/web/package.json evalrx/reporting/web/package-lock.json ./ +RUN npm ci +COPY evalrx/reporting/web/ ./ +RUN npm run build + FROM python:3.11-slim WORKDIR /app @@ -7,6 +16,7 @@ RUN pip install --no-cache-dir \ torch torchvision --index-url https://download.pytorch.org/whl/cu124 COPY . /evalrx +COPY --from=web /src/evalrx/reporting/web_dist /evalrx/evalrx/reporting/web_dist RUN pip install --no-cache-dir "/evalrx[local]" WORKDIR /app/example diff --git a/examples/paper_diagnosis_benchmark/Dockerfile b/examples/paper_diagnosis_benchmark/Dockerfile index 6441d9f2..43094e1a 100644 --- a/examples/paper_diagnosis_benchmark/Dockerfile +++ b/examples/paper_diagnosis_benchmark/Dockerfile @@ -3,7 +3,7 @@ FROM python:3.11-slim WORKDIR /app COPY . /evalrx -RUN pip install --no-cache-dir "/evalrx[dashboard,data]" +RUN pip install --no-cache-dir "/evalrx[data]" WORKDIR /app/example COPY examples/paper_diagnosis_benchmark/ . diff --git a/pyproject.toml b/pyproject.toml index 9acd520b..8aa0960e 100755 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,22 +8,26 @@ dynamic = ["version"] description = "Failure case analysis in the era of LLM." readme = "README.md" license = { file = "LICENSE" } -requires-python = ">=3.10" +requires-python = ">=3.11" keywords = ["llm", "vlm", "interpretability", "failure-analysis", "explainability"] classifiers = [ "Development Status :: 3 - Alpha", "Intended Audience :: Science/Research", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Topic :: Scientific/Engineering :: Artificial Intelligence", ] # Light core: pure-API failure analysis installs WITHOUT torch. # White-box / local inference lives in the [local] extra; see below. +# pydantic-ai runs every typed judge call (evalrx.agent_runtime.judge_call): +# schema-validated output, validation errors sent back to the judge, a typed +# error when the retry budget runs out. It needs Python 3.11. dependencies = [ "pyyaml>=6.0", "numpy>=1.24", + "pydantic>=2.12", + "pydantic-ai-slim>=2.71,<3", ] [project.optional-dependencies] @@ -131,8 +135,8 @@ dev = [ "pytest>=8.0", "pytest-cov>=4.0", "ruff>=0.4", - "mypy>=1.8", - # Validate run_log.jsonl against the published schema (log_schema.py). + "mypy>=1.19", + # Validate run log events against the published schema (log_schema.py). "jsonschema>=4.0", ] @@ -155,7 +159,7 @@ where = ["."] include = ["evalrx*"] [tool.setuptools.package-data] -# Ship the published run_log.jsonl JSON Schema so non-Python consumers can +# Ship the published run log JSON Schema so non-Python consumers can # validate the log without installing evalrx. "evalrx.eval_agent" = ["run_log.schema.json"] # Ship bundled Agent Skills (e.g. nature-figure) so `pip install` carries them @@ -174,7 +178,7 @@ markers = [ [tool.ruff] line-length = 100 -target-version = "py310" +target-version = "py311" exclude = ["examples/"] [tool.ruff.lint] @@ -182,5 +186,5 @@ select = ["E", "F", "I"] ignore = ["E501"] [tool.mypy] -python_version = "3.10" +python_version = "3.11" ignore_missing_imports = true diff --git a/tests/integration/test_audio_processor.py b/tests/integration/test_audio_processor.py index 72665517..fc227fc1 100644 --- a/tests/integration/test_audio_processor.py +++ b/tests/integration/test_audio_processor.py @@ -19,11 +19,8 @@ import numpy as np import pytest -from evalrx.models.backends.hf.model import ( - AUDIO_SAMPLE_RATE, - _check_audio_duration, - _resolve_audio, -) +from evalrx.models._media import resolve_audio as _resolve_audio +from evalrx.models.backends.hf.model import AUDIO_SAMPLE_RATE, _check_audio_duration pytestmark = pytest.mark.network diff --git a/tests/judge_replies.py b/tests/judge_replies.py new file mode 100644 index 00000000..87bb2189 --- /dev/null +++ b/tests/judge_replies.py @@ -0,0 +1,40 @@ +"""JSON replies a scripted judge gives to M3's typed proposal and review calls.""" + +from __future__ import annotations + +import json +from typing import Any + + +def hypothesis( + statement: str, + failure_mode: str, + *, + plain: str = "The model gets these cases wrong for the reason stated.", + test: str = "", + expected: str | None = None, +) -> dict[str, Any]: + """One entry of a :class:`~evalrx.eval_agent.stages.diagnosis.Proposal`.""" + entry: dict[str, Any] = { + "hypothesis": statement, "plain_statement": plain, "failure_mode": failure_mode, + "test": test, + } + if expected is not None: + entry["expected_association"] = expected + return entry + + +def proposal(*hypotheses: dict[str, Any]) -> str: + """The proposer's reply; no hypotheses means "no problem found".""" + return json.dumps({"hypotheses": list(hypotheses)}) + + +def review(*decisions: tuple[int, str, str]) -> str: + """The critic's reply: ``(number, "keep" | "reject", reason)`` per hypothesis.""" + return json.dumps({"decisions": [ + {"number": n, "decision": d, "reason": r} for n, d, r in decisions + ]}) + + +def keep_all(n: int, reason: str = "evidence directly supports this claim") -> str: + return review(*((i, "keep", reason) for i in range(1, n + 1))) diff --git a/tests/test_analysis/test_case_partitions.py b/tests/test_analysis/test_case_partitions.py index c63cdd9b..085eab26 100644 --- a/tests/test_analysis/test_case_partitions.py +++ b/tests/test_analysis/test_case_partitions.py @@ -9,7 +9,7 @@ from __future__ import annotations from evalrx.core import CaseBatch, FailureCase, Label -from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 +from evalrx.eval_agent.run_logger import RunLogger from evalrx.reporting.dynamic import build_report_data @@ -21,7 +21,7 @@ def _case(i: int) -> FailureCase: def _write_run(root, *, n_explore: int, batches) -> None: - logger = RunLoggerV2(root) + logger = RunLogger(root) logger.log_run_start({"model": "m", "benchmark_name": "b", "n_cases": n_explore}) for cases, split in batches: logger.log_cases(CaseBatch(cases), split=split) @@ -47,7 +47,6 @@ def test_tagged_records_are_read_as_recorded(tmp_path): assert [(r["code"], r["label"], r["n"]) for r in rows] == [ ("E", "Explore", 3), ("H", "Held-out", 2), ("C", "Confirm", 1), ] - assert not any(r["inferred"] for r in rows) # The sheet's headline counts come from the same table, not from the # length of the case-record list (which holds every partition). headline = data["case_study"]["headline"] if data.get("case_study") else None @@ -55,24 +54,6 @@ def test_tagged_records_are_read_as_recorded(tmp_path): assert (headline["n_explore"], headline["n_heldout"]) == (3, 3) -def test_an_untagged_two_way_run_is_inferred_from_the_record_order(tmp_path): - # Logged the way run() logs: explore first, then the withheld pool, with - # run_start counting only the explore partition. - _write_run(tmp_path, n_explore=2, batches=[ - ([_case(0), _case(1)], None), - ([_case(2), _case(3), _case(4)], None), - ]) - data = build_report_data(tmp_path) - assert _by_split(data) == {"explore": ["c0", "c1"], "confirm": ["c2", "c3", "c4"]} - rows = data["setting"]["partitions"] - # One withheld pool served as both the held-out and the confirm set, and it - # is named for both: the batch figure draws this row once, so a label of - # just "Held-out" would leave the confirm set with no size anywhere. - assert [(r["code"], r["label"], r["n"], r["inferred"]) for r in rows] == [ - ("E", "Explore", 2, True), ("H/C", "Held-out / Confirm", 3, True), - ] - - def test_a_run_without_a_split_shows_no_partitions(tmp_path): _write_run(tmp_path, n_explore=3, batches=[([_case(0), _case(1), _case(2)], None)]) data = build_report_data(tmp_path) diff --git a/tests/test_analysis/test_case_study_sheet.py b/tests/test_analysis/test_case_study_sheet.py index 31631785..91fbc189 100644 --- a/tests/test_analysis/test_case_study_sheet.py +++ b/tests/test_analysis/test_case_study_sheet.py @@ -34,7 +34,7 @@ def _write(path: Path, payload) -> None: def make_run(root: Path, *, n_broken: int = 1, verdict_status: str = "supported") -> Path: - """A run directory in the RunLoggerV2 shape RunContext + the benchmark + """A run directory in the RunLogger shape RunContext + the benchmark runner produce: run.json (run-wide events + manifest) plus one JSON document per stage under M1..M5.""" logs = root / "logs" @@ -81,7 +81,7 @@ def make_run(root: Path, *, n_broken: int = 1, verdict_status: str = "supported" {"cycle": 0, "selected_analyzers": ["coverage_verification_gap", "logprob_entropy"], # entry["findings"][analyzer] and entry["results"][analyzer]["findings"] - # are the SAME object in a real RunLoggerV2 probe entry (both derive + # are the SAME object in a real RunLogger probe entry (both derive # from Result.findings) — populate both so every real reader finds it. "findings": {"coverage_verification_gap": {"per_case": per_case}}, "results": {"coverage_verification_gap": {"findings": {"per_case": per_case}}}}, @@ -119,13 +119,27 @@ def make_run(root: Path, *, n_broken: int = 1, verdict_status: str = "supported" "payload": {"name": "self_consistency_5", "strategy": "direct", "n_samples": 5, "generation_kwargs": {"temperature": 0.7}, "prompt_template": "{prompt}"}}}, ]}) + _number_events(logs) return root +def _number_events(logs: Path) -> None: + """Give every record the global sequence number the logger stamps.""" + seq = 0 + for path in [logs / "run.json", *(logs / f"M{n}" / "log.json" for n in range(1, 6))]: + doc = json.loads(path.read_text(encoding="utf-8")) + for bucket in doc.values(): + for row in bucket if isinstance(bucket, list) else [bucket]: + if isinstance(row, dict) and "config" not in row: # not the manifest + seq += 1 + row["event_seq"] = seq + _write(path, doc) + + def _events(root: Path) -> list[dict]: - from evalrx.reporting.run_events import read_v2_events + from evalrx.reporting.run_events import read_run_events - return read_v2_events(root) + return read_run_events(root) @pytest.fixture diff --git a/tests/test_analysis/test_cli.py b/tests/test_analysis/test_cli.py index 85abd358..37a46863 100755 --- a/tests/test_analysis/test_cli.py +++ b/tests/test_analysis/test_cli.py @@ -68,19 +68,17 @@ def test_top_level_serve_help(capsys): def test_top_level_serve_dispatch(monkeypatch): - import evalrx.cli as cli_mod + import evalrx.reporting.server as server_mod captured = {} - def _fake_serve(run_dir, *, port, no_audio, open_browser, block=True, runs_root=None): - captured.update(run_dir=run_dir, port=port, no_audio=no_audio, - open_browser=open_browser, block=block, runs_root=runs_root) + def _fake_serve(run_dir, *, port, open_browser, runs_root=None): + captured.update(run_dir=run_dir, port=port, open_browser=open_browser, runs_root=runs_root) return 0 - monkeypatch.setattr(cli_mod, "serve_report", _fake_serve) - assert main(["serve", "my_run", "--port", "8500", "--no-audio", "--no-browser"]) == 0 - assert captured == {"run_dir": "my_run", "port": 8500, "no_audio": True, - "open_browser": False, "block": True, "runs_root": None} + monkeypatch.setattr(server_mod, "serve_dynamic_report", _fake_serve) + assert main(["serve", "my_run", "--port", "8500", "--no-browser"]) == 0 + assert captured == {"run_dir": "my_run", "port": 8500, "open_browser": False, "runs_root": None} def test_langfuse_report_source_materializes_a_cache(monkeypatch, tmp_path): @@ -155,3 +153,160 @@ def test_chat_repl_is_retired(): from evalrx.analysis import cli assert not hasattr(cli, "chat_main") + + +# --- every command reaches the function behind it --------------------------- + +def test_run_dispatches_to_the_benchmark_runner(monkeypatch): + import evalrx.benchmark.run as run_mod + + seen = [] + monkeypatch.setattr(run_mod, "run_args", lambda args: seen.append(args.command) or 3) + monkeypatch.setattr(run_mod, "build_parser", lambda parser=None: parser) + + assert main(["run"]) == 3 + assert seen == ["run"] + + +def test_explore_without_a_path_is_a_usage_error(capsys): + with pytest.raises(SystemExit) as exc: + main(["explore"]) + assert exc.value.code == 2 + assert "evalrx explore requires a results path" in capsys.readouterr().err + + +@pytest.mark.parametrize("code, status", [(0, "completed"), (1, "failed")]) +def test_explore_progress_path_brackets_the_run_with_job_events(monkeypatch, tmp_path, code, status): + import json + + import evalrx.cli as cli_mod + + captured = {} + monkeypatch.setattr(cli_mod, "run_explore", lambda path, **kwargs: captured.update(kwargs) or code) + progress = tmp_path / "progress.jsonl" + + assert main(["explore", "data", "--progress-path", str(progress), "--thread-id", "t1"]) == code + events = [json.loads(line) for line in progress.read_text().splitlines()] + assert [(e["stage"], e["status"], e["thread_id"], e["turn_id"]) for e in events] == [ + ("job", "started", "t1", "explore"), ("job", status, "t1", "explore")] + assert captured["progress_sink"] is not None + + +def test_explore_no_narrate_without_progress_path_passes_no_sink(monkeypatch): + import evalrx.cli as cli_mod + + captured = {} + monkeypatch.setattr(cli_mod, "run_explore", lambda path, **kwargs: captured.update(kwargs) or 0) + + assert main(["explore", "data", "--no-narrate"]) == 0 + assert captured["progress_sink"] is None + + +def test_run_codebase_dispatch(monkeypatch): + import evalrx.cli as cli_mod + from evalrx.analysis.explorer import RECORDS_FILENAME + from evalrx.analysis.narration import TerminalNarrator + + calls = [] + monkeypatch.setattr(cli_mod, "run_codebase_cli", lambda path, **kwargs: calls.append((path, kwargs)) or 0) + + assert main(["run-codebase", "repo"]) == 0 + assert main(["run-codebase", "repo", "--no-explore", "--no-narrate", "--records-name", "r.jsonl", + "--serve-report", "--model", "m", "-q", "why"]) == 0 + (path, default), (_, custom) = calls + sink = default.pop("progress_sink") + assert path == "repo" and isinstance(sink, TerminalNarrator) + assert default == { + "out": "evalrx_run_codebase_output", "coder_provider": "claude_code", "coder_model": "", + "coder_binary": "", "outcome_col": None, "records_name": RECORDS_FILENAME, "timeout_sec": 1200, + "max_attempts": 2, "question": "Explore this dataset and surface the patterns that matter.", + "analyze": True, "open_report": False} + assert (custom["analyze"], custom["progress_sink"], custom["records_name"], custom["open_report"], + custom["coder_model"], custom["question"]) == (False, None, "r.jsonl", True, "m", "why") + + +def test_serve_reports_a_missing_ui_extra_as_a_usage_error(monkeypatch, capsys): + import evalrx.reporting.server as server_mod + + def _no_ui(*args, **kwargs): + raise ImportError("install evalrx[ui]") + + monkeypatch.setattr(server_mod, "serve_dynamic_report", _no_ui) + with pytest.raises(SystemExit) as exc: + main(["serve", "out"]) + assert exc.value.code == 2 + assert "install evalrx[ui]" in capsys.readouterr().err + + +@pytest.mark.parametrize("command", ["serve", "report", "publish-report"]) +def test_langfuse_source_without_a_trace_id_is_a_usage_error(command, capsys): + with pytest.raises(SystemExit) as exc: + main([command, "out", "--source", "langfuse"]) + assert exc.value.code == 2 + assert "--trace-id is required with --source langfuse" in capsys.readouterr().err + + +def test_publish_report_prints_what_it_wrote(monkeypatch, capsys): + from types import SimpleNamespace + + import evalrx.reporting.dynamic as dynamic_mod + + seen = {} + + def _publish(source_dir): + seen.update(source_dir=source_dir) + return SimpleNamespace(data_path="d.json", spec_path="s.json", generated_by="deterministic") + + monkeypatch.setattr(dynamic_mod, "publish_report", _publish) + + assert main(["publish-report", "out"]) == 0 + assert seen == {"source_dir": "out"} + assert capsys.readouterr().out.splitlines() == [ + "Published report data: d.json", "Published report layout: s.json (deterministic)"] + + +def test_publish_report_failure_is_a_usage_error(monkeypatch, capsys): + import evalrx.reporting.dynamic as dynamic_mod + + def _missing(source_dir): + raise LookupError("no run found") + + monkeypatch.setattr(dynamic_mod, "publish_report", _missing) + with pytest.raises(SystemExit) as exc: + main(["publish-report", "out"]) + assert exc.value.code == 2 + assert "no run found" in capsys.readouterr().err + + +def test_export_langfuse_writes_beside_the_run_or_syncs(monkeypatch): + from pathlib import Path + + import evalrx.observability as exporter_mod + + written = [] + synced = [] + monkeypatch.setattr(exporter_mod, "export_to_langfuse_bundle", lambda run_dir, out: written.append((run_dir, out))) + monkeypatch.setattr(exporter_mod, "sync_to_langfuse_live", lambda run_dir: synced.append(run_dir) or run_dir == "ok") + + assert main(["export-langfuse", "out"]) == 0 + assert main(["export-langfuse", "out", "-o", "t.json"]) == 0 + assert written == [("out", Path("out") / "langfuse_trace.json"), ("out", "t.json")] + assert main(["export-langfuse", "ok", "--sync"]) == 0 + assert main(["export-langfuse", "down", "--sync"]) == 1 + assert synced == ["ok", "down"] and len(written) == 2 + + +def test_backfill_langfuse_prints_a_summary(monkeypatch, capsys): + import evalrx.observability as observability_mod + + seen = {} + + def _backfill(run_dir, dry_run=False): + seen.update(run_dir=run_dir, dry_run=dry_run) + return {"trace_id": "t", "events": 3, "published": 1, "pending": 2} + + monkeypatch.setattr(observability_mod, "backfill_run_to_langfuse", _backfill) + + assert main(["backfill-langfuse", "out", "--dry-run"]) == 0 + assert seen == {"run_dir": "out", "dry_run": True} + assert capsys.readouterr().out.strip() == "Langfuse backfill: trace=t events=3 published=1 pending=2" diff --git a/tests/test_analysis/test_dynamic_report.py b/tests/test_analysis/test_dynamic_report.py index 23dde161..30f3b24b 100644 --- a/tests/test_analysis/test_dynamic_report.py +++ b/tests/test_analysis/test_dynamic_report.py @@ -6,10 +6,10 @@ def test_publish_report_contract_and_case_records(tmp_path): from evalrx.core import CaseBatch, FailureCase, Label - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.reporting.dynamic import load_published_report, publish_report - logger = RunLoggerV2(tmp_path) + logger = RunLogger(tmp_path) logger.log_run_start({ "model": "demo-model", "benchmark_name": "demo-set", "n_cases": 1, "label_distribution": {"fail": 1}, @@ -39,10 +39,10 @@ def test_report_agent_repairs_once_then_validates(): valid = { "root": "page", "elements": { - "page": {"type": "ReportPage", "props": {}, "children": ["hero", "journey", "outcome"]}, + "page": {"type": "ReportPage", "props": {}, "children": ["hero", "journey", "findings"]}, "hero": {"type": "SettingHero", "props": {}}, "journey": {"type": "Journey", "props": {}}, - "outcome": {"type": "OutcomeCard", "props": {}}, + "findings": {"type": "FindingGrid", "props": {}}, }, } @@ -61,10 +61,10 @@ def generate(self, _prompt): def test_invalid_agent_output_falls_back(tmp_path): - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.reporting.dynamic import load_published_report, publish_report - logger = RunLoggerV2(tmp_path) + logger = RunLogger(tmp_path) logger.log_run_start({"model": "demo", "n_cases": 0}) logger.close() @@ -83,11 +83,11 @@ def test_dynamic_api_filters_and_serves_spa(tmp_path): from fastapi.testclient import TestClient from evalrx.core import CaseBatch, FailureCase, Label - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.reporting.dynamic import publish_report from evalrx.reporting.server import create_app - logger = RunLoggerV2(tmp_path) + logger = RunLogger(tmp_path) logger.log_run_start({"model": "demo", "n_cases": 2}) logger.log_cases(CaseBatch([ FailureCase.from_prompt("alpha", id="a", label=Label.FAIL), @@ -109,7 +109,7 @@ def test_runs_panel_lists_and_opens_sibling_experiments(tmp_path): from fastapi.testclient import TestClient from evalrx.core import CaseBatch, FailureCase, Label - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.reporting.dynamic import publish_report from evalrx.reporting.server import create_app @@ -118,7 +118,7 @@ def test_runs_panel_lists_and_opens_sibling_experiments(tmp_path): run_a = tmp_path / "exp_a" / "outputs" / "logs" run_b = tmp_path / "exp_b" / "outputs" / "logs" for run, model in ((run_a, "model-a"), (run_b, "model-b")): - logger = RunLoggerV2(run) + logger = RunLogger(run) logger.log_run_start({"model": model, "benchmark_name": "demo", "n_cases": 1}) logger.log_cases(CaseBatch([FailureCase.from_prompt("q", id="c1", label=Label.FAIL)])) # discover_runs' marker is run.json + at least one M/log.json. @@ -166,11 +166,11 @@ def test_an_uploaded_run_gets_its_own_id_and_an_empty_server_names_no_run(tmp_pa from fastapi.testclient import TestClient from evalrx.core import CaseBatch, FailureCase, Label - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.reporting.server import create_app run = tmp_path / "shared" / "logs" - logger = RunLoggerV2(run) + logger = RunLogger(run) logger.log_run_start({"model": "uploaded-model", "n_cases": 1}) logger.log_cases(CaseBatch([FailureCase.from_prompt("q", id="c1", label=Label.FAIL)])) logger.log_stage_skipped("M1", "no_signal") @@ -210,7 +210,7 @@ def test_runs_listing_keeps_the_most_recent_past_the_display_limit(tmp_path, mon from fastapi.testclient import TestClient from evalrx.core import CaseBatch, FailureCase, Label - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.reporting import server as server_mod monkeypatch.setattr(server_mod, "RUNS_DISPLAY_LIMIT", 2) @@ -218,13 +218,13 @@ def test_runs_listing_keeps_the_most_recent_past_the_display_limit(tmp_path, mon runs = [] for i, stamp in enumerate(stamps): run = tmp_path / f"exp_{i}" / "outputs" / "logs" - logger = RunLoggerV2(run) + logger = RunLogger(run) logger.log_cases(CaseBatch([FailureCase.from_prompt("q", id="c1", label=Label.FAIL)])) # discover_runs' marker is run.json + at least one M/log.json. logger.log_stage_skipped("M1", "no_signal") logger.close() # _run_mtime takes the max mtime across run.json and every M/log.json - # (RunLoggerV2 flushes an empty doc for every stage at close(), not + # (RunLogger flushes an empty doc for every stage at close(), not # just the one actually used) — stamp every file, or an untouched # stage's real write time wins regardless. for f in run.rglob("*"): @@ -242,11 +242,11 @@ def test_runs_listing_keeps_the_most_recent_past_the_display_limit(tmp_path, mon def test_runs_discovery_does_not_descend_into_a_found_runs_data_dir(tmp_path): from evalrx.core import CaseBatch, FailureCase, Label - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.reporting.server import discover_runs run = tmp_path / "exp" / "outputs" / "logs" - logger = RunLoggerV2(run) + logger = RunLogger(run) logger.log_cases(CaseBatch([FailureCase.from_prompt("q", id="c1", label=Label.FAIL)])) logger.log_stage_skipped("M1", "no_signal") logger.close() @@ -263,46 +263,97 @@ def test_runs_discovery_does_not_descend_into_a_found_runs_data_dir(tmp_path): def test_external_case_media_is_copied_into_durable_run(tmp_path): from evalrx.core import CaseBatch, FailureCase, Inputs - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 - from evalrx.reporting.run_events import read_v2_events + from evalrx.eval_agent.run_logger import RunLogger + from evalrx.reporting.run_events import read_run_events media = tmp_path / "source.wav" media.write_bytes(b"RIFF-fake-audio") run = tmp_path / "run" - logger = RunLoggerV2(run) + logger = RunLogger(run) logger.log_cases(CaseBatch([ FailureCase(inputs=Inputs(prompt="listen", audio=str(media)), id="audio-1"), ])) logger.close() - events = [e for e in read_v2_events(run) if e.get("event") == "case_record"] + events = [e for e in read_run_events(run) if e.get("event") == "case_record"] path = run / events[0]["media_paths"][0] assert path.parent == run / "media" assert path.read_bytes() == b"RIFF-fake-audio" -def test_unparsed_m3_response_is_recovered_for_audit_only(): - from evalrx.reporting.dynamic import _recover_unparsed_hypotheses +def _report_of_cases(tmp_path, cases): + from evalrx.core import CaseBatch + from evalrx.eval_agent.run_logger import RunLogger + from evalrx.reporting.dynamic import build_report_data + + run = tmp_path / "run" + logger = RunLogger(run) + logger.log_run_start({"model": "demo", "n_cases": len(cases)}) + logger.log_cases(CaseBatch(cases)) + logger.close() + return build_report_data(run) + + +def test_each_media_slot_is_paired_with_its_own_copy(tmp_path): + from evalrx.core import FailureCase, Inputs + + image = tmp_path / "scene.png" + image.write_bytes(b"fake-png") + audio = tmp_path / "clip.wav" + audio.write_bytes(b"RIFF-fake-audio") + data = _report_of_cases(tmp_path, [ + FailureCase(inputs=Inputs(prompt="both", image=str(image), audio=str(audio)), id="both"), + ]) - response = """HYPOTHESIS: Formatting causes the failure. -PLAIN_STATEMENT: The answer changes when formatting changes. -FAILURE_MODE: brittleness -TEST: flip_rate HIGHER on failing cases -EXPECTED_ASSOCIATION: higher_on_failures""" - proposals = _recover_unparsed_hypotheses(response) - assert proposals[0]["statement"] == "Formatting causes the failure." - assert proposals[0]["accepted_by_pipeline"] is False + by_kind = {item["kind"]: item["path"] for item in data["media"]} + assert by_kind["image"].startswith("media/") and by_kind["image"].endswith("_scene.png") + assert by_kind["audio"].startswith("media/") and by_kind["audio"].endswith("_clip.wav") + assert len(data["cases"][0]["media_ids"]) == 2 + + +def test_a_slot_the_logger_could_not_copy_does_not_take_another_slots_copy(tmp_path): + from evalrx.core import FailureCase, Inputs + + audio = tmp_path / "clip.wav" + audio.write_bytes(b"RIFF-fake-audio") + missing = str(tmp_path / "gone.png") + data = _report_of_cases(tmp_path, [ + FailureCase(inputs=Inputs(prompt="one", image=missing, audio=str(audio)), id="one"), + ]) + + by_kind = {item["kind"]: item["path"] for item in data["media"]} + assert by_kind["image"] == missing + assert by_kind["audio"].endswith("_clip.wav") + + +def test_case_choices_and_task_come_from_the_case_metadata(tmp_path): + from evalrx.core import FailureCase + + data = _report_of_cases(tmp_path, [ + FailureCase.from_prompt("mc", id="mc", metadata={ + "task": "multiple_choice_letter", "category": "Reasoning", + "choices": ["A", "B"], "options": ["(A) cat", "(B) dog"], + }), + FailureCase.from_prompt("numeric", id="numeric", metadata={"task": "exact_or_numeric"}), + FailureCase.from_prompt("bare", id="bare"), + ]) + + cases = {case["id"]: case for case in data["cases"]} + assert cases["mc"]["choices"] == ["(A) cat", "(B) dog"] + assert cases["mc"]["task"] == "Reasoning" + assert cases["numeric"]["choices"] == [] and cases["numeric"]["task"] == "exact_or_numeric" + assert cases["bare"]["choices"] == [] and cases["bare"]["task"] == "" def test_m1_examples_are_logged_and_reconstructed_from_case_evidence(tmp_path): from evalrx.core import CaseBatch, FailureCase, Label, Result - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.reporting.dynamic import build_report_data case = FailureCase.from_prompt( "Choose the animal", id="case-1", expected="cat", observed="dog", label=Label.FAIL, ) - logger = RunLoggerV2(tmp_path) + logger = RunLogger(tmp_path) logger.log_run_start({"model": "demo", "n_cases": 1}) logger.log_cases(CaseBatch([case])) logger.log_probe(0, {"format_check": Result( @@ -318,38 +369,14 @@ def test_m1_examples_are_logged_and_reconstructed_from_case_evidence(tmp_path): assert example["check_result"]["answer flipped"] == 1 -def test_legacy_m4_example_is_labeled_as_an_aggregate_validation_test(): - from evalrx.reporting.dynamic import _m4_examples - - example = _m4_examples([{ - "hypothesis": "Formatting causes the failure.", "status": "refuted", - "effect_size": -0.5, "verdict": "The independent test refuted it.", - "evidence": {"chosen_tool": "signal_label_assoc", "ci": [-0.7, -0.2]}, - }], {}, []) - assert example[0]["kind"] == "validation_test" - assert "full validation set" in example[0]["plain_reading"] - - def test_report_uses_plain_language_for_internal_signal_names(): - from evalrx.reporting.dynamic import _plain_signal + from evalrx.reporting.plain_labels import _plain_signal label = _plain_signal("format_sensitivity.format_flip_rate") assert "answer order" in label.lower() assert "format_sensitivity" not in label -def test_indexed_media_can_be_served_from_the_adjacent_example_data_dir(tmp_path): - from evalrx.reporting.server import _resolve_indexed_media - - root = tmp_path / "example" / "outputs" / "logs" - root.mkdir(parents=True) - media = tmp_path / "example" / "data" / "clip.wav" - media.parent.mkdir() - media.write_bytes(b"RIFF-fake-audio") - - assert _resolve_indexed_media(root, str(media)) == media.resolve() - - def test_explicit_run_log_wins_over_a_nested_logs_subrun(tmp_path): from evalrx.reporting.server import _resolve_report_root @@ -362,10 +389,10 @@ def test_explicit_run_log_wins_over_a_nested_logs_subrun(tmp_path): def test_read_only_run_can_be_served_without_publishing(tmp_path, monkeypatch): from fastapi.testclient import TestClient - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.reporting.server import create_app - logger = RunLoggerV2(tmp_path) + logger = RunLogger(tmp_path) logger.log_run_start({"model": "read-only-demo", "n_cases": 0}) logger.close() monkeypatch.setattr("evalrx.reporting.server.report_is_current", lambda _root: False) @@ -380,50 +407,30 @@ def test_read_only_run_can_be_served_without_publishing(tmp_path, monkeypatch): assert payload["data"]["setting"]["model"] == "read-only-demo" -def test_a_pre_ref_run_still_numbers_its_repairs_the_emitters_way(): - """The AVLM run's stored payload predates `ref`, and must still be readable. +def test_case_media_is_served_from_the_copy_inside_the_run(tmp_path): + from fastapi.testclient import TestClient - Left to itself the frontend numbers each list from one, so the frozen - candidate is #1 on its card and whatever position it happened to occupy in - the sweep — two numbers, one repair, nothing on screen connecting them. - """ - from evalrx.reporting.dynamic import _backfill_repair_identity + from evalrx.core import CaseBatch, FailureCase, Inputs + from evalrx.eval_agent.run_logger import RunLogger + from evalrx.reporting.server import create_app - payload = { - "selection": [ - {"name": "visual_grounding", "tier": "L1"}, - {"name": "audio_evidence_then_answer", "tier": "L1"}, - {"name": "coded_pipeline", "tier": "L2"}, - ], - "attempted": [{"name": "coded_pipeline", "tier": "L2"}], - } - _backfill_repair_identity(payload) - - assert [r["ref"] for r in payload["selection"]] == ["R1", "R2", "R3"] - # Same repair, same number, in both lists. - assert [r["ref"] for r in payload["attempted"]] == ["R3"] - # The host authored two of these three and can say what they do. - assert payload["selection"][0]["headline"].startswith("Tells the model to read") - assert payload["selection"][2]["headline"].startswith("Runs a short program") - # The judge invented the middle one under a prompt that never asked for a - # description, so nothing is invented on its behalf now. - assert payload["selection"][1]["headline"] == "" - - -def test_backfill_never_overwrites_what_the_producer_wrote(): - from evalrx.reporting.dynamic import _backfill_repair_identity - - payload = { - "selection": [ - {"name": "coded_pipeline", "tier": "L2", "ref": "R9", - "headline": "Re-asks the model and takes the majority answer."}, - ], - "attempted": [], - } - _backfill_repair_identity(payload) + source = tmp_path / "data" / "clip.wav" + source.parent.mkdir() + source.write_bytes(b"RIFF-fake-audio") + run = tmp_path / "run" + logger = RunLogger(run) + logger.log_run_start({"model": "demo", "n_cases": 1}) + logger.log_cases(CaseBatch([ + FailureCase(inputs=Inputs(prompt="listen", audio=str(source)), id="audio-1"), + ])) + logger.close() + source.unlink() # the run is read where the producer's file is not - assert payload["selection"][0]["ref"] == "R9" - assert payload["selection"][0]["headline"].startswith("Re-asks the model") + with TestClient(create_app(run)) as client: + run_id = client.get("/api/session").json()["run"]["id"] + media = client.get(f"/api/runs/{run_id}/report").json()["data"]["media"] + response = client.get(f"/api/runs/{run_id}/media/{media[0]['id']}") + assert response.status_code == 200 and response.content == b"RIFF-fake-audio" def test_stage_figures_embed_everywhere_they_are_cited(tmp_path): @@ -452,19 +459,19 @@ def test_stage_figures_embed_everywhere_they_are_cited(tmp_path): def _v2_run_with_explore_snapshot(tmp_path, report: dict, figure_names: list[str]): - """A V2 run whose explore step left its workdir to be inlined on the event.""" + """A run whose explore step left its workdir to be inlined on the event.""" from types import SimpleNamespace - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger - # Not beside logs/: a sibling explore/ would be read as a V1 layout. + # Not beside logs/: the logger inlines it from the runtime tree. workdir = tmp_path / "sandbox" / "explore" (workdir / "figures").mkdir(parents=True) for name in figure_names: (workdir / "figures" / name).write_bytes(b"\x89PNG fake " + name.encode()) (workdir / "exploratory_report.json").write_text(json.dumps(report), encoding="utf-8") run_dir = tmp_path / "logs" - logger = RunLoggerV2(run_dir, observability_mode="offline") + logger = RunLogger(run_dir, observability_mode="offline") logger.log_run_start({"model": "demo-model", "benchmark_name": "demo-set", "n_cases": 1, "protocol": {}}) explorer_report = SimpleNamespace( ok=True, charts=[], observations=list(report.get("observations") or []), @@ -477,7 +484,7 @@ def _v2_run_with_explore_snapshot(tmp_path, report: dict, figure_names: list[str def test_v2_explore_snapshot_links_takeaways_to_the_charts_they_cite(tmp_path): - # RunLoggerV2 writes no explore/ directory: the explorer's report is inlined + # RunLogger writes no explore/ directory: the explorer's report is inlined # on the explore event and its figures are copied into M2/artifacts/ under # hashed names. The published M2 record used to be built from the event's # observation sentences (which cite nothing) over figures named by their @@ -542,11 +549,11 @@ def test_v2_explore_snapshot_links_takeaways_to_the_charts_they_cite(tmp_path): def test_v2_explore_event_without_a_snapshot_report_still_renders_its_sentences(tmp_path): # A run recorded before the snapshot carried the report (or one whose # report was over the inline cap) keeps the sentence-level fallback. - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.reporting.dynamic import build_report_data run_dir = tmp_path / "logs" - logger = RunLoggerV2(run_dir, observability_mode="offline") + logger = RunLogger(run_dir, observability_mode="offline") logger.log_run_start({"model": "demo-model", "benchmark_name": "demo-set", "n_cases": 1, "protocol": {}}) logger._append_stage("M2", "explore", { "cycle": 0, "ok": True, "observations": ["Every long reply failed; short ones were mixed."], @@ -564,7 +571,7 @@ def test_v2_explore_event_without_a_snapshot_report_still_renders_its_sentences( def test_cases_repaired_metric_reads_the_m5_confirmation(): - from evalrx.reporting.dynamic import _metrics + from evalrx.reporting.report_summary import _metrics run = {"n_cases": 128, "label_distribution": {"fail": 38}} raw = {"m4": {"results": [{}, {}, {}]}} @@ -589,14 +596,28 @@ def test_cases_repaired_metric_reads_the_m5_confirmation(): assert {m["id"]: m["value"] for m in _metrics(run, raw, [{"status": "fail"}], idle)}["fixed"] == 0 +def test_the_repair_list_reports_the_same_m5_result_as_the_header_tile(): + """The loop figure reads `repairs`; it said "0 fixed" beside a tile of 21.""" + from evalrx.reporting.report_summary import _cases_repaired, _repairs + + raw = {"m5_fix": {"ran": True, "fixed": False, "confirm": {}}} + unwon = {"ran": True, "fixed": False, "confirmation": {}, + "candidates": [{"name": "read_off_marks", "n_fixed": 21, "n_broken": 6, "effect": 0.117}]} + [repair] = _repairs(raw, unwon) + assert (repair["title"], repair["fixed_cases"], repair["broken_cases"]) == ("read_off_marks", 21, 6) + assert repair["effect"] == 0.117 + assert _cases_repaired([], unwon) == repair["fixed_cases"] + assert _repairs({"m5_fix": {"ran": False}}, unwon) == [] + + def test_m5_confirmation_joins_the_winning_candidate_the_logger_recorded(tmp_path): from types import SimpleNamespace from evalrx.core import CaseBatch, FailureCase, Label - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.reporting.dynamic import build_report_data - logger = RunLoggerV2(tmp_path, observability_mode="offline") + logger = RunLogger(tmp_path, observability_mode="offline") logger.log_run_start({ "model": "demo-model", "benchmark_name": "demo-set", "n_cases": 2, "label_distribution": {"fail": 2}, @@ -608,7 +629,7 @@ def test_m5_confirmation_joins_the_winning_candidate_the_logger_recorded(tmp_pat ])) winner = {"name": "malformed_choice_consensus", "tier": "L2", "n_pairs": 128, "n_fixed": 25, "n_broken": 0, "effect": 0.5, "fixed": True, "verdict": "fixed"} - # RunLoggerV2 writes `best` as the whole candidate, not its name. + # RunLogger writes `best` as the whole candidate, not its name. logger.log_fix(SimpleNamespace(to_dict=lambda: {"attempted": [winner], "best": dict(winner), "fixed": True})) logger.close() @@ -618,3 +639,295 @@ def test_m5_confirmation_joins_the_winning_candidate_the_logger_recorded(tmp_pat assert (m5["confirmation"]["n_fixed"], m5["confirmation"]["n_broken"]) == (25, 0) assert m5["best"]["name"] == "malformed_choice_consensus" assert {m["id"]: m["value"] for m in data["metrics"]}["fixed"] == 25 + # The repair list the loop figure reads, not the per-case repair outcomes; + # it counts the same 25 as the tile. + assert data["repairs"] == [{ + "id": "repair-1", "fixed": True, "title": "malformed_choice_consensus", + "effect": 0.5, "fixed_cases": 25, "broken_cases": 0, + }] + + +def _explore_output(root, *, hypotheses=True): + root.mkdir(parents=True, exist_ok=True) + report = { + "question": "Does batch temperature predict yield?", + "plain_question": "Which batch setting goes with low yield?", + "ok": True, + "observations": ["Hot batches yield less."], + "takeaways": [], + "hypotheses": [{"statement": "Heat lowers yield."}] if hypotheses else [], + } + (root / "exploratory_report.json").write_text(json.dumps(report), encoding="utf-8") + return root + + +def test_an_explore_output_is_its_own_report(tmp_path): + """`evalrx explore` / run-codebase write no run log, only their report.""" + from evalrx.reporting.dynamic import build_report_data + from evalrx.reporting.run_data import resolve_run_dirs + + root = _explore_output(tmp_path / "explore") + assert resolve_run_dirs(root)[1] == root + + data = build_report_data(root) + status = {stage["id"]: stage["status"] for stage in data["stages"]} + assert status["m1"] == "not-run" + assert status["m2"] == status["m3"] == "completed" + assert data["setting"]["question"] == "Which batch setting goes with low yield?" + assert data["stage_detail"]["m3"]["hypotheses"] + + without = build_report_data(_explore_output(tmp_path / "bare", hypotheses=False)) + assert {s["id"]: s["status"] for s in without["stages"]}["m3"] == "not-run" + + +def test_a_fused_output_reads_as_an_explore_report(tmp_path): + """A fused run writes FusedReport.to_dict(): no takeaways or hypotheses.""" + from evalrx.analysis.fused_pipeline import FusedReport, FusedSignal + from evalrx.reporting.dynamic import build_report_data + + report = FusedReport( + question="Which signal goes with hallucination?", ok=True, + observations=["Diffuse attention goes with false yes."], + candidate_signals=[FusedSignal(name="attn_entropy", source="explorer", reject=True)], + conclusion="attn_entropy held up on the confirm split.", + ) + (tmp_path / "fused_report.json").write_text(json.dumps(report.to_dict()), encoding="utf-8") + + data = build_report_data(tmp_path) + status = {stage["id"]: stage["status"] for stage in data["stages"]} + assert (status["m2"], status["m3"]) == ("completed", "not-run") + assert data["setting"]["kind"] == "explore" + assert data["setting"]["question"] == "Which signal goes with hallucination?" + m2 = data["stage_detail"]["m2"] + assert m2["observations"] == ["Diffuse attention goes with false yes."] + assert m2["candidate_signals"][0]["name"] == "attn_entropy" + + +def test_a_loop_run_beside_an_explore_report_stays_a_loop_run(tmp_path): + from evalrx.eval_agent.run_logger import RunLogger + from evalrx.reporting.dynamic import build_report_data + + _explore_output(tmp_path) + logger = RunLogger(tmp_path, observability_mode="offline") + logger.log_run_start({"model": "demo-model", "protocol": {}, "n_cases": 1}) + logger.close() + assert build_report_data(tmp_path)["setting"]["kind"] == "loop" + + +def test_the_explore_agent_code_reaches_the_m2_record(tmp_path): + from evalrx.reporting.dynamic import build_report_data + + root = _explore_output(tmp_path) + (root / "analysis.py").write_text("print('hi')\n", encoding="utf-8") + (root / "agent_raw_output.txt").write_text("x" * 200_005, encoding="utf-8") + agent = build_report_data(root)["stage_detail"]["m2"]["agent"] + assert agent["code"] == "print('hi')\n" + assert len(agent["transcript"]) == 200_000 and agent["transcript_truncated"] + assert build_report_data(_explore_output(tmp_path / "bare"))["stage_detail"]["m2"]["agent"] is None + + +def test_a_rerun_explore_output_invalidates_its_cached_report(tmp_path): + from evalrx.reporting.dynamic import publish_report, report_is_current + + root = _explore_output(tmp_path) + publish_report(root) + assert report_is_current(root) + later = (root / "report" / "report_spec.json").stat().st_mtime + 5 + os.utime(root / "exploratory_report.json", (later, later)) + assert not report_is_current(root) + + +def test_write_report_notes_a_missing_renderer_instead_of_failing(tmp_path, monkeypatch, capsys): + import evalrx.reporting.static_export as static_export + + def _missing(*_args, **_kwargs): + raise FileNotFoundError("Packaged report renderer is missing") + + monkeypatch.setattr(static_export, "export_static_report", _missing) + assert static_export.write_report(_explore_output(tmp_path)) is None + assert "report.html not written" in capsys.readouterr().out + + +def test_static_export_escapes_script_terminators(tmp_path): + """Run text must not be able to close the bootstrap script block.""" + from pathlib import Path + + import pytest + + import evalrx.reporting.static_export as static_export + + if not (Path(static_export.__file__).with_name("web_dist") / "index.html").exists(): + pytest.skip("report renderer not built") + root = _explore_output(tmp_path) + payload = "" + report = json.loads((root / "exploratory_report.json").read_text()) + report["plain_question"] = payload + (root / "exploratory_report.json").write_text(json.dumps(report), encoding="utf-8") + + page = static_export.export_static_report(root).read_text(encoding="utf-8") + assert payload not in page + assert "\\u003c/script" in page + + +def test_report_reads_model_m1_and_m4_status(tmp_path): + from evalrx.eval_agent.run_logger import RunLogger + from evalrx.reporting.run_data import extract_run_data + + logger = RunLogger(tmp_path, observability_mode="offline") + logger.log_run_start({"model": "new", "protocol": {}, "n_cases": 1}) + logger._append_stage("M1", "probe", {"cycle": 0, "analyzers": ["new_probe"]}) + logger._append_stage("M4", "surgery", { + "module": "m4", "status": "supported", "fixed": False, "confidence_score": 0.8, + "evidence": { + "m4_test_name": "association", "m4_effect_size": 0.3, + "m4_verdict": "supported by held-out evidence", "m4_evidence_grade": "causal", + }, + }) + logger.close() + + data = extract_run_data(tmp_path) + assert data["run"]["raw_model"] == "new" + assert data["m1"]["analyzers"] == ["new_probe"] + assert data["m4"]["results"][0]["status"] == "supported" + + +def test_langfuse_bundle_export(tmp_path): + from evalrx.eval_agent.run_logger import RunLogger + from evalrx.observability import export_to_langfuse_bundle + + logger = RunLogger(tmp_path / "run", observability_mode="offline") + logger.log_run_start({"model": "demo-model", "protocol": {}, "n_cases": 1}) + logger.close() + + out_json = tmp_path / "langfuse_trace.json" + bundle = export_to_langfuse_bundle(tmp_path / "run", out_json) + assert {"trace", "spans", "scores"} <= set(bundle) + assert json.loads(out_json.read_text(encoding="utf-8"))["trace"]["name"].startswith("EvalRX:") + + +def test_serve_opens_an_explore_output_and_its_figures(tmp_path): + """`evalrx serve `: the report and the charts it cites.""" + import shutil + from pathlib import Path + + from fastapi.testclient import TestClient + + from evalrx.reporting.server import create_app + + reference = Path(__file__).resolve().parents[2] / "examples/m2_m3/synthetic_yield_explore/reference_output" + root = tmp_path / "explore" + shutil.copytree(reference, root, ignore=shutil.ignore_patterns("report", "report.html")) + + with TestClient(create_app(root)) as client: + run = client.get("/api/session").json()["run"] + data = client.get(f"/api/runs/{run['id']}/report").json()["data"] + assert data["setting"]["kind"] == "explore" + figures = data["stage_detail"]["m2"]["figures"] + assert figures + figure = client.get(f"/api/runs/{run['id']}/artifact", params={"path": figures[0]["path"]}) + assert figure.status_code == 200 + assert figure.headers["content-type"] == "image/png" + + +def test_a_run_is_finished_once_its_logger_closes(tmp_path): + from evalrx.eval_agent.run_logger import RunLogger + from evalrx.reporting.dynamic import build_report_data + from evalrx.reporting.server import _compile_report + + logger = RunLogger(tmp_path, observability_mode="offline") + logger.log_run_start({"model": "demo-model", "protocol": {}, "n_cases": 1}) + assert build_report_data(tmp_path)["setting"]["finished"] is False + logger._append_stage("M1", "probe", {"cycle": 0, "analyzers": ["a"]}) + setting = build_report_data(tmp_path)["setting"] + assert setting["finished"] is False and setting["last_event_at"] + # A run still being written is compiled in memory, not published into it. + _, envelope = _compile_report(tmp_path) + assert envelope["generated_by"]["mode"] == "deterministic-live" + assert not (tmp_path / "report").exists() + + logger.close() + assert build_report_data(tmp_path)["setting"]["finished"] is True + _compile_report(tmp_path) + assert (tmp_path / "report" / "report_data.json").exists() + + +def test_follow_run_streams_updates_until_the_run_ends(tmp_path): + from evalrx.eval_agent.run_logger import RunLogger + from evalrx.reporting.server import RunRegistry, follow_run + + logger = RunLogger(tmp_path, observability_mode="offline") + logger.log_run_start({"model": "demo-model", "protocol": {}, "n_cases": 1}) + runs = RunRegistry() + key = runs.register(tmp_path) + steps = iter([ + lambda: None, # nothing new: a keep-alive comment + lambda: logger._append_stage("M1", "probe", {"cycle": 0, "analyzers": ["a"]}), + logger.close, + ]) + frames = list(follow_run(runs, key, sleep=lambda _sec: next(steps)())) + + assert frames[0].startswith(": waiting") + assert [f.split("\n")[0] for f in frames[1:]] == ["event: update", "event: update", "event: done"] + assert runs.get(key).data["setting"]["finished"] is True + + +def test_follow_run_ends_at_once_for_a_finished_run_and_yields_to_a_reconnect(tmp_path): + from evalrx.eval_agent.run_logger import RunLogger + from evalrx.reporting.server import RunRegistry, follow_run + + logger = RunLogger(tmp_path / "done", observability_mode="offline") + logger.log_run_start({"model": "demo-model", "protocol": {}, "n_cases": 1}) + logger.close() + runs = RunRegistry() + assert list(follow_run(runs, runs.register(tmp_path / "done"))) == ["event: done\ndata: {}\n\n"] + + live = RunLogger(tmp_path / "live", observability_mode="offline") + live.log_run_start({"model": "demo-model", "protocol": {}, "n_cases": 1}) + frames = list(follow_run(runs, runs.register(tmp_path / "live"), max_sec=4, sleep=lambda _sec: None)) + # No `done`: the stream just ends, and EventSource reconnects on its own. + assert frames == [": waiting\n\n", ": waiting\n\n"] + + +def test_finalize_leaves_run_end_last_after_the_fix_step(tmp_path): + from types import SimpleNamespace + + from evalrx.eval_agent.run_context import RunContext + from evalrx.reporting.dynamic import build_report_data + from evalrx.reporting.run_events import read_run_events + + ctx = RunContext(tmp_path / "run", observability_mode="offline") + ctx.logger.log_run_start({"model": "demo-model", "protocol": {}, "n_cases": 1}) + ctx.logger._append_stage("M1", "probe", {"cycle": 0, "analyzers": ["a"]}) + ctx.logger._append_run("loop_end", {"cycles": 1}) + # M5's fix step logs after loop_end: the run is not over yet. + assert build_report_data(ctx.root)["setting"]["finished"] is False + ctx.logger.log_fix(SimpleNamespace(to_dict=lambda: {"attempted": [], "best": None, "fixed": False})) + ctx.finalize() + + events = read_run_events(ctx.root) + assert events[-1]["event"] == "run_end" + assert build_report_data(ctx.root)["setting"]["finished"] is True + + +def test_a_second_logger_in_the_same_directory_is_followed_until_it_ends(tmp_path): + from evalrx.eval_agent.run_logger import RunLogger + from evalrx.reporting.server import RunRegistry, follow_run + + first = RunLogger(tmp_path, observability_mode="offline") + first.log_run_start({"model": "first", "protocol": {}, "n_cases": 1}) + for _ in range(5): + first._append_stage("M1", "probe", {"cycle": 0, "analyzers": ["a"]}) + first.close() + + # The second run restarts event_seq below the first run's stale M1 log. + second = RunLogger(tmp_path, observability_mode="offline") + second.log_run_start({"model": "second", "protocol": {}, "n_cases": 1}) + runs = RunRegistry() + key = runs.register(tmp_path) + assert runs.get(key).data["setting"]["finished"] is False + steps = iter([ + lambda: second._append_stage("M2", "analysis", {"cycle": 0, "findings": []}), + second.close, + ]) + frames = list(follow_run(runs, key, sleep=lambda _sec: next(steps)())) + assert [f.split("\n")[0] for f in frames] == ["event: update", "event: update", "event: done"] diff --git a/tests/test_analysis/test_fused_pipeline.py b/tests/test_analysis/test_fused_pipeline.py index ab28c537..8cbe7fa6 100644 --- a/tests/test_analysis/test_fused_pipeline.py +++ b/tests/test_analysis/test_fused_pipeline.py @@ -370,3 +370,23 @@ def test_a_correctness_name_that_does_not_track_the_label_is_kept(): ids = list(inp.labels) inp.per_case["some.correct"] = {c: float(i % 2) for i, c in enumerate(ids)} assert not restates_label(inp, "some.correct") + + +def test_one_surviving_result_does_not_vouch_for_its_tools_other_results(): + from evalrx.analysis.fused_pipeline import _fused_signal + from evalrx.analysis.stats_tools import StatsToolResult + + def signal(name: str): + result = StatsToolResult( + tool="signal_label_assoc", analysis_key=f"signal_label_assoc:{name}", + e_value=30.0, effect=0.4, reject=False, + ) + return _fused_signal( + name=name, source="catalog", description="", suggested_test="", recipe=None, + result=result, rejected_result_keys={"signal_label_assoc:kept"}, + confirmed_on="confirm", + ) + + kept, dropped = signal("kept"), signal("dropped") + assert kept.fdr_corrected and kept.reject + assert not dropped.fdr_corrected and not dropped.reject diff --git a/tests/test_analysis/test_general_m2.py b/tests/test_analysis/test_general_m2.py index 2d459119..2bad7838 100644 --- a/tests/test_analysis/test_general_m2.py +++ b/tests/test_analysis/test_general_m2.py @@ -3,7 +3,8 @@ from __future__ import annotations from evalrx.analysis import StatsAnalysisAgent, profile_records -from evalrx.analysis.stats_tools import StatsInput, default_plan +from evalrx.analysis.planner import plan_stats_input +from evalrx.analysis.stats_tools import StatsInput def test_profile_records_infers_roles_and_grain(): @@ -21,7 +22,7 @@ def test_profile_records_infers_roles_and_grain(): assert profile.columns["score"].dtype == "numeric" -def test_default_plan_ranks_signals_before_applying_cap(): +def test_plan_ranks_signals_before_applying_cap(): labels = {f"f{i}": True for i in range(6)} labels.update({f"p{i}": False for i in range(6)}) weak = {cid: 0.5 for cid in labels} @@ -31,10 +32,10 @@ def test_default_plan_ranks_signals_before_applying_cap(): } inp = StatsInput(labels=labels, per_case={"zzz_constant": weak, "aaa_strong": strong}) - plan = default_plan(inp, max_signals=1) + plan = plan_stats_input(inp, max_signals=1) - assert plan[0][0] == "signal_label_assoc" - assert plan[0][1]["signal"] == "aaa_strong" + assert plan[0].tool == "signal_label_assoc" + assert plan[0].config["signal"] == "aaa_strong" def test_stats_analysis_agent_tests_more_than_four_signals_by_default(): @@ -57,68 +58,52 @@ def test_stats_analysis_agent_tests_more_than_four_signals_by_default(): assert report.corrected_rejections["families"]["bh"]["n_tested"] >= 6 -# ── the M2 section parser must survive how judges actually write ───────────── -def _base_report(): - from evalrx.analysis.analysis_module import AnalysisReport - return AnalysisReport(model_name="m", - narrative="Model: EndpointModel(qwen3.5-2b)\nrest") - - -def test_markdown_headings_are_parsed_not_dropped(): - """A judge wrote '## CONCLUSION'; the matcher demanded 'CONCLUSION:'. - - No section was ever entered, so 4,158 characters of analysis fell through to - the base narrative's first line and M3 received nothing to hypothesise from. - The run then reported stopped_by=no_hypotheses as though that were a - finding. Earlier runs parsed only because the judge happened to use a colon. - """ - from evalrx.analysis.stats_agent import _parse_llm_analysis - - raw = ( - "## CONCLUSION\n\n" - "The failures are a capability defect in list-state maintenance.\n\n" - "## EVIDENCE_CHAIN\n\n" - "- Step 1 - kendall tau 0.92 with edit distance 7.82\n" - "- Step 2 - 66% token loss\n\n" - "## QUALITATIVE\n\n" - "- probe1 has an internally incoherent signature on ~45% of fails\n" - ) - conclusion, evidence, qualitative = _parse_llm_analysis(raw, _base_report()) - assert "capability defect" in conclusion - assert len(evidence) == 2 and "kendall tau" in evidence[0] - assert len(qualitative) == 1 - - -def test_the_original_colon_contract_still_parses(): - from evalrx.analysis.stats_agent import _parse_llm_analysis - - raw = ("CONCLUSION: it broke\n" - "EVIDENCE_CHAIN:\n- step one\n- step two\n" - "QUALITATIVE:\n- note") - conclusion, evidence, qualitative = _parse_llm_analysis(raw, _base_report()) - assert conclusion == "it broke" - assert evidence == ["step one", "step two"] - assert qualitative == ["note"] - +# ── the M2 judge's analysis is a typed answer ──────────────────────────────── +def _analyze_with(reply: str): + from evalrx.analysis import StatsAnalysisAgent + from evalrx.core.result import Result + from evalrx.eval_agent.stages.protocol import ExperimentProtocol -def test_bold_headings_parse_too(): - from evalrx.analysis.stats_agent import _parse_llm_analysis + class Judge: + def __init__(self): + self.prompts: list[str] = [] - raw = "**CONCLUSION**\nthe thing happened\n**EVIDENCE_CHAIN**\n- because\n" - conclusion, evidence, _ = _parse_llm_analysis(raw, _base_report()) - assert conclusion == "the thing happened" - assert evidence == ["because"] + def generate(self, prompt, **kwargs): + self.prompts.append(prompt) + return reply + judge = Judge() + res = {"a": Result(analyzer="a", model="m", findings={"x": 1.0})} + report = StatsAnalysisAgent(judge=judge).analyze( + res, model_name="m", protocol=ExperimentProtocol(description="d")) + return report, judge -def test_prose_without_sections_yields_no_conclusion_not_a_synthesized_one(): - """No section => "" — so the caller keeps the deterministic conclusion it - already built. Returning base.narrative's first line here ("Model: ") - was how a quota message from the CLI silently replaced a real M2 verdict. - """ - from evalrx.analysis.stats_agent import _parse_llm_analysis - conclusion, _, _ = _parse_llm_analysis("just prose", _base_report()) - assert conclusion == "" +def test_an_analysis_in_markdown_around_json_is_read(): + """Judges decorate their answers; '## CONCLUSION' once lost a whole analysis.""" + reply = ( + "## Analysis\n```json\n" + '{"conclusion": "The failures are a capability defect in list-state maintenance.",' + ' "evidence_chain": ["kendall tau 0.92 with edit distance 7.82", "66% token loss"],' + ' "qualitative": ["probe1 is incoherent on ~45% of fails"]}\n```' + ) + report, judge = _analyze_with(reply) + assert len(judge.prompts) == 1 + assert "capability defect" in report.conclusion + assert report.evidence_chain[0].startswith("kendall tau") and len(report.evidence_chain) == 2 + assert report.qualitative_findings == ["probe1 is incoherent on ~45% of fails"] + + +def test_prose_keeps_the_deterministic_conclusion_and_says_why(): + """No valid analysis after one retry: the deterministic conclusion stays, + and the report says the judge gave no usable answer (a quota message read + as an analysis once replaced a real M2 verdict with "Model: ").""" + report, judge = _analyze_with("just prose") + assert len(judge.prompts) == 2 + assert report.stats_tool != "llm_guided" + assert "JudgeOutputError" in report.llm_fallback_reason + assert report.llm_raw == "just prose" + assert report.conclusion and "just prose" not in report.conclusion # ── what the judge is shown about multiplicity ─────────────────────────────── @@ -209,7 +194,7 @@ def test_a_judge_that_answered_leaves_no_fallback_reason(): class LiveJudge: def generate(self, prompt, **kwargs): - return "CONCLUSION: it worked\nEVIDENCE_CHAIN:\n- because" + return '{"conclusion": "it worked", "evidence_chain": ["because"]}' res = {"a": Result(analyzer="a", model="m", findings={"x": 1.0})} report = StatsAnalysisAgent(judge=LiveJudge()).analyze( diff --git a/tests/test_analysis/test_holdout.py b/tests/test_analysis/test_holdout.py index 7cf43e4e..e3330793 100644 --- a/tests/test_analysis/test_holdout.py +++ b/tests/test_analysis/test_holdout.py @@ -142,6 +142,18 @@ def test_holdout_confirm_without_judge_marks_not_judged(): assert confirm["judge"] is None +def test_holdout_confirm_records_a_judge_that_never_answers_validly(): + class _Rambling: + def generate(self, prompt, **kwargs): + return "I think it is mostly supported, roughly." + + confirm = holdout_confirm(_report(), _rows(), outcome_col="label", judge=_Rambling()) + (hv,) = confirm["hypothesis_verdicts"] + # Not "not_testable": that would be a verdict the judge never gave. + assert hv["verdict"] == "not_judged" and hv["needs_surgery"] is True + assert "no valid answer" in hv["judge_error"] + + def test_holdout_confirm_non_binary_outcome_degrades_honestly(): rows = [{"x": 0.9, "label": f"grade{i % 3}"} for i in range(12)] confirm = holdout_confirm(_report(), rows, outcome_col="label", judge=None) diff --git a/tests/test_analysis/test_html_report.py b/tests/test_analysis/test_html_report.py deleted file mode 100644 index c0295b46..00000000 --- a/tests/test_analysis/test_html_report.py +++ /dev/null @@ -1,139 +0,0 @@ -"""Tests for dynamic HTML report generator and Langfuse exporter.""" - -import json -from pathlib import Path - -from evalrx.reporting.html_report import build_html_report, embed_figures -from evalrx.reporting.langfuse_exporter import export_to_langfuse_bundle -from evalrx.reporting.run_data import extract_run_data - - -def _png(path: Path) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(b"\x89PNG\r\n\x1a\n" + b"fake") - - -def test_embed_figures_finds_v1_figures_dir(tmp_path: Path): - _png(tmp_path / "figures" / "m2_effects.png") - out = embed_figures(None, tmp_path) - assert "m2_effects" in out and out["m2_effects"].startswith("data:image/png;base64,") - - -def test_embed_figures_finds_v2_m2_artifacts(tmp_path: Path): - """Regression test: embed_figures used to only glob logs_dir/figures, so - RunContext.figures_dir's V2 mapping (M2/artifacts, run_context.py) meant - every V2 run's static HTML export rendered zero embedded M2 charts.""" - _png(tmp_path / "M2" / "artifacts" / "m2_effects.png") - out = embed_figures(None, tmp_path) - assert "m2_effects" in out and out["m2_effects"].startswith("data:image/png;base64,") - - -def test_embed_figures_combines_v1_and_v2_sources_without_clobbering(tmp_path: Path): - _png(tmp_path / "figures" / "shared.png") - _png(tmp_path / "M2" / "artifacts" / "other.png") - out = embed_figures(None, tmp_path) - assert {"shared", "other"} <= set(out) - - -def test_html_report_generation(tmp_path: Path): - # Test against real MMAU outputs - run_dir = Path("examples/m1_m5/mmau_qwen2_audio/outputs") - example_dir = Path("examples/m1_m5/mmau_qwen2_audio") - out_file = tmp_path / "test_report.html" - - if run_dir.exists(): - data = extract_run_data(run_dir, example_dir) - assert data["run"]["model"] is not None - assert "m1" in data - assert "m2" in data - assert "m3" in data - - res_path = build_html_report( - run_dir=run_dir, - example_dir=example_dir, - out_path=out_file, - no_audio=True, - ) - assert res_path.exists() - content = res_path.read_text(encoding="utf-8") - assert "EvalRX" in content - assert "What this report says" in content - assert "What we checked" in content - assert "What patterns we found" in content - assert "Possible explanation to test" in content - assert "Repair attempt" in content - assert "fonts.googleapis.com" not in content - assert "fonts.gstatic.com" not in content - - -def test_langfuse_bundle_export(tmp_path: Path): - run_dir = Path("examples/m1_m5/mmau_qwen2_audio/outputs") - out_json = tmp_path / "langfuse_trace.json" - - if run_dir.exists(): - bundle = export_to_langfuse_bundle(run_dir, out_json) - assert "trace" in bundle - assert "spans" in bundle - assert "scores" in bundle - assert out_json.exists() - loaded = json.loads(out_json.read_text(encoding="utf-8")) - assert loaded["trace"]["name"].startswith("EvalRX:") - - -def test_report_reads_model_m1_and_m4_status(tmp_path: Path): - """extract_run_data surfaces the run's model, M1 analyzers, and M4 status. - - V1's flat, append-only run_log.jsonl could accumulate two traces in one - file (a run re-launched into the same directory), which is what this - test used to guard against by injecting a stale "old" trace and checking - the reader picked the "new" one. RunLoggerV2 does full-document atomic - rewrites instead of appending — a second instance pointed at the same - run_dir overwrites run.json and any stage doc it touches wholesale, so - that scenario can't arise on disk in the first place; there's nothing - for a reader-side trace filter to do. - """ - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 - - logger = RunLoggerV2(tmp_path, observability_mode="offline") - logger.log_run_start({"model": "new", "protocol": {}, "n_cases": 1}) - logger._append_stage("M1", "probe", {"cycle": 0, "analyzers": ["new_probe"]}) - logger._append_stage("M4", "surgery", { - "module": "m4", "status": "supported", "fixed": False, "confidence_score": 0.8, - "evidence": { - "m4_test_name": "association", "m4_effect_size": 0.3, - "m4_verdict": "supported by held-out evidence", "m4_evidence_grade": "causal", - }, - }) - logger.close() - - data = extract_run_data(tmp_path) - - assert data["run"]["raw_model"] == "new" - assert data["m1"]["analyzers"] == ["new_probe"] - assert data["m4"]["results"][0]["status"] == "supported" - - -def test_report_escapes_script_terminators_in_case_data(tmp_path: Path): - """Manifest/model text must not be able to escape the CASES script block.""" - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 - from evalrx.reporting.html_report import generate_html_report - - RunLoggerV2(tmp_path, observability_mode="offline").log_run_start({"protocol": {}}) - data = extract_run_data(tmp_path) - payload = "" - data["cases"] = [{ - "id": "case-1", - "status": "unchanged", - "output": "", - "instruction": payload, - "choices": [], - "expected": "", - "duration": 0.0, - "task": "", - "probe_flags": [], - }] - - page = generate_html_report(data, {}, {}, {}) - - assert payload not in page - assert "\\u003c/script\\u003e" in page diff --git a/tests/test_analysis/test_hypothesis_agent.py b/tests/test_analysis/test_hypothesis_agent.py index 801c8c0c..ebe9f974 100644 --- a/tests/test_analysis/test_hypothesis_agent.py +++ b/tests/test_analysis/test_hypothesis_agent.py @@ -1,6 +1,12 @@ from __future__ import annotations -from evalrx.analysis.hypothesis_agent import Hypothesis, HypothesisAgent, _parse_hypotheses +import json +from pathlib import Path + +import pytest + +from evalrx.agent_runtime.cli_types import CliAgentConfig, CliAgentResult +from evalrx.analysis.hypothesis_agent import Hypothesis, HypothesisAgent class ScriptedJudge: @@ -38,119 +44,84 @@ def generate(self, prompt: str, **kwargs) -> str: "candidate_signals": [{"name": "temperature", "display_name": "Temperature", "rationale": "r=0.86"}], } -_GOOD_RESPONSE = """\ -HYPOTHESIS: Higher temperature accelerates the reaction, raising yield. -PLAIN: Warmer batches speed up the reaction, so more product comes out. -BASIS: Higher temperature batches yield more (70.1% vs 88.4%). -TEST: Run a controlled temperature-ramp experiment holding pressure fixed. - -HYPOTHESIS: Catalyst B underperforms due to a side reaction at high pressure. -PLAIN: Catalyst B does worse because it triggers an unwanted extra reaction under high pressure. -BASIS: Temperature signal only -TEST: Compare catalyst B vs C yield holding temperature fixed.""" +def _answer(*items: tuple[str, str]) -> str: + return json.dumps({"hypotheses": [ + {"hypothesis": h, "plain_statement": plain, "basis": "Higher temperature batches yield more.", + "test": "Run a controlled temperature-ramp experiment holding pressure fixed."} + for h, plain in items + ]}) -_JARGON_RESPONSE = """\ -HYPOTHESIS: Higher temperature accelerates the reaction, raising yield. -PLAIN: This is collinear with the AUC of the reaction rate. -BASIS: Higher temperature batches yield more (70.1% vs 88.4%). -TEST: Run a controlled temperature-ramp experiment holding pressure fixed.""" +_GOOD_RESPONSE = _answer( + ("Higher temperature accelerates the reaction, raising yield.", + "Warmer batches speed up the reaction, so more product comes out."), + ("Catalyst B underperforms due to a side reaction at high pressure.", + "Catalyst B does worse because it triggers an unwanted extra reaction under high pressure."), +) -def test_parse_hypotheses_splits_multiple_entries(): - out = _parse_hypotheses(_GOOD_RESPONSE) - assert len(out) == 2 - assert out[0].statement == "Higher temperature accelerates the reaction, raising yield." - assert out[0].plain_statement == "Warmer batches speed up the reaction, so more product comes out." - assert out[0].basis == "Higher temperature batches yield more (70.1% vs 88.4%)." - assert out[0].test_design == "Run a controlled temperature-ramp experiment holding pressure fixed." - assert out[1].statement.startswith("Catalyst B underperforms") - - -def test_parse_hypotheses_plain_line_is_optional(): - """Older/repaired responses may omit PLAIN entirely — parsing must not break.""" - raw = ( - "HYPOTHESIS: Higher temperature accelerates the reaction, raising yield.\n" - "BASIS: Higher temperature batches yield more.\n" - "TEST: Run a controlled experiment." - ) - out = _parse_hypotheses(raw) - assert len(out) == 1 - assert out[0].plain_statement == "" - - -def test_parse_hypotheses_no_hypothesis_marker_yields_empty(): - assert _parse_hypotheses("NO_HYPOTHESIS") == [] - assert _parse_hypotheses("") == [] - - -def test_parse_hypotheses_dedupes_restated_hypothesis_in_a_cli_trajectory(): - """CliAgentResult.raw_output for the CLI-agent backend is the full - rendered tool-call trajectory, not just a final answer — an agent that - narrates a plan before its final answer can restate the same hypothesis - twice. This must not double-count it (observed on a real claude_code run).""" - trajectory = ( - "[assistant] Let me think through this...\n" - + _GOOD_RESPONSE - + "\n\n[assistant] Here is my final answer.\n" - + _GOOD_RESPONSE - ) - - out = _parse_hypotheses(trajectory) +_JARGON_RESPONSE = _answer( + ("Higher temperature accelerates the reaction, raising yield.", + "This is collinear with the AUC of the reaction rate."), +) - assert len(out) == 2 - statements = [h.statement for h in out] - assert len(statements) == len(set(statements)) - assert out[0].statement == "Higher temperature accelerates the reaction, raising yield." +_NONE = json.dumps({"hypotheses": []}) -def test_propose_uses_judge_and_returns_parsed_hypotheses(): - judge = ScriptedJudge(_GOOD_RESPONSE) +def test_propose_uses_judge_and_returns_typed_hypotheses(): + judge = ScriptedJudge(f"Here you go:\n```json\n{_GOOD_RESPONSE}\n```") agent = HypothesisAgent(judge=judge) out = agent.propose(_REPORT) assert len(out) == 2 assert all(isinstance(h, Hypothesis) for h in out) + assert out[0].statement == "Higher temperature accelerates the reaction, raising yield." assert out[0].plain_statement == "Warmer batches speed up the reaction, so more product comes out." + assert out[0].basis == "Higher temperature batches yield more." + assert out[0].test_design.startswith("Run a controlled") # the prompt actually carries the takeaway/observation/signal content assert "Higher temperature batches yield more" in judge.prompts[0] assert "temperature" in judge.prompts[0].lower() - # PLAIN line already passed the check — no repair round needed + # the plain statements already pass the check: one call assert len(judge.prompts) == 1 -def test_propose_repairs_a_jargon_plain_line(): - fixed = ( - "HYPOTHESIS: Higher temperature accelerates the reaction, raising yield.\n" - "PLAIN: Warmer batches produce more output.\n" - "BASIS: Higher temperature batches yield more (70.1% vs 88.4%).\n" - "TEST: Run a controlled temperature-ramp experiment holding pressure fixed." - ) +def test_an_empty_list_means_no_hypotheses(): + assert HypothesisAgent(judge=ScriptedJudge(_NONE)).propose(_REPORT) == [] + + +def test_propose_sends_a_jargon_plain_statement_back_once(): + fixed = _answer(("Higher temperature accelerates the reaction, raising yield.", + "Warmer batches produce more output.")) judge = QueuedJudge(_JARGON_RESPONSE, fixed) - agent = HypothesisAgent(judge=judge) - out = agent.propose(_REPORT) + out = HypothesisAgent(judge=judge).propose(_REPORT) assert len(judge.prompts) == 2 - assert "collinear" in judge.prompts[0] - # the repair prompt names the specific violation and echoes the original answer - assert "jargon" in judge.prompts[1].lower() - assert "AUC" in judge.prompts[1] or "collinear" in judge.prompts[1] - assert len(out) == 1 - assert out[0].plain_statement == "Warmer batches produce more output." - - -def test_propose_keeps_original_when_repair_still_fails(): - """If the repair round itself doesn't fix the jargon, fall back to - whatever was parsed rather than dropping the hypothesis entirely.""" - judge = ScriptedJudge(_JARGON_RESPONSE) # same jargon-y answer every call - agent = HypothesisAgent(judge=judge) + assert "plain-language check" in judge.prompts[1] + assert "collinear" in judge.prompts[1] + assert [h.plain_statement for h in out] == ["Warmer batches produce more output."] - out = agent.propose(_REPORT) + +def test_propose_keeps_the_answer_when_the_revision_still_has_jargon(): + judge = ScriptedJudge(_JARGON_RESPONSE) # same answer every call + + out = HypothesisAgent(judge=judge).propose(_REPORT) assert len(judge.prompts) == 2 - assert len(out) == 1 - assert out[0].statement == "Higher temperature accelerates the reaction, raising yield." + assert [h.statement for h in out] == ["Higher temperature accelerates the reaction, raising yield."] + + +def test_an_answer_without_the_hypotheses_field_is_not_read_as_none(): + judge = QueuedJudge('{"note": "thinking"}', _GOOD_RESPONSE) + out = HypothesisAgent(judge=judge).propose(_REPORT) + assert len(judge.prompts) == 2 and len(out) == 2 + + +def test_propose_returns_empty_when_no_valid_answer_arrives(): + judge = ScriptedJudge("HYPOTHESIS: an old-style answer") + assert HypothesisAgent(judge=judge).propose(_REPORT) == [] + assert len(judge.prompts) == 2 def test_propose_returns_empty_without_a_configured_backend(): @@ -193,7 +164,7 @@ def generate(self, prompt: str) -> str: def test_agent_report_appends_intervenable_cause_hint(): from evalrx.analysis.hypothesis_agent import _is_agent_report - judge = ScriptedJudge("NO_HYPOTHESIS") + judge = ScriptedJudge(_NONE) HypothesisAgent(judge=judge).propose(_AGENT_REPORT) assert _is_agent_report(_AGENT_REPORT) is True assert "AGENT TRAJECTORIES" in judge.prompts[0] @@ -204,7 +175,56 @@ def test_agent_report_appends_intervenable_cause_hint(): def test_non_agent_report_gets_no_hint(): from evalrx.analysis.hypothesis_agent import _is_agent_report - judge = ScriptedJudge("NO_HYPOTHESIS") + judge = ScriptedJudge(_NONE) HypothesisAgent(judge=judge).propose(_REPORT) assert _is_agent_report(_REPORT) is False assert "AGENT TRAJECTORIES" not in judge.prompts[0] + + +# ── CLI coding-agent backend ────────────────────────────────────────────────── +class _FakeRunner: + """Stands in for CodegenRunner: 'the agent' writes answer.json (or not).""" + + answers: list = [] + workdirs: list = [] + + def __init__(self, cli_config): + pass + + def run(self, prompt, *, workdir: Path, timeout_sec=None): + _FakeRunner.workdirs.append(workdir) + assert "answer.json" in prompt + answer = _FakeRunner.answers.pop(0) + if isinstance(answer, str): + (workdir / "answer.json").write_text(answer) + return CliAgentResult(files={}, provider_name="claude_code", elapsed_sec=1.0, + raw_output="[assistant] draft " + _JARGON_RESPONSE) + return CliAgentResult(files={}, provider_name="claude_code", elapsed_sec=1.0, **answer) + + +@pytest.fixture +def fake_runner(monkeypatch): + import evalrx.agent_runtime.codegen as codegen + + monkeypatch.setattr(codegen, "CodegenRunner", _FakeRunner) + _FakeRunner.answers, _FakeRunner.workdirs = [], [] + return _FakeRunner + + +def test_cli_backend_reads_the_answer_file_not_the_trajectory(fake_runner): + fake_runner.answers = [_GOOD_RESPONSE] + agent = HypothesisAgent(cli_config=CliAgentConfig(provider="claude_code")) + out = agent.propose(_REPORT) + assert [h.plain_statement for h in out][0] == "Warmer batches speed up the reaction, so more product comes out." + + +def test_cli_backend_retries_in_a_fresh_directory_when_no_file_is_written(fake_runner): + fake_runner.answers = [{"raw_output": "I wrote nothing"}, _GOOD_RESPONSE] + out = HypothesisAgent(cli_config=CliAgentConfig(provider="claude_code")).propose(_REPORT) + assert len(out) == 2 + assert len(set(fake_runner.workdirs)) == 2 + + +def test_cli_backend_failure_yields_no_hypotheses(fake_runner): + fake_runner.answers = [{"error": "[TIMEOUT] agent killed after 90s"}] + assert HypothesisAgent(cli_config=CliAgentConfig(provider="claude_code")).propose(_REPORT) == [] diff --git a/tests/test_analysis/test_langfuse_source.py b/tests/test_analysis/test_langfuse_source.py index c40888df..309d0b95 100644 --- a/tests/test_analysis/test_langfuse_source.py +++ b/tests/test_analysis/test_langfuse_source.py @@ -39,7 +39,7 @@ def get_many(self, **kwargs): assert [event["event"] for event in events] == ["run_start", "analysis"] assert calls[0]["trace_id"] == "00000000000000000000000000000001" - # materialize() writes a V2-shaped bundle (run.json + M*/log.json), not a + # materialize() writes a run-log bundle (run.json + M*/log.json), not a # flat run_log.jsonl — recovered events with no "stage" tag route by their # own event name to the canonical stage doc ("analysis" -> M2). run = json.loads((root / "run.json").read_text()) @@ -85,7 +85,7 @@ def resolve_media_references(self, *, obj, resolve_with): def test_materialized_langfuse_run_builds_the_report(tmp_path): from evalrx.reporting.dynamic import build_report_data from evalrx.reporting.langfuse_source import LangfuseRunSource - from evalrx.reporting.run_events import read_v2_events + from evalrx.reporting.run_events import read_run_events observations = [ SimpleNamespace( @@ -103,13 +103,37 @@ def test_materialized_langfuse_run_builds_the_report(tmp_path): ))) root = LangfuseRunSource(client).materialize("trace", tmp_path / "cache") - # A real V2 root, not just a stray run.json: read_v2_events (the same + # A real run root, not just a stray run.json: read_run_events (the same # read path the report uses) must recover both events, not silently - # nothing — resolve_v2_root requires a real M/log.json too. - events = read_v2_events(root) + # nothing — resolve_run_root requires a real M/log.json too. + events = read_run_events(root) assert {e["event"] for e in events} == {"run_start", "probe"} data = build_report_data(root) assert data["trace_id"] == "trace" assert data["stage_detail"]["m1"] is not None + + +def test_a_run_rebuilt_from_langfuse_is_finished_by_its_run_end(tmp_path): + from evalrx.reporting.dynamic import build_report_data + from evalrx.reporting.langfuse_source import LangfuseRunSource + + def source(events): + class Observations: + def get_many(self, **_kwargs): + return SimpleNamespace( + data=[_observation(e["event_seq"], e) for e in events], + meta=SimpleNamespace(cursor=None), + ) + + return LangfuseRunSource(SimpleNamespace(api=SimpleNamespace(observations=Observations()))) + + start = {"event": "run_start", "event_seq": 1, "schema_version": 7, "ts": "2026-11-13T00:00:00+00:00"} + analysis = {"event": "analysis", "event_seq": 2, "ts": "2026-11-13T00:00:01+00:00"} + end = {"event": "run_end", "event_seq": 3, "ts": "2026-11-13T00:00:02+00:00"} + + ended = source([start, analysis, end]).materialize("trace", tmp_path / "ended") + assert build_report_data(ended)["setting"]["finished"] is True + running = source([start, analysis]).materialize("trace", tmp_path / "running") + assert build_report_data(running)["setting"]["finished"] is False diff --git a/tests/test_analysis/test_report_compiler.py b/tests/test_analysis/test_report_compiler.py index 3767eea4..a7e0b2b7 100644 --- a/tests/test_analysis/test_report_compiler.py +++ b/tests/test_analysis/test_report_compiler.py @@ -1,7 +1,5 @@ from __future__ import annotations -from evalrx.reporting.compiler import compile_diagnostic_report - def test_reader_report_is_generic_and_keeps_observation_distinct_from_proof(): from evalrx.reporting.compiler import compile_reader_report @@ -21,67 +19,3 @@ def test_reader_report_is_generic_and_keeps_observation_distinct_from_proof(): assert payload["key_findings"][0]["title"] == "Arbitrary task signal" assert payload["key_findings"][0]["summary"] == "It differed between the two outcome groups." assert "does not prove" in payload["key_findings"][0]["limitation"] - - -def _explore_report(): - return { - "question": "q", - "conclusion": "Supported signal found.", - "observations": ["obs"], - "visual_plan": [{"name": "v", "plot_kind": "bar"}], - "chart_readings": [{"chart": "C", "reading": "read"}], - "dashboard_storyboard": [{ - "id": "analysis", - "title": "Analysis", - "stages": ["M2"], - "summary": "Agent-owned panel text", - "items": ["Method: held-out check"], - "artifact_refs": ["candidate_signals"], - }], - "charts": [{"name": "c", "title": "C", "data": "tables/c.csv"}], - "candidate_signals": [ - {"name": "low_focus", "effect": 0.4, "ci": [0.1, 0.7], "reject": True}, - {"name": "probe1_false_detection", "effect": 1.0, "ci": [1.0, 1.0], - "reject": True}, - ], - "critique": ["watch leakage"], - } - - -def test_compile_diagnostic_report_is_claim_first(): - story = { - "analyses": [{"cycle": 1, "conclusion": "M2 supported low_focus"}], - "diagnoses": [{"cycle": 1, "hypotheses": [{"statement": "low_focus cause"}]}], - } - report = compile_diagnostic_report(story, _explore_report()) - - assert report.answer.startswith("High attention focus is associated with FAIL cases") - assert "sanity check" in report.answer - by_text = {c.text: c for c in report.claims} - assert any("High attention focus is associated" in text for text in by_text) - leaky = next(c for c in report.claims if "Sanity check" in c.text) - assert leaky.status == "descriptive" - assert report.chart_readings == [{"chart": "C", "reading": "read"}] - assert report.dashboard_storyboard[0]["summary"] == "Agent-owned panel text" - assert report.critique == ["watch leakage"] - - -def test_question_falls_back_to_run_start_protocol_description_not_generic_text(): - """A loop/agentic run with no explore_report (so no explore_report["question"]) - must not show the generic "What distinguishes failures from passes?" filler — - it should surface what run_start's own protocol actually says this run - investigates, both in the compiled question and the problem_setting panel.""" - story = { - "run_start": {"protocol": {"description": "Do FAIL cases share an attention signature?"}}, - } - report = compile_diagnostic_report(story, explore_report=None) - - assert report.question == "Do FAIL cases share an attention signature?" - problem_setting = next(p for p in report.dashboard_storyboard if p["id"] == "problem_setting") - assert problem_setting["summary"] == "Do FAIL cases share an attention signature?" - - -def test_question_uses_generic_text_when_neither_source_is_available(): - report = compile_diagnostic_report(story=None, explore_report=None) - assert report.question == "What distinguishes failures from passes?" - diff --git a/tests/test_analysis/test_report_ui_contract.py b/tests/test_analysis/test_report_ui_contract.py index e8d34617..758de19b 100644 --- a/tests/test_analysis/test_report_ui_contract.py +++ b/tests/test_analysis/test_report_ui_contract.py @@ -1,26 +1,6 @@ from __future__ import annotations from evalrx.analysis.prompts.explorer import _ANALYSIS_CONTRACT -from evalrx.reporting.stages import STAGE_SPECS, stage_specs_as_dicts -from evalrx.viz.prompts import DASHBOARD_STORYBOARD_SYSTEM_PROMPT - - -def test_stage_specs_define_m1_to_m5_dashboard_roles(): - ids = [s.id for s in STAGE_SPECS] - assert ids == ["M1", "M2", "M3", "M4", "M5"] - rows = stage_specs_as_dicts() - assert rows[0]["dashboard_role"].startswith("Problem Setting") - assert "Analysis" in rows[1]["dashboard_role"] - assert "Hypotheses" in rows[2]["dashboard_role"] - - -def test_dashboard_storyboard_prompt_is_three_panel_and_stage_aware(): - prompt = DASHBOARD_STORYBOARD_SYSTEM_PROMPT - assert "Problem Setting" in prompt - assert "Analysis" in prompt - assert "Hypotheses & Artifacts" in prompt - assert "M1" in prompt and "M2" in prompt and "M3-M5" in prompt - assert "display_name" in prompt def test_explorer_analysis_contract_requires_reader_friendly_m2_language(): diff --git a/tests/test_analysis/test_run_cli.py b/tests/test_analysis/test_run_cli.py index 41d0d3f4..04ff7051 100644 --- a/tests/test_analysis/test_run_cli.py +++ b/tests/test_analysis/test_run_cli.py @@ -131,7 +131,7 @@ def test_default_runner_constructs_agentic_pipeline_for_every_modality(monkeypat from evalrx.benchmark.models import resolve from evalrx.benchmark.tasks import get from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label - from evalrx.eval_agent import AgenticDiagnoseLoop, CaseDiscoveryAgent + from evalrx.eval_agent import CaseDiscoveryAgent, VLDiagnoseLoop from evalrx.specs import get_spec from tests.conftest import FakeModel @@ -157,11 +157,11 @@ class ReachedController(Exception): def run(loop, data): assert loop.probe_agent.allow_codegen - assert loop.max_actions == 12 + assert loop.policy.max_actions == 12 assert loop.fix_agent.proposer._floor_candidates == () assert len(data) == 8 raise ReachedController - monkeypatch.setattr(AgenticDiagnoseLoop, 'run', run) + monkeypatch.setattr(VLDiagnoseLoop, 'run', run) with pytest.raises(ReachedController): runner.run(args, get(dataset), resolved) diff --git a/tests/test_analysis/test_run_data_extract.py b/tests/test_analysis/test_run_data_extract.py new file mode 100644 index 00000000..79fffff2 --- /dev/null +++ b/tests/test_analysis/test_run_data_extract.py @@ -0,0 +1,176 @@ +"""extract_run_data reads a run from its log alone.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +from evalrx.reporting.run_data import extract_run_data +from evalrx.reporting.run_events import write_run_bundle + +TRACE = "00000000-0000-0000-0000-00000000000a" +LONG_NEED = "count how often the answer changes when the same question is asked " * 4 + + +def _event(seq: int, name: str, stage: str = "RUN", **payload: Any) -> dict[str, Any]: + return {"event": name, "stage": stage, "trace_id": TRACE, "event_seq": seq, + "ts": f"2026-08-20T00:00:{seq:02d}+00:00", **payload} + + +def _run(root: Path, events: list[dict[str, Any]]) -> Path: + write_run_bundle(root / "logs", events) + return root + + +def test_every_stage_is_read_from_its_events(tmp_path): + root = _run(tmp_path / "outputs", [ + _event(1, "run_start", model="org/some-model", n_cases=4, + label_distribution={"fail": 3, "pass": 1}, protocol={"description": "Answer the question."}), + _event(2, "probe_search", "M1", n_synthesized=7), + _event(3, "tool_codegen", "M1", module="m1", tool_name="probe1", need=LONG_NEED), + _event(4, "probe", "M1", cycle=1, duration_sec=3.0, + analyzers=["format_sensitivity", "generated:probe1", "mystery_probe", "calibration"], + findings={ + "format_sensitivity": {"n_cases": 4, "mean_flip_rate": 0.5, + "per_case": [{"sample_id": "c1", "format_flip_rate": 0.5}]}, + "generated:probe1": {"n_cases": 2, "flip_rate": 0.25, "mean_gap": 1.5, "ok": True}, + "calibration": {"n_scored": 3, "logprob_channel": {"ece": 0.125}}, + }), + _event(5, "analysis", "M2", conclusion="Order matters.", narrative="n", severity="high", duration_sec=1.0, + stats_results=[ + {"tool": "t_small", "summary": "small", "effect": 0.1, "reject": True, "p_value": 0.04}, + {"tool": "t_null", "effect": 0.9, "reject": False, "underpowered": True}, + {"tool": "t_big", "effect": -0.6, "ci": [-0.8, -0.4], "reject": True, "config": {"k": 1}}, + ], + findings=["[HIGH] format_sensitivity.mean_flip_rate=0.5 > 0.2: answers flip with option order"]), + _event(6, "explore", "M2", observations=["Short answers fail more; long ones pass."], + workspace_snapshot={"files": {"analysis.py": "print(1)", "stdout.txt": "1\n", + "agent_audit.json": json.dumps({"files_read": 2})}}), + _event(7, "diagnosis", "M3", duration_sec=2.0, + hypotheses=[{"id": "h1", "statement": "Option order drives the answer."}]), + _event(8, "surgery", "M4", module="m4", hypothesis_id="h1", status="supported", confidence_score=0.9, + evidence={"m4_effect_size": 0.4, "m4_verdict": "supported"}), + _event(9, "surgery", "M5", module="m5", hypothesis_id="h1", status="supported"), + _event(10, "fix", "M5", module="fix", fixed=True, attempted=[{"name": "a"}], + best={"name": "think_first", "fixed": True, "payload": {"prompt_template": "Think first. {q}"}}), + _event(11, "loop_end", cycles=2, stopped_by="budget", total_duration_sec=9.0), + ]) + (root / "summary.json").write_text(json.dumps({"model": "some-model-as-typed", "dataset": "my_dataset"})) + + data = extract_run_data(root) + + assert data["run"]["kind"] == "loop" + assert (data["run"]["model"], data["run"]["raw_model"]) == ("some-model-as-typed", "org/some-model") + assert data["run"]["benchmark_name"] == "my_dataset" + assert (data["run"]["n_cases"], data["run"]["cycles"], data["run"]["stopped_by"]) == (4, 2, "budget") + assert data["pre_m1"] == {"ran": True, "n_cases": 7} + + assert [r["name"] for r in data["m1"]["results"]] == [ + "format_sensitivity", "calibration", "generated:probe1", "mystery_probe"] + results = {r["name"]: r for r in data["m1"]["results"]} + assert results["format_sensitivity"]["headline"] == [ + {"label": "Answer Flip Rate after Shuffling", "value": "50.0%"}] + assert results["format_sensitivity"]["per_case"] == [{"sample_id": "c1", "format_flip_rate": 0.5}] + assert [h["value"] for h in results["calibration"]["headline"]] == ["0.125", None] + generated = results["generated:probe1"] + assert generated["display_name"] == "Agent-written probe · probe1" + assert generated["question"].endswith("…") and len(generated["question"]) == 178 + assert generated["description"] == LONG_NEED + assert generated["headline"] == [{"label": "flip rate", "value": "25.0%"}, + {"label": "mean gap", "value": "1.5"}] + assert (results["mystery_probe"]["display_name"], results["mystery_probe"]["findings"]) == ("Mystery Probe", {}) + + assert [s["tool"] for s in data["m2"]["stats"]] == ["t_big", "t_small", "t_null"] + assert data["m2"]["stats"][0] == { + "tool": "t_big", "config": {"k": 1}, "summary": "", "effect": -0.6, "ci": [-0.8, -0.4], + "reject": True, "p_value": None, "underpowered": False, "details": {}} + # No explore report was inlined, so the events' own sentences stand in. + assert [t["title"] for t in data["m2"]["explore"]["takeaways"]] == [ + "answers flip with option order", "Short answers fail more"] + assert data["agents"]["explore"] == {"code": "print(1)", "stdout": "1\n", "audit": {"files_read": 2}} + + assert data["m3"]["hypotheses"] == [{"id": "h1", "statement": "Option order drives the answer."}] + assert data["m4"]["results"] == [{ + "hypothesis_id": "h1", "hypothesis": None, "status": "supported", "effect_size": 0.4, + "confidence": 0.9, "verdict": "supported", "evidence_grade": None, "protocol_consistent": None, + "evidence": {"m4_effect_size": 0.4, "m4_verdict": "supported"}}] + assert data["m4"]["event"]["module"] == "m4" + assert [s["module"] for s in data["m5_surgery"]["surgeries"]] == ["m5"] + fix = data["m5_fix"] + assert (fix["ran"], fix["fixed"], fix["best"]["name"]) == (True, True, "think_first") + assert fix["selection"] == [{"name": "a"}] + assert fix["prompt_template"] == "Think first. {q}" + + +def test_a_run_with_no_summary_is_named_after_its_folder(tmp_path): + root = _run(tmp_path / "my_bench", [ + _event(1, "run_start", model="EndpointModel(qwen3.5-2b)", protocol="Answer the question."), + _event(2, "probe", "M1", analyzers=[]), + ]) + (root / "summary.json").write_text("{not json") + + data = extract_run_data(root) + + assert (data["run"]["model"], data["run"]["benchmark_name"]) == ("qwen3.5-2b", "my_bench") + assert data["run"]["protocol"] == "Answer the question." + assert data["m2"]["stats"] == [] and data["m3"]["hypotheses"] == [] + assert data["m4"] == {"ran": False, "results": [], "event": {}} + + +def test_only_the_latest_run_in_a_reused_directory_is_read(tmp_path): + earlier = {**_event(1, "run_start", model="old"), "trace_id": "earlier"} + stale = {**_event(2, "diagnosis", "M3", hypotheses=[{"id": "stale"}]), "trace_id": "earlier"} + root = _run(tmp_path / "outputs", [ + earlier, stale, + _event(3, "run_start", model="new"), + _event(4, "probe", "M1", analyzers=[]), + ]) + + data = extract_run_data(root) + + assert data["run"]["raw_model"] == "new" + assert data["m3"]["hypotheses"] == [] + + +def test_per_case_repair_outcomes_come_from_the_confirmation_attempts(): + from evalrx.reporting.report_inputs import _repair_outcomes + + fix = _event(1, "fix", "M5", module="fix", + selection_attempted=[{"name": "swept", "outputs": {"c9": "ignored"}}], + attempted=[ + {"name": "first", "tier": "L1", "outputs": {"c1": "A", "c2": "B"}, "fixed_cases": ["c1"]}, + {"name": "second", "tier": "L2", "outputs": {"c2": "C", "c3": "D"}, "broken_cases": ["c3"]}, + {"name": "never_ran", "outputs": None}, + ]) + + assert _repair_outcomes([_event(0, "probe", "M1"), fix]) == { + "c1": {"candidate": "first", "tier": "L1", "status": "fixed", "output": "A"}, + # A later attempt on the same case is the one the report shows. + "c2": {"candidate": "second", "tier": "L2", "status": "unchanged", "output": "C"}, + "c3": {"candidate": "second", "tier": "L2", "status": "broken", "output": "D"}, + } + + +def test_the_report_names_the_agent_that_drove_the_run(): + from evalrx.reporting.dynamic import _diagnosed_by + + assert _diagnosed_by({"coder": "claude_code:claude-opus-5"}) == "Claude Code · claude-opus-5" + assert _diagnosed_by({"coder": "codex"}) == "Codex" + assert _diagnosed_by({"coder": "some_new_cli:m"}) == "some_new_cli · m" + assert _diagnosed_by({}) == "" + + +def test_a_log_without_the_event_sequence_is_refused_by_name(tmp_path): + import pytest + + from evalrx.reporting.run_events import read_run_events + + root = _run(tmp_path / "outputs", [_event(1, "run_start"), _event(2, "probe", "M1", analyzers=[])]) + path = root / "logs" / "M1" / "log.json" + doc = json.loads(path.read_text()) + del doc["probe"][0]["event_seq"] + path.write_text(json.dumps(doc)) + + with pytest.raises(ValueError, match="written by an earlier log format"): + read_run_events(root) diff --git a/tests/test_analyzers/test_prompt_contrast.py b/tests/test_analyzers/test_prompt_contrast.py index 250ea2ce..9422571e 100755 --- a/tests/test_analyzers/test_prompt_contrast.py +++ b/tests/test_analyzers/test_prompt_contrast.py @@ -99,22 +99,19 @@ def test_default_score_word_boundary(): def test_stats_layer_runs_paired_contrasts(): - from evalrx.analysis.stats_tools import ( - build_stats_input, - default_plan, - run_stats_tool, - ) + from evalrx.analysis.planner import plan_stats_input + from evalrx.analysis.stats_tools import build_stats_input, run_stats_tool batch = _batch() res = PromptContrastAnalyzer().run(InterventionModel(), batch) inp = build_stats_input({"prompt_contrast": res}, batch) assert set(inp.groups) == {"baseline", "describe_first", "sensitive"} - plan = default_plan(inp) - tools = [t for t, _, _ in plan] + plan = plan_stats_input(inp) + tools = [item.tool for item in plan] assert "friedman_nemenyi" in tools # Pairwise paired contrasts against the baseline strategy. - pairs = [c["strategies"] for t, c, _ in plan if t == "mcnemar_evalue"] + pairs = [item.config["strategies"] for item in plan if item.tool == "mcnemar_evalue"] assert ["baseline", "describe_first"] in pairs assert ["baseline", "sensitive"] in pairs diff --git a/tests/test_benchmark/test_runner_run.py b/tests/test_benchmark/test_runner_run.py new file mode 100644 index 00000000..0a6cada4 --- /dev/null +++ b/tests/test_benchmark/test_runner_run.py @@ -0,0 +1,266 @@ +"""runner.run end to end, with the model, the judge and the stage calls faked. + +What is real: the argument parser, the RunContext and its logger, the label +quarantine around the fix stage, and every agent the runner constructs. +""" + +from __future__ import annotations + +import json +from types import SimpleNamespace + +import pytest + +from evalrx.benchmark import runner +from evalrx.benchmark.models import resolve +from evalrx.benchmark.run import build_parser +from evalrx.benchmark.tasks import get +from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label +from evalrx.eval_agent import CaseDiscoveryAgent, VLDiagnoseLoop +from evalrx.eval_agent.loop_reports import AutoDiagnoseReport +from evalrx.eval_agent.stages.fix.tiers import FixTier +from evalrx.eval_agent.stages.fix.types import FixCandidate, FixOutcome, FixValidation +from evalrx.reporting.run_events import read_run_events +from evalrx.specs import get_spec +from tests.conftest import FakeModel + +GEN = {"do_sample": True, "temperature": 0.6, "top_p": 0.95} + + +def _batch(prefix: str, n: int) -> CaseBatch: + return CaseBatch([ + FailureCase(id=f"{prefix}{i}", inputs=Inputs(prompt=f"{prefix} question {i}"), expected="A", + observed="A" if i % 2 else "B", label=Label.PASS if i % 2 else Label.FAIL) + for i in range(n) + ]) + + +class Cell: + """One faked benchmark cell; ``calls`` is the order the runner reached things in.""" + + def __init__(self, monkeypatch, tmp_path): + self.monkeypatch = monkeypatch + self.tmp_path = tmp_path + self.calls: list[str] = [] + self.loop = None + self.fix_kwargs: dict = {} + self.hidden_during_fix: bool | None = None + self.report = AutoDiagnoseReport(cycles=1, stopped_by="agent_stop") + self.outcome = FixOutcome( + max_tier=FixTier.L2_SCAFFOLD, + attempted=[FixValidation( + candidate=FixCandidate(tier=FixTier.L1_PROMPT, name="think_first", payload={}), + n_fixed=2, n_broken=1, effect=0.125, fixed=True)], + recommendation={"recommend_tier": "L3a"}, + ) + self.m5_proposal = SimpleNamespace(status="supported") + self.has_m4_groups = True + + def run(self, *argv: str, modality: str = "llm", dataset: str = "bbh_causal_judgement", + model: str = "gemini-3.6-flash", backend: str | None = "gemini", model_obj=None) -> int: + cell = self + patch = self.monkeypatch.setattr + args = build_parser().parse_args([ + "--modality", modality, "--model", model, "--dataset", dataset, + "--run-dir", str(self.tmp_path / "runs"), *argv]) + resolved = resolve(args.model, modality, backend) + self.run_dir = runner.run_dir_for(args, get(dataset)) + target = model_obj or FakeModel() + + def build_judge(_args): + cell.calls.append("judge") + return FakeModel(), "claude", None, () + + def load_model(*_a): + cell.calls.append("load_model") + return target, dict(GEN), get_spec(resolved.spec_key) + + def discover(_agent, _model, candidates, protocol=None): + cell.calls.append(f"discover:{len(candidates)}") + batch = CaseBatch(list(candidates)) + return SimpleNamespace(cases=batch, n_pass=len(batch) // 2, n_fail=len(batch) - len(batch) // 2, + n_unknown=0, has_m4_groups=cell.has_m4_groups) + + def loop_run(loop, data): + mode = type(loop.policy).__name__ + cell.calls.append(f"loop.run:{mode}:{len(data)}") + cell.loop = loop + return cell.report + + def run_m5(_loop, _report, _cases, allow_unverified=False): + cell.calls.append(f"run_m5:allow_unverified={allow_unverified}") + return cell.m5_proposal + + def run_fix(_loop, _report, _cases, **kwargs): + cell.calls.append("run_fix") + cell.fix_kwargs = kwargs + cell.hidden_during_fix = not (cell.run_dir / "baseline.json").exists() + return cell.outcome + + patch(runner, "ensure_manifest", lambda *a: self.tmp_path / "manifest.json") + patch(runner, "ensure_val_manifest", lambda *a: self.tmp_path / "val_manifest.json") + patch(runner.T, "build_cases", lambda _task, manifest, _limit: ( + _batch("v" if "val" in manifest.name else "c", 4 if "val" in manifest.name else 8), + [{"sample_seed": 11}])) + patch(runner, "build_judge", build_judge) + patch(runner, "load_model", load_model) + patch(CaseDiscoveryAgent, "discover", discover) + patch(VLDiagnoseLoop, "run", loop_run) + patch(VLDiagnoseLoop, "run_m5", run_m5) + patch(VLDiagnoseLoop, "run_fix", run_fix) + return runner.run(args, get(dataset), resolved) + + def read(self, name: str) -> dict: + return json.loads((self.run_dir / name).read_text()) + + def config(self) -> dict: + """The run configuration as the finished log records it.""" + return self.read("logs/run.json")["manifest"]["config"] + + def events(self) -> list[str]: + return [e["event"] for e in read_run_events(self.run_dir / "logs")] + + +@pytest.fixture +def cell(monkeypatch, tmp_path): + return Cell(monkeypatch, tmp_path) + + +def test_a_full_cell_runs_discovery_diagnosis_m5_and_the_fix_then_closes_the_log(cell, capsys): + assert cell.run() == 0 + + assert cell.calls == ["judge", "load_model", "discover:8", "loop.run:JudgePolicy:8", + "run_m5:allow_unverified=True", "run_fix"] + # The gemini backend exposes no internals, so the default L3b ladder stops at L2. + assert cell.fix_kwargs == {"max_tier": "L2", "auto_escalate": cell.fix_kwargs["auto_escalate"], + "allow_unverified": True} + assert cell.hidden_during_fix is True + assert (cell.run_dir / "baseline.json").exists() + + baseline = cell.read("baseline.json") + assert (baseline["n"], baseline["n_pass"], baseline["n_fail"], baseline["accuracy"]) == (8, 4, 4, 0.5) + assert baseline["cases"][0] == {"id": "c0", "expected": "A", "observed": "B", "label": "fail"} + assert baseline["generation_kwargs"] == GEN + assert cell.read("summary.json") == { + "model": "gemini-3.6-flash", "spec": baseline["spec"], "dataset": "bbh_causal_judgement", + "modality": "llm", "backend": "gemini", "n_cases": 8, "baseline_accuracy": 0.5, "cycles": 1, + "stopped_by": "agent_stop", "n_verified": 0, + "fix": {"recommendation": "{'recommend_tier': 'L3a'}", + "attempted": [{"tier": "L1", "name": "think_first", "fixed": True, "repairs": 2, + "breaks": 1, "effect": 0.125}]}, + "diagnosis_status": "completed", "fix_tier": "L2", + } + assert (cell.run_dir / "api_capabilities.json").exists() + + # The loop is faked, so the log holds only what the runner itself writes. + assert cell.events() == ["diagnose_report", "run_end"] + assert cell.config()["n_cases"] == 8 + + out = capsys.readouterr().out + assert "Baseline: PASS=4, FAIL=4, UNKNOWN=0, accuracy=0.500" in out + assert "Diagnosis: stopped_by=agent_stop, cycles=1, verified=0" in out + assert "[fix] --fix-tier L3b clamped to L2" in out + assert "M5 experiment on the UNVERIFIED (best lead) hypothesis: status=supported" in out + assert "Fix [L1] think_first: fixed=True, repairs=2, breaks=1, effect=+0.125" in out + assert "Done. Tidy M1-M5 logs:" in out + + +def test_the_loop_is_wired_from_the_arguments(cell): + cell.run("--max-actions", "5", "--confirm-split", "0.25") + + loop = cell.loop + assert (loop.policy.max_actions, loop.max_cycles, loop.confirm_split, loop.m4_holdout) == (5, 1, 0.25, False) + assert loop.val_data is None and loop.explorer is not None + assert loop.probe_agent.allow_codegen is True + assert loop.fix_agent.proposer._floor_candidates == () + config = cell.config() + assert (config["m1_workers"], config["m1_codegen"], config["m1_selection"], config["m2_codegen"]) == ( + 8, True, "judge", True) + assert (config["split_mode"], config["n_cases"], config["manifest_seed"]) == ("explore_confirm", 8, 11) + + +def test_a_diagnosis_error_still_writes_the_summary_and_returns_2(cell): + cell.report = AutoDiagnoseReport(cycles=2, stopped_by="diagnosis_error") + + assert cell.run("--skip-fix") == 2 + assert cell.calls[-1] == "loop.run:JudgePolicy:8" + summary = cell.read("summary.json") + assert (summary["diagnosis_status"], summary["fix"], summary["cycles"]) == ("error", None, 2) + assert cell.events()[-1] == "run_end" + + +def test_skip_m5_goes_straight_to_the_fix(cell, capsys): + assert cell.run("--skip-m5") == 0 + assert cell.calls[-2:] == ["loop.run:JudgePolicy:8", "run_fix"] + assert "M5: skipped by --skip-m5" in capsys.readouterr().out + + +@pytest.mark.parametrize("flags, scope", [ + (["--fix-candidate", "self_consistency_5"], "self_consistency_5"), + (["--code-only"], "coded_pipeline"), + (["--registered-repairs-only"], "registered methods"), +]) +def test_a_pre_registered_fix_scope_skips_m5(cell, capsys, flags, scope): + assert cell.run(*flags) == 0 + assert "run_m5:allow_unverified=True" not in cell.calls and cell.calls[-1] == "run_fix" + assert f"M5: skipped for pre-registered fix scope {scope!r}" in capsys.readouterr().out + + +def test_m5_with_nothing_to_test_says_so(cell, capsys): + cell.m5_proposal = None + assert cell.run() == 0 + assert "M5: no hypothesis to experiment on" in capsys.readouterr().out + + +def test_baseline_only_needs_no_judge_and_writes_no_log(cell, capsys): + assert cell.run("--baseline-only") == 0 + assert cell.calls == ["load_model", "discover:8"] + assert cell.read("baseline.json")["n"] == 8 + assert not (cell.run_dir / "logs").exists() and not (cell.run_dir / "summary.json").exists() + assert "Done (baseline only)." in capsys.readouterr().out + + +def test_download_only_stops_after_the_manifest(cell): + assert cell.run("--download-only") == 0 + assert cell.calls == [] + + +def test_a_one_sided_baseline_cannot_be_diagnosed(cell): + cell.has_m4_groups = False + with pytest.raises(SystemExit, match="M4 needs both PASS and FAIL cases"): + cell.run() + assert cell.calls == ["judge", "load_model", "discover:8"] + + +def test_held_out_labels_a_separate_validation_set_for_the_fixed_loop(cell, capsys): + assert cell.run("--diagnosis-mode", "fixed", "--held-out", "--skip-fix") == 0 + + assert cell.calls == ["judge", "load_model", "discover:8", "discover:4", "loop.run:FixedOrderPolicy:8"] + assert cell.loop.m4_holdout is True and [c.id for c in cell.loop.val_data] == ["v0", "v1", "v2", "v3"] + val = cell.read("baseline_val.json") + assert (val["role"], val["n"], val["n_pass"], val["accuracy"]) == ("validation", 4, 2, 0.5) + config = cell.config() + assert (config["split_mode"], config["n_val_cases"], config["held_out"]) == ("held_out_val", 4, True) + assert config["m1_selection"] == "pinned" + assert "Validation baseline: PASS=2, FAIL=2, accuracy=0.500" in capsys.readouterr().out + + +def test_weights_are_loaded_before_the_timed_discovery_pass(cell, capsys): + class Loadable(FakeModel): + runtime = SimpleNamespace(attn_impl="sdpa") + + def load(self): + cell.calls.append("load_weights") + + assert cell.run("--baseline-only", model_obj=Loadable()) == 0 + assert cell.calls == ["load_model", "load_weights", "discover:8"] + assert "(attn_impl=sdpa); generation=" in capsys.readouterr().out + + +def test_a_deployed_baseline_spec_becomes_the_model_under_test(cell, tmp_path): + spec_file = tmp_path / "winner.json" + spec_file.write_text(json.dumps({"payload": {"name": "vote3", "n_samples": 3, "strategy": "majority"}})) + + assert cell.run("--baseline-spec", str(spec_file)) == 0 + assert type(cell.loop.model).__name__ == "SpecPipelineModel" + assert cell.loop.fix_agent.proposer._deployed_spec["name"] == "vote3" diff --git a/tests/test_contract/test_pipeline_emission.py b/tests/test_contract/test_pipeline_emission.py index bcd3843c..83c38f8d 100644 --- a/tests/test_contract/test_pipeline_emission.py +++ b/tests/test_contract/test_pipeline_emission.py @@ -19,7 +19,8 @@ from evalrx.eval_agent import DiagnosisAgent, RunContext, VLDiagnoseLoop from evalrx.eval_agent.stages.protocol import ExperimentProtocol from tests.conftest import FakeModel -from tests.test_eval_agent.test_vl_diagnose import ScriptedModel +from tests.judge_replies import hypothesis, proposal +from tests.test_eval_agent.test_vl_diagnose import M3Judge pytest.importorskip("pydantic") @@ -51,10 +52,9 @@ def _batch(n_fail: int = 3, n_pass: int = 3, **slots) -> CaseBatch: def _judge() -> DiagnosisAgent: - return DiagnosisAgent(judge=ScriptedModel([ - '[{"hypothesis": "The model ignores the modality under test.", ' - '"failure_mode": "attention", "test": "attention.entropy"}]' - ])) + return DiagnosisAgent(judge=M3Judge(proposal(hypothesis( + "The model ignores the modality under test.", "attention", test="attention.entropy", + )))) def _run(tmp_path, model, cases) -> "tuple[dict, RunContext]": diff --git a/tests/test_contract/test_realistic_judge.py b/tests/test_contract/test_realistic_judge.py index c2c44d44..a5621e0c 100644 --- a/tests/test_contract/test_realistic_judge.py +++ b/tests/test_contract/test_realistic_judge.py @@ -8,7 +8,7 @@ So the fixtures here are deliberately shabby, in the exact ways a cheap model on low effort was observed to be shabby: -* it proposes a mechanism and no way to be wrong about it (no ``TEST:`` line), +* it proposes a mechanism and no way to be wrong about it (no ``test`` field), * it leaves ``Hypothesis.id`` empty, because nothing in the loop fills it, * the model under test declares tool calling, because every chat model served over an OpenAI-compatible endpoint does. @@ -28,7 +28,8 @@ from evalrx.eval_agent import DiagnosisAgent, RunContext, VLDiagnoseLoop from evalrx.eval_agent.stages.protocol import ExperimentProtocol from tests.conftest import FakeModel -from tests.test_eval_agent.test_vl_diagnose import ScriptedModel +from tests.judge_replies import proposal +from tests.test_eval_agent.test_vl_diagnose import M3Judge pytest.importorskip("pydantic") @@ -37,19 +38,21 @@ DiagnosisOutput, HypothesisTestOutput, ProbeOutput, + StatsReportWire, ) #: What the judge returned on the live run: a mechanism, a failure mode, and no -#: `test` key at all. The parser accepts it and `test_design` comes out "". +#: `test` key at all (no plain_statement either). The schema accepts it and +#: `test_design` comes out "". NO_TEST_RESPONSE = ( - '[{"hypothesis": "The model gives unstable answers across resamples.", ' - '"failure_mode": "self_consistency"}]' + '{"hypotheses": [{"hypothesis": "The model gives unstable answers across resamples.", ' + '"failure_mode": "self_consistency"}]}' ) #: The same claim WITH the commitment to how it could be wrong. WITH_TEST_RESPONSE = ( - '[{"hypothesis": "The model gives unstable answers across resamples.", ' - '"failure_mode": "self_consistency", "test": "self_consistency.consistency"}]' + '{"hypotheses": [{"hypothesis": "The model gives unstable answers across resamples.", ' + '"failure_mode": "self_consistency", "test": "self_consistency.consistency"}]}' ) @@ -90,7 +93,7 @@ def _run(tmp_path, judge_response: str, model=None, cases=None): description="Does the model answer these consistently?", task_domain="reasoning", ), - diagnosis_agent=DiagnosisAgent(judge=ScriptedModel([judge_response])), + diagnosis_agent=DiagnosisAgent(judge=M3Judge(judge_response)), max_cycles=1, run_logger=ctx.logger, ).run(cases if cases is not None else _batch()) return {p.name: p for p in (ctx.root / "contract").glob("*.json")} @@ -166,8 +169,8 @@ def test_omitting_the_test_design_is_currently_the_more_permissive_path(tmp_path Same batch, same analyzers, same statistics. The ONLY difference is whether the judge said in advance how its claim could be wrong: - no TEST: line -> SUPPORTED (verdict_fallback searches every signal) - a TEST: line -> INCONCLUSIVE (the named test did not run, and + no test field -> SUPPORTED (verdict_fallback searches every signal) + a test field -> INCONCLUSIVE (the named test did not run, and hypothesis_tester refuses substitutes) The strict half is deliberate and documented in hypothesis_tester: "An @@ -233,9 +236,29 @@ def test_a_batch_that_does_carry_trajectories_is_an_agent_run(tmp_path): # ── a judge that fails outright ────────────────────────────────────────────── -def test_an_empty_judge_response_does_not_corrupt_the_contract(tmp_path): - """A rate-limited judge returns "". The run should degrade, not lie.""" - files = _run(tmp_path, "") +@pytest.mark.parametrize("response", ["", "I think the model is just bad at this, honestly."], + ids=["empty", "prose"]) +def test_an_unreadable_judge_response_fails_m3_without_corrupting_the_contract(tmp_path, response): + """A rate-limited judge returns "", a lazy one returns prose. The run should + degrade, not lie: M3 is retried, then recorded as failed with every exchange, + and no M3 payload claims a completed diagnosis that found nothing.""" + import json + + files = _run(tmp_path, response) + assert not [n for n in files if n.endswith(".invalid.json")], sorted(files) + _latest(files, "m1", ProbeOutput) # the stages that ran still decode + _latest(files, "m2", StatsReportWire) + assert not [n for n in files if n.endswith(".m3.json")], sorted(files) + + calls = json.loads((tmp_path / "run" / "M3" / "log.json").read_text())["model_calls"] + judge_calls = [c for c in calls if c["role"] == "diagnosis_judge"] + assert judge_calls and all(c["output"] == response for c in judge_calls) + failures = [c for c in calls if c["role"] == "diagnosis"] + assert failures and all("JudgeOutputError" in c["error"] for c in failures) + + +def test_a_judge_that_finds_nothing_is_a_completed_empty_result(tmp_path): + files = _run(tmp_path, proposal()) assert not [n for n in files if n.endswith(".invalid.json")], sorted(files) m3 = _latest(files, "m3", DiagnosisOutput) # Zero hypotheses is a completed, empty result -- not an error, and not a @@ -244,26 +267,12 @@ def test_an_empty_judge_response_does_not_corrupt_the_contract(tmp_path): assert m3.status.state.value in ("empty", "succeeded") -def test_a_malformed_judge_response_does_not_corrupt_the_contract(tmp_path): - files = _run(tmp_path, "I think the model is just bad at this, honestly.") - assert not [n for n in files if n.endswith(".invalid.json")], sorted(files) - _latest(files, "m3", DiagnosisOutput) # decodes, whatever it contains - - # ── M2 must actually ship its statistics ───────────────────────────────────── -def test_m2_serializes_the_typed_verdicts_not_the_legacy_summaries(): - """StatsAnalysisReport carries two similarly named lists with different shapes. - - stats_results list[StatsToolResult] -- the per-tool verdicts - stats_tool_results list[dict] -- legacy JSON-safe summaries, - keyed by `name`, no `tool` - - Reading the second and filtering on `tool` dropped every result. A live run - shipped M2 with zero statistics next to corrected_rejections.n_tested=16 -- - and "nothing was tested" is a legitimate state, so nothing downstream could - tell the empty payload was a field mix-up. - """ +def test_m2_serializes_every_typed_verdict(): + """A live run once shipped M2 with zero statistics next to + corrected_rejections.n_tested=16, and "nothing was tested" is a legitimate + state, so nothing downstream could tell the payload had lost its rows.""" from evalrx.analysis.stats_agent import StatsAnalysisReport from evalrx.analysis.stats_tools import StatsToolResult from evalrx.contract.emit import from_stats_report @@ -275,8 +284,6 @@ def test_m2_serializes_the_typed_verdicts_not_the_legacy_summaries(): analysis_key="signal_label_assoc:self_consistency.consistency"), StatsToolResult(tool="mcnemar_evalue", ok=True, effect=0.1, reject=False), ], - # Populated too, and first in the old lookup order -- the whole trap. - stats_tool_results=[{"name": "scalar_summary", "metrics": {"n_scalar_metrics": 52}}], corrected_rejections={"method": "BH", "alpha": 0.05, "n_tested": 2, "rejected_result_keys": []}, ) diff --git a/tests/test_contract/test_stage_detail.py b/tests/test_contract/test_stage_detail.py index f2cfa35a..d29e8445 100644 --- a/tests/test_contract/test_stage_detail.py +++ b/tests/test_contract/test_stage_detail.py @@ -27,6 +27,28 @@ def test_a_real_runs_stage_detail_conforms(): StageDetail.model_validate(data["stage_detail"]) +@pytest.mark.parametrize("example", ["synthetic_yield_explore", "deco_hallu_explore"]) +def test_an_explore_output_conforms(example): + from evalrx.reporting.dynamic import build_report_data + + root = Path(__file__).resolve().parents[2] / "examples/m2_m3" / example / "reference_output" + StageDetail.model_validate(build_report_data(root)["stage_detail"]) + + +def test_a_fused_output_conforms(tmp_path): + from evalrx.analysis.fused_pipeline import FusedReport, FusedSignal + from evalrx.reporting.dynamic import build_report_data + + report = FusedReport( + question="q", ok=True, observations=["o"], caveats=["c"], + candidate_signals=[FusedSignal(name="s", source="explorer", reject=True, effect=0.3, + ci=(0.1, 0.5), p_value=0.01)], + recommended_confirmatory_tests=["t"], conclusion="c", + ) + (tmp_path / "fused_report.json").write_text(json.dumps(report.to_dict()), encoding="utf-8") + StageDetail.model_validate(build_report_data(tmp_path)["stage_detail"]) + + def test_a_full_m1_to_m5_run_conforms(tmp_path): from evalrx.reporting.dynamic import build_report_data from tests.test_analysis.test_case_study_sheet import make_run @@ -38,14 +60,14 @@ def test_a_full_m1_to_m5_run_conforms(tmp_path): def test_a_logged_run_with_examples_and_a_repair_conforms(tmp_path): from evalrx.core import CaseBatch, FailureCase, Label, Result - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.reporting.dynamic import build_report_data cases = CaseBatch([ FailureCase.from_prompt("Q1", id="c1", expected="a", observed="b", label=Label.FAIL), FailureCase.from_prompt("Q2", id="c2", expected="a", observed="a", label=Label.PASS), ]) - logger = RunLoggerV2(tmp_path, observability_mode="offline") + logger = RunLogger(tmp_path, observability_mode="offline") logger.log_run_start({"model": "demo", "n_cases": 2}) logger.log_cases(cases) logger.log_probe(0, {"format_check": Result( @@ -66,10 +88,10 @@ def test_a_logged_run_with_examples_and_a_repair_conforms(tmp_path): def test_an_empty_run_conforms(tmp_path): - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.reporting.dynamic import build_report_data - logger = RunLoggerV2(tmp_path, observability_mode="offline") + logger = RunLogger(tmp_path, observability_mode="offline") logger.log_run_start({"model": "demo", "n_cases": 0}) logger.close() StageDetail.model_validate(build_report_data(tmp_path)["stage_detail"]) diff --git a/tests/test_contract/test_wire_guards.py b/tests/test_contract/test_wire_guards.py index 88e947d8..d5976ea2 100644 --- a/tests/test_contract/test_wire_guards.py +++ b/tests/test_contract/test_wire_guards.py @@ -140,7 +140,7 @@ def test_descriptive_report_may_not_ship_a_verdict(): StatsReportWire( **_envelope("m2"), descriptive_only=True, corrected_rejections=CorrectedRejections( - method="ebh", deferred=False, rejected_result_keys=["k1"], + method="e-BH", deferred=False, rejected_result_keys=["k1"], ), ) diff --git a/tests/test_core/test_judge_call.py b/tests/test_core/test_judge_call.py new file mode 100644 index 00000000..fb0db282 --- /dev/null +++ b/tests/test_core/test_judge_call.py @@ -0,0 +1,136 @@ +"""ask_judge: typed output, validation retry with feedback, loud failure.""" + +from __future__ import annotations + +import asyncio +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from typing import Literal + +import pytest +from pydantic import BaseModel, Field, ValidationError + +from evalrx.agent_runtime.judge_call import ( + JudgeCallError, + JudgeOutputError, + ask_judge, + validate_reply, +) + + +class Pick(BaseModel): + tool: Literal["probe", "stats"] + rationale: str = Field(min_length=1) + + +class ScriptedJudge: + def __init__(self, *replies: str) -> None: + self.replies = list(replies) + self.prompts: list[str] = [] + + def generate(self, prompt: str, **kwargs) -> str: + self.prompts.append(prompt) + return self.replies.pop(0) + + +def test_valid_json_in_prose_and_fences_is_one_call(): + judge = ScriptedJudge('Sure:\n```json\n{"tool": "stats", "rationale": "next"}\n```\nDone.') + reply = ask_judge(judge, "pick one", Pick, role="decide") + assert reply.output == Pick(tool="stats", rationale="next") + assert len(judge.prompts) == 1 + assert '"tool"' in judge.prompts[0] and "pick one" in judge.prompts[0] # schema + request + assert [e.attempt for e in reply.exchanges] == [1] + assert reply.raw.startswith("Sure:") + + +def test_invalid_answer_is_sent_back_with_the_errors(): + judge = ScriptedJudge('{"tool": "launch", "rationale": "x"}', '{"tool": "probe", "rationale": "ok"}') + reply = ask_judge(judge, "pick one", Pick, role="decide", retries=1) + assert reply.output.tool == "probe" + second = judge.prompts[1] + assert "Your previous answer:" in second and "That answer could not be used:" in second + assert '"launch"' in second # the judge sees its own answer ... + assert "probe" in second and "stats" in second # ... and what was allowed + assert [e.record()["metadata"]["attempt"] for e in reply.exchanges] == [1, 2] + + +def test_exhausted_retries_raise_with_every_exchange(): + judge = ScriptedJudge("no json here", "still none") + with pytest.raises(JudgeOutputError) as info: + ask_judge(judge, "pick one", Pick, role="decide", retries=1) + assert [e.output for e in info.value.exchanges] == ["no json here", "still none"] + assert info.value.raw == "still none" + + +def test_a_failing_judge_raises_judge_call_error(): + class Broken: + def generate(self, prompt, **kwargs): + raise RuntimeError("account limit reached") + + with pytest.raises(JudgeCallError, match="account limit") as info: + ask_judge(Broken(), "pick one", Pick, role="decide") + (exchange,) = info.value.exchanges + assert exchange.output is None and "account limit" in exchange.error + + +def test_check_asks_for_a_revision_then_accepts_on_the_last_attempt(): + judge = ScriptedJudge(*['{"tool": "probe", "rationale": "jargon"}'] * 2) + reply = ask_judge( + judge, "pick", Pick, role="decide", retries=1, + check=lambda p: "too technical" if p.rationale == "jargon" else None, + ) + assert reply.output.rationale == "jargon" + assert len(judge.prompts) == 2 and "too technical" in judge.prompts[1] + + +def test_images_reach_only_a_judge_that_takes_them(tmp_path: Path): + figure = tmp_path / "fig.png" + figure.write_bytes(b"png") + seen = {} + + class Seeing: + def generate(self, prompt, *, images=None): + seen["images"] = images + return '{"tool": "probe", "rationale": "r"}' + + reply = ask_judge(Seeing(), "p", Pick, role="r", images=[figure]) + assert seen["images"] == [figure] + assert reply.exchanges[0].record()["inputs"]["images"] == [str(figure)] + blind = ScriptedJudge('{"tool": "probe", "rationale": "r"}') + assert ask_judge(blind, "p", Pick, role="r", images=[figure]).exchanges[0].images == () + + +def test_works_from_threads_and_inside_a_running_event_loop(): + def one(_): + return ask_judge(ScriptedJudge('{"tool": "probe", "rationale": "r"}'), "p", Pick, role="r").output.tool + + with ThreadPoolExecutor(4) as pool: + assert list(pool.map(one, range(4))) == ["probe"] * 4 + + async def inside(): + return one(0) + + assert asyncio.run(inside()) == "probe" + + +def test_a_cited_reference_before_the_answer_is_skipped(): + # "[2]" is valid JSON but not a Pick; the object after it is. + judge = ScriptedJudge('As finding [2] shows: {"tool": "stats", "rationale": "next"}') + assert ask_judge(judge, "p", Pick, role="r").output.tool == "stats" + assert len(judge.prompts) == 1 + + +def test_a_list_wrapped_in_an_object_is_found(): + from pydantic import RootModel + + class Items(RootModel[list[dict]]): + pass + + assert validate_reply('{"candidates": [{"name": "a"}]}', Items).root == [{"name": "a"}] + + +def test_validate_reply_reports_the_first_values_error_or_no_json(): + with pytest.raises(ValueError, match="no JSON"): + validate_reply("nothing", Pick) + with pytest.raises(ValidationError, match="tool"): + validate_reply('see {this} then {"rationale": "r"}', Pick) diff --git a/tests/test_core/test_load_and_config.py b/tests/test_core/test_load_and_config.py index 23dda369..0ffa7e3e 100755 --- a/tests/test_core/test_load_and_config.py +++ b/tests/test_core/test_load_and_config.py @@ -11,7 +11,7 @@ from evalrx.config import ModelConfig, load_config from evalrx.core import Capability, CapabilityError -from evalrx.models import load, load_model, resolve_spec_key +from evalrx.models import load, load_model from evalrx.models.backends.api import APIModel from evalrx.models.backends.hf.model import HFLocalModel @@ -23,14 +23,8 @@ def test_load_spec_key_returns_hf_local(): assert {Capability.GENERATE, Capability.ATTENTION, Capability.HIDDEN_STATES} <= model.capabilities -def test_load_alias_resolves(): - assert resolve_spec_key("qwen") == "qwen2.5-7b-instruct" - model = load("qwen") - assert model.spec.key == "qwen2.5-7b-instruct" - - def test_load_unknown_key_raises(): - with pytest.raises(ValueError, match="Unknown model"): + with pytest.raises(KeyError, match="Unknown model spec 'not-a-real-model'"): load("not-a-real-model") @@ -59,7 +53,7 @@ def test_load_checkpoint_override(): # -- load_model(ModelConfig) ------------------------------------------ def test_load_model_from_config(): - model = load_model(ModelConfig(name="qwen")) + model = load_model(ModelConfig(name="qwen2.5-7b-instruct")) assert isinstance(model, HFLocalModel) assert model.spec.key == "qwen2.5-7b-instruct" @@ -71,7 +65,7 @@ def test_load_model_backend_and_want_from_config(): def test_load_model_unknown_raises(): - with pytest.raises(ValueError, match="Unknown model"): + with pytest.raises(KeyError, match="Unknown model spec 'nope'"): load_model(ModelConfig(name="nope")) diff --git a/tests/test_core/test_pipeline_and_run.py b/tests/test_core/test_pipeline_and_run.py index 8fac735c..7d5804ed 100755 --- a/tests/test_core/test_pipeline_and_run.py +++ b/tests/test_core/test_pipeline_and_run.py @@ -28,7 +28,7 @@ def test_run_entrypoint_with_config(tmp_path, monkeypatch): import evalrx cfg_file = tmp_path / "c.yaml" - cfg_file.write_text("model: qwen\nanalysis: attention\n") + cfg_file.write_text("model: qwen2.5-7b-instruct\nanalysis: attention\n") config = evalrx.load_config(cfg_file) # Swap the real Qwen for a FakeModel so no weights are loaded. @@ -36,13 +36,3 @@ def test_run_entrypoint_with_config(tmp_path, monkeypatch): result = evalrx.run(config, "the capital of france is") assert isinstance(result, AttentionResult) - -def test_run_strips_legacy_call_prefix(tmp_path, monkeypatch): - import evalrx - - cfg_file = tmp_path / "c.yaml" - cfg_file.write_text("model: qwen\nanalysis: call_attention\n") # old style - config = evalrx.load_config(cfg_file) - monkeypatch.setattr(evalrx, "load_model", lambda cfg: FakeModel()) - result = evalrx.run(config, "x") - assert isinstance(result, AttentionResult) diff --git a/tests/test_core/test_registry_and_shim.py b/tests/test_core/test_registry_and_shim.py index 0a7b9187..9c7117bf 100755 --- a/tests/test_core/test_registry_and_shim.py +++ b/tests/test_core/test_registry_and_shim.py @@ -18,13 +18,6 @@ def test_models_live_in_specs(): assert "qwen2.5-7b-instruct" in list_specs() -def test_registry_models_is_deprecated_shim(): - # registry.models still works but warns and delegates to specs. - with pytest.warns(DeprecationWarning): - names = registry.models.list() - assert "qwen2.5-7b-instruct" in names - - def test_analyzers_registered(): names = registry.analyzers.list() assert "attention" in names diff --git a/tests/test_datasets/test_datasets.py b/tests/test_datasets/test_datasets.py index a8675cbc..86a6be74 100755 --- a/tests/test_datasets/test_datasets.py +++ b/tests/test_datasets/test_datasets.py @@ -10,7 +10,6 @@ from evalrx.datasets import ( GUIOSDataset, LLMQADataset, - PureQADataset, Spatial457Dataset, TextVQASizeDataset, VLMQADataset, @@ -29,18 +28,14 @@ def test_llm_qa_sample_loads(): assert "llm_qa" in c.tags and c.metadata["difficulty"] == "easy" -def test_pure_qa_is_llm_qa_alias(): - assert PureQADataset is LLMQADataset # back-compat - - -def test_pure_qa_from_records_and_jsonl(tmp_path): +def test_llm_qa_from_records_and_jsonl(tmp_path): recs = [{"question": "q1", "answer": "a1"}, {"question": "q2", "answer": "a2"}] - cb = PureQADataset.from_records(recs).load() + cb = LLMQADataset.from_records(recs).load() assert len(cb) == 2 and cb[1].expected == "a2" p = tmp_path / "qa.jsonl" p.write_text("\n".join(json.dumps(r) for r in recs)) - cb2 = PureQADataset.from_jsonl(str(p)).load() + cb2 = LLMQADataset.from_jsonl(str(p)).load() assert len(cb2) == 2 and cb2[0].inputs.prompt == "q1" diff --git a/tests/test_docs_imports.py b/tests/test_docs_imports.py new file mode 100644 index 00000000..37692f03 --- /dev/null +++ b/tests/test_docs_imports.py @@ -0,0 +1,48 @@ +"""Every `from evalrx... import ...` in the docs' Python examples resolves. + +The examples mostly need a model, so they can't run here; but a renamed or +removed name is the drift readers hit first, and that much is checkable. +""" + +from __future__ import annotations + +import ast +import importlib +import re +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +DOCS = sorted([ROOT / "README.md", *(ROOT / "docs").glob("*.md")]) +BLOCK = re.compile(r"```python\n(.*?)```", re.S) +IMPORT = re.compile(r"^\s*from (evalrx[\w.]*) import (\([^)]*\)|[^\n]+)", re.M) + + +def _imports() -> list[tuple[str, str, str]]: + found = [] + for doc in DOCS: + for block in BLOCK.findall(doc.read_text(encoding="utf-8")): + for match in IMPORT.finditer(block): + statement = f"from {match.group(1)} import {match.group(2)}" + try: + node = ast.parse(statement).body[0] + except SyntaxError: + continue + assert isinstance(node, ast.ImportFrom) + for alias in node.names: + found.append((doc.relative_to(ROOT).as_posix(), node.module or "", alias.name)) + return sorted(set(found)) + + +@pytest.mark.parametrize(("doc", "module", "name"), _imports()) +def test_documented_import_resolves(doc: str, module: str, name: str) -> None: + try: + imported = importlib.import_module(module) + except ModuleNotFoundError as exc: + if exc.name and not exc.name.startswith("evalrx"): + pytest.skip(f"optional dependency {exc.name} is not installed") + raise + assert hasattr(imported, name) or importlib.util.find_spec(f"{module}.{name}"), ( + f"{doc}: `from {module} import {name}` no longer resolves" + ) diff --git a/tests/test_eval_agent/test_agent_launch_smoke.py b/tests/test_eval_agent/test_agent_launch_smoke.py index 6862fad2..b76c9b49 100644 --- a/tests/test_eval_agent/test_agent_launch_smoke.py +++ b/tests/test_eval_agent/test_agent_launch_smoke.py @@ -14,6 +14,7 @@ ) from evalrx.eval_agent.stages.protocol import ExperimentProtocol from tests.conftest import FakeModel +from tests.judge_replies import hypothesis, keep_all, proposal class _ScriptedJudge(FakeModel): @@ -27,26 +28,14 @@ def generate(self, inputs, **kwargs) -> str: prompt = str(inputs) self.calls.append(prompt) if "adversarial ML reviewer" in prompt: - return ( - "KEEP: Failure is driven by an attention signal present on failing cases.\n" - "REASON: evidence directly supports this claim" - ) - return json.dumps( - [ - { - "hypothesis": ( - "Failure is driven by an attention signal present on failing cases." - ), - # Present because the prompt asks for it: a missing or - # jargon-y plain line costs one extra plain-language - # repair call, which would change the call count below. - "plain_statement": ( - "The model looks at the wrong part of the input on the cases it gets wrong." - ), - "failure_mode": "attention", - } - ] - ) + return keep_all(1) + return proposal(hypothesis( + "Failure is driven by an attention signal present on failing cases.", + "attention", + # A clean plain statement: a missing or jargon-y one costs one extra + # revision call, which would change the call count below. + plain="The model looks at the wrong part of the input on the cases it gets wrong.", + )) class _SignalProbe(ProbeAgent): @@ -114,7 +103,7 @@ def test_vl_agent_launches_m1_to_m4_and_dashboard_loader_reads_run(tmp_path): assert report.stopped_by == "criteria_met" assert report.cycles == 1 - assert [h.predicted_failure_mode for h in report.all_hypotheses] == ["attention"] + assert [h.predicted_failure_mode for h in report.final_hypotheses] == ["attention"] assert len(report.all_test_results) == 1 assert report.all_test_results[0].status.value == "supported" assert report.all_test_results[0].effect_size == 1.0 diff --git a/tests/test_eval_agent/test_agentic_actions.py b/tests/test_eval_agent/test_agentic_actions.py index 2c887623..e034d2f6 100644 --- a/tests/test_eval_agent/test_agentic_actions.py +++ b/tests/test_eval_agent/test_agentic_actions.py @@ -6,13 +6,14 @@ from __future__ import annotations +import pytest +from pydantic import ValidationError + from evalrx.eval_agent.agentic.actions import ( Action, - ActionParseError, _fallback_action, + action_model, decide, - parse_action, - validate_json_shape, ) from evalrx.eval_agent.agentic.board import EvidenceBoard from evalrx.eval_agent.agentic.tools import ToolOutcome, ToolRegistry, ToolSpec @@ -34,77 +35,25 @@ def _registry() -> ToolRegistry: # --------------------------------------------------------------------------- -# validate_json_shape +# action_model # --------------------------------------------------------------------------- -def test_validate_json_shape_passes_valid_object(): - schema = {"type": "object", "required": ["a"], "properties": {"a": {"type": "string"}}} - assert validate_json_shape({"a": "x"}, schema) == [] - - -def test_validate_json_shape_flags_missing_required(): - schema = {"type": "object", "required": ["a"], "properties": {}} - errors = validate_json_shape({}, schema) - assert any("missing required field 'a'" in e for e in errors) - - -def test_validate_json_shape_flags_wrong_type(): - schema = {"type": "object", "properties": {"a": {"type": "string"}}} - errors = validate_json_shape({"a": 5}, schema) - assert any("expected string" in e for e in errors) - - -def test_validate_json_shape_flags_short_string(): - schema = {"type": "string", "minLength": 3} - errors = validate_json_shape("ab", schema) - assert any("too short" in e for e in errors) - - -# --------------------------------------------------------------------------- -# parse_action -# --------------------------------------------------------------------------- - -def test_parse_action_accepts_valid_json(): - registry = _registry() - raw = '{"tool": "run_probe", "params": {}, "rationale": "need M1 first"}' - action = parse_action(raw, registry) - assert action.tool == "run_probe" - assert action.rationale == "need M1 first" - assert action.valid is True - - -def test_parse_action_strips_markdown_fences(): - registry = _registry() - raw = '```json\n{"tool": "stop", "params": {}, "rationale": "done"}\n```' - action = parse_action(raw, registry) - assert action.tool == "stop" - - -def test_parse_action_rejects_non_json(): - registry = _registry() - try: - parse_action("not json at all", registry) - raise AssertionError("expected ActionParseError") - except ActionParseError as exc: - assert "not valid JSON" in str(exc) +def test_action_model_accepts_a_registered_tool(): + choice = action_model(_registry()).model_validate( + {"tool": "run_probe", "params": {"k": 1}, "rationale": "start with M1"} + ) + assert (choice.tool, choice.params, choice.rationale) == ("run_probe", {"k": 1}, "start with M1") -def test_parse_action_rejects_missing_rationale(): - registry = _registry() - try: - parse_action('{"tool": "run_probe", "params": {}}', registry) - raise AssertionError("expected ActionParseError") - except ActionParseError as exc: - assert any("rationale" in e for e in exc.errors) - - -def test_parse_action_rejects_unknown_tool(): - registry = _registry() - try: - parse_action('{"tool": "nonexistent", "rationale": "x"}', registry) - raise AssertionError("expected ActionParseError") - except ActionParseError as exc: - assert "unknown tool" in str(exc) +@pytest.mark.parametrize("data", [ + {"tool": "nonexistent", "rationale": "x"}, + {"tool": "run_probe"}, + {"tool": "run_probe", "rationale": ""}, + {"tool": "run_probe", "rationale": "x", "params": []}, +]) +def test_action_model_rejects_unknown_tools_and_missing_fields(data): + with pytest.raises(ValidationError): + action_model(_registry()).model_validate(data) # --------------------------------------------------------------------------- @@ -174,7 +123,7 @@ def test_decide_repairs_once_then_succeeds(): registry = _registry() board = EvidenceBoard() judge = _StubJudge([ - "garbage, not json", + '```json\n{"tool": "nonexistent", "rationale": "x"}\n```', '{"tool": "run_probe", "params": {}, "rationale": "retry worked"}', ]) @@ -184,6 +133,19 @@ def test_decide_repairs_once_then_succeeds(): assert action.valid is True assert action.repair_attempts == 1 assert len(judge.calls) == 2 + assert "nonexistent" in judge.calls[1] and "run_probe" in judge.calls[1] + + +def test_decide_falls_back_when_the_judge_raises(): + class _Broken: + def generate(self, prompt, **kwargs): + raise RuntimeError("limit reached") + + run_logger = _StubRunLogger() + action = decide(_Broken(), EvidenceBoard(), _registry(), run_logger=run_logger, step=0) + assert (action.tool, action.valid) == ("run_probe", False) + (call,) = run_logger.decisions[0]["judge_calls"] + assert "limit reached" in call["error"] def test_decide_falls_back_after_exhausting_repairs(): diff --git a/tests/test_eval_agent/test_agentic_launch_smoke.py b/tests/test_eval_agent/test_agentic_launch_smoke.py index ba62203c..7300646c 100644 --- a/tests/test_eval_agent/test_agentic_launch_smoke.py +++ b/tests/test_eval_agent/test_agentic_launch_smoke.py @@ -1,4 +1,4 @@ -"""End-to-end smoke test for AgenticDiagnoseLoop — the judge-decided mode. +"""End-to-end smoke test for VLDiagnoseLoop under a JudgePolicy — the judge-decided mode. Mirrors test_agent_launch_smoke.py's fixtures (a synthetic attention signal that discriminates FAIL/PASS perfectly), but drives the loop via a scripted @@ -14,13 +14,14 @@ from evalrx.core.capability import Capability from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label from evalrx.core.result import Result -from evalrx.eval_agent import AgenticDiagnoseLoop, DiagnosisAgent, HypothesisTester +from evalrx.eval_agent import DiagnosisAgent, HypothesisTester, JudgePolicy, VLDiagnoseLoop from evalrx.eval_agent.log_schema import validate_event from evalrx.eval_agent.run_context import RunContext from evalrx.eval_agent.stages.probe_agent import ProbeAgent from evalrx.eval_agent.stages.protocol import ExperimentProtocol -from evalrx.reporting.run_events import read_v2_events +from evalrx.reporting.run_events import read_run_events from tests.conftest import FakeModel +from tests.judge_replies import hypothesis, keep_all, proposal class _ScriptedM3Judge(FakeModel): @@ -35,14 +36,12 @@ def generate(self, inputs, **kwargs) -> str: prompt = str(inputs) self.calls.append(prompt) if "adversarial ML reviewer" in prompt: - return ( - "KEEP: Failure is driven by an attention signal present on failing cases.\n" - "REASON: evidence directly supports this claim" - ) - return json.dumps([{ - "hypothesis": "Failure is driven by an attention signal present on failing cases.", - "failure_mode": "attention", - }]) + return keep_all(1) + return proposal(hypothesis( + "Failure is driven by an attention signal present on failing cases.", + "attention", + plain="The model looks at the wrong part of the input on the cases it gets wrong.", + )) class _ScriptedActionJudge(FakeModel): @@ -110,16 +109,15 @@ def _protocol() -> ExperimentProtocol: def _build_loop(tmp_path, action_judge, *, max_actions=10): ctx = RunContext(tmp_path / "run", verbose=False) - loop = AgenticDiagnoseLoop( + loop = VLDiagnoseLoop( model=FakeModel( capabilities={Capability.GENERATE, Capability.ATTENTION}, modalities={"text"}, ), protocol=_protocol(), - judge=action_judge, + policy=JudgePolicy(action_judge, max_actions=max_actions), probe_agent=_SignalProbe(max_analyzers=1), diagnosis_agent=DiagnosisAgent(judge=_ScriptedM3Judge()), hypothesis_tester=HypothesisTester(min_effect=0.05), - max_actions=max_actions, run_logger=ctx.logger, ) return ctx, loop @@ -133,7 +131,7 @@ def test_agentic_loop_reaches_a_supported_hypothesis_via_scripted_actions(tmp_pa assert report.stopped_by == "agent_stop" assert len(action_judge.calls) == 5 # exactly the scripted sequence, no repairs - assert [h.predicted_failure_mode for h in report.all_hypotheses] == ["attention"] + assert [h.predicted_failure_mode for h in report.final_hypotheses] == ["attention"] assert len(report.all_test_results) == 1 assert report.all_test_results[0].status.value == "supported" assert report.all_test_results[0].effect_size == 1.0 @@ -144,7 +142,7 @@ def test_agentic_loop_reaches_a_supported_hypothesis_via_scripted_actions(tmp_pa # probe/analysis/diagnosis/surgery events from the wrapped M1-M4 stages, # bracketed by run_start/loop_end so the dashboard can show run provenance. ctx.finalize() - lines = read_v2_events(ctx.root) + lines = read_run_events(ctx.root) for event in lines: validate_event(event) events = {line["event"] for line in lines} @@ -175,14 +173,13 @@ def test_agentic_loop_wires_cluster_failures_into_the_m3_prompt(tmp_path): action_judge = _ScriptedActionJudge(sequence) m3_judge = _ScriptedM3Judge() ctx = RunContext(tmp_path / "run", verbose=False) - loop = AgenticDiagnoseLoop( + loop = VLDiagnoseLoop( model=FakeModel(capabilities={Capability.GENERATE, Capability.ATTENTION}, modalities={"text"}), protocol=_protocol(), - judge=action_judge, + policy=JudgePolicy(action_judge, max_actions=10), probe_agent=_SignalProbe(max_analyzers=1), diagnosis_agent=DiagnosisAgent(judge=m3_judge), hypothesis_tester=HypothesisTester(min_effect=0.05), - max_actions=10, run_logger=ctx.logger, ) @@ -224,12 +221,12 @@ def test_benchmark_controller_cannot_open_confirmation_or_repair(tmp_path): '{"tool":"stop","params":{"resolved":false,"reason":"done"},"rationale":"done"}', ]) ctx, loop = _build_loop(tmp_path, judge) - loop._registry_factory = _benchmark_agentic_registry + loop.policy.registry_factory = _benchmark_agentic_registry loop.confirm_split = 0.5 report = loop.run(_cases()) assert report.stopped_by == "agent_stop" ctx.finalize() - events = read_v2_events(ctx.root) + events = read_run_events(ctx.root) tools = [e for e in events if e["event"] == "agent_tool"] assert len(judge.calls) == 2 # forbidden action is rejected before dispatch assert all(e["tool"] != "run_fix" for e in tools) diff --git a/tests/test_eval_agent/test_agentic_probe_tools.py b/tests/test_eval_agent/test_agentic_probe_tools.py index 615423af..aba61294 100644 --- a/tests/test_eval_agent/test_agentic_probe_tools.py +++ b/tests/test_eval_agent/test_agentic_probe_tools.py @@ -12,14 +12,14 @@ from evalrx.core.capability import Capability from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label -from evalrx.eval_agent import AgenticDiagnoseLoop, DiagnosisAgent, HypothesisTester +from evalrx.eval_agent import DiagnosisAgent, HypothesisTester, JudgePolicy, VLDiagnoseLoop from evalrx.eval_agent.agentic.actions import Action from evalrx.eval_agent.agentic.board import EvidenceBoard from evalrx.eval_agent.agentic.tools import ( _requested_probes, - _RunState, build_default_registry, ) +from evalrx.eval_agent.policy import RunState from evalrx.eval_agent.run_context import RunContext from evalrx.eval_agent.stages.probe_agent import ProbeAgent from evalrx.eval_agent.stages.protocol import ExperimentProtocol @@ -59,20 +59,21 @@ def _cases() -> CaseBatch: def _setup(tmp_path, model=None, judge=None): ctx = RunContext(tmp_path / "run", verbose=False) - loop = AgenticDiagnoseLoop( + judge = judge or _Judge() + loop = VLDiagnoseLoop( model=model or _CountingModel(capabilities=_WHITEBOX, modalities={"text"}), protocol=ExperimentProtocol( description="probe tool test", task_domain="test", failure_patterns="none", target_modalities=frozenset({"text"}), ), - judge=judge or _Judge(), + policy=JudgePolicy(judge), probe_agent=ProbeAgent(max_workers=1, max_analyzers=2), diagnosis_agent=DiagnosisAgent(judge=_Judge()), hypothesis_tester=HypothesisTester(min_effect=0.05), run_logger=ctx.logger, ) data = _cases() - state = _RunState(original_data=data, data=data) + state = RunState(original_data=data, data=data, judge=judge) return loop, state, build_default_registry(loop, state), EvidenceBoard() diff --git a/tests/test_eval_agent/test_agentic_search_probes_tool.py b/tests/test_eval_agent/test_agentic_search_probes_tool.py index 753dd308..356833d6 100644 --- a/tests/test_eval_agent/test_agentic_search_probes_tool.py +++ b/tests/test_eval_agent/test_agentic_search_probes_tool.py @@ -1,13 +1,14 @@ """The agentic loop's `search_probes` tool: wires ProbeSearchAgent into the ToolRegistry, reusing the loop's own decision judge + model + protocol. Exercised directly against the tool handler with a minimal fake loop (not the -full AgenticDiagnoseLoop machinery) and a fake model/judge — no GPU.""" +full VLDiagnoseLoop + JudgePolicy machinery) and a fake model/judge — no GPU.""" from __future__ import annotations from evalrx.core.case import CaseBatch, FailureCase, Inputs from evalrx.eval_agent.agentic.board import EvidenceBoard -from evalrx.eval_agent.agentic.tools import _RunState, build_default_registry +from evalrx.eval_agent.agentic.tools import build_default_registry +from evalrx.eval_agent.policy import RunState class _ScriptedJudge: @@ -34,11 +35,10 @@ def generate(self, inputs, **kwargs) -> str: class _FakeLoop: - """Duck-typed stand-in for AgenticDiagnoseLoop — search_probes only reads - .judge/.model/.protocol/.run_logger off the loop.""" + """Duck-typed stand-in for VLDiagnoseLoop — search_probes reads only + .model/.protocol/.run_logger off the loop, and the judge off the run state.""" - def __init__(self, judge, model) -> None: - self.judge = judge + def __init__(self, model) -> None: self.model = model self.protocol = None self.run_logger = None @@ -51,15 +51,15 @@ def _seed_pool() -> CaseBatch: def test_search_probes_registered_in_default_registry(): - loop = _FakeLoop(_ScriptedJudge(), _AlwaysWrongModel()) - state = _RunState(original_data=_seed_pool(), data=_seed_pool()) + loop = _FakeLoop(_AlwaysWrongModel()) + state = RunState(original_data=_seed_pool(), data=_seed_pool(), judge=_ScriptedJudge()) registry = build_default_registry(loop, state) assert "search_probes" in registry.tool_names() def test_search_probes_runs_and_populates_board_and_state(): - loop = _FakeLoop(_ScriptedJudge(), _AlwaysWrongModel()) - state = _RunState(original_data=_seed_pool(), data=_seed_pool()) + loop = _FakeLoop(_AlwaysWrongModel()) + state = RunState(original_data=_seed_pool(), data=_seed_pool(), judge=_ScriptedJudge()) registry = build_default_registry(loop, state) board = EvidenceBoard() @@ -74,8 +74,8 @@ def test_search_probes_runs_and_populates_board_and_state(): def test_search_probes_empty_seed_pool_returns_failure_without_crashing(): - loop = _FakeLoop(_ScriptedJudge(), _AlwaysWrongModel()) - state = _RunState(original_data=CaseBatch([]), data=CaseBatch([])) + loop = _FakeLoop(_AlwaysWrongModel()) + state = RunState(original_data=CaseBatch([]), data=CaseBatch([]), judge=_ScriptedJudge()) registry = build_default_registry(loop, state) board = EvidenceBoard() @@ -87,8 +87,8 @@ def test_search_probes_empty_seed_pool_returns_failure_without_crashing(): def test_search_probes_respects_call_cap_via_registry_dispatch(): from evalrx.eval_agent.agentic.actions import Action - loop = _FakeLoop(_ScriptedJudge(), _AlwaysWrongModel()) - state = _RunState(original_data=_seed_pool(), data=_seed_pool()) + loop = _FakeLoop(_AlwaysWrongModel()) + state = RunState(original_data=_seed_pool(), data=_seed_pool(), judge=_ScriptedJudge()) registry = build_default_registry(loop, state) board = EvidenceBoard() action = Action(tool="search_probes", params={"budget": 1}, rationale="t") diff --git a/tests/test_eval_agent/test_agy_log_scan.py b/tests/test_eval_agent/test_agy_log_scan.py index f5a8bef3..95ca70c7 100755 --- a/tests/test_eval_agent/test_agy_log_scan.py +++ b/tests/test_eval_agent/test_agy_log_scan.py @@ -46,20 +46,24 @@ def test_scan_picks_last_error(tmp_path): assert "UNAUTHENTICATED" in _scan_agy_log(str(log)) -def test_startup_stderr_takes_priority_over_background_auth_log(monkeypatch): - from pathlib import Path - from subprocess import CompletedProcess +def test_startup_stderr_takes_priority_over_background_auth_log(tmp_path): + import stat import pytest from evalrx.agent_runtime.judges import agy - def fail(cmd, **kwargs): - path = Path(cmd[cmd.index('--log-file') + 1]) - path.write_text('E1005 12:00:00 a.go:1] doRefreshQuota: skipped (not logged in)\n') - return CompletedProcess(cmd, 1, stdout='', stderr='invalid model selection: unsupported model') - - monkeypatch.setattr(agy.subprocess, 'run', fail) + # A fake agy: writes a misleading background auth line to its log file, + # then fails at startup with the real reason on stderr. + binary = tmp_path / "agy" + binary.write_text( + "#!/bin/sh\n" + 'while [ "$1" != "--log-file" ]; do shift; done\n' + "echo 'E1005 12:00:00 a.go:1] doRefreshQuota: skipped (not logged in)' > \"$2\"\n" + "echo 'invalid model selection: unsupported model' >&2\n" + "exit 1\n" + ) + binary.chmod(binary.stat().st_mode | stat.S_IXUSR) with pytest.raises(RuntimeError, match='invalid model selection') as exc: - agy.AgyModel(binary_path='/bin/false').generate('OK') + agy.AgyModel(binary_path=str(binary)).generate('OK') assert 'not logged in' not in str(exc.value) diff --git a/tests/test_eval_agent/test_attention_decoding.py b/tests/test_eval_agent/test_attention_decoding.py index b4892791..3519a931 100644 --- a/tests/test_eval_agent/test_attention_decoding.py +++ b/tests/test_eval_agent/test_attention_decoding.py @@ -9,10 +9,10 @@ import numpy as np +from evalrx.analysis.planner import plan_stats_input from evalrx.analysis.stats_tools import ( StatsInput, build_stats_input, - default_plan, run_stats_tool, ) from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label @@ -101,7 +101,7 @@ def test_per_case_maps_become_vectors(self): assert "relative_attention.map" in inp.per_case_vectors assert set(inp.per_case_vectors["relative_attention.map"]) == set(maps) - def test_default_plan_includes_decoding_when_maps_present(self): + def test_plan_includes_decoding_when_maps_present(self): inp = _maps(structured=True) - tools = [t for t, _, _ in default_plan(inp)] + tools = [item.tool for item in plan_stats_input(inp)] assert "attention_decoding" in tools diff --git a/tests/test_eval_agent/test_auto_diagnose.py b/tests/test_eval_agent/test_auto_diagnose.py index b1b00c39..ebecccee 100755 --- a/tests/test_eval_agent/test_auto_diagnose.py +++ b/tests/test_eval_agent/test_auto_diagnose.py @@ -24,6 +24,7 @@ ) from evalrx.eval_agent.hypothesis import Hypothesis from tests.conftest import FakeModel +from tests.judge_replies import hypothesis, keep_all, proposal # ── helpers ──────────────────────────────────────────────────────────────────── @@ -325,31 +326,34 @@ def _make_report(severity="high") -> AnalysisReport: ) -def test_unparsed_judge_text_falls_back_loudly_but_no_issue_quietly(caplog): +def test_unparsed_judge_text_raises_after_one_retry_and_no_problem_still_falls_back(): """gemma-4-e2b/bbh_causal_judgement (2026-08-22): the judge wrote three - hypotheses in a label format the parser missed and the run silently diagnosed - an analysis-module template. The fallback stays (M5 still needs a hypothesis) - but a parse miss must be visible; a genuine NO_ISSUE verdict stays quiet.""" - import logging - - with caplog.at_level(logging.WARNING, logger="evalrx.eval_agent.stages.diagnosis"): - judge = ScriptedModel(answers=["Three rich paragraphs of diagnosis without any label lines."], - capabilities={Capability.GENERATE}) - diag = DiagnosisAgent(judge=judge).diagnose(_make_report()) + hypotheses in a format the old text parser missed and the run silently + diagnosed an analysis-module template. An unreadable answer is now sent back + once with the validation errors and then raised, with every exchange, for the + loop to log and retry; a genuine "no problem" (an empty proposal) with + medium/high M2 findings still yields one template hypothesis per finding.""" + import pytest + + from evalrx.agent_runtime.judge_call import JudgeOutputError + + judge = ScriptedModel(answers=["Three rich paragraphs of diagnosis without any JSON."], + capabilities={Capability.GENERATE}) + with pytest.raises(JudgeOutputError) as err: + DiagnosisAgent(judge=judge).diagnose(_make_report()) + assert judge._i == 2 + assert [e.role for e in err.value.exchanges] == ["diagnosis_judge", "diagnosis_judge"] + + judge = ScriptedModel(answers=[proposal()], capabilities={Capability.GENERATE}) + diag = DiagnosisAgent(judge=judge).diagnose(_make_report()) assert len(diag.hypotheses) == 1 and diag.hypotheses[0].predicted_failure_mode == "attention_sink" - assert any("parsed to zero hypotheses" in r.message for r in caplog.records) - - caplog.clear() - with caplog.at_level(logging.WARNING, logger="evalrx.eval_agent.stages.diagnosis"): - judge = ScriptedModel(answers=["NO_ISSUE"], capabilities={Capability.GENERATE}) - diag = DiagnosisAgent(judge=judge).diagnose(_make_report()) - assert len(diag.hypotheses) == 1 # the NO_ISSUE fallback is by design - assert not any("parsed to zero" in r.message for r in caplog.records) + assert diag.proposed_hypotheses == [] # the template is not the judge's proposal + assert judge._i == 1 # nothing to review, so no critic call def test_diagnosis_parses_hypothesis_from_report(): judge = ScriptedModel( - answers=["HYPOTHESIS: model over-attends to BOS\nFAILURE_MODE: attention_sink\n"], + answers=[proposal(hypothesis("model over-attends to BOS", "attention_sink")), keep_all(1)], capabilities={Capability.GENERATE}, ) diag = DiagnosisAgent(judge=judge).diagnose(_make_report()) @@ -360,20 +364,10 @@ def test_diagnosis_parses_hypothesis_from_report(): def test_diagnosis_no_issue_returns_empty(): - judge = ScriptedModel(answers=["NO_ISSUE"], capabilities={Capability.GENERATE}) + judge = ScriptedModel(answers=[proposal()], capabilities={Capability.GENERATE}) diag = DiagnosisAgent(judge=judge).diagnose(_make_report(severity="none")) assert diag.hypotheses == [] - assert "NO_ISSUE" in diag.raw_judge_output - - -def test_diagnosis_backward_compat_accepts_results_dict(): - """Passing a raw results dict (old API) still works via AnalysisModule wrapping.""" - from evalrx.analyzers.attention.summary import AttentionAnalyzer - model = FakeModel() - results = {"attention": AttentionAnalyzer().run(model, "probe")} - judge = ScriptedModel(answers=["NO_ISSUE"], capabilities={Capability.GENERATE}) - diag = DiagnosisAgent(judge=judge).diagnose(results, model_name="m") - assert isinstance(diag, DiagnosisResult) + assert diag.raw_judge_output == proposal() def test_diagnosis_prompt_includes_severity_and_narrative(): @@ -382,7 +376,7 @@ def test_diagnosis_prompt_includes_severity_and_narrative(): class CapturingModel(FakeModel): def generate(self, inputs, **kw): captured.append(str(inputs)) - return "NO_ISSUE" + return proposal() DiagnosisAgent(judge=CapturingModel(capabilities={Capability.GENERATE})).diagnose( _make_report("high") @@ -499,9 +493,9 @@ def test_m5_experiment_gets_its_own_trial_with_kept_sandbox(tmp_path): # the whole point of giving the experiment its own durable folder, # not one shared/overwritten sandbox. Checked before finalize(), # which inlines and deletes the ephemeral runtime tree trials live - # under — V2 keeps no per-trial main.py/record.md on disk at all - # (that was a V1-only artifact); the generated code is captured - # inline into M5/log.json's "experiment" entry instead. + # under — no per-trial main.py/record.md stays on disk; the + # generated code is captured inline into M5/log.json's "experiment" + # entry instead. assert list((p / "workspace").glob("exp_*.py")), \ f"sandbox script should be kept in {p / 'workspace'}" diff --git a/tests/test_eval_agent/test_cli_judge_runtime.py b/tests/test_eval_agent/test_cli_judge_runtime.py new file mode 100644 index 00000000..679e79df --- /dev/null +++ b/tests/test_eval_agent/test_cli_judge_runtime.py @@ -0,0 +1,104 @@ +"""The CLI judges share one runner: a timeout kills the whole process group, +and a limit notice is an error for every provider, not only Claude.""" + +from __future__ import annotations + +import os +import stat +import time +from pathlib import Path + +import pytest + +from evalrx.agent_runtime.judges import AgyModel, ClaudeModel, CodexModel +from evalrx.agent_runtime.providers.base import CliAgentBase + + +def _binary(tmp_path: Path, name: str, body: str) -> str: + path = tmp_path / name + path.write_text(f"#!/bin/sh\n{body}\n", encoding="utf-8") + path.chmod(path.stat().st_mode | stat.S_IXUSR) + return str(path) + + +def _alive(pid: int) -> bool: + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + return True + + +def test_a_timeout_kills_the_judges_child_processes_too(tmp_path): + # A CLI's worker processes outlived a plain subprocess.run timeout, which + # kills only the direct child; the runner kills the whole process group. + pidfile = tmp_path / "grandchild.pid" + body = f'sleep 30 & echo $! > "{pidfile}"; sleep 30' + judge = ClaudeModel(binary_path=_binary(tmp_path, "claude", body), timeout_sec=1) + with pytest.raises(RuntimeError, match="timed out after 1s"): + judge.generate("hi") + grandchild = int(pidfile.read_text()) + deadline = time.monotonic() + 5 + while _alive(grandchild) and time.monotonic() < deadline: + time.sleep(0.1) + assert not _alive(grandchild) + + +@pytest.mark.parametrize("make", [ + lambda b: ClaudeModel(binary_path=b), + lambda b: AgyModel(binary_path=b), +]) +def test_a_limit_notice_on_stdout_is_an_error_for_each_provider(tmp_path, make): + binary = _binary(tmp_path, "cli", "cat >/dev/null 2>&1; echo \"You've hit your usage limit. Limit resets at 5pm.\"") + with pytest.raises(RuntimeError, match="account limit reached"): + make(binary).generate("hi") + + +def test_codex_limit_notice_in_its_answer_file_is_an_error(tmp_path): + body = ( + 'while [ "$1" != "--output-last-message" ]; do shift; done\n' + "echo \"You've hit your usage limit.\" > \"$2\"" + ) + with pytest.raises(RuntimeError, match="account limit reached"): + CodexModel(binary_path=_binary(tmp_path, "codex", body)).generate("hi") + + +def test_the_prompt_reaches_claude_on_stdin_and_the_cwd_is_not_the_callers(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + out = ClaudeModel(binary_path=_binary(tmp_path, "claude", 'printf "%s|" "$PWD"; cat')).generate("PROMPT") + cwd, prompt = out.split("|", 1) + assert prompt == "PROMPT" + assert Path(cwd).resolve() != tmp_path.resolve() + + +class _ScriptAgent(CliAgentBase): + _provider_name = "script" + + def _build_cmd(self, prompt: str, workdir: Path) -> list[str]: + return [self._binary] + + +def test_a_coding_agent_that_prints_a_limit_notice_reports_it(tmp_path): + notice = "echo '[assistant] starting'; echo \"You've hit your usage limit. Limit resets at 5pm.\"" + result = _ScriptAgent(_binary(tmp_path, "cli", notice)).run("write it", workdir=tmp_path / "w") + assert result.error and "account limit reached" in result.error + + +def test_a_coding_agent_that_wrote_files_is_not_read_as_limited(tmp_path): + body = "echo 'x = 1' > main.py; echo 'Note: your usage limit resets on Monday.'" + result = _ScriptAgent(_binary(tmp_path, "cli", body)).run("write it", workdir=tmp_path / "w") + assert result.error is None and "main.py" in result.files + + +def test_claude_code_limit_notice_in_its_stream_is_reported(tmp_path): + from evalrx.agent_runtime.providers.claude_code import ClaudeCodeAgent + + stream = [ + '{"type":"system","subtype":"init","model":"m","tools":["Bash"]}', + '{"type":"assistant","message":{"content":[{"type":"text","text":"You\'ve hit your usage limit · resets 5pm"}]}}', + '{"type":"result","subtype":"success","result":"You\'ve hit your usage limit · resets 5pm",' + '"num_turns":1,"duration_ms":900,"total_cost_usd":0,"usage":{"input_tokens":3,"output_tokens":9}}', + ] + body = "cat <<'EOF'\n" + "\n".join(stream) + "\nEOF" + result = ClaudeCodeAgent(_binary(tmp_path, "claude", body)).run("write it", workdir=tmp_path / "w") + assert result.error and "account limit reached" in result.error diff --git a/tests/test_eval_agent/test_confirm_split.py b/tests/test_eval_agent/test_confirm_split.py index 81d611db..fd4a0f3c 100644 --- a/tests/test_eval_agent/test_confirm_split.py +++ b/tests/test_eval_agent/test_confirm_split.py @@ -16,7 +16,7 @@ from evalrx.core.model import Model from evalrx.eval_agent.hypothesis import Hypothesis from evalrx.eval_agent.loop import VLDiagnoseLoop -from evalrx.eval_agent.loop_reports import VLDiagnoseReport +from evalrx.eval_agent.loop_reports import AutoDiagnoseReport from evalrx.eval_agent.stages.fix.agent import FixCandidate, FixOutcome, FixValidation from evalrx.eval_agent.stages.fix.tiers import FixTier from evalrx.eval_agent.stages.protocol import ExperimentProtocol @@ -89,8 +89,9 @@ def __init__(self): self.tiers = [] self.min_tiers = [] - def propose_and_validate(self, model, data, hypotheses, proposal_data=None, *, - max_tier=None, min_tier=None): + def propose_and_validate(self, model, data, hypotheses, prior_attempts=None, + context=None, proposal_data=None, *, + max_tier=None, min_tier=None, record=True): self.calls += 1 self.tiers.append(max_tier if max_tier is not None else self.max_tier) self.min_tiers.append(min_tier) @@ -127,10 +128,17 @@ def validate_candidate(self, model, data, candidate): e_value=1.0, ) + def recommend(self, routed, *, model=None, data=None, reason_prefix="", max_tier=None): + return {"recommend_tier": (max_tier or self.max_tier).label, "reason": reason_prefix} + + def no_fix_recommendation(self, attempted, routed_tiers, data, model, *, max_tier=None): + return {"recommend_tier": (max_tier or self.max_tier).label, + "reason": "no candidate validated"} + def _report(): h = Hypothesis(statement="x", target_model="m", predicted_failure_mode="") - return VLDiagnoseReport(cycles=1, stopped_by="max_cycles", final_hypotheses=[h]) + return AutoDiagnoseReport(cycles=1, stopped_by="max_cycles", final_hypotheses=[h]) # The reports below carry proposals only (nothing M4-verified): since the @@ -216,7 +224,7 @@ def test_run_fix_escalates_on_explore_then_confirms_once(): def test_explore_selection_rejects_tiny_high_effect_candidate(): """A 2/5 swing must not outrank a supported improvement on 64 pairs.""" class SelectionAgent(_RecordingFixAgent): - def propose_and_validate(self, model, data, hypotheses, proposal_data=None): + def propose_and_validate(self, model, data, hypotheses, **_): tiny = FixValidation( candidate=FixCandidate(FixTier.L2_SCAFFOLD, "tiny", payload={}), n_pairs=5, n_fixed=2, n_broken=0, effect=0.4, e_value=2.0, @@ -416,34 +424,40 @@ def test_run_fix_never_writes_to_the_fix_agent(): assert stub.max_tier is FixTier.L2_SCAFFOLD -def test_tier_ladder_rejects_an_agent_without_a_tier_window(): - """An agent that cannot take max_tier/min_tier would run every rung at its - own tier; the ladder refuses it instead of silently mislabelling rungs.""" - import pytest - - class NoWindow(_RecordingFixAgent): - def propose_and_validate(self, model, data, hypotheses): - raise AssertionError("must not be called") +def test_confirm_freezes_the_supported_explore_lead_and_says_why_it_did_not_hold(): + """The lead with support is the one frozen, and when it fails on CONFIRM + the agent's recommendation is prefixed with that fact.""" + from evalrx.eval_agent.loop_fix import _confirm_from_explore + from evalrx.eval_agent.stages.fix.types import FixCandidate, FixValidation - with pytest.raises(TypeError, match="max_tier"): - _loop(fix_agent=NoWindow(), confirm_split=0.5).run_fix( - _report(), _batch(), auto_escalate=True, allow_unverified=True + def lead(name, n_pairs, n_fixed, n_broken): + return FixValidation( + candidate=FixCandidate(tier=FixTier.L1_PROMPT, name=name, payload={}), + n_pairs=n_pairs, n_fixed=n_fixed, n_broken=n_broken, effect=0.1, ) + # Two fixes on two pairs is a fragile lead beside 5 net on 12 pairs. + fragile, supported = lead("fragile", 2, 2, 0), lead("supported", 12, 6, 1) + confirmed = lead("supported", 20, 1, 3) -def test_ladder_without_split_returns_an_opaque_custom_result(): - """A custom agent's application-specific result ends the climb and is - returned as-is, with or without a held-out split.""" - opaque = object() - - class Opaque(_RecordingFixAgent): - def propose_and_validate(self, model, data, hypotheses, *, max_tier=None, - min_tier=None): - self.calls += 1 - return opaque + class _Agent(_RecordingFixAgent): + def validate_candidate(self, model, data, candidate): + self.validated = candidate.name + return confirmed - stub = Opaque() - out = _loop(fix_agent=stub).run_fix( - _report(), _batch(), auto_escalate=True, allow_unverified=True + agent = _Agent() + confirm = CaseBatch([ + FailureCase.from_prompt("q", id="c0", expected="yes", observed="no", label=Label.FAIL), + ]) + outcome = _confirm_from_explore( + agent, object(), confirm, [fragile, supported], + max_tier=FixTier.L2_SCAFFOLD, repair_rounds=1, ) - assert out is opaque and stub.calls == 1 + assert agent.validated == "supported" + assert outcome.selected_on_explore == "supported" and not outcome.fixed + assert [row["name"] for row in outcome.selection_attempted] == ["fragile", "supported"] + assert outcome.recommendation == { + "recommend_tier": FixTier.L2_SCAFFOLD.label, + "reason": "the candidate selected on EXPLORE did not validate on untouched CONFIRM; " + "no candidate validated", + } diff --git a/tests/test_eval_agent/test_diagnosis_handoff.py b/tests/test_eval_agent/test_diagnosis_handoff.py index 79e2989f..cbd9794c 100755 --- a/tests/test_eval_agent/test_diagnosis_handoff.py +++ b/tests/test_eval_agent/test_diagnosis_handoff.py @@ -14,6 +14,7 @@ from evalrx.eval_agent.stages.diagnosis import DiagnosisAgent from evalrx.eval_agent.stages.protocol import ExperimentProtocol from tests.conftest import FakeModel +from tests.judge_replies import hypothesis, keep_all, proposal def _stats_report_with_conclusion() -> StatsAnalysisReport: @@ -45,15 +46,21 @@ def __init__(self) -> None: def generate(self, inputs, **kw) -> str: # diagnose() makes a second adversarial-validation call; record all and - # let tests inspect the first (the diagnosis prompt). The response - # carries a clean PLAIN_STATEMENT because the prompt demands one — a - # missing or jargon-y line costs a third call (the plain-language - # repair turn), which is what test_plain_language_repair covers. - self.prompts.append(str(inputs)) - return ("HYPOTHESIS: model fails to ground answers in the image\n" - "PLAIN_STATEMENT: The model answers from the wording of the question " - "instead of looking at the picture.\n" - "FAILURE_MODE: weak_visual_grounding") + # let tests inspect the first (the diagnosis prompt). The proposal + # carries a clean plain_statement because the prompt demands one — a + # missing or jargon-y one costs a third call (the plain-language + # revision), which is what test_plain_language_revision covers. + prompt = str(inputs) + self.prompts.append(prompt) + if "adversarial ML reviewer" in prompt: + return keep_all(1) + return _proposal() + + +def _proposal(plain: str = "The model answers from the wording of the question " + "instead of looking at the picture.") -> str: + return proposal(hypothesis("model fails to ground answers in the image", + "weak_visual_grounding", plain=plain)) def test_prompt_includes_conclusion_evidence_and_stats(): @@ -149,8 +156,9 @@ def test_critic_reviews_against_the_proposers_context_and_a_label_summary(): # the proposer's own prompt is unchanged by the cases kwarg assert "LABEL SUMMARY" not in judge.prompts[0] # and the critic prompt travels on the result so the run logger can persist it + # (the request itself; the judge also saw the Review schema ask_judge adds) diag = DiagnosisAgent(judge=CapturingJudge()).diagnose(_stats_report_with_conclusion(), cases=cases) - assert "LABEL SUMMARY" in diag.critic_prompt and diag.critic_prompt == judge.prompts[1] + assert "LABEL SUMMARY" in diag.critic_prompt and diag.critic_prompt in judge.prompts[1] def test_diagnose_without_cases_keeps_the_critic_prompt_label_free(): @@ -160,7 +168,7 @@ def test_diagnose_without_cases_keeps_the_critic_prompt_label_free(): assert "Context the proposer worked from" in judge.prompts[1] # conclusion/evidence still travel -def test_plain_language_repair_runs_once_when_the_plain_line_is_jargon(): +def test_plain_language_revision_runs_once_when_the_plain_statement_is_jargon(): """The prompt asking for plain language is not enough on its own — a judge will reuse the technical line — so the host checks it and spends ONE extra call to fix it. The analysis-side hypothesis agent already worked this way; @@ -171,33 +179,38 @@ def __init__(self) -> None: self.prompts: list[str] = [] def generate(self, inputs, **kw) -> str: - self.prompts.append(str(inputs)) - plain = ("Spearman rho of 0.42 between the coefficient and the p-value" - if len(self.prompts) == 1 - else "The model answers Yes whatever the picture shows.") - return ("HYPOTHESIS: model fails to ground answers in the image\n" - f"PLAIN_STATEMENT: {plain}\n" - "FAILURE_MODE: weak_visual_grounding") + prompt = str(inputs) + self.prompts.append(prompt) + if "adversarial ML reviewer" in prompt: + return keep_all(1) + return _proposal("Spearman rho of 0.42 between the coefficient and the p-value" + if len(self.prompts) == 1 + else "The model answers Yes whatever the picture shows.") judge = JargonThenPlain() diag = DiagnosisAgent(judge=judge).diagnose(_stats_report_with_conclusion()) - assert len(judge.prompts) == 3, "proposer, plain-language repair, then the critic" - assert "fail a plain-language check" in judge.prompts[1] + assert len(judge.prompts) == 3, "proposer, its plain-language revision, then the critic" + assert "fail the plain-language check" in judge.prompts[1] + assert "Spearman rho of 0.42" in judge.prompts[1] # the rejected answer goes back assert diag.hypotheses[0].plain_statement == ( "The model answers Yes whatever the picture shows." ) - assert [call["role"] for call in diag.model_calls] == [ - "diagnosis_judge", "diagnosis_plain_language_repair", "hypothesis_critic", + assert [(call["role"], call["metadata"]["attempt"]) for call in diag.model_calls] == [ + ("diagnosis_judge", 1), ("diagnosis_judge", 2), ("hypothesis_critic", 1), ] - assert diag.model_calls[0]["inputs"]["prompt"] == judge.prompts[0] - assert [call["inputs"] for call in diag.model_calls[1:]] == judge.prompts[1:] + assert [call["inputs"] for call in diag.model_calls] == judge.prompts assert all(call["duration_sec"] >= 0 for call in diag.model_calls) -def test_plain_language_repair_failure_keeps_the_original_hypotheses(): - """A repair that raises must not cost the run its diagnosis — a jargon-y - headline is a reader problem, not an M4 problem.""" - class RaisesOnRepair(FakeModel): +def test_a_judge_error_on_the_plain_language_revision_raises(): + """The revision is attempt 2 of the same typed call, so a judge that raises + there fails the call like any other judge failure — JudgeCallError carrying + both exchanges — and the loop decides whether to retry M3.""" + import pytest + + from evalrx.agent_runtime.judge_call import JudgeCallError + + class RaisesOnRevision(FakeModel): def __init__(self) -> None: super().__init__(capabilities={Capability.GENERATE}) self.calls = 0 @@ -206,13 +219,13 @@ def generate(self, inputs, **kw) -> str: self.calls += 1 if self.calls == 2: raise RuntimeError("judge went away") - return ("HYPOTHESIS: model fails to ground answers in the image\n" - "PLAIN_STATEMENT: rho of 0.42 against the coefficient\n" - "FAILURE_MODE: weak_visual_grounding") + return _proposal("rho of 0.42 against the coefficient") - diag = DiagnosisAgent(judge=RaisesOnRepair()).diagnose(_stats_report_with_conclusion()) - assert len(diag.hypotheses) == 1 - assert diag.hypotheses[0].plain_statement == "rho of 0.42 against the coefficient" + with pytest.raises(JudgeCallError, match="judge went away") as err: + DiagnosisAgent(judge=RaisesOnRevision()).diagnose(_stats_report_with_conclusion()) + first, second = err.value.exchanges + assert first.output and first.error is None + assert second.output is None and "judge went away" in second.error def test_loop_hands_the_case_batch_to_agents_that_accept_it_only(): diff --git a/tests/test_eval_agent/test_diagnosis_markdown_labels.py b/tests/test_eval_agent/test_diagnosis_markdown_labels.py deleted file mode 100644 index b3be519f..00000000 --- a/tests/test_eval_agent/test_diagnosis_markdown_labels.py +++ /dev/null @@ -1,305 +0,0 @@ -"""M3's line parser must read a judge that answers in Markdown. - -Live failure (qwen3.5-2b / bbh_word_sorting smoke, 2026-08-18): the judge wrote -three well-formed hypotheses as ``**HYPOTHESIS:** …`` / ``**FAILURE_MODE:** …`` -/ ``**TEST:** …`` and ``_parse_hypotheses`` — a bare ``startswith("HYPOTHESIS:")`` -— returned zero, so the loop stopped with "no_hypotheses" after a 30-minute M1. -The label is the contract, not its decoration. -""" - -from __future__ import annotations - -from evalrx.eval_agent.stages.diagnosis import ( - _normalise_label_line, - _parse_hypotheses, - _validate_hypotheses, -) -from tests.conftest import FakeModel - -_LIVE_STYLE = """Three hypotheses, ordered so the instrumentation check comes first. - -**HYPOTHESIS:** `generated:probe1`'s metrics use a misaligned reference, so the +0.73 effect rests on a broken probe. -**FAILURE_MODE:** probe_metric_misalignment -**TEST:** Re-run the probe with the gold string as the answer and require misplaced=0. - -**HYPOTHESIS:** The long-list failures are multiset errors on an otherwise ordered output. -**FAILURE_MODE:** computation_slip -**TEST:** Recompute `dropped/duplicated` from raw strings. -""" - - -def test_markdown_bold_labels_parse_like_bare_ones(): - hs = _parse_hypotheses(_LIVE_STYLE, "qwen") - assert [h.predicted_failure_mode for h in hs] == ["probe_metric_misalignment", "computation_slip"] - assert hs[0].statement.startswith("`generated:probe1`'s metrics") - assert hs[0].test_design.startswith("Re-run the probe") - assert hs[1].test_design.startswith("Recompute") - - -def test_every_common_decoration_is_normalised(): - cases = { - "HYPOTHESIS: plain": "HYPOTHESIS: plain", - "**HYPOTHESIS:** bold-outside": "HYPOTHESIS: bold-outside", - "**HYPOTHESIS**: bold-inside": "HYPOTHESIS: bold-inside", - "- FAILURE_MODE: bullet": "FAILURE_MODE: bullet", - "* TEST: star bullet": "TEST: star bullet", - "1. HYPOTHESIS: numbered": "HYPOTHESIS: numbered", - "2) TEST: numbered paren": "TEST: numbered paren", - "### FAILURE_MODE: heading": "FAILURE_MODE: heading", - "__hypothesis__: underscored lower": "HYPOTHESIS: underscored lower", - "`KEEP:` code": "KEEP: code", - "- **KEEP:** the *first* one **": "KEEP: the *first* one", # inner emphasis kept, trailing dropped - } - for raw, want in cases.items(): - assert _normalise_label_line(raw) == want, raw - # non-label lines are only stripped - assert _normalise_label_line(" evidence: HYPOTHESIS-like words inside ") == "evidence: HYPOTHESIS-like words inside" - assert _normalise_label_line("The hypothesis: is not a label") == "The hypothesis: is not a label" - - -_BOLD_NUMBERED_STYLE = """## Hypotheses - -**HYPOTHESIS 1:** The "No" prior is produced *inside* the chain of thought. -**PLAIN_STATEMENT:** The model grades the stories like a law professor. -**FAILURE_MODE:** task_framing_override -**TEST:** New per-case lexical analyzer over stored outputs: count of strict-doctrine markers HIGHER on failing cases. -**EXPECTED_ASSOCIATION:** higher_on_failures - -**HYPOTHESIS 2:** The bias is a length-dependent deliberation drift. -**PLAIN_STATEMENT:** The longer it thinks out loud, the more objections it invents. -**FAILURE_MODE:** overthinking -**TEST:** `termination_audit.output_words` HIGHER on failing cases. -**EXPECTED_ASSOCIATION:** higher_on_failures -""" - - -def test_numbered_labels_parse_like_bare_ones(): - """gemma-4-e2b / bbh_causal_judgement chain (2026-08-22): ``**HYPOTHESIS 1:**`` - / ``**HYPOTHESIS 2:**`` — three well-formed hypotheses, zero parsed, and the - run silently diagnosed an analysis-module template instead.""" - hs = _parse_hypotheses(_BOLD_NUMBERED_STYLE, "gemma") - assert [h.predicted_failure_mode for h in hs] == ["task_framing_override", "overthinking"] - assert hs[0].statement == 'The "No" prior is produced *inside* the chain of thought.' - assert hs[0].plain_statement.startswith("The model grades") - assert hs[0].test_design.startswith("New per-case lexical analyzer") - assert hs[1].statement.startswith("The bias is a length-dependent") - for raw, want in { - "**HYPOTHESIS 1:** one": "HYPOTHESIS: one", - "HYPOTHESIS #2: two": "HYPOTHESIS: two", - "Hypothesis (3): three": "HYPOTHESIS: three", - "**TEST 1:** t": "TEST: t", - "3. **HYPOTHESIS 3:** bullet and number": "HYPOTHESIS: bullet and number", - }.items(): - assert _normalise_label_line(raw) == want, raw - # a number that is part of the statement, not the label, stays - assert _normalise_label_line("HYPOTHESIS: 3 of the cases") == "HYPOTHESIS: 3 of the cases" - - -def test_json_output_is_untouched_by_the_text_normaliser(): - raw = '[{"hypothesis": "json path statement long enough", "failure_mode": "fm"}]' - hs = _parse_hypotheses(raw, "m") - assert [h.statement for h in hs] == ["json path statement long enough"] - - -class _Critic(FakeModel): - def __init__(self, reply: str) -> None: - super().__init__() - self.reply = reply - - def generate(self, inputs, **kw): - return self.reply - - -def test_critic_keep_lines_in_markdown_are_honoured(): - hs = _parse_hypotheses(_LIVE_STYLE, "qwen") - out = _validate_hypotheses( - hs, "{}", _Critic("Verdicts:\n- **KEEP:** the long-list failures are multiset errors on an otherwise ordered output.\n- **REJECT:** the probe one"), - ) - # annotate, never filter: every proposal comes back, kept ones first - assert len(out) == len(hs) - assert out[0].predicted_failure_mode == "computation_slip" - assert out[0].metadata["critic"] == "keep" - assert {h.metadata["critic"] for h in out[1:]} <= {"reject", "unparsed"} - - -def test_critic_rejecting_everything_keeps_flagged_leads(): - hs = _parse_hypotheses(_LIVE_STYLE, "qwen") - cap = {} - out = _validate_hypotheses( - hs, "{}", - _Critic("\n".join( - f"REJECT: {h.statement}\nREASON: n=32 cannot separate this from chance" - for h in hs)), - capture=cap, - ) - assert len(out) == len(hs) - assert all(h.metadata["critic"] == "reject" for h in out) - assert all(h.metadata["critic_reason"].startswith("n=32") for h in out) - assert cap["n_rejected"] == len(hs) and cap["n_kept"] == 0 - assert "REJECT:" in cap["raw"] - - -def test_unparsable_critic_marks_hypotheses_unreviewed(): - hs = _parse_hypotheses(_LIVE_STYLE, "qwen") - out = _validate_hypotheses(hs, "{}", _Critic("I cannot review these.")) - assert len(out) == len(hs) - assert all(h.metadata["critic"] == "unparsed" for h in out) - - -def test_markdown_expected_association_label_is_normalised(): - raw = ( - "**HYPOTHESIS:** the chain breaks on long lists of words\n" - "**FAILURE_MODE:** chain_break\n" - "**TEST:** step_rollout_value.max_value_drop HIGHER on failing cases\n" - "**EXPECTED_ASSOCIATION:** higher_on_failures\n" - ) - hs = _parse_hypotheses(raw, "m") - assert len(hs) == 1 - assert hs[0].expected_association == "higher_on_failures" - assert hs[0].test_design.startswith("step_rollout_value.max_value_drop") - - -def test_critic_context_is_optional_and_lands_in_its_prompt(): - """The critic reviews against what the proposer saw: *context* (conclusion, - evidence, stats, explore notes, label summary) goes into its prompt; the - old 3-positional call keeps working and adds no context block.""" - hs = _parse_hypotheses(_LIVE_STYLE, "qwen") - cap = {} - _validate_hypotheses(hs, "{}", _Critic("KEEP: everything"), capture=cap, - context="LABEL SUMMARY: gold=no answered=yes n=27 FAIL=27") - assert "Context the proposer worked from" in cap["prompt"] - assert "gold=no answered=yes n=27 FAIL=27" in cap["prompt"] - assert cap["prompt"].index("Context the proposer") < cap["prompt"].index("Findings summary") - - bare = {} - _validate_hypotheses(hs, "{}", _Critic("KEEP: everything"), capture=bare) - assert "Context the proposer worked from" not in bare["prompt"] - - -def test_label_context_tabulates_gold_by_answer_on_binary_batches(): - from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label - from evalrx.eval_agent.stages.diagnosis import _format_label_context - - assert _format_label_context(None) == "" - - def _c(i, observed, expected, label): - return FailureCase(id=f"c{i}", inputs=Inputs(prompt="Is there a dog?"), - observed=observed, expected=expected, label=label) - - binary = CaseBatch( - [_c(i, "Yes", "No", Label.FAIL) for i in range(3)] - + [_c(10 + i, "Yes", "Yes", Label.PASS) for i in range(4)] - + [_c(20, "No", "Yes", Label.FAIL), _c(21, "No", "No", Label.PASS)] - ) - text = _format_label_context(binary) - assert "labelled cases: 9 (4 FAIL / 5 PASS)" in text - assert "gold=no answered=yes n=3 FAIL=3" in text - assert "gold=yes answered=yes n=4 FAIL=0" in text - assert "answered yes on 7/9 binary cases" in text - - numeric = CaseBatch([_c(i, "Answer: 12", "12", Label.PASS) for i in range(5)] - + [_c(9, "Answer: 7", "12", Label.FAIL)]) - text = _format_label_context(numeric) - assert "labelled cases: 6 (1 FAIL / 5 PASS)" in text - assert "gold x answer" not in text - - -# Live failure #2 (VideoLLaMA2.1-7B-AV / Music-AVQA, 560 cases, 2026-08-23): -# Opus at high effort numbered its three hypotheses the way anyone numbers a -# list — HYPOTHESIS 1: / HYPOTHESIS 2: / HYPOTHESIS 3: — and the parser, which -# by then handled every Markdown decoration and every LEADING list marker, -# returned zero again. The first fix took the ordinal before the label ("1. -# TEST:") and missed the ordinal after it. Two and a half hours of GPU and a -# high-effort judge, discarded over a digit. -# -# Verbatim from that run's prompts/c0_m3_diagnosis.response.txt, trimmed. -_NUMBERED_STYLE = """HYPOTHESIS 1: The M2 item set contains unrendered prompt templates \u2014 31% of questions reach the model with literal `/` tokens where a spatial referent should be. -PLAIN_STATEMENT: Roughly a third of the questions were never filled in properly. -FAILURE_MODE: prompt_template_unsubstituted -TEST: `generated:probe1.has_placeholder` on failing vs passing cases (already +0.33, p\u22481e-15). -EXPECTED_ASSOCIATION: higher_on_failures - -HYPOTHESIS 2: On the well-formed remainder, the model answers audio-grounded questions from visual priors rather than the audio stream. -PLAIN_STATEMENT: The model is mostly watching, not listening. -FAILURE_MODE: ignored_obs -TEST: `modality_ablation.grounded_in_audio` on failing vs passing cases within the placeholder-free stratum. -EXPECTED_ASSOCIATION: higher_on_failures - -HYPOTHESIS 3: The model conditions its answer on its own generated text rather than on the raw AV evidence. -PLAIN_STATEMENT: If you ask it to describe the clip first, it answers its own description. -FAILURE_MODE: self_conditioning_cascade -TEST: `prompt_contrast` describe_first contrast, plus `perturbation_battery.noop_clause_flipped` HIGHER on failing cases. -EXPECTED_ASSOCIATION: higher_on_failures -""" - - -def test_an_ordinal_after_the_label_parses(): - hs = _parse_hypotheses(_NUMBERED_STYLE, "videollama2.1-7b-av") - assert [h.predicted_failure_mode for h in hs] == [ - "prompt_template_unsubstituted", "ignored_obs", "self_conditioning_cascade", - ] - # The ordinal is a label decoration, not part of the claim. - assert hs[0].statement.startswith("The M2 item set contains") - assert hs[1].test_design.startswith("`modality_ablation.grounded_in_audio`") - assert hs[2].plain_statement.startswith("If you ask it to describe") - - -def test_ordinals_in_either_position_and_every_marker_shape(): - """Before and after the label, with and without punctuation.""" - for line, want in { - "HYPOTHESIS 1: a": "HYPOTHESIS: a", - "HYPOTHESIS 12: a": "HYPOTHESIS: a", - "HYPOTHESIS #2: a": "HYPOTHESIS: a", - "TEST 3.: a": "TEST: a", - "REASON (4): a": "REASON: a", - "1. TEST: a": "TEST: a", - "**HYPOTHESIS 1:** a": "HYPOTHESIS: a", - "- FAILURE_MODE 2: a": "FAILURE_MODE: a", - }.items(): - assert _normalise_label_line(line) == want, line - - -def test_a_word_after_the_label_is_not_an_ordinal(): - """Only digits are decoration. `HYPOTHESIS TESTING:` is a different label - and must not be silently read as `HYPOTHESIS:`.""" - assert _normalise_label_line("HYPOTHESIS TESTING: a") == "HYPOTHESIS TESTING: a" - - -def test_a_wrapped_failure_mode_unwraps_but_prose_keeps_its_code_spans(): - """FAILURE_MODE is a lookup key; TEST is a sentence. They need opposite rules. - - Regression from the fix that stopped the normaliser eating content - backticks: a judge writing ``FAILURE_MODE: `ignored_obs` `` then produced - the key "`ignored_obs", which matches nothing in - `_FAILURE_MODE_TO_ANALYZERS` -- so the next cycle's focused re-probe - silently falls back to the generic ranking. Seen live on the Music-AVQA run, - where all three hypotheses came out with a leading backtick. - """ - from evalrx.eval_agent.stages.diagnosis import _unwrap_value - - assert _unwrap_value("`ignored_obs`") == "ignored_obs" - assert _unwrap_value("**language_prior_bias**") == "language_prior_bias" - assert _unwrap_value("plain_mode") == "plain_mode" - # Only an ENTIRELY wrapped value is decoration. - assert _unwrap_value("some `sig` text") == "some `sig` text" - assert _unwrap_value("`unclosed") == "`unclosed" - - raw = ( - "HYPOTHESIS 1: The audio branch contributes a clip-level prior.\n" - "FAILURE_MODE: `ignored_obs`\n" - "TEST: `modality_ablation.grounded_in_audio` HIGHER on failing cases\n" - "EXPECTED_ASSOCIATION: `higher_on_failures`\n" - ) - h = _parse_hypotheses(raw, "videollama2.1-7b-av")[0] - assert h.predicted_failure_mode == "ignored_obs" # a key, unwrapped - assert h.expected_association == "higher_on_failures" - assert h.test_design.startswith("`modality_ablation") # a sentence, intact - - -def test_the_failure_mode_keys_the_next_cycle_actually_routes_on(): - """The unwrapped mode must hit the routing table, or the fix is cosmetic.""" - from evalrx.eval_agent.stages.diagnosis import _unwrap_value - from evalrx.eval_agent.stages.probe import _FAILURE_MODE_TO_ANALYZERS - - for wrapped in ("`ignored_obs`", "`language_prior_bias`"): - assert _unwrap_value(wrapped) in _FAILURE_MODE_TO_ANALYZERS diff --git a/tests/test_eval_agent/test_diagnosis_missing_failure_mode.py b/tests/test_eval_agent/test_diagnosis_missing_failure_mode.py deleted file mode 100644 index 64b58760..00000000 --- a/tests/test_eval_agent/test_diagnosis_missing_failure_mode.py +++ /dev/null @@ -1,104 +0,0 @@ -"""A hypothesis whose ``FAILURE_MODE:`` line the judge forgot is still a hypothesis. - -Live failure (gemma-4-e2b / gsm8k, agy gemini-3.1-pro-preview, 2026-08-27): the -judge answered with three complete HYPOTHESIS / PLAIN_STATEMENT / TEST blocks -and no FAILURE_MODE / EXPECTED_ASSOCIATION lines. ``_parse_hypotheses`` only -appended on ``FAILURE_MODE:``, so three well-formed claims parsed as zero, the -loop stopped with ``no_hypotheses`` and the fix stage never ran — silently: the -run log recorded ``n_hypotheses: 0`` next to a 2.3 KB ``raw_judge_output``. -""" - -from __future__ import annotations - -import logging - -from evalrx.core.model import Capability -from evalrx.eval_agent.stages.diagnosis import ( - MISSING_FAILURE_MODE, - DiagnosisAgent, - _parse_hypotheses, -) -from tests.test_eval_agent.test_auto_diagnose import ScriptedModel, _make_report - -_LIVE_NO_MODE = """HYPOTHESIS: Output truncation (`answer_extraction_audit.output_truncated`) is driven by an excessive number of chain-of-thought sentences. -TEST: Re-run the evaluation with a higher maximum output token limit and check whether truncation drops. -PLAIN_STATEMENT: The model talks too much while reasoning and hits the length limit before printing the answer. - -HYPOTHESIS: Mid-thought self-correction (`cot_faithfulness.cot_changed_answer`) inflates the token count. -TEST: Check whether `cot_changed_answer` co-occurs with `output_truncated`. -PLAIN_STATEMENT: The model changes its mind halfway through and runs out of room. - -HYPOTHESIS: Problems with many distinct quantities (`coverage_verification_gap.n_unique`) exhaust the output budget. -TEST: Measure generation length as a function of `n_unique`. -PLAIN_STATEMENT: When a problem has many details the model writes too much and gets cut off. -""" - -_WELL_FORMED = """HYPOTHESIS: The model over-attends to the first token. -PLAIN_STATEMENT: The model keeps looking at the start of the prompt instead of the question. -FAILURE_MODE: attention_sink -TEST: attention_sink.mean_sink_mass -EXPECTED_ASSOCIATION: higher_on_failures -""" - - -def test_blocks_without_failure_mode_are_kept_with_a_placeholder_mode(): - hs = _parse_hypotheses(_LIVE_NO_MODE, "gemma") - assert len(hs) == 3 - assert {h.predicted_failure_mode for h in hs} == {MISSING_FAILURE_MODE} - assert hs[0].statement.startswith("Output truncation") - assert hs[0].test_design.startswith("Re-run the evaluation") - assert hs[0].plain_statement.startswith("The model talks too much") - assert hs[2].test_design.startswith("Measure generation length") - assert all(h.target_model == "gemma" for h in hs) - - -def test_well_formed_blocks_keep_the_old_reading(): - hs = _parse_hypotheses(_WELL_FORMED, "m") - assert len(hs) == 1 - h = hs[0] - assert h.predicted_failure_mode == "attention_sink" - assert h.test_design == "attention_sink.mean_sink_mass" - assert h.expected_association == "higher_on_failures" - assert h.plain_statement.startswith("The model keeps looking") - - -def test_mixed_blocks_parse_in_order(): - raw = _WELL_FORMED + "\n" + _LIVE_NO_MODE.split("\n\n")[0] + "\n" - hs = _parse_hypotheses(raw, "m") - assert [h.predicted_failure_mode for h in hs] == ["attention_sink", MISSING_FAILURE_MODE] - assert hs[1].test_design.startswith("Re-run the evaluation") - - -def test_lines_after_failure_mode_still_attach_to_the_closed_hypothesis(): - raw = "HYPOTHESIS: a\nFAILURE_MODE: m\nTEST: t1\nEXPECTED_ASSOCIATION: lower_on_failures\n" - hs = _parse_hypotheses(raw, "m") - assert len(hs) == 1 and hs[0].test_design == "t1" - assert hs[0].expected_association == "lower_on_failures" - - -def test_a_bare_hypothesis_label_with_no_statement_is_not_a_hypothesis(): - assert _parse_hypotheses("HYPOTHESIS:\nTEST: t\n", "m") == [] - - -def test_diagnose_reasks_once_when_a_non_empty_answer_parses_to_zero(caplog): - """The judge's first answer carries no label lines at all; the agent asks it - once more for the exact format instead of substituting template hypotheses.""" - judge = ScriptedModel( - answers=[ - "Three paragraphs of prose about attention sinks, without any label lines.", - _WELL_FORMED, - ], - capabilities={Capability.GENERATE}, - ) - with caplog.at_level(logging.WARNING, logger="evalrx.eval_agent.stages.diagnosis"): - diag = DiagnosisAgent(judge=judge).diagnose(_make_report()) - assert [h.predicted_failure_mode for h in diag.hypotheses] == ["attention_sink"] - assert diag.hypotheses[0].statement == "The model over-attends to the first token." - assert any("re-asking" in r.message for r in caplog.records) - assert "over-attends" in diag.raw_judge_output - - -def test_diagnose_does_not_reask_on_a_no_issue_verdict(): - judge = ScriptedModel(answers=["NO_ISSUE"], capabilities={Capability.GENERATE}) - diag = DiagnosisAgent(judge=judge).diagnose(_make_report(severity="none")) - assert diag.hypotheses == [] and judge._i == 1 diff --git a/tests/test_eval_agent/test_diagnosis_typed.py b/tests/test_eval_agent/test_diagnosis_typed.py new file mode 100644 index 00000000..f1c1b065 --- /dev/null +++ b/tests/test_eval_agent/test_diagnosis_typed.py @@ -0,0 +1,162 @@ +"""M3 asks the judge for typed answers: a ``Proposal`` and a critic ``Review``. + +The proposer's reply is validated against the ``Proposal`` schema (an invalid +one goes back once with the errors, then raises); the critic's ``Review`` +annotates hypotheses by number and never removes one. +""" + +from __future__ import annotations + +import pytest + +from evalrx.agent_runtime.judge_call import JudgeCallError +from evalrx.analysis.analysis_module import AnalysisFinding, AnalysisReport +from evalrx.core.capability import Capability +from evalrx.eval_agent.stages.diagnosis import DiagnosisAgent +from tests.conftest import FakeModel +from tests.judge_replies import hypothesis, keep_all, proposal, review + + +class _Judge(FakeModel): + """Answers the proposer from *proposals* in order and the critic with *critic*. + + A reply that is an exception instance is raised instead of returned. + """ + + def __init__(self, proposals: list, critic: object = None) -> None: + super().__init__(capabilities={Capability.GENERATE}) + self._proposals = iter(proposals) + self._critic = critic + self.prompts: list[str] = [] + + def generate(self, inputs, **kw) -> str: + prompt = str(inputs) + self.prompts.append(prompt) + reply = self._critic if "adversarial ML reviewer" in prompt else next(self._proposals) + if isinstance(reply, Exception): + raise reply + return reply + + +def _report(*findings: AnalysisFinding, severity: str = "none") -> AnalysisReport: + return AnalysisReport( + model_name="test-model", findings=list(findings), severity=severity, + narrative="narrative", raw_results={}, + ) + + +def _finding(severity: str, analyzer: str = "attention_sink") -> AnalysisFinding: + return AnalysisFinding( + analyzer=analyzer, metric="mean_sink_mass", value=0.85, threshold=0.6, + direction="above", severity=severity, message="over-attends to the first token", + ) + + +_THREE = proposal( + hypothesis("the model ignores visual evidence entirely", "visual_blindness"), + hypothesis("the model truncates long answers", "termination"), + hypothesis("the model copies the option order it was shown", "position_bias"), +) + + +def test_a_valid_proposal_maps_every_field_onto_the_hypothesis(): + judge = _Judge([proposal(hypothesis( + "the model ignores the image on counting questions", "visual_neglect", + plain="The model counts without looking at the picture.", + test="relative_attention.max_relative_weight LOWER on failing cases", + expected="lower_on_failures", + ))], critic=keep_all(1)) + diag = DiagnosisAgent(judge=judge).diagnose(_report()) + + [h] = diag.hypotheses + assert h.statement == "the model ignores the image on counting questions" + assert h.target_model == "test-model" + assert h.predicted_failure_mode == "visual_neglect" + assert h.plain_statement == "The model counts without looking at the picture." + assert h.test_design == "relative_attention.max_relative_weight LOWER on failing cases" + assert h.expected_association == "lower_on_failures" + assert [c["role"] for c in diag.model_calls] == ["diagnosis_judge", "hypothesis_critic"] + + +@pytest.mark.parametrize("bad_mode", ["`visual_neglect`", "VisualNeglect"]) +def test_a_failure_mode_that_is_not_snake_case_is_sent_back_and_the_second_reply_used(bad_mode): + judge = _Judge([ + proposal(hypothesis("the model ignores the image on counting questions", bad_mode)), + proposal(hypothesis("the model ignores the image on counting questions", "visual_neglect")), + ], critic=keep_all(1)) + diag = DiagnosisAgent(judge=judge).diagnose(_report()) + + assert [h.predicted_failure_mode for h in diag.hypotheses] == ["visual_neglect"] + assert len(judge.prompts) == 3, "proposal, its one retry, then the critic" + retry = judge.prompts[1] + assert "Your previous answer" in retry and bad_mode in retry + # the validation error goes back with it (the schema alone is in every prompt) + assert "hypotheses.0.failure_mode" in retry + assert "hypotheses.0.failure_mode" not in judge.prompts[0] + assert [(c["role"], c["metadata"]["attempt"]) for c in diag.model_calls] == [ + ("diagnosis_judge", 1), ("diagnosis_judge", 2), ("hypothesis_critic", 1), + ] + + +def test_critic_decisions_annotate_by_number_and_order_kept_first(): + judge = _Judge([_THREE], critic=review( + (3, "keep", "the option order explains the failures"), + (1, "reject", "nothing in the evidence tests vision"), + )) + diag = DiagnosisAgent(judge=judge).diagnose(_report()) + + # The critic lists hypotheses numbered in the proposed order. + critic_prompt = judge.prompts[-1] + assert "1. the model ignores visual evidence entirely (failure_mode: visual_blindness)" in critic_prompt + assert "3. the model copies the option order it was shown (failure_mode: position_bias)" in critic_prompt + + # Nothing is dropped; kept first, then the one with no decision, then rejected. + assert [h.predicted_failure_mode for h in diag.hypotheses] == [ + "position_bias", "termination", "visual_blindness"] + assert [h.metadata["critic"] for h in diag.hypotheses] == ["keep", "unparsed", "reject"] + assert diag.hypotheses[0].metadata["critic_reason"] == "the option order explains the failures" + assert "critic_reason" not in diag.hypotheses[1].metadata + # The review record stays in proposed order. + assert [d["decision"] for d in diag.review_decisions] == ["reject", "unparsed", "keep"] + assert diag.n_critic_kept == 1 and diag.n_critic_rejected == 1 + + +@pytest.mark.parametrize("critic", [RuntimeError("judge went away"), "no JSON here at all"], + ids=["judge_raises", "unreadable_review"]) +def test_a_critic_that_gives_no_usable_review_keeps_every_hypothesis(critic): + judge = _Judge([_THREE], critic=critic) + diag = DiagnosisAgent(judge=judge).diagnose(_report()) + + assert [h.predicted_failure_mode for h in diag.hypotheses] == [ + "visual_blindness", "termination", "position_bias"] + assert all("critic" not in h.metadata for h in diag.hypotheses) + assert [d["decision"] for d in diag.review_decisions] == ["review_unavailable"] * 3 + assert diag.n_critic_kept == 0 and diag.n_critic_rejected == 0 + # The failed critic exchanges are still recorded. + critic_calls = diag.model_calls[1:] + assert critic_calls and all(c["role"] == "hypothesis_critic" for c in critic_calls) + + +def test_an_empty_proposal_with_medium_findings_yields_template_hypotheses(): + judge = _Judge([proposal()]) + diag = DiagnosisAgent(judge=judge).diagnose( + _report(_finding("medium"), _finding("low", analyzer="logit_lens"), severity="medium"), + ) + + assert diag.proposed_hypotheses == [] + assert [h.predicted_failure_mode for h in diag.hypotheses] == ["attention_sink"] # low is not templated + assert "over-attends to the first token" in diag.hypotheses[0].statement + assert len(judge.prompts) == 1, "nothing proposed, so no critic call" + + +def test_an_empty_proposal_without_findings_is_no_problem(): + diag = DiagnosisAgent(judge=_Judge([proposal()])).diagnose(_report()) + assert diag.hypotheses == [] and diag.review_decisions == [] + + +def test_a_proposer_that_raises_gives_judge_call_error(): + judge = _Judge([RuntimeError("quota exhausted")]) + with pytest.raises(JudgeCallError, match="quota exhausted") as err: + DiagnosisAgent(judge=judge).diagnose(_report(_finding("high"), severity="high")) + [exchange] = err.value.exchanges + assert exchange.role == "diagnosis_judge" and exchange.output is None diff --git a/tests/test_eval_agent/test_docker_runner.py b/tests/test_eval_agent/test_docker_runner.py new file mode 100644 index 00000000..44c8f392 --- /dev/null +++ b/tests/test_eval_agent/test_docker_runner.py @@ -0,0 +1,16 @@ +"""The in-container runner rebuilds the cases ProbeAgent ships to Docker.""" + +from __future__ import annotations + +from evalrx.agent_runtime._docker_runner import _build_cases +from evalrx.core.case import Label + + +def test_a_case_without_a_usable_label_is_unknown(): + batch = _build_cases([ + {"prompt": "a", "label": "fail"}, + {"prompt": "b"}, + {"prompt": "c", "label": "not-a-label"}, + ]) + assert [case.label for case in batch] == [Label.FAIL, Label.UNKNOWN, Label.UNKNOWN] + assert [case.to_dict()["label"] for case in batch] == ["fail", "unknown", "unknown"] diff --git a/tests/test_eval_agent/test_experiment_writer_safety.py b/tests/test_eval_agent/test_experiment_writer_safety.py index 661092d6..e5274104 100644 --- a/tests/test_eval_agent/test_experiment_writer_safety.py +++ b/tests/test_eval_agent/test_experiment_writer_safety.py @@ -4,6 +4,7 @@ from evalrx.core.capability import Capability from evalrx.eval_agent.hypothesis import Hypothesis +from evalrx.eval_agent.stages.experiment_code import contains_forbidden_model_load from evalrx.eval_agent.stages.experiment_writer import ( ExperimentWriter, ExperimentWriterConfig, @@ -80,4 +81,4 @@ def test_writer_blocks_generated_second_model_load_before_execution(): def test_json_load_is_not_mistaken_for_model_loading(): code = "import json\nwith open('cases.json') as f:\n cases = json.load(f)\n" - assert ExperimentWriter._contains_forbidden_model_load({"experiment.py": code}) is False + assert contains_forbidden_model_load({"experiment.py": code}) is False diff --git a/tests/test_eval_agent/test_explore_context.py b/tests/test_eval_agent/test_explore_context.py index a83af0c5..6994941d 100644 --- a/tests/test_eval_agent/test_explore_context.py +++ b/tests/test_eval_agent/test_explore_context.py @@ -19,6 +19,7 @@ _format_explore_section, ) from tests.conftest import FakeModel +from tests.judge_replies import hypothesis, keep_all, proposal, review # --------------------------------------------------------------------------- # ExploreContext construction @@ -69,10 +70,13 @@ def __init__(self) -> None: def generate(self, inputs, images=None, **kw): # noqa: D401 self.calls.append({"prompt": str(inputs), "images": list(images or [])}) # M3 cites the explore chart it drew the hypothesis from (by title); the - # critic pass keeps it. _extract_referenced reads this output for provenance. - return ("HYPOTHESIS: model ignores the image, consistent with the ObjSize by " - "label chart\nFAILURE_MODE: weak_visual_grounding\n" - "KEEP: model ignores the image, consistent with the ObjSize by label chart") + # critic keeps it. _extract_referenced reads this output for provenance. + if "adversarial ML reviewer" in str(inputs): + return keep_all(1) + return proposal(hypothesis( + "model ignores the image, consistent with the ObjSize by label chart", + "weak_visual_grounding", + )) def _stats_report_with_figure(fig: str) -> StatsAnalysisReport: @@ -208,10 +212,10 @@ def test_loop_init_stores_coerced_explore_context(): def test_log_diagnosis_records_explore_provenance(tmp_path): import json - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.eval_agent.stages.diagnosis import DiagnosisResult - logger = RunLoggerV2(run_dir=tmp_path / "run1", observability_mode="offline") + logger = RunLogger(run_dir=tmp_path / "run1", observability_mode="offline") diag = DiagnosisResult( model_name="vlm", hypotheses=[], @@ -234,14 +238,14 @@ def test_log_diagnosis_persists_the_critic_prompt_beside_its_response(tmp_path): import json from evalrx.eval_agent.hypothesis import Hypothesis - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.eval_agent.stages.diagnosis import DiagnosisResult - logger = RunLoggerV2(run_dir=tmp_path / "run2", observability_mode="offline") + logger = RunLogger(run_dir=tmp_path / "run2", observability_mode="offline") h1 = Hypothesis(statement="h1", target_model="vlm", predicted_failure_mode="x") diag = DiagnosisResult( model_name="vlm", hypotheses=[h1], raw_judge_output="...", - critic_raw_output="REJECT: h1\nREASON: n=30", + critic_raw_output=review((1, "reject", "n=30")), critic_prompt="adversarial reviewer ... LABEL SUMMARY ... gold=no answered=yes", n_critic_rejected=1, proposed_hypotheses=[h1], @@ -253,6 +257,6 @@ def test_log_diagnosis_persists_the_critic_prompt_beside_its_response(tmp_path): # both record shapes travel together: the critic prompt/response and the review list assert entry["proposed_hypotheses"][0]["statement"] == "h1" assert entry["review"]["n_rejected"] == 1 and entry["review"]["decisions"][0]["decision"] == "reject" - # Inlined directly (no sibling .prompt.txt/.response.txt files under V2). - assert entry["critic_raw_output"] == "REJECT: h1\nREASON: n=30" + # Inlined directly (no sibling .prompt.txt/.response.txt files). + assert entry["critic_raw_output"] == review((1, "reject", "n=30")) assert "LABEL SUMMARY" in entry["critic_prompt"] diff --git a/tests/test_eval_agent/test_fix_agent.py b/tests/test_eval_agent/test_fix_agent.py index 23b9fe37..8db7bfb9 100644 --- a/tests/test_eval_agent/test_fix_agent.py +++ b/tests/test_eval_agent/test_fix_agent.py @@ -2065,8 +2065,10 @@ def test_min_tier_filters_cheaper_candidates_for_one_ladder_station(): assert out.attempted assert {v.candidate.tier for v in out.attempted} == {FixTier.L2_SCAFFOLD} - assert len(judge.prompts) == 1 + # One L2 request, sent back once because the answer held no JSON. + assert len(judge.prompts) == 2 assert "L2" in judge.prompts[0] + assert "I refuse to answer in JSON." in judge.prompts[1] def test_no_rubric_cases_yield_recommendation_not_crash(): @@ -2109,12 +2111,12 @@ def forward(self, inputs, capture, spec=None): def test_outcome_serializes_and_logs(tmp_path): - from evalrx.eval_agent import RunLoggerV2 + from evalrx.eval_agent import RunLogger judge = ScriptedJudge( json.dumps([{"name": "careful", "prompt_template": "Look carefully. {prompt}"}]) ) - logger = RunLoggerV2(tmp_path / "logs", observability_mode="offline") + logger = RunLogger(tmp_path / "logs", observability_mode="offline") agent = FixAgent(judge=judge, max_tier="L1", run_logger=logger) out = agent.propose_and_validate(BaselineFailsModel(), _gold_yes_batch(), [_hyp("x")]) d = out.to_dict() @@ -2129,14 +2131,14 @@ def test_outcome_serializes_and_logs(tmp_path): def test_run_fix_on_loop_report(): - from evalrx.eval_agent import VLDiagnoseLoop, VLDiagnoseReport + from evalrx.eval_agent import AutoDiagnoseReport, VLDiagnoseLoop from evalrx.eval_agent.hypothesis import HypothesisStatus from evalrx.eval_agent.stages.hypothesis_tester import HypothesisTestResult from evalrx.eval_agent.stages.protocol import ExperimentProtocol h = _hyp("prompt phrasing underspecifies the task") h.status = HypothesisStatus.SUPPORTED - report = VLDiagnoseReport( + report = AutoDiagnoseReport( cycles=1, stopped_by="max_cycles", verified_hypotheses=[ @@ -2447,9 +2449,9 @@ def forward(self, inputs, capture, spec=None): def test_fix_agent_coded_candidate_fixes_and_logs(tmp_path): pytest.importorskip("PIL") - from evalrx.eval_agent import RunLoggerV2 + from evalrx.eval_agent import RunLogger - logger = RunLoggerV2(tmp_path / "logs", observability_mode="offline") + logger = RunLogger(tmp_path / "logs", observability_mode="offline") agent = FixAgent( judge=CodeWritingJudge(), max_tier="L2", run_logger=logger, exec_timeout_sec=30 ) @@ -3246,9 +3248,9 @@ def test_bridged_attend_enables_coded_l3a(tmp_path): def test_declarative_candidate_gets_record_and_result_but_no_workspace(tmp_path): """A template/spec candidate never touches a sandbox — its trial folder - never gets a workspace/ subdir. Under V2 there is no per-trial - record.md/result.json either (that was a V1-only artifact); the same - outcome data lives inline in M5/log.json's "fix" entry instead.""" + never gets a workspace/ subdir. There is no per-trial + record.md/result.json either; the outcome data lives inline in + M5/log.json's "fix" entry.""" from evalrx.eval_agent.run_context import RunContext ctx = RunContext(tmp_path / "run1") @@ -3284,8 +3286,8 @@ def test_deduped_candidate_in_round_two_leaves_no_trial_folder(tmp_path): """A judge that keeps proposing the SAME failing candidate is deduped before a trial is ever allocated for it — round 2 must not produce a second (duplicate) attempt. A declarative candidate's trial is never - materialized on disk at all under V2 (lazy, and record.md/result.json - are V1-only artifacts), so the dedup guarantee is checked against the + materialized on disk at all (it is lazy, and nothing writes a + record.md/result.json), so the dedup guarantee is checked against the returned attempt list and the inlined M5/log.json record instead of a directory listing.""" from evalrx.eval_agent.run_context import RunContext @@ -3409,9 +3411,8 @@ def test_two_coded_fix_attempts_get_separate_trial_workspaces(tmp_path): ctx.finalize() assert not runtime_root.exists() - # Each attempt's own outcome — not a shared/overwritten one. Under V2 - # there's no per-trial record.md/result.json (V1-only); the same data is - # inlined per-candidate in M5/log.json's "fix" entry instead. + # Each attempt's own outcome — not a shared/overwritten one. It is + # inlined per-candidate in M5/log.json's "fix" entry. fix = json.loads((tmp_path / "run1" / "M5" / "log.json").read_text())["fix"][-1] coded_entries = [a for a in fix["attempted"] if a["kind"] == "code"] assert len(coded_entries) == 2 @@ -3870,9 +3871,9 @@ def test_a_coded_pipeline_that_reads_baseline_output_needs_no_repair_round(tmp_p the first attempt, the host states the support threshold it enforces, the guard anchors every case on its record, the frozen control still holds, and no repair round is spent.""" - from evalrx.eval_agent import RunLoggerV2 + from evalrx.eval_agent import RunLogger - logger = RunLoggerV2(tmp_path / "logs", observability_mode="offline") + logger = RunLogger(tmp_path / "logs", observability_mode="offline") judge = _BaselineOutputJudge() agent = FixAgent( judge=judge, max_tier="L2", run_logger=logger, exec_timeout_sec=30, diff --git a/tests/test_eval_agent/test_fix_validation_end.py b/tests/test_eval_agent/test_fix_validation_end.py index feeadfd5..455e5266 100644 --- a/tests/test_eval_agent/test_fix_validation_end.py +++ b/tests/test_eval_agent/test_fix_validation_end.py @@ -76,6 +76,30 @@ def _mc_score(case, output): return m[-1] == str(case.metadata["gold"]).strip("()").lower() +class _StubFixAgent: + """The fix-agent interface the loop calls, recording what it was handed.""" + + run_logger = None + max_tier = FixTier.L2_SCAFFOLD + alpha = 0.05 + + def __init__(self): + self.hypotheses = None + self.context = None + + def propose_and_validate(self, model, data, hypotheses, prior_attempts=None, + context=None, proposal_data=None, *, + max_tier=None, min_tier=None, record=True): + from evalrx.eval_agent.stages.fix.types import FixOutcome + + self.hypotheses = list(hypotheses) + self.context = context + return FixOutcome(max_tier=self.max_tier) + + def recommend(self, routed, *, model=None, data=None, reason_prefix="", max_tier=None): + return {"recommend_tier": (max_tier or self.max_tier).label, "reason": reason_prefix} + + class CountingModel(Model): """Answers (B) and records every kwargs it was called with.""" @@ -249,7 +273,7 @@ def test_bridge_enforces_floor_and_passes_generation_kwargs(tmp_path): def test_candidate_outputs_and_truncation_are_recorded(tmp_path): - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger class Truncating(CountingModel): def generate(self, inputs, **kwargs): @@ -259,7 +283,7 @@ def generate(self, inputs, **kwargs): judge = ScriptedJudge(json.dumps([ {"name": "rewrite", "prompt_template": "Think step by step. {prompt}"}, ])) - logger = RunLoggerV2(run_dir=tmp_path / "logs", observability_mode="offline") + logger = RunLogger(run_dir=tmp_path / "logs", observability_mode="offline") agent = FixAgent(judge=judge, max_tier="L1", run_logger=logger) batch = _mc_batch(2, 2) out = agent.propose_and_validate(Truncating(), batch, [_hyp("h")]) @@ -268,7 +292,7 @@ def generate(self, inputs, **kwargs): assert all(o.endswith("Answer: (B)") for o in v.outputs.values()) assert v.n_truncated == len(batch) assert "hit the decode cap" in v.summary - # RunLoggerV2 keeps per-case outputs inline under the candidate's own + # RunLogger keeps per-case outputs inline under the candidate's own # "outputs" key in M5/log.json — no sibling outputs.jsonl file. logger.close() m5 = json.loads((tmp_path / "logs" / "M5" / "log.json").read_text()) @@ -358,7 +382,7 @@ def test_floor_skipped_for_image_yes_no_batches(): def test_run_fix_drops_m5_refuted_hypothesis_and_tells_the_proposer(): - from evalrx.eval_agent import VLDiagnoseLoop, VLDiagnoseReport + from evalrx.eval_agent import AutoDiagnoseReport, VLDiagnoseLoop from evalrx.eval_agent.stages.hypothesis_tester import HypothesisTestResult from evalrx.eval_agent.stages.protocol import ExperimentProtocol from evalrx.eval_agent.stages.surgery import InterventionResult @@ -374,7 +398,7 @@ def _tr(h): is_consistent_with_protocol=True, confidence=0.9, verdict="signal vs FAIL effect=+0.9") - report = VLDiagnoseReport(cycles=1, stopped_by="criteria_met", + report = AutoDiagnoseReport(cycles=1, stopped_by="criteria_met", verified_hypotheses=[_tr(h_bad), _tr(h_ok)], final_hypotheses=[h_bad, h_ok]) report.fix_proposal = InterventionResult( @@ -382,19 +406,7 @@ def _tr(h): evidence={"verdict": 0.0, "alt_ordering_rescue_rate": 0.09}, ) - class Recorder: - run_logger = None - - def __init__(self): - self.hypotheses = None - self.context = None - - def propose_and_validate(self, model, data, hypotheses, prior_attempts=None, context=None): - self.hypotheses = list(hypotheses) - self.context = context - return object() - - stub = Recorder() + stub = _StubFixAgent() loop = VLDiagnoseLoop(model=CountingModel(), protocol=ExperimentProtocol(description="BBH"), fix_agent=stub, confirm_split=0.5) loop.run_fix(report, _mc_batch(4, 4)) @@ -410,25 +422,17 @@ def propose_and_validate(self, model, data, hypotheses, prior_attempts=None, con assert {c.id for c in ctx.example_cases}.isdisjoint({c.id for c in confirm}) -def test_run_fix_with_no_verified_hypothesis_does_not_call_minimal_agent(): - """Even a legacy minimal proposer cannot bypass the M4 evidence gate.""" - from evalrx.eval_agent import VLDiagnoseLoop, VLDiagnoseReport +def test_run_fix_with_no_verified_hypothesis_does_not_call_the_fix_agent(): + """The M4 evidence gate is the loop's: the fix agent is not asked.""" + from evalrx.eval_agent import AutoDiagnoseReport, VLDiagnoseLoop from evalrx.eval_agent.stages.protocol import ExperimentProtocol - class Minimal: - run_logger = None - seen = None - - def propose_and_validate(self, model, data, hypotheses): - self.seen = list(hypotheses) - return object() - - stub = Minimal() + stub = _StubFixAgent() loop = VLDiagnoseLoop(model=CountingModel(), protocol=ExperimentProtocol(description="d"), fix_agent=stub) - report = VLDiagnoseReport(cycles=1, stopped_by="max_cycles", final_hypotheses=[_hyp("x")]) + report = AutoDiagnoseReport(cycles=1, stopped_by="max_cycles", final_hypotheses=[_hyp("x")]) outcome = loop.run_fix(report, _mc_batch()) - assert stub.seen is None + assert stub.hypotheses is None assert outcome.stage_status == "skipped" @@ -630,7 +634,7 @@ def raising_strategy(model, case): def _inconclusive_report(): - from evalrx.eval_agent import VLDiagnoseReport + from evalrx.eval_agent import AutoDiagnoseReport from evalrx.eval_agent.stages.hypothesis_tester import HypothesisTestResult hs = [_hyp("lead A (weak)"), _hyp("lead B (best)"), _hyp("lead C (refuted)")] @@ -647,7 +651,7 @@ def _inconclusive_report(): effect_size=-0.3, is_consistent_with_protocol=True, confidence=0.5, verdict="refuted"), ] - return VLDiagnoseReport(cycles=1, stopped_by="max_cycles", verified_hypotheses=[], + return AutoDiagnoseReport(cycles=1, stopped_by="max_cycles", verified_hypotheses=[], all_test_results=trs, final_hypotheses=hs), hs @@ -670,17 +674,7 @@ def test_run_fix_without_verified_skips_repair_authoring(): report, hs = _inconclusive_report() - class Recorder: - run_logger = None - hypotheses = None - context = None - - def propose_and_validate(self, model, data, hypotheses, prior_attempts=None, context=None): - self.hypotheses = list(hypotheses) - self.context = context - return object() - - stub = Recorder() + stub = _StubFixAgent() loop = VLDiagnoseLoop(model=CountingModel(), protocol=ExperimentProtocol(description="d"), fix_agent=stub) outcome = loop.run_fix(report, _mc_batch()) @@ -816,26 +810,17 @@ def fake_run(code, model, data, **kw): # the best unverified leads — the candidate validation on CONFIRM is the gate. -def test_run_fix_allow_unverified_keeps_a_minimal_fix_agent_working(): - """A stub that only accepts (model, data, hypotheses) keeps working and - receives the final proposals when nothing was verified.""" - from evalrx.eval_agent import VLDiagnoseLoop, VLDiagnoseReport +def test_run_fix_allow_unverified_passes_the_final_proposals(): + """With nothing M4-tested, the fix agent receives the last cycle's proposals.""" + from evalrx.eval_agent import AutoDiagnoseReport, VLDiagnoseLoop from evalrx.eval_agent.stages.protocol import ExperimentProtocol - class Minimal: - run_logger = None - seen = None - - def propose_and_validate(self, model, data, hypotheses): - self.seen = list(hypotheses) - return object() - - stub = Minimal() + stub = _StubFixAgent() loop = VLDiagnoseLoop(model=CountingModel(), protocol=ExperimentProtocol(description="d"), fix_agent=stub) - report = VLDiagnoseReport(cycles=1, stopped_by="max_cycles", final_hypotheses=[_hyp("x")]) + report = AutoDiagnoseReport(cycles=1, stopped_by="max_cycles", final_hypotheses=[_hyp("x")]) loop.run_fix(report, _mc_batch(), allow_unverified=True) - assert stub.seen and stub.seen[0].statement == "x" + assert stub.hypotheses and stub.hypotheses[0].statement == "x" def test_run_fix_allow_unverified_uses_unverified_leads_and_says_so(): @@ -844,21 +829,11 @@ def test_run_fix_allow_unverified_uses_unverified_leads_and_says_so(): report, hs = _inconclusive_report() - class Recorder: - run_logger = None - hypotheses = None - context = None - - def propose_and_validate(self, model, data, hypotheses, prior_attempts=None, context=None): - self.hypotheses = list(hypotheses) - self.context = context - return object() - - stub = Recorder() + stub = _StubFixAgent() loop = VLDiagnoseLoop(model=CountingModel(), protocol=ExperimentProtocol(description="d"), fix_agent=stub) outcome = loop.run_fix(report, _mc_batch(), allow_unverified=True) - assert getattr(outcome, "stage_status", "completed") != "skipped" + assert outcome.stage_status != "skipped" assert [h.id for h in stub.hypotheses] == ["h1", "h0"] # best first, refuted dropped assert stub.context.hypotheses_note.startswith("UNVERIFIED") # the proposer sees the caveat right under the hypotheses heading @@ -889,15 +864,7 @@ def test_run_fix_allow_unverified_keeps_leads_beside_verified_symptom(): report.all_test_results.append(supported) report.final_hypotheses.append(symptom) - class Recorder: - run_logger = None - - def propose_and_validate(self, model, data, hypotheses, context=None): - self.hypotheses = list(hypotheses) - self.context = context - return object() - - stub = Recorder() + stub = _StubFixAgent() loop = VLDiagnoseLoop( model=CountingModel(), protocol=ExperimentProtocol(description="d"), diff --git a/tests/test_eval_agent/test_holdout_cases_logged.py b/tests/test_eval_agent/test_holdout_cases_logged.py index 24428f7d..bc16828d 100644 --- a/tests/test_eval_agent/test_holdout_cases_logged.py +++ b/tests/test_eval_agent/test_holdout_cases_logged.py @@ -17,7 +17,7 @@ from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label from evalrx.eval_agent import DiagnosisAgent, RunContext, VLDiagnoseLoop from evalrx.eval_agent.stages.protocol import ExperimentProtocol -from evalrx.reporting.run_events import read_v2_events +from evalrx.reporting.run_events import read_run_events from tests.conftest import FakeModel from tests.test_eval_agent.test_vl_diagnose import ScriptedModel @@ -35,7 +35,7 @@ def _batch(n: int = 20) -> CaseBatch: def _logged_ids(root) -> set[str]: ids = set() - for e in read_v2_events(root): + for e in read_run_events(root): if e.get("event") == "case_record": ids.add(e["case"]["id"]) return ids @@ -71,7 +71,7 @@ def test_logging_a_case_twice_does_not_duplicate_it(tmp_path): ctx.logger.log_cases(cases) ctx.logger.log_cases(cases) ids = [ - e["case"]["id"] for e in read_v2_events(ctx.root) if e.get("event") == "case_record" + e["case"]["id"] for e in read_run_events(ctx.root) if e.get("event") == "case_record" ] assert len(ids) == len(set(ids)) == 8 @@ -97,7 +97,7 @@ def test_each_case_record_names_its_partition(tmp_path): by_split: dict[str, set[str]] = {} run_start = None - for e in read_v2_events(ctx.root): + for e in read_run_events(ctx.root): if e.get("event") == "run_start": run_start = e if e.get("event") == "case_record": diff --git a/tests/test_eval_agent/test_infrastructure.py b/tests/test_eval_agent/test_infrastructure.py index 9f3f8343..ecddaa8e 100755 --- a/tests/test_eval_agent/test_infrastructure.py +++ b/tests/test_eval_agent/test_infrastructure.py @@ -12,7 +12,6 @@ import textwrap from pathlib import Path -from unittest.mock import patch import pytest @@ -293,29 +292,6 @@ def test_jsonl_store_query_filter_by_status(tmp_path): assert supported[0].statement == "s1" -# ───────────────────────────────────────────────────────────────────────────── -# SandboxFactory -# ───────────────────────────────────────────────────────────────────────────── - - -def test_create_sandbox_default_returns_experiment_sandbox(tmp_path): - from evalrx.agent_runtime.factory import SandboxFactoryConfig, create_sandbox - from evalrx.agent_runtime.sandbox import ExperimentSandbox - - sandbox = create_sandbox(SandboxFactoryConfig(), tmp_path) - assert isinstance(sandbox, ExperimentSandbox) - - -def test_create_sandbox_docker_fallback_returns_subprocess(tmp_path): - from evalrx.agent_runtime.factory import SandboxFactoryConfig, create_sandbox - from evalrx.agent_runtime.sandbox import ExperimentSandbox - - # Patch Docker check to simulate unavailability - with patch("evalrx.agent_runtime.factory._try_create_docker_sandbox", return_value=None): - sandbox = create_sandbox(SandboxFactoryConfig(mode="docker"), tmp_path) - assert isinstance(sandbox, ExperimentSandbox) - - # ───────────────────────────────────────────────────────────────────────────── # ExperimentWriterResult backward compat # ───────────────────────────────────────────────────────────────────────────── diff --git a/tests/test_eval_agent/test_log_schema.py b/tests/test_eval_agent/test_log_schema.py index 4ab1e14d..b3033f09 100755 --- a/tests/test_eval_agent/test_log_schema.py +++ b/tests/test_eval_agent/test_log_schema.py @@ -4,7 +4,7 @@ ``run_log.schema.json`` is (1) in sync with the schema-as-code builder, and (2) a well-formed Draft 2020-12 schema. (3) — that what a run actually emits for *every* event type validates against it — lives in -``test_run_logger_v2.py``'s +``test_run_logger.py``'s ``test_persisted_event_identity_orders_concurrent_calls_and_validates``, next to the producer it's checking. """ diff --git a/tests/test_eval_agent/test_loop_explore_step.py b/tests/test_eval_agent/test_loop_explore_step.py index 06385d3e..064f6688 100644 --- a/tests/test_eval_agent/test_loop_explore_step.py +++ b/tests/test_eval_agent/test_loop_explore_step.py @@ -24,11 +24,12 @@ from evalrx.core.result import Result from evalrx.eval_agent.hypothesis import Hypothesis from evalrx.eval_agent.loop import VLDiagnoseLoop -from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 +from evalrx.eval_agent.run_logger import RunLogger from evalrx.eval_agent.stages.diagnosis import DiagnosisResult, ExploreContext from evalrx.eval_agent.stages.protocol import ExperimentProtocol -from evalrx.reporting.run_events import read_v2_events +from evalrx.reporting.run_events import read_run_events from tests.conftest import FakeModel +from tests.judge_replies import hypothesis, keep_all, proposal # ── stubs ───────────────────────────────────────────────────────────────────── @@ -198,7 +199,7 @@ def test_no_explorer_is_a_noop(): def test_explorer_failure_costs_the_notes_not_the_run(tmp_path): calls: list[str] = [] - logger = RunLoggerV2(run_dir=tmp_path / "logs", observability_mode="offline") + logger = RunLogger(run_dir=tmp_path / "logs", observability_mode="offline") loop, diag = _loop(calls, _Explorer(calls, raise_exc=RuntimeError("coder down")), run_logger=logger) @@ -208,7 +209,7 @@ def test_explorer_failure_costs_the_notes_not_the_run(tmp_path): assert calls[:4] == ["m1", "explore", "m2", "m3"] assert report.final_hypotheses # M3 still ran, on M2 alone assert diag.seen_context == [None] - events = read_v2_events(tmp_path / "logs") + events = read_run_events(tmp_path / "logs") ex = [e for e in events if e["event"] == "explore"] assert len(ex) == 1 and ex[0]["ok"] is False and "no report" in ex[0]["error"] # the failed step is still accounted for @@ -234,7 +235,7 @@ def test_explore_persists_beside_logs_and_m3_sees_the_rendered_chart(tmp_path): calls: list[str] = [] workdir = tmp_path / "sandbox" _seed_workdir(workdir) - logger = RunLoggerV2(run_dir=tmp_path / "logs", observability_mode="offline") + logger = RunLogger(run_dir=tmp_path / "logs", observability_mode="offline") loop, diag = _loop(calls, _Explorer(calls, report=_report(workdir)), run_logger=logger) loop.run(_batch()) @@ -252,12 +253,12 @@ def test_explore_persists_beside_logs_and_m3_sees_the_rendered_chart(tmp_path): ctx = diag.seen_context[0] assert ctx.figure_paths == [str(figs[0])] - events = read_v2_events(tmp_path / "logs") + events = read_run_events(tmp_path / "logs") ex = next(e for e in events if e["event"] == "explore") assert ex["ok"] is True and ex["n_charts"] == 1 and ex["n_charts_rendered"] == 1 - # V2 inlines the ephemeral explore workspace into M2/artifacts (a + # The logger inlines the ephemeral explore workspace into M2/artifacts (a # content-hashed copy) instead of leaving a report_path pointer at the - # original workdir — there's no sibling report_path under V2. + # original workdir. assert "report_path" not in ex assert len(ex["figures"]) == 1 and ex["figures"][0].endswith(".png") assert ex["observations"] == _report().observations @@ -271,7 +272,7 @@ def test_explicit_explore_dir_wins(tmp_path): calls: list[str] = [] workdir = tmp_path / "sandbox" _seed_workdir(workdir) - logger = RunLoggerV2(run_dir=tmp_path / "logs", observability_mode="offline") + logger = RunLogger(run_dir=tmp_path / "logs", observability_mode="offline") loop, _ = _loop(calls, _Explorer(calls, report=_report(workdir)), run_logger=logger, explore_dir=tmp_path / "elsewhere") loop.run(_batch()) @@ -320,9 +321,12 @@ def __init__(self) -> None: def generate(self, inputs, images=None, **kw): self.calls.append({"prompt": str(inputs), "images": [str(p) for p in (images or [])]}) - return ("HYPOTHESIS: long chains lose words, consistent with the Mean n_steps " - "by label chart\nFAILURE_MODE: long_chain\n" - "KEEP: long chains lose words, consistent with the Mean n_steps by label chart") + if "adversarial ML reviewer" in str(inputs): + return keep_all(1) + return proposal(hypothesis( + "long chains lose words, consistent with the Mean n_steps by label chart", + "long_chain", + )) def test_real_m3_gets_the_explore_notes_and_the_rendered_png(tmp_path): @@ -333,7 +337,7 @@ def test_real_m3_gets_the_explore_notes_and_the_rendered_png(tmp_path): workdir = tmp_path / "sandbox" _seed_workdir(workdir) judge = _ImageJudge() - logger = RunLoggerV2(run_dir=tmp_path / "logs", observability_mode="offline") + logger = RunLogger(run_dir=tmp_path / "logs", observability_mode="offline") loop = VLDiagnoseLoop( model=FakeModel(), protocol=ExperimentProtocol(description="chains"), probe_agent=_Probe(calls), stats_agent=_Stats(calls), @@ -349,7 +353,7 @@ def test_real_m3_gets_the_explore_notes_and_the_rendered_png(tmp_path): assert "FAIL cases have ~4x longer chains" in prompt png = next((tmp_path / "explore" / "figures").glob("*.png")) assert str(png) in judge.calls[0]["images"] - events = read_v2_events(tmp_path / "logs") + events = read_run_events(tmp_path / "logs") m3 = next(e for e in events if e["event"] == "diagnosis") assert m3.get("explore_context_used") is True assert "Mean n_steps by label" in (m3.get("referenced_charts") or []) @@ -361,7 +365,7 @@ def test_real_m3_gets_the_explore_notes_and_the_rendered_png(tmp_path): def test_default_explore_dir_with_a_run_context_stays_off_the_run_root(tmp_path): """Regression test for the bug where _explore_out_dir() hand-derived ctx.root/"explore" instead of calling ctx.explore_dir — which would have - left real files outside V2's JSON-only run artifact, never cleaned up + left real files outside the JSON-only run artifact, never cleaned up by finalize()'s runtime_root rmtree.""" from evalrx.eval_agent.run_context import RunContext @@ -375,7 +379,7 @@ def test_default_explore_dir_with_a_run_context_stays_off_the_run_root(tmp_path) assert ctx.runtime_root in out_dir.parents assert out_dir != ctx.root / "explore" loop.run(_batch()) - # V2 never leaves real files at /explore; the runtime tree that held + # No real files stay at /explore; the runtime tree that held # them was captured into M2/log.json and then deleted by finalize(). assert not (tmp_path / "run" / "explore").exists() assert (tmp_path / "run" / "M2" / "log.json").is_file() @@ -386,7 +390,7 @@ def test_default_explore_dir_beside_a_standalone_logs_dir_and_inside_other_dirs( for name, expected in (("logs", tmp_path / "explore"), ("logs_confirm", tmp_path / "explore"), ("run_2026", tmp_path / "run_2026" / "explore")): - logger = RunLoggerV2(run_dir=tmp_path / name, observability_mode="offline") + logger = RunLogger(run_dir=tmp_path / name, observability_mode="offline") loop, _ = _loop(calls, _Explorer(calls, report=_report()), run_logger=logger) assert loop._explore_out_dir() == expected, name logger.close() @@ -399,7 +403,8 @@ def test_default_explore_dir_beside_a_standalone_logs_dir_and_inside_other_dirs( def test_agentic_explore_publishes_artifacts_and_passes_notes_to_m3(tmp_path): from evalrx.eval_agent.agentic.board import EvidenceBoard - from evalrx.eval_agent.agentic.tools import _explore_data, _RunState + from evalrx.eval_agent.agentic.tools import _explore_data + from evalrx.eval_agent.policy import RunState from evalrx.eval_agent.run_context import RunContext calls = [] @@ -409,7 +414,7 @@ def test_agentic_explore_publishes_artifacts_and_passes_notes_to_m3(tmp_path): data = _batch() with RunContext(tmp_path / 'run') as ctx: loop, diag = _loop(calls, explorer, run_logger=ctx.logger) - state = _RunState(original_data=data, data=data, timings={}) + state = RunState(original_data=data, data=data, timings={}) state.probe_results = loop.probe_agent.probe(loop.model, data) outcome = _explore_data(loop, state)(EvidenceBoard(), {'question': 'Inspect long chains'}) assert outcome.ok @@ -418,6 +423,6 @@ def test_agentic_explore_publishes_artifacts_and_passes_notes_to_m3(tmp_path): loop._do_m3(0, None, [], state.timings, cases=data) assert diag.seen_context[-1] is not None assert state.timings['explore'] > 0 - events = read_v2_events(tmp_path / 'run') + events = read_run_events(tmp_path / 'run') assert any(e['event'] == 'explore' for e in events) assert any(e['event'] == 'diagnosis' for e in events) diff --git a/tests/test_eval_agent/test_loop_narration.py b/tests/test_eval_agent/test_loop_narration.py index fd63bf39..03abc78a 100644 --- a/tests/test_eval_agent/test_loop_narration.py +++ b/tests/test_eval_agent/test_loop_narration.py @@ -1,5 +1,5 @@ """Regression coverage for the M1-M5 loop's live terminal narration -(RunLoggerV2's `narrate=True` -> LoopNarrator).""" +(RunLogger's `narrate=True` -> LoopNarrator).""" from __future__ import annotations diff --git a/tests/test_eval_agent/test_m1_full_logging.py b/tests/test_eval_agent/test_m1_full_logging.py index 3e21bf9d..43a7d0c2 100644 --- a/tests/test_eval_agent/test_m1_full_logging.py +++ b/tests/test_eval_agent/test_m1_full_logging.py @@ -1,6 +1,6 @@ """M1 (ProbeAgent) full-output logging. -RunLoggerV2.log_probe must capture *everything* M1 generates so a run is +RunLogger.log_probe must capture *everything* M1 generates so a run is fully observable afterwards: per-analyzer COMPLETE results (metadata + n_cases + rendered summary, not just the inlined findings), the heavy artifacts, and the analyzers that were selected but errored at runtime. @@ -13,9 +13,9 @@ def test_log_probe_persists_full_results_and_failed_analyzers(tmp_path): from evalrx.core.result import Result - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger - logger = RunLoggerV2(run_dir=tmp_path / "run", observability_mode="offline") + logger = RunLogger(run_dir=tmp_path / "run", observability_mode="offline") res = Result( analyzer="self_consistency", model="FakeVLM()", @@ -47,9 +47,9 @@ def test_log_probe_persists_full_results_and_failed_analyzers(tmp_path): def test_log_probe_without_failures_omits_failed_analyzers(tmp_path): """No failures -> no failed_analyzers key (kept optional/additive).""" from evalrx.core.result import Result - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger - logger = RunLoggerV2(run_dir=tmp_path / "run", observability_mode="offline") + logger = RunLogger(run_dir=tmp_path / "run", observability_mode="offline") logger.log_probe(0, {"pope": Result(analyzer="pope", model="m", findings={"acc": 0.9})}) logger.close() diff --git a/tests/test_eval_agent/test_model_call_instrumentation.py b/tests/test_eval_agent/test_model_call_instrumentation.py index f582fed8..3b6c6a10 100644 --- a/tests/test_eval_agent/test_model_call_instrumentation.py +++ b/tests/test_eval_agent/test_model_call_instrumentation.py @@ -4,8 +4,8 @@ ``model.generate()`` N times per case and reduce that to one derived score (``consistency``) with the N raw generations gone — no way to see what the model was actually asked or actually said at each of those calls. This is the -gap RunLoggerV2.log_model_call / model_instrumentation.InstrumentedModel -closes; see run_logger_v2.py's log_probe (drains + nests into Langfuse) and +gap RunLogger.log_model_call / model_instrumentation.InstrumentedModel +closes; see run_logger.py's log_probe (drains + nests into Langfuse) and model_instrumentation.py. """ @@ -15,7 +15,7 @@ from evalrx.core.capability import Capability from evalrx.core.case import CaseBatch, FailureCase, Inputs -from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 +from evalrx.eval_agent.run_logger import RunLogger from evalrx.eval_agent.stages.probe_agent import ProbeAgent from tests.conftest import FakeModel @@ -47,7 +47,7 @@ def _batch(n: int = 2) -> CaseBatch: def test_self_consistency_calls_are_recorded_and_survive_the_analyzer(tmp_path): model = _CountingModel(capabilities={Capability.GENERATE}) - run_logger = RunLoggerV2(run_dir=tmp_path / "run1") + run_logger = RunLogger(run_dir=tmp_path / "run1") run_logger.current_cycle = 0 agent = ProbeAgent(run_logger=run_logger) batch = _batch() @@ -56,7 +56,7 @@ def test_self_consistency_calls_are_recorded_and_survive_the_analyzer(tmp_path): run_logger.log_probe(0, results) run_logger.close() - # RunLoggerV2 inlines model_call records into M1/log.json's "model_calls" + # RunLogger inlines model_call records into M1/log.json's "model_calls" # array rather than a sibling model_calls.jsonl file. m1 = _load(tmp_path / "run1", "M1", "log.json") records = m1["model_calls"] @@ -89,7 +89,7 @@ def test_perturbation_analyzer_calls_carry_the_rewritten_prompt(tmp_path): exercise. A rewritten call won't exact-match the case's own prompt, so it should fall back to batch_case_ids (scoped) rather than case_id (exact).""" model = _CountingModel(capabilities={Capability.GENERATE}) - run_logger = RunLoggerV2(run_dir=tmp_path / "run3") + run_logger = RunLogger(run_dir=tmp_path / "run3") run_logger.current_cycle = 0 agent = ProbeAgent(run_logger=run_logger) batch = CaseBatch([FailureCase( @@ -114,7 +114,7 @@ def test_wrapping_does_not_change_result_model_repr(tmp_path): InstrumentedModel must forward it unchanged or every call fragments the experiment cache and mislabels its Result.""" model = FakeModel(capabilities={Capability.GENERATE}) - run_logger = RunLoggerV2(run_dir=tmp_path / "run2") + run_logger = RunLogger(run_dir=tmp_path / "run2") run_logger.current_cycle = 0 agent = ProbeAgent(run_logger=run_logger) @@ -144,7 +144,7 @@ def test_log_probe_drains_calls_tagged_under_a_stale_cycle(tmp_path): forever (they stay durably in M1/log.json's model_calls either way — this is specifically about the buffer/Langfuse side).""" model = _CountingModel(capabilities={Capability.GENERATE}) - run_logger = RunLoggerV2(run_dir=tmp_path / "run4") + run_logger = RunLogger(run_dir=tmp_path / "run4") agent = ProbeAgent(run_logger=run_logger) run_logger.current_cycle = 7 # stale: set as if a PRIOR cycle never advanced diff --git a/tests/test_eval_agent/test_nl_runner.py b/tests/test_eval_agent/test_nl_runner.py new file mode 100644 index 00000000..5b7a46e5 --- /dev/null +++ b/tests/test_eval_agent/test_nl_runner.py @@ -0,0 +1,26 @@ +"""The template scaffold writes a run.py that compiles against today's API.""" + +from __future__ import annotations + +import ast +import importlib +import py_compile + +from evalrx.eval_agent import scaffold_from_description + + +def test_template_scaffold_imports_only_names_that_exist(tmp_path): + out = scaffold_from_description( + "My VLM confuses left and right in spatial questions", output_dir=tmp_path / "exp", + ) + run_py = out / "run.py" + assert {p.name for p in out.iterdir()} >= {"run.py", "Dockerfile", "docker-compose.yml"} + py_compile.compile(str(run_py), doraise=True) + missing = [ + f"{node.module}.{alias.name}" + for node in ast.walk(ast.parse(run_py.read_text(encoding="utf-8"))) + if isinstance(node, ast.ImportFrom) and (node.module or "").startswith("evalrx") + for alias in node.names + if not hasattr(importlib.import_module(node.module or ""), alias.name) + ] + assert missing == [] diff --git a/tests/test_eval_agent/test_policy.py b/tests/test_eval_agent/test_policy.py new file mode 100644 index 00000000..544a4553 --- /dev/null +++ b/tests/test_eval_agent/test_policy.py @@ -0,0 +1,104 @@ +"""The loop owns the run bracket; a policy only decides the order of the stages. + +Also: a run that a policy stopped on M3 shows M3 as failed in the report. +""" + +from __future__ import annotations + +from evalrx.core.capability import Capability +from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label +from evalrx.eval_agent import AutoDiagnoseReport, FixedOrderPolicy, JudgePolicy, VLDiagnoseLoop +from evalrx.eval_agent.run_context import RunContext +from evalrx.eval_agent.stages.protocol import ExperimentProtocol +from evalrx.reporting.run_events import read_run_events +from tests.conftest import FakeModel + + +def _loop(tmp_path, **kwargs) -> tuple[RunContext, VLDiagnoseLoop]: + ctx = RunContext(tmp_path / "run", verbose=False) + loop = VLDiagnoseLoop( + model=FakeModel(capabilities={Capability.GENERATE}), + protocol=ExperimentProtocol(description="policy test", target_modalities=frozenset({"text"})), + run_logger=ctx.logger, + **kwargs, + ) + return ctx, loop + + +def test_the_fixed_order_is_the_default_policy(tmp_path): + _, loop = _loop(tmp_path) + assert isinstance(loop.policy, FixedOrderPolicy) + _, judged = _loop(tmp_path, policy=JudgePolicy(FakeModel())) + assert isinstance(judged.policy, JudgePolicy) + + +def test_a_custom_policy_gets_the_loop_and_the_run_bracket(tmp_path): + seen = {} + + class OneStep: + def run(self, loop, data, timings): + seen["tokens_reset"] = loop._tokens_used == 0 + timings["m1"] = 1.5 + return AutoDiagnoseReport(cycles=1, stopped_by="custom", store=loop.store) + + ctx, loop = _loop(tmp_path, policy=OneStep()) + loop._tokens_used = 99 + data = CaseBatch([FailureCase(inputs=Inputs(prompt="q"), label=Label.FAIL)]) + + report = loop.run(data) + + assert report.stopped_by == "custom" and seen["tokens_reset"] + ctx.finalize() + (end,) = [e for e in read_run_events(ctx.root) if e["event"] == "loop_end"] + assert end["stopped_by"] == "custom" + + +def test_a_run_that_stopped_on_m3_shows_m3_as_failed_in_the_report(tmp_path): + from evalrx.reporting.dynamic import build_report_data + + class Unreadable: + def diagnose(self, analysis, **kwargs): + raise RuntimeError("the judge's answer could not be read") + + ctx, loop = _loop(tmp_path, diagnosis_agent=Unreadable()) + data = CaseBatch([ + FailureCase(inputs=Inputs(prompt=f"q{i}"), label=Label.FAIL if i % 2 else Label.PASS) + for i in range(4) + ]) + assert loop.run(data).stopped_by == "diagnosis_error" + ctx.finalize() + + report = build_report_data(ctx.root) + m3 = next(s for s in report["stages"] if s["id"] == "m3") + assert m3["status"] == "failed" + assert "could not be read" in report["stage_detail"]["m3"]["error"] + + +def test_a_later_m3_failure_keeps_the_earlier_hypotheses_in_the_report(tmp_path): + from evalrx.eval_agent import DiagnosisResult, Hypothesis + from evalrx.reporting.dynamic import build_report_data + + class FailsSecond: + calls = 0 + + def diagnose(self, analysis, **kwargs): + FailsSecond.calls += 1 + if FailsSecond.calls > 1: + raise RuntimeError("the judge's answer could not be read") + h = Hypothesis(statement="The model guesses without looking.", target_model="m", + predicted_failure_mode="no_such_signal") + return DiagnosisResult(model_name="m", hypotheses=[h], raw_judge_output="{}") + + ctx, loop = _loop(tmp_path, diagnosis_agent=FailsSecond(), max_cycles=2) + data = CaseBatch([ + FailureCase(inputs=Inputs(prompt=f"q{i}"), label=Label.FAIL if i % 2 else Label.PASS) + for i in range(4) + ]) + report = loop.run(data) + assert report.stopped_by == "diagnosis_error" and len(report.final_hypotheses) == 1 + ctx.finalize() + + data = build_report_data(ctx.root) + assert next(s for s in data["stages"] if s["id"] == "m3")["status"] == "failed" + detail = data["stage_detail"]["m3"] + assert detail["error"] and len(detail["hypotheses"]) == 1 diff --git a/tests/test_eval_agent/test_probe_routing_whitebox.py b/tests/test_eval_agent/test_probe_routing_whitebox.py index 4f66d6c5..e9e954fa 100644 --- a/tests/test_eval_agent/test_probe_routing_whitebox.py +++ b/tests/test_eval_agent/test_probe_routing_whitebox.py @@ -22,7 +22,6 @@ from evalrx.core.registry import registry # noqa: E402 from evalrx.eval_agent.stages.probe import ( # noqa: E402 _FAILURE_MODE_TO_ANALYZERS, - _PRIORITY, _SLOT_PRIORITY, StrategyProbe, ) @@ -48,7 +47,6 @@ def test_every_routed_analyzer_is_registered(): tables = { **{f"failure_mode:{k}": v for k, v in _FAILURE_MODE_TO_ANALYZERS.items()}, **{f"slot:{k}": v for k, v in _SLOT_PRIORITY.items()}, - **{f"kind:{k}": v for k, v in _PRIORITY.items()}, } unknown = {where: sorted(set(names) - registered) for where, names in tables.items() if set(names) - registered} diff --git a/tests/test_eval_agent/test_run_logger_v2.py b/tests/test_eval_agent/test_run_logger.py similarity index 88% rename from tests/test_eval_agent/test_run_logger_v2.py rename to tests/test_eval_agent/test_run_logger.py index 5ec682a5..cae333f0 100644 --- a/tests/test_eval_agent/test_run_logger_v2.py +++ b/tests/test_eval_agent/test_run_logger.py @@ -1,5 +1,5 @@ -"""RunLoggerV2 conformance: every log_* method, exercised end to end, must -produce the tidy M1..M5 layout described in RUN_LOGGER_V2.md — few files, +"""RunLogger conformance: every log_* method, exercised end to end, must +produce the tidy M1..M5 layout described in RUN_LOGGER.md — few files, same-type-in-one-json, one folder per stage, nothing but JSON except real binary media. @@ -16,17 +16,17 @@ from types import SimpleNamespace -def _emit_every_method(run_dir) -> "RunLoggerV2": # noqa: F821 +def _emit_every_method(run_dir) -> "RunLogger": # noqa: F821 from evalrx.analysis.explorer import ExploratoryAnalysisReport from evalrx.analysis.stats_agent import StatsAnalysisReport from evalrx.core import CaseBatch, FailureCase from evalrx.core.result import Result from evalrx.eval_agent.hypothesis import Hypothesis, HypothesisStatus - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.eval_agent.stages.diagnosis import DiagnosisResult from evalrx.eval_agent.stages.surgery import InterventionResult - logger = RunLoggerV2(run_dir=run_dir) + logger = RunLogger(run_dir=run_dir) logger.current_cycle = 0 logger.log_run_start({"model": "fake", "n_cases": 3}) @@ -249,10 +249,10 @@ def test_unroutable_tag_with_no_alias_warns_and_lands_in_run_json(tmp_path): run.json["unrouted"] rather than silently dropped.""" import pytest - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger run_dir = tmp_path / "run1" - logger = RunLoggerV2(run_dir=run_dir) + logger = RunLogger(run_dir=run_dir) logger.log_run_start() with pytest.warns(UserWarning, match="totally_new_stage"): logger.log_tool_codegen( @@ -287,10 +287,10 @@ def test_probe_artifacts_land_under_that_stages_artifacts_dir(tmp_path): import numpy as np from evalrx.core.result import Result - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger run_dir = tmp_path / "run1" - logger = RunLoggerV2(run_dir=run_dir) + logger = RunLogger(run_dir=run_dir) logger.log_run_start() res = Result( analyzer="attention_sink", model="fake", findings={"n_cases": 1}, @@ -308,16 +308,15 @@ def test_probe_artifacts_land_under_that_stages_artifacts_dir(tmp_path): def test_model_calls_are_recorded_and_probe_events_stay_intact_alongside(tmp_path): - """Wiring parity with the V1 InstrumentedModel fix: ProbeAgent + RunLoggerV2 - together must still capture every target-model call.""" + """ProbeAgent + RunLogger together must capture every target-model call.""" from evalrx.core.capability import Capability from evalrx.core.case import CaseBatch, FailureCase, Inputs - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.eval_agent.stages.probe_agent import ProbeAgent from tests.conftest import FakeModel run_dir = tmp_path / "run1" - logger = RunLoggerV2(run_dir=run_dir) + logger = RunLogger(run_dir=run_dir) logger.current_cycle = 0 model = FakeModel(capabilities={Capability.GENERATE}) agent = ProbeAgent(run_logger=logger) @@ -346,9 +345,9 @@ def test_atomic_write_leaves_a_valid_file_after_every_event(tmp_path): def test_close_ends_the_langfuse_trace(tmp_path): run_dir = tmp_path / "run1" - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger - logger = RunLoggerV2(run_dir=run_dir) + logger = RunLogger(run_dir=run_dir) logger.log_run_start({"model": "fake"}) logger.close() assert (run_dir / "langfuse_trace.json").exists() @@ -357,15 +356,15 @@ def test_close_ends_the_langfuse_trace(tmp_path): def test_full_loop_run_is_a_drop_in_replacement_for_run_logger(tmp_path): """The strongest check available without a real model: run an actual VLDiagnoseLoop.run() — the same real integration test_holdout_cases_logged - exercises against RunLogger — with RunLoggerV2 constructed directly + exercises against RunLogger — with RunLogger constructed directly (bypassing RunContext, a known, documented scope cut) instead of ctx.logger, and confirm no other loop/stage code needed to change AND the - held-out split's cases still get logged (the exact regression that test - guards against for V1).""" + held-out split's cases still get logged (the regression that test guards + against).""" from evalrx.core.capability import Capability from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label from evalrx.eval_agent import DiagnosisAgent, VLDiagnoseLoop - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.eval_agent.stages.protocol import ExperimentProtocol from tests.conftest import FakeModel from tests.test_eval_agent.test_vl_diagnose import ScriptedModel @@ -380,7 +379,7 @@ def test_full_loop_run_is_a_drop_in_replacement_for_run_logger(tmp_path): ]) all_ids = {c.id for c in cases} run_dir = tmp_path / "run1" - logger = RunLoggerV2(run_dir=run_dir) + logger = RunLogger(run_dir=run_dir) VLDiagnoseLoop( model=FakeModel(capabilities={Capability.GENERATE}, modalities={"text"}), protocol=ExperimentProtocol(description="does it answer?", task_domain="qa"), @@ -398,7 +397,7 @@ def test_full_loop_run_is_a_drop_in_replacement_for_run_logger(tmp_path): f"{len(missing)} of {len(all_ids)} cases were never logged — the same " "held-out-split regression test_holdout_cases_logged.py guards against." ) - # M1 actually ran and produced a probe entry — the loop drove RunLoggerV2 + # M1 actually ran and produced a probe entry — the loop drove RunLogger # through log_probe (and, transitively, InstrumentedModel/log_model_call) # exactly as it drives RunLogger. m1 = _load(run_dir, "M1", "log.json") @@ -424,7 +423,7 @@ def test_run_context_v2_keeps_only_json_and_media_and_inlines_reports(tmp_path): code="print('candidate')", ) report = SimpleNamespace( - cycles=1, stopped_by="done", resolved=False, all_hypotheses=[], + cycles=1, stopped_by="done", resolved=False, final_hypotheses=[], verified_hypotheses=[], all_test_results=[], ) ctx.write_diagnose_report(report, [], discovery=[{"id": "case-1"}]) @@ -507,33 +506,33 @@ def test_run_context_v2_root_holds_no_v1_named_directories(tmp_path): ctx.logger.log_run_start({"model": "fake"}) report = SimpleNamespace( - cycles=1, stopped_by="done", resolved=False, all_hypotheses=[], + cycles=1, stopped_by="done", resolved=False, final_hypotheses=[], verified_hypotheses=[], all_test_results=[], ) ctx.write_diagnose_report(report, [], discovery=[]) ctx.finalize() top_level = {p.name for p in root.iterdir()} - v1_only = {"explore", "figures", "report", "tools", "workspace", "fixes", - "experiments", "run_log.jsonl", "manifest.json", "README.txt"} - assert not (top_level & v1_only), top_level + loose_files = {"explore", "figures", "report", "tools", "workspace", "fixes", + "experiments", "run_log.jsonl", "manifest.json", "README.txt"} + assert not (top_level & loose_files), top_level assert top_level <= {"run.json", "M1", "M2", "M3", "M4", "M5", "artifacts", "contract", "langfuse_trace.json"} - # figures_dir/artifacts_dir's file did land under the V2 mapping (M2/artifacts), + # figures_dir/artifacts_dir's file did land under M2/artifacts, # not disappear — this isn't just an absence check. assert (root / "M2" / "artifacts" / "effect.png").is_file() def test_reporting_reader_and_server_discover_v2_run(tmp_path): from evalrx.observability.tracer import backfill_run_to_langfuse - from evalrx.reporting.run_events import read_v2_events, resolve_v2_root + from evalrx.reporting.run_events import read_run_events, resolve_run_root from evalrx.reporting.server import find_run_root root = tmp_path / "archive" / "logs" _emit_every_method(root) - events = read_v2_events(root.parent) + events = read_run_events(root.parent) - assert resolve_v2_root(root.parent) == root.resolve() + assert resolve_run_root(root.parent) == root.resolve() assert find_run_root(tmp_path / "archive") == root assert any(event["event"] == "run_start" for event in events) assert any(event["event"] == "case_record" for event in events) @@ -551,11 +550,11 @@ def test_reporting_reader_and_server_discover_v2_run(tmp_path): def test_non_numeric_probe_artifacts_survive_without_sidecar_files(tmp_path): from evalrx.core.result import Result - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger artifacts = {"details": {"answer": "yes"}, "samples": ["yes", "no"], "rows": [{"case_id": "a", "score": 0.5}]} - with RunLoggerV2(tmp_path, observability_mode="offline") as logger: + with RunLogger(tmp_path, observability_mode="offline") as logger: logger.log_probe(0, {"probe": Result( analyzer="probe", model="stub", findings={}, artifacts=artifacts, )}) @@ -624,28 +623,21 @@ def fail_copy(*args, **kwargs): assert not runtime.exists() -def test_m4_case_study_accepts_new_and_legacy_v2_bundles(tmp_path): +def test_the_case_study_reads_m4_from_the_logged_bundle(tmp_path): from evalrx.reporting.case_study import _m4 - from evalrx.reporting.run_events import read_v2_events + from evalrx.reporting.run_events import read_run_events _emit_every_method(tmp_path) - for legacy in (False, True): - if legacy: - path = tmp_path / "M4" / "log.json" - doc = _load(tmp_path, "M4", "log.json") - for event in doc["surgery"]: - event.pop("module") - path.write_text(json.dumps(doc)) - events = read_v2_events(tmp_path) - rows = _m4(SimpleNamespace(events_of=lambda name: [e for e in events if e["event"] == name])) - assert len(rows) == 1 - assert rows[0]["status"] == "supported" - assert rows[0]["test_name"] == "paired_t_test" + events = read_run_events(tmp_path) + rows = _m4(SimpleNamespace(events_of=lambda name: [e for e in events if e["event"] == name])) + assert len(rows) == 1 + assert rows[0]["status"] == "supported" + assert rows[0]["test_name"] == "paired_t_test" def test_loop_summary_keeps_verified_hypothesis_evidence(tmp_path): from evalrx.eval_agent.hypothesis import Hypothesis, HypothesisStatus - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.eval_agent.stages.hypothesis_tester import HypothesisTestResult hypothesis = Hypothesis(statement="why", target_model="stub", predicted_failure_mode="mode") @@ -653,9 +645,9 @@ def test_loop_summary_keeps_verified_hypothesis_evidence(tmp_path): hypothesis=hypothesis, status=HypothesisStatus.SUPPORTED, test_name="audit", effect_size=0.2, is_consistent_with_protocol=True, confidence=0.9, verdict="supported", ) - with RunLoggerV2(tmp_path, observability_mode="offline") as logger: + with RunLogger(tmp_path, observability_mode="offline") as logger: logger.log_loop_end(SimpleNamespace( - cycles=1, stopped_by="verified", all_hypotheses=[hypothesis], verified_hypotheses=[result], + cycles=1, stopped_by="verified", final_hypotheses=[hypothesis], verified_hypotheses=[result], )) assert _load(tmp_path, "run.json")["loop_end"][0]["verified_hypotheses"] == [{ "statement": "why", "failure_mode": "mode", "status": "supported", @@ -667,46 +659,48 @@ def test_persisted_event_identity_orders_concurrent_calls_and_validates(tmp_path from concurrent.futures import ThreadPoolExecutor from evalrx.eval_agent.log_schema import EVENT_TYPES, _validator, build_schema - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 - from evalrx.reporting.run_events import read_v2_events + from evalrx.eval_agent.run_logger import RunLogger + from evalrx.reporting.run_events import read_run_events monkeypatch.setenv("EVALRX_VALIDATE_LOG", "1") _emit_every_method(tmp_path) validator = _validator(build_schema()) - emitted = read_v2_events(tmp_path) + emitted = read_run_events(tmp_path) for event in emitted: validator.validate(event) # Every event type the schema knows about actually got exercised here — # catches a type that's defined but never driven by this conformance check. # diagnose_report and unrouted aren't part of _emit_every_method's mirror - # of RunLoggerV2's log_* API; they're validated in their own dedicated + # of RunLogger's log_* API; they're validated in their own dedicated # tests instead (test_run_context_v2_keeps_only_json_and_media_and_inlines_reports, # test_unroutable_tag_with_no_alias_warns_and_lands_in_run_json). covered = {e["event"] for e in emitted} expected = set(EVENT_TYPES) - {"diagnose_report", "unrouted"} assert covered == expected, f"uncovered event types: {expected - covered}" root = tmp_path / "concurrent" - with RunLoggerV2(root, observability_mode="offline") as logger: + with RunLogger(root, observability_mode="offline") as logger: monkeypatch.setattr(logger, "_ts", lambda: "2026-09-07T00:00:00+00:00") with ThreadPoolExecutor(max_workers=4) as pool: list(pool.map(lambda index: logger.log_model_exchange( f"M{index % 5 + 1}", role="test", operation="generate", inputs=index, output=index, ), range(30))) - events = read_v2_events(root) - assert [event["event_seq"] for event in events] == list(range(1, 31)) - assert len({event["span_id"] for event in events}) == 30 + events = read_run_events(root) + # 30 calls, then the run_end the logger writes as it closes. + assert [event["event_seq"] for event in events] == list(range(1, 32)) + assert events[-1]["event"] == "run_end" + assert len({event["span_id"] for event in events}) == 31 for event in events: validator.validate(event) - assert [event["event_seq"] for event in read_v2_events(root)] == list(range(1, 31)) + assert [event["event_seq"] for event in read_run_events(root)] == list(range(1, 32)) def test_v2_schema_validation_warns_but_preserves_invalid_event(tmp_path, monkeypatch): import pytest - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger monkeypatch.setenv("EVALRX_VALIDATE_LOG", "1") - with RunLoggerV2(tmp_path, observability_mode="offline") as logger: + with RunLogger(tmp_path, observability_mode="offline") as logger: with pytest.warns(UserWarning, match="violates log schema"): logger.log_stage_skipped("M4", "reason", cycle="invalid") assert _load(tmp_path, "M4", "log.json")["stage_skipped"][0]["cycle"] == "invalid" @@ -741,10 +735,10 @@ def test_hypothesis_id_joins_m3_to_m4_and_m5(tmp_path): def test_outbox_dir_is_per_user(monkeypatch, tmp_path): - # A shared /tmp/evalrx-v2-outbox is owned by whoever created it first, so + # A shared /tmp/evalrx-outbox is owned by whoever created it first, so # every other user on the host failed with "unable to open database file". - import evalrx.eval_agent.run_logger_v2 as v2 + import evalrx.eval_agent.run_logger as run_logger - monkeypatch.setattr(v2.tempfile, "gettempdir", lambda: str(tmp_path)) - monkeypatch.setattr(v2.getpass, "getuser", lambda: "alice") - assert v2._outbox_dir() == tmp_path / "evalrx-v2-outbox-alice" + monkeypatch.setattr(run_logger.tempfile, "gettempdir", lambda: str(tmp_path)) + monkeypatch.setattr(run_logger.getpass, "getuser", lambda: "alice") + assert run_logger._outbox_dir() == tmp_path / "evalrx-outbox-alice" diff --git a/tests/test_eval_agent/test_run_logger_overlays.py b/tests/test_eval_agent/test_run_logger_overlays.py index 231b6f47..3d4b38e9 100755 --- a/tests/test_eval_agent/test_run_logger_overlays.py +++ b/tests/test_eval_agent/test_run_logger_overlays.py @@ -1,6 +1,6 @@ -"""RunLoggerV2.log_probe <-> Result.image_overlays() wiring. +"""RunLogger.log_probe <-> Result.image_overlays() wiring. -The bare attention heatmaps RunLoggerV2 saves have no spatial reference to the +The bare attention heatmaps RunLogger saves have no spatial reference to the actual image; Result subclasses (e.g. RelativeAttentionResult) can define an ``image_overlays(fig_dir, stem_prefix) -> list[Path]`` hook to additionally save heatmap-on-image visualisations, which must flow into log_probe's @@ -54,9 +54,9 @@ class _FakeResultNoOverlays: def test_log_probe_returns_overlay_png_from_result_hook(tmp_path): - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger - logger = RunLoggerV2(run_dir=tmp_path / "run1") + logger = RunLogger(run_dir=tmp_path / "run1") pngs = logger.log_probe(0, {"fake_analyzer": _FakeResultWithOverlays()}) assert len(pngs) == 1 assert pngs[0].name == "c0_fake_analyzer_fake_overlay.png" @@ -65,18 +65,18 @@ def test_log_probe_returns_overlay_png_from_result_hook(tmp_path): def test_log_probe_survives_image_overlays_raising(tmp_path): - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger - logger = RunLoggerV2(run_dir=tmp_path / "run1") + logger = RunLogger(run_dir=tmp_path / "run1") pngs = logger.log_probe(0, {"broken_analyzer": _FakeResultOverlaysRaise()}) assert pngs == [] logger.close() def test_log_probe_without_image_overlays_hook_is_unaffected(tmp_path): - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger - logger = RunLoggerV2(run_dir=tmp_path / "run1") + logger = RunLogger(run_dir=tmp_path / "run1") pngs = logger.log_probe(0, {"plain_analyzer": _FakeResultNoOverlays()}) assert pngs == [] logger.close() @@ -88,7 +88,7 @@ def test_log_probe_combines_overlay_and_npy_heatmap_pngs(tmp_path): pytest.importorskip("matplotlib") import numpy as np - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger @dataclass class _Mixed: @@ -106,7 +106,7 @@ def image_overlays(self, fig_dir, stem_prefix) -> "list[Path]": path.write_bytes(b"\x89PNG\r\n\x1a\n") return [path] - logger = RunLoggerV2(run_dir=tmp_path / "run1") + logger = RunLogger(run_dir=tmp_path / "run1") pngs = logger.log_probe(0, {"mixed_analyzer": _Mixed()}) names = {p.name for p in pngs} assert "c0_mixed_analyzer_overlay.png" in names diff --git a/tests/test_eval_agent/test_stats_tools.py b/tests/test_eval_agent/test_stats_tools.py index eb4ec235..be1be5c7 100755 --- a/tests/test_eval_agent/test_stats_tools.py +++ b/tests/test_eval_agent/test_stats_tools.py @@ -4,7 +4,7 @@ - build_stats_input: per-case signals / labels / scalars / strategy groups - each catalog tool on synthetic data (signal_label_assoc, bootstrap_diff, mcnemar_evalue, friedman_nemenyi, single_rate_evalue, rank_corr) - - default_plan shape from the data + - the deterministic plan's shape from the data - fdr_correct (e-BH across e-values) - StatsAnalysisAgent orchestration + backward compat (no data → threshold only) """ @@ -12,10 +12,10 @@ from __future__ import annotations import evalrx.analysis as public_analysis +from evalrx.analysis.planner import plan_stats_input from evalrx.analysis.stats_tools import ( StatsInput, StatsToolResult, - default_plan, run_stats_tool, ) from evalrx.core.case import CaseBatch, FailureCase, Inputs, Label @@ -202,17 +202,16 @@ def test_rank_corr_on_continuous_signal(): # ── planner + FDR ─────────────────────────────────────────────────────────── -def test_default_plan_picks_relevant_tools(): +def test_plan_picks_relevant_tools(): inp = build_stats_input({"attention": _attention_result()}, _labeled_cases()) - plan = default_plan(inp) - tools = {t for t, _, _ in plan} + tools = {item.tool for item in plan_stats_input(inp)} assert "signal_label_assoc" in tools assert "single_rate_evalue" in tools -def test_default_plan_empty_without_labels_or_groups(): +def test_plan_empty_without_labels_or_groups(): inp = StatsInput() # nothing testable - assert default_plan(inp) == [] + assert plan_stats_input(inp) == [] def test_fdr_correct_with_evalues(): @@ -286,7 +285,6 @@ def test_fdr_correct_signal_pvalues_use_bh(): out = fdr_correct([r]) # unpaired signal test enters the BH p-value family assert out["method"] == "BH" assert out["n_tested"] == 1 - assert out["rejected_tools"] == ["signal_label_assoc"] assert out["rejected_result_keys"] == ["signal_label_assoc:attention.low_img_attn"] assert r.fdr_corrected is True and r.correction_method == "BH" diff --git a/tests/test_eval_agent/test_targeted_testing.py b/tests/test_eval_agent/test_targeted_testing.py index fdcc968d..7625a301 100755 --- a/tests/test_eval_agent/test_targeted_testing.py +++ b/tests/test_eval_agent/test_targeted_testing.py @@ -29,6 +29,7 @@ ) from evalrx.eval_agent.stages.protocol import ExperimentProtocol from tests.conftest import FakeModel +from tests.judge_replies import hypothesis, keep_all, proposal, review # ── fixtures ──────────────────────────────────────────────────────────────── @@ -212,7 +213,7 @@ def test_best_hypotheses_prefers_intervention_grade(): assert best[0].evidence_grade == "intervention" -# ── P3 diagnosis: TEST line + available evidence ──────────────────────────── +# ── P3 diagnosis: test field + available evidence ──────────────────────────── class ScriptedJudge(FakeModel): @@ -235,13 +236,13 @@ def generate(self, inputs, **kw) -> str: return next(self._answers) -def test_diagnosis_parses_test_line_into_design(): - judge = ScriptedJudge( - "HYPOTHESIS: the model ignores the image\n" - "FAILURE_MODE: visual_blindness\n" - "TEST: relative_attention.max_relative_weight association\n" - "EXPECTED_ASSOCIATION: lower_on_failures\n" - ) +def test_diagnosis_maps_the_test_field_into_design(): + judge = TwoAnswerJudge([ + proposal(hypothesis("the model ignores the image", "visual_blindness", + test="relative_attention.max_relative_weight association", + expected="lower_on_failures")), + keep_all(1), + ]) diag = DiagnosisAgent(judge=judge).diagnose(_report()) assert len(diag.hypotheses) == 1 assert diag.hypotheses[0].test_design == "relative_attention.max_relative_weight association" @@ -254,13 +255,11 @@ def test_critic_rejection_annotates_instead_of_deleting(): M4/M5/fix. The verdict is provenance now: the hypothesis stays, flagged, and the held-out M4 decides.""" judge = TwoAnswerJudge([ - "HYPOTHESIS: the model ignores visual evidence entirely\n" - "PLAIN_STATEMENT: The model answers without looking at the picture.\n" - "FAILURE_MODE: visual_blindness\n" - "TEST: relative_attention.max_relative_weight\n" - "EXPECTED_ASSOCIATION: lower_on_failures\n", - "REJECT: the model ignores visual evidence entirely\n" - "REASON: the cited evidence does not test that mechanism\n", + proposal(hypothesis("the model ignores visual evidence entirely", "visual_blindness", + plain="The model answers without looking at the picture.", + test="relative_attention.max_relative_weight", + expected="lower_on_failures")), + review((1, "reject", "the cited evidence does not test that mechanism")), ]) diag = DiagnosisAgent(judge=judge).diagnose(_report()) assert len(diag.hypotheses) == 1 @@ -268,7 +267,7 @@ def test_critic_rejection_annotates_instead_of_deleting(): assert h.metadata["critic"] == "reject" assert h.metadata["critic_reason"] == "the cited evidence does not test that mechanism" assert diag.n_critic_rejected == 1 and diag.n_critic_kept == 0 - assert "REJECT:" in diag.critic_raw_output + assert '"reject"' in diag.critic_raw_output def test_critic_record_carries_the_proposer_reviewer_shape_too(): @@ -277,16 +276,14 @@ def test_critic_record_carries_the_proposer_reviewer_shape_too(): annotations — the reviewer records, it never removes (2026-08-21 merge of the two M3-critic designs).""" judge = TwoAnswerJudge([ - "HYPOTHESIS: the model ignores visual evidence entirely\n" - "PLAIN_STATEMENT: The model answers without looking at the picture.\n" - "FAILURE_MODE: visual_blindness\n" - "HYPOTHESIS: the model truncates long answers\n" - "PLAIN_STATEMENT: The model stops writing before it reaches the answer.\n" - "FAILURE_MODE: termination\n", - "KEEP: the model truncates long answers\n" - "REASON: termination_audit shows it\n" - "REJECT: the model ignores visual evidence entirely\n" - "REASON: the cited evidence does not test that mechanism\n", + proposal( + hypothesis("the model ignores visual evidence entirely", "visual_blindness", + plain="The model answers without looking at the picture."), + hypothesis("the model truncates long answers", "termination", + plain="The model stops writing before it reaches the answer."), + ), + review((2, "keep", "termination_audit shows it"), + (1, "reject", "the cited evidence does not test that mechanism")), ]) diag = DiagnosisAgent(judge=judge).diagnose(_report()) assert [h.statement for h in diag.proposed_hypotheses] == [ @@ -304,7 +301,7 @@ def test_critic_record_carries_the_proposer_reviewer_shape_too(): def test_diagnosis_prompt_lists_available_evidence(): - judge = ScriptedJudge("NO_ISSUE") + judge = ScriptedJudge(proposal()) DiagnosisAgent(judge=judge).diagnose(_report()) p = judge.prompts[0] assert "AVAILABLE EVIDENCE" in p diff --git a/tests/test_eval_agent/test_verbose_logging.py b/tests/test_eval_agent/test_verbose_logging.py index d79508a0..41b84f6c 100644 --- a/tests/test_eval_agent/test_verbose_logging.py +++ b/tests/test_eval_agent/test_verbose_logging.py @@ -64,10 +64,7 @@ def test_loop_stage_narration_is_actually_visible(capsys): evalrx.disable_console_logging() -# V1's console narration (_VerboseFormatter) rendered stats_plan/ -# corrected_rejections/etc. field-by-field, which is where this suite used -# to guard against a real crash (an externalised {path, n_items, bytes} -# stand-in iterated as if it were still the raw list — see git history for -# the fix). RunLoggerV2's narration (_V2JsonFormatter.line) is a one-line -# `[stage] event cycle=N` summary that never touches those fields, so that -# bug class does not exist to regress here anymore. +# RunLogger's narration (_EventLine.line) is a one-line +# `[stage] event cycle=N` summary. It never renders stats_plan / +# corrected_rejections field by field, so there is no per-field rendering to +# guard here. diff --git a/tests/test_eval_agent/test_vl_diagnose.py b/tests/test_eval_agent/test_vl_diagnose.py index 56a125ec..9d28a2a1 100755 --- a/tests/test_eval_agent/test_vl_diagnose.py +++ b/tests/test_eval_agent/test_vl_diagnose.py @@ -11,6 +11,7 @@ from __future__ import annotations +import json from typing import Any from evalrx.core.capability import Capability @@ -18,6 +19,7 @@ from evalrx.core.result import Result from evalrx.eval_agent import ( AnalysisModule, + AutoDiagnoseReport, CaseDiscoveryAgent, DiagnosisAgent, HypothesisTester, @@ -25,13 +27,12 @@ ProbeAgent, StatsAnalysisAgent, StatsAnalysisReport, - StatsToolAgent, VLDiagnoseLoop, - VLDiagnoseReport, ) from evalrx.eval_agent.hypothesis import Hypothesis, HypothesisStatus from evalrx.eval_agent.stages.protocol import ExperimentProtocol, ProbingSchema from tests.conftest import FakeModel +from tests.judge_replies import hypothesis, keep_all, proposal # ── helpers ──────────────────────────────────────────────────────────────────── @@ -96,6 +97,21 @@ def generate(self, inputs, **kwargs) -> str: return answer +class M3Judge(FakeModel): + """An M3 judge: gives *reply* to the proposer and keeps every hypothesis + when asked as the adversarial critic.""" + + def __init__(self, reply: str, n_keep: int = 1, **kwargs: Any) -> None: + super().__init__(**kwargs) + self.reply, self.n_keep = reply, n_keep + self.prompts: list[str] = [] + + def generate(self, inputs, **kwargs) -> str: + prompt = str(inputs) + self.prompts.append(prompt) + return keep_all(self.n_keep) if "adversarial ML reviewer" in prompt else self.reply + + # ══════════════════════════════════════════════════════════════════════════════ # ExperimentProtocol # ══════════════════════════════════════════════════════════════════════════════ @@ -226,6 +242,35 @@ def test_structured_judge_scoring_records_reason(self): "The observed answer names blue." ) + def test_judge_without_a_valid_label_falls_back_to_the_rubric_and_says_so(self): + model = ScriptedModel(["The answer is red."], capabilities={Capability.GENERATE}) + + class Rambling(FakeModel): + def __init__(self): + super().__init__(capabilities={Capability.GENERATE}) + self.calls = 0 + + def generate(self, inputs, **kwargs): + self.calls += 1 + return "It's probably fine, I guess." + + judge = Rambling() + candidates = CaseBatch([FailureCase( + id="colour", inputs=Inputs(prompt="Which color is lowest?"), + expected={"all_of": ["blue"]}, + )]) + report = CaseDiscoveryAgent(judge=judge).discover(model, candidates) + assert judge.calls == 2 # sent back once with the validation errors + assert report.n_fail == 1 # the rubric decides: "red" lacks "blue" + assert "heuristic fallback" in report.cases[0].metadata["discovery_reason"] + + def test_a_lowercase_label_is_read(self): + model = ScriptedModel(["blue"], capabilities={Capability.GENERATE}) + judge = ScriptedModel(['{"label": "fail", "reason": "wrong colour"}'], + capabilities={Capability.GENERATE}) + candidates = CaseBatch([FailureCase(id="c", inputs=Inputs(prompt="q"), expected="blue")]) + assert CaseDiscoveryAgent(judge=judge).discover(model, candidates).n_fail == 1 + # ══════════════════════════════════════════════════════════════════════════════ # ProbingSchema / ProbeAgent.probe_with_schema @@ -379,7 +424,7 @@ def test_llm_prompt_includes_complete_output_contract(self): success_criteria="Reply with only the option letter.", output_contract={"kind": "multiple_choice_letter", "choices": ["A", "B", "C", "D"]}, ) - judge = ScriptedModel(["CONCLUSION: No issue.\nEVIDENCE_CHAIN:\n- none\nQUALITATIVE:\n- none"]) + judge = ScriptedModel(['{"conclusion": "No issue.", "evidence_chain": ["none"]}']) report = StatsAnalysisAgent(judge=judge).analyze({}, protocol=protocol) assert "Reply with only the option letter" in report.llm_prompt assert '"kind": "multiple_choice_letter"' in report.llm_prompt @@ -394,43 +439,6 @@ def test_stats_tool_basic_path(self): report = StatsAnalysisAgent().analyze({}) assert report.stats_tool == "threshold_rules" - def test_stats_tools_collect_scalar_metrics(self): - results = {"self_consistency": Result( - analyzer="self_consistency", model="m", - cases=CaseBatch([]), - findings={"consistency": 0.25, "n_samples": 4}, - )} - report = StatsAnalysisAgent().analyze(results) - - names = [tool["name"] for tool in report.stats_tool_results] - assert "scalar_summary" in names - assert report.visualizations - assert report.to_dict()["stats_tool_results"] - - def test_stats_tools_compute_per_case_label_association(self): - cases = [ - FailureCase(id="fail_1", inputs=Inputs(prompt="q1"), label=Label.FAIL), - FailureCase(id="pass_1", inputs=Inputs(prompt="q2"), label=Label.PASS), - ] - data = CaseBatch(cases) - results = {"attention": Result( - analyzer="attention", - model="m", - cases=data, - findings={"per_case": [{"sample_id": "fail_1", "has_issue": True}]}, - )} - - report = StatsAnalysisAgent().analyze(results) - tool = next( - t for t in report.stats_tool_results - if t["name"] == "per_case_signal_label_association" - ) - - assert tool["metrics"]["n_signal"] == 1 - assert tool["metrics"]["n_no_signal"] == 1 - assert tool["metrics"]["fail_rate_signal"] == 1.0 - assert tool["metrics"]["fail_rate_control"] == 0.0 - def test_stats_tool_agent_can_be_disabled(self): results = {"self_consistency": Result( analyzer="self_consistency", model="m", @@ -438,21 +446,8 @@ def test_stats_tool_agent_can_be_disabled(self): findings={"consistency": 0.25}, )} report = StatsAnalysisAgent(enable_stats_tools=False).analyze(results) - assert report.stats_tool_results == [] - assert report.visualizations == [] - - def test_stats_tool_agent_selects_expected_tools(self): - results = {"attention": Result( - analyzer="attention", - model="m", - cases=CaseBatch([]), - findings={ - "mean_entropy": 0.5, - "per_case": [{"sample_id": "x", "has_issue": True}], - }, - )} - selected = StatsToolAgent().select(results) - assert selected == ["scalar_summary", "per_case_signal_label_association"] + assert report.stats_results == [] + assert report.figures == [] def test_llm_guided_path_falls_back_on_failure(self): # A judge that raises should fall back to basic path silently @@ -468,12 +463,12 @@ def generate(self, *a, **kw): assert report.stats_tool == "threshold_rules" def test_llm_guided_path_uses_judge(self): - expected = ( - "CONCLUSION: Spatial attention is broken.\n" - "EVIDENCE_CHAIN:\n- Analyzer attention flagged anomaly\n" - "- Protocol expects spatial tasks\n- No corroborating signals\n" - "QUALITATIVE:\n- Entropy is unusually high\n" - ) + expected = json.dumps({ + "conclusion": "Spatial attention is broken.", + "evidence_chain": ["Analyzer attention flagged anomaly", "Protocol expects spatial tasks", + "No corroborating signals"], + "qualitative": ["Entropy is unusually high"], + }) judge = ScriptedModel([expected]) protocol = _spatial_protocol() agent = StatsAnalysisAgent(judge=judge) @@ -483,7 +478,8 @@ def test_llm_guided_path_uses_judge(self): )} report = agent.analyze(results, protocol=protocol) assert report.stats_tool == "llm_guided" - assert "broken" in report.conclusion.lower() or len(report.conclusion) > 0 + assert report.conclusion == "Spatial attention is broken." + assert report.qualitative_findings == ["Entropy is unusually high"] # ══════════════════════════════════════════════════════════════════════════════ @@ -714,12 +710,9 @@ def test_fallback_signal_uses_empty_outputs_not_labels(self): # ══════════════════════════════════════════════════════════════════════════════ def _scripted_diagnosis_agent(mode: str = "attention") -> DiagnosisAgent: - hyp_json = ( - f'[{{"hypothesis": "Model fails due to {mode} issue.", ' - f'"failure_mode": "{mode}"}}]' - ) - judge = ScriptedModel([hyp_json]) - return DiagnosisAgent(judge=judge) + return DiagnosisAgent(judge=M3Judge(proposal( + hypothesis(f"Model fails due to {mode} issue.", mode), + ))) class TestVLDiagnoseLoop: @@ -733,7 +726,7 @@ def test_run_returns_vl_diagnose_report(self): max_cycles=1, ) report = loop.run(_labeled_batch()) - assert isinstance(report, VLDiagnoseReport) + assert isinstance(report, AutoDiagnoseReport) def test_report_has_cycles(self): loop = VLDiagnoseLoop( @@ -745,7 +738,7 @@ def test_report_has_cycles(self): report = loop.run(_labeled_batch()) assert report.cycles >= 1 - def test_report_has_all_hypotheses(self): + def test_report_has_final_hypotheses(self): loop = VLDiagnoseLoop( model=_vlm(), protocol=_spatial_protocol(), @@ -753,7 +746,7 @@ def test_report_has_all_hypotheses(self): max_cycles=1, ) report = loop.run(_labeled_batch()) - assert len(report.all_hypotheses) >= 1 + assert len(report.final_hypotheses) >= 1 def test_report_has_test_results(self): loop = VLDiagnoseLoop( @@ -833,7 +826,7 @@ def test_run_m5_returns_none_without_verified(self): diagnosis_agent=_scripted_diagnosis_agent(), max_cycles=1, ) - report = VLDiagnoseReport(cycles=1, stopped_by="max_cycles") + report = AutoDiagnoseReport(cycles=1, stopped_by="max_cycles") result = loop.run_m5(report, _labeled_batch()) assert result is None @@ -855,7 +848,7 @@ def test_run_m5_operates_on_best_hypothesis(self): confidence=0.7, verdict="supported", ) - report = VLDiagnoseReport( + report = AutoDiagnoseReport( cycles=1, stopped_by="criteria_met", verified_hypotheses=[tr], @@ -903,7 +896,7 @@ def test_analysis_only_stops_after_m2(self): report = loop.run(_labeled_batch()) assert report.cycles == 1 assert report.final_stats_report is not None - assert report.all_hypotheses == [] + assert report.final_hypotheses == [] assert report.all_test_results == [] def test_no_diagnosis_agent_stops_early(self, monkeypatch): @@ -961,7 +954,7 @@ def test_run_analysis_proposes_without_confirming(self): report = loop.run_analysis(data) assert report.stopped_by == "analysis_complete" assert report.cycles == 1 - assert len(report.all_hypotheses) >= 1 + assert len(report.final_hypotheses) >= 1 # M4 did not run: no test results, nothing verified. assert report.all_test_results == [] assert report.verified_hypotheses == [] @@ -972,9 +965,9 @@ def test_run_analysis_no_hypotheses_when_m3_empty(self): # An M3 that yields nothing still leaves a valid analysis (stats) report. loop, data = self._signal_setup() # Swap in a diagnosis agent whose judge returns no hypotheses. - loop.diagnosis_agent = DiagnosisAgent(judge=ScriptedModel(["[]"])) + loop.diagnosis_agent = DiagnosisAgent(judge=ScriptedModel([proposal()])) report = loop.run_analysis(data) - assert report.all_hypotheses == [] + assert report.final_hypotheses == [] assert report.stopped_by == "no_hypotheses" assert report.final_stats_report is not None @@ -989,7 +982,7 @@ def test_run_confirm_with_reloaded_hypotheses_and_stats(self): loop, data = self._signal_setup() analysis = loop.run_analysis(data) reloaded = [hypothesis_from_dict(hypothesis_to_dict(h)) - for h in analysis.all_hypotheses] + for h in analysis.final_hypotheses] confirmed = loop.run_confirm( data, reloaded, stats_report=analysis.final_stats_report @@ -1008,7 +1001,7 @@ def test_run_confirm_regenerates_stats_when_omitted(self): loop, data = self._signal_setup() analysis = loop.run_analysis(data) reloaded = [hypothesis_from_dict(hypothesis_to_dict(h)) - for h in analysis.all_hypotheses] + for h in analysis.final_hypotheses] # No stats_report supplied → run_confirm re-runs M1→M2 silently. confirmed = loop.run_confirm(data, reloaded) assert len(confirmed.all_test_results) == len(reloaded) @@ -1023,7 +1016,7 @@ def test_confirm_then_run_m5(self): loop, data = self._signal_setup() analysis = loop.run_analysis(data) reloaded = [hypothesis_from_dict(hypothesis_to_dict(h)) - for h in analysis.all_hypotheses] + for h in analysis.final_hypotheses] confirmed = loop.run_confirm( data, reloaded, stats_report=analysis.final_stats_report ) @@ -1056,7 +1049,7 @@ def test_run_confirm_promotes_to_confirmatory(self): loop, data = self._signal_setup() analysis = loop.run_analysis(data) confirmed = loop.run_confirm( - data, list(analysis.all_hypotheses), + data, list(analysis.final_hypotheses), stats_report=analysis.final_stats_report, ) sr = confirmed.final_stats_report @@ -1075,45 +1068,6 @@ def test_run_keeps_validity_inline(self): assert report.final_stats_report.descriptive_only is False -class TestDescriptivePhaseCompiler: - """The compiler hides validity in analysis-phase (descriptive) mode.""" - - _EXPLORE = { - "candidate_signals": [ - {"name": "focus_share", "reject": True, "effect": 0.4, "ci": [0.1, 0.7]} - ] - } - - def test_descriptive_mode_demotes_claims(self): - from evalrx.reporting.compiler import compile_diagnostic_report - - story = {"analyses": [{"cycle": 0, "descriptive_only": True}], "surgeries": []} - rep = compile_diagnostic_report(story, self._EXPLORE).to_dict() - assert rep["claims"], "expected at least one claim" - assert all(c["status"] == "descriptive" for c in rep["claims"]) - assert any("ANALYSIS PHASE" in c for c in rep["caveats"]) - - def test_confirmatory_mode_shows_validity(self): - from evalrx.reporting.compiler import compile_diagnostic_report - - # A confirmatory M2 (descriptive_only False) restores the supported verdict. - story = {"analyses": [{"cycle": 0, "descriptive_only": False}], "surgeries": []} - rep = compile_diagnostic_report(story, self._EXPLORE).to_dict() - assert any(c["status"] == "supported" for c in rep["claims"]) - - def test_surgery_presence_restores_validity(self): - from evalrx.reporting.compiler import compile_diagnostic_report - - # Even a descriptive analysis flips to validity once a confirm-phase - # surgery (M4) is recorded in the merged story. - story = { - "analyses": [{"cycle": 0, "descriptive_only": True}], - "surgeries": [{"cycle": 0, "module": "m4"}], - } - rep = compile_diagnostic_report(story, self._EXPLORE).to_dict() - assert any(c["status"] == "supported" for c in rep["claims"]) - - class TestM3FaultTolerance: def test_judge_exception_in_m3_does_not_kill_loop(self, tmp_path): """A judge timeout/quota error in M3 must end the loop gracefully @@ -1126,9 +1080,9 @@ def diagnose(self, analysis, model_name="", prior_cycles=None): import json - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger - run_logger = RunLoggerV2(tmp_path / "logs") + run_logger = RunLogger(tmp_path / "logs") loop = VLDiagnoseLoop( model=_vlm(), protocol=_spatial_protocol(), @@ -1136,14 +1090,14 @@ def diagnose(self, analysis, model_name="", prior_cycles=None): max_cycles=2, run_logger=run_logger, ) report = loop.run(_labeled_batch()) - assert isinstance(report, VLDiagnoseReport) + assert isinstance(report, AutoDiagnoseReport) assert report.stopped_by == "diagnosis_error" errors = json.loads((tmp_path / "logs/M3/log.json").read_text())["model_calls"] assert len(errors) == 2 assert errors[0]["metadata"]["retrying"] is True assert errors[1]["metadata"]["retrying"] is False assert all("timed out" in e["error"] for e in errors) - assert report.all_hypotheses == [] + assert report.final_hypotheses == [] def test_default_is_a_single_diagnosis_cycle(): @@ -1288,7 +1242,7 @@ def test_run_confirm_tests_on_holdout(self): def test_m3_transient_error_retries_without_reprobing(tmp_path): from types import SimpleNamespace - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger class Transient: calls = 0 @@ -1297,11 +1251,11 @@ def diagnose(self, analysis, **kwargs): self.calls += 1 if self.calls == 1: raise TimeoutError("transient timeout") - return SimpleNamespace(hypotheses=[], raw_judge_output="NO_ISSUE", tokens_used=1) + return SimpleNamespace(hypotheses=[], raw_judge_output=proposal(), tokens_used=1) agent = Transient() loop = VLDiagnoseLoop(model=_vlm(), protocol=_spatial_protocol(), diagnosis_agent=agent, - run_logger=RunLoggerV2(tmp_path / "logs")) + run_logger=RunLogger(tmp_path / "logs")) result = loop._do_m3(0, None, [], {}, log=False) assert result is not None and result.hypotheses == [] assert agent.calls == 2 diff --git a/tests/test_examples/test_benchmark_common.py b/tests/test_examples/test_benchmark_common.py index 051296e4..c9ffd907 100644 --- a/tests/test_examples/test_benchmark_common.py +++ b/tests/test_examples/test_benchmark_common.py @@ -411,7 +411,7 @@ def test_skip_m5_is_independent_of_fix_and_tier_search(common): def test_run_fix_isolated_hides_the_run_dir_from_the_fix_stage_and_restores_it(common, tmp_path): """The fix stage must not be able to read baseline.json / discovery_cases / the run-wide log from its workspace; afterwards everything is back, and - the managed JSON log the fix stage rewrote is kept as-is (RunLoggerV2 + the managed JSON log the fix stage rewrote is kept as-is (RunLogger rewrites a whole document atomically, so the new one already carries everything the old one had — no append, no `.pre_fix` sibling).""" import importlib diff --git a/tests/test_examples/test_figure_data_extract.py b/tests/test_examples/test_figure_data_extract.py index 3e7e3888..9b5cbff2 100644 --- a/tests/test_examples/test_figure_data_extract.py +++ b/tests/test_examples/test_figure_data_extract.py @@ -74,7 +74,7 @@ def _write(path: Path, payload) -> None: def make_run(root: Path, *, signal_values=None, m4_effect=-0.42, n_broken=1) -> Path: - """Write a run directory in the RunLoggerV2 shape _common/runner.py + + """Write a run directory in the RunLogger shape _common/runner.py + RunContext produce: run.json (run-wide events + manifest) plus one JSON document per stage under M1..M5, no run_log.jsonl / manifest.json / report/*.json siblings.""" diff --git a/tests/test_examples/test_llm_benchmark_internals.py b/tests/test_examples/test_llm_benchmark_internals.py index 0315f3d2..555735b8 100644 --- a/tests/test_examples/test_llm_benchmark_internals.py +++ b/tests/test_examples/test_llm_benchmark_internals.py @@ -557,9 +557,9 @@ def test_a_freshly_built_batch_is_not_reported_stale(): def test_load_prior_run_reads_the_last_cycle_and_rebuilds_the_report(pipe, tmp_path): - """RunLoggerV2 keeps every cycle's entry in an array under its own stage; + """RunLogger keeps every cycle's entry in an array under its own stage; the last entry is the one confirm-only reloads. Nothing is externalised - to a sibling file under V2 — stats_results and analyzer results are + to a sibling file — stats_results and analyzer results are inline — so this only needs the three stage documents, no artifacts/.""" logs = tmp_path / "logs" (logs / "M1").mkdir(parents=True) diff --git a/tests/test_examples/test_vlm_benchmark_common.py b/tests/test_examples/test_vlm_benchmark_common.py index d7acb3e8..e882fecd 100644 --- a/tests/test_examples/test_vlm_benchmark_common.py +++ b/tests/test_examples/test_vlm_benchmark_common.py @@ -35,7 +35,7 @@ def test_examples_choose_their_model_through_the_config(): import re from pathlib import Path - from evalrx.models import resolve_spec_key + from evalrx.specs import REGISTRY common = _module() assert common.BenchmarkConfig.model == "qwen2.5-vl-7b-instruct" # the default @@ -44,6 +44,6 @@ def test_examples_choose_their_model_through_the_config(): src = (root / example / "run.py").read_text() key = re.search(r'model="([^"]+)"', src).group(1) assert key == "qwen3.5-2b-vl" - assert resolve_spec_key(key) == key # a registered spec, not an alias + assert key in REGISTRY for example in ("chartqa_qwen2_5_vl", "spatial457_qwen2_5_vl"): assert 'model=' not in (root / example / "run.py").read_text() diff --git a/tests/test_models/test_qwen.py b/tests/test_models/test_qwen.py index af4b384c..362415c6 100755 --- a/tests/test_models/test_qwen.py +++ b/tests/test_models/test_qwen.py @@ -1,15 +1,12 @@ -"""Back-compat tests for the deprecated ``QwenLLM`` shim. +"""hf_local generation paths driven through a fake model. -The concrete Qwen class is gone — identity lives in ``evalrx.specs`` and -construction goes through ``compose``. ``QwenLLM(...)`` is kept only as a -deprecated alias that builds an ``hf_local`` model. (HF-local forward/capture -mechanics are covered by ``test_models/test_discover.py`` and the analyzer tests; -spec×backend composition by ``test_models/test_compose.py``.) +(HF-local forward/capture mechanics are covered by +``test_models/test_discover.py`` and the analyzer tests; spec×backend +composition by ``test_models/test_compose.py``.) """ from __future__ import annotations -import warnings from types import SimpleNamespace import pytest @@ -21,33 +18,6 @@ from evalrx.core.spec import AudioSpec, ModelSpec, VisionSpec from evalrx.models.backends.base import RuntimeConfig from evalrx.models.backends.hf.model import HFLocalModel -from evalrx.models.whitebox.qwen import QwenLLM - - -def test_qwenllm_warns_deprecation(): - with pytest.warns(DeprecationWarning, match="evalrx.load"): - QwenLLM() - - -def test_qwenllm_returns_hf_local_model_with_caps(): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - model = QwenLLM() - assert isinstance(model, HFLocalModel) - assert model.spec.key == "qwen2.5-7b-instruct" - # capabilities come from the hf_local backend + spec (no weights loaded) - assert Capability.ATTENTION in model.capabilities - assert Capability.HIDDEN_STATES in model.capabilities - assert Capability.GENERATE in model.capabilities - assert Capability.GRADIENTS in model.capabilities # forward(with_grad=True) - assert Capability.EMBEDDINGS not in model.capabilities - - -def test_qwenllm_checkpoint_override(): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - model = QwenLLM(checkpoint="some/other-qwen") - assert model.spec.hf_repo == "some/other-qwen" def test_hf_vcd_processor_contrasts_clean_and_noisy_scores_each_step(): diff --git a/tests/test_models/test_whitebox_factories.py b/tests/test_models/test_whitebox_factories.py index e60f8ce1..4d12b222 100755 --- a/tests/test_models/test_whitebox_factories.py +++ b/tests/test_models/test_whitebox_factories.py @@ -2,8 +2,6 @@ from __future__ import annotations -import pytest - from evalrx.core.capability import Capability from evalrx.models.whitebox import qwen as qmod from evalrx.models.whitebox import qwen_omni as qomnimod @@ -53,11 +51,3 @@ def test_factory_names_exposed(): for name in ["qwen3_omni_30b_a3b_instruct", "qwen3_omni_30b_a3b_captioner"]: assert name in qomnimod.__all__ and callable(getattr(qomnimod, name)) - -def test_legacy_shims_still_work_with_deprecation(): - with pytest.warns(DeprecationWarning): - m = qmod.QwenLLM() - assert m.spec.key == "qwen2.5-7b-instruct" - with pytest.warns(DeprecationWarning): - vm = qvlmod.QwenVL() - assert vm.spec.key == "qwen2.5-vl-7b-instruct" and vm.spec.is_vlm diff --git a/tests/test_observability/test_outbox.py b/tests/test_observability/test_outbox.py index 0dbcc719..11b1a8ec 100644 --- a/tests/test_observability/test_outbox.py +++ b/tests/test_observability/test_outbox.py @@ -69,18 +69,19 @@ def test_skipped_stage_keeps_its_pipeline_stage_in_the_envelope(): def test_backfill_dry_run_preserves_existing_trace_and_order(tmp_path): - from evalrx.eval_agent.run_logger_v2 import RunLoggerV2 + from evalrx.eval_agent.run_logger import RunLogger from evalrx.observability import backfill_run_to_langfuse trace_id = "00000000-0000-0000-0000-000000000001" - logger = RunLoggerV2(tmp_path, trace_id=trace_id, observability_mode="offline") + logger = RunLogger(tmp_path, trace_id=trace_id, observability_mode="offline") logger.log_run_start({}) logger._append_stage("M2", "analysis", {}) logger.close() summary = backfill_run_to_langfuse(tmp_path, dry_run=True) - assert summary == {"trace_id": trace_id, "events": 2, "pending": 2, "published": 0} + # run_start, analysis, and the run_end close() writes. + assert summary == {"trace_id": trace_id, "events": 3, "pending": 3, "published": 0} def test_tracer_flushes_events_through_langfuse_client(tmp_path): diff --git a/tools/colab/lock/gpu.txt b/tools/colab/lock/gpu.txt index 7a0be4ac..c7308d56 100644 --- a/tools/colab/lock/gpu.txt +++ b/tools/colab/lock/gpu.txt @@ -11,7 +11,11 @@ annotated-doc==0.0.5 annotated-types==0.8.0 # via pydantic anyio==4.15.1 - # via httpx + # via + # httpx + # httpx2 + # pydantic-ai-slim + # pydantic-graph attrs==26.1.0 # via aiohttp certifi==2026.7.22 @@ -59,14 +63,26 @@ fsspec==2026.7.0 # datasets # huggingface-hub # torch +genai-prices==0.2.5 + # via pydantic-ai-slim +griffelib==2.4.1 + # via pydantic-ai-slim h11==0.16.0 - # via httpcore + # via + # httpcore + # httpcore2 hf-xet==1.7.0 # via huggingface-hub httpcore==1.0.9 # via httpx +httpcore2==2.16.2 + # via httpx2 httpx==0.28.1 # via huggingface-hub +httpx2==2.16.2 + # via + # genai-prices + # pydantic-ai-slim huggingface-hub==1.33.0 # via # accelerate @@ -77,6 +93,7 @@ idna==3.20 # via # anyio # httpx + # httpx2 # requests # yarl interface-meta==2.0.1 @@ -87,6 +104,8 @@ joblib==1.6.0 # via scikit-learn kiwisolver==1.5.1 # via matplotlib +logfire-api==6.0.0 + # via pydantic-graph markdown-it-py==4.2.0 # via rich markupsafe==3.0.4 @@ -163,6 +182,8 @@ nvidia-nvshmem-cu12==3.4.5 # via torch nvidia-nvtx-cu12==12.9.79 # via cuda-toolkit +opentelemetry-api==1.45.2 + # via pydantic-ai-slim packaging==26.3 # via # accelerate @@ -194,9 +215,17 @@ psutil==7.2.2 pyarrow==26.0.0 # via datasets pydantic==2.14.0 + # via + # evalrx (pyproject.toml) + # genai-prices + # pydantic-ai-slim + # pydantic-graph +pydantic-ai-slim==2.71.0 # via evalrx (pyproject.toml) pydantic-core==2.50.0 # via pydantic +pydantic-graph==2.71.0 + # via pydantic-ai-slim pygments==2.21.0 # via rich pyparsing==3.3.3 @@ -262,6 +291,10 @@ transformers==5.15.0 # evalrx (pyproject.toml) triton==3.7.1 # via torch +truststore==0.10.5 + # via + # httpcore2 + # httpx2 typer==0.27.3 # via transformers typing-extensions==4.16.0 @@ -270,13 +303,18 @@ typing-extensions==4.16.0 # aiosignal # anyio # formulaic + # httpx2 # huggingface-hub + # opentelemetry-api # pydantic # pydantic-core # torch # typing-inspection typing-inspection==0.4.4 - # via pydantic + # via + # pydantic + # pydantic-ai-slim + # pydantic-graph urllib3==2.8.0 # via requests wrapt==2.5.0 diff --git a/tools/colab/lock/tpu.txt b/tools/colab/lock/tpu.txt index 97ec242b..35e46562 100644 --- a/tools/colab/lock/tpu.txt +++ b/tools/colab/lock/tpu.txt @@ -48,6 +48,8 @@ anyio==4.15.1 # httpx2 # mcp # py-key-value-aio + # pydantic-ai-slim + # pydantic-graph # sse-starlette # starlette # watchfiles @@ -208,6 +210,8 @@ gemma==4.0.1 # via # -r tools/colab/lock/tpu.in # evalrx (pyproject.toml) +genai-prices==0.2.5 + # via pydantic-ai-slim gitdb==4.0.12 # via gitpython gitpython==3.2.0 @@ -288,7 +292,9 @@ grain==0.2.18 graphviz==0.21 # via kauldron griffelib==2.3.2 - # via fastmcp-slim + # via + # fastmcp-slim + # pydantic-ai-slim grpc-google-iam-v1==0.14.5 # via # google-cloud-resource-manager @@ -331,7 +337,9 @@ httpx==0.28.1 httpx2==2.13.1 # via # fastmcp-slim + # genai-prices # mcp + # pydantic-ai-slim huggingface-hub==0.36.2 # via datasets humanize==4.16.0 @@ -441,6 +449,8 @@ libclang==18.1.1 # via tensorflow-cpu libtpu==0.0.21.1 # via -r tools/colab/lock/tpu.in +logfire-api==6.0.0 + # via pydantic-graph mako==1.4.3 # via alembic markdown==3.11 @@ -558,6 +568,7 @@ opentelemetry-api==1.45.1 # fastmcp-slim # google-api-core # mcp + # pydantic-ai-slim opt-einsum==3.4.0 # via # jax @@ -682,15 +693,22 @@ pydantic==2.14.0 # via # evalrx (pyproject.toml) # fastmcp-slim + # genai-prices # google-cloud-aiplatform # google-genai # kubernetes # mcp # mcp-types # openapi-pydantic + # pydantic-ai-slim + # pydantic-graph # pydantic-settings +pydantic-ai-slim==2.71.0 + # via evalrx (pyproject.toml) pydantic-core==2.50.0 # via pydantic +pydantic-graph==2.71.0 + # via pydantic-ai-slim pydantic-settings==2.15.0 # via fastmcp-slim pydub==0.25.1 @@ -935,6 +953,8 @@ typing-inspection==0.4.4 # via # mcp # pydantic + # pydantic-ai-slim + # pydantic-graph # pydantic-settings uncalled-for==0.4.1 # via fastmcp-slim diff --git a/tools/demo_video/storyboard.py b/tools/demo_video/storyboard.py index 523e7a51..b656adb4 100644 --- a/tools/demo_video/storyboard.py +++ b/tools/demo_video/storyboard.py @@ -3,7 +3,7 @@ Two input shapes, both real runs — nothing here invents numbers: -* ``--run-dir DIR`` — a live RunLoggerV2 output (``logs/run.json`` + +* ``--run-dir DIR`` — a live RunLogger output (``logs/run.json`` + ``logs/M*/log.json``). Every narrated line comes from the real ``LoopNarrator`` fed the logged records, exactly as ``examples/benchmark/tools/replay_narrate.py`` does, so durations are the @@ -328,7 +328,7 @@ def main() -> int: formatter_class=argparse.RawDescriptionHelpFormatter) source = ap.add_mutually_exclusive_group(required=True) source.add_argument("--report", type=Path, help="exported report .html") - source.add_argument("--run-dir", type=Path, help="RunLoggerV2 run directory") + source.add_argument("--run-dir", type=Path, help="RunLogger run directory") source.add_argument("--transcript", type=Path, help="saved terminal transcript of a narrated run") ap.add_argument("--out", type=Path, required=True, help="storyboard .json to write")