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): resume trial judges after worker restarts (#114646)

Alex Lebedev84a4fad7cb67
diff --git a/docs/internal/scout-online-evals-devbox.md b/docs/internal/scout-online-evals-devbox.md
index e2f0c2a0c9a3..22f2d309d361 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
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 scout and judge deadlines include five minutes for startup and log reads, plus time to collect and save the final result.
+Trial scout deadlines include five minutes for startup and log reads, plus time to collect and save the final result.
Trial plans and evaluation documents keep one complete adopted reference each and exclude suggestion-generation history. The judge reads that same adopted reference from its evidence attachment.
@@ -67,8 +67,10 @@ Judges use ordinary Tasks permissions and logging rather than the scout runs' pr
Scout sandboxes keep private gateway capture and exclude shared context-layer inputs. Tasks no longer calls Signals to interpret trial documents or judge credentials. Shared dispatch preparation, file attachments and budget-stop handling remain unchanged.
-The judge has no live project tools, external MCP connections or repository credentials. Its run disables live context, so the Tasks worker neither mounts the current wiki nor adds Store skill descriptions. Internal Tasks also exclude project and personal instructions. A retry to correct its JSON response uses the same sandbox and keeps these inputs disabled. Deploy the Tasks worker's support for this run setting before starting new judges.
+The judge has no live project tools, external MCP connections or repository credentials. Its run disables live context, so the Tasks worker neither mounts the current wiki nor adds Store skill descriptions. Internal Tasks also exclude project and personal instructions. Deploy the Tasks worker's support for this run setting before starting new judges.
-It returns one verdict per rubric check, with quotes checked against the original saved files. Missing evidence gives an unknown verdict. A judge failure is shown separately from a failed rubric check, and incomplete results cannot win. Judging has a 30-minute runtime limit per run; saved results never rerun the judge when viewed.
+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.
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/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.py
index d504f8e20012..4ae464b2fbef 100644
--- a/posthog/temporal/tests/ai/test_module_integrity.py
+++ b/posthog/temporal/tests/ai/test_module_integrity.py
@@ -104,6 +104,7 @@ class TestSignalsProductModuleIntegrity:
"EmitEvalSignalWorkflow",
"RunSignalsScoutWorkflow",
"RunScoutTrialEvaluationWorkflow",
+ "RunScoutTrialJudgeWorkflow",
"RunScoutTrialComparisonWorkflow",
"SignalsScoutCoordinatorWorkflow",
"RunScoutSuggestionsWorkflow",
@@ -183,6 +184,7 @@ class TestSignalsProductModuleIntegrity:
"prepare_scout_trial_comparison_evaluation_activity",
"finish_scout_trial_comparison_activity",
"judge_scout_trial_run_activity",
+ "poll_scout_trial_judge_activity",
"finish_scout_trial_evaluation_activity",
"resume_signals_scout_workflow_step",
"plan_scout_suggestion_runs_activity",
diff --git a/products/signals/backend/scout_harness/limits.py b/products/signals/backend/scout_harness/limits.py
index 76b9726d5a31..bb20f6917be7 100644
--- a/products/signals/backend/scout_harness/limits.py
+++ b/products/signals/backend/scout_harness/limits.py
@@ -61,7 +61,7 @@ MAX_TRIAL_VARIANTS = 20
MAX_TRIAL_REPEATS = 20
MAX_TRIAL_RUNS = MAX_TRIAL_VARIANTS * MAX_TRIAL_REPEATS
TRIAL_JUDGE_CONCURRENCY = 3
-TRIAL_JUDGE_TIMEOUT_MINUTES = TRIAL_ACTIVITY_TIMEOUT_S // 60 + 2
+TRIAL_JUDGE_TIMEOUT_MINUTES = 33
# Leave time to load evidence and save the report after every judging wave.
TRIAL_EVALUATION_TIMEOUT_MINUTES = -(-MAX_TRIAL_RUNS // TRIAL_JUDGE_CONCURRENCY) * TRIAL_JUDGE_TIMEOUT_MINUTES + 10
diff --git a/products/signals/backend/scout_harness/trial_evaluation.py b/products/signals/backend/scout_harness/trial_evaluation.py
index 2c776d73d0a9..9d6ee07983b1 100644
--- a/products/signals/backend/scout_harness/trial_evaluation.py
+++ b/products/signals/backend/scout_harness/trial_evaluation.py
@@ -10,10 +10,11 @@ from uuid import UUID
from django.utils import timezone
from pydantic import BaseModel, JsonValue, ValidationError
+from rest_framework.exceptions import NotFound, PermissionDenied
from posthog.clickhouse.query_tagging import private_capture_context
from posthog.dataclasses import frozen
-from posthog.models import Team, User
+from posthog.models import User
from posthog.storage import object_storage
from posthog.sync import database_sync_to_async
@@ -29,6 +30,7 @@ from products.signals.backend.scout_harness.trial_comparison_types import (
from products.signals.backend.scout_harness.trial_evaluation_report import build_trial_comparison_report
from products.signals.backend.scout_harness.trial_evaluation_types import (
TrialComparisonReport,
+ TrialEvaluationAccess,
TrialEvaluationCriterion,
TrialEvaluationRequest,
TrialEvaluationSnapshot,
@@ -231,7 +233,10 @@ def _read_trial_judge_input(team_id: int, evaluation_id: UUID, launch_id: UUID)
def _assert_context_access(
- context: TrialContext | TrialComparisonHistoryEntry | TrialComparisonPlan, *, config: SignalScoutConfig, user: User
+ context: TrialContext | TrialComparisonHistoryEntry | TrialComparisonPlan | TrialEvaluationAccess,
+ *,
+ config: SignalScoutConfig,
+ user: User,
) -> None:
if (
config.team_id != 2
@@ -259,7 +264,7 @@ def assert_evaluation_access(snapshot: TrialEvaluationSnapshot, *, config: Signa
_assert_context_access(load_trial_context(snapshot.team_id, snapshot.context_id), config=config, user=user)
-def _assert_worker_access(snapshot: TrialEvaluationSnapshot) -> None:
+def _assert_worker_access(snapshot: TrialEvaluationSnapshot, *, use_saved_access: bool = False) -> None:
assert_trial_environment_ready()
config = (
SignalScoutConfig.objects.for_team(snapshot.team_id)
@@ -270,6 +275,23 @@ def _assert_worker_access(snapshot: TrialEvaluationSnapshot) -> None:
user = User.objects.filter(id=snapshot.user_id, is_active=True).first()
if config is None or user is None:
raise TrialEvaluationError("The evaluation is no longer available to this operator.")
+ access = (
+ _read_document(_key(snapshot.team_id, snapshot.evaluation_id, "access"), TrialEvaluationAccess)
+ if use_saved_access
+ else None
+ )
+ if access is not None:
+ if (
+ access.evaluation_id != snapshot.evaluation_id
+ or access.team_id != snapshot.team_id
+ or access.config_id != snapshot.config_id
+ or access.user_id != snapshot.user_id
+ or access.context_id != snapshot.context_id
+ ):
+ raise TrialEvaluationError("The saved source identity does not match this evaluation.")
+ # Polls only need the frozen source identity; current permissions are still checked every time.
+ _assert_context_access(access, config=config, user=user)
+ return
assert_evaluation_access(snapshot, config=config, user=user)
@@ -640,6 +662,20 @@ def prepare_trial_evaluation(
stored = _write_once(_key(config.team_id, request.evaluation_id, "snapshot"), snapshot)
if stored.request_hash != request_hash:
raise TrialEvaluationError("This evaluation ID was already used for a different request.")
+ if stored.context_id != context.id:
+ raise TrialEvaluationError("The saved evaluation uses a different starting context.")
+ access = TrialEvaluationAccess(
+ evaluation_id=stored.evaluation_id,
+ team_id=stored.team_id,
+ config_id=stored.config_id,
+ user_id=stored.user_id,
+ context_id=context.id,
+ skill_name=context.skill_name,
+ skill_version=context.skill_version,
+ )
+ saved_access = _write_once(_key(stored.team_id, stored.evaluation_id, "access"), access)
+ if saved_access != access:
+ raise TrialEvaluationError("The saved source identity does not match this evaluation.")
_save_trial_judge_inputs(stored)
return stored
@@ -672,22 +708,7 @@ def _error_judgment(evidence: TrialRunEvidence, error: str | None = None) -> Tri
)
-def _claim_judgment(snapshot: TrialEvaluationSnapshot, evidence: TrialRunEvidence) -> bool:
- key = _key(snapshot.team_id, snapshot.evaluation_id, f"attempts/{evidence.launch_id}")
- try:
- object_storage.write(
- key,
- _error_judgment(evidence).model_dump_json(),
- extras={"ContentType": "application/json", "IfNoneMatch": "*"},
- )
- except object_storage.ObjectStorageError:
- if _read_document(key, TrialRunJudgment) is None:
- raise
- return False
- return True
-
-
-async def run_evaluation_run(team_id: int, evaluation_id: UUID, launch_id: UUID) -> None:
+async def run_evaluation_run(team_id: int, evaluation_id: UUID, launch_id: UUID) -> bool:
from products.signals.backend.scout_harness.trial_judge import ( # noqa: PLC0415 -- keep judge dependencies off API startup
TrialJudgeExecutionError,
judge_trial_run,
@@ -702,7 +723,7 @@ async def run_evaluation_run(team_id: int, evaluation_id: UUID, launch_id: UUID)
if evidence is None:
raise TrialEvaluationError("The trial is not part of this evaluation.")
if await asyncio.to_thread(_read_judgment, snapshot, evidence) is not None:
- return
+ return True
if evidence.exclusion_reason:
judgment = TrialRunJudgment(
launch_id=launch_id,
@@ -711,24 +732,22 @@ async def run_evaluation_run(team_id: int, evaluation_id: UUID, launch_id: UUID)
summary=evidence.exclusion_reason,
)
else:
- await database_sync_to_async(assert_trial_work_enabled)(
- await database_sync_to_async(Team.objects.get)(pk=team_id)
- )
step = "access_check"
try:
- await database_sync_to_async(_assert_worker_access)(snapshot)
- step = "judgment_claim"
- if not await asyncio.to_thread(_claim_judgment, snapshot, evidence):
- return
+ await database_sync_to_async(_assert_worker_access)(snapshot, use_saved_access=True)
step = "judge_execution"
- judgment = await judge_trial_run(snapshot, evidence)
+ collected_judgment = await judge_trial_run(snapshot, evidence)
+ if collected_judgment is None:
+ return False
+ judgment = collected_judgment
if judgment.launch_id != launch_id or judgment.variant_id != evidence.variant_id:
- judgment = _error_judgment(evidence)
+ judgment = _error_judgment(evidence, "The judge returned a result for another trial run.")
except TrialJudgeExecutionError as error:
judgment = _error_judgment(evidence, str(error))
- except Exception as error:
+ except (TrialEvaluationError, NotFound, PermissionDenied) as error:
judgment = _error_judgment(evidence, safe_judge_failure(step, error))
await asyncio.to_thread(_write_once, _key(team_id, evaluation_id, f"runs/{launch_id}"), judgment)
+ return True
@private_capture_context()
@@ -754,6 +773,10 @@ def finish_trial_evaluation(team_id: int, evaluation_id: UUID) -> TrialCompariso
for evidence in snapshot.runs:
judgment = _read_judgment(snapshot, evidence)
if judgment is None:
+ if not evidence.exclusion_reason:
+ raise TrialEvaluationNotReady(
+ "Judging has not finished. Resume this evaluation to collect its results."
+ )
judgment = _write_once(
_key(team_id, evaluation_id, f"runs/{evidence.launch_id}"), _error_judgment(evidence)
)
diff --git a/products/signals/backend/scout_harness/trial_evaluation_types.py b/products/signals/backend/scout_harness/trial_evaluation_types.py
index 4e5c1b9e6798..ec8ce18a57fb 100644
--- a/products/signals/backend/scout_harness/trial_evaluation_types.py
+++ b/products/signals/backend/scout_harness/trial_evaluation_types.py
@@ -34,6 +34,16 @@ class TrialEvaluationRequest(EvaluationDocument):
rubric_source: Literal["saved"]
+class TrialEvaluationAccess(EvaluationDocument):
+ evaluation_id: UUID
+ team_id: int
+ config_id: UUID
+ user_id: int
+ context_id: UUID
+ skill_name: str
+ skill_version: int = Field(ge=1)
+
+
class TrialEvaluationSnapshot(EvaluationDocument):
version: Literal[1] = 1
evaluation_id: UUID
diff --git a/products/signals/backend/scout_harness/trial_judge.py b/products/signals/backend/scout_harness/trial_judge.py
index 280389d35978..3c322efff224 100644
--- a/products/signals/backend/scout_harness/trial_judge.py
+++ b/products/signals/backend/scout_harness/trial_judge.py
@@ -1,24 +1,33 @@
from __future__ import annotations
+import json
import asyncio
from dataclasses import field
+from datetime import timedelta
from uuid import UUID, uuid5
+from django.db import IntegrityError
+from django.utils import timezone
+
from pydantic import JsonValue
from posthog.clickhouse.query_tagging import private_capture_context
from posthog.dataclasses import frozen
+from posthog.models import Team
from posthog.sync import database_sync_to_async
from products.signals.backend import trial_judging
from products.signals.backend.models import SignalScoutRun
-from products.signals.backend.scout_harness.limits import TRIAL_ACTIVITY_TIMEOUT_S
from products.signals.backend.scout_harness.trial_evaluation import (
+ TrialEvaluationError,
read_trial_evidence_sources,
trial_evidence_storage_key,
)
from products.signals.backend.scout_harness.trial_evaluation_types import TrialEvaluationSnapshot
-from products.signals.backend.scout_harness.trial_launch import assert_trial_environment_ready
+from products.signals.backend.scout_harness.trial_launch import (
+ assert_trial_environment_ready,
+ assert_trial_work_enabled,
+)
from products.signals.backend.scout_harness.trial_state import ScoutTrialStore
from products.signals.backend.temporal.agentic import get_or_create_signals_sandbox_env
from products.signals.backend.trial_judging import (
@@ -32,16 +41,10 @@ from products.signals.backend.trial_judging import (
)
from products.signals.backend.trial_judging_types import TrialJudgeVerdicts, TrialRunEvidence, TrialRunJudgment
from products.tasks.backend.facade import api as tasks_facade
-from products.tasks.backend.facade.agents import CustomPromptSandboxContext, MultiTurnSession
-from products.tasks.backend.facade.contracts import TaskRunInputFile
+from products.tasks.backend.facade.contracts import TaskRunDTO, TaskRunInputFile
JUDGE_MAX_RUNTIME_SECONDS = 30 * 60
JUDGE_SANDBOX_ENVIRONMENT = "SIGNALS_SCOUT_TRIAL_JUDGE"
-_JSON_RETRY_PROMPT = (
- "Return the complete JSON object with summary and one result per supplied criterion. "
- "Use the required schema, without prose or code fences. Preserve your assessment and exact citations. "
- "Do not invent missing evidence; mark unsupported conclusions unknown."
-)
def _judging_input(snapshot: TrialEvaluationSnapshot) -> TrialJudgeInput:
@@ -93,21 +96,23 @@ def _assert_scout_available(snapshot: TrialEvaluationSnapshot, evidence: TrialRu
raise TrialJudgeValidationError("The scout trial was invalidated after its evidence was saved.")
+def _has_assessment(output: dict | None) -> bool:
+ return isinstance(output, dict) and "summary" in output and "criteria" in output
+
+
def _token_count(state: dict[str, object], field_name: str) -> int | None:
usage = state.get("token_usage")
value = usage.get(field_name) if isinstance(usage, dict) else None
return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else None
-@frozen(frozen=False)
+@frozen
class _JudgeRun:
snapshot: TrialEvaluationSnapshot = field(repr=False)
evidence: TrialRunEvidence = field(repr=False)
prompt: str = field(repr=False)
- run_id: UUID | None = None
def bind_before_dispatch(self, run_id: UUID) -> dict[str, JsonValue]:
- self.run_id = run_id
files = [
TaskRunInputFile(
id=str(uuid5(run_id, file.id)),
@@ -128,107 +133,130 @@ class _JudgeRun:
"include_live_context": False,
}
- def fail_unfinished(self, error: str) -> None:
- if self.run_id is None:
- return
- run = tasks_facade.get_task_run(self.run_id, team_id=self.snapshot.team_id)
- if run is not None:
- tasks_facade.update_task_run(
- run.id,
- run.task_id,
- self.snapshot.team_id,
- validated_data={"status": "failed", "error_message": error},
- only_if_non_terminal=True,
- )
-
+ @property
+ def origin_key(self) -> str:
+ return f"scout-trial-judge:{self.snapshot.evaluation_id}:{self.evidence.launch_id}"
-async def _finish_judge(session: MultiTurnSession | None, judge_run: _JudgeRun | None, failure: str | None) -> None:
- try:
- if session is not None:
- await session.end(status="failed" if failure else "completed", error=failure)
- except (Exception, asyncio.CancelledError):
- failure = failure or "The judge could not complete its sandbox cleanup."
- raise
- finally:
- if failure is not None and judge_run is not None:
- await database_sync_to_async(judge_run.fail_unfinished)(failure)
+ def existing(self) -> TaskRunDTO | None:
+ task = tasks_facade.get_task_by_origin_key(self.snapshot.team_id, self.origin_key)
+ if task is None:
+ return None
+ if task.latest_run_id is None:
+ raise TrialJudgeExecutionError("The saved judge task has no run.")
+ run = tasks_facade.get_task_run(task.latest_run_id, team_id=self.snapshot.team_id)
+ if (
+ run is None
+ or run.task_id != task.id
+ or run.created_by_id != self.snapshot.user_id
+ or run.task_origin_product != tasks_facade.TaskOriginProduct.SIGNALS_SCOUT_SUGGESTIONS
+ ):
+ raise TrialJudgeExecutionError("The saved judge task is unavailable for this evaluation.")
+ return run
-
-async def judge_trial_run(snapshot: TrialEvaluationSnapshot, evidence: TrialRunEvidence) -> TrialRunJudgment:
- session: MultiTurnSession | None = None
- judge_run: _JudgeRun | None = None
- failure: str | None = None
- with private_capture_context():
+ def create(self) -> TaskRunDTO:
+ team = Team.objects.get(pk=self.snapshot.team_id)
+ assert_trial_work_enabled(team)
+ environment_id = get_or_create_signals_sandbox_env(
+ self.snapshot.team_id,
+ JUDGE_SANDBOX_ENVIRONMENT,
+ tasks_facade.SandboxNetworkAccessLevel.CUSTOM,
+ allowed_domains=[],
+ include_default_domains=False,
+ )
try:
- await database_sync_to_async(_assert_scout_available)(snapshot, evidence)
- prompt = trial_judging.build_trial_judge_prompt(_judging_input(snapshot), evidence)
- sources = await asyncio.to_thread(read_trial_evidence_sources, snapshot, evidence)
- origin_key = f"scout-trial-judge:{snapshot.evaluation_id}:{evidence.launch_id}"
- existing = await database_sync_to_async(tasks_facade.get_task_by_origin_key)(snapshot.team_id, origin_key)
- if existing is not None:
- raise TrialJudgeExecutionError(
- "This run already has a judge task. Start a new evaluation to judge it again."
- )
- environment_id = await database_sync_to_async(get_or_create_signals_sandbox_env)(
- snapshot.team_id,
- JUDGE_SANDBOX_ENVIRONMENT,
- tasks_facade.SandboxNetworkAccessLevel.CUSTOM,
- allowed_domains=[],
- include_default_domains=False,
- )
- context = CustomPromptSandboxContext(
- team_id=snapshot.team_id,
- user_id=snapshot.user_id,
+ created = tasks_facade.create_and_run_task(
+ team=team,
+ title="[sandbox_prompt:scout_trial_judge] Assess a saved scout run",
+ description=self.prompt,
+ # Reuse rubric generation's repo-less internal sandbox policy.
+ origin_product=tasks_facade.TaskOriginProduct.SIGNALS_SCOUT_SUGGESTIONS,
+ origin_key=self.origin_key,
+ user_id=self.snapshot.user_id,
+ create_pr=False,
+ mode="background",
+ internal=True,
sandbox_environment_id=environment_id,
posthog_mcp_scopes=[],
- model=snapshot.judge_model,
+ model=self.snapshot.judge_model,
runtime_adapter="codex",
reasoning_effort="high",
initial_permission_mode="full-access",
github_read_access=False,
- sandbox_timeout_seconds=TRIAL_ACTIVITY_TIMEOUT_S + 60,
+ sandbox_timeout_seconds=JUDGE_MAX_RUNTIME_SECONDS + 120,
+ inactivity_timeout_seconds=JUDGE_MAX_RUNTIME_SECONDS,
+ ai_stage="scout:trial_judge",
+ mcp_builtin_agent_key="scout",
+ mcp_gateway_server_ids=[],
+ before_task_dispatch=self.bind_before_dispatch,
+ output_schema=TrialJudgeVerdicts.model_json_schema(),
)
+ except IntegrityError:
+ # Task creation rolls back before this lookup; its unique origin key owns dispatch.
+ existing = self.existing()
+ if existing is None:
+ raise
+ return existing
+ if created.latest_run is None:
+ raise TrialJudgeExecutionError("The judge task was created without a run.")
+ return created.latest_run
+
+ def expire(self, run: TaskRunDTO) -> TaskRunDTO:
+ error = "The judge did not finish within 30 minutes."
+ updated = tasks_facade.update_task_run(
+ run.id,
+ run.task_id,
+ self.snapshot.team_id,
+ validated_data={"status": "failed", "error_message": error},
+ only_if_non_terminal=True,
+ )
+ if updated is not None and updated.status == "completed":
+ completed = tasks_facade.get_task_run(run.id, team_id=self.snapshot.team_id)
+ if completed is not None:
+ return completed
+ raise TrialJudgeExecutionError(error)
+
+
+async def judge_trial_run(snapshot: TrialEvaluationSnapshot, evidence: TrialRunEvidence) -> TrialRunJudgment | None:
+ with private_capture_context():
+ try:
+ await database_sync_to_async(_assert_scout_available)(snapshot, evidence)
+ prompt = trial_judging.build_trial_judge_prompt(_judging_input(snapshot), evidence)
judge_run = _JudgeRun(snapshot=snapshot, evidence=evidence, prompt=prompt)
- async with asyncio.timeout(TRIAL_ACTIVITY_TIMEOUT_S):
- session, output = await MultiTurnSession.start(
- prompt=prompt,
- context=context,
- model=TrialJudgeVerdicts,
- step_name="scout_trial_judge",
- ai_stage="scout:trial_judge",
- # Reuse rubric generation's repo-less internal sandbox policy.
- origin_product=tasks_facade.TaskOriginProduct.SIGNALS_SCOUT_SUGGESTIONS,
- origin_key=origin_key,
- internal=True,
- mcp_builtin_agent_key="scout",
- mcp_gateway_server_ids=[],
- before_task_dispatch=judge_run.bind_before_dispatch,
- max_poll_seconds=JUDGE_MAX_RUNTIME_SECONDS,
- json_retry_prompt=_JSON_RETRY_PROMPT,
+ run = await database_sync_to_async(judge_run.existing)()
+ if run is None:
+ await asyncio.to_thread(read_trial_evidence_sources, snapshot, evidence)
+ run = await database_sync_to_async(judge_run.create)()
+ if run.status in {"failed", "cancelled"}:
+ raise TrialJudgeExecutionError(
+ "The judge task failed before saving its assessment."
+ if run.status == "failed"
+ else "The judge task was cancelled before saving its assessment."
)
- verdicts = parse_trial_judgment(output.model_dump_json(), criteria=snapshot.criteria, sources=sources)
- run = await database_sync_to_async(tasks_facade.get_task_run)(session.task_run.id, team_id=snapshot.team_id)
+ if run.status != "completed":
+ if run.created_at is None:
+ raise TrialJudgeExecutionError("The judge task has no saved start time.")
+ if timezone.now() < run.created_at + timedelta(seconds=JUDGE_MAX_RUNTIME_SECONDS):
+ return None
+ # Tasks saves the output before it records completion, so a lost completion signal leaves the run open.
+ if not _has_assessment(run.output):
+ run = await database_sync_to_async(judge_run.expire)(run)
+ output = run.output
+ 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(
+ json.dumps({"summary": output["summary"], "criteria": output["criteria"]}, ensure_ascii=False),
+ criteria=snapshot.criteria,
+ sources=sources,
+ )
return TrialRunJudgment(
launch_id=evidence.launch_id,
variant_id=evidence.variant_id,
status="judged",
summary=verdicts.summary,
criteria=verdicts.criteria,
- input_tokens=_token_count(run.state, "input_tokens") if run is not None else None,
- output_tokens=_token_count(run.state, "output_tokens") if run is not None else None,
+ input_tokens=_token_count(run.state, "input_tokens"),
+ output_tokens=_token_count(run.state, "output_tokens"),
)
- except asyncio.CancelledError:
- failure = "The judge was cancelled before its assessment finished."
- raise
- except TrialJudgeExecutionError as error:
- failure = str(error)
- raise
- except Exception as error:
- failure = safe_judge_failure("sandbox_judge", error)
- raise TrialJudgeExecutionError(failure) from None
- finally:
- try:
- await asyncio.shield(asyncio.wait_for(_finish_judge(session, judge_run, failure), timeout=30))
- except Exception as error:
- if failure is None:
- raise TrialJudgeExecutionError(safe_judge_failure("sandbox_cleanup", error)) from None
+ except (TrialJudgeValidationError, TrialEvaluationError) as error:
+ raise TrialJudgeExecutionError(str(error)) from None
diff --git a/products/signals/backend/temporal/__init__.py b/products/signals/backend/temporal/__init__.py
index 8119e7fab349..2b86e38875cc 100644
--- a/products/signals/backend/temporal/__init__.py
+++ b/products/signals/backend/temporal/__init__.py
@@ -32,9 +32,11 @@ from products.signals.backend.temporal.agentic.scout_trial_comparison import (
)
from products.signals.backend.temporal.agentic.scout_trial_evaluation import (
RunScoutTrialEvaluationWorkflow,
+ RunScoutTrialJudgeWorkflow,
finish_scout_trial_evaluation_activity,
judge_scout_trial_run_activity,
load_scout_trial_evaluation_activity,
+ poll_scout_trial_judge_activity,
)
from products.signals.backend.temporal.agentic.select_repository import select_repository_activity
from products.signals.backend.temporal.backfill_error_tracking import (
@@ -122,6 +124,7 @@ WORKFLOWS = [
CustomSignalAgentWorkflow,
RunSignalsScoutWorkflow,
RunScoutTrialEvaluationWorkflow,
+ RunScoutTrialJudgeWorkflow,
RunScoutTrialComparisonWorkflow,
SignalsScoutCoordinatorWorkflow,
RunScoutSuggestionsWorkflow,
@@ -136,6 +139,7 @@ ACTIVITIES = [
prepare_scout_trial_comparison_evaluation_activity,
finish_scout_trial_comparison_activity,
judge_scout_trial_run_activity,
+ poll_scout_trial_judge_activity,
finish_scout_trial_evaluation_activity,
generate_scout_rubrics_activity,
fail_scout_rubrics_activity,
diff --git a/products/signals/backend/temporal/agentic/scout_trial_evaluation.py b/products/signals/backend/temporal/agentic/scout_trial_evaluation.py
index afccd79f81bb..6b1d6bccdfbe 100644
--- a/products/signals/backend/temporal/agentic/scout_trial_evaluation.py
+++ b/products/signals/backend/temporal/agentic/scout_trial_evaluation.py
@@ -11,7 +11,7 @@ from asgiref.sync import async_to_sync
from temporalio import activity, workflow
from temporalio.client import WorkflowExecutionStatus
from temporalio.common import RetryPolicy, WorkflowIDConflictPolicy, WorkflowIDReusePolicy
-from temporalio.exceptions import ActivityError, ApplicationError, WorkflowAlreadyStartedError
+from temporalio.exceptions import ActivityError, ApplicationError, ChildWorkflowError, WorkflowAlreadyStartedError
from temporalio.service import RPCError, RPCStatusCode
from posthog.clickhouse.query_tagging import private_capture_context
@@ -59,11 +59,11 @@ async def load_scout_trial_evaluation_activity(inputs: TrialEvaluationInput) ->
raise ValueError("Missing evaluation")
return [str(run.launch_id) for run in snapshot.runs]
except Exception as error:
- raise ApplicationError(safe_judge_failure("snapshot_load", error), non_retryable=True) from None
+ raise ApplicationError(safe_judge_failure("snapshot_load", error)) from None
@activity.defn
-async def judge_scout_trial_run_activity(inputs: TrialEvaluationRunInput) -> None:
+async def poll_scout_trial_judge_activity(inputs: TrialEvaluationRunInput) -> bool:
from products.signals.backend.scout_harness.trial_evaluation import ( # noqa: PLC0415 -- avoid loading the harness through the workflow registry
run_evaluation_run,
)
@@ -77,11 +77,18 @@ async def judge_scout_trial_run_activity(inputs: TrialEvaluationRunInput) -> Non
with private_capture_context():
try:
async with Heartbeater():
- await run_evaluation_run(inputs.team_id, UUID(inputs.evaluation_id), UUID(inputs.launch_id))
+ return await run_evaluation_run(inputs.team_id, UUID(inputs.evaluation_id), UUID(inputs.launch_id))
except ScoutTrialsDisabled as error:
raise ApplicationError(str(error), type="ScoutTrialsDisabled", non_retryable=True) from None
except Exception as error:
- raise ApplicationError(safe_judge_failure("judge_activity", error), non_retryable=True) from None
+ raise ApplicationError(safe_judge_failure("judge_activity", error)) from None
+
+
+async def judge_scout_trial_run_activity(inputs: TrialEvaluationRunInput) -> None:
+ # Existing evaluation histories still schedule the long-lived activity during a rollout.
+ while not await poll_scout_trial_judge_activity(inputs):
+ await asyncio.sleep(10)
@activity.defn
@@ -99,7 +106,35 @@ async def finish_scout_trial_evaluation_activity(inputs: TrialEvaluationInput) -
inputs.team_id, UUID(inputs.evaluation_id)
)
except Exception as error:
- raise ApplicationError(safe_judge_failure("report_save", error), non_retryable=True) from None
+ raise ApplicationError(safe_judge_failure("report_save", error)) from None
+
+
+class RunScoutTrialJudgeWorkflow:
+ @workflow.run
+ async def run(self, inputs: TrialEvaluationRunInput) -> None:
+ deadline = workflow.now() + timedelta(minutes=TRIAL_JUDGE_TIMEOUT_MINUTES)
+ while True:
+ remaining = deadline - workflow.now()
+ if remaining <= timedelta(0):
+ raise ApplicationError("The judge status could not be collected before the evaluation deadline.")
+ finished = await workflow.execute_activity(
+ poll_scout_trial_judge_activity,
+ inputs,
+ start_to_close_timeout=min(timedelta(minutes=2), remaining),
+ schedule_to_close_timeout=remaining,
+ heartbeat_timeout=timedelta(seconds=30),
+ retry_policy=RetryPolicy(initial_interval=timedelta(seconds=5), maximum_interval=timedelta(seconds=30)),
+ )
+ if finished:
+ return
+ await workflow.sleep(timedelta(seconds=10))
+
+
+def _trials_disabled(error: BaseException | None) -> bool:
+ while isinstance(error, (ActivityError, ChildWorkflowError)):
+ error = error.cause
+ return isinstance(error, ApplicationError) and error.type == "ScoutTrialsDisabled"
@workflow.defn
@@ -110,38 +145,47 @@ class RunScoutTrialEvaluationWorkflow:
load_scout_trial_evaluation_activity,
inputs,
start_to_close_timeout=timedelta(minutes=1),
- retry_policy=RetryPolicy(maximum_attempts=1),
+ schedule_to_close_timeout=timedelta(minutes=3),
)
judge_timeout = timedelta(minutes=TRIAL_JUDGE_TIMEOUT_MINUTES)
+ # Bound collectors; a timed-out collector can leave its Task running until its own deadline.
semaphore = asyncio.Semaphore(TRIAL_JUDGE_CONCURRENCY)
+ resumable_judges = workflow.patched("scout-trial-resumable-judges")
- async def score(launch_id: str) -> bool:
+ async def score(launch_id: str) -> None:
async with semaphore:
- try:
+ run_input = TrialEvaluationRunInput(
+ team_id=inputs.team_id, evaluation_id=inputs.evaluation_id, launch_id=launch_id
+ )
+ if resumable_judges:
+ # Separate histories keep the largest supported trial below Temporal's event limit.
+ await workflow.execute_child_workflow(
+ RunScoutTrialJudgeWorkflow.run,
+ run_input,
+ id=f"{workflow.info().workflow_id}:judge:{launch_id}",
+ execution_timeout=judge_timeout,
+ )
+ else:
+ # Preserve scheduled activity commands when replaying across a worker rollout.
await workflow.execute_activity(
judge_scout_trial_run_activity,
- TrialEvaluationRunInput(
- team_id=inputs.team_id, evaluation_id=inputs.evaluation_id, launch_id=launch_id
- ),
+ run_input,
start_to_close_timeout=judge_timeout,
heartbeat_timeout=timedelta(seconds=30),
retry_policy=RetryPolicy(maximum_attempts=1),
)
- except ActivityError as error:
- if isinstance(error.cause, ApplicationError) and error.cause.type == "ScoutTrialsDisabled":
- return True
- # Finalization records missing outcomes without buying another judge call.
- return False
-
- blocked = await asyncio.gather(*(score(launch_id) for launch_id in launch_ids))
- if any(blocked):
- # Keep unstarted judgments resumable after active activities have saved their results.
+
+ outcomes = await asyncio.gather(*(score(launch_id) for launch_id in launch_ids), return_exceptions=True)
+ if any(_trials_disabled(outcome) for outcome in outcomes):
raise ApplicationError("Scout trials are disabled. Resume when they are enabled again.", non_retryable=True)
+ if resumable_judges and any(isinstance(outcome, BaseException) for outcome in outcomes):
+ # Keep completed judgments, and let a retry reconnect to the remaining Tasks.
+ raise ApplicationError("Some judge results could not be collected. Resume this evaluation to try again.")
await workflow.execute_activity(
finish_scout_trial_evaluation_activity,
inputs,
start_to_close_timeout=timedelta(minutes=1),
- retry_policy=RetryPolicy(maximum_attempts=1),
+ schedule_to_close_timeout=timedelta(minutes=3),
)
return inputs.evaluation_id
diff --git a/products/signals/backend/test/test_scout_trial_comparison.py b/products/signals/backend/test/test_scout_trial_comparison.py
index 8dafc300056f..b936d7a68a7c 100644
--- a/products/signals/backend/test/test_scout_trial_comparison.py
+++ b/products/signals/backend/test/test_scout_trial_comparison.py
@@ -121,7 +121,7 @@ class TestScoutTrialComparisonWorkflow(SimpleTestCase):
assert prepared and finished and not failed
async def test_judging_wait_bounds_sandbox_evaluation_workflows(self) -> None:
- expected_minutes = 5107
+ expected_minutes = 4437
inputs = TrialComparisonInput(team_id=2, comparison_id=str(uuid4()))
now = datetime(2026, 1, 1, tzinfo=UTC)
started = now
@@ -166,7 +166,7 @@ class TestScoutTrialComparisonWorkflow(SimpleTestCase):
assert start_trial_comparison(2, comparison_id) == first
for call in client.start_workflow.await_args_list:
assert call.kwargs["id"] == first
- assert call.kwargs["execution_timeout"] == timedelta(minutes=5192)
+ assert call.kwargs["execution_timeout"] == timedelta(minutes=4522)
assert call.kwargs["id_conflict_policy"] == WorkflowIDConflictPolicy.USE_EXISTING
assert call.kwargs["id_reuse_policy"] == WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY
assert call.args[1] == TrialComparisonInput(team_id=2, comparison_id=str(comparison_id))
diff --git a/products/signals/backend/test/test_scout_trial_evaluation.py b/products/signals/backend/test/test_scout_trial_evaluation.py
index ab8bc904fdc0..93dde0c708c0 100644
--- a/products/signals/backend/test/test_scout_trial_evaluation.py
+++ b/products/signals/backend/test/test_scout_trial_evaluation.py
@@ -17,8 +17,11 @@ from django.utils import timezone
from asgiref.sync import async_to_sync
from parameterized import parameterized
from pydantic import BaseModel
+from temporalio import activity, workflow
from temporalio.common import RetryPolicy
-from temporalio.exceptions import ActivityError, ApplicationError
+from temporalio.exceptions import ActivityError, ApplicationError, ChildWorkflowError
+from temporalio.testing import ActivityEnvironment, WorkflowEnvironment
+from temporalio.worker import Replayer, UnsandboxedWorkflowRunner, Worker
from posthog.models import Team, User
from posthog.models.scoping import team_scope
@@ -68,21 +71,18 @@ from products.signals.backend.scout_harness.trial_judge import (
judge_trial_run,
parse_trial_judgment,
)
-from products.signals.backend.scout_harness.trial_launch import (
- ScoutTrialLaunchError,
- ScoutTrialsDisabled,
- TrialContext,
- TrialLaunch,
-)
+from products.signals.backend.scout_harness.trial_launch import ScoutTrialLaunchError, TrialContext, TrialLaunch
from products.signals.backend.scout_harness.trial_result import TrialWorkflowStatus, export_trial_result
from products.signals.backend.scout_harness.trial_rubrics import SavedScoutRubricReader
from products.signals.backend.scout_harness.trial_state import ScoutTrialStore, TrialReport
from products.signals.backend.temporal.agentic.scout_trial_evaluation import (
RunScoutTrialEvaluationWorkflow,
+ RunScoutTrialJudgeWorkflow,
TrialEvaluationInput,
TrialEvaluationRunInput,
finish_scout_trial_evaluation_activity,
load_scout_trial_evaluation_activity,
+ poll_scout_trial_judge_activity,
start_trial_evaluation,
)
from products.signals.backend.test.test_scout_harness_api import _make_run
@@ -278,6 +278,19 @@ class TestScoutTrialEvaluation(BaseTest):
def _sources(self, snapshot: TrialEvaluationSnapshot) -> list[TrialEvidenceSource]:
return read_trial_evidence_sources(snapshot, snapshot.runs[0])
+ def _save_judgments(self, snapshot: TrialEvaluationSnapshot) -> None:
+ for evidence in snapshot.runs:
+ judgment = TrialRunJudgment(
+ launch_id=evidence.launch_id,
+ variant_id=evidence.variant_id,
+ status="judge_error",
+ summary="Synthetic unavailable judgment.",
+ error="Synthetic judge failure.",
+ )
+ self.documents[
+ f"signals/scout-trials/{snapshot.team_id}/evaluations/{snapshot.evaluation_id}/runs/{evidence.launch_id}.json"
+ ] = judgment.model_dump_json()
+
def test_saves_and_reads_frozen_evidence_for_more_than_twenty_runs(self) -> None:
template = prepare_trial_evaluation(config=self.config, user=self.user, request=self.request).runs[0]
variants = [
@@ -353,6 +366,11 @@ class TestScoutTrialEvaluation(BaseTest):
snapshot = prepare_trial_evaluation(config=self.config, user=self.user, request=self.request)
assert snapshot.judge_prompt_version == JUDGE_PROMPT_VERSION
assert snapshot.judge_model == "gpt-6-astra"
+ saved = json.loads(
+ self.documents[f"signals/scout-trials/{self.team.id}/evaluations/{snapshot.evaluation_id}/snapshot.json"]
+ )
+ assert "skill_name" not in saved
+ assert "skill_version" not in saved
self.scout_run.summary = "A later edit must not change the evidence."
self.scout_run.save(update_fields=["summary"])
self.skill.body = "The current skill changed after capture."
@@ -376,12 +394,18 @@ class TestScoutTrialEvaluation(BaseTest):
def test_saved_report_remains_readable_when_launches_are_disabled(self) -> None:
snapshot = prepare_trial_evaluation(config=self.config, user=self.user, request=self.request)
+ self._save_judgments(snapshot)
report = finish_trial_evaluation(self.team.id, snapshot.evaluation_id)
with override_settings(SCOUT_LIVE_TRIALS_PRIVATE_CAPTURE=False):
assert_evaluation_access(snapshot, config=self.config, user=self.user)
assert read_trial_evaluation_report(snapshot) == report
with self.assertRaises(ScoutTrialLaunchError):
prepare_trial_evaluation(config=self.config, user=self.user, request=self.request)
+ self._save("contexts", self.context.id, self.context.model_copy(update={"user_id": self.user.id + 1}))
+ with self.assertRaises(TrialEvaluationError):
+ assert_evaluation_access(snapshot, config=self.config, user=self.user)
+ with self.assertRaises(TrialEvaluationError):
+ finish_trial_evaluation(self.team.id, snapshot.evaluation_id)
@parameterized.expand(
[
@@ -476,6 +500,7 @@ class TestScoutTrialEvaluation(BaseTest):
assert read_trial_evaluation(self.team.id, prepared.evaluation_id) == prepared
snapshot = _read_trial_judge_input(self.team.id, prepared.evaluation_id, self.launch.id)
assert snapshot is not None
+ self._save_judgments(prepared)
assert (
finish_trial_evaluation(self.team.id, prepared.evaluation_id).rubric_reference_context == self.reference
)
@@ -606,10 +631,10 @@ class TestScoutTrialEvaluation(BaseTest):
else:
evidence = evidence.model_copy(update={"launch_id": uuid4()})
- with patch(f"{JUDGE_MODULE}.MultiTurnSession.start", new_callable=AsyncMock) as start:
+ with patch(f"{JUDGE_MODULE}.tasks_facade.create_and_run_task") as start:
with self.assertRaises(TrialJudgeExecutionError):
async_to_sync(judge_trial_run)(snapshot, evidence)
- start.assert_not_awaited()
+ start.assert_not_called()
@parameterized.expand(
[(bound, status, None) for bound in (False, True) for status in ("pending", "unknown", "not_started")]
@@ -824,6 +849,7 @@ class TestScoutTrialEvaluation(BaseTest):
assert report.text.count(final_summary) == 1
else:
assert packed["captured_submission_details"]["summary"] == original_summary
+ self._save_judgments(snapshot)
report_document = finish_trial_evaluation(self.team.id, snapshot.evaluation_id)
assert len(report_document.model_dump_json().encode()) < 32 * 1024
@@ -849,14 +875,19 @@ class TestScoutTrialEvaluation(BaseTest):
@parameterized.expand(
[
- (False, "returned"),
- (True, "returned"),
- (False, "unexpected"),
- (False, "revocation"),
+ ("pending", False),
+ ("worker_interruption", False),
+ ("result_save", False),
+ ("pending", True),
]
)
- def test_retries_do_not_repeat_paid_judgments(self, interrupted: bool, failure_kind: str) -> None:
+ def test_retries_collect_existing_judgments_without_finalizing_incomplete_runs(
+ self, interrupted_at: str, legacy: bool
+ ) -> None:
snapshot = prepare_trial_evaluation(config=self.config, user=self.user, request=self.request)
+ if legacy:
+ del self.documents[f"signals/scout-trials/{self.team.id}/evaluations/{snapshot.evaluation_id}/access.json"]
+ assert read_trial_evaluation(self.team.id, snapshot.evaluation_id) == snapshot
judgment = TrialRunJudgment(
launch_id=self.launch.id,
variant_id=self.request.baseline_variant_id,
@@ -865,27 +896,39 @@ class TestScoutTrialEvaluation(BaseTest):
error="Synthetic failure",
)
judge = AsyncMock(return_value=judgment)
- if failure_kind == "unexpected":
- judge.side_effect = RuntimeError("Private synthetic failure detail")
- elif failure_kind == "revocation":
- judge.side_effect = TrialJudgeExecutionError(
- "The private evaluation failed at credential_revocation (RuntimeError). No exception details were saved."
- )
- with patch(f"{JUDGE_MODULE}.judge_trial_run", judge):
- async_to_sync(run_evaluation_run)(self.team.id, snapshot.evaluation_id, self.launch.id)
- if interrupted:
- del self.documents[
- f"signals/scout-trials/{self.team.id}/evaluations/{snapshot.evaluation_id}/runs/{self.launch.id}.json"
- ]
- async_to_sync(run_evaluation_run)(self.team.id, snapshot.evaluation_id, self.launch.id)
- judge.assert_awaited_once()
+ if interrupted_at == "pending":
+ judge.side_effect = [None, judgment]
+ elif interrupted_at == "worker_interruption":
+ judge.side_effect = [RuntimeError("Private synthetic failure detail"), judgment]
+ with (
+ patch(f"{JUDGE_MODULE}.judge_trial_run", judge),
+ patch.object(object_storage, "read", wraps=object_storage.read) as read,
+ ):
+ if interrupted_at == "pending":
+ assert not async_to_sync(run_evaluation_run)(self.team.id, snapshot.evaluation_id, self.launch.id)
+ elif interrupted_at == "worker_interruption":
+ with self.assertRaises(RuntimeError):
+ async_to_sync(run_evaluation_run)(self.team.id, snapshot.evaluation_id, self.launch.id)
+ else:
+ with patch.object(
+ object_storage, "write", side_effect=object_storage.ObjectStorageError("Unavailable")
+ ):
+ with self.assertRaises(object_storage.ObjectStorageError):
+ async_to_sync(run_evaluation_run)(self.team.id, snapshot.evaluation_id, self.launch.id)
+ context_key = f"signals/scout-trials/{self.team.id}/contexts/{self.context.id}.json"
+ assert (context_key in [call.args[0] for call in read.call_args_list]) == legacy
+ with self.assertRaises(TrialEvaluationNotReady):
+ finish_trial_evaluation(self.team.id, snapshot.evaluation_id)
+ assert context_key in [call.args[0] for call in read.call_args_list]
+ assert read_trial_evaluation_report(snapshot) is None
+ read.reset_mock()
+ assert async_to_sync(run_evaluation_run)(self.team.id, snapshot.evaluation_id, self.launch.id)
+ assert async_to_sync(run_evaluation_run)(self.team.id, snapshot.evaluation_id, self.launch.id)
+ assert (context_key in [call.args[0] for call in read.call_args_list]) == legacy
+ assert judge.await_count == 2
report = finish_trial_evaluation(self.team.id, snapshot.evaluation_id)
assert report.runs[0].status == "judge_error"
assert "Private synthetic" not in report.model_dump_json()
- if failure_kind != "returned":
- assert ("credential_revocation" if failure_kind == "revocation" else "judge_execution") in (
- report.runs[0].error or ""
- )
@parameterized.expand(
[
@@ -893,14 +936,34 @@ class TestScoutTrialEvaluation(BaseTest):
"inactive",
"membership_revoked",
"project_revoked",
+ "current_skill_removed",
"historical_skill_removed",
"source_skill",
"source_config_team",
"source_invalidated",
+ "saved_context",
+ "saved_evaluation",
]
)
def test_worker_rechecks_source_and_operator_access_before_judging(self, revoked: str) -> None:
+ runtime_skill = self.skill
+ if revoked == "historical_skill_removed":
+ self.skill.is_latest = False
+ self.skill.save(update_fields=["is_latest"])
+ runtime_skill = LLMSkill.objects.create(
+ team=self.team,
+ name=self.skill.name,
+ version=2,
+ body=self.skill.body,
+ allowed_tools=["emit_report"],
+ )
+ self.context = self.context.model_copy(update={"skill_version": runtime_skill.version})
+ self.launch = self.launch.model_copy(update={"skill_version": runtime_skill.version})
+ self._save("contexts", self.context.id, self.context)
+ self._save("launches", self.launch.id, self.launch)
snapshot = prepare_trial_evaluation(config=self.config, user=self.user, request=self.request)
+ with patch(f"{JUDGE_MODULE}.judge_trial_run", new_callable=AsyncMock, return_value=None):
+ assert not async_to_sync(run_evaluation_run)(self.team.id, snapshot.evaluation_id, self.launch.id)
if revoked == "staff_revoked":
self.user.is_staff = False
self.user.save(update_fields=["is_staff"])
@@ -917,12 +980,14 @@ class TestScoutTrialEvaluation(BaseTest):
return_value=False,
)
)
- elif revoked == "historical_skill_removed":
+ elif revoked == "current_skill_removed":
self.skill.delete()
+ elif revoked == "historical_skill_removed":
+ LLMSkill.objects.filter(pk=runtime_skill.id).delete()
LLMSkill.objects.create(
team=self.team,
name=self.skill.name,
- version=2,
+ version=3,
body="Updated synthetic instructions.",
allowed_tools=["emit_report"],
)
@@ -932,15 +997,20 @@ class TestScoutTrialEvaluation(BaseTest):
elif revoked == "source_config_team":
self.config.team = Team.objects.create(organization=self.organization, name="Other synthetic project")
self.config.save(update_fields=["team"])
+ elif revoked in {"saved_context", "saved_evaluation"}:
+ key = f"signals/scout-trials/{self.team.id}/evaluations/{snapshot.evaluation_id}/access.json"
+ access = json.loads(self.documents[key])
+ access["context_id" if revoked == "saved_context" else "evaluation_id"] = str(uuid4())
+ self.documents[key] = json.dumps(access)
else:
ScoutTrialStore(self.scout_run).invalidate("Synthetic invalidation", allow_terminal=True)
with (
patch(f"{JUDGE_MODULE}.get_or_create_signals_sandbox_env", return_value=None),
- patch(f"{JUDGE_MODULE}.MultiTurnSession.start", new_callable=AsyncMock) as start,
+ patch(f"{JUDGE_MODULE}.tasks_facade.create_and_run_task") as start,
):
async_to_sync(run_evaluation_run)(self.team.id, snapshot.evaluation_id, self.launch.id)
- start.assert_not_awaited()
+ start.assert_not_called()
judgment = TrialRunJudgment.model_validate_json(
self.documents[
f"signals/scout-trials/{self.team.id}/evaluations/{snapshot.evaluation_id}/runs/{self.launch.id}.json"
@@ -948,10 +1018,8 @@ class TestScoutTrialEvaluation(BaseTest):
)
assert judgment.status == "judge_error"
- @parameterized.expand(["before_start", "during_judging"])
- def test_flag_disable_preserves_unstarted_attempts_and_active_results(self, timing: str) -> None:
+ def test_flag_disable_preserves_active_results(self) -> None:
snapshot = prepare_trial_evaluation(config=self.config, user=self.user, request=self.request)
- saved = dict(self.documents)
judgment = TrialRunJudgment(
launch_id=self.launch.id,
variant_id=self.request.baseline_variant_id,
@@ -974,13 +1042,6 @@ class TestScoutTrialEvaluation(BaseTest):
return judgment
with patch(f"{JUDGE_MODULE}.judge_trial_run", side_effect=judge) as paid_judge:
- if timing == "before_start":
- self.trials_flag.return_value = False
- with self.assertRaises(ScoutTrialsDisabled):
- async_to_sync(run_evaluation_run)(self.team.id, snapshot.evaluation_id, self.launch.id)
- assert self.documents == saved
- paid_judge.assert_not_called()
- self.trials_flag.return_value = True
async_to_sync(run_evaluation_run)(self.team.id, snapshot.evaluation_id, self.launch.id)
async_to_sync(run_evaluation_run)(self.team.id, snapshot.evaluation_id, self.launch.id)
paid_judge.assert_called_once()
@@ -1108,6 +1169,7 @@ class TestScoutTrialEvaluation(BaseTest):
object_storage, "object_storage_client", return_value=object_storage.ObjectStorage(storage_client)
):
assert service.history(10).results[0].status == "failed"
+ self._save_judgments(snapshot)
finish_trial_evaluation(self.team.id, snapshot.evaluation_id)
history = service.history(10)
assert history.results[0].status == "completed"
@@ -1182,9 +1244,43 @@ class TestScoutTrialEvaluation(BaseTest):
dispatch.assert_not_called()
[email protected](name="RunScoutTrialEvaluationWorkflow")
+class LegacyTrialEvaluationWorkflow:
+ @workflow.run
+ async def run(self, inputs: TrialEvaluationInput) -> str:
+ launch_ids = await workflow.execute_activity(
+ "load_scout_trial_evaluation_activity",
+ inputs,
+ start_to_close_timeout=timedelta(minutes=1),
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+ semaphore = asyncio.Semaphore(3)
+
+ async def judge(launch_id: str) -> None:
+ async with semaphore:
+ await workflow.execute_activity(
+ "judge_scout_trial_run_activity",
+ TrialEvaluationRunInput(
+ team_id=inputs.team_id, evaluation_id=inputs.evaluation_id, launch_id=launch_id
+ ),
+ start_to_close_timeout=timedelta(minutes=18),
+ heartbeat_timeout=timedelta(seconds=30),
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+
+ await asyncio.gather(*(judge(launch_id) for launch_id in launch_ids))
+ await workflow.execute_activity(
+ "finish_scout_trial_evaluation_activity",
+ inputs,
+ start_to_close_timeout=timedelta(minutes=1),
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+ return inputs.evaluation_id
+
+
class TestScoutTrialEvaluationWorkflow(SimpleTestCase):
- @parameterized.expand([False, True])
- async def test_bounds_concurrency_and_finalizes_after_one_activity_fails(self, disabled: bool) -> None:
+ @parameterized.expand(["none", "disabled", "interrupted"])
+ async def test_bounds_pending_judges_and_keeps_incomplete_evaluations_resumable(self, failure: str) -> None:
inputs = TrialEvaluationInput(team_id=2, evaluation_id=str(uuid4()))
launch_ids = [str(uuid4()) for _ in range(7)]
reached_limit = asyncio.Event()
@@ -1192,6 +1288,7 @@ class TestScoutTrialEvaluationWorkflow(SimpleTestCase):
active = 0
highest_active = 0
completed: set[str] = set()
+ attempts: dict[str, int] = {}
finalized = False
async def execute(function: Callable[..., object], payload: object, **options: object) -> object:
@@ -1204,32 +1301,59 @@ class TestScoutTrialEvaluationWorkflow(SimpleTestCase):
return None
assert isinstance(payload, TrialEvaluationRunInput)
policy = options["retry_policy"]
- assert isinstance(policy, RetryPolicy) and policy.maximum_attempts == 1
+ assert isinstance(policy, RetryPolicy) and policy.maximum_attempts != 1
timeout = options["start_to_close_timeout"]
- assert isinstance(timeout, timedelta) and timeout >= timedelta(minutes=37)
+ assert isinstance(timeout, timedelta) and timeout < timedelta(minutes=5)
+ deadline = options["schedule_to_close_timeout"]
+ assert isinstance(deadline, timedelta) and deadline > timeout
+ attempts[payload.launch_id] = attempts.get(payload.launch_id, 0) + 1
active += 1
highest_active = max(highest_active, active)
if active == 3:
reached_limit.set()
await release.wait()
active -= 1
- completed.add(payload.launch_id)
- if payload.launch_id == launch_ids[0]:
+ if payload.launch_id == launch_ids[0] and failure != "none":
error = ActivityError(
"Synthetic worker interruption",
scheduled_event_id=1,
started_event_id=2,
identity="worker",
- activity_type="judge_scout_trial_run_activity",
+ activity_type="poll_scout_trial_judge_activity",
activity_id="scoring",
retry_state=None,
)
- if disabled:
+ if failure == "disabled":
raise error from ApplicationError("Scout trials are disabled.", type="ScoutTrialsDisabled")
raise error
- return None
+ if attempts[payload.launch_id] == 1:
+ return False
+ completed.add(payload.launch_id)
+ return True
+
+ async def child(function: Callable[..., object], payload: TrialEvaluationRunInput, **options: object) -> None:
+ try:
+ await RunScoutTrialJudgeWorkflow().run(payload)
+ except ActivityError as error:
+ raise ChildWorkflowError(
+ "Synthetic child workflow failure",
+ namespace="default",
+ workflow_id=str(options["id"]),
+ run_id=str(uuid4()),
+ workflow_type="RunScoutTrialJudgeWorkflow",
+ initiated_event_id=1,
+ started_event_id=2,
+ retry_state=None,
+ ) from error
- with patch(f"{WORKFLOW_MODULE}.workflow.execute_activity", side_effect=execute):
+ with (
+ patch(f"{WORKFLOW_MODULE}.workflow.execute_activity", side_effect=execute),
+ patch(f"{WORKFLOW_MODULE}.workflow.execute_child_workflow", side_effect=child),
+ patch(f"{WORKFLOW_MODULE}.workflow.patched", return_value=True),
+ patch(f"{WORKFLOW_MODULE}.workflow.info", return_value=MagicMock(workflow_id=inputs.evaluation_id)),
+ patch(f"{WORKFLOW_MODULE}.workflow.now", return_value=timezone.now()),
+ patch(f"{WORKFLOW_MODULE}.workflow.sleep", new_callable=AsyncMock),
+ ):
task = asyncio.create_task(RunScoutTrialEvaluationWorkflow().run(inputs))
wait_for_limit = asyncio.create_task(reached_limit.wait())
try:
@@ -1241,14 +1365,117 @@ class TestScoutTrialEvaluationWorkflow(SimpleTestCase):
release.set()
wait_for_limit.cancel()
await asyncio.gather(wait_for_limit, return_exceptions=True)
- if disabled:
- with self.assertRaisesMessage(ApplicationError, "Resume when they are enabled"):
+ if failure != "none":
+ with self.assertRaises(ApplicationError):
await task
else:
assert await task == inputs.evaluation_id
assert highest_active == 3
- assert completed == set(launch_ids)
- assert finalized is not disabled
+ assert completed == set(launch_ids if failure == "none" else launch_ids[1:])
+ assert finalized is (failure == "none")
+
+ async def test_worker_restart_collects_the_existing_judge_before_finalizing(self) -> None:
+ inputs = TrialEvaluationInput(team_id=2, evaluation_id=str(uuid4()))
+ launch_id = str(uuid4())
+ observing = asyncio.Event()
+ judge_tasks: dict[str, str] = {}
+ completed_tasks: set[str] = set()
+ saved_judgments: set[str] = set()
+ finalized = False
+
+ @activity.defn(name="load_scout_trial_evaluation_activity")
+ async def load(_inputs: TrialEvaluationInput) -> list[str]:
+ return [launch_id]
+
+ @activity.defn(name="poll_scout_trial_judge_activity")
+ async def observe(run: TrialEvaluationRunInput) -> bool:
+ task_id = judge_tasks.setdefault(run.launch_id, str(uuid4()))
+ if task_id not in completed_tasks:
+ observing.set()
+ await activity.wait_for_worker_shutdown()
+ raise RuntimeError("Synthetic observer worker shutdown")
+ saved_judgments.add(run.launch_id)
+ return True
+
+ @activity.defn(name="finish_scout_trial_evaluation_activity")
+ async def finish(_inputs: TrialEvaluationInput) -> None:
+ nonlocal finalized
+ assert saved_judgments == {launch_id}
+ finalized = True
+
+ queue = f"trial-evaluation-restart-{uuid4()}"
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=queue,
+ workflows=[RunScoutTrialEvaluationWorkflow, RunScoutTrialJudgeWorkflow],
+ activities=[load, observe, finish],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ max_cached_workflows=0,
+ graceful_shutdown_timeout=timedelta(seconds=10),
+ ):
+ handle = await env.client.start_workflow(
+ RunScoutTrialEvaluationWorkflow.run,
+ inputs,
+ id=inputs.evaluation_id,
+ task_queue=queue,
+ )
+ await asyncio.wait_for(observing.wait(), timeout=30)
+ assert not finalized
+ assert not saved_judgments
+ original_task_id = judge_tasks[launch_id]
+ completed_tasks.add(original_task_id)
+ async with Worker(
+ env.client,
+ task_queue=queue,
+ workflows=[RunScoutTrialEvaluationWorkflow, RunScoutTrialJudgeWorkflow],
+ activities=[load, observe, finish],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ max_cached_workflows=0,
+ ):
+ assert await asyncio.wait_for(handle.result(), timeout=30) == inputs.evaluation_id
+
+ self.assertTrue(finalized)
+ assert judge_tasks == {launch_id: original_task_id}
+ assert saved_judgments == {launch_id}
+
+ async def test_replays_judgments_recorded_before_resumable_judges(self) -> None:
+ @activity.defn(name="load_scout_trial_evaluation_activity")
+ async def load(_inputs: TrialEvaluationInput) -> list[str]:
+ return [str(uuid4()) for _ in range(4)]
+
+ @activity.defn(name="judge_scout_trial_run_activity")
+ async def judge(_inputs: TrialEvaluationRunInput) -> None:
+ return None
+
+ @activity.defn(name="finish_scout_trial_evaluation_activity")
+ async def finish(_inputs: TrialEvaluationInput) -> None:
+ return None
+
+ inputs = TrialEvaluationInput(team_id=2, evaluation_id=str(uuid4()))
+ queue = f"trial-evaluation-replay-{uuid4()}"
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=queue,
+ workflows=[LegacyTrialEvaluationWorkflow],
+ activities=[load, judge, finish],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ handle = await env.client.start_workflow(
+ LegacyTrialEvaluationWorkflow.run,
+ inputs,
+ id=inputs.evaluation_id,
+ task_queue=queue,
+ )
+ assert await asyncio.wait_for(handle.result(), timeout=30) == inputs.evaluation_id
+ history = await handle.fetch_history()
+
+ assert not any(event.HasField("marker_recorded_event_attributes") for event in history.events)
+ await Replayer(
+ workflows=[RunScoutTrialEvaluationWorkflow, RunScoutTrialJudgeWorkflow],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ).replay_workflow(history)
def test_new_evaluation_allows_all_bounded_judging_waves(self) -> None:
client = AsyncMock()
@@ -1256,14 +1483,33 @@ class TestScoutTrialEvaluationWorkflow(SimpleTestCase):
with patch(f"{WORKFLOW_MODULE}.async_connect", AsyncMock(return_value=client)):
start_trial_evaluation(2, evaluation_id)
timeout = client.start_workflow.call_args.kwargs["execution_timeout"]
- assert timeout >= timedelta(minutes=-(-MAX_TRIAL_RUNS // 3) * 37 + 2)
+ assert timeout >= timedelta(minutes=-(-MAX_TRIAL_RUNS // 3) * 33 + 2)
assert client.start_workflow.call_args.args[1] == TrialEvaluationInput(
team_id=2, evaluation_id=str(evaluation_id)
)
- async def test_activity_failure_does_not_put_evidence_in_temporal_history(self) -> None:
- with patch(f"{MODULE}.read_trial_evaluation", side_effect=ValueError("Private synthetic evidence")):
- with self.assertRaisesMessage(ApplicationError, "snapshot_load (ValueError)") as failure:
- await load_scout_trial_evaluation_activity(TrialEvaluationInput(team_id=2, evaluation_id=str(uuid4())))
+ @parameterized.expand(["load", "judge", "finish"])
+ async def test_activity_failure_stays_retryable_without_putting_evidence_in_history(self, stage: str) -> None:
+ inputs = TrialEvaluationInput(team_id=2, evaluation_id=str(uuid4()))
+ boundary = {
+ "load": "read_trial_evaluation",
+ "judge": "run_evaluation_run",
+ "finish": "finish_trial_evaluation",
+ }[stage]
+ with patch(f"{MODULE}.{boundary}", side_effect=RuntimeError("Private synthetic evidence")):
+ with self.assertRaises(ApplicationError) as failure:
+ env = ActivityEnvironment()
+ if stage == "load":
+ await env.run(load_scout_trial_evaluation_activity, inputs)
+ elif stage == "judge":
+ await env.run(
+ poll_scout_trial_judge_activity,
+ TrialEvaluationRunInput(
+ team_id=inputs.team_id, evaluation_id=inputs.evaluation_id, launch_id=str(uuid4())
+ ),
+ )
+ else:
+ await env.run(finish_scout_trial_evaluation_activity, inputs)
assert "Private synthetic evidence" not in str(failure.exception)
- assert failure.exception.non_retryable
+ assert "RuntimeError" in str(failure.exception)
+ assert not failure.exception.non_retryable
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 f986a93c0c29..c3a46280a3c5 100644
--- a/products/signals/backend/test/test_scout_trial_judge_sandbox.py
+++ b/products/signals/backend/test/test_scout_trial_judge_sandbox.py
@@ -1,194 +1,212 @@
from __future__ import annotations
-import json
import asyncio
-from types import SimpleNamespace
-from uuid import uuid4
+from collections.abc import Callable
+from datetime import UTC, datetime, timedelta
+import time_machine
from posthog.test.base import BaseTest
from unittest.mock import AsyncMock, MagicMock, patch
-from django.test import SimpleTestCase, override_settings
+from django.test import override_settings
from asgiref.sync import async_to_sync
from parameterized import parameterized
from posthog.models.scoping import team_scope
+from products.signals.backend.scout_harness.trial_evaluation import TrialEvaluationError
from products.signals.backend.scout_harness.trial_judge import TrialJudgeExecutionError, judge_trial_run
-from products.signals.backend.test.test_scout_trial_judge import _snapshot, _verdict
+from products.signals.backend.scout_harness.trial_launch import ScoutTrialsDisabled
+from products.signals.backend.test.test_scout_trial_judge import _criterion, _snapshot, _verdict
from products.signals.backend.trial_judging_types import TrialJudgeVerdicts
+from products.tasks.backend.facade import api as tasks_facade
from products.tasks.backend.models import Task, TaskRun
MODULE = "products.signals.backend.scout_harness.trial_judge"
-SESSION_MODULE = "products.tasks.backend.logic.services.custom_prompt_multi_turn_runner"
-
-
-class TestSandboxJudgeLifecycle(SimpleTestCase):
- @parameterized.expand(["success", "invalid_result", "cancelled", "startup_failure", "cleanup_failure"])
- async def test_judge_closes_its_sandbox_and_does_not_disclose_errors(self, outcome: str) -> None:
- snapshot = _snapshot()
- evidence = snapshot.runs[0]
- run = SimpleNamespace(
- id=uuid4(), task_id=uuid4(), state={"token_usage": {"input_tokens": 123, "output_tokens": 45}}
- )
- session = SimpleNamespace(task_run=run, end=AsyncMock())
- if outcome == "cleanup_failure":
- session.end.side_effect = RuntimeError("private fixture content must not appear in errors")
- output = TrialJudgeVerdicts.model_validate({"summary": "Synthetic assessment.", "criteria": [_verdict()]})
- if outcome == "invalid_result":
- output = output.model_copy(update={"criteria": output.criteria * 2})
-
- async def start(**kwargs):
- self.assertEqual(kwargs["max_poll_seconds"], 30 * 60)
- self.assertEqual(kwargs["context"].sandbox_timeout_seconds, 37 * 60)
- kwargs["before_task_dispatch"](run.id)
- if outcome == "cancelled":
- raise asyncio.CancelledError
- if outcome == "startup_failure":
- raise RuntimeError("private fixture content must not appear in errors")
- return session, output
-
- with (
- patch(f"{MODULE}.asyncio.timeout", wraps=asyncio.timeout) as timeout_guard,
- patch(f"{MODULE}._assert_scout_available"),
- patch(f"{MODULE}.read_trial_evidence_sources", return_value=evidence.sources),
- patch(f"{MODULE}.tasks_facade.get_task_by_origin_key", return_value=None),
- patch(f"{MODULE}.get_or_create_signals_sandbox_env", return_value=str(uuid4())),
- patch(f"{MODULE}.tasks_facade.attach_task_run_input_files"),
- patch(f"{MODULE}.tasks_facade.get_task_run", return_value=run),
- patch(f"{MODULE}.tasks_facade.update_task_run") as update_run,
- patch(f"{MODULE}.MultiTurnSession.start", side_effect=start),
- ):
- if outcome == "success":
- result = await judge_trial_run(snapshot, evidence)
- self.assertEqual(result.status, "judged")
- self.assertEqual((result.input_tokens, result.output_tokens), (123, 45))
- self.assertEqual(result.criteria[0].verdict, "pass")
- session.end.assert_awaited_once_with(status="completed", error=None)
- update_run.assert_not_called()
- elif outcome == "cancelled":
- with self.assertRaises(asyncio.CancelledError):
- await judge_trial_run(snapshot, evidence)
- self.assertEqual(update_run.call_args.kwargs["validated_data"]["status"], "failed")
- else:
- with self.assertRaises(TrialJudgeExecutionError) as error:
- await judge_trial_run(snapshot, evidence)
- self.assertNotIn("private fixture content", str(error.exception))
- self.assertEqual(update_run.call_args.kwargs["validated_data"]["status"], "failed")
- if outcome == "invalid_result":
- self.assertEqual(session.end.call_args.kwargs["status"], "failed")
- timeout_guard.assert_called_once_with(36 * 60)
-
- @parameterized.expand(["missing_evidence", "existing_judge"])
- async def test_unavailable_input_and_existing_judge_do_not_start_a_paid_run(self, failure: str) -> None:
- snapshot = _snapshot()
- with (
- patch(f"{MODULE}._assert_scout_available"),
- patch(
- f"{MODULE}.read_trial_evidence_sources",
- side_effect=ValueError("private missing file") if failure == "missing_evidence" else None,
- return_value=snapshot.runs[0].sources,
- ),
- patch(f"{MODULE}.tasks_facade.get_task_by_origin_key", return_value=object()),
- patch(f"{MODULE}.MultiTurnSession.start", new_callable=AsyncMock) as start,
- ):
- with self.assertRaises(TrialJudgeExecutionError):
- await judge_trial_run(snapshot, snapshot.runs[0])
- start.assert_not_awaited()
+DISPATCH = "products.tasks.backend.logic.services.workflow_dispatch.enqueue_or_start_workflow"
+@override_settings(DEBUG=False)
class TestSandboxJudgeDispatch(BaseTest):
- @parameterized.expand([("valid_json", False), ("invalid_json", True)])
- @override_settings(DEBUG=False)
- def test_ordinary_task_attaches_evidence_and_retries_json_in_same_run(self, _name: str, retry_json: bool) -> None:
- snapshot = _snapshot().model_copy(update={"team_id": self.team.id, "user_id": self.user.id})
- evidence = snapshot.runs[0]
- output = TrialJudgeVerdicts.model_validate({"summary": "Synthetic assessment.", "criteria": [_verdict()]})
- dispatched: list[TaskRun] = []
- log_lines: list[str] = []
- followup_messages: list[str] = []
-
- def append_response(text: str) -> None:
- log_lines.extend(
- [
- json.dumps(
- {
- "notification": {
- "method": "session/update",
- "params": {
- "update": {
- "sessionUpdate": "agent_message",
- "content": {"type": "text", "text": text},
- }
- },
- }
- }
- ),
- json.dumps({"notification": {"result": {"stopReason": "end_turn"}}}),
- ]
- )
-
- append_response("The synthetic check passed." if retry_json else output.model_dump_json())
-
- async def signal(signal: object, message: str | None = None, **_kwargs: object) -> None:
- if message is not None:
- followup_messages.append(message)
- self.assertIn("Return the complete JSON object", message)
- append_response(output.model_dump_json())
-
- workflow_handle = MagicMock(signal=AsyncMock(side_effect=signal))
- client = MagicMock()
- client.get_workflow_handle.return_value = workflow_handle
+ def setUp(self) -> None:
+ super().setUp()
+ self.snapshot = _snapshot().model_copy(update={"team_id": self.team.id, "user_id": self.user.id})
+ self.evidence = self.snapshot.runs[0]
+ self.output = TrialJudgeVerdicts.model_validate({"summary": "Synthetic assessment.", "criteria": [_verdict()]})
+ self.enterContext(team_scope(self.team.id, canonical=True))
+ self.enterContext(patch(f"{MODULE}._assert_scout_available"))
+ self.read_sources = self.enterContext(
+ patch(f"{MODULE}.read_trial_evidence_sources", return_value=self.evidence.sources)
+ )
+ self.enterContext(patch("posthoganalytics.feature_enabled", return_value=False))
+ self.trials_enabled = self.enterContext(
+ patch("products.signals.backend.scout_harness.trial_launch.scout_trials_enabled", return_value=True)
+ )
+ self.dispatch = self.enterContext(patch(DISPATCH))
+
+ @parameterized.expand([("poll_completed", False), ("worker_interrupted", True), ("origin_race", False)])
+ def test_ordinary_task_resumes_and_collects_complete_saved_output(self, scenario: str, interrupted: bool) -> None:
+ criteria = [_criterion(f"check-{index}") for index in range(14)]
+ snapshot = self.snapshot.model_copy(update={"criteria": criteria})
+ output = TrialJudgeVerdicts.model_validate(
+ {
+ "summary": "Synthetic assessment.",
+ "criteria": [
+ {
+ **_verdict(identifier=criterion.id),
+ "reason": "The synthetic observation supports this check. " * 38,
+ }
+ for criterion in criteria
+ ],
+ }
+ )
+ self.assertGreater(len(output.model_dump_json()), 20_000)
def dispatch(run: TaskRun, **_kwargs: object) -> None:
run.refresh_from_db()
self.assertEqual(run.task.origin_product, Task.OriginProduct.SIGNALS_SCOUT_SUGGESTIONS)
self.assertFalse(run.task.is_scout_experiment)
self.assertNotIn("scout_trial_judge", run.state)
+ self.assertNotIn("caller_ends_run", run.state)
+ self.assertEqual(run.task.json_schema, TrialJudgeVerdicts.model_json_schema())
self.assertEqual(run.state["pending_dispatch"]["posthog_mcp_scopes"], [])
+ self.assertFalse(run.state["pending_dispatch"]["create_pr"])
self.assertEqual(run.state["pending_user_message_id"], str(run.id))
self.assertEqual(run.state["pending_user_artifact_ids"], [item["id"] for item in run.artifacts])
- self.assertEqual([item["name"] for item in run.artifacts], [file.filename for file in evidence.files])
- self.assertNotIn(evidence.sources[0].text, run.state["pending_user_message"])
+ self.assertEqual([item["name"] for item in run.artifacts], [file.filename for file in self.evidence.files])
+ self.assertNotIn(self.evidence.sources[0].text, run.state["pending_user_message"])
self.assertEqual(run.state["model"], snapshot.judge_model)
self.assertEqual(run.state["reasoning_effort"], "high")
+ self.assertEqual(run.state["sandbox_ttl_seconds"], 32 * 60)
+ self.assertEqual(run.state["inactivity_timeout_seconds"], 30 * 60)
self.assertEqual(run.state["mcp_gateway_server_ids"], [])
self.assertFalse(run.state["include_live_context"])
self.assertEqual(run.task.mcp_builtin_agent_key, "scout")
self.assertEqual(run.task.mcp_gateway_server_allowlist, [])
self.assertIsNone(run.task.repository)
+ self.assertIsNone(run.task.github_integration_id)
+ self.assertIsNone(run.task.github_user_integration_id)
self.assertTrue(run.task.internal)
for artifact in run.artifacts:
self.assertIn(f"/{snapshot.team_id}/evaluations/{snapshot.evaluation_id}/", artifact["storage_path"])
- self.assertIn(str(evidence.launch_id), artifact["storage_path"])
-
- dispatched.append(run)
-
- with (
- team_scope(self.team.id, canonical=True),
- patch(f"{MODULE}._assert_scout_available"),
- patch(f"{MODULE}.read_trial_evidence_sources", return_value=evidence.sources),
- patch("posthoganalytics.feature_enabled", return_value=False),
- patch(
- "products.tasks.backend.logic.services.workflow_dispatch.enqueue_or_start_workflow",
- side_effect=dispatch,
- ),
- patch(f"{SESSION_MODULE}.async_connect", new=AsyncMock(return_value=client)),
- patch("asyncio.sleep", new_callable=AsyncMock),
- patch("posthog.storage.object_storage.read", side_effect=lambda *_args, **_kwargs: "\n".join(log_lines)),
- ):
- result = async_to_sync(judge_trial_run)(snapshot, evidence)
- self.assertEqual(result.status, "judged")
- self.assertEqual(len(dispatched), 1)
- with self.assertRaisesMessage(TrialJudgeExecutionError, "already has a judge task"):
- async_to_sync(judge_trial_run)(snapshot, evidence)
- self.assertEqual(
- Task.objects.filter(team_id=self.team.id, origin_key__startswith="scout-trial-judge:").count(), 1
+ self.assertIn(str(self.evidence.launch_id), artifact["storage_path"])
+
+ self.dispatch.side_effect = dispatch
+ create_and_run_task: Callable[..., object] = tasks_facade.create_and_run_task
+
+ def interrupted_create(**kwargs: object) -> None:
+ create_and_run_task(**kwargs)
+ raise asyncio.CancelledError
+
+ if interrupted:
+ with (
+ patch(f"{MODULE}.tasks_facade.create_and_run_task", side_effect=interrupted_create),
+ self.assertRaises(asyncio.CancelledError),
+ ):
+ async_to_sync(judge_trial_run)(snapshot, self.evidence)
+ else:
+ self.assertIsNone(async_to_sync(judge_trial_run)(snapshot, self.evidence))
+
+ run = TaskRun.objects.get(team_id=self.team.id, task__origin_key__startswith="scout-trial-judge:")
+ self.assertFalse(run.is_terminal)
+ if scenario == "origin_race":
+ assert run.task.origin_key is not None
+ existing = tasks_facade.get_task_by_origin_key(self.team.id, run.task.origin_key)
+ with patch(f"{MODULE}.tasks_facade.get_task_by_origin_key", side_effect=[None, existing]):
+ self.assertIsNone(async_to_sync(judge_trial_run)(snapshot, self.evidence))
+ self.trials_enabled.return_value = False
+ self.assertIsNone(async_to_sync(judge_trial_run)(snapshot, self.evidence))
+ handle = MagicMock(signal=AsyncMock())
+ client = MagicMock()
+ client.get_workflow_handle.return_value = handle
+ with patch("posthog.temporal.common.client.sync_connect", return_value=client):
+ saved = tasks_facade.set_task_run_output(
+ run.id, run.task_id, self.team.id, output=output.model_dump(mode="json")
)
- self.assertEqual(TaskRun.objects.filter(team_id=self.team.id, task=dispatched[0].task).count(), 1)
- dispatched[0].refresh_from_db()
- self.assertFalse(dispatched[0].state["include_live_context"])
- self.assertEqual(workflow_handle.signal.call_args.kwargs["args"], ["completed", None])
- self.assertEqual(result.criteria[0].verdict, "pass")
- self.assertEqual(len(followup_messages), int(retry_json))
+ assert saved is not None
+ self.assertEqual(saved.output, output.model_dump(mode="json"))
+ self.assertEqual(handle.signal.call_args.kwargs["args"], ["completed", None])
+ self.assertIsNone(async_to_sync(judge_trial_run)(snapshot, self.evidence))
+ tasks_facade.update_task_run(
+ run.id,
+ run.task_id,
+ self.team.id,
+ validated_data={
+ "status": "completed",
+ "output": {"final_message": '"criteria":[]}'},
+ "state": {"token_usage": {"input_tokens": 123, "output_tokens": 45}},
+ },
+ )
+
+ result = async_to_sync(judge_trial_run)(snapshot, self.evidence)
+ assert result is not None
+ self.assertEqual(result.status, "judged")
+ self.assertEqual(result.criteria, output.criteria)
+ self.assertEqual((result.input_tokens, result.output_tokens), (123, 45))
+ self.assertEqual(
+ Task.objects.filter(team_id=self.team.id, origin_key__startswith="scout-trial-judge:").count(), 1
+ )
+ self.assertEqual(TaskRun.objects.filter(team_id=self.team.id, task=run.task).count(), 1)
+ self.dispatch.assert_called_once()
+
+ @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:
+ 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:")
+ started_at = datetime.now(UTC)
+ with time_machine.travel(started_at + timedelta(minutes=29), tick=False):
+ self.assertIsNone(async_to_sync(judge_trial_run)(self.snapshot, self.evidence))
+ if output_saved:
+ with patch("posthog.temporal.common.client.sync_connect", side_effect=RuntimeError):
+ tasks_facade.set_task_run_output(
+ run.id, run.task_id, self.team.id, output=self.output.model_dump(mode="json")
+ )
+ with time_machine.travel(started_at + timedelta(minutes=31), tick=False):
+ if output_saved:
+ result = async_to_sync(judge_trial_run)(self.snapshot, self.evidence)
+ assert result is not None
+ self.assertEqual((result.status, result.criteria), ("judged", self.output.criteria))
+ else:
+ with self.assertRaises(TrialJudgeExecutionError):
+ async_to_sync(judge_trial_run)(self.snapshot, self.evidence)
+ run.refresh_from_db()
+ if output_saved:
+ self.assertFalse(run.is_terminal)
+ else:
+ self.assertEqual(run.status, TaskRun.Status.FAILED)
+ assert run.error_message is not None
+ self.assertIn("did not finish", run.error_message)
+ self.dispatch.assert_called_once()
+
+ @parameterized.expand(["failed", "cancelled", "invalid_result", "missing_result"])
+ def test_terminal_failure_is_not_judged_or_restarted(self, outcome: str) -> 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 = outcome if outcome in {"failed", "cancelled"} else TaskRun.Status.COMPLETED
+ run.error_message = "private fixture content must not appear in errors"
+ run.output = self.output.model_dump(mode="json")
+ if outcome == "invalid_result":
+ run.output["criteria"] *= 2
+ elif outcome == "missing_result":
+ run.output = {"final_message": "private fixture content must not appear in errors"}
+ run.save(update_fields=["status", "output", "error_message"])
+
+ with self.assertRaises(TrialJudgeExecutionError) as error:
+ async_to_sync(judge_trial_run)(self.snapshot, self.evidence)
+ self.assertNotIn("private fixture content", str(error.exception))
+ self.dispatch.assert_called_once()
+
+ @parameterized.expand(["missing_evidence", "disabled"])
+ def test_unavailable_input_or_disabled_trials_do_not_start_a_paid_run(self, reason: str) -> None:
+ if reason == "missing_evidence":
+ self.read_sources.side_effect = TrialEvaluationError("The saved evidence file is unavailable.")
+ else:
+ self.trials_enabled.return_value = False
+ with self.assertRaises(TrialJudgeExecutionError if reason == "missing_evidence" else ScoutTrialsDisabled):
+ async_to_sync(judge_trial_run)(self.snapshot, self.evidence)
+ self.assertFalse(
+ Task.objects.filter(team_id=self.team.id, origin_key__startswith="scout-trial-judge:").exists()
+ )
+ self.dispatch.assert_not_called()