diff --git a/CHANGELOG.md b/CHANGELOG.md index 865cad4e..631cf8a4 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,82 @@ Versions follow [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Added — held-out confirmation that respects groups + +Rows cut from one underlying item (frames of a clip, one prompt answered by +several models) are not independent. `evalrx explore --group-col COLUMN` and +`split_records(..., group_col=)` keep each group on one side of the split, and +`holdout_confirm(..., group_col=)` resamples whole groups for every interval. +`evalrx.stats.weighted_bootstrap` is the cluster bootstrap behind it, and +`compare(a, b, paired=False, cluster_by=(groups_a, groups_b))` is the clustered +two-group comparison. A `two_group` sufficient statistic may carry +`clusters_a` / `clusters_b`. When no group column is named, the profile +suggests columns that look like one (`DatasetProfile.suggested_group_columns`) +and a held-out run reports how many held-out rows share a group with an +explored row. `docs/holdout_confirmation.md` is the guide; +`docs/validation/holdout_calibration_20261121.md` has the calibration. + +### Added — more comparisons a frozen recipe can ask for + +A recipe may carry `where` (a subgroup condition), `design: stratified` with +`strata`, `design: did` with a `modifier`, `design: dose_response` with fixed +`bins`, and `expect` (`>`, `<`, `abs<` a bound, or `nonzero`). `abs<` is how a +control is written: it holds only when the whole interval is inside the bound. +Recipes may call `has_word(column, "word")` and `contains(column, "text")`. +A numeric outcome is supported (differences of means). Signals whose claim +holds list `representative_cases`, chosen at each side's median. +`evalrx.analysis.holdout_designs` implements the designs. + +### Added — host-checked predictions and structured experiment plans + +A hypothesis may carry `predictions` about named signals; the host checks them +on the held-out rows and reports `host_verdict` without a model. `experiment` +(`data_needed`, `operation`, `expected_result`, `falsified_by`) replaces a +free-text plan for an intervention. `HypothesisAgent` asks for both. + +### Added — data card, leakage check, keyword recipes + +`--data-card` (or `--row-unit`, `--row-extraction`, `--outcome-threshold`, +`--deployment-aggregation`) records what a row is and how the table was built; +answers and gaps are printed in the report's caveats. The profile flags +columns that almost fully determine the outcome +(`DatasetProfile.leakage_suspects`). `--group-col` / `--time-col` name column +roles explicitly, and calendar-like names and ISO date values are recognised +as time. `--text-col` freezes over-represented words as recipes on the +exploration half and re-tests them on the held-out half +(`evalrx.analysis.keywords`). + +### Changed — every held-out claim is corrected, and the header says how + +All held-out claims — one per adjudicated signal, one per hypothesis +prediction — share one Benjamini-Hochberg family; `reject` on a signal now +means its claim survived that correction, and `raw_reject` keeps the +uncorrected verdict. In-sample `two_group` candidates get a p-value and their +own BH family instead of an uncorrected interval check. `adjudication.method` +names the correction actually applied (`"BH"`, `"e-BH"`, `"e-BH + BH"`, or +`"none"` when nothing could be tested); it no longer says `e-BH` for an empty +family. Two-group comparisons of a binary outcome with independent rows use +the exact test for their p-value (`evalrx.stats.two_group_exact_p`). +`compare(..., paired=False)` reports its method as `two-sample bootstrap +(unpaired)` unless clusters were given. + +### Changed — the held-out judge follows `--backend` + +`--judge-backend` (default `same`) picks the judge; it no longer requires the +Claude CLI on a run that used another backend. `--judge-model` defaults to +`claude-opus-4-8` only on a Claude backend. `confirm_report.json` records +whether the judge is the model that proposed the hypotheses and warns when it +is or may be. + +### Changed — row limit and sandbox + +A host load that drops rows at `--max-rows` says how many were dropped and +that the kept rows are not a random sample +(`load_records_from_path(..., info=)`). `explore(..., out=)` deletes the +temporary sandbox, which holds a copy of the data, once the artifacts are +written; `--keep-sandbox` / `keep_sandbox=True` keeps it. Recipes are refused +if any of their expressions reads the outcome column, whatever its name. + ### Changed — Stage 0 labels a sampled case by the majority of five answers A sampling model can answer one case both ways, so one answer labelled the case diff --git a/README.md b/README.md index 79a5a890..ceb4e8c7 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,11 @@ evalrx explore ./results \ `codex` can be replaced with `claude_code`, `opencode`, `gemini_cli`, `kimi_cli`, or `antigravity` — the selected coding-agent CLI must be installed -and authenticated separately. Then open the run, or export a portable file: +and authenticated separately. Add `--holdout-frac 0.4 --holdout-confirm` to +re-test what it finds on rows it never saw, and `--group-col` when several +rows come from one underlying item +([held-out confirmation](https://evalvitals.github.io/evalrx/holdout_confirmation/)). +Then open the run, or export a portable file: ```bash evalrx serve evalrx_explore_output # local report server @@ -221,7 +225,7 @@ raising it rather than climbing on its own. | **L2** | Scaffolds around an unchanged model — multi-call, tools, aggregation | ✅ | | **L3a** | Read internals — attention-guided cropping, contrastive decoding | ✅ | | **L3b** | Write internals — attention reweighting, activation steering | ✅ | -| **L4** | **Parameter space — build a dataset, fine-tune, re-test; or write a training-free weight edit** | ✅ LoRA on the LLM ([`internals.py`](evalrx/eval_agent/stages/fix/internals.py)); ✅ rank-one weight edit, opt-in ([`weight_edit.py`](evalrx/eval_agent/stages/fix/weight_edit.py)); other recipe shapes recorded, not yet executed | +| **L4** | **Parameter space — build a dataset, fine-tune, re-test; or write a weight-space edit** | ✅ LoRA on the LLM ([`internals.py`](evalrx/eval_agent/stages/fix/internals.py)); ✅ rank-one weight edit, opt-in ([`weight_edit.py`](evalrx/eval_agent/stages/fix/weight_edit.py)); other recipe shapes recorded, not yet executed | **L3b and L4 only exist for open weights** — you cannot modify a forward pass or fine-tune through somebody's API. diff --git a/docs/cli.md b/docs/cli.md index b2728468..f27c0526 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -112,7 +112,11 @@ set. | `--out` | `evalrx_explore_output` | Output directory for report/code/figures/tables. | | `--backend` (`--coder-provider`) | `antigravity` | Coding-agent CLI: `antigravity`, `codex`, `claude_code`, `opencode`, `gemini_cli`, `kimi_cli`. Must be installed + authenticated separately. | | `--model` (`--coder-model`) | backend default | Model name passed to the coding agent. | -| `--max-rows` / `--max-files` | `2000` / `200` | Sampling caps for large inputs. | +| `--group-col` | — | Column naming the unit rows were cut from. Keeps each group on one side of the held-out split and resamples whole groups for held-out intervals. See [Held-out Confirmation](holdout_confirmation.md). | +| `--time-col` | by name | Time column, when its name does not say so. | +| `--text-col` | — | Free-text column to mine for keyword recipes (chosen on the exploration half, re-tested on the held-out half). Needs `--holdout-frac`. | +| `--data-card FILE` | — | JSON/YAML answering `unit`, `extraction`, `threshold`, `aggregation`; printed in the report's caveats. Also `--row-unit`, `--row-extraction`, `--outcome-threshold`, `--deployment-aggregation`. | +| `--max-rows` / `--max-files` | `2000` / `200` | Caps on what the host loads. Rows dropped by `--max-rows` are reported with a warning. | | `--timeout-sec` / `--max-attempts` | `120` / `2` | Per-attempt timeout and repair-retry budget. | | `--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`. | @@ -120,7 +124,9 @@ set. | `--no-hypotheses` | off | Skip M3 — stop after M2's takeaways. | | `--holdout-frac` | `0.0` | Fraction held out *before* exploration (outcome-stratified, deterministic). | | `--holdout-confirm` | off | Re-test frozen recipes/hypotheses on the held-out rows (`confirm_report.json`). Requires `--holdout-frac > 0`. | -| `--judge-model` | `claude-opus-4-8` | Judge grading each hypothesis against the held-out table (only with `--holdout-confirm`). | +| `--judge-backend` | `same` | Backend of the judge grading each hypothesis against the held-out table (only with `--holdout-confirm`). `same` follows `--backend`; a judge that is also the proposer is flagged in the report. | +| `--judge-model` | per backend | That judge's model: `claude-opus-4-8` on a Claude backend, otherwise `--model`, otherwise the backend's default. | +| `--keep-sandbox` | off | Keep the temporary working directory (a copy of the data) instead of deleting it once artifacts are in `--out`. | | `--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. | diff --git a/docs/holdout_confirmation.md b/docs/holdout_confirmation.md new file mode 100644 index 00000000..8f17aa41 --- /dev/null +++ b/docs/holdout_confirmation.md @@ -0,0 +1,254 @@ +# Held-out Confirmation + +`evalrx explore --holdout-frac F --holdout-confirm` explores one part of a +table and re-tests what it found on the rest. This page covers what makes that +re-test mean something: which rows count as independent, which comparisons can +be re-tested, how many claims are corrected together, and what the report says +about the data it was given. + +```bash +evalrx explore ./results \ + --outcome-col label \ + --group-col clip_id \ + --holdout-frac 0.4 --holdout-confirm \ + --data-card card.yaml +``` + +## Rows that are not independent + +Many tables hold several rows per underlying item: frames cut from one clip, +one prompt answered by several models, chunks of one document. Rows of an item +resemble each other. Two things go wrong if they are treated as independent. + +- **The split leaks.** A row-level split puts rows of one item on both sides, + so the held-out half contains near-copies of rows the explorer has seen. +- **The intervals are too narrow.** A thousand rows from fifty items are + closer to fifty observations than to a thousand. + +`--group-col COLUMN` names the item. The split then sends each group wholly to +one side, and every held-out interval resamples whole groups +([`weighted_bootstrap`](https://github.com/evalvitals/evalrx/blob/main/evalrx/stats/bootstrap.py)). +`confirm_report.json` records this under `split_meta.group_overlap` (the share +of held-out rows whose group was explored — zero with a group column) and +`adjudication.clustered_by`. + +The size of the problem is measurable. In +[the calibration run](validation/holdout_calibration_20261121.md), a flag with +no effect at all was called significant in 22% of datasets when rows were +treated as independent and in 7.5% when the group column was used; the target +is 5%. + +### When no group column is named + +The run looks for one. A column is suggested when it has at least 20 distinct +values, at least a fifth of the rows share their value with another row, and +rows that share a value agree on the outcome well beyond chance (intraclass +correlation of 0.1 or more). The warning is printed, written to the report's +caveats, and comes with the measured overlap. It reads like this (the numbers +depend on the table): + +```text +WARNING: column 'clip_id' looks like the unit rows were cut from (200 groups; +rows of one group share 51% of the outcome variance) and 91.6% of held-out +rows share a group with an explored row, so the held-out check is not +independent of the exploration. Re-run with --group-col clip_id. +``` + +Only string columns and integer id columns are considered. A float column that +repeats is a rounded measurement, not an item. + +`--time-col COLUMN` names a time column the same way. Without it, a column is +taken as time when its name contains `date`, `time`, `timestamp`, `month`, +`year`, `week` or `quarter` as a whole word, ends in `_at`, or holds ISO dates. + +## Comparisons a recipe can ask for + +A candidate signal carries a **recipe**: an expression over the table's +columns, fixed during exploration. By default it is compared as two groups — +the outcome among rows the expression flags against the rest. Optional fields +on the recipe ask for a different comparison. Every number in them is fixed +during exploration and reused unchanged. + +| Field | Comparison | Use it for | +|---|---|---| +| *(none)* | Flagged rows against unflagged rows. | A threshold or a composite condition. | +| `where` | The same, inside the rows where the condition holds. | A finding about one subgroup. | +| `design: stratified` + `strata` | The difference within each stratum, averaged with the strata's sizes as weights. | A gap that may only reflect a different mix. | +| `design: did` + `modifier` | The recipe's effect where the modifier holds, minus its effect where it does not. | An interaction: "the jump is larger for X". | +| `design: dose_response` + `bins` | The change in the outcome per step up fixed cut points. | A continuous signal. | + +```json +{"name": "late_batch_matched", "kind": "expr", + "expr": "batch == 'late'", + "where": "task == 'i2v'", + "design": "stratified", "strata": ["generator", "int(encoder_score * 5)"], + "expect": {"relation": "abs<", "value": 0.10}} +``` + +Expressions may use column names, comparisons, `and`/`or`/`not`, arithmetic, +`abs`/`min`/`max`/`float`/`int`/`len`, `has_word(column, "word")` and +`contains(column, "text")`. None may read the outcome column, whatever it is +called. + +A continuous recipe with no `bins` cannot be re-tested — there is no frozen +threshold to reuse — and is skipped with a reason that says so. A stratum that +holds only flagged or only unflagged rows contributes nothing and is counted in +`details.n_rows_in_one_sided_strata`. + +The outcome may be two-valued (effects are differences of failure rates) or +numeric (differences of means). + +## Stating what is expected + +Without `expect`, a recipe claims "the effect is not zero". With it, the +recipe states the prediction to be tested: + +| `relation` | Claim | +|---|---| +| `">"`, `"<"` | The effect is above / below `value` (use `0` for a direction). | +| `"abs<"` | The effect is smaller than `value` in either direction. | +| `"nonzero"` | The default. | + +`"abs<"` is how a **control** is written: a comparison that should come out +small. It holds only when the whole interval lies inside the bound. A control +that shows a real difference of nine points against a bound of ten is +`inconclusive`, not a finding and not a pass. + +Each claim ends in one of three states: + +- `holds` — it survived the correction described below. +- `contradicted` — the data show the opposite of a bounded claim (not corrected + for multiplicity; "not zero" has no testable opposite and is never + contradicted). +- `inconclusive` — neither. + +`reject` on a signal means its claim holds and the claim is one of separation; +a control that holds has `reject: false`. + +## One correction for every claim + +Every adjudicated signal makes one claim, and so does every numeric prediction +a hypothesis carries. All of them are corrected together with +Benjamini-Hochberg at `alpha`. `adjudication.method` names what was applied — +`"BH"`, or `"none"` when no claim could be tested — and `n_in_family` counts +the claims. `raw_reject` on a signal says whether it would have passed alone. + +p-values come from the same cluster bootstrap as the intervals. For a +two-group comparison of a two-valued outcome with independent rows, the exact +(Fisher) test is used instead, because a bootstrap of a small, cleanly +separated sample degenerates: four failures against four passes resample to +the same difference every time. `details.p_value_method` records which was +used, and `details.small_sample_warning` appears when the smaller side has +fewer than ten independent units. + +Candidates adjudicated during exploration (`sufficient` statistics) follow the +same rule: paired comparisons share an e-BH family and two-group comparisons +share a BH family. + +## Hypotheses: what the host checks and what the judge grades + +A hypothesis may carry `predictions` — numeric statements about named signals: + +```json +{"statement": "Late batches fail more on image-to-video, not text-to-video.", + "predictions": [ + {"signal": "late_i2v", "relation": ">", "value": 0.10}, + {"signal": "late_t2v", "relation": "abs<", "value": 0.10}], + "experiment": { + "data_needed": "200 held-out prompts re-rendered with both encoders", + "operation": "swap the image encoder, keep everything else", + "expected_result": "the late-batch gap closes", + "falsified_by": "the gap stays above 10 points"}} +``` + +The host checks each prediction against the held-out rows and sets +`host_verdict`: `supported` when all hold, `refuted` when any is contradicted, +`inconclusive` otherwise, `none` when there was nothing to check. This needs +no model. The judge still grades the hypothesis as a whole, is shown the +host's results, and is asked to leave them as given. + +`experiment` replaces a free-text test plan with four fields. It describes the +intervention needed when re-counting rows cannot settle the claim; a plan with +no `falsified_by` is visibly incomplete. + +`--judge-backend` picks the judge: `same` (default) follows `--backend`, so a +run on Codex does not also need the Claude CLI. `confirm_report.json` records +the judge under `judge`, including `same_as_proposer`. When the judge is, or +may be, the model that proposed the hypotheses, the report says so; pass +`--judge-backend` or `--judge-model` for an independent review. Signal verdicts +and host-checked predictions never depend on the judge. + +## Representative cases + +For each signal whose claim holds, `representative_cases` lists three rows per +side, chosen nearest the side's median on the outcome and on the columns the +recipe reads. They show what the comparison is mostly made of; the most extreme +rows would show the cases least like the rest. Each entry gives the row's +position in `holdout_records.json` and its id when the rows have one. + +## Keywords in a free-text column + +`--text-col COLUMN` adds keyword candidates. On the exploration rows, the words +most over-represented on each side of the outcome are found (log-odds ratio +with a prior, counting rows rather than occurrences). Each becomes a recipe +`has_word(column, "word")` whose `expect` is the direction it showed there, and +is then re-tested on the held-out rows in the same family as everything else. + +Some word always leans one way. The discipline is in the second step: a word +has to repeat its direction on rows it was not chosen on, after correction. + +## What the report says about the data + +**Data card.** Four facts decide whether a pattern in a table says anything +about the system that produced it: + +| Field | Question | +|---|---| +| `unit` | What is one row? | +| `extraction` | How was a row cut from the raw object? | +| `threshold` | How was the outcome, or its threshold, set? | +| `aggregation` | How are results combined when the system is used? | + +Give them with `--data-card FILE` (JSON or YAML) or `--row-unit`, +`--row-extraction`, `--outcome-threshold` and `--deployment-aggregation`. The +answers are printed in the report's caveats and passed to the explorer. Any +left unanswered are listed there too. + +**Leakage check.** A column that almost fully determines the outcome is +usually the outcome under another name, or something recorded after it. Such +columns are reported in the caveats: a column with few distinct values whose +values predict the outcome at least 98% of the time, a numeric column whose +rank AUC is within 0.01 of 0 or 1, or — for a numeric outcome — a correlation +of 0.98 or more. + +**Row limit.** `--max-rows` caps what the host loads (default 2000). When rows +are dropped the run says how many, and that the loaded rows are taken from the +start of each file and are not a random sample. + +## From Python + +```python +from evalrx.analysis.holdout import holdout_confirm, split_records + +explore, held_out = split_records(rows, 0.4, outcome_col="label", group_col="clip_id") +# ... explore on `explore`, collect candidate signals with recipes ... +confirm = holdout_confirm(report, held_out, outcome_col="label", group_col="clip_id") +``` + +`evalrx.stats.compare(a, b, paired=False, cluster_by=(groups_a, groups_b))` +gives the clustered two-group comparison on its own, and +`tools/check_holdout_calibration.py` reruns the calibration. + +## Limits + +- The bootstrap interval is approximate, and on grouped data it errs on the + permissive side: in the calibration run the false-positive rate with 120 + groups was 7.5% against a 5% target, and interval coverage was 93% against + 95%. With fewer groups expect it to be worse. +- A group column has to be named or noticed. Grouping that is not in the table + — two rows that came from one source but carry no shared id — cannot be + detected. +- Stratification removes differences in mix across the strata that were named. + It says nothing about differences along anything else. +- A claim that holds on held-out rows is a pattern that repeated. Whether it is + a cause is the question `experiment` is for. diff --git a/docs/quickstart.md b/docs/quickstart.md index 8f1e39b5..ebdd2596 100755 --- a/docs/quickstart.md +++ b/docs/quickstart.md @@ -192,9 +192,13 @@ report (`exploratory_report.json`), and rendered charts under Add `--holdout-frac 0.4 --holdout-confirm` for a held-out design: the split is carved off BEFORE exploration (outcome-stratified, deterministic), the explorer is told to freeze threshold-explicit recipes, and after M3 the -held-out rows re-test every recipe verbatim (e-BH, `split_label="held_out"`) -while an LLM judge grades each hypothesis — `confirm_report.json` lands next -to the report and fills the *Held-out Verdicts* section. +held-out rows re-test every recipe verbatim (all claims corrected together +with Benjamini-Hochberg, `split_label="held_out"`) while an LLM judge grades +each hypothesis — `confirm_report.json` lands next to the report and fills the +*Held-out Verdicts* section. If several rows come from one underlying item, +name it with `--group-col`: the split then keeps each item on one side and the +intervals count items rather than rows. See +[Held-out Confirmation](holdout_confirmation.md). **Agent-trajectory records.** Rows produced by `evalrx.analysis.trajectory_records` flow through explore unchanged; use diff --git a/docs/stage_io.md b/docs/stage_io.md index ad82eee3..d52b85e3 100644 --- a/docs/stage_io.md +++ b/docs/stage_io.md @@ -258,8 +258,13 @@ object). **Output:** `list[Hypothesis]`, each with `statement` (technical claim), `plain_statement` (jargon-free rewrite), `basis` (which M2 takeaway grounds -it), `test_design` (what evidence would confirm/refute it). Proposal only — -generating a hypothesis is not testing one. +it), `test_design` (what evidence would confirm/refute it). Two optional +fields appear only when stated: `predictions` (numeric claims about named +candidate signals, which the host checks on held-out rows) and `experiment` +(`data_needed`, `operation`, `expected_result`, `falsified_by` — the +intervention needed when re-counting rows cannot decide the claim). See +[Held-out Confirmation](holdout_confirmation.md). Proposal only — generating a +hypothesis is not testing one. **UI (Tab 3 — Hypotheses):** one card per hypothesis — headline is `plain_statement` (falls back to `statement`), technical `statement` shown diff --git a/docs/validation/holdout_calibration_20261121.md b/docs/validation/holdout_calibration_20261121.md new file mode 100644 index 00000000..4c1b2ac9 --- /dev/null +++ b/docs/validation/holdout_calibration_20261121.md @@ -0,0 +1,81 @@ +# Held-out comparison designs: calibration (2026-11-21) + +**What was checked.** Whether the held-out comparisons in +`evalrx.analysis.holdout_designs` give the error rates they claim, on simulated +data with a known answer. No model and no real dataset is involved. + +**How to rerun.** `python tools/check_holdout_calibration.py --runs 400 --n-boot 1000` +(about one minute on one CPU core). Every number below is that command's +output. + +## 1. False positives when nothing is going on + +Data: 120 groups of 2–10 rows. Rows of a group share a failure tendency +(group effect with standard deviation 1.2 on the logit scale). A flag has no +effect on the outcome. 400 datasets per cell; the target is 0.050 and the +simulation error is about ±0.021. + +| The flag varies by | Rows treated as independent | Group column used | +|---|---|---| +| group | **0.223** | 0.075 | +| row | 0.045 | 0.050 | + +When the flag is a property of the group — the common case, since a flag +computed from an item's features is shared by the rows cut from it — treating +rows as independent rejects four times as often as it should. Using the group +column brings the rate to 0.075. That is still above 0.050 by more than the +simulation error: the percentile bootstrap is somewhat too narrow at this +number of groups. + +When the flag varies row by row within groups, both are on target. + +## 2. Interval coverage when the effect is known + +Data: 150 groups of 2–8 rows with a group-level shift in the failure rate. +400 datasets per design; the target is 0.950. + +| Design | True effect | Mean estimate | Coverage | +|---|---|---|---| +| two-group | 0.200 | 0.200 | 0.932 | +| stratified | 0.100 | 0.101 | 0.963 | +| difference in differences | 0.250 | 0.258 | 0.950 | +| dose-response (per bin step) | 0.120 | 0.120 | 0.950 | + +In the stratified data the flag is three times as common in the stratum that +fails more. The unadjusted two-group difference averages 0.274; the stratified +estimate recovers the within-stratum effect of 0.100. + +## 3. Keyword recipes + +Data: 120 clips of 3–7 rows, a `note` column with one real keyword (present in +60% of failing rows, none of the passing ones) and six filler words that are +independent of the outcome. Keywords are chosen on a 60% exploration half, +split by clip, and re-tested on the rest with the clip as the group column. +200 datasets. + +| | | +|---|---| +| Real keyword accepted | 200 / 200 | +| Runs in which any filler word was accepted | 8.0% | +| Mean share of accepted keywords that were filler | 5.6% | + +The share of accepted keywords that are filler is the quantity the correction +is meant to hold at 5%. It came out at 5.6%, which is within simulation error +of the target but on the high side, in line with the slightly narrow grouped +interval in part 1. The fillers come in pairs that always occur together, so +one chance acceptance usually brings a second. + +## What this does and does not show + +It shows the estimators are unbiased on data of the shape they assume and that +the error rates are near their targets. Where they miss, they miss on the +permissive side: 7.5% against 5% for a grouped two-group comparison with 120 +groups, 93.2% coverage against 95%, and 5.6% filler keywords against 5%. A +result that only just clears the threshold on grouped data deserves less +confidence than the threshold suggests. + +It does not show how the designs behave on real tables, where grouping may be +partial or unrecorded, strata may be sparse, and the outcome threshold may +itself have been tuned on the data. It also says nothing about the quality of +the recipes an explorer proposes — only about how a recipe, once frozen, is +re-tested. diff --git a/evalrx/analysis/adjudicate.py b/evalrx/analysis/adjudicate.py index 74e36286..a17b51a4 100644 --- a/evalrx/analysis/adjudicate.py +++ b/evalrx/analysis/adjudicate.py @@ -9,17 +9,19 @@ Mechanics (mirror ``stats_tools`` / ``stats_tool_generator`` exactly): -- ``_reconstruct_decision`` turns sufficient statistics into - ``(reject, e_value, effect, ci)`` via the validated core. -- ``fdr_correct`` applies e-BH across every candidate that produced an e-value - (the ``paired_binary`` shape), so proposing more candidates pays more - multiplicity — exactly one e-BH family, no per-candidate self-rejection. -- A ``two_group`` candidate yields a bootstrap-CI reject but no e-value (matching - the ``signal_label_assoc`` catalog tool). It is host-adjudicated but sits - OUTSIDE the e-BH family and is flagged ``fdr_corrected=False`` — honest, not - over-claimed. +- ``reconstruct_evidence`` turns sufficient statistics into a verdict via the + validated core. +- A ``paired_binary`` candidate yields an e-value; those candidates share one + e-BH family. +- A ``two_group`` candidate yields a bootstrap interval and p-value; those + candidates share one Benjamini-Hochberg family. Its ``reject`` is survival of + that correction, so proposing more two-group candidates pays more + multiplicity, as it does for paired ones. ``raw_reject`` in the returned + metadata lists the candidates whose own interval excluded zero. - A candidate with no adjudicable ``sufficient`` is ``descriptive_only`` and never rejects. +- ``method`` in the returned metadata names the correction that was applied: + ``"e-BH"``, ``"BH"``, both, or ``"none"`` when no candidate could be tested. IMPORTANT — split discipline: in the standalone chat path the candidate's ``sufficient`` is computed on the SAME rows used to discover the signal. That is @@ -33,7 +35,7 @@ from typing import TYPE_CHECKING, Any -from evalrx.analysis.stats_tool_generator import _reconstruct_decision +from evalrx.analysis.stats_tool_generator import reconstruct_evidence from evalrx.analysis.stats_tools import StatsToolResult, fdr_correct if TYPE_CHECKING: @@ -57,76 +59,82 @@ def adjudicate_signals( Reads only ``candidate.sufficient`` — never a self-declared verdict. Returns a metadata dict describing the single e-BH family the candidates competed in. """ - # 1) Host reconstruction per candidate; assemble the e-BH family from the - # candidates that produced an e-value (paired_binary). + # 1) Host reconstruction per candidate; candidates with an e-value form the + # e-BH family, candidates with a p-value the BH family. raw_reject: dict[int, bool] = {} family: list[StatsToolResult] = [] family_key: dict[int, str] = {} for i, c in enumerate(candidates): - recon = ( - _reconstruct_decision(c.sufficient, alpha) + evidence = ( + reconstruct_evidence(c.sufficient, alpha) if isinstance(c.sufficient, dict) else None ) - if recon is None: + if evidence is None: c.host_adjudicated = False c.descriptive_only = True c.fdr_corrected = False c.e_value = None + c.p_value = None c.reject = False continue - reject, e_value, effect, ci = recon c.host_adjudicated = True c.descriptive_only = False - c.e_value = e_value - if effect is not None: - c.effect = effect - if ci is not None: - c.ci = ci - raw_reject[i] = bool(reject) - if e_value is not None: + c.e_value = evidence["e_value"] + c.p_value = evidence["p_value"] + if evidence["effect"] is not None: + c.effect = evidence["effect"] + if evidence["ci"] is not None: + c.ci = evidence["ci"] + raw_reject[i] = bool(evidence["reject"]) + if c.e_value is not None or c.p_value is not None: key = _family_key(c, i) family_key[i] = key family.append( StatsToolResult( tool="candidate_signal", analysis_key=key, - e_value=e_value, effect=effect, ci=ci, reject=bool(reject), + e_value=c.e_value, + p_value=c.p_value if c.e_value is None else None, + effect=c.effect, ci=c.ci, reject=raw_reject[i], + correction_family="e_bh" if c.e_value is not None else "bh", ) ) - # 2) ONE e-BH family across the e-value-bearing candidates (the multiplicity - # firewall). `fdr_correct` only considers results with an e-value. + # 2) One e-BH family across the e-value-bearing candidates and one BH + # family across the p-value-bearing ones (the multiplicity firewall). fdr = fdr_correct(family, alpha=alpha) rejected_keys = set(fdr.get("rejected_result_keys", [])) - # 3) Final reject per candidate. + # 3) Final reject per candidate: survival of its family's correction. + # `fdr_corrected` means "this rejection is FDR-controlled" — True ONLY + # when it survived (matches fused_pipeline; a family member that did not + # survive is reject=False, fdr_corrected=False). for i, c in enumerate(candidates): if not c.host_adjudicated: continue - if c.e_value is not None: - # In the e-BH family. `reject` IS the e-BH outcome; `fdr_corrected` - # means "this rejection is FDR-controlled" — True ONLY when it survived - # e-BH (matches fused_pipeline; a family member that did not survive is - # reject=False, fdr_corrected=False). Family membership is recoverable - # from `e_value is not None`, so no information is lost. - c.reject = family_key.get(i) in rejected_keys - c.fdr_corrected = bool(c.reject) - else: - # two_group: CI-based reject, outside the e-BH family (mirrors M2's - # signal_label_assoc). Honest about not being FDR-corrected. - c.fdr_corrected = False - c.reject = raw_reject.get(i, False) + c.reject = family_key.get(i) in rejected_keys + c.fdr_corrected = bool(c.reject) + n_e = sum(1 for c in candidates if c.host_adjudicated and c.e_value is not None) + n_p = sum( + 1 for c in candidates + if c.host_adjudicated and c.e_value is None and c.p_value is not None + ) + method = " + ".join( + name for name, size in (("e-BH", n_e), ("BH", n_p)) if size + ) or "none" return { - "method": "e-BH", + "method": method, "alpha": alpha, "split": split_label, "n_candidates": len(candidates), "n_host_adjudicated": sum(1 for c in candidates if c.host_adjudicated), - "n_in_family": len(family), # e-value-bearing candidates under e-BH + "n_in_family": n_e, # e-value-bearing candidates under e-BH + "n_in_p_family": n_p, # p-value-bearing (two_group) candidates under BH "n_rejected": sum(1 for c in candidates if c.reject), "rejected": [c.name for c in candidates if c.reject], + "raw_reject": [c.name for i, c in enumerate(candidates) if raw_reject.get(i)], } diff --git a/evalrx/analysis/api.py b/evalrx/analysis/api.py index a91afa04..ed863c1d 100644 --- a/evalrx/analysis/api.py +++ b/evalrx/analysis/api.py @@ -14,6 +14,7 @@ from __future__ import annotations +import json import logging from dataclasses import dataclass, field from pathlib import Path @@ -47,6 +48,8 @@ def explore( model: str = "", binary: str = "", outcome_col: str | None = None, + group_col: str | None = None, + time_col: str | None = None, propose_hypotheses: bool = True, skills: "list[str] | tuple[str, ...]" = (), allow_skills: bool = False, @@ -57,6 +60,9 @@ def explore( timeout_sec: int = 120, max_attempts: int = 2, progress_sink: Any = None, + keep_sandbox: bool = False, + caveats: "list[str] | tuple[str, ...]" = (), + extra_candidates: "list[Any] | tuple[Any, ...]" = (), ) -> ExploreRunResult: """Run one exploratory analysis over a path or in-memory records. @@ -70,8 +76,24 @@ def explore( it to auto-detect by name heuristics, or fall back to unsupervised EDA when the data has no recognizable outcome. + *group_col* names the unit rows were cut from (several rows per source + item, the same prompt answered by several models): the explorer is told + rows that share it are not independent. *time_col* names a time column. + Both override the name heuristics, which know only a few English names. + *propose_hypotheses* runs M3 (:class:`~evalrx.analysis.hypothesis_agent.HypothesisAgent`) on M2's takeaways after a successful explore; set False to skip it. + + *caveats* are host-side warnings about the data (rows dropped by the row + limit, a column that looks like a grouping unit, an unanswered data card) + to print with the report. *extra_candidates* are candidate signals the + host derived itself, such as keyword contrasts; they are appended to the + explorer's own and treated the same way from then on. + + The agent works in a temporary sandbox that holds a copy of the data. When + *out* is given the sandbox is deleted once the artifacts are copied there; + pass *keep_sandbox* to leave it for inspection. Without *out* the sandbox + is the only place the artifacts live, so it is always kept. """ skill_dirs = resolve_skill_paths( provider=provider, @@ -96,6 +118,12 @@ def explore( if progress_sink is not None: progress_sink.emit("m2", "started", "Starting exploratory analysis (M2)") + # Only named roles are passed on, so an agent that predates them still works. + roles: dict[str, Any] = {} + if group_col: + roles["group_col"] = group_col + if time_col: + roles["time_col"] = time_col if isinstance(source, (str, Path)): report = agent.explore_path( source, @@ -104,9 +132,22 @@ def explore( max_files=max_files, include_tool_calls=include_tool_calls, outcome_col=outcome_col, + **roles, ) else: - report = agent.explore_records(source, question=question, outcome_col=outcome_col) + report = agent.explore_records( + source, question=question, outcome_col=outcome_col, **roles + ) + + for caveat in caveats: + if caveat and caveat not in report.caveats: + report.caveats.append(caveat) + # Host-derived candidates do not depend on the agent, so they are kept even + # when its exploration failed: the run can still test them on held-out rows. + taken = {c.name for c in report.candidate_signals} + report.candidate_signals.extend( + c for c in extra_candidates if c.name not in taken + ) # Host adjudication: any candidate that attached host-checkable `sufficient` # stats gets a verdict recomputed by the validated core (the explorer never @@ -157,6 +198,13 @@ def explore( from evalrx.analysis.explore_run import write_report_artifacts write_report_artifacts(report, out_dir) + discard = getattr(agent, "discard_sandbox", None) + if not keep_sandbox and callable(discard) and discard(): + # The report on disk must not point at a directory that is gone. + report.workdir = str(out_dir) + (out_dir / "exploratory_report.json").write_text( + json.dumps(report.to_dict(), indent=2, default=str), encoding="utf-8" + ) if progress_sink is not None: progress_sink.emit( "persist", "completed", "Analysis artifacts are ready", diff --git a/evalrx/analysis/explore_run.py b/evalrx/analysis/explore_run.py index 163cd5b4..f81704f1 100644 --- a/evalrx/analysis/explore_run.py +++ b/evalrx/analysis/explore_run.py @@ -23,7 +23,11 @@ from typing import Any from evalrx.analysis.api import explore -from evalrx.analysis.explorer import RECORDS_FILENAME, load_records_from_path +from evalrx.analysis.explorer import ( + RECORDS_FILENAME, + load_records_from_path, + truncation_warning, +) from evalrx.analysis.holdout import holdout_confirm as run_holdout_confirm from evalrx.analysis.holdout import split_records from evalrx.viz.renderer import render_chart_specs @@ -41,12 +45,134 @@ def _build_judge(model: str): - """Judge for the held-out confirm phase (separate so tests can stub it).""" + """Claude judge for the held-out confirm phase (separate so tests can stub it).""" from evalrx.agent_runtime.judges import ClaudeModel return ClaudeModel(model=model, effort="low") +_CLAUDE_BACKENDS = ("claude", "claude_code") +_DEFAULT_CLAUDE_JUDGE = "claude-opus-4-8" + + +def resolve_judge( + judge_backend: str, + judge_model: str, + *, + coder_provider: str, + coder_model: str = "", + coder_binary: str = "", + timeout_sec: int = 120, +) -> "tuple[Any, dict[str, Any]]": + """The judge that grades hypotheses on held-out rows, and a record of it. + + *judge_backend* ``"same"`` follows the backend the explorer ran on, so a + run on a backend other than Claude does not need the Claude CLI as well. + Any other value names a backend outright. The returned record says which + backend and model graded, and whether that is the model that proposed the + hypotheses — a review by the proposer is not an independent check, and the + report says so rather than leaving it to be assumed. + """ + backend = coder_provider if judge_backend in ("", "same") else judge_backend + if backend in _CLAUDE_BACKENDS: + model = judge_model or _DEFAULT_CLAUDE_JUDGE + judge: Any = _build_judge(model) + meta: dict[str, Any] = {"backend": "claude", "model": model, "effort": "low"} + else: + from evalrx.agent_runtime.cli_types import CliAgentConfig + from evalrx.agent_runtime.judges.cli_agent import CliAgentJudge + + same_backend = backend == coder_provider + model = judge_model or (coder_model if same_backend else "") + judge = CliAgentJudge( + CliAgentConfig( + provider=backend, model=model, + binary_path=coder_binary if same_backend else "", + timeout_sec=timeout_sec, + ), + timeout_sec=timeout_sec, + ) + meta = {"backend": backend, "model": model or "(backend default)"} + + proposer_claude = coder_provider in _CLAUDE_BACKENDS + same_family = (backend in _CLAUDE_BACKENDS) == proposer_claude and ( + proposer_claude or backend == coder_provider + ) + if same_family: + reviewer_model = "" if meta["model"] == "(backend default)" else meta["model"] + if coder_model and reviewer_model and coder_model != reviewer_model: + meta["same_as_proposer"] = "no" + elif coder_model == reviewer_model: + meta["same_as_proposer"] = "yes" + else: + # One side runs on its backend's default model, which is not known here. + meta["same_as_proposer"] = "same_backend" + else: + meta["same_as_proposer"] = "no" + return judge, meta + + +def same_reviewer_caveat(judge_meta: "dict[str, Any] | None", coder_provider: str) -> str: + """A sentence for the report when the reviewer is, or may be, the proposer.""" + same = (judge_meta or {}).get("same_as_proposer") + if same == "yes": + return ( + f"the hypotheses were proposed and graded by the same model " + f"({judge_meta.get('model') if judge_meta else ''} on {coder_provider}); " + "its grades are not an independent review. Signal verdicts and " + "host-checked predictions do not depend on the judge." + ) + if same == "same_backend": + return ( + f"the hypotheses were proposed and graded on the same backend " + f"({coder_provider}), and at least one of the two used its default " + "model, so the grader may be the proposer; pass --judge-backend or " + "--judge-model for an independent review. Signal verdicts and " + "host-checked predictions do not depend on the judge." + ) + return "" + + +#: The four things a reader needs to know about a table before trusting any +#: pattern found in it. Keys are the ``data_card`` fields. +DATA_CARD_QUESTIONS = { + "unit": "what one row is", + "extraction": "how a row was cut from the raw object", + "threshold": "how the outcome or its threshold was set", + "aggregation": "how results are combined when the system is used", +} + + +def load_data_card(path: "str | Path") -> dict[str, str]: + """Read a data card (JSON or YAML mapping) and keep its known fields.""" + text = Path(path).read_text(encoding="utf-8") + try: + raw = json.loads(text) + except json.JSONDecodeError: + import yaml + + raw = yaml.safe_load(text) + if not isinstance(raw, dict): + raise ValueError(f"data card {path} must be a mapping of field to answer") + return {k: str(v).strip() for k, v in raw.items() + if k in DATA_CARD_QUESTIONS and str(v).strip()} + + +def data_card_caveats(card: "dict[str, str] | None") -> list[str]: + """The data card as report caveats: each answer, then what was left unanswered.""" + card = card or {} + out = [f"data card — {DATA_CARD_QUESTIONS[k]}: {card[k]}" + for k in DATA_CARD_QUESTIONS if card.get(k)] + missing = [DATA_CARD_QUESTIONS[k] for k in DATA_CARD_QUESTIONS if not card.get(k)] + if missing: + out.append( + "data card — not stated: " + "; ".join(missing) + ". Patterns below " + "may come from how the table was built rather than from the system; " + "answer these with --data-card or the --row-* flags." + ) + return out + + def run_explore( path: str | Path, *, @@ -69,8 +195,14 @@ def run_explore( holdout_frac: float = 0.0, holdout_seed: int = 0, holdout_confirm: bool = False, - judge_model: str = "claude-opus-4-8", + judge_model: str = "", progress_sink: Any = None, + group_col: str | None = None, + time_col: str | None = None, + text_col: str | None = None, + data_card: "dict[str, str] | None" = None, + judge_backend: str = "same", + keep_sandbox: bool = False, ) -> int: """Run one exploratory analysis and persist its artifacts. @@ -97,19 +229,48 @@ def run_explore( recipes + hypotheses (``analysis.holdout``) and ``confirm_report.json`` lands next to the exploratory report. Without it the rows are simply reserved on disk. + + *group_col* names the unit rows were cut from. The split then keeps each + group on one side and the held-out intervals resample whole groups. When + it is not given and a column looks like such a unit, the run says so and + reports how many held-out rows share a group with an explored row. + *time_col* names a time column. *text_col* names a free-text column: the + words over-represented on either side of the outcome in the exploration + half are frozen as keyword recipes and re-tested with everything else. + + *data_card* answers :data:`DATA_CARD_QUESTIONS`; the answers, and the + questions left unanswered, are printed in the report's caveats. + + *judge_backend* picks who grades the hypotheses: ``"same"`` (default) uses + the explorer's backend, anything else names a backend. *judge_model* + overrides its model. """ out_dir = Path(out).resolve() out_dir.mkdir(parents=True, exist_ok=True) source: Any = path holdout_rows: "list[dict[str, Any]] | None" = None + host_caveats: list[str] = data_card_caveats(data_card) + extra_candidates: list[Any] = [] + split_extra: dict[str, Any] = {} + if data_card: + question = question.rstrip() + " DATA CARD (from the user): " + "; ".join( + f"{DATA_CARD_QUESTIONS[k]} — {v}" for k, v in data_card.items() + if k in DATA_CARD_QUESTIONS + ) + "." if holdout_frac and holdout_frac > 0: + load_info: dict[str, Any] = {} records = load_records_from_path( path, max_rows=max_rows, max_files=max_files, - include_tool_calls=include_tool_calls, + include_tool_calls=include_tool_calls, info=load_info, ) + warning = truncation_warning(load_info, max_rows) + if warning: + print(f"WARNING: {warning}") + host_caveats.append(warning) explore_share, holdout_rows = split_records( - records, holdout_frac, seed=holdout_seed, outcome_col=outcome_col + records, holdout_frac, seed=holdout_seed, outcome_col=outcome_col, + group_col=group_col, ) if holdout_rows is None: print(f"holdout: split impossible (n={len(records)}, frac={holdout_frac}) " @@ -122,6 +283,23 @@ def run_explore( else "(reserved, not verified in this mode)")) if holdout_confirm: question = question.rstrip() + HOLDOUT_QUESTION_SUFFIX + split_extra, group_caveats = _group_checks( + records, explore_share, holdout_rows, + outcome_col=outcome_col, group_col=group_col, time_col=time_col, + ) + for caveat in group_caveats: + print(f"WARNING: {caveat}") + host_caveats.extend(group_caveats) + if text_col: + extra_candidates = _keyword_candidates( + explore_share, text_col, outcome_col or "label" + ) + if extra_candidates: + print(f"keywords: froze {len(extra_candidates)} keyword recipe(s) " + f"from {text_col!r} on the exploration rows") + elif text_col: + print("keywords: --text-col needs --holdout-frac > 0 (keyword recipes are " + "chosen on one half and tested on the other); ignored") result = explore( source, @@ -131,6 +309,8 @@ def run_explore( model=coder_model, binary=coder_binary, outcome_col=outcome_col, + group_col=group_col, + time_col=time_col, propose_hypotheses=propose_hypotheses, skills=skills, allow_skills=allow_skills, @@ -141,6 +321,9 @@ def run_explore( timeout_sec=timeout_sec, max_attempts=max_attempts, progress_sink=progress_sink, + keep_sandbox=keep_sandbox, + caveats=host_caveats, + extra_candidates=extra_candidates, ) report = result.report @@ -167,7 +350,8 @@ def run_explore( print( f"\nhost adjudication ({adj.get('split')}): " f"{adj.get('n_rejected', 0)}/{adj.get('n_host_adjudicated', 0)} reject " - f"(e-BH family n={adj.get('n_in_family', 0)}, alpha={adj.get('alpha')})" + f"(correction: {adj.get('method')}, e-BH family n={adj.get('n_in_family', 0)}, " + f"BH family n={adj.get('n_in_p_family', 0)}, alpha={adj.get('alpha')})" ) if holdout_rows is not None: @@ -181,23 +365,35 @@ def run_explore( "holdout_frac": holdout_frac, "seed": holdout_seed, "stratified_by": outcome_col or "label", + "group_col": group_col, + **split_extra, } if holdout_confirm: judge = None judge_meta = None + confirm_caveats = list(host_caveats) try: - judge = _build_judge(judge_model) - judge_meta = {"model": judge_model, "effort": "low"} + judge, judge_meta = resolve_judge( + judge_backend, judge_model, coder_provider=coder_provider, + coder_model=coder_model, coder_binary=coder_binary, + timeout_sec=timeout_sec, + ) except Exception as exc: # noqa: BLE001 — verdicts degrade to not_judged print(f"judge unavailable ({exc}) — hypotheses will be not_judged") + reviewer = same_reviewer_caveat(judge_meta, coder_provider) + if reviewer and report.hypotheses: + print(f"WARNING: {reviewer}") + confirm_caveats.append(reviewer) if progress_sink is not None: progress_sink.emit("m4", "started", "Verifying hypotheses on the held-out split") confirm = run_holdout_confirm( report.to_dict(), holdout_rows, outcome_col=outcome_col or "label", judge=judge, judge_meta=judge_meta, + group_col=group_col, ) confirm["split_meta"] = split_meta + confirm["caveats"] = confirm_caveats (out_dir / "confirm_report.json").write_text( json.dumps(confirm, indent=1, default=str), encoding="utf-8" ) @@ -215,10 +411,22 @@ def run_explore( f"\nheld-out adjudication: {cadj.get('n_rejected', 0)}/" f"{cadj.get('n_host_adjudicated', 0)} reject " f"(n={confirm.get('n_validate_rows')} rows, " - f"{confirm.get('n_validate_fail')} failures)" + f"{confirm.get('n_validate_fail')} failures; correction: " + f"{cadj.get('method')} over {cadj.get('n_in_family', 0)} claim(s)" + + (f", groups: {group_col}" if group_col else "") + ")" ) + for v in confirm.get("signal_verdicts", []): + if v.get("status") != "adjudicated": + continue + claim = v.get("claim") or {} + ci = v.get("ci") or (float("nan"), float("nan")) + print(f" - {v.get('name')} [{v.get('design')}]: effect " + f"{v.get('effect'):+.4f} (CI {ci[0]:+.4f}..{ci[1]:+.4f}), " + f"claim \"{claim.get('text')}\" {claim.get('status')}") for v in confirm.get("hypothesis_verdicts", []): - print(f" * [{v.get('verdict')}] {str(v.get('statement', ''))[:90]}") + host = v.get("host_verdict") + tag = f"{v.get('verdict')}" + (f"; host: {host}" if host not in (None, "none") else "") + print(f" * [{tag}] {str(v.get('statement', ''))[:90]}") else: (out_dir / "holdout_split.json").write_text( json.dumps(split_meta, indent=1), encoding="utf-8" @@ -232,6 +440,88 @@ def run_explore( return 0 if report.ok else 1 +def _group_checks( + records: "list[dict[str, Any]]", + explore_rows: "list[dict[str, Any]]", + holdout_rows: "list[dict[str, Any]]", + *, + outcome_col: str | None, + group_col: str | None, + time_col: str | None, +) -> "tuple[dict[str, Any], list[str]]": + """Check the split against the data's grouping; return split facts and warnings. + + With a group column the overlap is zero by construction and is recorded as + such. Without one, each column that looks like a grouping unit is reported + with the share of held-out rows whose group the explorer has seen: when + that share is large the "held-out" rows are near-copies of explored ones. + Columns that almost determine the outcome are reported as well. + """ + from evalrx.analysis.fused_pipeline import group_overlap + from evalrx.analysis.profile import profile_records + + facts: dict[str, Any] = {} + caveats: list[str] = [] + if group_col: + if not any(r.get(group_col) not in (None, "") for r in records): + caveats.append( + f"group column {group_col!r} is absent or empty in the loaded rows; " + "the split and the intervals treated rows as independent" + ) + else: + facts["group_overlap"] = group_overlap(explore_rows, holdout_rows, group_col) + profile = profile_records( + records, outcome_col=outcome_col, + group_cols=[group_col] if group_col else (), + time_cols=[time_col] if time_col else (), + ) + suggested = [] + for s in profile.suggested_group_columns: + overlap = group_overlap(explore_rows, holdout_rows, s["column"]) + suggested.append({**s, "holdout_share_in_explore_groups": overlap["share"]}) + if group_col: + continue + caveats.append( + f"column {s['column']!r} looks like the unit rows were cut from " + f"({s['n_groups']} groups; rows of one group share {s['icc']:.0%} of the " + f"outcome variance) and {overlap['share']:.1%} of held-out rows share " + "a group with an explored row, so the held-out check is not independent " + f"of the exploration. Re-run with --group-col {s['column']}." + ) + if suggested: + facts["suggested_group_columns"] = suggested + for s in profile.leakage_suspects: + caveats.append( + f"column {s['column']!r} almost fully determines the outcome " + f"({s['measure']}={s['value']}); a signal built on it may be the " + "outcome under another name" + ) + if profile.leakage_suspects: + facts["leakage_suspects"] = profile.leakage_suspects + return facts, caveats + + +def _keyword_candidates( + explore_rows: "list[dict[str, Any]]", text_col: str, outcome_col: str +) -> list[Any]: + """Keyword recipes chosen on the exploration rows (see ``analysis.keywords``).""" + from evalrx.analysis.holdout import outcome_values + from evalrx.analysis.keywords import keyword_candidates + + values, kind, _, _ = outcome_values(explore_rows, outcome_col) + if kind is None: + return [] + if kind == "continuous": + present = sorted(v for v in values if v is not None) + median = present[len(present) // 2] + side: "list[float | None]" = [ + None if v is None else (1.0 if v > median else 0.0) for v in values + ] + return keyword_candidates(explore_rows, text_col, side, + side_names=("above-median", "at-or-below-median")) + return keyword_candidates(explore_rows, text_col, values) + + def _verdict_suffix(signal: Any) -> str: """One-line host verdict tag for a candidate signal, or '' if not adjudicated.""" if not getattr(signal, "host_adjudicated", False): @@ -243,7 +533,10 @@ def _verdict_suffix(signal: Any) -> str: parts.append(f"e={signal.e_value:.2f}") parts.append("e-BH family") elif signal.ci is not None: - parts.append(f"CI={signal.ci[0]:+.3f}..{signal.ci[1]:+.3f} (not FDR-corrected)") + parts.append(f"CI={signal.ci[0]:+.3f}..{signal.ci[1]:+.3f}") + if getattr(signal, "p_value", None) is not None: + parts.append(f"p={signal.p_value:.3g}") + parts.append("BH family") return " [host: " + ", ".join(parts) + "]" diff --git a/evalrx/analysis/explorer.py b/evalrx/analysis/explorer.py index 44d653d7..1b46ea35 100755 --- a/evalrx/analysis/explorer.py +++ b/evalrx/analysis/explorer.py @@ -122,6 +122,7 @@ class CandidateSignal: effect: float | None = None ci: tuple[float, float] | None = None e_value: float | None = None + p_value: float | None = None # host-computed (two_group); never self-declared reject: bool | None = None underpowered: bool = False host_adjudicated: bool = False @@ -139,6 +140,7 @@ def to_dict(self) -> dict[str, Any]: "effect": self.effect, "ci": list(self.ci) if self.ci is not None else None, "e_value": self.e_value, + "p_value": self.p_value, "reject": self.reject, "underpowered": self.underpowered, "host_adjudicated": self.host_adjudicated, @@ -273,6 +275,8 @@ def __init__( cli_config = replace(cli_config, skills=bundled, allow_skills=True) self._cli_config = cli_config + # A sandbox made here is this agent's to remove; one passed in is not. + self._owns_sandbox = sandbox is None self._sandbox = sandbox or ExperimentSandbox(cleanup=False) self._timeout_sec = timeout_sec self._max_attempts = max(1, max_attempts) @@ -287,15 +291,40 @@ def available(self) -> bool: self._cli_config is not None and self._cli_config.provider != "llm" ) + def discard_sandbox(self) -> bool: + """Delete the temporary sandbox this agent created; True if it did. + + The sandbox holds a full copy of the input data. Once the artifacts + have been copied to an output directory nothing reads it again, so it + should not be left in the system temp directory. A sandbox the caller + supplied is never touched. + """ + if not self._owns_sandbox: + return False + workdir = Path(self._sandbox.workdir) + import tempfile + + temp_root = Path(tempfile.gettempdir()).resolve() + if workdir.parent != temp_root or not workdir.name.startswith("evalrx_sandbox_"): + return False + shutil.rmtree(workdir, ignore_errors=True) + return not workdir.exists() + def explore_records( self, records: Any, *, question: str = "Explore this dataset and surface the patterns that matter.", outcome_col: str | None = None, + group_col: str | None = None, + time_col: str | None = None, ) -> ExploratoryAnalysisReport: """Run local exploratory analysis over plain records. + ``group_col`` names the unit rows were cut from and ``time_col`` a + time column; both override the name heuristics in the data profile the + explorer is shown. + ``outcome_col`` optionally names the target/label column explicitly (e.g. M1 always passes ``"label"``). When omitted, the outcome (if any) is auto-detected by name heuristics; arbitrary datasets with no @@ -303,7 +332,9 @@ def explore_records( having a FAIL/PASS split forced onto them. """ rows = _records_to_rows(records) - profile = _profile_rows(rows, outcome_col=outcome_col) + profile = _profile_rows( + rows, outcome_col=outcome_col, group_col=group_col, time_col=time_col + ) self._write_input(rows) return self._run_explore_loop( question, profile, lambda: self._write_code(question, profile) @@ -318,6 +349,8 @@ def explore_path( max_files: int = 200, include_tool_calls: bool = False, outcome_col: str | None = None, + group_col: str | None = None, + time_col: str | None = None, ) -> ExploratoryAnalysisReport: """Run exploratory analysis directly over *path* (a file or directory). @@ -340,16 +373,28 @@ def explore_path( max_files=max_files, include_tool_calls=include_tool_calls, outcome_col=outcome_col, + group_col=group_col, + time_col=time_col, ) else: + load_info: dict[str, Any] = {} rows = load_records_from_path( path, max_rows=max_rows, max_files=max_files, include_tool_calls=include_tool_calls, + info=load_info, + ) + report = self.explore_records( + rows, question=question, outcome_col=outcome_col, + group_col=group_col, time_col=time_col, ) - report = self.explore_records(rows, question=question, outcome_col=outcome_col) report.data_profile.setdefault("loaded_rows", len(rows)) + warning = truncation_warning(load_info, max_rows) + if warning: + report.data_profile.setdefault("available_rows", load_info.get("n_available")) + if warning not in report.caveats: + report.caveats.append(warning) report.data_profile.setdefault("source_path", str(Path(path))) report.data_profile.setdefault("folder_scan", folder_scan) return report @@ -363,13 +408,22 @@ def _explore_raw_folder( max_files: int, include_tool_calls: bool, outcome_col: str | None, + group_col: str | None = None, + time_col: str | None = None, ) -> ExploratoryAnalysisReport: raw_input_dir = self._copy_raw_input(path, max_files=max_files, include_tool_calls=include_tool_calls) profile: dict[str, Any] = {"folder_scan": folder_scan, "raw_input_dir": raw_input_dir} + if group_col: + profile["group_columns"] = [group_col] + if time_col: + profile["time_columns"] = [time_col] return self._run_explore_loop( question, profile, - lambda: self._write_code_raw_folder(question, folder_scan, raw_input_dir, outcome_col), + lambda: self._write_code_raw_folder( + question, folder_scan, raw_input_dir, outcome_col, + group_col=group_col, time_col=time_col, + ), ) def _copy_raw_input(self, path: str | Path, *, max_files: int, include_tool_calls: bool) -> str: @@ -572,6 +626,9 @@ def _write_code_raw_folder( folder_scan: dict[str, Any], raw_input_dir: str, outcome_col: str | None, + *, + group_col: str | None = None, + time_col: str | None = None, ) -> tuple[str, str]: outcome_hint = ( f'- the caller named "{outcome_col}" as the target/outcome column — ' @@ -579,6 +636,18 @@ def _write_code_raw_folder( "of any other auto-detection heuristic you might otherwise apply\n" if outcome_col else "" ) + if group_col: + outcome_hint += ( + f'- the caller named "{group_col}" as the GROUP column: rows that ' + "share its value were cut from the same source item and are not " + "independent. Keep it in your tidy table, count groups as well as " + "rows, and do not treat it as an ordinary predictor\n" + ) + if time_col: + outcome_hint += ( + f'- the caller named "{time_col}" as the TIME column — keep it in ' + "your tidy table and check for drift along it\n" + ) prompt = _GENERATE_PROMPT_RAW_FOLDER.format( question=question, input_filename=RECORDS_FILENAME, @@ -814,27 +883,55 @@ def load_records_from_path( max_rows: int = 2000, max_files: int = 200, include_tool_calls: bool = False, + info: "dict[str, Any] | None" = None, ) -> list[dict[str, Any]]: - """Load a bounded sample of JSON/JSONL records from a file or directory.""" + """Load a bounded sample of JSON/JSONL records from a file or directory. + + At most *max_rows* rows are returned, spread evenly over the files. Pass a + dict as *info* to learn what was left out: it receives ``n_loaded``, + ``n_available`` (rows in all the files that were read), ``n_files`` and + ``truncated``. Rows are taken from the start of each file, so a truncated + load is not a random sample. + """ root = Path(path) files, _ = _discover_json_files(root, max_files=max_files, include_tool_calls=include_tool_calls) per_file_limit = max(1, max_rows // max(1, len(files))) rows: list[dict[str, Any]] = [] + n_available = 0 for file_path in files: - n_from_file = 0 - for row in _load_json_records(file_path): + file_rows = _load_json_records(file_path) + n_available += len(file_rows) + if len(rows) >= max_rows: + if info is None: + break + continue # only counting what the cap left out + for row in file_rows[:per_file_limit]: flat = _flatten_record(row) flat["_source_file"] = str(file_path) flat["_source_dir"] = file_path.parent.name rows.append(flat) - n_from_file += 1 if len(rows) >= max_rows: - return rows - if n_from_file >= per_file_limit: break + if info is not None: + info.update( + n_loaded=len(rows), n_available=n_available, n_files=len(files), + truncated=len(rows) < n_available, + ) return rows +def truncation_warning(info: "dict[str, Any]", max_rows: int) -> str: + """One sentence saying how many rows the cap dropped, or '' if none.""" + if not info.get("truncated"): + return "" + return ( + f"only {info.get('n_loaded')} of {info.get('n_available')} rows were loaded " + f"(the limit is {max_rows} rows, split evenly over {info.get('n_files')} " + "file(s) and taken from the start of each); the rest were not analysed, " + "and the loaded rows are not a random sample. Raise --max-rows to include them." + ) + + _RECORD_LIST_KEYS = ("cases", "records", "results", "rows", "items", "data", "examples", "samples") @@ -949,6 +1046,8 @@ def _profile_rows( rows: list[dict[str, Any]], *, outcome_col: str | None = None, + group_col: str | None = None, + time_col: str | None = None, sample_size: int = 5, ) -> dict[str, Any]: """Profile rows for the explorer prompt, including outcome-kind detection. @@ -958,7 +1057,11 @@ def _profile_rows( the prompt can adapt to binary / categorical / continuous / no-outcome data instead of always assuming a FAIL/PASS split. """ - profile = profile_records(rows, outcome_col=outcome_col) + profile = profile_records( + rows, outcome_col=outcome_col, + group_cols=[group_col] if group_col else (), + time_cols=[time_col] if time_col else (), + ) outcome = describe_outcome(profile) numeric_columns = [ c.name for c in profile.columns.values() @@ -979,6 +1082,11 @@ def _profile_rows( "id_columns": profile.id_columns, "group_columns": profile.group_columns, "time_columns": profile.time_columns, + # The unit rows were cut from, when the caller named one. Rows that + # share it are not independent evidence. + "unit_column": group_col, + "suggested_group_columns": profile.suggested_group_columns, + "leakage_suspects": profile.leakage_suspects, "outcome": outcome, "warnings": profile.warnings, "sample_rows": rows[:sample_size], diff --git a/evalrx/analysis/fused_pipeline.py b/evalrx/analysis/fused_pipeline.py index 01709cc8..bd2c615b 100644 --- a/evalrx/analysis/fused_pipeline.py +++ b/evalrx/analysis/fused_pipeline.py @@ -137,18 +137,101 @@ def to_dict(self) -> dict[str, Any]: # Deterministic stratified EXPLORE / CONFIRM split (records level) # --------------------------------------------------------------------------- +def _group_key(row: Any, group_col: str, index: int) -> Any: + """A row's group, or a key unique to the row when the group is missing.""" + value = row.get(group_col) if isinstance(row, dict) else getattr(row, group_col, None) + if value is None or value == "": + return ("__row__", index) + return ("v", str(value)) + + +def _split_by_group( + rows: list[dict[str, Any]], + *, + n_confirm: int, + seed: int, + label_col: str, + group_col: str, +) -> "tuple[list[dict], list[dict]]": + """Split so that every group lies wholly on one side. + + Groups are stratified by their most common label and, within a stratum, + drawn in a seeded random order until the stratum's share of the confirm + rows is reached. Group sizes differ, so the confirm share is approximate: + the draw stops at whichever group count lands closest to the target. + """ + import random + from collections import Counter + + members: dict[Any, list[int]] = {} + for i, row in enumerate(rows): + members.setdefault(_group_key(row, group_col, i), []).append(i) + + strata: dict[str, list[Any]] = {} + distinct = {str(r.get(label_col)) for r in rows} + if len(distinct) > 10: + # A many-valued outcome (a score) has no "most common label" worth + # stratifying on. Stratify groups by the quartile of their mean when + # the outcome is numeric, and not at all otherwise. + means: dict[Any, float] = {} + for key, idxs in members.items(): + nums = [ + float(v) for v in (rows[i].get(label_col) for i in idxs) + if isinstance(v, (int, float)) and not isinstance(v, bool) + ] + if nums: + means[key] = sum(nums) / len(nums) + ranked = sorted(means, key=lambda k: (means[k], str(k))) + quartile = {k: f"q{min(3, 4 * pos // max(1, len(ranked)))}" + for pos, k in enumerate(ranked)} + for key in members: + strata.setdefault(quartile.get(key, "unscored"), []).append(key) + else: + for key, idxs in members.items(): + labels = Counter(str(rows[i].get(label_col)) for i in idxs) + # Ties resolve to the label that sorts first, so the split is deterministic. + top = min(labels, key=lambda lab: (-labels[lab], lab)) + strata.setdefault(top, []).append(key) + + rng = random.Random(seed) + frac = n_confirm / len(rows) + confirm_idx: set[int] = set() + for label in sorted(strata): + keys = strata[label] + rng.shuffle(keys) + target = frac * sum(len(members[k]) for k in keys) + taken = 0 + for key in keys: + size = len(members[key]) + # Take the group only if that brings the stratum closer to its target. + if abs(taken + size - target) > abs(taken - target): + continue + confirm_idx.update(members[key]) + taken += size + explore = [r for i, r in enumerate(rows) if i not in confirm_idx] + confirm = [r for i, r in enumerate(rows) if i in confirm_idx] + return explore, confirm + + def _split_records( records: list[dict[str, Any]], *, frac: float, seed: int, label_col: str, + group_col: str | None = None, ) -> "tuple[list[dict], list[dict] | None]": """Deterministic, label-stratified ``(explore, confirm)`` split. Returns ``(explore, confirm)``. Like the in-loop split, returns ``(records, None)`` when ``frac <= 0`` or the batch is too small to hold out — a no-op, so the caller falls back to in-sample confirmation with a caveat. + + With *group_col*, rows that share a value of that column are kept on one + side. Use it when rows are not independent — several rows cut from the + same source item, the same prompt answered by several models — because a + row-level split would otherwise put near-copies of an explore row in the + confirm half and the confirmation would not be held out in any useful sense. """ from evalrx.stats.subset_sampling import stratified_subset @@ -159,6 +242,15 @@ def _split_records( if n_confirm <= 0 or n_confirm >= len(rows): return rows, None + if group_col: + explore, confirm = _split_by_group( + rows, n_confirm=n_confirm, seed=seed, label_col=label_col, + group_col=group_col, + ) + if not explore or not confirm: + return rows, None + return explore, confirm + def _key(row: dict[str, Any]) -> Any: return str(row.get(label_col)) @@ -170,6 +262,33 @@ def _key(row: dict[str, Any]) -> Any: return explore, confirm +def group_overlap( + explore: list[dict[str, Any]], + confirm: list[dict[str, Any]], + group_col: str, +) -> dict[str, Any]: + """How many confirm rows share a *group_col* value with an explore row. + + A share near zero means the two halves are separated at the group level; + a large share means the confirm half repeats groups the explorer has seen. + Rows with a missing group value count as not shared. + """ + seen = { + str(r.get(group_col)) for r in explore + if r.get(group_col) not in (None, "") + } + present = [r for r in confirm if r.get(group_col) not in (None, "")] + shared = sum(1 for r in present if str(r.get(group_col)) in seen) + return { + "group_col": group_col, + "n_confirm_rows": len(confirm), + "n_confirm_rows_in_explore_groups": shared, + "share": round(shared / len(confirm), 4) if confirm else 0.0, + "n_explore_groups": len(seen), + "n_confirm_groups": len({str(r.get(group_col)) for r in present}), + } + + # --------------------------------------------------------------------------- # Orchestrator # --------------------------------------------------------------------------- @@ -184,6 +303,7 @@ def run_fused_analysis( seed: int = 0, id_col: str = "case_id", label_col: str = "label", + group_col: str | None = None, ) -> FusedReport: """Run discovery on EXPLORE, confirmation on the held-out CONFIRM split. @@ -194,10 +314,13 @@ def run_fused_analysis( stats_agent: optional :class:`StatsAnalysisAgent`; one is built with a high signal cap when omitted so the whole family is tested. confirm_split: fraction held out for confirmation (0 = in-sample fallback). + group_col: optional column naming the unit rows were cut from; rows + that share a value stay on one side of the split. """ rows = list(records or []) explore_rows, confirm_rows = _split_records( - rows, frac=confirm_split, seed=seed, label_col=label_col + rows, frac=confirm_split, seed=seed, label_col=label_col, + group_col=group_col, ) held_out = confirm_rows is not None confirm_label = "held_out" if held_out else "in_sample" @@ -213,6 +336,12 @@ def run_fused_analysis( "frac": confirm_split, "seed": seed, } + if group_col: + report.split["group_col"] = group_col + if held_out: + report.split["group_overlap"] = group_overlap( + explore_rows, confirm_rows, group_col + ) # ── 1. Discovery source A: the LAMBDA explorer (EXPLORE only) ── explore_report = explorer.explore_records(explore_rows, question=question) diff --git a/evalrx/analysis/holdout.py b/evalrx/analysis/holdout.py index 6558006a..ce6dac8b 100644 --- a/evalrx/analysis/holdout.py +++ b/evalrx/analysis/holdout.py @@ -6,20 +6,22 @@ 1. :func:`split_records` carves the loaded records into a deterministic, outcome-stratified explore/holdout partition BEFORE exploration — the - explorer only ever sees the explore share. + explorer only ever sees the explore share. With a group column, rows that + share a group stay on one side. 2. :func:`holdout_confirm` re-evaluates the explorer's FROZEN recipes verbatim - on the held-out rows (:func:`~evalrx.analysis.operationalize.compile_recipe`, - thresholds exactly as fitted — no re-fitting), rebuilds two-group sufficient - statistics, adjudicates with - :func:`~evalrx.analysis.adjudicate.adjudicate_signals` - (``split_label="held_out"`` — a REJECT here is a real held-out verdict), and - optionally has an LLM judge grade each M3 hypothesis against the held-out - table (supported / partial / refuted / not_testable + surgery routing). + on the held-out rows (thresholds, subgroup conditions, strata and cut + points exactly as fitted — no re-fitting), estimates each one's effect with + a cluster bootstrap (:mod:`~evalrx.analysis.holdout_designs`), corrects all + claims in one Benjamini-Hochberg family, checks the numeric predictions a + hypothesis carries, and optionally has an LLM judge grade each M3 + hypothesis against the held-out table (supported / partial / refuted / + not_testable + surgery routing). The returned dict is the ``confirm_report.json`` shape the dashboard's *Held-out Verdicts* tab renders. The judge is duck-typed (any object with ``generate(str) -> str``); pass ``judge=None`` for signal verdicts only — -hypotheses then carry ``verdict="not_judged"``. +hypotheses then carry ``verdict="not_judged"`` and, when they stated numeric +predictions, a ``host_verdict`` that needed no judge. """ from __future__ import annotations @@ -29,11 +31,24 @@ 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 -from evalrx.analysis.operationalize import RecipeError, SignalRecipe, compile_recipe +from evalrx.analysis.holdout_designs import ( + DesignEstimate, + claim_status, + contrary_p_value, + estimate_design, + representative_rows, +) +from evalrx.analysis.hypothesis_agent import ExperimentPlan +from evalrx.analysis.operationalize import ( + RecipeError, + SignalRecipe, + expr_columns, + parse_expectation, +) from evalrx.analysis.prompts.holdout import JUDGE_PROMPT +from evalrx.stats.bootstrap import bootstrap_p_value +from evalrx.stats.multiplicity import bh _FAIL_LIKE = ("fail", "failed", "failure", "error", "wrong", "incorrect", "no") @@ -44,6 +59,7 @@ def split_records( *, seed: int = 0, outcome_col: str | None = None, + group_col: str | None = None, ) -> "tuple[list[dict[str, Any]], list[dict[str, Any]] | None]": """Deterministic ``(explore, holdout)`` partition, stratified by outcome. @@ -51,9 +67,14 @@ def split_records( fused path hold out rows the same way. Returns ``(records, None)`` when the fraction or batch size makes a split meaningless — callers fall back to a plain in-sample run with a caveat rather than a fake split. + + *group_col* names the unit rows were cut from; rows that share its value + all go to the same side, so the held-out half holds no near-copy of a row + the explorer saw. """ return _split_records( - records, frac=holdout_frac, seed=seed, label_col=outcome_col or "label" + records, frac=holdout_frac, seed=seed, label_col=outcome_col or "label", + group_col=group_col, ) @@ -112,29 +133,81 @@ def failure_indicator( return out, positive, note -def _holdout_sufficient( - values: "dict[str, float]", - id_to_fail: "dict[str, int]", -) -> "dict[str, Any] | None": - """Two-group sufficient stats: failure indicators among signal-ABSENT (a) - vs signal-PRESENT (b) rows. Defined only for binary-flag recipes — a - continuous recipe has no frozen threshold to reuse.""" - pairs = [(v, id_to_fail[cid]) for cid, v in values.items() if cid in id_to_fail] - if not pairs: - return None - if not {round(v, 6) for v, _ in pairs} <= {0.0, 1.0}: - return None - a = [f for v, f in pairs if v == 0.0] - b = [f for v, f in pairs if v == 1.0] - if not a or not b: - return None - return {"kind": "two_group", "a": a, "b": b} +def outcome_values( + rows: "list[dict[str, Any]]", outcome_col: str +) -> "tuple[list[float | None], str | None, Any, str]": + """The outcome as one number per row: ``(values, kind, positive_label, note)``. + + ``kind`` is ``"binary"`` (values are 0/1 failure indicators, chosen by + :func:`failure_indicator`), ``"continuous"`` (a numeric outcome used as it + is, so effects are differences of means), or None when the column is + neither — then nothing can be re-tested and *note* says why. + """ + indicators, positive, note = failure_indicator(rows, outcome_col) + if positive is not None: + return [None if v is None else float(v) for v in indicators], "binary", positive, note + present = [r.get(outcome_col) for r in rows if r.get(outcome_col) is not None] + if present and all( + isinstance(v, (int, float)) and not isinstance(v, bool) for v in present + ): + values = [ + None if r.get(outcome_col) is None else float(r[outcome_col]) for r in rows + ] + return values, "continuous", None, ( + f"outcome = numeric {outcome_col!r}; effects are differences of its mean " + "(rows a recipe flags minus rows it does not)" + ) + return [None] * len(rows), None, None, note class _HoldoutVerdict(BaseModel): verdict: Literal["supported", "partial", "refuted", "not_testable"] reasoning: str needs_surgery: bool = False + # The plan for the intervention, when one is needed and the hypothesis + # did not already carry one. + experiment: ExperimentPlan | None = None + + +_ID_KEYS = ("case_id", "id", "sample_id") + + +def _row_ref(row: "dict[str, Any]", index: int, id_col: str | None) -> "dict[str, Any]": + """A pointer to one held-out row: its position and, when present, its id.""" + for key in ((id_col,) if id_col else ()) + _ID_KEYS: + value = row.get(key) + if value not in (None, ""): + return {"row": index, "id": value} + return {"row": index, "id": None} + + +def _evidence_line(entry: "dict[str, Any]", outcome_kind: str | None) -> str: + """One line of the held-out table a judge reads, per adjudicated signal.""" + name = entry.get("name") + claim = entry.get("claim") or {} + tail = ( + f"(n={entry.get('n_holdout')}, effect={entry.get('effect')}, " + f"CI={entry.get('ci')}, p={entry.get('p_value')}, " + f"claim \"{claim.get('text')}\" {claim.get('status')}, " + f"verdict={'REJECT H0' if entry.get('reject') else 'not rejected'})" + ) + design = entry.get("design") + details = entry.get("details") or {} + if design == "two_group" and outcome_kind == "binary": + return (f"- {name}: flagged-group fail rate {entry.get('fail_rate_flagged')} " + f"vs unflagged {entry.get('fail_rate_unflagged')} {tail}") + if design == "two_group": + return (f"- {name}: outcome mean {details.get('mean_flagged')} among flagged rows " + f"vs {details.get('mean_unflagged')} among unflagged {tail}") + if design == "stratified": + return (f"- {name}: difference within strata, averaged over " + f"{details.get('n_strata_used')} strata " + f"(unadjusted {details.get('unadjusted_difference')}) {tail}") + if design == "did": + return (f"- {name}: effect {details.get('effect_where_modifier_1')} where the " + f"modifier holds vs {details.get('effect_where_modifier_0')} where it " + f"does not; difference of the two {tail}") + return f"- {name}: outcome change per step up the fixed bins {tail}" def holdout_confirm( @@ -145,31 +218,42 @@ def holdout_confirm( alpha: float = 0.05, judge: Any = None, judge_meta: "dict[str, Any] | None" = None, + group_col: str | None = None, + id_col: str | None = None, + n_boot: int = 2000, + seed: int = 0, + n_representatives: int = 3, ) -> "dict[str, Any]": """Re-test one exploratory report's recipes + hypotheses on held-out rows. *report* is the ``exploratory_report.json`` dict (``to_dict()`` of a live report works too). Returns the ``confirm_report.json`` payload; the caller persists it next to the exploratory report. + + *group_col* names the unit rows were cut from. Rows that share it are + resampled together, so an interval reflects how many independent groups + there are rather than how many rows. Without it rows are treated as + independent, which is only right when they are. + + Every adjudicated signal makes one claim — the recipe's ``expect`` when it + has one, otherwise "the effect is not zero" — and so does every numeric + prediction a hypothesis states. All claims are corrected together with + Benjamini-Hochberg at *alpha*; ``reject`` on a signal means its claim + survived that correction. ``adjudication.method`` names the correction + that was actually applied, and is ``"none"`` when no claim could be tested. """ rows = [dict(r) for r in holdout_rows] - indicators, positive_label, outcome_note = failure_indicator(rows, outcome_col) - - # Stable ids: force the compile id_col so recipe values map back to rows - # regardless of what id-ish keys the upload carries. - id_to_fail: "dict[str, int]" = {} - for i, (row, ind) in enumerate(zip(rows, indicators)): - row["_holdout_id"] = f"h{i}" - if ind is not None: - id_to_fail[f"h{i}"] = ind - n_fail = sum(id_to_fail.values()) + outcome, outcome_kind, positive_label, outcome_note = outcome_values(rows, outcome_col) + n_fail = int(sum(v for v in outcome if v is not None)) if outcome_kind == "binary" else 0 + clusters = [r.get(group_col) for r in rows] if group_col else None candidates_raw = [c for c in report.get("candidate_signals") or [] if isinstance(c, dict)] hypotheses = [h for h in report.get("hypotheses") or [] if isinstance(h, dict)] # ── 1. frozen-recipe re-evaluation on the held-out rows ───────────────── signal_verdicts: "list[dict[str, Any]]" = [] - candidates: "list[CandidateSignal]" = [] + estimates: "dict[int, DesignEstimate]" = {} + recipes: "dict[int, SignalRecipe]" = {} for c in candidates_raw: entry: "dict[str, Any]" = { "name": c.get("name"), @@ -178,85 +262,174 @@ def holdout_confirm( "explore_effect": c.get("effect"), "explore_reject_in_sample": c.get("reject"), } + signal_verdicts.append(entry) recipe_dict = c.get("recipe") - if not id_to_fail: - entry.update(status="skipped", reason=outcome_note or "no binary outcome") - signal_verdicts.append(entry) + if outcome_kind is None: + entry.update(status="skipped", reason=outcome_note or "no usable outcome") continue - if not isinstance(recipe_dict, dict) or recipe_dict.get("kind") != "expr": + if not isinstance(recipe_dict, dict) or recipe_dict.get("kind", "expr") != "expr": entry.update(status="skipped", reason="no expr recipe to re-evaluate") - signal_verdicts.append(entry) continue + recipe = SignalRecipe.from_dict(recipe_dict) try: - values = compile_recipe( - SignalRecipe.from_dict(recipe_dict), rows, id_col="_holdout_id" + est = estimate_design( + recipe, rows, outcome, clusters=clusters, alpha=alpha, + n_boot=n_boot, seed=seed, reserved=(outcome_col,), ) except (RecipeError, NotImplementedError) as exc: entry.update(status="skipped", reason=f"recipe error: {exc}") - signal_verdicts.append(entry) continue - sufficient = _holdout_sufficient(values, id_to_fail) - if sufficient is None: - entry.update( - status="skipped", - reason="recipe is not a binary flag on held-out rows " - "(no frozen threshold to reuse)", - ) - signal_verdicts.append(entry) + if not est.ok: + entry.update(status="skipped", reason=est.reason, design=est.design) continue - cand = CandidateSignal( - name=str(c.get("name") or "signal"), - rationale=str(c.get("rationale") or ""), - recipe=recipe_dict, - sufficient=sufficient, - ) - n_a, n_b = len(sufficient["a"]), len(sufficient["b"]) + index = len(signal_verdicts) - 1 + estimates[index] = est + recipes[index] = recipe entry.update( status="adjudicated", - n_holdout=n_a + n_b, - n_flagged=n_b, - fail_rate_flagged=round(sum(sufficient["b"]) / n_b, 4), - fail_rate_unflagged=round(sum(sufficient["a"]) / n_a, 4), + design=est.design, + n_holdout=est.n, + effect=est.effect, + ci=est.ci, + p_value=est.p_value, + details=est.details, ) - signal_verdicts.append(entry) - candidates.append(cand) - - meta = adjudicate_signals(candidates, alpha=alpha, split_label="held_out") - by_name = {c.name: c for c in candidates} - for entry in signal_verdicts: - adjudicated = by_name.get(str(entry.get("name"))) - if entry.get("status") == "adjudicated" and adjudicated is not None: - entry.update( - reject=bool(adjudicated.reject), - effect=adjudicated.effect, - ci=adjudicated.ci, - fdr_corrected=bool(adjudicated.fdr_corrected), + if est.n_clusters is not None: + entry["n_clusters"] = est.n_clusters + if est.design == "two_group": + entry["n_flagged"] = est.details["n_flagged"] + if outcome_kind == "binary": + entry["fail_rate_flagged"] = round(est.details["mean_flagged"], 4) + entry["fail_rate_unflagged"] = round(est.details["mean_unflagged"], 4) + + # ── 2. numeric predictions carried by hypotheses, on the same estimates ── + by_name: "dict[str, int]" = {} + for index in estimates: + by_name.setdefault(str(signal_verdicts[index].get("name")), index) + prediction_results: "list[list[dict[str, Any]]]" = [] + for h in hypotheses: + results: "list[dict[str, Any]]" = [] + for raw in h.get("predictions") or []: + if not isinstance(raw, dict): + continue + item: "dict[str, Any]" = { + "signal": raw.get("signal"), "relation": raw.get("relation"), + "value": raw.get("value"), + } + parsed = parse_expectation(raw) + target = by_name.get(str(raw.get("signal"))) + if parsed is None: + item.update(status="not_testable", reason="malformed prediction") + elif target is None: + item.update(status="not_testable", + reason="no held-out estimate for that signal") + else: + relation, value = parsed + est = estimates[target] + item.update( + relation=relation, value=value, effect=est.effect, ci=est.ci, + p_value=bootstrap_p_value(est.draws, relation, value), + _p_contrary=contrary_p_value(est.draws, relation, value), + ) + results.append(item) + prediction_results.append(results) + + # ── 3. one correction family over every claim ─────────────────────────── + signal_claims = sorted(estimates) + hypothesis_claims = [ + (hi, pi) for hi, results in enumerate(prediction_results) + for pi, item in enumerate(results) if "p_value" in item + ] + p_values = [float(estimates[i].p_value or 1.0) for i in signal_claims] + [ + float(prediction_results[hi][pi]["p_value"]) for hi, pi in hypothesis_claims + ] + surviving = set(bh(p_values, alpha)) + + for position, index in enumerate(signal_claims): + est, entry = estimates[index], signal_verdicts[index] + holds = position in surviving + status = claim_status(holds, est.p_contrary, alpha) + entry["claim"] = { + "relation": est.relation, "value": est.value, "text": est.claim_text(), + "status": status, "stated_by_recipe": recipes[index].expect is not None, + } + entry["raw_reject"] = bool((est.p_value or 1.0) <= alpha) + entry["fdr_corrected"] = holds + # "The effect is at most this large" holding is not a separation of + # the outcome groups, so it never reads as a rejection. + entry["reject"] = holds and est.relation != "abs<" + if holds and n_representatives > 0: + picked = representative_rows( + est, rows, outcome, expr_columns(recipes[index].expr), k=n_representatives, ) + if picked: + entry["representative_cases"] = { + side: [_row_ref(rows[i], i, id_col) for i in idxs] + for side, idxs in picked.items() + } + for offset, (hi, pi) in enumerate(hypothesis_claims): + item = prediction_results[hi][pi] + holds = (len(signal_claims) + offset) in surviving + item["status"] = claim_status(holds, item.pop("_p_contrary"), alpha) + + n_claims = len(p_values) + # Which tests the p-values in the family came from; each signal records + # its own under details.p_value_method. A hypothesis prediction is always + # read off the bootstrap replicates. + p_value_methods = sorted( + {str(estimates[i].details.get("p_value_method")) for i in signal_claims} + | ({"percentile bootstrap"} if hypothesis_claims else set()) + ) + rejected = [str(e.get("name")) for e in signal_verdicts if e.get("reject")] + meta: "dict[str, Any]" = { + "method": "BH" if n_claims else "none", + "alpha": alpha, + "split": "held_out", + "n_candidates": len(candidates_raw), + "n_host_adjudicated": len(estimates), + "n_in_family": n_claims, + "n_signal_claims": len(signal_claims), + "n_hypothesis_claims": len(hypothesis_claims), + "n_rejected": len(rejected), + "rejected": rejected, + "p_values": p_value_methods or None, + "clustered_by": group_col, + } + if not n_claims: + meta["note"] = "no claim could be re-tested on the held-out rows, so nothing was corrected" - # ── 2. LLM judge per hypothesis, grounded in the held-out table ───────── + # ── 4. LLM judge per hypothesis, grounded in the held-out table ───────── evidence_lines = [ - f"- {e.get('name')}: flagged-group fail rate {e.get('fail_rate_flagged')} " - f"vs unflagged {e.get('fail_rate_unflagged')} " - f"(n={e.get('n_holdout')}, effect={e.get('effect')}, CI={e.get('ci')}, " - f"verdict={'REJECT H0' if e.get('reject') else 'not rejected'})" + _evidence_line(e, outcome_kind) for e in signal_verdicts if e.get("status") == "adjudicated" ] or ["- (no recipe could be re-evaluated on the held-out split)"] evidence = "\n".join(evidence_lines) hypothesis_verdicts: "list[dict[str, Any]]" = [] - for h in hypotheses: + for h, results in zip(hypotheses, prediction_results): verdict = dict(h) + host_verdict = _host_verdict(results) + if results: + verdict["prediction_results"] = results + verdict["host_verdict"] = host_verdict if judge is None: verdict.update(verdict="not_judged", reasoning="", needs_surgery=True) hypothesis_verdicts.append(verdict) continue + checked = "" + if results: + checked = "\n\nPREDICTIONS THE HOST ALREADY CHECKED for this hypothesis:\n" + "\n".join( + f"- {r.get('signal')} {r.get('relation')} {r.get('value')}: " + f"{r.get('status')} (effect={r.get('effect')}, CI={r.get('ci')})" + for r in results + ) prompt = JUDGE_PROMPT.format( statement=h.get("statement", ""), basis=h.get("basis", ""), test_design=h.get("test_design", ""), n_rows=len(rows), - evidence=evidence, + evidence=evidence + checked, ) try: graded = ask_judge(judge, prompt, _HoldoutVerdict, role="holdout_judge").output @@ -267,6 +440,9 @@ def holdout_confirm( else: verdict.update(verdict=graded.verdict, reasoning=graded.reasoning, needs_surgery=graded.needs_surgery) + if (not verdict.get("experiment") and graded.experiment is not None + and not graded.experiment.is_empty()): + verdict["experiment"] = graded.experiment.model_dump() hypothesis_verdicts.append(verdict) return { @@ -277,6 +453,7 @@ def holdout_confirm( "alpha": alpha, "outcome": { "column": outcome_col, + "kind": outcome_kind, "positive_label": positive_label, "note": outcome_note, }, @@ -285,3 +462,20 @@ def holdout_confirm( "hypothesis_verdicts": hypothesis_verdicts, "judge": judge_meta if judge is not None else None, } + + +def _host_verdict(results: "list[dict[str, Any]]") -> str: + """A hypothesis's standing on its own numeric predictions. + + ``supported`` when every prediction holds, ``refuted`` when any is + contradicted, ``inconclusive`` when some stay open, and ``none`` when it + stated no prediction the held-out rows could test. + """ + statuses = [r.get("status") for r in results if r.get("status") != "not_testable"] + if not statuses: + return "none" + if "contradicted" in statuses: + return "refuted" + if all(s == "holds" for s in statuses): + return "supported" + return "inconclusive" diff --git a/evalrx/analysis/holdout_designs.py b/evalrx/analysis/holdout_designs.py new file mode 100644 index 00000000..eaa6bdf6 --- /dev/null +++ b/evalrx/analysis/holdout_designs.py @@ -0,0 +1,497 @@ +"""Comparison designs for re-testing a frozen recipe on held-out rows. + +:func:`~evalrx.analysis.holdout.holdout_confirm` used to know one comparison: +the outcome rate among rows a 0/1 recipe flags against the rate among the rows +it does not. Many findings are not of that shape, and forcing them into it +either loses the finding or tests a different one. This module adds the shapes +that came up in practice, all estimated the same way: + +- ``two_group`` — flagged against unflagged rows (the original). +- ``stratified`` — the same difference taken within strata and averaged + with the strata's sizes as weights, so a gap that is only + a difference in mix between the two groups shrinks. +- ``did`` — difference in differences: how much larger the recipe's + effect is where a second 0/1 condition holds. +- ``dose_response`` — a continuous recipe cut at fixed points chosen during + exploration; the estimate is the change in the outcome + per step up the bins. + +Every design is a statistic of row weights, so one cluster bootstrap +(:func:`evalrx.stats.bootstrap.weighted_bootstrap`) gives each an interval and +a p-value, and rows that belong to one group are resampled together. + +A recipe may also state what it expects (``expect``): that the effect is +positive, negative, or no larger than a bound. "No larger than a bound" is how +a control is written — a comparison that should come out small — and it holds +only when the whole interval lies inside the bound, not whenever the estimate +happens to be near zero. + +Nothing here refits anything: the expression, the subgroup condition, the +strata and the cut points all come from the recipe as it was frozen. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass, field +from typing import Any, Callable + +import numpy as np + +from evalrx.analysis.operationalize import ( + RECIPE_DESIGNS, + RecipeError, + SignalRecipe, + evaluate_expr, + parse_expectation, +) +from evalrx.stats.bootstrap import ( + bootstrap_p_value, + mean_difference_statistic, + weighted_bootstrap, +) +from evalrx.stats.exact import two_group_exact_p + +#: Below this many independent units (groups, or rows when there are none) on +#: the smaller side, a bootstrap interval and p-value are not to be relied on. +MIN_UNITS_PER_SIDE = 10 + +#: At most this many strata / bins are written into a verdict's details. +_MAX_DETAIL_ROWS = 40 + + +@dataclass +class DesignEstimate: + """One recipe's held-out estimate, before any multiplicity correction.""" + + design: str = "" + ok: bool = False + reason: str = "" # why it was skipped, when not ok + effect: float | None = None + ci: tuple[float, float] | None = None + relation: str = "nonzero" # the claim being tested + value: float = 0.0 + p_value: float | None = None # for the claim + p_contrary: float | None = None # for the opposite of a bounded claim + n: int = 0 + n_clusters: int | None = None + details: dict[str, Any] = field(default_factory=dict) + # Bootstrap replicates and the rows used; kept for follow-up claims on the + # same estimate and for picking representative rows. Never serialised. + draws: Any = None + rows_used: list[int] = field(default_factory=list) + flag: list[float] = field(default_factory=list) + + def claim_text(self) -> str: + if self.relation == "nonzero": + return "effect is not zero" + if self.relation == "abs<": + return f"|effect| < {self.value:g}" + return f"effect {self.relation} {self.value:g}" + + +def _as_flag(value: Any) -> float | None: + """A recipe value as 0.0/1.0, or None when it is not a flag.""" + if isinstance(value, bool): + return 1.0 if value else 0.0 + if isinstance(value, (int, float)) and round(float(value), 6) in (0.0, 1.0): + return float(round(float(value))) + return None + + +def _as_number(value: Any) -> float | None: + if isinstance(value, bool): + return 1.0 if value else 0.0 + if isinstance(value, (int, float)) and math.isfinite(float(value)): + return float(value) + return None + + +def _stratified_statistic( + y: np.ndarray, flag: np.ndarray, codes: np.ndarray, n_strata: int +) -> "Callable[[np.ndarray], float]": + """Size-weighted average of the within-stratum difference of means. + + A stratum that loses one of its two groups in a replicate drops out of + that replicate and the remaining weights are renormalised. + """ + in_b, in_a = flag, 1.0 - flag + y_b, y_a = y * in_b, y * in_a + + def statistic(w: np.ndarray) -> float: + w_b = np.bincount(codes, weights=w * in_b, minlength=n_strata) + w_a = np.bincount(codes, weights=w * in_a, minlength=n_strata) + s_b = np.bincount(codes, weights=w * y_b, minlength=n_strata) + s_a = np.bincount(codes, weights=w * y_a, minlength=n_strata) + both = (w_b > 0) & (w_a > 0) + if not both.any(): + return float("nan") + diff = s_b[both] / w_b[both] - s_a[both] / w_a[both] + size = w_b[both] + w_a[both] + return float((diff * size).sum() / size.sum()) + + return statistic + + +def _did_statistic( + y: np.ndarray, flag: np.ndarray, modifier: np.ndarray +) -> "Callable[[np.ndarray], float]": + """(flag effect where modifier is 1) minus (flag effect where it is 0).""" + cells = [(flag * modifier), ((1 - flag) * modifier), + (flag * (1 - modifier)), ((1 - flag) * (1 - modifier))] + sums = [y * c for c in cells] + + def statistic(w: np.ndarray) -> float: + means = [] + for cell, total in zip(cells, sums): + weight = float(w @ cell) + if weight <= 0.0: + return float("nan") + means.append(float(w @ total) / weight) + return (means[0] - means[1]) - (means[2] - means[3]) + + return statistic + + +def _slope_statistic(y: np.ndarray, x: np.ndarray) -> "Callable[[np.ndarray], float]": + """Weighted least-squares slope of *y* on *x* (here: on the bin index).""" + + def statistic(w: np.ndarray) -> float: + total = float(w.sum()) + if total <= 0.0: + return float("nan") + mx = float(w @ x) / total + my = float(w @ y) / total + var = float(w @ ((x - mx) ** 2)) + if var <= 0.0: + return float("nan") + return float(w @ ((x - mx) * (y - my))) / var + + return statistic + + +def _skip(design: str, reason: str) -> DesignEstimate: + return DesignEstimate(design=design, ok=False, reason=reason) + + +def estimate_design( + recipe: SignalRecipe, + rows: "list[dict[str, Any]]", + outcome: "list[float | None]", + *, + clusters: "list[Any] | None" = None, + alpha: float = 0.05, + n_boot: int = 2000, + seed: int = 0, + id_col: str = "case_id", + reserved: "tuple[str, ...] | list[str]" = (), +) -> DesignEstimate: + """Estimate one frozen recipe's effect on *rows* with a cluster bootstrap. + + *outcome* is one number per row (a 0/1 failure indicator or a numeric + outcome), None where it is missing. *clusters* is one group id per row, or + None when rows are independent. Raises :class:`RecipeError` for an invalid + expression; returns a skipped estimate (``ok=False`` with a reason) when + the recipe is valid but the design cannot be estimated on these rows. + """ + design = (recipe.design or "").strip().lower() + if design and design not in RECIPE_DESIGNS: + return _skip(design, f"unknown design {design!r}; expected one of {list(RECIPE_DESIGNS)}") + + kwargs: dict[str, Any] = {"id_col": id_col, "reserved": reserved} + x_raw = evaluate_expr(recipe.expr, rows, **kwargs) + keep = [v is not None and y is not None for v, y in zip(x_raw, outcome)] + n_where_out = 0 + if (recipe.where or "").strip(): + cond = evaluate_expr(recipe.where, rows, what="where", **kwargs) + for i, c in enumerate(cond): + if keep[i] and (c is None or not c): + keep[i] = False + n_where_out += 1 + + flags = [_as_flag(v) for v in x_raw] + numbers = [_as_number(v) for v in x_raw] + idx = [i for i, k in enumerate(keep) if k and numbers[i] is not None] + if not idx: + return _skip(design or "two_group", "the recipe has no value on any held-out row") + is_flag = all(flags[i] is not None for i in idx) + + if not design: + if is_flag: + design = "two_group" + elif recipe.bins: + design = "dose_response" + else: + return _skip( + "two_group", + "recipe is not a binary flag on held-out rows (no frozen threshold " + "to reuse); give it fixed `bins` for a dose-response trend, or " + "write the threshold into the expression", + ) + if design != "dose_response" and not is_flag: + return _skip(design, f"design {design!r} needs a 0/1 recipe; this one is continuous") + + details: dict[str, Any] = {} + if n_where_out: + details["n_excluded_by_where"] = n_where_out + statistic: "Callable[[np.ndarray], float]" + + if design == "two_group": + y = np.asarray([outcome[i] for i in idx], dtype=float) + flag = np.asarray([flags[i] for i in idx], dtype=float) + if flag.sum() == 0 or flag.sum() == len(flag): + return _skip(design, "all held-out rows fall on one side of the recipe") + statistic = mean_difference_statistic(y, flag) + details.update(_two_group_details(y, flag)) + + elif design == "stratified": + if not recipe.strata: + return _skip(design, "design 'stratified' needs `strata` expressions") + labels = [evaluate_expr(e, rows, what="strata", **kwargs) for e in recipe.strata] + idx = [i for i in idx if all(col[i] is not None for col in labels)] + keys = [tuple(str(col[i]) for col in labels) for i in idx] + flag_all = np.asarray([flags[i] for i in idx], dtype=float) + # Only strata that hold both groups can contribute a difference. + sides: dict[tuple, set[float]] = {} + for key, f in zip(keys, flag_all): + sides.setdefault(key, set()).add(float(f)) + usable = {k for k, v in sides.items() if len(v) == 2} + sel = [j for j, k in enumerate(keys) if k in usable] + if not sel: + return _skip(design, "no stratum holds both flagged and unflagged rows") + details["n_strata"] = len(sides) + details["n_strata_used"] = len(usable) + details["n_rows_in_one_sided_strata"] = len(idx) - len(sel) + idx = [idx[j] for j in sel] + keys = [keys[j] for j in sel] + order = {k: c for c, k in enumerate(sorted(usable))} + codes = np.asarray([order[k] for k in keys], dtype=np.int64) + y = np.asarray([outcome[i] for i in idx], dtype=float) + flag = np.asarray([flags[i] for i in idx], dtype=float) + statistic = _stratified_statistic(y, flag, codes, len(order)) + details["unadjusted_difference"] = round( + float(mean_difference_statistic(y, flag)(np.ones(len(y)))), 6) + details["strata"] = _strata_details(y, flag, codes, sorted(usable), recipe.strata) + + elif design == "did": + if not (recipe.modifier or "").strip(): + return _skip(design, "design 'did' needs a 0/1 `modifier` expression") + mod_raw = evaluate_expr(recipe.modifier, rows, what="modifier", **kwargs) + mods = [_as_flag(v) if v is not None else None for v in mod_raw] + if any(mods[i] is None and mod_raw[i] is not None for i in idx): + return _skip(design, "the `modifier` expression is not 0/1 on held-out rows") + idx = [i for i in idx if mods[i] is not None] + y = np.asarray([outcome[i] for i in idx], dtype=float) + flag = np.asarray([flags[i] for i in idx], dtype=float) + mod = np.asarray([mods[i] for i in idx], dtype=float) + cells = {} + for label, m in (("modifier_1", 1.0), ("modifier_0", 0.0)): + for side, f in (("flagged", 1.0), ("unflagged", 0.0)): + pick = (mod == m) & (flag == f) + if not pick.any(): + return _skip(design, f"no held-out row with {label} and {side}") + cells[f"{label}_{side}"] = {"n": int(pick.sum()), + "mean": round(float(y[pick].mean()), 6)} + statistic = _did_statistic(y, flag, mod) + details["cells"] = cells + details["effect_where_modifier_1"] = round( + cells["modifier_1_flagged"]["mean"] - cells["modifier_1_unflagged"]["mean"], 6) + details["effect_where_modifier_0"] = round( + cells["modifier_0_flagged"]["mean"] - cells["modifier_0_unflagged"]["mean"], 6) + + else: # dose_response + edges = sorted(set(recipe.bins)) + if not edges: + return _skip(design, "design 'dose_response' needs fixed `bins` cut points") + x = np.asarray([numbers[i] for i in idx], dtype=float) + y = np.asarray([outcome[i] for i in idx], dtype=float) + bin_index = np.searchsorted(np.asarray(edges), x, side="right").astype(float) + occupied = sorted(set(bin_index.tolist())) + if len(occupied) < 2: + return _skip(design, "held-out rows fall into a single bin") + statistic = _slope_statistic(y, bin_index) + details["bins"] = [ + {"bin": int(b), "low": edges[int(b) - 1] if b >= 1 else None, + "high": edges[int(b)] if b < len(edges) else None, + "n": int((bin_index == b).sum()), + "mean": round(float(y[bin_index == b].mean()), 6)} + for b in occupied + ][:_MAX_DETAIL_ROWS] + details["effect_unit"] = "change in the outcome per step up the bins" + flag = bin_index # kept so representatives can be chosen per bin end + + cl = [clusters[i] for i in idx] if clusters is not None else None + boot = weighted_bootstrap(statistic, len(idx), clusters=cl, n_boot=n_boot, + ci=1.0 - alpha, seed=seed) + draws = boot["draws"] + if draws.size < max(20, n_boot // 2): + return _skip(design, "the estimate was undefined in most bootstrap replicates " + "(a group or cell is too small)") + relation, value = parse_expectation(recipe.expect) or ("nonzero", 0.0) + p_value = bootstrap_p_value(draws, relation, value) + p_contrary = contrary_p_value(draws, relation, value) + details["p_value_method"] = "percentile bootstrap" + binary = bool(np.isin(y, (0.0, 1.0)).all()) + if design == "two_group" and cl is None and binary and (relation == "nonzero" or value == 0.0) and relation != "abs<": + # Independent rows and a binary outcome: the exact test replaces the + # bootstrap p-value, which degenerates on small, cleanly separated + # samples. The interval stays the bootstrap one. + counts = (int(y[flag == 0.0].sum()), int((flag == 0.0).sum()), + int(y[flag == 1.0].sum()), int((flag == 1.0).sum())) + side = {"nonzero": "two-sided", ">": "greater", "<": "less"}[relation] + p_value = two_group_exact_p(*counts, alternative=side) + if relation != "nonzero": + p_contrary = two_group_exact_p( + *counts, alternative="less" if relation == ">" else "greater") + details["p_value_method"] = "exact (Fisher)" + units = _units_per_side(design, flag, cl) + if units is not None: + details["min_units_per_side"] = units + if units < MIN_UNITS_PER_SIDE: + details["small_sample_warning"] = ( + f"only {units} independent unit(s) on the smaller side; the interval " + f"and p-value are unreliable below about {MIN_UNITS_PER_SIDE}" + ) + estimate = DesignEstimate( + design=design, ok=True, effect=float(boot["effect"]), + ci=(float(boot["ci_low"]), float(boot["ci_high"])), + relation=relation, value=value, + p_value=p_value, + p_contrary=p_contrary, + n=len(idx), n_clusters=boot["n_clusters"] if clusters is not None else None, + details=details, draws=draws, rows_used=idx, + flag=[float(v) for v in np.asarray(flag).tolist()], + ) + if boot["n_undefined"]: + estimate.details["n_undefined_replicates"] = int(boot["n_undefined"]) + return estimate + + +def _units_per_side(design: str, flag: np.ndarray, clusters: "list[Any] | None") -> int | None: + """Independent units (groups, else rows) on the smaller side of a comparison. + + For a dose-response design the two sides are the lowest and highest bin. + Returns None for designs whose sides are not two sets of rows. + """ + if design not in ("two_group", "stratified", "dose_response"): + return None + low, high = float(flag.min()), float(flag.max()) + counts = [] + for side in (low, high): + members = np.flatnonzero(flag == side) + if clusters is None: + counts.append(len(members)) + else: + keys = {("__row__", int(j)) if clusters[j] in (None, "") else ("v", clusters[j]) + for j in members} + counts.append(len(keys)) + return int(min(counts)) + + +def contrary_p_value(draws: Any, relation: str, value: float) -> float | None: + """p-value for the OPPOSITE of a bounded claim, or None when there is none. + + "The effect is not zero" has no testable opposite without a bound, so it + can only hold or stay open. A bounded claim can also be contradicted: the + data can show the effect lies on the other side of the bound. + """ + d = np.asarray(draws, dtype=float) + if d.size == 0 or relation == "nonzero": + return None + if relation == ">": + return bootstrap_p_value(d, "<", value) + if relation == "<": + return bootstrap_p_value(d, ">", value) + # "abs<": the opposite is |effect| > value. + return float((1 + int(np.sum(np.abs(d) <= abs(value)))) / (d.size + 1)) + + +def claim_status(holds: bool, p_contrary: float | None, alpha: float) -> str: + """``holds`` / ``contradicted`` / ``inconclusive`` for one claim.""" + if holds: + return "holds" + if p_contrary is not None and p_contrary <= alpha: + return "contradicted" + return "inconclusive" + + +def _two_group_details(y: np.ndarray, flag: np.ndarray) -> dict[str, Any]: + flagged, unflagged = y[flag == 1.0], y[flag == 0.0] + return { + "n_flagged": int(len(flagged)), + "n_unflagged": int(len(unflagged)), + "mean_flagged": round(float(flagged.mean()), 6), + "mean_unflagged": round(float(unflagged.mean()), 6), + } + + +def _strata_details( + y: np.ndarray, flag: np.ndarray, codes: np.ndarray, + keys: "list[tuple]", exprs: "list[str]", +) -> list[dict[str, Any]]: + out = [] + for code, key in enumerate(keys[:_MAX_DETAIL_ROWS]): + pick = codes == code + a, b = y[pick & (flag == 0.0)], y[pick & (flag == 1.0)] + out.append({ + "stratum": dict(zip(exprs, key)), + "n_flagged": int(len(b)), "n_unflagged": int(len(a)), + "difference": round(float(b.mean() - a.mean()), 6), + }) + return out + + +def representative_rows( + estimate: DesignEstimate, + rows: "list[dict[str, Any]]", + outcome: "list[float | None]", + columns: "list[str]", + *, + k: int = 3, +) -> dict[str, list[int]]: + """Typical rows on each side of a comparison, as indices into *rows*. + + "Typical" means close to the side's median on the outcome and on the + numeric *columns* the recipe reads, each distance scaled by the side's + spread. Rows at the median show what the comparison is mostly made of; + the most extreme rows would show the cases least like the rest. For a + dose-response design the two sides are the lowest and the highest bin. + """ + if not estimate.ok or not estimate.rows_used: + return {} + flag = np.asarray(estimate.flag, dtype=float) + low, high = float(flag.min()), float(flag.max()) + if low == high: + return {} + names = ("unflagged", "flagged") if estimate.design != "dose_response" else ("lowest_bin", "highest_bin") + out: dict[str, list[int]] = {} + for name, side in zip(names, (low, high)): + members = [estimate.rows_used[j] for j in np.flatnonzero(flag == side)] + features: list[list[float]] = [[float(outcome[i] or 0.0) for i in members]] + for col in columns: + numeric = [ + float(v) for v in (rows[i].get(col) for i in members) + if isinstance(v, (int, float)) and not isinstance(v, bool) + ] + # A column is used only when every row of the side has a number in it. + if len(numeric) == len(members): + features.append(numeric) + score = np.zeros(len(members)) + for feature in features: + arr = np.asarray(feature) + centre = float(np.median(arr)) + spread = float(np.median(np.abs(arr - centre))) or float(arr.std()) or 1.0 + score += np.abs(arr - centre) / spread + order = np.argsort(score, kind="mergesort")[:k] + out[name] = [members[int(j)] for j in order] + return out + + +__all__ = [ + "DesignEstimate", + "RecipeError", + "claim_status", + "contrary_p_value", + "estimate_design", + "representative_rows", +] diff --git a/evalrx/analysis/hypothesis_agent.py b/evalrx/analysis/hypothesis_agent.py index c6fa0c8d..89b8e0d1 100644 --- a/evalrx/analysis/hypothesis_agent.py +++ b/evalrx/analysis/hypothesis_agent.py @@ -20,8 +20,8 @@ from __future__ import annotations import logging -from dataclasses import dataclass -from typing import TYPE_CHECKING, Any +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Literal from pydantic import BaseModel, Field @@ -64,23 +64,68 @@ def _is_agent_report(report: dict) -> bool: logger = logging.getLogger(__name__) +class ExperimentPlan(BaseModel): + """An experiment the existing table cannot stand in for, in four parts. + + A hypothesis about a cause usually cannot be settled by re-counting rows; + it needs something changed and re-run. Free text hides whether a plan is + complete, so the four parts are separate: a plan with no stated way to + fail is visible as such. + """ + + data_needed: str = Field("", description="rows or inputs to collect or re-run") + operation: str = Field("", description="what is changed or applied to them") + expected_result: str = Field("", description="what is seen if the hypothesis is right") + falsified_by: str = Field("", description="what result would show it is wrong") + + def is_empty(self) -> bool: + return not any((self.data_needed, self.operation, self.expected_result, + self.falsified_by)) + + +class HeldOutPrediction(BaseModel): + """A numeric prediction about one candidate signal's held-out effect. + + The host checks it directly against the held-out rows, so the part of a + hypothesis that is a number is not left to a model to grade. + """ + + signal: str = Field(description="name of a candidate signal that has a recipe") + relation: Literal["nonzero", ">", "<", "abs<"] = "nonzero" + value: float = 0.0 + + @dataclass class Hypothesis: """One M3-proposed, falsifiable candidate explanation. Proposed only — - ``test_design`` names how it *could* be checked, not a verdict.""" + ``test_design`` names how it *could* be checked, not a verdict. + + ``predictions`` are the parts of the claim the held-out rows can decide + (checked by the host); ``experiment`` is the plan for the part they + cannot (an intervention), or None when the hypothesis needs none. + """ statement: str = "" plain_statement: str = "" basis: str = "" test_design: str = "" + predictions: list[dict[str, Any]] = field(default_factory=list) + experiment: dict[str, str] | None = None def to_dict(self) -> dict[str, Any]: - return { + out: dict[str, Any] = { "statement": self.statement, "plain_statement": self.plain_statement, "basis": self.basis, "test_design": self.test_design, } + # Optional parts appear only when stated, so a hypothesis without them + # serialises exactly as it did before they existed. + if self.predictions: + out["predictions"] = self.predictions + if self.experiment: + out["experiment"] = self.experiment + return out class HypothesisAgent: @@ -123,9 +168,7 @@ def propose(self, report: dict[str, Any], *, max_items: int = 8) -> list[Hypothe observations = [str(o) for o in report.get("observations") or []][:max_items] observations_text = "\n".join(f"- {o}" for o in observations) or "(none recorded)" signals = [s for s in report.get("candidate_signals") or [] if isinstance(s, dict)][:max_items] - signals_text = "\n".join( - f"- {s.get('display_name') or s.get('name')}: {s.get('rationale', '')}" for s in signals - ) or "(none recorded)" + signals_text = "\n".join(_signal_line(s) for s in signals) or "(none recorded)" if not takeaways and not observations and not signals: return [] @@ -144,9 +187,17 @@ def propose(self, report: dict[str, Any], *, max_items: int = 8) -> list[Hypothe except JudgeError as exc: logger.warning("HypothesisAgent: no hypotheses: %s", exc) return [] + known = {str(s.get("name")) for s in signals if isinstance(s.get("recipe"), dict)} return [ - Hypothesis(statement=d.hypothesis, plain_statement=d.plain_statement, - basis=d.basis, test_design=d.test) + Hypothesis( + statement=d.hypothesis, plain_statement=d.plain_statement, + basis=d.basis, test_design=d.test, + # A prediction about a signal with no recipe cannot be checked + # on held-out rows, so it is not carried forward as one. + predictions=[p.model_dump() for p in d.predictions if p.signal in known], + experiment=(None if d.experiment is None or d.experiment.is_empty() + else d.experiment.model_dump()), + ) for d in reply.output.hypotheses ] @@ -158,11 +209,29 @@ def _backend(self) -> "Any | None": return self._judge +def _signal_line(signal: dict[str, Any]) -> str: + """One prompt line per candidate signal; names the recipe when there is one, + since only a signal with a recipe can carry a held-out prediction.""" + label = signal.get("display_name") or signal.get("name") + line = f"- {label}: {signal.get('rationale', '')}" + recipe = signal.get("recipe") + if isinstance(recipe, dict) and recipe.get("expr"): + line += f" [signal name: {signal.get('name')}; recipe: {recipe.get('expr')}]" + return line + + 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") + predictions: list[HeldOutPrediction] = Field( + default_factory=list, max_length=4, + description="numeric predictions about named candidate signals on held-out rows", + ) + experiment: ExperimentPlan | None = Field( + None, description="the experiment needed when held-out rows cannot decide the claim", + ) class _Proposal(BaseModel): diff --git a/evalrx/analysis/keywords.py b/evalrx/analysis/keywords.py new file mode 100644 index 00000000..180e8a6e --- /dev/null +++ b/evalrx/analysis/keywords.py @@ -0,0 +1,107 @@ +"""Keyword contrasts for a free-text column, frozen as recipes. + +"Which words turn up more on the failing side" is a natural first look at a +text column, and an easy one to fool oneself with: there are thousands of +words, and some will separate any two groups by chance. This module gives the +look the same discipline as any other candidate signal. The words are chosen +on the exploration rows only; each becomes a recipe ``has_word(column, +"word")`` with the direction it showed there stated as its expectation; and +the recipes are then re-tested on held-out rows, in the same correction family +as everything else. + +Ranking uses the log-odds ratio with a Dirichlet prior, which does not let a +word seen three times outrank one seen three hundred: + "Fightin' Words: Lexical Feature Selection and Evaluation for Identifying + the Content of Political Conflict" + Monroe, Colaresi & Quinn (2008), Political Analysis 16(4):372-403 + https://doi.org/10.1093/pan/mpn018 +""" + +from __future__ import annotations + +import math +import re +from typing import Any + +from evalrx.analysis.explorer import CandidateSignal + +_WORD = re.compile(r"[^\W_]+(?:'[^\W_]+)?", re.UNICODE) + + +def tokenize(text: Any) -> set[str]: + """The distinct lower-cased words of *text* (three characters or longer).""" + return {w for w in _WORD.findall(str(text).lower()) if len(w) >= 3} + + +def keyword_candidates( + rows: "list[dict[str, Any]]", + text_col: str, + side: "list[float | None]", + *, + top_k: int = 5, + min_rows: int = 5, + prior: float = 0.5, + side_names: "tuple[str, str]" = ("failing", "passing"), +) -> list[CandidateSignal]: + """Up to *top_k* words over-represented on each side, as candidate signals. + + *side* is 1.0 for a row on the first side (by convention the failing one), + 0.0 for the other, None to leave the row out. A word must occur in at + least *min_rows* rows. Counts are of rows containing the word, not of + occurrences, so one long text cannot carry a word on its own. + + Each candidate's recipe expects the effect to have the sign it had here + (more failures where the word occurs, or fewer). The candidates carry no + verdict: they were picked on these very rows, so only a held-out re-test + says anything about them. + """ + docs = [ + (tokenize(r.get(text_col)), s) for r, s in zip(rows, side) + if s is not None and r.get(text_col) not in (None, "") + ] + n1 = sum(1 for _, s in docs if s == 1.0) + n0 = len(docs) - n1 + if n1 == 0 or n0 == 0: + return [] + count1: dict[str, int] = {} + count0: dict[str, int] = {} + for words, s in docs: + target = count1 if s == 1.0 else count0 + for w in words: + target[w] = target.get(w, 0) + 1 + scored: list[tuple[float, str]] = [] + for w in set(count1) | set(count0): + c1, c0 = count1.get(w, 0), count0.get(w, 0) + if c1 + c0 < min_rows: + continue + # Log odds of a row containing the word, on each side, with a prior. + l1 = math.log((c1 + prior) / (n1 - c1 + prior)) + l0 = math.log((c0 + prior) / (n0 - c0 + prior)) + variance = (1 / (c1 + prior) + 1 / (n1 - c1 + prior) + + 1 / (c0 + prior) + 1 / (n0 - c0 + prior)) + scored.append(((l1 - l0) / math.sqrt(variance), w)) + scored.sort(key=lambda t: (-t[0], t[1])) + picks = [(z, w) for z, w in scored[:top_k] if z > 0] + picks += [(z, w) for z, w in scored[::-1][:top_k] if z < 0 and (z, w) not in picks] + + out: list[CandidateSignal] = [] + for z, w in picks: + c1, c0 = count1.get(w, 0), count0.get(w, 0) + toward = side_names[0] if z > 0 else side_names[1] + name = f"kw_{re.sub(r'[^0-9a-z]+', '_', w)}" + out.append(CandidateSignal( + name=name, + display_name=f'Text mentions "{w}"', + rationale=( + f'"{w}" occurs in {c1}/{n1} {side_names[0]} rows and {c0}/{n0} ' + f"{side_names[1]} rows of the exploration half (leans {toward}; " + f"z = {z:+.1f}). Chosen on those rows, so untested." + ), + suggested_test="held-out re-test of the frozen keyword recipe", + recipe={ + "name": name, "kind": "expr", + "expr": f"has_word({text_col}, {w!r})", + "expect": {"relation": ">" if z > 0 else "<", "value": 0.0}, + }, + )) + return out diff --git a/evalrx/analysis/operationalize.py b/evalrx/analysis/operationalize.py index 7ec9e4d3..9696880d 100644 --- a/evalrx/analysis/operationalize.py +++ b/evalrx/analysis/operationalize.py @@ -31,7 +31,7 @@ import logging import operator import re -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Any, Callable logger = logging.getLogger(__name__) @@ -54,6 +54,15 @@ class RecipeError(ValueError): """A recipe is structurally invalid (bad syntax / disallowed construct).""" +#: How a recipe is compared with the outcome on held-out rows; see +#: :mod:`evalrx.analysis.holdout_designs`. An empty design is inferred: a 0/1 +#: recipe is a two-group comparison, a continuous one with ``bins`` is a +#: dose-response trend. +RECIPE_DESIGNS = ("two_group", "stratified", "did", "dose_response") +#: Relations a recipe's ``expect`` may state about its held-out effect. +EXPECT_RELATIONS = ("nonzero", ">", "<", "abs<") + + @dataclass class SignalRecipe: """A deterministic recipe for a new per-case signal (carries NO e-value). @@ -66,6 +75,20 @@ class SignalRecipe: e.g. ``"(obj_size < 40) and (attention_focus_share < 0.3)"``. code: ``kind="code"`` — sandbox source (deferred). suggested_test: catalog tool to route to, e.g. ``"signal_label_assoc"``. + where: optional DSL condition; only rows where it is true take + part (a comparison inside one subgroup). Rows where it + is false or cannot be evaluated are left out, not scored 0. + design: one of :data:`RECIPE_DESIGNS`, or empty to infer. + strata: ``design="stratified"`` — DSL expressions whose values + define the strata the comparison is made within. + modifier: ``design="did"`` — a 0/1 DSL expression; the estimate is + the recipe's effect where it is 1 minus where it is 0. + bins: ``design="dose_response"`` — fixed, increasing cut + points for a continuous ``expr``, chosen on the + exploration rows and reused unchanged. + expect: the predicted held-out effect, ``{"relation": r, + "value": v}`` with ``r`` in :data:`EXPECT_RELATIONS`. + Without it the claim is "the effect is not zero". """ name: str @@ -74,10 +97,32 @@ class SignalRecipe: expr: str = "" code: str = "" suggested_test: str = "" + where: str = "" + design: str = "" + strata: list[str] = field(default_factory=list) + modifier: str = "" + bins: list[float] = field(default_factory=list) + expect: dict[str, Any] | None = None @classmethod def from_dict(cls, data: dict[str, Any]) -> "SignalRecipe": - """Build from the ``recipe`` dict an explorer candidate may carry.""" + """Build from the ``recipe`` dict an explorer candidate may carry. + + Fields of the wrong shape are dropped rather than raised on: the dict + is written by a model, and a malformed optional field should cost that + field, not the whole recipe. :func:`recipe_problems` reports them. + """ + strata = data.get("strata") + if isinstance(strata, str): + strata = [strata] + bins: list[float] = [] + for edge in data.get("bins") or []: + try: + bins.append(float(edge)) + except (TypeError, ValueError): + bins = [] + break + expect = data.get("expect") return cls( name=str(data.get("name", "")), description=str(data.get("description", "")), @@ -85,9 +130,31 @@ def from_dict(cls, data: dict[str, Any]) -> "SignalRecipe": expr=str(data.get("expr", "")), code=str(data.get("code", "")), suggested_test=str(data.get("suggested_test", "")), + where=str(data.get("where") or ""), + design=str(data.get("design") or ""), + strata=[str(x) for x in strata] if isinstance(strata, (list, tuple)) else [], + modifier=str(data.get("modifier") or ""), + bins=bins, + expect=dict(expect) if isinstance(expect, dict) else None, ) +def parse_expectation(expect: Any) -> "tuple[str, float] | None": + """``(relation, value)`` for a recipe's ``expect``, or None if absent or malformed.""" + if not isinstance(expect, dict): + return None + relation = str(expect.get("relation") or "").strip() + if relation not in EXPECT_RELATIONS: + return None + try: + value = float(expect.get("value", 0.0) or 0.0) + except (TypeError, ValueError): + return None + if relation == "abs<" and value <= 0: + return None + return relation, (0.0 if relation == "nonzero" else value) + + # --------------------------------------------------------------------------- # Safe expression DSL (kind="expr") # --------------------------------------------------------------------------- @@ -112,9 +179,22 @@ def from_dict(cls, data: dict[str, Any]) -> "SignalRecipe": _UNARY_OPS: dict[type[ast.unaryop], Callable[[Any], Any]] = { ast.UAdd: operator.pos, ast.USub: operator.neg, ast.Not: operator.not_, } +def _contains(text: Any, piece: Any) -> bool: + """Case-insensitive substring test; the recipe form of a keyword flag.""" + return str(piece).lower() in str(text).lower() + + +def _has_word(text: Any, word: Any) -> bool: + """Case-insensitive whole-word test: ``has_word("restart", "art")`` is False.""" + return re.search( + rf"(? None: for node in ast.walk(tree): if isinstance(node, ast.Call): if not (isinstance(node.func, ast.Name) and node.func.id in _FUNCS): - raise RecipeError("only abs/min/max/float/int/len calls are allowed") + raise RecipeError( + "only abs/min/max/float/int/len/contains/has_word calls are allowed" + ) if node.keywords: raise RecipeError("keyword arguments are not allowed in a recipe expr") continue @@ -224,11 +306,89 @@ def _row_id(row: Any, id_col: str, index: int) -> str: return str(index) +def _parse_expr(expr: str, reserved: "frozenset[str] | set[str]", what: str = "expr") -> "tuple[ast.Expression, list[str]]": + """Parse and validate one DSL expression; return its tree and column names. + + Raises :class:`RecipeError` for bad syntax, a disallowed construct, or a + reference to a reserved outcome/id column. + """ + text = (expr or "").strip() + if not text: + raise RecipeError(f"recipe.{what} is empty") + try: + tree = ast.parse(text, mode="eval") + except SyntaxError as exc: + raise RecipeError(f"invalid {what} syntax: {exc}") from exc + _validate(tree) + names = _free_names(tree) + # Hard leak guard (G4): a recipe must be a function of PREDICTOR signals only, + # never the outcome/id. Referencing the label column would make the signal the + # label itself — a guaranteed double-dip self-prediction. + leaked = sorted(n for n in names if n in reserved) + if leaked: + raise RecipeError( + f"recipe {what} may not reference reserved outcome/id column(s): {leaked}" + ) + return tree, names + + +def expr_columns(expr: str) -> list[str]: + """Column names a DSL expression reads; empty when it does not parse.""" + try: + tree = ast.parse((expr or "").strip(), mode="eval") + except SyntaxError: + return [] + return _free_names(tree) + + +_SKIP = object() + + +def _eval_row(tree: ast.Expression, names: list[str], row: Any) -> Any: + """Evaluate a parsed expression on one row; ``_SKIP`` if it cannot be.""" + env: dict[str, Any] = {} + for n in names: + v = _row_get(row, n) + if v is None: + return _SKIP + env[n] = v + try: + return _ev(tree.body, env) + except (KeyError, TypeError, ValueError, ZeroDivisionError): + return _SKIP + + +def evaluate_expr( + expr: str, + records: Any, + *, + id_col: str = "case_id", + reserved: "tuple[str, ...] | list[str] | set[str] | frozenset[str]" = (), + what: str = "expr", +) -> list[Any]: + """Evaluate one DSL expression on every row, in row order. + + Returns the raw value per row (a number, a bool or a string), or None for + a row it could not be evaluated on. Unlike :func:`compile_recipe` it does + not coerce to float, so it also serves stratum labels. *reserved* adds + column names the expression may not use, on top of the built-in outcome + and id names — pass the actual outcome column when it has another name. + """ + blocked = _RESERVED_RECIPE_NAMES | {id_col} | set(reserved) + tree, names = _parse_expr(expr, blocked, what) + out: list[Any] = [] + for row in records or []: + value = _eval_row(tree, names, row) + out.append(None if value is _SKIP else value) + return out + + def compile_recipe( recipe: SignalRecipe, records: Any, *, id_col: str = "case_id", + reserved: "tuple[str, ...] | list[str] | set[str] | frozenset[str]" = (), ) -> dict[str, float]: """Compile *recipe* into ``{case_id -> value}`` over *records*. @@ -237,6 +397,11 @@ def compile_recipe( column, type mismatch, non-numeric result) SKIPS that case rather than aborting, so a recipe that only partially applies still yields a usable (smaller) signal; an empty result tells the caller the recipe could not be operationalized. + + A recipe's ``where`` condition restricts the rows: a row where it is false, + or cannot be evaluated, is skipped like a row with a missing column. + *reserved* names further columns no expression may reference (the outcome + column, when it is not one of the built-in outcome names). """ if recipe.kind == "code": raise NotImplementedError( @@ -246,41 +411,20 @@ def compile_recipe( if recipe.kind != "expr": raise RecipeError(f"unknown recipe kind: {recipe.kind!r}") - expr = (recipe.expr or "").strip() - if not expr: - raise RecipeError("recipe.expr is empty") - try: - tree = ast.parse(expr, mode="eval") - except SyntaxError as exc: - raise RecipeError(f"invalid expr syntax: {exc}") from exc - _validate(tree) - names = _free_names(tree) - - # Hard leak guard (G4): a recipe must be a function of PREDICTOR signals only, - # never the outcome/id. Referencing the label column would make the signal the - # label itself — a guaranteed double-dip self-prediction. - reserved = _RESERVED_RECIPE_NAMES | {id_col} - leaked = sorted(n for n in names if n in reserved) - if leaked: - raise RecipeError( - f"recipe expr may not reference reserved outcome/id column(s): {leaked}" - ) + blocked = _RESERVED_RECIPE_NAMES | {id_col} | set(reserved) + tree, names = _parse_expr(recipe.expr, blocked) + where = None + if (recipe.where or "").strip(): + where = _parse_expr(recipe.where, blocked, "where") out: dict[str, float] = {} for i, row in enumerate(records or []): - env: dict[str, Any] = {} - missing = False - for n in names: - v = _row_get(row, n) - if v is None: - missing = True - break - env[n] = v - if missing: - continue - try: - value = _ev(tree.body, env) - except (KeyError, TypeError, ValueError, ZeroDivisionError): + if where is not None: + keep = _eval_row(where[0], where[1], row) + if keep is _SKIP or not keep: + continue + value = _eval_row(tree, names, row) + if value is _SKIP: continue fv = _to_float(value) if fv is not None: diff --git a/evalrx/analysis/profile.py b/evalrx/analysis/profile.py index ea2867c6..ac9bfce9 100644 --- a/evalrx/analysis/profile.py +++ b/evalrx/analysis/profile.py @@ -7,9 +7,12 @@ from __future__ import annotations +import re from dataclasses import dataclass, field from typing import Any +import numpy as np + @dataclass class ColumnProfile: @@ -57,6 +60,11 @@ class DatasetProfile: time_columns: list[str] = field(default_factory=list) grain: str = "unknown" warnings: list[str] = field(default_factory=list) + # Columns that look like the unit rows were cut from, found from the data + # rather than the column name; see :func:`suggest_group_columns`. + suggested_group_columns: list[dict[str, Any]] = field(default_factory=list) + # Columns that almost fully determine the outcome; see :func:`leakage_suspects`. + leakage_suspects: list[dict[str, Any]] = field(default_factory=list) def to_dict(self) -> dict[str, Any]: return { @@ -68,6 +76,8 @@ def to_dict(self) -> dict[str, Any]: "time_columns": self.time_columns, "grain": self.grain, "warnings": self.warnings, + "suggested_group_columns": self.suggested_group_columns, + "leakage_suspects": self.leakage_suspects, } @@ -89,11 +99,229 @@ def _infer_role(name: str) -> str: return "outcome" if low in {"model", "source", "source_dir", "dataset", "split", "strategy", "group"}: return "group" + if low.endswith("_group") or low.startswith("group_"): + return "group" if low in {"time", "timestamp", "date", "datetime"} or low.endswith("_time"): return "time" + # Calendar words as whole name parts ("month_reported", "created_at", + # "report_date"), not as substrings, so "candidate" is not read as a date. + tokens = set(re.split(r"[^a-z0-9]+", low)) + if tokens & _TIME_TOKENS or low.endswith("_at"): + return "time" return "predictor" +_TIME_TOKENS = frozenset({"date", "datetime", "timestamp", "month", "year", "week", "quarter"}) +_ISO_DATE = re.compile(r"^\d{4}-\d{2}(-\d{2})?([T ]\d{2}:\d{2}.*)?$") + + +def _looks_like_dates(values: list[Any]) -> bool: + """True when nearly every non-null value is an ISO date or year-month string.""" + strings = [v for v in values if isinstance(v, str) and v.strip()] + if len(strings) < 3 or len(strings) < 0.9 * sum(v is not None for v in values): + return False + hits = sum(1 for v in strings if _ISO_DATE.match(v.strip())) + return hits >= 0.9 * len(strings) + + +def _numeric_outcome(values: list[Any]) -> "list[float | None] | None": + """The outcome as numbers, or None when it is not numeric or two-valued. + + Booleans and numbers map to themselves. A two-valued string outcome maps + to 0/1 in sorted order; the direction does not matter to the callers, + which only measure agreement and association strength. + """ + present = [v for v in values if v is not None] + if not present: + return None + if all(isinstance(v, (bool, int, float)) for v in present): + return [None if v is None else float(v) for v in values] + levels = sorted({str(v).strip().lower() for v in present}) + if len(levels) != 2: + return None + return [None if v is None else float(levels.index(str(v).strip().lower())) + for v in values] + + +def intraclass_correlation(groups: list[Any], y: list[float]) -> float | None: + """One-way ICC(1): the share of outcome variance that lies between groups. + + Zero means rows of one group agree no more than unrelated rows; a value + near one means rows of a group are near-copies. Returns None when it is + not defined (a single group, no group with two rows, or no variance). + """ + by_group: dict[Any, list[float]] = {} + for g, value in zip(groups, y): + by_group.setdefault(g, []).append(value) + k, n = len(by_group), len(y) + if k < 2 or n <= k: + return None + grand = sum(y) / n + ss_between = sum(len(v) * (sum(v) / len(v) - grand) ** 2 for v in by_group.values()) + ss_within = sum(sum((x - sum(v) / len(v)) ** 2 for x in v) for v in by_group.values()) + ms_between = ss_between / (k - 1) + ms_within = ss_within / (n - k) + n0 = (n - sum(len(v) ** 2 for v in by_group.values()) / n) / (k - 1) + denom = ms_between + (n0 - 1.0) * ms_within + if denom <= 0: + return None + return float((ms_between - ms_within) / denom) + + +def suggest_group_columns( + rows: list[dict[str, Any]], + *, + outcome_col: str | None, + exclude: "set[str] | frozenset[str]" = frozenset(), + min_groups: int = 20, + min_repeat_share: float = 0.2, + min_icc: float = 0.1, +) -> list[dict[str, Any]]: + """Columns that look like the unit several rows were cut from. + + A candidate has many distinct values, repeats (at least *min_repeat_share* + of rows share their value with another row), and rows that share a value + agree on the outcome far more than chance (ICC at least *min_icc*). Such a + column should be passed as the group column: a row-level split would put + rows of one group on both sides, and intervals that treat rows as + independent would be too narrow. + + Only string columns and integer id columns are considered; a float + column that repeats is a rounded measurement, not a sampling unit. + Returns the candidates sorted by ICC, largest first. + """ + if not rows or not outcome_col: + return [] + y_all = _numeric_outcome([r.get(outcome_col) for r in rows]) + if y_all is None: + return [] + names = sorted({str(k) for row in rows for k in row} - {outcome_col} - set(exclude)) + out: list[dict[str, Any]] = [] + for name in names: + pairs = [ + (row.get(name), y) for row, y in zip(rows, y_all) + if y is not None and row.get(name) not in (None, "") + ] + if len(pairs) < 2 * min_groups: + continue + values = [v for v, _ in pairs] + is_string = all(isinstance(v, str) for v in values) + is_int_id = ( + all(isinstance(v, int) and not isinstance(v, bool) for v in values) + and _infer_role(name) in ("id", "group") + ) + if not (is_string or is_int_id): + continue + counts: dict[Any, int] = {} + for v in values: + counts[v] = counts.get(v, 0) + 1 + if len(counts) < min_groups or len(counts) == len(values): + continue + repeat_share = sum(c for c in counts.values() if c > 1) / len(values) + if repeat_share < min_repeat_share: + continue + icc = intraclass_correlation(values, [y for _, y in pairs]) + if icc is None or icc < min_icc: + continue + out.append({ + "column": name, + "n_groups": len(counts), + "share_rows_in_repeated_groups": round(repeat_share, 4), + "icc": round(icc, 4), + }) + out.sort(key=lambda d: (-d["icc"], d["column"])) + return out + + +def _auc(scores: np.ndarray, y: np.ndarray) -> float | None: + """Rank AUC of *scores* for the binary *y* (ties get the average rank).""" + pos, neg = int(y.sum()), int((1 - y).sum()) + if pos == 0 or neg == 0: + return None + order = np.argsort(scores, kind="mergesort") + ranks = np.empty(len(scores)) + sorted_scores = scores[order] + i = 0 + while i < len(scores): + j = i + while j + 1 < len(scores) and sorted_scores[j + 1] == sorted_scores[i]: + j += 1 + ranks[order[i:j + 1]] = (i + j) / 2.0 + 1.0 + i = j + 1 + return float((ranks[y == 1].sum() - pos * (pos + 1) / 2.0) / (pos * neg)) + + +def leakage_suspects( + rows: list[dict[str, Any]], + *, + outcome_col: str | None, + exclude: "set[str] | frozenset[str]" = frozenset(), + min_rows: int = 20, + threshold: float = 0.98, +) -> list[dict[str, Any]]: + """Columns that almost fully determine the outcome. + + Such a column is usually the outcome under another name, or was written + after the outcome was known (a grader's note, a post-hoc flag). It would + "explain" everything and mean nothing, so it is reported for the user to + judge rather than silently used. + + For a two-valued outcome a column is suspect when guessing the more common + outcome within each of its values is right at least *threshold* of the + time (columns with few distinct values), or when its rank AUC is that far + from 0.5 (numeric columns). For a numeric outcome it is suspect when the + absolute correlation reaches *threshold*. Columns whose values are nearly + unique per row are skipped: an id determines everything and tells nothing. + """ + if not rows or not outcome_col: + return [] + y_all = _numeric_outcome([r.get(outcome_col) for r in rows]) + if y_all is None: + return [] + binary = {v for v in y_all if v is not None} <= {0.0, 1.0} + names = sorted({str(k) for row in rows for k in row} - {outcome_col} - set(exclude)) + out: list[dict[str, Any]] = [] + for name in names: + pairs = [ + (row.get(name), y) for row, y in zip(rows, y_all) + if y is not None and row.get(name) is not None + ] + if len(pairs) < min_rows: + continue + values = [v for v, _ in pairs] + y = np.asarray([t for _, t in pairs], dtype=float) + if float(y.std()) == 0.0: + continue + numeric = all(isinstance(v, (bool, int, float)) for v in values) + try: + n_distinct = len(set(values)) + except TypeError: # unhashable values (lists, dicts) are not predictors here + continue + base = max(float(y.mean()), 1.0 - float(y.mean())) if binary else None + if binary and n_distinct <= max(2, min(20, len(values) // 5)): + by_value: dict[Any, list[float]] = {} + for v, t in pairs: + by_value.setdefault(v, []).append(t) + right = sum(max(sum(ts), len(ts) - sum(ts)) for ts in by_value.values()) + accuracy = right / len(pairs) + if accuracy >= threshold and base is not None and base <= 0.95: + out.append({"column": name, "measure": "accuracy_from_value", + "value": round(accuracy, 4), "baseline": round(base, 4)}) + continue + if not numeric or n_distinct < 2: + continue + x = np.asarray([float(v) for v in values if isinstance(v, (bool, int, float))]) + if binary: + auc = _auc(x, y) + if auc is not None and max(auc, 1.0 - auc) >= threshold + (1.0 - threshold) / 2: + out.append({"column": name, "measure": "auc", "value": round(auc, 4)}) + elif float(x.std()) > 0.0: + r = float(np.corrcoef(x, y)[0, 1]) + if abs(r) >= threshold: + out.append({"column": name, "measure": "correlation", "value": round(r, 4)}) + return out + + def _infer_dtype(values: list[Any]) -> str: non_null = [v for v in values if v is not None] if not non_null: @@ -113,9 +341,20 @@ def _infer_dtype(values: list[Any]) -> str: return "mixed" -def profile_records(records: Any, *, outcome_col: str | None = None) -> DatasetProfile: +def profile_records( + records: Any, + *, + outcome_col: str | None = None, + group_cols: "list[str] | tuple[str, ...]" = (), + time_cols: "list[str] | tuple[str, ...]" = (), +) -> DatasetProfile: """Profile a list/DataFrame-like object of row records. + ``group_cols`` and ``time_cols`` name columns whose role the caller knows; + they override the name heuristic, which only recognises a short list of + English names. A named column that is absent from the data is reported in + ``warnings`` instead of being ignored silently. + ``outcome_col``, when given and present, overrides name-heuristic role inference: that column is forced to role ``"outcome"`` (and any other column the heuristic would have called ``"outcome"`` is demoted back to @@ -148,6 +387,15 @@ def profile_records(records: Any, *, outcome_col: str | None = None) -> DatasetP role = "predictor" else: role = _infer_role(name) + if role == "predictor" and _looks_like_dates(vals): + role = "time" + # An explicit role wins over anything inferred, except that the + # outcome column stays the outcome. + if role != "outcome": + if name in group_cols: + role = "group" + elif name in time_cols: + role = "time" unique_values = {str(v) for v in non_null_vals} numeric_vals = [ float(v) for v in non_null_vals @@ -176,6 +424,36 @@ def profile_records(records: Any, *, outcome_col: str | None = None) -> DatasetP outcome_columns = [c.name for c in columns.values() if c.role == "outcome"] group_columns = [c.name for c in columns.values() if c.role == "group"] time_columns = [c.name for c in columns.values() if c.role == "time"] + for kind, wanted in (("group", group_cols), ("time", time_cols)): + for name in wanted: + if name not in columns: + warnings.append(f"{kind} column {name!r} was named but is not in the data") + + outcome_name = outcome_columns[0] if outcome_columns else None + # A column the caller already named as the group needs no suggestion. One + # that merely has a group-like name still does: the name alone does not + # make the split or the intervals use it. + suggested = suggest_group_columns( + rows, outcome_col=outcome_name, exclude=set(group_cols) + ) + for s in suggested: + warnings.append( + f"column {s['column']!r} looks like the unit rows were cut from " + f"({s['n_groups']} groups, rows of one group share " + f"{s['icc']:.0%} of the outcome variance); name it as the group column " + "so the split and the intervals respect it" + ) + suspects = leakage_suspects( + rows, outcome_col=outcome_name, exclude=set(id_columns) + ) + for s in suspects: + if s["column"] in columns: + columns[s["column"]].leakage_suspect = True + warnings.append( + f"column {s['column']!r} almost fully determines the outcome " + f"({s['measure']}={s['value']}); check that it is not the outcome " + "itself or something recorded after it" + ) grain = "case" if id_columns else "row" if id_columns and rows: id_col = id_columns[0] @@ -192,6 +470,8 @@ def profile_records(records: Any, *, outcome_col: str | None = None) -> DatasetP time_columns=time_columns, grain=grain, warnings=warnings, + suggested_group_columns=suggested, + leakage_suspects=suspects, ) diff --git a/evalrx/analysis/prompts/explorer.py b/evalrx/analysis/prompts/explorer.py index c0389d5b..c01f52d2 100644 --- a/evalrx/analysis/prompts/explorer.py +++ b/evalrx/analysis/prompts/explorer.py @@ -293,9 +293,38 @@ label/outcome column (a recipe is a PREDICTOR, never the answer). Example: "recipe": {{"name": "small_and_peripheral", "kind": "expr", "expr": "(obj_size < 40) and (focus_share < 0.3)"}} Emit a recipe rather than prose whenever the candidate is computable from the columns. + The expr may also call has_word(text_column, "word") for a keyword flag + (whole word, any case) or contains(text_column, "some phrase") for a substring. + A recipe MAY carry these optional fields, which say HOW it is compared with + the outcome on held-out rows. Fix every number in them now; none is re-fitted: + "where": "" only rows where it is true take part (a comparison + inside one subgroup). Use this instead of an expr + that returns nothing for the other rows. + "design": "stratified", "strata": ["", ...] + compare flagged with unflagged rows WITHIN strata + and average, for a gap that may only reflect a + different mix (same generator, same score band). + A stratum expr may be a column name or a banding + such as "int(score * 5)". + "design": "did", "modifier": "<0/1 expr>" + how much LARGER the recipe's effect is where the + modifier holds than where it does not (an + interaction). + "design": "dose_response", "bins": [] + for a CONTINUOUS expr: fixed cut points; tested as + the change in the outcome per step up the bins. + A continuous expr without bins cannot be re-tested. + "expect": {{"relation": ">" | "<" | "abs<" | "nonzero", "value": }} + what you predict the effect to be. Use "abs<" with + a bound for a control you expect to come out small, + so that a small difference counts as the prediction + holding rather than as a failed finding. - ALTERNATIVELY, you MAY attach host-adjudicable "sufficient" statistics computed from the rows, as ONE of these shapes: {{"kind": "two_group", "a": [0/1, ...], "b": [0/1, ...]}} # is_fail indicators among signal-ABSENT (a) vs signal-PRESENT (b) cases + # when the profile names a group column, ALSO give the group of every entry, + # in the same order: "clusters_a": [...], "clusters_b": [...] — rows of one + # group are then not counted as independent evidence {{"kind": "paired_binary", "b": , "c": }} # discordant counts of a paired intervention (b = flips the good way, c = the bad way) Do NOT emit "reject"/"e_value"/"p_value" anywhere — this tool never adjudicates a verdict itself; a self-declared verdict is ignored. Omit both for diff --git a/evalrx/analysis/prompts/holdout.py b/evalrx/analysis/prompts/holdout.py index 55356630..8cf06b9a 100644 --- a/evalrx/analysis/prompts/holdout.py +++ b/evalrx/analysis/prompts/holdout.py @@ -9,7 +9,10 @@ HELD-OUT EVIDENCE (validate split, n={n_rows}; recipe thresholds frozen from the exploration phase; REJECT H0 means the signal separated the outcome groups on -held-out data): +held-out data after correction for every claim tested; each line also states +the claim that was tested and whether it holds, is contradicted or stays +inconclusive — a claim of the form "|effect| < bound" is a control that was +predicted to come out small): {evidence} Grade the hypothesis STRICTLY against this held-out evidence: @@ -21,5 +24,9 @@ all (e.g. causal direction); it needs an intervention/surgery experiment. Give the verdict, 2-3 sentences of reasoning citing the held-out numbers, and -whether the claim needs an intervention (surgery) experiment. +whether the claim needs an intervention (surgery) experiment. Where the host +already checked a numeric prediction, take its result as given and judge only +what the numbers leave open. If an intervention is needed, also give +"experiment" with four short fields: data_needed, operation, expected_result, +and falsified_by (the result that would show the hypothesis is wrong). """ diff --git a/evalrx/analysis/prompts/hypothesis_agent.py b/evalrx/analysis/prompts/hypothesis_agent.py index b8dcb190..387f5fa7 100644 --- a/evalrx/analysis/prompts/hypothesis_agent.py +++ b/evalrx/analysis/prompts/hypothesis_agent.py @@ -60,6 +60,19 @@ 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. +- predictions (optional, up to 4): the part of the claim that rows which were + held out can decide. Each names one candidate signal above that has a + recipe, by its signal name, and states what its effect (outcome among rows + the recipe flags, minus the outcome among rows it does not) should be: + {{"signal": "", "relation": ">" | "<" | "abs<" | "nonzero", + "value": }}. Use "abs<" for a comparison your hypothesis says + should come out small, such as a control. Leave the list empty if no + listed signal bears on the claim; do not invent signal names. +- experiment (optional): only when the claim is about a cause that re-counting + existing rows cannot settle. Give four short fields: data_needed (what to + collect or re-run), operation (what is changed), expected_result (what is + seen if you are right) and falsified_by (what result would show you are + wrong). Omit it when the predictions above are enough. 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 diff --git a/evalrx/analysis/stats_tool_generator.py b/evalrx/analysis/stats_tool_generator.py index d5337968..5655cbaa 100755 --- a/evalrx/analysis/stats_tool_generator.py +++ b/evalrx/analysis/stats_tool_generator.py @@ -44,6 +44,7 @@ from evalrx.analysis.stats_tools import StatsInput, StatsToolResult, describe_data from evalrx.stats import compare from evalrx.stats.evalue import evalue_bernoulli +from evalrx.stats.exact import two_group_exact_p if TYPE_CHECKING: from evalrx.agent_runtime.cli_types import CliAgentConfig @@ -305,15 +306,16 @@ def _extract_code(raw: str) -> str: return cleaned.strip() -def _reconstruct_decision( - suff: Any, alpha: float -) -> "tuple[bool, float | None, float | None, tuple | None] | None": - """Recompute ``(reject, e_value, effect, ci)`` HOST-SIDE from a generated - tool's sufficient statistics, using the validated core — so a generated - tool can choose WHAT statistic to compute but never WHETHER to reject. +def reconstruct_evidence(suff: Any, alpha: float) -> "dict[str, Any] | None": + """Recompute a verdict HOST-SIDE from sufficient statistics. - Returns ``None`` when *suff* is missing or not an adjudicable shape; the - caller then treats the tool as descriptive (``reject=False``). + Returns ``reject``, ``e_value``, ``p_value``, ``effect``, ``ci`` and + ``n_clusters``, or ``None`` when *suff* is missing or not an adjudicable + shape. ``paired_binary`` yields an e-value; ``two_group`` yields a + bootstrap interval and p-value. A ``two_group`` shape may carry + ``clusters_a`` / ``clusters_b`` — one group id per entry of ``a`` / ``b`` — + and the bootstrap then resamples whole groups, so rows cut from one item + are not counted as independent evidence. """ if not isinstance(suff, dict): return None @@ -325,21 +327,55 @@ def _reconstruct_decision( return None n = b + c e_value = evalue_bernoulli(b, n, p0=0.5) if n > 0 else 1.0 - reject = e_value >= 1.0 / alpha - effect = (b - c) / n if n > 0 else 0.0 - return reject, float(e_value), effect, None + return { + "reject": e_value >= 1.0 / alpha, "e_value": float(e_value), + "p_value": None, "effect": (b - c) / n if n > 0 else 0.0, + "ci": None, "n_clusters": None, + } if kind == "two_group": a = [int(x) for x in suff["a"]] grp_b = [int(x) for x in suff["b"]] if not a or not grp_b: return None - sr = compare(a, grp_b, paired=False, alpha=alpha) - return bool(sr.reject), sr.e_value, sr.effect, tuple(sr.ci) + cluster_by = None + if suff.get("clusters_a") is not None or suff.get("clusters_b") is not None: + ca, cb = list(suff["clusters_a"]), list(suff["clusters_b"]) + if len(ca) != len(a) or len(cb) != len(grp_b): + # Misaligned group ids cannot be trusted to mean anything. + return None + cluster_by = (ca, cb) + sr = compare(a, grp_b, paired=False, alpha=alpha, cluster_by=cluster_by) + p_value = sr.details.get("p_value") + if cluster_by is None and set(a) | set(grp_b) <= {0, 1}: + # Independent rows, binary outcome: the exact test, which does + # not degenerate on small cleanly separated samples. + p_value = two_group_exact_p(sum(a), len(a), sum(grp_b), len(grp_b)) + return { + "reject": bool(sr.reject), "e_value": sr.e_value, + "p_value": p_value, "effect": sr.effect, + "ci": tuple(sr.ci), "n_clusters": sr.details.get("n_clusters"), + } except (KeyError, TypeError, ValueError): return None return None +def _reconstruct_decision( + suff: Any, alpha: float +) -> "tuple[bool, float | None, float | None, tuple | None] | None": + """Recompute ``(reject, e_value, effect, ci)`` HOST-SIDE from a generated + tool's sufficient statistics, using the validated core — so a generated + tool can choose WHAT statistic to compute but never WHETHER to reject. + + Returns ``None`` when *suff* is missing or not an adjudicable shape; the + caller then treats the tool as descriptive (``reject=False``). + """ + evidence = reconstruct_evidence(suff, alpha) + if evidence is None: + return None + return evidence["reject"], evidence["e_value"], evidence["effect"], evidence["ci"] + + def _parse_result(stdout: str, name: str, alpha: float = 0.05) -> StatsToolResult: """Parse the last ``STATS_RESULT_JSON=`` line of *stdout*. diff --git a/evalrx/cli.py b/evalrx/cli.py index ef746afa..d9f40d48 100755 --- a/evalrx/cli.py +++ b/evalrx/cli.py @@ -80,6 +80,42 @@ def _add_explore(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> No "auto-detect by name heuristics, or fall back to unsupervised EDA " "when the data has no recognizable outcome.", ) + explore.add_argument( + "--group-col", + default=None, + help="Column naming the unit rows were cut from (several rows per source " + "item, one prompt answered by several models). Each group is kept on " + "one side of the held-out split, and held-out intervals resample " + "whole groups. Without it rows are treated as independent.", + ) + explore.add_argument( + "--time-col", + default=None, + help="Name of a time column, when its name does not say so.", + ) + explore.add_argument( + "--text-col", + default=None, + help="Free-text column to mine for keywords: words over-represented on " + "either side of the outcome in the exploration half are frozen as " + "recipes and re-tested on the held-out half. Needs --holdout-frac.", + ) + explore.add_argument( + "--data-card", default=None, metavar="FILE", + help="JSON or YAML file answering four questions about the table: unit " + "(what a row is), extraction (how it was cut from the raw object), " + "threshold (how the outcome was set), aggregation (how results are " + "combined in use). Answers are printed in the report's caveats; " + "unanswered questions are listed there too.", + ) + explore.add_argument("--row-unit", default=None, + help="Data card: what one row is.") + explore.add_argument("--row-extraction", default=None, + help="Data card: how a row was cut from the raw object.") + explore.add_argument("--outcome-threshold", default=None, + help="Data card: how the outcome or its threshold was set.") + explore.add_argument("--deployment-aggregation", default=None, + help="Data card: how results are combined when the system is used.") explore.add_argument( "--out", default="evalrx_explore_output", @@ -95,7 +131,12 @@ def _add_explore(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> No ) explore.add_argument("--model", "--coder-model", dest="coder_model", default="") explore.add_argument("--coder-binary", default="") - explore.add_argument("--max-rows", type=int, default=2000) + explore.add_argument( + "--max-rows", type=int, default=2000, + help="Most rows the host loads (for a held-out split, or for a backend " + "without file access). Rows beyond it are dropped, with a warning " + "that says how many (default 2000).", + ) explore.add_argument("--max-files", type=int, default=200) explore.add_argument("--include-tool-calls", action="store_true") explore.add_argument("--timeout-sec", type=int, default=120) @@ -135,9 +176,22 @@ def _add_explore(sub: argparse._SubParsersAction[argparse.ArgumentParser]) -> No explore.add_argument("--holdout-seed", type=int, default=0, help="Seed for the held-out split (default 0).") explore.add_argument( - "--judge-model", default="claude-opus-4-8", - help="LLM judge grading each hypothesis against the held-out table " - "(only used with --holdout-confirm).", + "--judge-backend", default="same", + choices=["same", "claude", "antigravity", "codex", "claude_code", "opencode", + "gemini_cli", "kimi_cli"], + help="Backend of the judge grading each hypothesis against the held-out " + "table (only with --holdout-confirm). 'same' (default) follows " + "--backend. A judge that is also the proposer is flagged in the report.", + ) + explore.add_argument( + "--judge-model", default="", + help="Model of that judge. Default: claude-opus-4-8 on a Claude backend, " + "otherwise the model given with --model, otherwise the backend's own default.", + ) + explore.add_argument( + "--keep-sandbox", action="store_true", + help="Keep the temporary working directory (it holds a copy of the data) " + "instead of deleting it once the artifacts are in --out.", ) explore.add_argument("--progress-path", default="", help="Append durable workbench progress events to this JSONL path.") @@ -168,6 +222,19 @@ def _explore(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int: # "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 + data_card: dict[str, str] = {} + if args.data_card: + from evalrx.analysis.explore_run import load_data_card + + try: + data_card = load_data_card(args.data_card) + except (OSError, ValueError) as exc: + parser.error(f"--data-card: {exc}") + for key, value in (("unit", args.row_unit), ("extraction", args.row_extraction), + ("threshold", args.outcome_threshold), + ("aggregation", args.deployment_aggregation)): + if value: + data_card[key] = value code = run_explore( args.path, question=args.question, @@ -191,6 +258,12 @@ def _explore(args: argparse.Namespace, parser: argparse.ArgumentParser) -> int: holdout_confirm=args.holdout_confirm, judge_model=args.judge_model, progress_sink=progress_sink, + group_col=args.group_col, + time_col=args.time_col, + text_col=args.text_col, + data_card=data_card or None, + judge_backend=args.judge_backend, + keep_sandbox=args.keep_sandbox, ) if event_sink is not None: event_sink.emit( diff --git a/evalrx/stats/__init__.py b/evalrx/stats/__init__.py index e14bb28f..6c6ea880 100755 --- a/evalrx/stats/__init__.py +++ b/evalrx/stats/__init__.py @@ -12,9 +12,15 @@ compare_multiple, compare_paired_rates, ) -from evalrx.stats.bootstrap import clustered_bootstrap_diff +from evalrx.stats.bootstrap import ( + bootstrap_p_value, + clustered_bootstrap_diff, + mean_difference_statistic, + weighted_bootstrap, +) from evalrx.stats.ebh import ebh from evalrx.stats.evalue import e_value_test, evalue_bernoulli, evalue_bounded_mean +from evalrx.stats.exact import two_group_exact_p 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 @@ -28,10 +34,14 @@ "MultiCompareResult", "mcnemar", "clustered_bootstrap_diff", + "weighted_bootstrap", + "bootstrap_p_value", + "mean_difference_statistic", "evalue_bernoulli", "e_value_test", "evalue_bounded_mean", "ebh", + "two_group_exact_p", "friedman_test", "nemenyi_cd", "nemenyi_pairs", diff --git a/evalrx/stats/api.py b/evalrx/stats/api.py index d5164823..9dc7fb16 100755 --- a/evalrx/stats/api.py +++ b/evalrx/stats/api.py @@ -58,7 +58,15 @@ def compare( n_boot: int = 2000, seed: int = 0, ) -> StatResult: - """Compare two per-example success vectors. Returns a :class:`StatResult`.""" + """Compare two per-example success vectors. Returns a :class:`StatResult`. + + ``cluster_by`` is one cluster id per example when ``paired`` (the examples + are aligned), and a pair ``(clusters_a, clusters_b)`` when not: rows that + share a cluster are then resampled together, which widens the interval when + rows of one cluster resemble each other. The unpaired result carries the + bootstrap p-value in ``details["p_value"]`` and the number of clusters in + ``details["n_clusters"]`` when clusters were used. + """ # The bootstrap CI level must track alpha: on the unpaired path `reject` is # "CI excludes 0", so a smaller alpha (e.g. a Bonferroni alpha/m) has to # WIDEN the CI. For the default alpha=0.05 this is 1-0.05=0.95 — identical to @@ -84,8 +92,12 @@ def compare( "n_discordant": mc["n_discordant"]} else: reject = not ci_includes_zero # unpaired: CI excludes 0 - method = "clustered bootstrap (unpaired)" - details = {} + clustered = "n_clusters" in boot + method = ("clustered bootstrap (unpaired)" if clustered + else "two-sample bootstrap (unpaired)") + details = {"p_value": boot.get("p_value")} + if clustered: + details["n_clusters"] = boot["n_clusters"] # underpowered: not significant AND the CI is too wide to rule out a min_effect-sized effect width = ci[1] - ci[0] diff --git a/evalrx/stats/bootstrap.py b/evalrx/stats/bootstrap.py index 870d3ed2..0da262dd 100755 --- a/evalrx/stats/bootstrap.py +++ b/evalrx/stats/bootstrap.py @@ -18,10 +18,162 @@ from __future__ import annotations from collections import defaultdict -from typing import Optional, Sequence +from typing import Any, Callable, Iterator, Optional, Sequence import numpy as np +#: Relations a bootstrap p-value can be asked about; see :func:`bootstrap_p_value`. +RELATIONS = ("nonzero", ">", "<", "abs<") + + +def _cluster_codes(clusters: Optional[Sequence], n: int) -> "tuple[np.ndarray, int]": + """Integer code per row and the number of clusters. + + ``None`` makes every row its own cluster. A missing cluster value (``None`` + or an empty string) is also its own cluster: an unknown group must not be + merged with other unknown groups. + """ + if clusters is None: + return np.arange(n), n + values = list(clusters) + if len(values) != n: + raise ValueError(f"clusters has {len(values)} entries for {n} rows") + index: dict = {} + codes = np.empty(n, dtype=np.int64) + for i, value in enumerate(values): + key: Any = ("__row__", i) if value is None or value == "" else ("v", value) + codes[i] = index.setdefault(key, len(index)) + return codes, len(index) + + +def _weight_draws( + codes: np.ndarray, n_clusters: int, n_boot: int, seed: int, chunk: int = 64 +) -> "Iterator[np.ndarray]": + """Yield one row-weight vector per replicate. + + Each replicate draws ``n_clusters`` clusters with replacement; a row's + weight is how often its cluster was drawn, so rows of one cluster always + enter or leave a replicate together. + """ + rng = np.random.default_rng(seed) + probs = np.full(n_clusters, 1.0 / n_clusters) + done = 0 + while done < n_boot: + size = min(chunk, n_boot - done) + counts = rng.multinomial(n_clusters, probs, size=size) + for row in counts: + yield row[codes].astype(float) + done += size + + +def weighted_bootstrap( + statistic: "Callable[[np.ndarray], float]", + n: int, + *, + clusters: Optional[Sequence] = None, + n_boot: int = 2000, + ci: float = 0.95, + seed: int = 0, +) -> dict: + """Cluster bootstrap of any statistic written as a function of row weights. + + ``statistic(w)`` receives one non-negative weight per row and returns a + float, or NaN when the statistic is undefined for that replicate (for + example one arm received no weight). The point estimate is + ``statistic(ones)``. Writing the statistic over weights lets one routine + serve a difference of means, a stratified difference, a difference in + differences and a trend slope, with the same resampling of whole clusters. + + Returns ``effect``, ``ci_low``, ``ci_high``, ``draws`` (finite replicates + only), ``n_clusters`` and ``n_undefined``. + """ + if n <= 0: + return {"effect": 0.0, "ci_low": 0.0, "ci_high": 0.0, "ci": ci, "n": 0, + "n_clusters": 0, "n_undefined": 0, "draws": np.empty(0)} + codes, n_clusters = _cluster_codes(clusters, n) + point = float(statistic(np.ones(n))) + values = np.fromiter( + (statistic(w) for w in _weight_draws(codes, n_clusters, n_boot, seed)), + dtype=float, count=n_boot, + ) + draws = values[np.isfinite(values)] + if draws.size == 0 or not np.isfinite(point): + return {"effect": point, "ci_low": float("nan"), "ci_high": float("nan"), + "ci": ci, "n": n, "n_clusters": n_clusters, + "n_undefined": int(n_boot - draws.size), "draws": draws} + lo = float(np.quantile(draws, (1 - ci) / 2)) + hi = float(np.quantile(draws, 1 - (1 - ci) / 2)) + return {"effect": point, "ci_low": lo, "ci_high": hi, "ci": ci, "n": n, + "n_clusters": n_clusters, "n_undefined": int(n_boot - draws.size), + "draws": draws} + + +def bootstrap_p_value(draws: "Sequence[float] | np.ndarray", relation: str = "nonzero", + value: float = 0.0) -> float: + """Percentile-bootstrap p-value for the claim ``effect value``. + + The p-value is the share of replicates on the wrong side of the claim, + with one added to numerator and denominator so it is never zero: + + - ``"nonzero"``: two-sided, against an effect of exactly zero. + - ``">"`` / ``"<"``: one-sided, against ``effect <= value`` / ``>= value``. + - ``"abs<"``: against ``|effect| >= value`` (the effect is at most that + large in either direction). + + This inverts the percentile interval, so it is approximate in the same way + the interval is, and it cannot go below ``1 / (len(draws) + 1)``. + """ + d = np.asarray(draws, dtype=float) + b = d.size + if b == 0: + return 1.0 + if relation == "nonzero": + below = (1 + int(np.sum(d <= 0.0))) / (b + 1) + above = (1 + int(np.sum(d >= 0.0))) / (b + 1) + return float(min(1.0, 2.0 * min(below, above))) + if relation == ">": + return float((1 + int(np.sum(d <= value))) / (b + 1)) + if relation == "<": + return float((1 + int(np.sum(d >= value))) / (b + 1)) + if relation == "abs<": + return float((1 + int(np.sum(np.abs(d) >= abs(value)))) / (b + 1)) + raise ValueError(f"unknown relation {relation!r}; expected one of {RELATIONS}") + + +def mean_difference_statistic( + y: np.ndarray, arm: np.ndarray +) -> "Callable[[np.ndarray], float]": + """Weighted ``mean(y | arm == 1) - mean(y | arm == 0)`` as a weight function.""" + y = np.asarray(y, dtype=float) + in_b = np.asarray(arm, dtype=float) + in_a = 1.0 - in_b + y_b, y_a = y * in_b, y * in_a + + def statistic(w: np.ndarray) -> float: + w_b, w_a = float(w @ in_b), float(w @ in_a) + if w_b <= 0.0 or w_a <= 0.0: + return float("nan") + return float(w @ y_b) / w_b - float(w @ y_a) / w_a + + return statistic + + +def _two_group_clusters(clusters: Any, na: int, nb: int) -> "list | None": + """``(clusters_a, clusters_b)`` flattened to one list, or None if not that shape.""" + if clusters is None or isinstance(clusters, (str, bytes)): + return None + try: + if len(clusters) != 2: + return None + first, second = clusters + if isinstance(first, (str, bytes)) or isinstance(second, (str, bytes)): + return None + if len(first) != na or len(second) != nb: + return None + except TypeError: + return None + return list(first) + list(second) + def clustered_bootstrap_diff( success_a: Sequence[float], @@ -37,10 +189,16 @@ def clustered_bootstrap_diff( paired=True: A and B are per-example aligned vectors of equal length; resamples CLUSTERS of example indices (default: each example its own cluster) so the pairing is preserved. - paired=False: A and B are two independent groups (lengths may differ); - each group is resampled independently (two-sample bootstrap). - ``clusters`` is ignored — a single cluster sequence cannot - align to two groups of different sizes. + paired=False: A and B are two groups (lengths may differ). Without + clusters each group is resampled independently (two-sample + bootstrap). Pass ``clusters=(clusters_a, clusters_b)``, one + cluster id per row of each group, to resample whole clusters + instead; a cluster may have rows in both groups, and they + then move together. A single flat sequence cannot be aligned + to two groups and is ignored, as before. + + Unpaired results also carry ``p_value``, the two-sided percentile-bootstrap + p-value against a difference of zero (see :func:`bootstrap_p_value`). """ a = np.asarray(success_a, dtype=float) b = np.asarray(success_b, dtype=float) @@ -49,6 +207,16 @@ def clustered_bootstrap_diff( na, nb = len(a), len(b) if na == 0 or nb == 0: return {"effect": 0.0, "ci_low": 0.0, "ci_high": 0.0, "ci": ci, "n": 0} + joint = _two_group_clusters(clusters, na, nb) + if joint is not None: + arm = np.concatenate([np.zeros(na), np.ones(nb)]) + out = weighted_bootstrap( + mean_difference_statistic(np.concatenate([a, b]), arm), na + nb, + clusters=joint, n_boot=n_boot, ci=ci, seed=seed, + ) + draws = out.pop("draws") + out.update(n_a=na, n_b=nb, p_value=bootstrap_p_value(draws)) + return out rng = np.random.default_rng(seed) point = float(b.mean() - a.mean()) ia = rng.integers(0, na, size=(n_boot, na)) @@ -57,7 +225,8 @@ def clustered_bootstrap_diff( lo = float(np.quantile(diffs, (1 - ci) / 2)) hi = float(np.quantile(diffs, 1 - (1 - ci) / 2)) return {"effect": point, "ci_low": lo, "ci_high": hi, "ci": ci, - "n": na + nb, "n_a": na, "n_b": nb} + "n": na + nb, "n_a": na, "n_b": nb, + "p_value": bootstrap_p_value(diffs)} n = len(a) if n != len(b): diff --git a/evalrx/stats/exact.py b/evalrx/stats/exact.py new file mode 100644 index 00000000..28af2505 --- /dev/null +++ b/evalrx/stats/exact.py @@ -0,0 +1,53 @@ +"""Exact test for a difference of two proportions (rows independent). + +The percentile bootstrap degenerates on small, cleanly separated samples: four +failures against four passes resample to the same difference every time, so +its p-value is as small as the number of replicates allows however little data +there is. Conditioning on the margins gives the exact answer instead (2/70 for +that table), so a two-group comparison of a binary outcome with independent +rows uses this test for its p-value and keeps the bootstrap for its interval. + +Fisher's exact test: + "On the Interpretation of χ² from Contingency Tables, and the Calculation of P" + Fisher (1922), J. Royal Statistical Society 85(1):87-94 + https://doi.org/10.2307/2340521 +""" + +from __future__ import annotations + +import math + + +def _log_comb(n: int, k: int) -> float: + return math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1) + + +def two_group_exact_p( + fail_a: int, n_a: int, fail_b: int, n_b: int, alternative: str = "two-sided" +) -> float: + """Exact p-value for ``rate_b - rate_a`` given both group sizes and the total. + + ``alternative`` is ``"two-sided"`` (a difference at least as large in + either direction), ``"greater"`` (``rate_b > rate_a``) or ``"less"``. + Group ``a`` has ``fail_a`` failures in ``n_a`` rows; likewise ``b``. + """ + if alternative not in ("two-sided", "greater", "less"): + raise ValueError(f"unknown alternative {alternative!r}") + if n_a <= 0 or n_b <= 0: + return 1.0 + n, total = n_a + n_b, fail_a + fail_b + observed = fail_b / n_b - fail_a / n_a + log_denom = _log_comb(n, n_b) + eps = 1e-12 + prob = 0.0 + for k in range(max(0, n_b - (n - total)), min(n_b, total) + 1): + diff = k / n_b - (total - k) / n_a + if alternative == "two-sided": + extreme = abs(diff) + eps >= abs(observed) + elif alternative == "greater": + extreme = diff + eps >= observed + else: + extreme = diff - eps <= observed + if extreme: + prob += math.exp(_log_comb(total, k) + _log_comb(n - total, n_b - k) - log_denom) + return min(1.0, max(0.0, prob)) diff --git a/mkdocs.yml b/mkdocs.yml index bb0a7e4e..aeb85c4a 100755 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -38,12 +38,14 @@ nav: - Exploratory Analysis (M2/M3): m2_analysis.md - Verification & Intervention (M4/M5): intervention.md - Weight Edits & Probe Tools: wsp_and_probe_tools.md + - Held-out Confirmation: holdout_confirmation.md - Stage Input/Output Reference: stage_io.md - Analyzer Zoo: analyzers.md - Architecture: architecture.md - Extending: extending.md - Roadmap: roadmap.md - Validation: + - Held-out designs calibration (2026-11-21): validation/holdout_calibration_20261121.md - Published weight edit on Qwen3.5-0.8B (2026-11-15): validation/astra_p50c_20261115.md - Gemini agentic run (2026-10-13): validation/gemini_agentic_20261013.md - Historical Gemma repairs (2026-08-30): validation/gemma_repair_20260830.md diff --git a/tests/test_analysis/test_adjudicate.py b/tests/test_analysis/test_adjudicate.py index 7c36aa19..132c80c2 100644 --- a/tests/test_analysis/test_adjudicate.py +++ b/tests/test_analysis/test_adjudicate.py @@ -7,6 +7,8 @@ from __future__ import annotations +import pytest + from evalrx.agent_runtime.sandbox import ExperimentSandbox from evalrx.analysis import ( CandidateSignal, @@ -45,17 +47,73 @@ def test_balanced_paired_binary_does_not_reject(): assert c.reject is False -def test_two_group_uses_ci_reject_and_is_not_in_ebh_family(): +def test_two_group_gets_a_p_value_and_its_own_bh_family(): # Signal-absent cases all pass (0), signal-present cases all fail (1). c = _sig("strong_signal", {"kind": "two_group", "a": [0] * 8, "b": [1] * 8}) meta = adjudicate_signals([c]) assert c.host_adjudicated assert c.e_value is None # unpaired path produces no e-value - assert c.fdr_corrected is False # therefore not part of the e-BH family - assert c.reject is True # but CI excludes 0 -> host rejects + # Exact test: one table in C(16, 8) is this extreme, on each side. + assert c.p_value == pytest.approx(2 / 12870) + assert c.reject is True and c.fdr_corrected is True assert c.effect is not None and c.ci is not None assert meta["n_in_family"] == 0 # no e-value-bearing candidate + assert meta["n_in_p_family"] == 1 + assert meta["method"] == "BH" # the correction that was actually applied + + +def test_two_group_candidates_pay_for_multiplicity(): + # 9/20 against 2/20 failures: p is about 0.03 on its own, so it rejects + # alone but not among twenty candidates of which it is the best. + borderline = {"kind": "two_group", "a": [1] * 2 + [0] * 18, "b": [1] * 9 + [0] * 11} + alone = _sig("alone", dict(borderline)) + assert adjudicate_signals([alone])["rejected"] == ["alone"] + + noise = {"kind": "two_group", "a": [1, 0] * 10, "b": [1, 0] * 10} + crowd = [_sig("candidate", dict(borderline))] + [ + _sig(f"noise{i}", dict(noise)) for i in range(19) + ] + meta = adjudicate_signals(crowd) + assert meta["n_in_p_family"] == 20 + assert meta["rejected"] == [] + assert meta["raw_reject"] == ["candidate"] # its own interval excluded zero + assert crowd[0].reject is False and crowd[0].fdr_corrected is False + + +def test_two_group_with_group_ids_resamples_whole_groups(): + # Forty rows per side from five source items per side, and rows of an + # item agree: the evidence is ten items, not eighty rows. + a = [0] * 32 + [1] * 8 + b = [1] * 24 + [0] * 16 + rows = {"kind": "two_group", "a": a, "b": b} + grouped = {**rows, "clusters_a": [f"a{i // 8}" for i in range(40)], + "clusters_b": [f"b{i // 8}" for i in range(40)]} + independent, clustered = _sig("rows", rows), _sig("groups", grouped) + adjudicate_signals([independent]) + adjudicate_signals([clustered]) + assert independent.reject is True + assert clustered.reject is False + assert clustered.p_value > 0.05 > independent.p_value + + # Group ids that do not line up with the rows are not adjudicable. + broken = _sig("broken", {**rows, "clusters_a": ["a1"], "clusters_b": ["b1"]}) + adjudicate_signals([broken]) + assert broken.host_adjudicated is False and broken.descriptive_only is True + + +def test_header_says_none_when_nothing_was_tested(): + meta = adjudicate_signals([_sig("vibes"), _sig("more_vibes")]) + assert meta["method"] == "none" + assert meta["n_host_adjudicated"] == 0 + + +def test_header_names_both_families_when_both_were_used(): + paired = _sig("paired", {"kind": "paired_binary", "b": 15, "c": 0}) + unpaired = _sig("unpaired", {"kind": "two_group", "a": [0] * 8, "b": [1] * 8}) + meta = adjudicate_signals([paired, unpaired]) + assert meta["method"] == "e-BH + BH" + assert meta["rejected"] == ["paired", "unpaired"] def test_no_sufficient_is_descriptive_only(): @@ -180,4 +238,6 @@ def test_self_declared_reject_and_evalue_are_ignored(tmp_path): adjudicate_report(report) assert cand.host_adjudicated is True assert cand.e_value is None # two_group -> no e-value (not 999999) - assert cand.fdr_corrected is False + # 4 against 4 with a clean split: exactly 2 of the C(8, 4) tables. + assert cand.p_value == pytest.approx(2 / 70) + assert cand.fdr_corrected is True # survived its (one-member) BH family diff --git a/tests/test_analysis/test_cli.py b/tests/test_analysis/test_cli.py index 37a46863..20c3c742 100755 --- a/tests/test_analysis/test_cli.py +++ b/tests/test_analysis/test_cli.py @@ -122,7 +122,8 @@ def _fake_run_explore(path, **kwargs): assert captured["holdout_frac"] == 0.4 assert captured["holdout_confirm"] is True assert captured["holdout_seed"] == 7 - assert captured["judge_model"] == "claude-opus-4-8" + # The judge follows --backend unless told otherwise; its model is resolved later. + assert captured["judge_backend"] == "same" and captured["judge_model"] == "" assert captured["open_report"] is False diff --git a/tests/test_analysis/test_explore_review_wiring.py b/tests/test_analysis/test_explore_review_wiring.py new file mode 100644 index 00000000..8e2cfc63 --- /dev/null +++ b/tests/test_analysis/test_explore_review_wiring.py @@ -0,0 +1,427 @@ +"""Explore-run wiring: column roles, data card, keyword recipes, judge backend, +row-limit warning and sandbox cleanup.""" + +from __future__ import annotations + +import json +import random +import tempfile +from pathlib import Path + +import pytest + +import evalrx.analysis.api as explore_api +import evalrx.analysis.explore_run as er +from evalrx.analysis.explorer import ( + CandidateSignal, + ExploratoryAnalysisAgent, + ExploratoryAnalysisReport, + load_records_from_path, + truncation_warning, +) +from evalrx.analysis.hypothesis_agent import HypothesisAgent +from evalrx.analysis.keywords import keyword_candidates, tokenize +from evalrx.cli import main + + +def _grouped_rows(seed: int = 0, n_groups: int = 200) -> list[dict]: + """Rows cut from source clips; a clip's rows share the flag and tend to share the outcome.""" + rng = random.Random(seed) + rows: list[dict] = [] + for g in range(n_groups): + flagged = g % 2 == 0 + clip_fails = rng.random() < (0.85 if flagged else 0.15) + for _ in range(rng.randint(3, 7)): + fail = clip_fails if rng.random() < 0.9 else not clip_fails + rows.append({ + "case": f"c{len(rows)}", "clip": f"clip{g}", "flag": int(flagged), + "note": ("timeout " if fail and rng.random() < 0.6 else "") + + rng.choice(["alpha beta", "gamma delta", "epsilon zeta"]), + "label": "fail" if fail else "pass", + }) + return rows + + +class _FakeAgent: + """Stands in for the coding agent: proposes one frozen recipe and one hypothesis.""" + + seen: dict = {} + + def __init__(self, **kwargs): + pass + + def explore_records(self, records, *, question, outcome_col=None, **roles): + type(self).seen = {"n": len(records), "question": question, "roles": roles, + "clips": {r["clip"] for r in records}} + report = ExploratoryAnalysisReport(question=question, ok=True, + workdir=str(Path(tempfile.gettempdir()))) + report.candidate_signals = [CandidateSignal( + name="flag", rationale="flagged clips fail more", + recipe={"name": "flag", "kind": "expr", "expr": "flag == 1"}, + )] + report.hypotheses = [{"statement": "Flagged clips fail more.", "basis": "b", + "test_design": "t", + "predictions": [{"signal": "flag", "relation": ">", "value": 0}]}] + return report + + +class _Judge: + def generate(self, prompt: str) -> str: + return json.dumps({"verdict": "supported", "reasoning": "held-out rates differ.", + "needs_surgery": False}) + + +@pytest.fixture +def fake_run(monkeypatch, tmp_path): + rows = _grouped_rows() + monkeypatch.setattr(explore_api, "ExploratoryAnalysisAgent", _FakeAgent) + + def _load(path, info=None, **kwargs): + if info is not None: + info.update(n_loaded=len(rows), n_available=len(rows), n_files=1, truncated=False) + return rows + + monkeypatch.setattr(er, "load_records_from_path", _load) + monkeypatch.setattr(er, "_build_judge", lambda model: _Judge()) + + def _run(**kwargs): + out = tmp_path / "out" + rc = er.run_explore(tmp_path / "data", out=out, coder_provider="claude_code", + outcome_col="label", propose_hypotheses=False, + holdout_frac=0.4, holdout_confirm=True, **kwargs) + assert rc == 0 + return (json.loads((out / "confirm_report.json").read_text()), + json.loads((out / "exploratory_report.json").read_text()), + json.loads((out / "holdout_records.json").read_text())) + + return _run + + +def test_group_col_separates_the_split_and_clusters_the_intervals(fake_run, capsys): + confirm, report, holdout = fake_run(group_col="clip") + assert not (_FakeAgent.seen["clips"] & {r["clip"] for r in holdout}) + assert _FakeAgent.seen["roles"] == {"group_col": "clip"} + meta = confirm["split_meta"] + assert meta["group_col"] == "clip" and meta["group_overlap"]["share"] == 0.0 + assert confirm["adjudication"]["clustered_by"] == "clip" + (verdict,) = confirm["signal_verdicts"] + assert verdict["n_clusters"] == len({r["clip"] for r in holdout}) + assert not any("looks like the unit" in c for c in confirm["caveats"]) + assert "groups: clip" in capsys.readouterr().out + + +def test_without_group_col_the_run_reports_the_overlap_and_names_the_column(fake_run, capsys): + confirm, report, holdout = fake_run() + (caveat,) = [c for c in confirm["caveats"] if "looks like the unit" in c] + assert "'clip'" in caveat and "--group-col clip" in caveat + (suggested,) = confirm["split_meta"]["suggested_group_columns"] + assert suggested["column"] == "clip" + assert suggested["holdout_share_in_explore_groups"] > 0.8 + # The same warning reaches the terminal and the exploratory report. + assert "WARNING: column 'clip' looks like the unit" in capsys.readouterr().out + assert caveat in report["caveats"] + # Row-level intervals: narrower than the grouped ones on the same data. + (by_row,) = confirm["signal_verdicts"] + grouped = fake_run(group_col="clip")[0]["signal_verdicts"][0] + assert (by_row["ci"][1] - by_row["ci"][0]) < (grouped["ci"][1] - grouped["ci"][0]) + + +def test_a_named_group_column_that_is_missing_is_reported(fake_run): + confirm, _, _ = fake_run(group_col="no_such_column") + assert any("'no_such_column' is absent or empty" in c for c in confirm["caveats"]) + assert "group_overlap" not in confirm["split_meta"] + + +def test_data_card_answers_and_gaps_are_printed_in_the_caveats(fake_run): + confirm, report, _ = fake_run( + data_card={"unit": "one generated clip", "threshold": "score below 60"}) + caveats = report["caveats"] + assert "data card — what one row is: one generated clip" in caveats + assert "data card — how the outcome or its threshold was set: score below 60" in caveats + (gap,) = [c for c in caveats if c.startswith("data card — not stated")] + assert "how a row was cut from the raw object" in gap + assert "how results are combined" in gap and "what one row is" not in gap + assert set(caveats) <= set(confirm["caveats"]) | set(report["caveats"]) + assert "DATA CARD (from the user)" in _FakeAgent.seen["question"] + assert "one generated clip" in _FakeAgent.seen["question"] + + +def test_text_column_keywords_are_frozen_on_explore_and_tested_on_holdout(fake_run): + confirm, report, _ = fake_run(text_col="note", group_col="clip") + names = [c["name"] for c in report["candidate_signals"]] + assert names[0] == "flag" and "kw_timeout" in names + verdicts = {v["name"]: v for v in confirm["signal_verdicts"]} + timeout = verdicts["kw_timeout"] + assert timeout["recipe"]["expr"] == "has_word(note, 'timeout')" + assert timeout["claim"]["text"] == "effect > 0" and timeout["claim"]["stated_by_recipe"] + assert timeout["claim"]["status"] == "holds" + # Filler words were picked too (something always leans one way). Each enters + # the family with the direction it showed on the exploration rows, so it + # has to repeat that direction on rows it was not chosen on. Whether a + # given filler survives is a matter of chance at the family's error rate + # and is measured by simulation (docs/validation), not asserted here. + fillers = [v for n, v in verdicts.items() if n.startswith("kw_") and n != "kw_timeout"] + assert fillers + assert all(v["claim"]["stated_by_recipe"] and v["claim"]["relation"] in (">", "<") + for v in fillers) + assert all(v["explore_reject_in_sample"] is False for v in fillers) + assert confirm["adjudication"]["n_in_family"] == len(verdicts) + 1 # + the prediction + + +def test_keyword_recipes_are_still_tested_when_the_agent_fails(monkeypatch, tmp_path): + # The keyword candidates come from the host, not the agent, so a run whose + # exploration failed still has something to confirm. + rows = _grouped_rows() + + class _Broken(_FakeAgent): + def explore_records(self, records, *, question, outcome_col=None, **roles): + return ExploratoryAnalysisReport(question=question, ok=False, + error="no agent", workdir=str(tmp_path / "x")) + + monkeypatch.setattr(explore_api, "ExploratoryAnalysisAgent", _Broken) + monkeypatch.setattr(er, "load_records_from_path", lambda path, **kw: rows) + monkeypatch.setattr(er, "_build_judge", lambda model: _Judge()) + out = tmp_path / "out" + rc = er.run_explore(tmp_path / "data", out=out, coder_provider="claude_code", + outcome_col="label", propose_hypotheses=False, holdout_frac=0.4, + holdout_confirm=True, group_col="clip", text_col="note") + assert rc == 1 # the exploration did fail + confirm = json.loads((out / "confirm_report.json").read_text()) + assert "kw_timeout" in confirm["adjudication"]["rejected"] + assert confirm["adjudication"]["n_in_family"] == len(confirm["signal_verdicts"]) > 1 + assert confirm["adjudication"]["p_values"] == ["percentile bootstrap"] + + +def test_hypothesis_prediction_gets_a_host_verdict_in_the_run(fake_run): + confirm, _, _ = fake_run(group_col="clip") + (hv,) = confirm["hypothesis_verdicts"] + assert hv["verdict"] == "supported" and hv["host_verdict"] == "supported" + + +# ── judge backend ──────────────────────────────────────────────────────────── + + +def test_judge_follows_the_explorer_backend(monkeypatch): + monkeypatch.setattr(er, "_build_judge", lambda model: ("claude-judge", model)) + judge, meta = er.resolve_judge("same", "", coder_provider="codex", coder_model="gpt-x", + coder_binary="/opt/codex") + assert judge.cli_config.provider == "codex" and judge.cli_config.model == "gpt-x" + assert judge.cli_config.binary_path == "/opt/codex" + assert meta == {"backend": "codex", "model": "gpt-x", "same_as_proposer": "yes"} + + judge, meta = er.resolve_judge("same", "", coder_provider="claude_code") + assert judge == ("claude-judge", "claude-opus-4-8") + assert meta["backend"] == "claude" and meta["same_as_proposer"] == "same_backend" + + judge, meta = er.resolve_judge("claude", "", coder_provider="codex", coder_model="gpt-x") + assert judge == ("claude-judge", "claude-opus-4-8") and meta["same_as_proposer"] == "no" + + judge, meta = er.resolve_judge("gemini_cli", "", coder_provider="codex", + coder_model="gpt-x", coder_binary="/opt/codex") + # Another backend gets neither the explorer's model nor its binary. + assert judge.cli_config.model == "" and judge.cli_config.binary_path == "" + assert meta == {"backend": "gemini_cli", "model": "(backend default)", + "same_as_proposer": "no"} + + _, meta = er.resolve_judge("same", "gpt-y", coder_provider="codex", coder_model="gpt-x") + assert meta["same_as_proposer"] == "no" + + +def test_same_reviewer_is_recorded_and_warned_about(fake_run, capsys): + confirm, _, _ = fake_run() + assert confirm["judge"]["same_as_proposer"] == "same_backend" + (caveat,) = [c for c in confirm["caveats"] if "same backend" in c] + assert "--judge-backend" in caveat + assert "WARNING: the hypotheses were proposed and graded on the same backend" in ( + capsys.readouterr().out) + assert er.same_reviewer_caveat({"same_as_proposer": "no"}, "codex") == "" + assert "same model (m on codex)" in er.same_reviewer_caveat( + {"same_as_proposer": "yes", "model": "m"}, "codex") + + +def test_cli_passes_the_new_flags(monkeypatch, tmp_path): + import evalrx.cli as cli_mod + + captured: dict = {} + monkeypatch.setattr(cli_mod, "run_explore", + lambda path, **kwargs: captured.update(kwargs) or 0) + card = tmp_path / "card.yaml" + card.write_text("unit: one clip\nextraction: first 4 seconds\nignored: x\n") + assert main(["explore", "data", "--group-col", "clip", "--time-col", "wave", + "--text-col", "note", "--data-card", str(card), + "--outcome-threshold", "score < 60", "--judge-backend", "codex", + "--judge-model", "m", "--keep-sandbox"]) == 0 + assert captured["group_col"] == "clip" and captured["time_col"] == "wave" + assert captured["text_col"] == "note" and captured["keep_sandbox"] is True + assert captured["judge_backend"] == "codex" and captured["judge_model"] == "m" + assert captured["data_card"] == {"unit": "one clip", "extraction": "first 4 seconds", + "threshold": "score < 60"} + + captured.clear() + assert main(["explore", "data"]) == 0 + assert captured["data_card"] is None and captured["group_col"] is None + assert captured["judge_backend"] == "same" and captured["keep_sandbox"] is False + + +def test_data_card_file_must_be_a_mapping(tmp_path): + card = tmp_path / "card.json" + card.write_text('["not", "a", "mapping"]') + with pytest.raises(ValueError, match="must be a mapping"): + er.load_data_card(card) + card.write_text('{"unit": " a row ", "aggregation": ""}') + assert er.load_data_card(card) == {"unit": "a row"} + + +# ── row limit ──────────────────────────────────────────────────────────────── + + +def test_row_limit_reports_how_many_rows_were_dropped(tmp_path, monkeypatch, capsys): + data = tmp_path / "data" + data.mkdir() + for k in range(3): + (data / f"part{k}.json").write_text(json.dumps( + [{"i": i, "part": k, "label": "fail" if i % 4 == 0 else "pass"} + for i in range(50)])) + info: dict = {} + rows = load_records_from_path(data, max_rows=60, info=info) + assert len(rows) == 60 and [sum(r["part"] == k for r in rows) for k in range(3)] == [20] * 3 + assert info == {"n_loaded": 60, "n_available": 150, "n_files": 3, "truncated": True} + assert "only 60 of 150 rows" in truncation_warning(info, 60) + # Without `info` the rows returned are the same. + assert load_records_from_path(data, max_rows=60) == rows + + full: dict = {} + assert len(load_records_from_path(data, max_rows=500, info=full)) == 150 + assert full["truncated"] is False and truncation_warning(full, 500) == "" + + class _Agent(_FakeAgent): + def explore_records(self, records, *, question, outcome_col=None, **roles): + return ExploratoryAnalysisReport(question=question, ok=True, + workdir=str(tmp_path / "nowhere")) + + monkeypatch.setattr(explore_api, "ExploratoryAnalysisAgent", _Agent) + out = tmp_path / "out" + assert er.run_explore(data, out=out, outcome_col="label", propose_hypotheses=False, + holdout_frac=0.3, max_rows=60) == 0 + assert "WARNING: only 60 of 150 rows were loaded" in capsys.readouterr().out + report = json.loads((out / "exploratory_report.json").read_text()) + assert any("only 60 of 150 rows" in c for c in report["caveats"]) + + +# ── sandbox cleanup ────────────────────────────────────────────────────────── + + +def test_agent_removes_only_a_sandbox_it_created(tmp_path): + from evalrx.agent_runtime.sandbox import ExperimentSandbox + + own = ExploratoryAnalysisAgent() + workdir = Path(own._sandbox.workdir) + assert workdir.name.startswith("evalrx_sandbox_") and workdir.exists() + (workdir / "records.json").write_text("[]") + assert own.discard_sandbox() is True and not workdir.exists() + + given = ExploratoryAnalysisAgent(sandbox=ExperimentSandbox(workdir=tmp_path, cleanup=False)) + assert given.discard_sandbox() is False and tmp_path.exists() + + +def test_explore_deletes_the_temp_sandbox_once_artifacts_are_written(monkeypatch, tmp_path): + made: list[Path] = [] + + class _Agent: + def __init__(self, **kwargs): + self.workdir = Path(tempfile.mkdtemp(prefix="evalrx_sandbox_")) + made.append(self.workdir) + + def explore_records(self, records, *, question, outcome_col=None, **roles): + (self.workdir / "tables").mkdir() + (self.workdir / "tables" / "t.csv").write_text("a,b\n1,2\n") + (self.workdir / "records.json").write_text(json.dumps(records)) + return ExploratoryAnalysisReport(question=question, ok=True, + workdir=str(self.workdir)) + + def discard_sandbox(self) -> bool: + import shutil + + shutil.rmtree(self.workdir) + return True + + monkeypatch.setattr(explore_api, "ExploratoryAnalysisAgent", _Agent) + rows = [{"x": 1, "label": "pass"}] + out = tmp_path / "out" + explore_api.explore(rows, out=out, propose_hypotheses=False) + assert not made[0].exists() + assert (out / "tables" / "t.csv").exists() and (out / "records.json").exists() + # The report on disk points at the output directory, not the deleted one. + assert json.loads((out / "exploratory_report.json").read_text())["workdir"] == str(out) + + kept = tmp_path / "kept" + explore_api.explore(rows, out=kept, propose_hypotheses=False, keep_sandbox=True) + assert made[1].exists() + # With no output directory the sandbox is the only copy and is never removed. + result = explore_api.explore(rows, propose_hypotheses=False) + assert made[2].exists() and result.report.workdir == str(made[2]) + + +# ── keywords and hypothesis structure ──────────────────────────────────────── + + +def test_keyword_candidates_rank_by_evidence_and_freeze_direction(): + rng = random.Random(0) + rows, side = [], [] + for _ in range(600): + fail = rng.random() < 0.3 + words = rng.sample([f"w{i:03d}" for i in range(300)], 12) + if rng.random() < (0.5 if fail else 0.1): + words.append("Timeout") + if rng.random() < (0.05 if fail else 0.4): + words.append("cached") + rows.append({"text": " ".join(words)}) + side.append(1.0 if fail else 0.0) + picked = keyword_candidates(rows, "text", side, top_k=1) + assert [c.name for c in picked] == ["kw_timeout", "kw_cached"] + assert picked[0].recipe["expect"] == {"relation": ">", "value": 0.0} + assert picked[1].recipe["expect"] == {"relation": "<", "value": 0.0} + assert "Chosen on those rows, so untested" in picked[0].rationale + assert picked[0].sufficient is None and picked[0].reject is None + assert keyword_candidates(rows, "text", [1.0] * 600) == [] # one side only + assert keyword_candidates(rows, "absent", side) == [] + assert tokenize("It's re-run_42, OK?") == {"it's", "run", "42"} - {"42"} | {"run"} + + +class _ProposalJudge: + def generate(self, prompt: str) -> str: + self.prompt = prompt + return json.dumps({"hypotheses": [{ + "hypothesis": "The encoder drops late frames, which causes the failures.", + "plain_statement": "Late frames get lost, and that is when it fails.", + "basis": "flag", "test": "re-run with frames kept", + "predictions": [{"signal": "flag", "relation": ">", "value": 0.1}, + {"signal": "prose_only", "relation": ">", "value": 0}], + "experiment": {"data_needed": "200 clips", "operation": "keep late frames", + "expected_result": "failures drop", + "falsified_by": "failures stay the same"}, + }, { + "hypothesis": "Something else entirely explains the pattern seen.", + "plain_statement": "Something else explains it.", + "experiment": {"data_needed": "", "operation": "", "expected_result": "", + "falsified_by": ""}, + }]}) + + +def test_hypothesis_agent_carries_predictions_and_a_structured_plan(): + judge = _ProposalJudge() + report = {"question": "q", "takeaways": [{"title": "t", "analysis": "a"}], + "candidate_signals": [ + {"name": "flag", "rationale": "r", + "recipe": {"name": "flag", "kind": "expr", "expr": "flag == 1"}}, + {"name": "prose_only", "rationale": "no recipe"}]} + first, second = HypothesisAgent(judge=judge).propose(report) + # The prompt names the signal and its recipe, so a prediction can refer to it. + assert "[signal name: flag; recipe: flag == 1]" in judge.prompt + # A prediction about a signal with no recipe cannot be checked and is dropped. + assert first.predictions == [{"signal": "flag", "relation": ">", "value": 0.1}] + assert first.experiment["falsified_by"] == "failures stay the same" + assert first.to_dict()["experiment"]["operation"] == "keep late frames" + # An all-empty plan is no plan; the dict then has the shape it always had. + assert second.experiment is None and second.predictions == [] + assert set(second.to_dict()) == {"statement", "plain_statement", "basis", "test_design"} diff --git a/tests/test_analysis/test_group_split.py b/tests/test_analysis/test_group_split.py new file mode 100644 index 00000000..9061d3da --- /dev/null +++ b/tests/test_analysis/test_group_split.py @@ -0,0 +1,165 @@ +"""Group-aware split, group-column suggestion, explicit roles and the leakage check.""" + +from __future__ import annotations + +import random + +from evalrx.analysis.fused_pipeline import _split_records, group_overlap +from evalrx.analysis.holdout import split_records +from evalrx.analysis.profile import ( + intraclass_correlation, + leakage_suspects, + profile_records, + suggest_group_columns, +) + + +def _grouped_rows(seed: int = 0, n_groups: int = 200) -> list[dict]: + """Several rows per source item; rows of an item tend to share the outcome.""" + rng = random.Random(seed) + rows: list[dict] = [] + for g in range(n_groups): + tendency = rng.random() + for _ in range(rng.randint(2, 8)): + score = tendency + rng.gauss(0, 0.15) + rows.append({ + "case_id": f"c{len(rows)}", + "clip": f"clip{g}", + "model": rng.choice(["a", "b", "c"]), + "noise": f"n{rng.randint(0, 40)}", + "x": round(rng.random(), 2), + "label": "fail" if score < 0.4 else "pass", + }) + return rows + + +def test_group_split_keeps_every_group_on_one_side(): + rows = _grouped_rows() + explore, holdout = split_records(rows, 0.3, seed=0, outcome_col="label", group_col="clip") + assert holdout is not None + assert not ({r["clip"] for r in explore} & {r["clip"] for r in holdout}) + assert group_overlap(explore, holdout, "clip")["share"] == 0.0 + # Complete, and close to the requested share and to the overall fail rate. + assert len(explore) + len(holdout) == len(rows) + assert abs(len(holdout) / len(rows) - 0.3) < 0.03 + + def fail_rate(rs: list[dict]) -> float: + return sum(r["label"] == "fail" for r in rs) / len(rs) + + assert abs(fail_rate(holdout) - fail_rate(rows)) < 0.05 + # Deterministic for a seed, different for another. + again = split_records(rows, 0.3, seed=0, outcome_col="label", group_col="clip")[1] + other = split_records(rows, 0.3, seed=1, outcome_col="label", group_col="clip")[1] + assert [r["case_id"] for r in again] == [r["case_id"] for r in holdout] + assert [r["case_id"] for r in other] != [r["case_id"] for r in holdout] + + +def test_row_level_split_leaves_most_held_out_rows_in_explored_groups(): + rows = _grouped_rows() + explore, holdout = split_records(rows, 0.3, seed=0, outcome_col="label") + assert group_overlap(explore, holdout, "clip")["share"] > 0.8 + + +def test_rows_without_a_group_are_their_own_group(): + rows = [{"g": None, "label": "fail" if i % 3 == 0 else "pass"} for i in range(60)] + explore, holdout = _split_records(rows, frac=0.3, seed=0, label_col="label", group_col="g") + assert holdout is not None and len(explore) + len(holdout) == 60 + assert 12 <= len(holdout) <= 24 + + +def test_group_split_handles_a_many_valued_outcome(): + rng = random.Random(3) + rows = [] + for g in range(150): + base = rng.random() + rows.extend({"g": f"g{g}", "score": base + rng.gauss(0, 0.1)} + for _ in range(rng.randint(1, 9))) + explore, holdout = _split_records(rows, frac=0.3, seed=0, label_col="score", group_col="g") + assert holdout is not None + assert abs(len(holdout) / len(rows) - 0.3) < 0.04 + assert group_overlap(explore, holdout, "g")["share"] == 0.0 + + def mean(rs: list[dict]) -> float: + return sum(r["score"] for r in rs) / len(rs) + + assert abs(mean(holdout) - mean(explore)) < 0.08 + + +def test_intraclass_correlation_extremes(): + assert intraclass_correlation(["a", "a", "b", "b"], [0.0, 0.0, 1.0, 1.0]) == 1.0 + icc = intraclass_correlation(["a", "a", "b", "b"], [0.0, 1.0, 0.0, 1.0]) + assert icc is not None and icc < 0 + assert intraclass_correlation(["a", "b"], [0.0, 1.0]) is None # no repeats + assert intraclass_correlation(["a", "a"], [0.0, 1.0]) is None # one group + + +def test_profile_suggests_the_grouping_column_from_the_data(): + rows = _grouped_rows() + profile = profile_records(rows, outcome_col="label") + (suggestion,) = profile.suggested_group_columns + assert suggestion["column"] == "clip" + assert suggestion["n_groups"] == 200 and suggestion["icc"] > 0.3 + assert any("'clip'" in w and "group column" in w for w in profile.warnings) + # A factor with three levels, an id that never repeats and a float are not units. + assert suggest_group_columns(rows, outcome_col="label", exclude={"clip"}) == [] + + +def test_explicit_roles_override_the_name_heuristic(): + rows = _grouped_rows() + for i, r in enumerate(rows): + r["batch"] = f"2024-{1 + i % 12:02d}" + r["wave"] = i % 4 + inferred = profile_records(rows, outcome_col="label") + assert "clip" not in inferred.group_columns + assert "batch" in inferred.time_columns # ISO year-month values + assert "wave" not in inferred.time_columns + + named = profile_records(rows, outcome_col="label", group_cols=["clip"], + time_cols=["wave", "absent"]) + assert "clip" in named.group_columns and named.columns["clip"].role == "group" + assert "wave" in named.time_columns + assert named.suggested_group_columns == [] # already named + assert any("'absent'" in w and "not in the data" in w for w in named.warnings) + + +def test_time_like_names_are_recognised_as_whole_words_only(): + rows = [{"month_reported": "x", "created_at": "y", "candidate": "z", + "content_group": "g", "label": "pass"} for _ in range(4)] + profile = profile_records(rows, outcome_col="label") + assert set(profile.time_columns) == {"month_reported", "created_at"} + assert "content_group" in profile.group_columns + assert profile.columns["candidate"].role == "predictor" + + +def test_leakage_check_flags_columns_that_determine_the_outcome(): + rng = random.Random(1) + rows = [] + for i in range(300): + score = rng.random() + fail = score < 0.3 + rows.append({ + "case_id": f"c{i}", + "label": "fail" if fail else "pass", + "grader_note": "wrong" if fail else "ok", # written after grading + "raw_score": score, # the outcome before the cut + "length": rng.randint(5, 50), + "mild": (score + rng.gauss(0, 0.5)), + }) + found = {s["column"]: s for s in leakage_suspects(rows, outcome_col="label", + exclude={"case_id"})} + assert set(found) == {"grader_note", "raw_score"} + assert found["grader_note"]["measure"] == "accuracy_from_value" + assert found["raw_score"]["measure"] == "auc" + + profile = profile_records(rows, outcome_col="label") + assert profile.columns["raw_score"].leakage_suspect is True + assert profile.columns["length"].leakage_suspect is False + assert sum("almost fully determines" in w for w in profile.warnings) == 2 + + +def test_leakage_check_on_a_numeric_outcome_uses_correlation(): + rng = random.Random(2) + rows = [{"y": v, "copy": 2 * v + 1, "other": rng.random()} + for v in (rng.random() for _ in range(100))] + (found,) = leakage_suspects(rows, outcome_col="y") + assert found["column"] == "copy" and found["measure"] == "correlation" diff --git a/tests/test_analysis/test_holdout_designs.py b/tests/test_analysis/test_holdout_designs.py new file mode 100644 index 00000000..eb292505 --- /dev/null +++ b/tests/test_analysis/test_holdout_designs.py @@ -0,0 +1,414 @@ +"""Held-out comparison designs, bounded predictions and the single correction family.""" + +from __future__ import annotations + +import json + +import pytest + +from evalrx.analysis.holdout import holdout_confirm, outcome_values +from evalrx.analysis.holdout_designs import estimate_design, representative_rows +from evalrx.analysis.operationalize import ( + RecipeError, + SignalRecipe, + compile_recipe, + evaluate_expr, + parse_expectation, +) + + +def _cell(n: int, n_fail: int, **cols) -> list[dict]: + """*n* rows sharing *cols*, the first *n_fail* of them failing.""" + return [{**cols, "label": "fail" if i < n_fail else "pass"} for i in range(n)] + + +def _signal(name: str, expr: str, **recipe) -> dict: + return {"name": name, "rationale": "", "recipe": {"name": name, "kind": "expr", + "expr": expr, **recipe}} + + +def _confirm(signals: list[dict], rows: list[dict], **kwargs) -> dict: + report = {"candidate_signals": signals, + "hypotheses": kwargs.pop("hypotheses", [])} + return holdout_confirm(report, rows, outcome_col="label", **kwargs) + + +def _by_name(confirm: dict) -> dict: + return {v["name"]: v for v in confirm["signal_verdicts"]} + + +# ── recipe fields ──────────────────────────────────────────────────────────── + + +def test_recipe_optional_fields_round_trip_and_tolerate_bad_shapes(): + recipe = SignalRecipe.from_dict({ + "name": "r", "expr": "x > 1", "where": "kind == 'i2v'", "design": "stratified", + "strata": "generator", "bins": [0.2, "0.5"], "modifier": "late == 1", + "expect": {"relation": "abs<", "value": 0.1}, + }) + assert recipe.where == "kind == 'i2v'" and recipe.strata == ["generator"] + assert recipe.bins == [0.2, 0.5] + assert parse_expectation(recipe.expect) == ("abs<", 0.1) + + sloppy = SignalRecipe.from_dict({"name": "r", "expr": "x", "bins": ["low", 1], + "strata": 7, "expect": "small"}) + assert sloppy.bins == [] and sloppy.strata == [] and sloppy.expect is None + assert parse_expectation({"relation": "~", "value": 1}) is None + assert parse_expectation({"relation": "abs<", "value": 0}) is None + assert parse_expectation({"relation": "nonzero", "value": 9}) == ("nonzero", 0.0) + + +def test_where_leaves_rows_out_instead_of_scoring_them_zero(): + rows = [{"case_id": "a", "kind": "i2v", "x": 5}, {"case_id": "b", "kind": "t2v", "x": 5}, + {"case_id": "c", "kind": "i2v", "x": 0}, {"case_id": "d", "x": 5}] + recipe = SignalRecipe(name="r", expr="x > 1", where="kind == 'i2v'") + assert compile_recipe(recipe, rows) == {"a": 1.0, "c": 0.0} + + +def test_no_expression_may_read_the_outcome_column_whatever_it_is_called(): + rows = [{"case_id": "a", "x": 1, "verdict": "bad"}] + with pytest.raises(RecipeError, match="reserved outcome/id"): + compile_recipe(SignalRecipe(name="r", expr="verdict == 'bad'"), rows, + reserved=("verdict",)) + with pytest.raises(RecipeError, match="recipe where may not reference"): + compile_recipe(SignalRecipe(name="r", expr="x > 0", where="label == 'fail'"), rows) + assert evaluate_expr("x + 1", rows) == [2] + + +def test_keyword_functions_in_the_recipe_language(): + rows = [{"case_id": "a", "t": "Please restart the ART module"}, + {"case_id": "b", "t": "start again"}] + word = compile_recipe(SignalRecipe(name="w", expr='has_word(t, "art")'), rows) + piece = compile_recipe(SignalRecipe(name="p", expr='contains(t, "art")'), rows) + assert word == {"a": 1.0, "b": 0.0} + assert piece == {"a": 1.0, "b": 1.0} + + +# ── designs ────────────────────────────────────────────────────────────────── + + +def test_subgroup_condition_tests_the_effect_inside_one_subgroup(): + rows = (_cell(40, 30, kind="i2v", late=1) + _cell(40, 6, kind="i2v", late=0) + + _cell(40, 8, kind="t2v", late=1) + _cell(40, 6, kind="t2v", late=0)) + out = _by_name(_confirm([ + _signal("late_i2v", "late == 1", where="kind == 'i2v'"), + _signal("late_t2v", "late == 1", where="kind == 't2v'"), + ], rows)) + assert out["late_i2v"]["n_holdout"] == 80 + assert out["late_i2v"]["details"]["n_excluded_by_where"] == 80 + assert out["late_i2v"]["effect"] == pytest.approx(0.60) + assert out["late_i2v"]["reject"] is True + assert out["late_t2v"]["effect"] == pytest.approx(0.05) + assert out["late_t2v"]["reject"] is False + + +def test_difference_in_differences_estimates_the_interaction(): + rows = (_cell(60, 45, kind="i2v", late=1) + _cell(60, 9, kind="i2v", late=0) + + _cell(60, 12, kind="t2v", late=1) + _cell(60, 9, kind="t2v", late=0)) + out = _by_name(_confirm([ + _signal("late_more_in_i2v", "late == 1", design="did", modifier="kind == 'i2v'"), + ], rows))["late_more_in_i2v"] + assert out["design"] == "did" + assert out["details"]["effect_where_modifier_1"] == pytest.approx(0.60) + assert out["details"]["effect_where_modifier_0"] == pytest.approx(0.05) + assert out["effect"] == pytest.approx(0.55) + assert out["ci"][0] > 0.3 and out["reject"] is True + assert out["details"]["cells"]["modifier_1_flagged"] == {"n": 60, "mean": 0.75} + + +def test_stratified_comparison_removes_a_gap_that_is_only_a_difference_in_mix(): + # The flag does nothing inside either generator; it is just far more + # common under the generator that fails more. + rows = (_cell(90, 54, gen="weak", flag=1) + _cell(30, 18, gen="weak", flag=0) + + _cell(30, 3, gen="strong", flag=1) + _cell(90, 9, gen="strong", flag=0)) + out = _by_name(_confirm([ + _signal("raw", "flag == 1"), + _signal("matched", "flag == 1", design="stratified", strata=["gen"], + expect={"relation": "abs<", "value": 0.15}), + ], rows)) + assert out["raw"]["effect"] == pytest.approx(0.475 - 0.225) + assert out["raw"]["reject"] is True + matched = out["matched"] + assert matched["design"] == "stratified" + assert matched["effect"] == pytest.approx(0.0, abs=1e-9) + assert matched["details"]["unadjusted_difference"] == pytest.approx(0.25) + assert matched["details"]["n_strata_used"] == 2 + assert matched["claim"]["status"] == "holds" # predicted small, is small + assert matched["reject"] is False # which is not a separation + + +def test_strata_with_only_one_group_are_dropped_and_counted(): + rows = (_cell(20, 10, gen="a", flag=1) + _cell(20, 4, gen="a", flag=0) + + _cell(15, 5, gen="b", flag=1)) # nothing to compare in "b" + out = _by_name(_confirm([ + _signal("m", "flag == 1", design="stratified", strata=["gen"]), + ], rows))["m"] + assert out["n_holdout"] == 40 + assert out["details"]["n_rows_in_one_sided_strata"] == 15 + assert out["details"]["n_strata"] == 2 and out["details"]["n_strata_used"] == 1 + + +def test_dose_response_uses_the_frozen_cut_points(): + rows = (_cell(50, 5, score=0.1) + _cell(50, 15, score=0.4) + _cell(50, 30, score=0.8)) + out = _by_name(_confirm([ + _signal("trend", "score", bins=[0.25, 0.6]), + _signal("no_bins", "score * 2"), + ], rows)) + trend = out["trend"] + assert trend["design"] == "dose_response" + assert [b["n"] for b in trend["details"]["bins"]] == [50, 50, 50] + assert [b["mean"] for b in trend["details"]["bins"]] == [0.1, 0.3, 0.6] + assert trend["effect"] == pytest.approx(0.25) # per step up the bins + assert trend["reject"] is True + # A continuous recipe with no cut points still cannot be re-tested, and says how to fix it. + assert out["no_bins"]["status"] == "skipped" + assert "binary flag" in out["no_bins"]["reason"] and "bins" in out["no_bins"]["reason"] + + +def test_designs_that_cannot_be_estimated_are_skipped_with_a_reason(): + rows = _cell(20, 10, flag=1, score=0.5, kind="a") + _cell(20, 4, flag=0, score=0.2, kind="a") + out = _by_name(_confirm([ + _signal("bad_design", "flag == 1", design="regression"), + _signal("no_strata", "flag == 1", design="stratified"), + _signal("no_modifier", "flag == 1", design="did"), + _signal("one_cell", "flag == 1", design="did", modifier="kind == 'b'"), + _signal("continuous_did", "score", design="did", modifier="flag == 1"), + _signal("one_sided", "score > 0"), + _signal("bad_syntax", "flag ==="), + ], rows)) + assert all(v["status"] == "skipped" for v in out.values()) + assert "unknown design" in out["bad_design"]["reason"] + assert "strata" in out["no_strata"]["reason"] + assert "modifier" in out["no_modifier"]["reason"] + assert "no held-out row" in out["one_cell"]["reason"] + assert "needs a 0/1 recipe" in out["continuous_did"]["reason"] + assert "one side" in out["one_sided"]["reason"] + assert "recipe error" in out["bad_syntax"]["reason"] + + +# ── claims, bounds and the correction family ───────────────────────────────── + + +def test_a_control_expected_to_be_small_is_not_recorded_as_a_finding(): + # A real difference of nine points on a comparison that was predicted to + # be under ten: it neither "holds" as a finding nor clearly stays in bound. + rows = _cell(300, 87, flag=1) + _cell(300, 60, flag=0) + out = _by_name(_confirm([ + _signal("as_finding", "flag == 1"), + _signal("as_control", "flag == 1", expect={"relation": "abs<", "value": 0.10}), + _signal("loose_control", "flag == 1", expect={"relation": "abs<", "value": 0.30}), + _signal("tight_control", "flag == 1", expect={"relation": "abs<", "value": 0.01}), + ], rows)) + assert out["as_finding"]["effect"] == pytest.approx(0.09) + assert out["as_finding"]["claim"]["text"] == "effect is not zero" + assert out["as_control"]["claim"]["text"] == "|effect| < 0.1" + assert out["as_control"]["claim"]["status"] == "inconclusive" + assert out["loose_control"]["claim"]["status"] == "holds" + assert out["tight_control"]["claim"]["status"] == "contradicted" + assert all(out[k]["reject"] is False + for k in ("as_control", "loose_control", "tight_control")) + + +def test_directional_claims_can_hold_or_be_contradicted(): + rows = _cell(100, 60, flag=1) + _cell(100, 20, flag=0) + out = _by_name(_confirm([ + _signal("up", "flag == 1", expect={"relation": ">", "value": 0}), + _signal("down", "flag == 1", expect={"relation": "<", "value": 0}), + _signal("big", "flag == 1", expect={"relation": ">", "value": 0.9}), + ], rows)) + assert out["up"]["claim"]["status"] == "holds" and out["up"]["reject"] is True + assert out["up"]["details"]["p_value_method"] == "exact (Fisher)" + assert out["down"]["claim"]["status"] == "contradicted" + assert out["big"]["claim"]["status"] == "contradicted" + assert out["big"]["details"]["p_value_method"] == "percentile bootstrap" + + +def test_header_lists_the_tests_the_p_values_came_from(): + rows = _cell(100, 60, flag=1) + _cell(100, 20, flag=0) + exact_only = _confirm([_signal("up", "flag == 1")], rows)["adjudication"] + assert exact_only["p_values"] == ["exact (Fisher)"] + both = _confirm([ + _signal("up", "flag == 1"), + _signal("bounded", "flag == 1", expect={"relation": "abs<", "value": 0.9}), + ], rows)["adjudication"] + assert both["p_values"] == ["exact (Fisher)", "percentile bootstrap"] + grouped = _confirm([_signal("up", "flag == 1")], + [{**r, "g": i // 4} for i, r in enumerate(rows)], + group_col="g")["adjudication"] + assert grouped["p_values"] == ["percentile bootstrap"] + empty = _confirm([{"name": "prose"}], rows)["adjudication"] + assert empty["p_values"] is None and empty["method"] == "none" + + +def test_all_claims_share_one_correction_family(): + # One strong flag, one borderline flag (p about 0.03 on its own) and + # twenty flags that are exactly balanced against the outcome. + rows = [] + for i in range(200): + fail = i < 80 + row = {"label": "fail" if fail else "pass", + "strong": int(i < 60 or 160 <= i), # 60/80 fails, 40/120 passes + "borderline": int(i < 46 or 80 <= i < 130)} # 46/80 fails, 50/120 passes + for k in range(20): + row[f"null{k}"] = int((i + k) % 2 == 0) # half of each side + rows.append(row) + nulls = [_signal(f"null{k}", f"null{k} == 1") for k in range(20)] + alone = _by_name(_confirm([_signal("borderline", "borderline == 1")], rows)) + assert 0.01 < alone["borderline"]["p_value"] < 0.05 + assert alone["borderline"]["reject"] is True + + confirm = _confirm( + [_signal("strong", "strong == 1"), _signal("borderline", "borderline == 1")] + nulls, + rows, + ) + meta = confirm["adjudication"] + assert meta["method"] == "BH" and meta["n_in_family"] == 22 + assert meta["rejected"] == ["strong"] + verdicts = _by_name(confirm) + # The borderline flag clears 0.05 on its own and does not survive the family. + assert verdicts["borderline"]["raw_reject"] is True + assert verdicts["borderline"]["reject"] is False + assert verdicts["borderline"]["fdr_corrected"] is False + assert verdicts["strong"]["fdr_corrected"] is True + + +def test_header_does_not_name_a_correction_when_nothing_was_tested(): + confirm = _confirm([{"name": "prose_only", "rationale": "no recipe"}], + _cell(10, 5, x=1)) + meta = confirm["adjudication"] + assert meta["method"] == "none" and meta["n_in_family"] == 0 + assert "nothing was corrected" in meta["note"] + + +def test_small_samples_get_the_exact_test_and_a_warning(): + rows = _cell(4, 4, flag=1) + _cell(4, 0, flag=0) + out = _by_name(_confirm([_signal("tiny", "flag == 1")], rows))["tiny"] + assert out["p_value"] == pytest.approx(2 / 70) # not 1/2001 from a degenerate bootstrap + assert out["details"]["min_units_per_side"] == 4 + assert "unreliable" in out["details"]["small_sample_warning"] + + +# ── groups ─────────────────────────────────────────────────────────────────── + + +def test_group_column_makes_intervals_count_groups_not_rows(): + # Ten source items, eight rows each; the flag and the outcome are both + # properties of the item. + rows = [] + for g, (flag, fail) in enumerate([(1, 1), (1, 1), (1, 1), (1, 0), (1, 0), + (0, 0), (0, 0), (0, 0), (0, 0), (0, 1)]): + rows += [{"item": f"i{g}", "flag": flag, "label": "fail" if fail else "pass"}] * 8 + signals = [_signal("flag", "flag == 1")] + by_row = _by_name(_confirm(signals, rows))["flag"] + by_item = _by_name(_confirm(signals, rows, group_col="item"))["flag"] + assert by_row["effect"] == pytest.approx(by_item["effect"]) == pytest.approx(0.4) + assert by_row["reject"] is True and by_item["reject"] is False + assert by_item["n_clusters"] == 10 and "n_clusters" not in by_row + assert by_item["details"]["min_units_per_side"] == 5 + width = lambda v: v["ci"][1] - v["ci"][0] # noqa: E731 + assert width(by_item) > 1.5 * width(by_row) + + +# ── numeric outcome, representatives, hypotheses ───────────────────────────── + + +def test_numeric_outcome_is_compared_by_mean(): + rows = ([{"flag": 1, "score": 70.0 + i % 5} for i in range(40)] + + [{"flag": 0, "score": 50.0 + i % 5} for i in range(40)]) + values, kind, positive, note = outcome_values(rows, "score") + assert kind == "continuous" and positive is None and "differences of its mean" in note + report = {"candidate_signals": [_signal("flag", "flag == 1")], "hypotheses": []} + confirm = holdout_confirm(report, rows, outcome_col="score") + verdict = confirm["signal_verdicts"][0] + assert confirm["outcome"]["kind"] == "continuous" and confirm["n_validate_fail"] == 0 + assert verdict["effect"] == pytest.approx(20.0) + assert verdict["details"]["mean_flagged"] == pytest.approx(72.0) + assert "fail_rate_flagged" not in verdict + assert verdict["reject"] is True + + +def test_representative_rows_sit_at_the_median_not_the_extreme(): + rows = ([{"id": f"f{i}", "size": float(i), "label": "fail"} for i in range(1, 22)] + + [{"id": f"p{i}", "size": float(-i), "label": "pass"} for i in range(1, 22)]) + confirm = _confirm([_signal("big", "size > 0")], rows, id_col="id") + cases = confirm["signal_verdicts"][0]["representative_cases"] + assert [c["id"] for c in cases["flagged"]] == ["f11", "f10", "f12"] + assert [c["id"] for c in cases["unflagged"]] == ["p11", "p10", "p12"] + assert cases["flagged"][0]["row"] == 10 # position in the held-out rows + # Not offered for a signal whose claim did not hold. + flat = _confirm([_signal("coin", "size > 100 or size < -100 or size == 1")], rows) + assert "representative_cases" not in flat["signal_verdicts"][0] + + outcome = [1.0] * 21 + [0.0] * 21 + estimate = estimate_design(SignalRecipe(name="b", expr="size > 0"), rows, outcome) + assert representative_rows(estimate, rows, outcome, ["size"], k=1) == { + "unflagged": [31], "flagged": [10]} + + +class _Judge: + def __init__(self) -> None: + self.prompts: list[str] = [] + + def generate(self, prompt: str) -> str: + self.prompts.append(prompt) + return json.dumps({ + "verdict": "partial", "reasoning": "numbers hold; the cause is open.", + "needs_surgery": True, + "experiment": {"data_needed": "200 held-out prompts", "operation": "swap the encoder", + "expected_result": "the gap closes", "falsified_by": "the gap stays"}, + }) + + +def test_numeric_predictions_are_checked_by_the_host_not_the_judge(): + # The flag raises the failure rate from 20% to 50%; the control does nothing. + rows = (_cell(100, 50, flag=1, ctrl=1) + _cell(100, 50, flag=1, ctrl=0) + + _cell(100, 20, flag=0, ctrl=1) + _cell(100, 20, flag=0, ctrl=0)) + hypotheses = [ + {"statement": "Flagged rows fail more and the control is flat.", + "predictions": [{"signal": "flag", "relation": ">", "value": 0.0}, + {"signal": "ctrl", "relation": "abs<", "value": 0.2}]}, + {"statement": "The flag effect is huge.", + "predictions": [{"signal": "flag", "relation": ">", "value": 0.8}]}, + {"statement": "Something about a signal nobody froze.", + "predictions": [{"signal": "missing", "relation": ">", "value": 0.0}, + {"signal": "flag", "relation": "roughly", "value": 1}]}, + {"statement": "No numbers at all."}, + ] + signals = [_signal("flag", "flag == 1"), _signal("ctrl", "ctrl == 1")] + confirm = _confirm(signals, rows, hypotheses=hypotheses) + first, second, third, fourth = confirm["hypothesis_verdicts"] + assert first["host_verdict"] == "supported" + assert [r["status"] for r in first["prediction_results"]] == ["holds", "holds"] + assert second["host_verdict"] == "refuted" + assert second["prediction_results"][0]["status"] == "contradicted" + assert third["host_verdict"] == "none" + assert [r["status"] for r in third["prediction_results"]] == ["not_testable"] * 2 + assert fourth["host_verdict"] == "none" and "prediction_results" not in fourth + # No judge ran: the host's verdicts stand on their own. + assert all(h["verdict"] == "not_judged" for h in confirm["hypothesis_verdicts"]) + # Signal claims and hypothesis predictions were corrected together. + meta = confirm["adjudication"] + assert (meta["n_signal_claims"], meta["n_hypothesis_claims"], meta["n_in_family"]) == (2, 3, 5) + assert not any("_p_contrary" in r for h in confirm["hypothesis_verdicts"] + for r in h.get("prediction_results", [])) + + +def test_judge_sees_host_results_and_can_fill_in_the_experiment_plan(): + rows = _cell(100, 60, flag=1) + _cell(100, 20, flag=0) + judge = _Judge() + kept = {"data_needed": "d", "operation": "o", "expected_result": "e", "falsified_by": "f"} + confirm = _confirm( + [_signal("flag", "flag == 1")], rows, judge=judge, + hypotheses=[ + {"statement": "A cause.", "predictions": [ + {"signal": "flag", "relation": ">", "value": 0.0}]}, + {"statement": "Another cause.", "experiment": kept}, + ], + ) + first, second = confirm["hypothesis_verdicts"] + assert "PREDICTIONS THE HOST ALREADY CHECKED" in judge.prompts[0] + assert "flag > 0.0: holds" in judge.prompts[0] + assert "PREDICTIONS THE HOST ALREADY CHECKED" not in judge.prompts[1] + assert first["verdict"] == "partial" and first["host_verdict"] == "supported" + assert first["experiment"]["falsified_by"] == "the gap stays" + assert second["experiment"] == kept # the proposer's plan is not overwritten diff --git a/tests/test_stats/test_cluster_bootstrap.py b/tests/test_stats/test_cluster_bootstrap.py new file mode 100644 index 00000000..d1053bd8 --- /dev/null +++ b/tests/test_stats/test_cluster_bootstrap.py @@ -0,0 +1,135 @@ +"""Cluster bootstrap over row weights, bootstrap p-values and the exact test.""" + +from __future__ import annotations + +import random + +import numpy as np +import pytest + +from evalrx.stats import ( + bootstrap_p_value, + clustered_bootstrap_diff, + compare, + mean_difference_statistic, + two_group_exact_p, + weighted_bootstrap, +) + + +def test_weighted_bootstrap_point_estimate_uses_unit_weights(): + y = np.array([0.0, 0.0, 1.0, 1.0, 1.0]) + arm = np.array([0.0, 0.0, 0.0, 1.0, 1.0]) + out = weighted_bootstrap(mean_difference_statistic(y, arm), 5, n_boot=200) + assert out["effect"] == pytest.approx(1.0 - 1.0 / 3.0) + assert out["n_clusters"] == 5 + assert out["ci_low"] <= out["effect"] <= out["ci_high"] + + +def test_rows_of_one_cluster_are_resampled_together(): + # Two clusters, each constant: every replicate holds whole clusters, so + # the weighted mean can only be 0, 0.5 or 1. + y = np.array([0.0] * 5 + [1.0] * 5) + clusters = ["a"] * 5 + ["b"] * 5 + + def mean(w: np.ndarray) -> float: + return float(w @ y) / float(w.sum()) + + out = weighted_bootstrap(mean, 10, clusters=clusters, n_boot=300, seed=1) + assert out["n_clusters"] == 2 + assert set(np.round(out["draws"], 6)) <= {0.0, 0.5, 1.0} + + +def test_missing_cluster_ids_are_not_merged_into_one_cluster(): + out = weighted_bootstrap(lambda w: float(w.sum()), 4, + clusters=[None, "", "a", "a"], n_boot=10) + assert out["n_clusters"] == 3 + + +def test_undefined_replicates_are_counted_not_averaged_in(): + y = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0]) + arm = np.array([0.0, 1.0, 1.0, 1.0, 1.0, 1.0]) # a single row in arm 0 + out = weighted_bootstrap(mean_difference_statistic(y, arm), 6, n_boot=400, seed=0) + assert out["n_undefined"] > 0 + assert len(out["draws"]) == 400 - out["n_undefined"] + + +def test_bootstrap_p_value_relations(): + draws = np.linspace(0.1, 0.3, 99) # every replicate is positive + assert bootstrap_p_value(draws, "nonzero") == pytest.approx(2 / 100) + assert bootstrap_p_value(draws, ">", 0.0) == pytest.approx(1 / 100) + assert bootstrap_p_value(draws, "<", 0.0) == 1.0 + assert bootstrap_p_value(draws, "abs<", 0.5) == pytest.approx(1 / 100) + assert bootstrap_p_value(draws, "abs<", 0.2) > 0.4 + assert bootstrap_p_value([], "nonzero") == 1.0 + with pytest.raises(ValueError, match="unknown relation"): + bootstrap_p_value(draws, "==") + + +def test_unpaired_compare_accepts_a_pair_of_cluster_sequences(): + # Forty rows a side, cut from five source items a side, and rows of an + # item agree with each other: the evidence is ten items, not 80 rows. + a = [0] * 32 + [1] * 8 + b = [1] * 24 + [0] * 16 + ids_a = [f"a{i // 8}" for i in range(40)] + ids_b = [f"b{i // 8}" for i in range(40)] + rows = compare(a, b, paired=False) + groups = compare(a, b, paired=False, cluster_by=(ids_a, ids_b)) + assert rows.method == "two-sample bootstrap (unpaired)" + assert groups.method == "clustered bootstrap (unpaired)" + assert groups.details["n_clusters"] == 10 + assert rows.effect == pytest.approx(groups.effect) == pytest.approx(0.4) + assert rows.reject is True # looks like a finding row by row + assert groups.reject is False # and is not one, item by item + assert (groups.ci[1] - groups.ci[0]) > 1.5 * (rows.ci[1] - rows.ci[0]) + assert groups.details["p_value"] > 0.05 > rows.details["p_value"] + + +def test_a_flat_cluster_sequence_is_still_ignored_for_unpaired(): + a, b = [0, 0, 1, 0], [1, 1, 0, 1, 1] + plain = clustered_bootstrap_diff(a, b, paired=False, seed=3) + flat = clustered_bootstrap_diff(a, b, clusters=list(range(9)), paired=False, seed=3) + assert "n_clusters" not in flat + assert (flat["ci_low"], flat["ci_high"]) == (plain["ci_low"], plain["ci_high"]) + + +def test_exact_p_matches_hand_counts_and_one_sided_halves(): + # 4 failures against 4 passes, cleanly split: 2 of the C(8, 4) = 70 tables. + assert two_group_exact_p(0, 4, 4, 4) == pytest.approx(2 / 70) + assert two_group_exact_p(0, 4, 4, 4, "greater") == pytest.approx(1 / 70) + assert two_group_exact_p(0, 4, 4, 4, "less") == pytest.approx(1.0) + assert two_group_exact_p(2, 10, 2, 10) == pytest.approx(1.0) + assert two_group_exact_p(0, 0, 3, 5) == 1.0 + with pytest.raises(ValueError): + two_group_exact_p(1, 2, 1, 2, "sideways") + + +def _null_rows(seed: int, n_groups: int = 80): + """No effect of the flag; rows of a group share an outcome tendency, and + the flag is a property of the whole group.""" + rng = random.Random(seed) + y, arm, clusters = [], [], [] + for g in range(n_groups): + p = 0.9 if rng.random() < 0.5 else 0.1 + flagged = rng.random() < 0.4 + for _ in range(rng.randint(3, 9)): + y.append(1.0 if rng.random() < p else 0.0) + arm.append(1.0 if flagged else 0.0) + clusters.append(g) + return np.array(y), np.array(arm), clusters + + +def test_ignoring_groups_inflates_false_positives_and_clustering_restores_them(): + # The reason the group column matters: under no effect at all, treating + # correlated rows as independent rejects far more often than 5%. + naive = clustered = 0 + runs = 120 + for seed in range(runs): + y, arm, clusters = _null_rows(seed) + stat = mean_difference_statistic(y, arm) + independent = weighted_bootstrap(stat, len(y), n_boot=300, seed=seed) + grouped = weighted_bootstrap(stat, len(y), clusters=clusters, n_boot=300, seed=seed) + naive += bootstrap_p_value(independent["draws"]) <= 0.05 + clustered += bootstrap_p_value(grouped["draws"]) <= 0.05 + assert naive / runs > 0.25 + assert clustered / runs < 0.12 diff --git a/tools/check_holdout_calibration.py b/tools/check_holdout_calibration.py new file mode 100644 index 00000000..4b8bf491 --- /dev/null +++ b/tools/check_holdout_calibration.py @@ -0,0 +1,189 @@ +"""Check the held-out comparison designs against data with a known answer. + +Usage: + python tools/check_holdout_calibration.py [--runs 400] [--n-boot 1000] + +Two questions, both answered by simulation because neither can be answered by +a unit test on one dataset: + +1. When nothing is going on, how often does a comparison come out + "significant"? It should be about 5%. The script draws data in which a flag + has no effect at all but rows cut from one source item share an outcome + tendency, and counts rejections with and without the group column. +2. When something is going on, does the 95% interval contain the true effect + about 95% of the time? The script draws data with a known effect for each + design (two-group, stratified, difference in differences, dose-response) + and counts how often the interval covers it. + +A third part runs the keyword pipeline end to end: words are chosen on an +exploration half and re-tested on the rest, on text with one real keyword and +six filler words, and the script counts how often a filler is accepted. + +It prints one table per part. No model and no network are needed. +""" + +from __future__ import annotations + +import argparse +import math +import random + +from evalrx.analysis.holdout import holdout_confirm, outcome_values, split_records +from evalrx.analysis.holdout_designs import estimate_design +from evalrx.analysis.keywords import keyword_candidates +from evalrx.analysis.operationalize import SignalRecipe + + +def _bernoulli(rng: random.Random, p: float) -> float: + return 1.0 if rng.random() < p else 0.0 + + +def null_data(seed: int, flag_level: str, n_groups: int = 120): + """No effect of ``f``. Rows of a group share a failure tendency.""" + rng = random.Random(seed) + rows, y, groups = [], [], [] + for g in range(n_groups): + tendency = 1.0 / (1.0 + math.exp(-(-0.5 + rng.gauss(0.0, 1.2)))) + group_flag = rng.random() < 0.4 + for _ in range(rng.randint(2, 10)): + flag = group_flag if flag_level == "group" else rng.random() < 0.4 + rows.append({"f": int(flag)}) + y.append(_bernoulli(rng, tendency)) + groups.append(g) + return rows, y, groups + + +def effect_data(seed: int, design: str, n_groups: int = 150): + """Data with a known effect for *design*; returns rows, outcome, groups, truth, recipe.""" + rng = random.Random(seed) + rows, y, groups = [], [], [] + for g in range(n_groups): + shift = rng.gauss(0.0, 0.08) # group-level shift in the failure rate + stratum = "weak" if rng.random() < 0.5 else "strong" + modifier = int(rng.random() < 0.5) + for _ in range(rng.randint(2, 8)): + if design == "two_group": + flag = int(rng.random() < 0.4) + p = 0.25 + 0.20 * flag + row = {"f": flag} + elif design == "stratified": + # The flag is far more common in the stratum that fails more; + # within a stratum it adds 0.10. + flag = int(rng.random() < (0.75 if stratum == "weak" else 0.25)) + p = (0.50 if stratum == "weak" else 0.15) + 0.10 * flag + row = {"f": flag, "s": stratum} + elif design == "did": + flag = int(rng.random() < 0.5) + p = 0.20 + 0.05 * flag + 0.05 * modifier + 0.25 * flag * modifier + row = {"f": flag, "m": modifier} + else: # dose_response: +0.12 per bin over three bins + score = rng.random() + step = (score > 1 / 3) + (score > 2 / 3) + p = 0.20 + 0.12 * step + row = {"score": score} + rows.append(row) + y.append(_bernoulli(rng, min(max(p + shift, 0.01), 0.99))) + groups.append(g) + recipes = { + "two_group": (SignalRecipe(name="r", expr="f == 1"), 0.20), + "stratified": (SignalRecipe(name="r", expr="f == 1", design="stratified", + strata=["s"]), 0.10), + "did": (SignalRecipe(name="r", expr="f == 1", design="did", modifier="m == 1"), 0.25), + "dose_response": (SignalRecipe(name="r", expr="score", bins=[1 / 3, 2 / 3]), 0.12), + } + recipe, truth = recipes[design] + return rows, y, groups, truth, recipe + + +def keyword_data(seed: int, n_groups: int = 120) -> list[dict]: + """Clips of 3-7 rows. "timeout" marks failures; the other words mark nothing.""" + rng = random.Random(seed) + rows: list[dict] = [] + for g in range(n_groups): + clip_fails = rng.random() < 0.5 + for _ in range(rng.randint(3, 7)): + fail = clip_fails if rng.random() < 0.9 else not clip_fails + filler = rng.choice(["alpha beta", "gamma delta", "epsilon zeta"]) + rows.append({ + "clip": f"clip{g}", + "note": ("timeout " if fail and rng.random() < 0.6 else "") + filler, + "label": "fail" if fail else "pass", + }) + return rows + + +def keyword_runs(runs: int, n_boot: int) -> tuple[float, float, float]: + """(share of runs accepting a filler, mean false share, share finding the real word).""" + any_false, found, false_share = 0, 0, 0.0 + for seed in range(runs): + rows = keyword_data(20_000 + seed) + explore, held_out = split_records(rows, 0.4, seed=seed, outcome_col="label", + group_col="clip") + assert held_out is not None + side = outcome_values(explore, "label")[0] + report = {"candidate_signals": [c.to_dict() for c in + keyword_candidates(explore, "note", side)], + "hypotheses": []} + confirm = holdout_confirm(report, held_out, outcome_col="label", + group_col="clip", n_boot=n_boot, seed=seed) + held = [v["name"] for v in confirm["signal_verdicts"] + if (v.get("claim") or {}).get("status") == "holds"] + false = [name for name in held if name != "kw_timeout"] + any_false += bool(false) + found += "kw_timeout" in held + false_share += len(false) / len(held) if held else 0.0 + return any_false / runs, false_share / runs, found / runs + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--runs", type=int, default=400) + parser.add_argument("--n-boot", type=int, default=1000) + args = parser.parse_args() + runs, n_boot = args.runs, args.n_boot + half_width = 1.96 * math.sqrt(0.05 * 0.95 / runs) + + print(f"1. False positives under no effect (target 0.050, runs={runs}, " + f"simulation error about +/-{half_width:.3f})") + print(f" {'flag varies by':<16}{'rows independent':>18}{'group column':>14}") + recipe = SignalRecipe(name="f", expr="f == 1") + for level in ("group", "row"): + rates = [] + for use_groups in (False, True): + rejections = 0 + for seed in range(runs): + rows, y, groups = null_data(seed, level) + est = estimate_design(recipe, rows, y, n_boot=n_boot, seed=seed, + clusters=groups if use_groups else None) + rejections += (est.p_value or 1.0) <= 0.05 + rates.append(rejections / runs) + print(f" {level:<16}{rates[0]:>18.3f}{rates[1]:>14.3f}") + + print(f"\n2. Coverage of the 95% interval when the effect is known (target 0.950, " + f"runs={runs})") + print(f" {'design':<16}{'true effect':>12}{'mean estimate':>15}{'coverage':>10}" + f"{'unadjusted':>12}") + for design in ("two_group", "stratified", "did", "dose_response"): + covered, total, unadjusted = 0, 0.0, 0.0 + for seed in range(runs): + rows, y, groups, truth, design_recipe = effect_data(10_000 + seed, design) + est = estimate_design(design_recipe, rows, y, clusters=groups, + n_boot=n_boot, seed=seed) + assert est.ok and est.ci is not None and est.effect is not None, est.reason + covered += est.ci[0] <= truth <= est.ci[1] + total += est.effect + unadjusted += est.details.get("unadjusted_difference", float("nan")) + extra = f"{unadjusted / runs:>12.3f}" if design == "stratified" else f"{'':>12}" + print(f" {design:<16}{truth:>12.3f}{total / runs:>15.3f}{covered / runs:>10.3f}{extra}") + + keyword_n = max(50, runs // 2) + any_false, false_share, found = keyword_runs(keyword_n, n_boot) + print(f"\n3. Keyword recipes chosen on one half and re-tested on the other " + f"(runs={keyword_n})") + print(f" real keyword accepted: {found:.3f}") + print(f" runs in which a filler word was accepted: {any_false:.3f}") + print(f" mean share of accepted keywords that were filler: {false_share:.3f}") + + +if __name__ == "__main__": + main()