Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(signals): correct scout trial judging and partial results (#115000)

Alex Lebedev9d4bb2f2b676
diff --git a/docs/internal/scout-online-evals-devbox.md b/docs/internal/scout-online-evals-devbox.md
index 7443f655a4a7..04b6b7b553c7 100644
--- a/docs/internal/scout-online-evals-devbox.md
+++ b/docs/internal/scout-online-evals-devbox.md
@@ -49,7 +49,7 @@ The rubric stays fixed across scout edits, and saved results retain the rubric u
History shows 30 trials per page, with previous and next controls for older results. Archive a completed or failed trial to hide it from history. Show archived trials to view their saved reports or restore them; archiving never deletes evidence or stops a running trial. Archive and restore remain available when the trials flag is off, with the same access checks. Open a trial to see its individual runs. Run-detail loading errors appear beside the affected run with a retry action, while the history page continues to show saved results.
-Trial scouts have a 30-minute runtime limit. Regular scouts keep their 15-minute limit. Timed-out scouts cannot be scored; start a new trial to try again.
+Trial scouts have a 30-minute runtime limit. Regular scouts keep their 15-minute limit. Timed-out scouts cannot be scored; their run details and scoring exclusion explain the timeout. Start a new trial to try again.
Trial scout deadlines include five minutes for startup and log reads, plus time to collect and save the final result.
@@ -73,6 +73,8 @@ The judge has no live project tools, external MCP connections or repository cred
The judge saves one JSON verdict per rubric check through Tasks' existing structured-output support. Signals checks that same Task until it finishes, then validates its quotes against the original saved files. New evaluations use saved scout identifiers to recheck current permissions on every status poll without downloading the full starting context again; preparation and report finalization still validate that context. Worker restarts resume result collection without starting another judge. If result collection remains unavailable, the evaluation fails without freezing an incomplete report; resuming the same evaluation reuses its Tasks and saved judgments.
-Missing evidence gives an unknown verdict. A judge failure is shown separately from a failed rubric check, and incomplete results cannot win. Each judge has a 30-minute deadline measured from its original Task run creation; retries do not reset it. Up to three collectors run at once, but judge Tasks can briefly overlap beyond that after a delayed start or collection failure. Saved results never rerun the judge when viewed.
+Unavailable or ambiguous evidence gives an unknown verdict. A required action proved missing from a complete record fails; missing thoughts alone never prove an omission. Citation checks accept decoded JSON string fields in tool responses. A judge failure is shown separately from a failed rubric check. Each judge has a 30-minute deadline measured from its original Task run creation; retries do not reset it. Up to three collectors run at once, but judge Tasks can briefly overlap beyond that after a delayed start or collection failure. Saved results never rerun the judge when viewed.
+
+Only versions whose runs all completed and were judged can lead. At least two completed versions with the same number of runs are needed; failed versions remain visible and are excluded even if most versions failed. The result compares completed versions by their total confirmed rubric passes. Unknown checks earn no passes and make any leader or tie provisional. Without a confirmed pass, unresolved checks cannot produce a leader. Final winners still require comparable applicable checks. Saved reports retain their original conclusions.
Before dispatch, the full batch must fit the project's existing daily scout budget. Resuming counts only runs that have not already started. This is a capacity check, not a reservation: simultaneous submissions can still race, and the budget remains shared with ordinary scouts.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index a1dc2542acbb..3e5fa56f69f4 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -11251,25 +11251,29 @@ snapshots:
scenes-app-inbox-scene--triage--light:
hash: v1.k794b7964.ea1f0a1a3cd9c029a33e39277a276be15a04555ba2addee17df2aacb108316dc.CFYN_7EjRWTlSCsBQMuZ6Bq_ViTyRy7_RqqtqKfg05w
scenes-app-inbox-scout-comparison-report--completed--dark:
- hash: v1.k794b7964.bde7c95ff4b10a7207a1033be8371299db8262535dfef24f00bf468e3b3a416a.XxO2bLTKsm0AfRGuhA8QmEsAIZ5zVrc4RnCUjCUFkHA
+ hash: v1.k794b7964.179dd1ea74dfa1727c501df365f491d5bb9246bfc731ac4821594687795197b1.Za7jkz_YuKW0eyjzp928-Hv652aROII5i6Da4dNfiuk
scenes-app-inbox-scout-comparison-report--completed--light:
- hash: v1.k794b7964.dc0fcac6f32410ab6f48dbde7a7f8535d2e07c00304d7ee1d67ca46a8d6c5ac3.wBBNQAPhU2qmCqkPQGmdT-PoBxTK4C0J14FZ5poX3BY
+ hash: v1.k794b7964.e7398105251db112e826ace5c21e53dbbfdddc0cc887fff863a16f575fe54586.Vc46v16nqaDOa0f3VbK7zbt3ahVLhx7rED1EsPOEMj8
scenes-app-inbox-scout-comparison-report--narrow--dark:
- hash: v1.k794b7964.5a22eb71a5dd3da5c533ac95dc4b7009e2a60c4c1c78635e566217d2fd9c86b4.Xgvw0yjUAWv1-Gdf2etryIStyoUk_IrgyQ11R6b7WLc
+ hash: v1.k794b7964.0b722f01c41e9b7e9e8823ca857cb8782bea1fd2713bd3a330d440e0fcf6d58f.g3f4yzApbydGHiCibYpLdrMgCHA4nOzWvecVVYg-3Ow
scenes-app-inbox-scout-comparison-report--narrow--light:
- hash: v1.k794b7964.2c0501903d8ed72ebab9d02dd5be7f03f687299fb5ad7de77cf173a9a3ca80fc.9zReQkI-0ZxtevUGUcU4SYtmtzPLMdGdxGQZfjo-Xa4
+ hash: v1.k794b7964.27703f41510e44bad576f483f5a04ac876db43c6db8c283449bb0f5251955ef2.cHm2wLfRefIf3YXBjtKWAlxlcWJZEgq6pvCLOlfuUNs
scenes-app-inbox-scout-comparison-report--partial-evidence--dark:
- hash: v1.k794b7964.fe60099df1ca0a9a610373d966a407eeb3655ecca44cf46f8722892174184eab.MCXzX2YcEtebuMRjg6Sj3LVn_tnrcVl4UeNam07cF-k
+ hash: v1.k794b7964.1cd1b5e035f195d6023f8a5c1b59ab71fe465e6eae00e2444fe71650d9a18385.HGq5YE07MKzc9jNJJ5Xne8p6qLOehObGOtUSrTR04uc
scenes-app-inbox-scout-comparison-report--partial-evidence--light:
- hash: v1.k794b7964.6316ef24a6e8455a9b9339fd58f25e4c54e21bfb5a9c3bf062bebdcadd319740.Cb-zIyn8aVctoHeuSZ7AtTit8fXzy01Be5qyvqS-3nA
+ hash: v1.k794b7964.7b55abae9d62bc53a010d56f66413e5fee268bde0bc19045b33e37c3970dac48.y0VvP-2kaonTzXDOqeYWLe6lGEBxeeDBl0AVLh3nS1E
+ scenes-app-inbox-scout-comparison-report--provisional-with-excluded-version--dark:
+ hash: v1.k794b7964.0d7ae222506ca576820ae512573a9961f23621ef1aac4f01e8685a92ab357cf8.RBWWgKPSKpyY5COAQVvzy-HH3GBhV4wTSqtLp0RU-NU
+ scenes-app-inbox-scout-comparison-report--provisional-with-excluded-version--light:
+ hash: v1.k794b7964.f12a66d7718ac7299e2b91badaa7db4e7f93fb2396a39085c76cf33739dbca1b.7tsk8_48ZxaPEWnBZZOI8xTV1OfhBSL5Q9A0m-xCDU4
scenes-app-inbox-scout-comparison-report--saved-rubric--dark:
hash: v1.k794b7964.edf4ea65e1743e44f4663a240839da906759cfeffe7c560ef6d24dbc22970b4c.sAyj4yU32EkApd-4Qhbfg-nz77whdSP6lhWQD_liOEU
scenes-app-inbox-scout-comparison-report--saved-rubric--light:
hash: v1.k794b7964.bb9005e232996137b1dec470fa5b624688f6a6b3fc1b606adefbc04ce0a72b9f.CeQcqzk3v9BzPAG89Ni2LfSa1CyGaYRu0jdGtitxtm0
scenes-app-inbox-scout-comparison-report--saved-without-conclusion--dark:
- hash: v1.k794b7964.0d1a9e9aefe758b2c97a26442b074852b9f35a7e0d843593cf9298c079baebed.dsF6SLjVkfLUFGR1Lq74klXKfjZPZuZ0F5Z8PqGzIuU
+ hash: v1.k794b7964.4522023356b6af7a16c6429605a4ea4bf7c4572a62c0f0bff09982b4d221778c.kQoI6T92e7vCtPh_nUryhesPm57wfcrDDzgqGeNKSW8
scenes-app-inbox-scout-comparison-report--saved-without-conclusion--light:
- hash: v1.k794b7964.38db646ee23535c2dd81f98471fe1417f29a7f41b55488a588d5924828660aa2.9lVtt8JtGs3ZH91m4Qpwk41zi9PgZ3_hlbl4q_J9-EQ
+ hash: v1.k794b7964.8edca2f2456d3a59383a48e141482abdd3275126e8eedac8c74e2ef45bccbd4a.kEpxgx15rO56AVfNkUrqW5x2RvHfvpRdXJEc8hWQfhU
scenes-app-inbox-scout-comparison-report--tie--dark:
hash: v1.k794b7964.6d08f0cf00174dc5964dbb7d030611e3098e307488c1a20472bc8ce936bad486.LnUvn3vfMEls6MYNg72smDhEA8SmeBCyIZCVAfJCS0Y
scenes-app-inbox-scout-comparison-report--tie--light:
@@ -11279,9 +11283,9 @@ snapshots:
scenes-app-inbox-scout-comparison-report--twelve-rubrics--light:
hash: v1.k794b7964.eeedea24a43ca2e8f1a654068902ae9fd84e04c5b23e189c15b01c1d0cdec2fa.qkHuAqtowa1Kvp0hzRvgtRsZ8Ye38t54Uih4pEHfZU4
scenes-app-inbox-scout-comparison-report--twelve-rubrics-narrow--dark:
- hash: v1.k794b7964.9cf8176ad44b0563ecc481e6efefde6f516c9ddc2d2a973e3cf9d8ade0bccb0e.ERV9ltQ2LPFqcLeFW1MrxcOXLWYFmwZgm73uqyE4aAI
+ hash: v1.k794b7964.8f05613b90ffd12b5ea9d96bf1289cd01e690db478991299c0f01b919dcb92d3.LwEf7QT12U6UfASYb_htyt3XWanp7yH4-_CJ5E54xFw
scenes-app-inbox-scout-comparison-report--twelve-rubrics-narrow--light:
- hash: v1.k794b7964.481b6146b8c00208b408cee3bc04af2674277a2ed91e7d66665077671afaed07.a8lIdTdMTxzmGA7VPzBP6cKlTfjTXa5SJ540vbfN_BQ
+ hash: v1.k794b7964.076433eef997e3f5e347f93153346b94c588bf13551891c1775d14c10dcae083.Z0ORivTB1k4pqMR2KKLJvYRsp5R9y3ccHwYlO2w4XFM
scenes-app-inbox-scout-comparisons--archived--dark:
hash: v1.k794b7964.d79efd52758535007dda391ffa79c431fc723269aa9063f13953ac53d933b20d.g0dlEEoVoPSiCLJbBapVwSmLN4GjGPBRdG1XMYPDHaE
scenes-app-inbox-scout-comparisons--archived--light:
@@ -11315,9 +11319,9 @@ snapshots:
scenes-app-inbox-scout-comparisons--many-rubrics--light:
hash: v1.k794b7964.5df26dccf7b8cf5960878c5faf5f6cd6a837f073d086b2db497003db8b66fbd2.SowFWB7XSAu_5YPzXHAAfVMWJgjxdm5rdPqVtCDN1lM
scenes-app-inbox-scout-comparisons--many-rubrics-narrow--dark:
- hash: v1.k794b7964.202841a7046db4a42fd3f1864a57a4d55fdcd1dbbb4bfc9e93a0b14232fd9560.tFEFTbkmVxeRo9Oo0WhdxJ_wciCqkTm1dHj1kePcFUQ
+ hash: v1.k794b7964.07cf23c3ccd2e941f51a4b03bcfc8bb299c52a9712f0cabbba5b91b337664aa6.poWGr1HgHlHgaPyXwQUZEGzkBjCAirrOQMz0B4nBLpU
scenes-app-inbox-scout-comparisons--many-rubrics-narrow--light:
- hash: v1.k794b7964.500612a262e5118f23af173c0f4b53a69503547df712d58a8c3a2be4a6b195f1.JonL4M9GYQJG9purie4YtY-dShjDCJnTmtyoDYf0FqY
+ hash: v1.k794b7964.b81d371227d8991407f9727a959efb7938efb3a9ff8bfbee99f360739e66f2cb._CKv0b9ATcip28P3ahjCz32p7ADxn5V7_vP20cVL5Hs
scenes-app-inbox-scout-comparisons--missing-saved-rubric--dark:
hash: v1.k794b7964.18496b515d6b92e96e151b1ff428bfba92de3df56de9488385a01e58eeeecf45.RcI6PYNWzHreMfFiMqEfmMakjX_JcL68vipa9kT1xUA
scenes-app-inbox-scout-comparisons--missing-saved-rubric--light:
@@ -11343,13 +11347,13 @@ snapshots:
scenes-app-inbox-scout-comparisons--scored--light:
hash: v1.k794b7964.f3a5e2f20df24053c5e6d93457d7c9b69d6197d22b9abbe6eab61e272c14d58d.et8rU3sDnPRmqFfRB86FwixaOOb0kl4xTV-SOn5vWi8
scenes-app-inbox-scout-comparisons--scored-narrow--dark:
- hash: v1.k794b7964.8e9213a5f9628415367afd7564f156eae7666f832dbde6e863833b78a40c4ada.PAy7h5uc8-VBeYUrUFVcGZkJJ2g50aFFFa6khQM4GSE
+ hash: v1.k794b7964.f17eb0d85051d08f552bc5ef543f309a9951c0be2852ae81fa06a28b03ce11e7.FJdjU5Gvs48DWcZA6A0escqWNtac_Miiilm2CyrQf5E
scenes-app-inbox-scout-comparisons--scored-narrow--light:
- hash: v1.k794b7964.f0437cc149985372ae4f679d50bf9876b38da564f68c0536b727462db36747db.TUIkBdQJfAA0VIhuUq8z5PY0rlOhu_Nuw9CIXFs9Pz4
+ hash: v1.k794b7964.5f370c42175efce684a7e7246df9af19698d53115700e989b2268254158b88ca.icD-fL0YTCapszPCVx5QJd4repcs8RH3V6rTIF8yIHU
scenes-app-inbox-scout-comparisons--scored-with-judge-error--dark:
- hash: v1.k794b7964.c93b40e3960f14f2b3df60e2e61a310d76623ca2267555fb25a65f21c477e2e3.iqftelzyEFEDXeW5QR1myZ8Kyck5NH7SUGMpj0_szoo
+ hash: v1.k794b7964.1af9bb1e7afb827890571bb8bb143e22015c2f4a5d5bffc1d54a26a67b1aabfb.OvxVezL_rV4dkKf1jVrdQ4QSKBF6pj2DcYkuYG8T9WI
scenes-app-inbox-scout-comparisons--scored-with-judge-error--light:
- hash: v1.k794b7964.04eab8f290c46ca9245d105742f1a30f832142b803d7330ca0b1d3ca28a1300a.qMmsG_g2u-KuRuVzEeQE_0ywkQvNLqrDfG_AsX8lVhQ
+ hash: v1.k794b7964.1d549fc936129c623ba890fac6e6302aa8d8e1cf1c87e2bf77d3907470bd8307.J5ls_C0HKe7ORijl6pmPXV_TkDBNkhU9llUAZQqs6VU
scenes-app-inbox-scout-comparisons--scoring--dark:
hash: v1.k794b7964.8520822da584372a1269788304b1b2c6876ddfe0e6394fa1d152fb041595e2e1.eF-e2oYCBolypY5GadwqVJGj3QQj6Ubk4kqGcCBHkBo
scenes-app-inbox-scout-comparisons--scoring--light:
diff --git a/products/signals/backend/scout_harness/trial_evaluation.py b/products/signals/backend/scout_harness/trial_evaluation.py
index 9d6ee07983b1..d421c1a9da9a 100644
--- a/products/signals/backend/scout_harness/trial_evaluation.py
+++ b/products/signals/backend/scout_harness/trial_evaluation.py
@@ -55,6 +55,7 @@ from products.signals.backend.scout_harness.trial_result import (
get_trial_workflow_status,
read_trial_result,
recover_trial_result,
+ trial_timeout_error,
)
from products.signals.backend.scout_harness.trial_rubrics import SavedScoutRubricReader, ScoutRubricReadError
from products.signals.backend.scout_harness.trial_state import ScoutTrialStore
@@ -443,11 +444,16 @@ def _run_evidence(
if status not in {"completed", "failed", "cancelled", "skipped"} or (run is None and status == "completed"):
raise TrialEvaluationNotReady("Every selected trial must have a known terminal state before scoring.")
if run is not None:
- run.task_run.refresh_from_db(fields=["status", "state"])
+ run.task_run.refresh_from_db(fields=["status", "state", "error_message"])
if run.task_run.status not in {"completed", "failed", "cancelled"}:
raise TrialEvaluationNotReady("Every selected trial task must finish before scoring.")
if status == "completed":
status = run.task_run.status
+ exclusion_reason = None
+ if status != "completed":
+ exclusion_reason = (
+ trial_timeout_error(run, status=status) if run is not None else None
+ ) or "The trial did not complete successfully."
evidence = TrialRunEvidence(
launch_id=launch.id,
variant_id=variant_id,
@@ -455,7 +461,7 @@ def _run_evidence(
task_id=run.task_run.task_id if run else None,
task_run_id=run.task_run_id if run else None,
execution_status=status,
- exclusion_reason=None if status == "completed" else "The trial did not complete successfully.",
+ exclusion_reason=exclusion_reason,
model=launch.model,
runtime_adapter=launch.runtime_adapter,
reasoning_effort=launch.reasoning_effort,
diff --git a/products/signals/backend/scout_harness/trial_evaluation_report.py b/products/signals/backend/scout_harness/trial_evaluation_report.py
index 0602368deb36..0cd130a4b3f3 100644
--- a/products/signals/backend/scout_harness/trial_evaluation_report.py
+++ b/products/signals/backend/scout_harness/trial_evaluation_report.py
@@ -43,42 +43,65 @@ def _overall_comparable(variant: TrialVariantAggregate, baseline: TrialVariantAg
def _comparison_outcome(variants: list[TrialVariantAggregate]) -> TrialComparisonOutcome:
+ completed = [
+ variant
+ for variant in variants
+ if variant.total_runs > 0
+ and variant.judged_runs == variant.total_runs
+ and not variant.excluded_runs
+ and not variant.judge_errors
+ ]
+ excluded = len(variants) - len(completed)
+ exclusion = (
+ f" {excluded} of {len(variants)} versions excluded because not every run completed and was judged."
+ if excluded
+ else ""
+ )
+ unknown = any(criterion.unknown for variant in completed for criterion in variant.criteria)
reason: str | None = None
- if len(variants) < 2:
- reason = "Compare at least two variants to find the best result."
- elif any(variant.judged_runs != variant.total_runs for variant in variants):
- reason = "Some runs failed, were stopped, or could not be judged. Complete those runs before choosing a winner."
- elif any(criterion.unknown for variant in variants for criterion in variant.criteria):
- reason = "Some rubric checks need more evidence. The results are incomplete, so a higher pass rate may be misleading."
- elif any(variant.score is None for variant in variants):
+ if len(completed) < 2:
+ reason = "Not enough completed versions to compare. At least two versions must complete every run and judging."
+ elif all(variant.score is None for variant in completed):
reason = "There are not enough applicable rubric checks to compare these variants."
- elif len({variant.total_runs for variant in variants}) != 1:
+ elif len({variant.total_runs for variant in completed}) != 1:
reason = "The variants have different numbers of runs. Use the same number of runs for a fair comparison."
- elif any(not _overall_comparable(variant, variants[0]) for variant in variants):
+ elif not unknown and any(not _overall_comparable(variant, completed[0]) for variant in completed):
reason = "Different rubric checks applied to these runs. Their pass rates cannot be compared fairly."
if reason is not None:
- return TrialComparisonOutcome(status="inconclusive", summary=reason)
+ return TrialComparisonOutcome(status="inconclusive", summary=reason + exclusion)
passed_counts = {
- variant.variant_id: sum(criterion.passed for criterion in variant.criteria) for variant in variants
+ variant.variant_id: sum(criterion.passed for criterion in variant.criteria) for variant in completed
}
passed = max(passed_counts.values())
- leaders = [variant for variant in variants if passed_counts[variant.variant_id] == passed]
+ leaders = [variant for variant in completed if passed_counts[variant.variant_id] == passed]
+ if unknown and passed == 0:
+ return TrialComparisonOutcome(
+ status="inconclusive",
+ summary="No version has a confirmed rubric pass, and some checks remain unknown." + exclusion,
+ )
assessed = sum(criterion.passed + criterion.failed for criterion in leaders[0].criteria)
runs = leaders[0].total_runs
run_label = "run" if runs == 1 else "runs"
- if len(leaders) == 1:
+ if unknown:
+ names = ", ".join(variant.label for variant in leaders)
+ position = "has" if len(leaders) == 1 else "are tied for"
+ summary = (
+ f"{names} {position} the most confirmed passes: {passed} across {runs} {run_label}. "
+ "This result is provisional: unknown checks earn no passes and could change the result when resolved."
+ )
+ elif len(leaders) == 1:
summary = (
f"{leaders[0].label} passed the most rubric checks: {passed} of {assessed} "
- f"across {runs} {run_label}. Every variant was judged on the same applicable checks."
+ f"across {runs} {run_label}. Compared versions were judged on the same applicable checks."
)
else:
names = ", ".join(variant.label for variant in leaders)
summary = f"{names} tied: each passed {passed} of {assessed} rubric checks across {runs} {run_label}."
return TrialComparisonOutcome(
- status="winner" if len(leaders) == 1 else "tie",
+ status="provisional" if unknown else "winner" if len(leaders) == 1 else "tie",
variant_ids=[variant.variant_id for variant in leaders],
- summary=summary,
+ summary=summary + exclusion,
)
@@ -205,6 +228,7 @@ def build_trial_comparison_report(
runs=scored,
evidence=snapshot.runs,
limitations=[
+ "Only versions with every run completed and judged can lead. At least two completed versions with the same number of runs are required; unknown checks earn no passes and make the result provisional.",
"Each run scores pass verdicts divided by pass and fail verdicts. Variant scores average runs with a decisive score; unknown and not applicable verdicts are excluded.",
"Rubric coverage is the fraction of applicable verdicts that are pass or fail. Execution failures and judge errors are listed separately.",
"The best result describes these runs only. It does not establish statistical significance or guarantee the same result on other data.",
diff --git a/products/signals/backend/scout_harness/trial_evaluation_types.py b/products/signals/backend/scout_harness/trial_evaluation_types.py
index ec8ce18a57fb..efa89004e654 100644
--- a/products/signals/backend/scout_harness/trial_evaluation_types.py
+++ b/products/signals/backend/scout_harness/trial_evaluation_types.py
@@ -92,7 +92,7 @@ class TrialVariantAggregate(EvaluationDocument):
class TrialComparisonOutcome(EvaluationDocument):
- status: Literal["winner", "tie", "inconclusive"]
+ status: Literal["winner", "tie", "provisional", "inconclusive"]
variant_ids: list[UUID] = Field(default_factory=list)
summary: str
diff --git a/products/signals/backend/scout_harness/trial_judge.py b/products/signals/backend/scout_harness/trial_judge.py
index 3c322efff224..ac7744e44a8b 100644
--- a/products/signals/backend/scout_harness/trial_judge.py
+++ b/products/signals/backend/scout_harness/trial_judge.py
@@ -244,7 +244,8 @@ async def judge_trial_run(snapshot: TrialEvaluationSnapshot, evidence: TrialRunE
if output is None or not _has_assessment(output):
raise TrialJudgeExecutionError("The judge finished without saving its structured assessment.")
sources = await asyncio.to_thread(read_trial_evidence_sources, snapshot, evidence)
- verdicts = parse_trial_judgment(
+ verdicts = await asyncio.to_thread(
+ parse_trial_judgment,
json.dumps({"summary": output["summary"], "criteria": output["criteria"]}, ensure_ascii=False),
criteria=snapshot.criteria,
sources=sources,
diff --git a/products/signals/backend/scout_harness/trial_result.py b/products/signals/backend/scout_harness/trial_result.py
index 138b0c54d77d..9aecf7568cdb 100644
--- a/products/signals/backend/scout_harness/trial_result.py
+++ b/products/signals/backend/scout_harness/trial_result.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import re
import json
import asyncio
import hashlib
@@ -26,6 +27,22 @@ MAX_TRIAL_RESULT_BYTES = 4 * 1024 * 1024
_RUNTIME_FIELDS = ("runtime_adapter", "model", "reasoning_effort", "service_tier")
+def trial_timeout_error(run: SignalScoutRun, *, status: str) -> str | None:
+ if status != "failed" or run.task_run.status != "failed":
+ return None
+ # Only this fixed poll error is safe to surface; other Task errors can contain private source text.
+ match = re.fullmatch(
+ r"custom_prompt - poll_for_turn: timed out after ([1-9][0-9]{0,5})s "
+ r"\(stage=(?:no_turn_output|stalled_after_output|active_at_budget)\)",
+ run.task_run.error_message or "",
+ )
+ if match is None:
+ return None
+ minutes = max(1, round(int(match[1]) / 60))
+ unit = "minute" if minutes == 1 else "minutes"
+ return f"The scout timed out after about {minutes} {unit}. This run was not judged."
+
+
@frozen
class TrialWorkflowStatus:
status: Literal["pending", "completed", "skipped", "failed", "cancelled", "not_started", "unknown"]
diff --git a/products/signals/backend/scout_harness/trial_views.py b/products/signals/backend/scout_harness/trial_views.py
index 6574c3f81e16..3d75aa1f82d3 100644
--- a/products/signals/backend/scout_harness/trial_views.py
+++ b/products/signals/backend/scout_harness/trial_views.py
@@ -45,6 +45,7 @@ from products.signals.backend.scout_harness.trial_result import (
read_trial_result,
recover_trial_result,
trial_result_key,
+ trial_timeout_error,
)
from products.signals.backend.scout_harness.trial_serializers import (
ScoutTrialHistoryQuerySerializer,
@@ -239,7 +240,7 @@ class ScoutTrialConfigMixin(ScoutTrialComparisonMixin):
invalid_reason = TRIAL_DATA_UNAVAILABLE_REASON
if saved_result is None:
workflow = get_trial_workflow_status(team_id=config.team_id, launch_id=launch.id)
- error = workflow.error
+ error = (trial_timeout_error(run, status=workflow.status) if run is not None else None) or workflow.error
if run is None:
trial_status = "pending" if workflow.status == "completed" and workflow.run_id else workflow.status
else:
@@ -269,13 +270,14 @@ class ScoutTrialConfigMixin(ScoutTrialComparisonMixin):
saved_summary = saved_result.get("summary")
if isinstance(saved_summary, str):
summary = saved_summary
- run.task_run.refresh_from_db(fields=["status", "state", "completed_at"])
+ run.task_run.refresh_from_db(fields=["status", "state", "completed_at", "error_message"])
if trial_status == "completed":
if run.task_run.status not in {"completed", "failed", "cancelled"}:
trial_status = "in_progress"
elif run.task_run.status != "completed":
trial_status = run.task_run.status
error = "The scout task stopped before completion."
+ error = trial_timeout_error(run, status=trial_status) or error
if private is not None:
try:
private = ScoutTrialStore(run).export()
diff --git a/products/signals/backend/test/test_scout_trial_evaluation.py b/products/signals/backend/test/test_scout_trial_evaluation.py
index 93dde0c708c0..f0bddd932464 100644
--- a/products/signals/backend/test/test_scout_trial_evaluation.py
+++ b/products/signals/backend/test/test_scout_trial_evaluation.py
@@ -562,23 +562,53 @@ class TestScoutTrialEvaluation(BaseTest):
assert all(criterion.verdict == "unknown" for criterion in judgment.criteria)
assert claim not in judgment.summary
- @parameterized.expand([(None,), ("failed",), ("cancelled",)])
- def test_invalidation_after_export_excludes_the_trial(self, task_status: str | None) -> None:
+ @parameterized.expand(
+ [
+ (None,),
+ ("failed",),
+ ("cancelled",),
+ (
+ "failed",
+ "custom_prompt - poll_for_turn: timed out after 1800s (stage=active_at_budget)",
+ "The scout timed out after about 30 minutes. This run was not judged.",
+ ),
+ (
+ "failed",
+ "Private task detail.",
+ "The trial did not complete successfully.",
+ ),
+ (
+ "cancelled",
+ "custom_prompt - poll_for_turn: timed out after 1800s (stage=active_at_budget)",
+ "The trial did not complete successfully.",
+ ),
+ ]
+ )
+ def test_invalidation_after_export_excludes_the_trial(
+ self, task_status: str | None, task_error: str | None = None, expected_reason: str | None = None
+ ) -> None:
export_trial_result(self.scout_run, status="completed")
if task_status is None:
ScoutTrialStore(self.scout_run).invalidate("The runtime changed after export.", allow_terminal=True)
else:
self.scout_run.task_run.status = task_status
- self.scout_run.task_run.save(update_fields=["status"])
+ self.scout_run.task_run.error_message = task_error or ""
+ self.scout_run.task_run.save(update_fields=["status", "error_message"])
snapshot = prepare_trial_evaluation(config=self.config, user=self.user, request=self.request)
assert snapshot.runs[0].exclusion_reason is not None
assert snapshot.runs[0].execution_status == (task_status or "completed")
+ if expected_reason is not None:
+ assert snapshot.runs[0].exclusion_reason == expected_reason
judge = AsyncMock()
with patch(f"{JUDGE_MODULE}.judge_trial_run", judge):
async_to_sync(run_evaluation_run)(self.team.id, snapshot.evaluation_id, self.launch.id)
judge.assert_not_called()
report = finish_trial_evaluation(self.team.id, snapshot.evaluation_id)
assert report.runs[0].status == "excluded"
+ if expected_reason is not None:
+ assert report.runs[0].summary == expected_reason
+ if task_error is not None:
+ assert task_error not in report.model_dump_json()
@parameterized.expand(
["user_id", "context_id", "model", "runtime_adapter", "reasoning_effort", "service_tier", "skill_body"]
diff --git a/products/signals/backend/test/test_scout_trial_evaluation_report.py b/products/signals/backend/test/test_scout_trial_evaluation_report.py
index 0383c62e4561..8e8b5e70e45d 100644
--- a/products/signals/backend/test/test_scout_trial_evaluation_report.py
+++ b/products/signals/backend/test/test_scout_trial_evaluation_report.py
@@ -110,9 +110,10 @@ class TestScoutTrialEvaluationReport(SimpleTestCase):
assert report.variants[1].criteria[0].baseline_delta == delta
assert report.runs[-1].score == (0.0 if candidate_verdict == "fail" else None)
assert report.outcome is not None
- assert report.outcome.status == ("tie" if candidate_verdict == "fail" else "inconclusive")
+ expected_status = {"fail": "tie", "unknown": "provisional", "not_applicable": "inconclusive"}
+ assert report.outcome.status == expected_status[candidate_verdict]
assert report.outcome.variant_ids == (
- [self.baseline.id, self.candidate.id] if candidate_verdict == "fail" else []
+ [self.baseline.id, self.candidate.id] if candidate_verdict != "not_applicable" else []
)
@parameterized.expand([("excluded",), ("judge_error",)])
@@ -139,6 +140,76 @@ class TestScoutTrialEvaluationReport(SimpleTestCase):
assert report.runs[-1].score is None
assert report.outcome is not None and report.outcome.status == "inconclusive"
assert report.outcome.variant_ids == []
+ assert "At least two versions" in report.outcome.summary
+
+ @parameterized.expand([("excluded",), ("judge_error",)])
+ def test_completed_versions_compete_even_when_most_versions_failed(self, status: str) -> None:
+ failed_variants = [
+ self.baseline.model_copy(
+ update={"id": uuid4(), "label": f"Incomplete {index}", "launch_ids": [uuid4(), uuid4()]}
+ )
+ for index in range(3)
+ ]
+ failed_runs = [
+ self.snapshot.runs[0].model_copy(update={"launch_id": launch_id, "variant_id": variant.id})
+ for variant in failed_variants
+ for launch_id in variant.launch_ids
+ ]
+ snapshot = self.snapshot.model_copy(
+ update={
+ "request": self.snapshot.request.model_copy(
+ update={
+ "variants": [*failed_variants, self.baseline, self.candidate],
+ "baseline_variant_id": failed_variants[0].id,
+ }
+ ),
+ "runs": [*failed_runs, *self.snapshot.runs],
+ }
+ )
+ failed_judgments = [
+ TrialRunJudgment.model_validate(
+ {
+ "launch_id": run.launch_id,
+ "variant_id": run.variant_id,
+ "status": status,
+ "summary": "Incomplete run",
+ }
+ )
+ for run in failed_runs
+ ]
+ report = build_trial_comparison_report(
+ snapshot,
+ [
+ *failed_judgments,
+ *[
+ self._judgment(run, verdict)
+ for run, verdict in zip(self.snapshot.runs, ["pass", "fail", "pass", "pass"], strict=True)
+ ],
+ ],
+ )
+ assert report.outcome is not None and report.outcome.status == "winner"
+ assert report.outcome.variant_ids == [self.candidate.id]
+ assert "3 of 5 versions excluded" in report.outcome.summary
+ assert len(report.runs) == 10
+ assert all(variant.baseline_delta is None for variant in report.variants)
+
+ @parameterized.expand(
+ [
+ ("leader", ["pass", "unknown", "fail", "fail"], "provisional"),
+ ("no_confirmed_passes", ["fail", "unknown", "fail", "fail"], "inconclusive"),
+ ("unknown_competitor", ["pass", "pass", "unknown", "unknown"], "provisional"),
+ ]
+ )
+ def test_unknown_checks_earn_no_passes(self, _name: str, verdicts: list[str], status: str) -> None:
+ report = build_trial_comparison_report(
+ self.snapshot,
+ [self._judgment(run, verdict) for run, verdict in zip(self.snapshot.runs, verdicts, strict=True)],
+ )
+ assert report.outcome is not None and report.outcome.status == status
+ assert report.outcome.variant_ids == ([self.baseline.id] if status == "provisional" else [])
+ assert report.variants[1].baseline_delta is None
+ if status == "provisional":
+ assert "unknown checks earn no passes" in report.outcome.summary
@parameterized.expand([("unknown", 0.0), ("not_applicable", None)])
def test_no_decisive_verdicts_produce_no_score(self, verdict: str, coverage: float | None) -> None:
diff --git a/products/signals/backend/test/test_scout_trial_judge.py b/products/signals/backend/test/test_scout_trial_judge.py
index 30f1095bb43f..2bd8fea09a1a 100644
--- a/products/signals/backend/test/test_scout_trial_judge.py
+++ b/products/signals/backend/test/test_scout_trial_judge.py
@@ -2,11 +2,15 @@ from __future__ import annotations
import json
from datetime import UTC, datetime
+from typing import cast
from uuid import uuid4
+from unittest.mock import patch
+
from django.test import SimpleTestCase
from parameterized import parameterized
+from pydantic import JsonValue
from products.signals.backend.facade.rubrics import ScoutRubricReferenceContext
from products.signals.backend.scout_harness.trial_evaluation_types import (
@@ -194,6 +198,74 @@ class TestSandboxJudgePrompt(SimpleTestCase):
class TestSandboxJudgeVerdicts(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (encoding_depth, kind)
+ for encoding_depth in (0, 1, 2)
+ for kind in (["string", "null"], {"unexpected": "object"})
+ ]
+ )
+ def test_tool_response_with_non_string_type_preserves_schema_and_result(
+ self, encoding_depth: int, kind: object
+ ) -> None:
+ schema_description = "Optional checkout field.\nMay be absent."
+ result_text = "Checkout verified.\nNo missing fields."
+ output: object = {"schema": {"type": kind, "description": schema_description}, "result": result_text}
+ for _ in range(encoding_depth):
+ output = json.dumps(output)
+ result = parse_trial_judgment(
+ json.dumps(
+ {
+ "summary": "Checked schema and result.",
+ "criteria": [
+ _verdict(identifier="schema", source_id="trace:1", quote=schema_description),
+ _verdict(identifier="result", source_id="trace:1", quote=result_text),
+ ],
+ }
+ ),
+ criteria=[_criterion("schema"), _criterion("result")],
+ sources=[TrialEvidenceSource(id="trace", kind="trace", text=_tool_line(rawOutput=output))],
+ )
+ self.assertEqual([criterion.verdict for criterion in result.criteria], ["pass", "pass"])
+ self.assertEqual(
+ [criterion.evidence[0].quote for criterion in result.criteria], [schema_description, result_text]
+ )
+
+ def test_many_citations_reuse_decoded_large_tool_response(self) -> None:
+ quotes = [f"Observation {index}.\nConfirmed." for index in range(180)]
+ response = json.dumps({"padding": "x" * 1_048_576, "results": quotes})
+ criteria = [_criterion(f"check-{index}") for index in range(30)]
+ content = json.dumps(
+ {
+ "summary": "Checked every observation.",
+ "criteria": [
+ {
+ **_verdict(identifier=criterion.id),
+ "evidence": [
+ {"source_id": "trace:1", "quote": quote} for quote in quotes[index * 6 : (index + 1) * 6]
+ ],
+ }
+ for index, criterion in enumerate(criteria)
+ ],
+ }
+ )
+ source = TrialEvidenceSource(id="trace", kind="trace", text=_tool_line(rawOutput=response))
+ loads = json.loads
+ response_decodes = 0
+
+ def count_response_decodes(value: str) -> JsonValue:
+ nonlocal response_decodes
+ if value == response:
+ response_decodes += 1
+ return cast(JsonValue, loads(value))
+
+ with patch("products.signals.backend.trial_judging.json.loads", side_effect=count_response_decodes):
+ result = parse_trial_judgment(content, criteria=criteria, sources=[source])
+
+ self.assertEqual([criterion.verdict for criterion in result.criteria], ["pass"] * 30)
+ self.assertEqual([citation.quote for criterion in result.criteria for citation in criterion.evidence], quotes)
+ self.assertLessEqual(response_decodes, 2)
+
@parameterized.expand(
[
("missing", []),
@@ -261,9 +333,13 @@ class TestSandboxJudgeVerdicts(SimpleTestCase):
)
self.assertEqual(result.criteria[0].verdict, "pass")
- @parameterized.expand([("acp",), ("pi",)])
- def test_tool_evidence_at_end_of_large_log_is_available(self, runtime: str) -> None:
- output = {"type": "text", "text": "Affected checkouts: 7.\nFilter: last 24 hours."}
+ @parameterized.expand([(runtime, depth) for runtime in ("acp", "pi") for depth in (0, 1, 2)])
+ def test_tool_evidence_at_end_of_large_log_is_available(self, runtime: str, depth: int) -> None:
+ quote = 'Affected checkouts: 7.\nFilter: "last 24 hours".'
+ text = quote
+ for _ in range(depth):
+ text = json.dumps({"results": text})
+ output = {"type": "text", "text": text}
if runtime == "acp":
tail = _tool_line(toolCallId="query-1", status="completed", rawOutput={"content": [output]})
else:
@@ -281,14 +357,104 @@ class TestSandboxJudgeVerdicts(SimpleTestCase):
json.dumps(
{
"summary": "Observed the result.",
- "criteria": [_verdict(source_id="trace:2001", quote=output["text"])],
+ "criteria": [_verdict(source_id="trace:2001", quote=quote)],
}
),
criteria=[_criterion()],
sources=[TrialEvidenceSource(id="trace", kind="trace", text=log)],
)
self.assertEqual(result.criteria[0].verdict, "pass")
- self.assertEqual(result.criteria[0].evidence[0].quote, output["text"])
+ self.assertEqual(result.criteria[0].evidence[0].quote, quote)
+ self.assertEqual(result.criteria[0].reason, "The result records the observation.")
+ self.assertEqual(result.criteria[0].confidence, "high")
+ self.assertEqual(result.summary, "Observed the result.")
+
+ @parameterized.expand(
+ [
+ (name, value, quote)
+ for quote in ("Hidden observation.", "Hidden observation.\nSecond line.")
+ for name, value in (
+ ("thought", {"type": "thinking", "text": quote}),
+ ("reasoning", {"reasoning": quote}),
+ ("metadata", {"_meta": quote}),
+ )
+ ]
+ + [
+ ("joined_fields", {"first": "First line.", "second": "\nSecond line."}, "First line.\nSecond line."),
+ (
+ "redacted_adjacency",
+ {"before": 1, "thinking": "Excluded.", "after": 2},
+ '"before": 1, "after": 2',
+ ),
+ ]
+ )
+ def test_encoded_tool_citations_cannot_use_reasoning_or_join_fields(
+ self, _name: str, value: object, quote: str
+ ) -> None:
+ source = TrialEvidenceSource(
+ id="trace",
+ kind="trace",
+ text=_tool_line(status="completed", rawOutput={"content": [{"type": "text", "text": json.dumps(value)}]}),
+ )
+ result = parse_trial_judgment(
+ json.dumps({"summary": "Claimed support.", "criteria": [_verdict(source_id="trace:1", quote=quote)]}),
+ criteria=[_criterion()],
+ sources=[source],
+ )
+ self.assertEqual(result.criteria[0].verdict, "unknown")
+ self.assertEqual(result.criteria[0].evidence, [])
+
+ def test_excessively_encoded_tool_text_does_not_hide_a_visible_sibling(self) -> None:
+ hidden = "Hidden observation."
+ for _ in range(3):
+ hidden = json.dumps({"results": hidden})
+ source = TrialEvidenceSource(
+ id="trace",
+ kind="trace",
+ text=_tool_line(status="completed", rawOutput={"encoded": hidden, "visible": "Visible observation."}),
+ )
+ result = parse_trial_judgment(
+ json.dumps(
+ {
+ "summary": "Checked both observations.",
+ "criteria": [
+ _verdict(source_id="trace:1", quote="Hidden observation."),
+ _verdict(identifier="visible", source_id="trace:1", quote="Visible observation."),
+ ],
+ }
+ ),
+ criteria=[_criterion(), _criterion("visible")],
+ sources=[source],
+ )
+ self.assertEqual(result.criteria[0].verdict, "unknown")
+ self.assertEqual(result.criteria[0].evidence, [])
+ self.assertEqual(result.criteria[1].verdict, "pass")
+
+ def test_deep_tool_citation_does_not_discard_other_verdicts(self) -> None:
+ nested: object = "Recorded observation."
+ for _ in range(500):
+ nested = {"value": nested}
+ source = TrialEvidenceSource(
+ id="trace",
+ kind="trace",
+ text=_tool_line(rawOutput={"nested": nested, "visible": "Visible observation."}),
+ )
+ result = parse_trial_judgment(
+ json.dumps(
+ {
+ "summary": "Checked both observations.",
+ "criteria": [
+ _verdict(source_id="trace:1", quote="Missing observation."),
+ _verdict(identifier="visible", source_id="trace:1", quote="Visible observation."),
+ ],
+ }
+ ),
+ criteria=[_criterion(), _criterion("visible")],
+ sources=[source],
+ )
+ self.assertEqual(result.criteria[0].verdict, "unknown")
+ self.assertEqual(result.criteria[0].evidence, [])
+ self.assertEqual(result.criteria[1].verdict, "pass")
@parameterized.expand(
[
@@ -307,6 +473,7 @@ class TestSandboxJudgeVerdicts(SimpleTestCase):
'"before": 1, "after": 2',
),
("empty_tool", _tool_line(), "trace:1", "{}"),
+ ("empty_tool_brace", _tool_line(), "trace:1", "{"),
]
)
def test_trace_citation_requires_the_recorded_tool_event(
diff --git a/products/signals/backend/test/test_scout_trial_judge_sandbox.py b/products/signals/backend/test/test_scout_trial_judge_sandbox.py
index c3a46280a3c5..9cb3613e133d 100644
--- a/products/signals/backend/test/test_scout_trial_judge_sandbox.py
+++ b/products/signals/backend/test/test_scout_trial_judge_sandbox.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
from collections.abc import Callable
from datetime import UTC, datetime, timedelta
+from threading import Event
import time_machine
from posthog.test.base import BaseTest
@@ -150,6 +151,37 @@ class TestSandboxJudgeDispatch(BaseTest):
self.assertEqual(TaskRun.objects.filter(team_id=self.team.id, task=run.task).count(), 1)
self.dispatch.assert_called_once()
+ def test_collecting_saved_output_does_not_block_the_event_loop(self) -> None:
+ self.assertIsNone(async_to_sync(judge_trial_run)(self.snapshot, self.evidence))
+ run = TaskRun.objects.get(team_id=self.team.id, task__origin_key__startswith="scout-trial-judge:")
+ run.status = TaskRun.Status.COMPLETED
+ run.output = self.output.model_dump(mode="json")
+ run.save(update_fields=["status", "output"])
+
+ async def collect_with_concurrent_work() -> None:
+ loop = asyncio.get_running_loop()
+ parser_started = asyncio.Event()
+ concurrent_work_finished = Event()
+
+ def blocking_parse(*_args: object, **_kwargs: object) -> TrialJudgeVerdicts:
+ loop.call_soon_threadsafe(parser_started.set)
+ self.assertTrue(concurrent_work_finished.wait(timeout=5), "Parsing blocked the event loop")
+ return self.output
+
+ async def concurrent_work() -> None:
+ await parser_started.wait()
+ concurrent_work_finished.set()
+
+ with patch(f"{MODULE}.parse_trial_judgment", side_effect=blocking_parse):
+ result, _ = await asyncio.gather(
+ judge_trial_run(self.snapshot, self.evidence),
+ concurrent_work(),
+ )
+ assert result is not None
+ self.assertEqual((result.status, result.criteria), ("judged", self.output.criteria))
+
+ async_to_sync(collect_with_concurrent_work)()
+
@parameterized.expand([("no_output", False), ("output_saved_without_completion", True)])
@time_machine.travel("2026-08-01T12:00:00Z", tick=False)
def test_resumed_judge_keeps_its_original_deadline(self, _name: str, output_saved: bool) -> None:
diff --git a/products/signals/backend/test/test_scout_trials_api.py b/products/signals/backend/test/test_scout_trials_api.py
index a4b929665cb5..dc2c414aba30 100644
--- a/products/signals/backend/test/test_scout_trials_api.py
+++ b/products/signals/backend/test/test_scout_trials_api.py
@@ -655,7 +655,15 @@ class TestScoutTrialLaunch(APIBaseTest):
@parameterized.expand(
[
("completed_task_cancelled_runner", "completed", "cancelled", False, "unknown"),
- ("failed_task_cancelled_runner", "failed", "cancelled", False, "unknown"),
+ (
+ "failed_task_cancelled_runner",
+ "failed",
+ "cancelled",
+ False,
+ "unknown",
+ "custom_prompt - poll_for_turn: timed out after 1800s (stage=active_at_budget)",
+ None,
+ ),
("task_still_ending", "in_progress", "cancelled", False, "unknown"),
("recover_missing_export", "completed", None, False, "completed"),
("concurrent_runner_export", "completed", "cancelled", True, "completed"),
@@ -667,8 +675,52 @@ class TestScoutTrialLaunch(APIBaseTest):
("scout_finished_task_not_started", "not_started", "completed", False, "unknown"),
("scout_finished_task_queued", "queued", "completed", False, "unknown"),
("scout_finished_task_active", "in_progress", "completed", False, "unknown"),
- ("scout_finished_task_failed", "failed", "completed", False, "unknown"),
+ (
+ "scout_finished_task_failed",
+ "failed",
+ "completed",
+ False,
+ "unknown",
+ "custom_prompt - poll_for_turn: timed out after 1800s (stage=no_turn_output)",
+ "The scout timed out after about 30 minutes. This run was not judged.",
+ ),
("scout_finished_task_cancelled", "cancelled", "completed", False, "unknown"),
+ (
+ "saved_timeout",
+ "failed",
+ "failed",
+ False,
+ "unknown",
+ "custom_prompt - poll_for_turn: timed out after 1800s (stage=active_at_budget)",
+ "The scout timed out after about 30 minutes. This run was not judged.",
+ ),
+ (
+ "recovered_timeout",
+ "failed",
+ None,
+ False,
+ "failed",
+ "custom_prompt - poll_for_turn: timed out after 900s (stage=stalled_after_output)",
+ "The scout timed out after about 15 minutes. This run was not judged.",
+ ),
+ (
+ "private_task_failure",
+ "failed",
+ "failed",
+ False,
+ "unknown",
+ "custom_prompt - poll_for_turn: timed out after 1800s (stage=active_at_budget) Private task detail.",
+ None,
+ ),
+ (
+ "completed_task_stale_timeout",
+ "completed",
+ "completed",
+ False,
+ "unknown",
+ "custom_prompt - poll_for_turn: timed out after 1800s (stage=active_at_budget)",
+ None,
+ ),
]
)
def test_poll_preserves_terminal_result(
@@ -678,6 +730,8 @@ class TestScoutTrialLaunch(APIBaseTest):
saved_status: str | None,
concurrent_export: bool,
workflow_status: Literal["unknown", "completed", "pending", "failed", "cancelled"],
+ task_error: str | None = None,
+ expected_error: str | None = None,
) -> None:
self._internal_scout_base()
launch = create_trial_launch(config=self.config, user=self.user, launch_id=uuid4())
@@ -697,7 +751,8 @@ class TestScoutTrialLaunch(APIBaseTest):
"reasoning_effort": launch.reasoning_effort,
"service_tier": launch.service_tier,
}
- run.task_run.save(update_fields=["state"])
+ run.task_run.error_message = task_error or ""
+ run.task_run.save(update_fields=["state", "error_message"])
concurrent_read = _label == "runner_export_after_row_read"
if saved_status is not None and not concurrent_export and not concurrent_read:
export_trial_result(run, status=saved_status)
@@ -751,6 +806,9 @@ class TestScoutTrialLaunch(APIBaseTest):
assert result["status"] == expected_status
assert result["task_status"] == task_status
assert result["export_error"] is None
+ if task_error is not None:
+ assert result["error"] == expected_error
+ assert task_error not in json.dumps(result)
if concurrent_read:
assert result["summary"] == run.summary
assert result["input_tokens"] == 120
diff --git a/products/signals/backend/trial_judging.py b/products/signals/backend/trial_judging.py
index d5046a392ae4..220eee901c5c 100644
--- a/products/signals/backend/trial_judging.py
+++ b/products/signals/backend/trial_judging.py
@@ -19,8 +19,9 @@ from products.signals.backend.trial_judging_types import (
TrialRunEvidence,
)
-JUDGE_PROMPT_VERSION = "sandbox-2"
+JUDGE_PROMPT_VERSION = "sandbox-3"
MAX_JUDGE_OUTPUT_CHARACTERS = 64_000
+MAX_QUOTE_JSON_DEPTH = 2
@frozen
@@ -73,11 +74,14 @@ Grading:
- pass: every applicable mandatory part is supported. A plausible report or completing most of the task
is insufficient. Lower confidence cannot compensate for an unverified requirement.
- fail: observed evidence establishes a violation, contradiction, or an explicit admission of an unmet
- requirement. One violated mandatory part is enough. A permitted successful retry may satisfy eventual
+ requirement. A mandatory action is demonstrably omitted when its applicability is established, it must
+ leave an observable record, and the complete relevant records show neither the action nor an allowed
+ alternative. One violated mandatory part is enough. A permitted successful retry may satisfy eventual
success, but it does not erase an independently forbidden action.
-- unknown: required evidence is unavailable, ambiguous, or insufficient after investigation. A missing
- observation is not proof that an action did not occur or a claim is false. A log-format problem, missing
- attachment, or budget exhaustion must be reported honestly as unknown, never silently passed.
+- unknown: required evidence is unavailable, ambiguous, or insufficient after investigation. Missing,
+ truncated, or unreadable records cannot establish that an action was omitted. A log-format problem,
+ missing attachment, or budget exhaustion must be reported honestly as unknown, never silently passed.
+ Missing thoughts or explanations do not establish that manual reasoning or comparison was omitted.
- not_applicable: evidence establishes that the criterion's entire applicability condition is absent.
If only one conditional branch is absent, assess the remaining mandatory parts.
@@ -85,8 +89,11 @@ For factual grounding, inventory the material claims in the title, report, and r
claims to observed results, including factual premises embedded in advice. A caveat about causation does
not validate a separate factual claim. Explicit hypotheses and investigation requests need not already
be proved. A report repeating itself, or copying a claim into memory, is not independent support.
-An observed contradiction means fail; otherwise missing material support means unknown. Unsupported
-confidence alone does not establish falsity. Explain the decisive observation or the missing evidence.
+An observed contradiction means fail. When the criterion requires grounding and the complete relevant
+sources are available, an unsupported factual assertion fails that grounding requirement; this does not
+establish that the assertion is false. If the relevant sources are unavailable or ambiguous, use unknown.
+Explicit hypotheses and stated evidence gaps are not unsupported factual assertions. Explain the decisive
+observation, unmet grounding requirement, or missing evidence.
Inspect query expressions, filters, time ranges, boundary operators, units, counted entities, and results.
A label such as users is not proof that real users were counted: check identifiers and null/sentinel
@@ -154,20 +161,80 @@ def _strings(value: JsonValue) -> Iterator[str]:
yield from _strings(child)
-def _without_reasoning(value: JsonValue) -> JsonValue:
+def _without_reasoning(value: JsonValue, *, json_depth: int = MAX_QUOTE_JSON_DEPTH) -> JsonValue:
+ if isinstance(value, str):
+ try:
+ decoded = cast(JsonValue, json.loads(value))
+ if not isinstance(decoded, (dict, list, str)):
+ return value
+ if not json_depth:
+ return None
+ filtered = _without_reasoning(decoded, json_depth=json_depth - 1)
+ except ValueError:
+ return value
+ except RecursionError:
+ return None
+ # Keep the original spelling unless encoded fields need the same exclusions as native JSON.
+ return value if filtered == decoded else json.dumps(filtered, ensure_ascii=False)
if isinstance(value, dict):
- if value.get("type") in {"thinking", "reasoning", "redacted_thinking", "analysis"}:
+ kind = value.get("type")
+ if isinstance(kind, str) and kind in {"thinking", "reasoning", "redacted_thinking", "analysis"}:
return None
return {
- key: _without_reasoning(child)
+ key: _without_reasoning(child, json_depth=json_depth)
for key, child in value.items()
if key not in {"_meta", "thinking", "reasoning", "reasoning_content", "reasoning_details", "signature"}
}
if isinstance(value, list):
- return [_without_reasoning(child) for child in value]
+ return [_without_reasoning(child, json_depth=json_depth) for child in value]
return value
+@frozen
+class _ToolQuoteText:
+ filtered: str = field(repr=False)
+ original: str = field(repr=False)
+
+ def contains(self, quote: str) -> bool:
+ # Filtering must not invent adjacency, including inside a decoded tool-result string.
+ return quote in self.filtered and quote in self.original
+
+
+def _tool_quote_texts(
+ value: JsonValue,
+ original: JsonValue,
+ *,
+ json_depth: int = MAX_QUOTE_JSON_DEPTH,
+ serialize: bool = True,
+) -> Iterator[_ToolQuoteText]:
+ if value is None and original is not None:
+ return
+ if serialize:
+ for separators in (None, (",", ":")):
+ yield _ToolQuoteText(
+ filtered=json.dumps(value, ensure_ascii=False, separators=separators),
+ original=json.dumps(original, ensure_ascii=False, separators=separators),
+ )
+ if isinstance(value, str) and isinstance(original, str):
+ yield _ToolQuoteText(filtered=value, original=original)
+ if json_depth:
+ try:
+ decoded = cast(JsonValue, json.loads(original))
+ except (ValueError, RecursionError):
+ return
+ yield from _tool_quote_texts(
+ _without_reasoning(decoded, json_depth=json_depth - 1),
+ decoded,
+ json_depth=json_depth - 1,
+ )
+ elif isinstance(value, dict) and isinstance(original, dict):
+ for key, child in value.items():
+ yield from _tool_quote_texts(child, original[key], json_depth=json_depth, serialize=False)
+ elif isinstance(value, list) and isinstance(original, list):
+ for child, previous in zip(value, original, strict=True):
+ yield from _tool_quote_texts(child, previous, json_depth=json_depth, serialize=False)
+
+
def _object(value: JsonValue) -> dict[str, JsonValue]:
return value if isinstance(value, dict) else {}
@@ -198,20 +265,36 @@ class _EvidenceQuotes:
self.sources = {source.id: source for source in sources}
if len(self.sources) != len(sources):
raise TrialJudgeValidationError("The saved evidence contains duplicate source identifiers.")
- self.trace_lines: dict[str, dict[str, JsonValue]] = {}
- self.original_trace_lines: dict[str, dict[str, JsonValue]] = {}
- requested = {citation.source_id for citation in citations if citation.source_id.startswith("trace:")}
+ self.trace_lines: dict[str, set[str]] = {}
+ requested: dict[str, set[str]] = {}
+ for citation in citations:
+ if citation.source_id.startswith("trace:") and citation.quote.strip():
+ requested.setdefault(citation.source_id, set()).add(citation.quote)
trace = self.sources.get("trace")
if trace is not None and requested:
for number, line in enumerate(io.StringIO(trace.text), start=1):
identifier = f"trace:{number}"
if identifier in requested and (payload := _tool_event(line)) is not None:
- self.original_trace_lines[identifier] = payload
- self.trace_lines[identifier] = {
- key: _without_reasoning(value)
- for key, value in payload.items()
- if key in {"toolCallId", "id", "title", "kind", "status", "rawInput", "rawOutput", "content"}
- }
+ matches: set[str] = set()
+ try:
+ filtered = {
+ key: _without_reasoning(value)
+ for key, value in payload.items()
+ if key
+ in {"toolCallId", "id", "title", "kind", "status", "rawInput", "rawOutput", "content"}
+ }
+ if filtered:
+ # Check a line's quotes together without retaining copies of large responses.
+ for text in _tool_quote_texts(filtered, payload):
+ matches.update(
+ quote for quote in requested[identifier] - matches if text.contains(quote)
+ )
+ if matches == requested[identifier]:
+ break
+ except RecursionError:
+ # Keep earlier matches if a later nested value is too deep.
+ pass
+ self.trace_lines[identifier] = matches
if len(self.trace_lines) == len(requested):
break
@@ -219,19 +302,7 @@ class _EvidenceQuotes:
if not citation.quote.strip():
return False
if citation.source_id.startswith("trace:"):
- payload = self.trace_lines.get(citation.source_id)
- # Redacting fields must not create a quotation absent from the recorded event.
- return bool(payload) and (
- any(
- citation.quote in json.dumps(payload, ensure_ascii=False, separators=separators)
- and citation.quote
- in json.dumps(
- self.original_trace_lines[citation.source_id], ensure_ascii=False, separators=separators
- )
- for separators in (None, (",", ":"))
- )
- or any(citation.quote in text for text in _strings(payload))
- )
+ return citation.quote in self.trace_lines.get(citation.source_id, set())
source = self.sources.get(citation.source_id)
if source is None or source.kind == "trace":
return False
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index ae90eec3b4d9..977ddc1521d8 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -4371,6 +4371,7 @@ export type TrialComparisonOutcomeStatusEnumApi =
export const TrialComparisonOutcomeStatusEnumApi = {
Winner: 'winner',
Tie: 'tie',
+ Provisional: 'provisional',
Inconclusive: 'inconclusive',
} as const
diff --git a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialComparisonReport.stories.tsx b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialComparisonReport.stories.tsx
index 0cc9a81d5c4b..167efe5ab18a 100644
--- a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialComparisonReport.stories.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialComparisonReport.stories.tsx
@@ -4,7 +4,12 @@ import { useState } from 'react'
import { scoutRubricReferenceFixture } from '../scoutRubricFixtures'
import { ScoutTrialComparisonReport } from './ScoutTrialComparisonReport'
import { ScoutTrialRunDrawer } from './ScoutTrialRunDrawer'
-import { trialFixtureLongReport, trialFixtureReport, trialFixtureResult } from './scoutTrialsFixtures'
+import {
+ trialFixtureEvaluationWithJudgeError,
+ trialFixtureLongReport,
+ trialFixtureReport,
+ trialFixtureResult,
+} from './scoutTrialsFixtures'
import type { ScoutTrialRow } from './scoutTrialUtils'
const meta: Meta<typeof ScoutTrialComparisonReport> = {
@@ -126,6 +131,79 @@ export const PartialEvidence: Story = {
},
}
+const excludedVariantId = '00000000-0000-4000-8000-000000000090'
+const excludedLaunchIds = ['00000000-0000-4000-8000-000000000091', '00000000-0000-4000-8000-000000000092']
+
+export const ProvisionalWithExcludedVersion: Story = {
+ args: {
+ report: {
+ ...trialFixtureReport,
+ outcome: {
+ status: 'provisional',
+ variant_ids: [trialFixtureReport.variants[1].variant_id],
+ summary:
+ 'Candidate prompt leads with 4 confirmed passes; Baseline has 3 passes and 1 unknown check. Missing evidence could change the result. Incomplete version is excluded because one run could not be judged.',
+ },
+ variants: [
+ ...trialFixtureReport.variants.map((variant) =>
+ variant.is_baseline
+ ? {
+ ...variant,
+ score: 1,
+ coverage: 0.75,
+ criteria: variant.criteria.map((criterion) =>
+ criterion.criterion_id === 'evidence'
+ ? { ...criterion, failed: 0, unknown: 1, pass_rate: 1, coverage: 0.5 }
+ : criterion
+ ),
+ }
+ : { ...variant, baseline_delta: null }
+ ),
+ {
+ ...trialFixtureEvaluationWithJudgeError.report!.variants[1],
+ variant_id: excludedVariantId,
+ label: 'Incomplete version',
+ },
+ ],
+ runs: [
+ ...trialFixtureReport.runs.map((run, index) =>
+ index === 0
+ ? {
+ ...run,
+ score: 1,
+ coverage: 0.5,
+ criteria: run.criteria?.map((criterion) =>
+ criterion.criterion_id === 'evidence'
+ ? {
+ ...criterion,
+ verdict: 'unknown' as const,
+ confidence: 'low' as const,
+ reason: 'The captured log does not establish whether the cited source was read.',
+ evidence: [],
+ }
+ : criterion
+ ),
+ }
+ : run
+ ),
+ ...trialFixtureEvaluationWithJudgeError.report!.runs.slice(2).map((run, index) => ({
+ ...run,
+ variant_id: excludedVariantId,
+ launch_id: excludedLaunchIds[index],
+ })),
+ ],
+ evidence: [
+ ...trialFixtureReport.evidence,
+ ...trialFixtureReport.evidence.slice(2).map((run, index) => ({
+ ...run,
+ variant_id: excludedVariantId,
+ launch_id: excludedLaunchIds[index],
+ })),
+ ],
+ },
+ },
+}
+
export const Tie: Story = {
args: {
report: {
diff --git a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialComparisonReport.test.tsx b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialComparisonReport.test.tsx
index 2ddb39276fc0..fae465e8a66e 100644
--- a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialComparisonReport.test.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialComparisonReport.test.tsx
@@ -1,4 +1,4 @@
-import { cleanup, render, screen } from '@testing-library/react'
+import { cleanup, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { initKeaTests } from '~/test/init'
@@ -25,9 +25,66 @@ describe('ScoutTrialComparisonReport', () => {
expect(screen.getByText('No clear winner')).not.toBeNull()
expect(screen.getByText('100%')).not.toBeNull()
expect(screen.getByText('1 run could not be judged')).not.toBeNull()
+ const excludedRow = screen.getByText('Excluded').closest('tr')!
+ expect(within(excludedRow).getByText('Candidate prompt')).not.toBeNull()
+ expect(within(excludedRow).getByText('–')).not.toBeNull()
expect(screen.queryByText(/Best in this trial/)).toBeNull()
})
+ it.each([false, true])('shows a provisional lead without presenting it as a final winner (tied: %s)', (tied) => {
+ const leaders = tied ? trialFixtureReport.variants : [trialFixtureReport.variants[1]]
+ render(
+ <ScoutTrialComparisonReport
+ report={{
+ ...trialFixtureReport,
+ outcome: {
+ status: 'provisional',
+ variant_ids: leaders.map((variant) => variant.variant_id),
+ summary: 'Unknown checks could change this result.',
+ },
+ }}
+ />
+ )
+
+ expect(
+ screen.getByText(
+ tied ? 'Provisional tied leaders: Candidate prompt, Baseline' : 'Provisional leader: Candidate prompt'
+ )
+ ).not.toBeNull()
+ expect(screen.getAllByText(tied ? 'Provisional tie' : 'Provisional leader')).toHaveLength(leaders.length)
+ expect(screen.getByText('Unknown checks could change this result.')).not.toBeNull()
+ expect(screen.queryByText(/Best in this trial/)).toBeNull()
+ expect(screen.queryByText('Most checks passed')).toBeNull()
+ })
+
+ it.each(['winner', 'tie', 'provisional'] as const)(
+ 'limits the %s conclusion to completed versions when another version is excluded',
+ (status) => {
+ render(
+ <ScoutTrialComparisonReport
+ report={{
+ ...trialFixtureReport,
+ outcome: { ...trialFixtureReport.outcome!, status },
+ variants: [
+ ...trialFixtureReport.variants,
+ {
+ ...trialFixtureReport.variants[1],
+ variant_id: '00000000-0000-4000-8000-000000000099',
+ label: 'Incomplete version',
+ judged_runs: 1,
+ judge_errors: 1,
+ },
+ ],
+ }}
+ />
+ )
+
+ expect(screen.getByText(/Best among completed versions/)).not.toBeNull()
+ expect(screen.getByText('Excluded')).not.toBeNull()
+ expect(screen.queryByText(/Best in this trial/)).toBeNull()
+ }
+ )
+
it('keeps old reports readable without inventing a comparison conclusion', () => {
render(<ScoutTrialComparisonReport report={{ ...trialFixtureReport, outcome: null }} />)
@@ -113,6 +170,23 @@ describe('ScoutTrialComparisonReport', () => {
expect(screen.queryByText(trialFixtureReport.evaluation_id)).toBeNull()
})
+ it('shows the timeout instead of hiding it behind a generic invalidation reason', () => {
+ render(
+ <ScoutTrialRunDrawer
+ result={{
+ ...trialFixtureResult,
+ status: 'failed',
+ error: 'This run reached its 10-minute time limit.',
+ invalid_reason: 'The trial stopped before it completed.',
+ }}
+ onClose={jest.fn()}
+ />
+ )
+
+ expect(screen.getByText('This run reached its 10-minute time limit.')).not.toBeNull()
+ expect(screen.queryByText('The trial stopped before it completed.')).toBeNull()
+ })
+
it.each([
[null, 'New report'],
['00000000-0000-4000-8000-000000000098', 'Updated existing report'],
diff --git a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialComparisonReport.tsx b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialComparisonReport.tsx
index 9bce44cfc94e..006cdbc1cde1 100644
--- a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialComparisonReport.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialComparisonReport.tsx
@@ -36,6 +36,8 @@ export function ScoutTrialComparisonReport({
const differencesOnly = filter?.evaluationId === report.evaluation_id ? filter.differencesOnly : checks.length > 5
const rubricLabel = 'Saved rubric'
const outcome = report.outcome
+ const hasExcludedVersions = versions.some((version) => version.excluded)
+ const hasTiedLeaders = (outcome?.variant_ids?.length ?? 0) > 1
const bestVersionNames = versions
.filter(({ variant }) => outcome?.variant_ids?.includes(variant.variant_id))
.map(({ variant }) => variant.label)
@@ -49,11 +51,16 @@ export function ScoutTrialComparisonReport({
<div className="flex min-w-0 flex-col gap-1">
<strong className="break-words">
{outcome?.status === 'winner'
- ? `Best in this trial: ${bestVersionNames}`
+ ? `${hasExcludedVersions ? 'Best among completed versions' : 'Best in this trial'}: ${bestVersionNames}`
: outcome?.status === 'tie'
- ? `Tie: ${bestVersionNames}`
- : 'No clear winner'}
+ ? `${hasExcludedVersions ? 'Best among completed versions (tie)' : 'Tie'}: ${bestVersionNames}`
+ : outcome?.status === 'provisional'
+ ? `${hasTiedLeaders ? 'Provisional tied leaders' : 'Provisional leader'}: ${bestVersionNames}`
+ : 'No clear winner'}
</strong>
+ {outcome?.status === 'provisional' && hasExcludedVersions && (
+ <span>Best among completed versions</span>
+ )}
<span className="break-words">
{outcome?.summary ??
'This saved report has no comparison conclusion. Review the results below.'}
@@ -64,23 +71,25 @@ export function ScoutTrialComparisonReport({
<section className="flex min-w-0 flex-col gap-2">
<h3 className="m-0 text-sm font-semibold">Leaderboard</h3>
- <p className="m-0 text-xs text-muted">Ranked by checks passed. Cost and time don't affect the rank.</p>
+ <p className="m-0 text-xs text-muted">
+ Completed versions are ranked by confirmed checks passed. Cost and time don't affect the rank.
+ </p>
<LemonTable<TrialVersionResult>
dataSource={versions}
rowKey={({ variant }) => variant.variant_id}
size="small"
- rowClassName={({ variant }) =>
- outcome?.status === 'winner' && outcome.variant_ids?.includes(variant.variant_id)
+ rowClassName={({ variant, excluded }) =>
+ !excluded && outcome?.status === 'winner' && outcome.variant_ids?.includes(variant.variant_id)
? 'bg-success-highlight'
: null
}
columns={[
- { title: '#', key: 'rank', width: 44, render: (_, version) => version.rank },
+ { title: '#', key: 'rank', width: 44, render: (_, version) => version.rank ?? '–' },
{
title: 'Version',
key: 'version',
width: 240,
- render: (_, { variant, letter, settings, prompt }) => (
+ render: (_, { variant, letter, settings, prompt, excluded }) => (
<div className="flex min-w-48 flex-col items-start gap-1">
<div className="flex flex-wrap items-center gap-2">
<LemonTag type="muted">{letter}</LemonTag>
@@ -88,10 +97,27 @@ export function ScoutTrialComparisonReport({
</div>
<div className="flex flex-wrap gap-1">
{variant.is_baseline && <LemonTag type="muted">Baseline</LemonTag>}
- {outcome?.variant_ids?.includes(variant.variant_id) &&
+ {excluded && <LemonTag type="warning">Excluded</LemonTag>}
+ {!excluded &&
+ outcome?.variant_ids?.includes(variant.variant_id) &&
outcome.status !== 'inconclusive' && (
- <LemonTag type={outcome.status === 'winner' ? 'success' : 'muted'} wrap>
- {outcome.status === 'winner' ? 'Most checks passed' : 'Tied'}
+ <LemonTag
+ type={
+ outcome.status === 'provisional'
+ ? 'warning'
+ : outcome.status === 'winner'
+ ? 'success'
+ : 'muted'
+ }
+ wrap
+ >
+ {outcome.status === 'provisional'
+ ? hasTiedLeaders
+ ? 'Provisional tie'
+ : 'Provisional leader'
+ : outcome.status === 'winner'
+ ? 'Most checks passed'
+ : 'Tied'}
</LemonTag>
)}
</div>
@@ -175,7 +201,8 @@ export function ScoutTrialComparisonReport({
]}
/>
<p className="m-0 text-xs text-muted">
- Pass rates average the judged runs. Unknown and not applicable checks are left out of the rate.
+ Pass rates average the judged runs. Unknown and not applicable checks are left out of the rate and
+ earn no passes in the ranking.
</p>
</section>
@@ -318,14 +345,21 @@ export function ScoutTrialComparisonReport({
header: 'How ranking works',
content: (
<ul className="m-0 flex flex-col gap-2 pl-4 text-sm">
- <li>The most checks passed across all runs ranks first. Equal totals are a tie.</li>
<li>
- There is no winner if a run failed, was stopped, could not be judged, or has unknown
- checks.
+ A version is excluded if any run failed, was stopped, was excluded, or could not be
+ judged. Its results stay visible.
+ </li>
+ <li>
+ At least two complete versions are needed. The most confirmed checks passed across
+ all runs ranks first. Equal totals are a tie.
+ </li>
+ <li>
+ Unknown checks earn no passes and make the lead provisional. They stay visible so
+ you can review the missing evidence.
</li>
<li>
- Checks that don't apply aren't counted. Versions need the same number of runs and
- applicable checks for a fair comparison.
+ Checks that don't apply aren't counted. A final winner or tie needs the same number
+ of runs and comparable applicable checks.
</li>
<li>{`The rubric stayed fixed at revision ${report.rubric_revision}. These results describe these runs, not future performance.`}</li>
</ul>
diff --git a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialRunDrawer.tsx b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialRunDrawer.tsx
index abe3149c88a1..5883604736d2 100644
--- a/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialRunDrawer.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/trials/ScoutTrialRunDrawer.tsx
@@ -79,7 +79,7 @@ export function ScoutTrialRunDrawer({
<LemonBanner type="warning">This run was stopped. It was not judged.</LemonBanner>
)}
{(result?.error || result?.invalid_reason) && (
- <LemonBanner type="error">{result.invalid_reason || result.error}</LemonBanner>
+ <LemonBanner type="error">{result.error || result.invalid_reason}</LemonBanner>
)}
{result?.export_error && (
<LemonBanner type="warning">
diff --git a/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialPresentation.test.ts b/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialPresentation.test.ts
index 787874a624d3..0b042a29b74f 100644
--- a/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialPresentation.test.ts
+++ b/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialPresentation.test.ts
@@ -34,6 +34,53 @@ describe('scout trial result presentation', () => {
expect(report.variants[0].is_baseline).toBe(true)
})
+ it.each([{ judged_runs: 1, excluded_runs: 1 }, { judged_runs: 1, judge_errors: 1 }, { judged_runs: 1 }])(
+ 'leaves incomplete versions unranked even with more passes: %s',
+ (incomplete) => {
+ const report = {
+ ...trialFixtureReport,
+ variants: trialFixtureReport.variants.map((variant) =>
+ variant.is_baseline ? variant : { ...variant, ...incomplete }
+ ),
+ }
+
+ expect(
+ trialVersionResults(report, rows).map(({ variant, rank, excluded }) => [variant.label, rank, excluded])
+ ).toEqual([
+ ['Baseline', 1, false],
+ ['Candidate prompt', null, true],
+ ])
+ }
+ )
+
+ it('keeps versions with unknown checks ranked by confirmed passes', () => {
+ const report = {
+ ...trialFixtureReport,
+ variants: trialFixtureReport.variants.map((variant) => ({
+ ...variant,
+ criteria: variant.criteria.map((criterion) => ({
+ ...criterion,
+ passed: variant.is_baseline ? 0 : 1,
+ failed: 0,
+ unknown: variant.is_baseline ? 2 : 1,
+ })),
+ })),
+ }
+
+ expect(
+ trialVersionResults(report, rows).map(({ variant, rank, excluded, counts }) => [
+ variant.label,
+ rank,
+ excluded,
+ counts.passed,
+ counts.unknown,
+ ])
+ ).toEqual([
+ ['Candidate prompt', 1, false, 2, 2],
+ ['Baseline', 2, false, 0, 4],
+ ])
+ })
+
test.each(['missing', 'unknown', 'known', 'zero'] as const)('keeps %s cost distinct from free runs', (state) => {
const inputs =
state === 'missing'
diff --git a/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialPresentation.ts b/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialPresentation.ts
index 0e00f7679638..90e52ed63509 100644
--- a/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialPresentation.ts
+++ b/products/signals/frontend/inbox/components/config/scouts/trials/scoutTrialPresentation.ts
@@ -47,7 +47,8 @@ export function trialVerdictLabel(verdict: TrialCriterionVerdictApi['verdict']):
export interface TrialVersionResult {
variant: TrialVariantAggregateApi
letter: string
- rank: number
+ rank: number | null
+ excluded: boolean
counts: TrialVerdictCounts
runs: TrialRunJudgmentApi[]
settings: string[]
@@ -58,7 +59,7 @@ export interface TrialVersionResult {
export function trialVersionResults(report: TrialComparisonReportApi, rows: ScoutTrialRow[]): TrialVersionResult[] {
const baselineEvidence = report.evidence.filter((run) => run.variant_id === report.baseline_variant_id)
- const versions = report.variants.map((variant, index) => {
+ const versions: TrialVersionResult[] = report.variants.map((variant, index) => {
const runs = report.runs.filter((run) => run.variant_id === variant.variant_id)
const evidence = report.evidence.filter((run) => run.variant_id === variant.variant_id)
const results = runs.map((run) => rows.find((row) => row.launchId === run.launch_id)?.result)
@@ -73,7 +74,12 @@ export function trialVersionResults(report: TrialComparisonReportApi, rows: Scou
return {
variant,
letter: String.fromCharCode(65 + index),
- rank: 0,
+ rank: null,
+ excluded:
+ variant.total_runs === 0 ||
+ variant.judged_runs !== variant.total_runs ||
+ variant.excluded_runs > 0 ||
+ variant.judge_errors > 0,
counts: trialVariantVerdictCounts(variant.criteria),
runs,
settings: [...new Set(evidence.map((run) => `${run.model} · ${run.reasoning_effort}`))],
@@ -91,8 +97,15 @@ export function trialVersionResults(report: TrialComparisonReportApi, rows: Scou
: null,
}
})
- versions.sort((left, right) => right.counts.passed - left.counts.passed)
+ versions.sort(
+ (left, right) =>
+ Number(left.excluded) - Number(right.excluded) ||
+ (left.excluded ? 0 : right.counts.passed - left.counts.passed)
+ )
for (const [index, version] of versions.entries()) {
+ if (version.excluded) {
+ continue
+ }
version.rank =
index > 0 && version.counts.passed === versions[index - 1].counts.passed
? versions[index - 1].rank
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 56c081ff9eeb..a8a3fceabce5 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -98647,6 +98647,7 @@ export namespace Schemas {
export const TrialComparisonOutcomeStatusEnum = {
Winner: 'winner',
Tie: 'tie',
+ Provisional: 'provisional',
Inconclusive: 'inconclusive',
} as const;