: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(trials): allow large saved context in scout trials (#113095)
Alex Lebedev579c3face667
diff --git a/docs/internal/scout-online-evals-devbox.md b/docs/internal/scout-online-evals-devbox.mdindex 46830700f7a7..fe05fbe82f62 100644--- a/docs/internal/scout-online-evals-devbox.md+++ b/docs/internal/scout-online-evals-devbox.md@@ -47,6 +47,8 @@ Revoke or expire private tokens before rolling the gateway back to a version witThe rubric stays fixed across scout edits, and saved results retain the rubric used for that trial. If a run is interrupted, reopen the existing trial before starting another paid attempt.+Variants and retries share a saved copy of the project's scout memory, notes and recent scout runs. This starting context lives in private object storage and can exceed the 16 MiB limit on launch settings without being shortened.+Each completed scout run gets its own judge sandbox. The judge reads the saved rubric and searches attached copies of the complete run log, reports, summary, instructions and starting context. These files live in private object storage; Temporal receives only their identifiers. Evidence larger than 128 MiB is refused explicitly instead of being silently shortened.The judge has no live project tools, external MCP connections or repository credentials. 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 15-minute runtime limit per run; saved results never rerun the judge when viewed.diff --git a/products/signals/backend/scout_harness/trial_comparison.py b/products/signals/backend/scout_harness/trial_comparison.pyindex ca341727bca2..47950d3a7e6e 100644--- a/products/signals/backend/scout_harness/trial_comparison.py+++ b/products/signals/backend/scout_harness/trial_comparison.py@@ -248,7 +248,7 @@ class ScoutTrialComparisons:config=self.config,user=self.user,launch_id=launch_id,- context_id=context.id,+ saved_context=context,model=variant.model,reasoning_effort=variant.reasoning_effort,skill_body=variant.skill_body,diff --git a/products/signals/backend/scout_harness/trial_evaluation.py b/products/signals/backend/scout_harness/trial_evaluation.pyindex bb2005cf0581..5e529239acae 100644--- a/products/signals/backend/scout_harness/trial_evaluation.py+++ b/products/signals/backend/scout_harness/trial_evaluation.py@@ -39,6 +39,7 @@ from products.signals.backend.scout_harness.trial_evaluation_types import ()from products.signals.backend.scout_harness.trial_inspection import ScoutTrialInspectionfrom products.signals.backend.scout_harness.trial_launch import (+ MAX_EVIDENCE_BYTES,ScoutTrialLaunchError,TrialContext,TrialLaunch,@@ -46,6 +47,7 @@ from products.signals.backend.scout_harness.trial_launch import (assert_trial_work_enabled,load_trial_context,read_trial_launch,+ trial_context_evidence,)from products.signals.backend.scout_harness.trial_result import (get_trial_workflow_status,@@ -58,7 +60,6 @@ from products.signals.backend.trial_judging import JUDGE_PROMPT_VERSION as JUDGEfrom products.tasks.backend.facade.api import get_task_run_log_size, get_task_run_log_urls, read_task_run_log_contentMAX_EVALUATION_BYTES = MAX_TRIAL_RUNS * 512 * 1024-MAX_EVIDENCE_BYTES = 128 * 1024 * 1024JUDGE_MODEL = "gpt-6-astra"_Document = TypeVar("_Document", bound=BaseModel)@@ -461,14 +462,7 @@ def _run_evidence(authored = [TrialEvidenceSource(id="instructions", kind="instructions", text=launch.skill_body),TrialEvidenceSource(id="launch-note", kind="instructions", text=launch.note),- TrialEvidenceSource(- id="context",- kind="context",- text=json.dumps(- {"memory": context.memory, "notes": context.notes, "recent_runs": context.recent_runs},- ensure_ascii=False,- ),- ),+ TrialEvidenceSource(id="context", kind="context", text=trial_context_evidence(context)),]summary = result.get("summary")if isinstance(summary, str) and summary:diff --git a/products/signals/backend/scout_harness/trial_launch.py b/products/signals/backend/scout_harness/trial_launch.pyindex 0107c98cca90..f7172b44e5f2 100644--- a/products/signals/backend/scout_harness/trial_launch.py+++ b/products/signals/backend/scout_harness/trial_launch.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport jsonimport hashlibfrom datetime import datetime+from functools import cached_propertyfrom typing import Literal, TypeVar, castfrom uuid import UUID@@ -37,7 +38,8 @@ from products.tasks.backend.facade.run_config import (get_runtime_adapter_for_model,)-MAX_TRIAL_CONTEXT_BYTES = 16 * 1024 * 1024+MAX_TRIAL_LAUNCH_BYTES = 16 * 1024 * 1024+MAX_EVIDENCE_BYTES = 128 * 1024 * 1024SCOUT_TRIAL_TASK_STATE_KEY = "scout_trial"@@ -96,6 +98,10 @@ class TrialContext(BaseModel):notes: list[dict[str, JsonValue]] = Field(default_factory=list)recent_runs: list[dict[str, JsonValue]] = Field(default_factory=list)+ @cached_property+ def evidence_bytes(self) -> int:+ return len(self.note.encode()) + len(trial_context_evidence(self).encode())+class TrialLaunch(BaseModel):model_config = ConfigDict(frozen=True, extra="forbid")@@ -135,8 +141,9 @@ def _read_document(key: str, document_type: type[_Document]) -> _Document | Nonedef _write_document_once(key: str, document: _Document) -> _Document:content = document.model_dump_json()- if len(content.encode()) > MAX_TRIAL_CONTEXT_BYTES:- raise ScoutTrialLaunchError("The saved scout context is too large for a live trial.")+ # Shared project history stays in object storage; launches carry only its context ID.+ if isinstance(document, TrialLaunch) and len(content.encode()) > MAX_TRIAL_LAUNCH_BYTES:+ raise ScoutTrialLaunchError("The trial settings are too large to save.")existing = _read_document(key, type(document))if existing is not None:return existing@@ -170,6 +177,12 @@ def assert_trial_environment_ready() -> None:raise ScoutTrialLaunchError("Scout trials require AI_GATEWAY_API_KEY for private report checks.")+def trial_context_evidence(context: TrialContext) -> str:+ return json.dumps(+ {"memory": context.memory, "notes": context.notes, "recent_runs": context.recent_runs}, ensure_ascii=False+ )++def load_trial_context(team_id: int, context_id: UUID | str) -> TrialContext:identifier = UUID(str(context_id))context = _read_document(_document_key(team_id, "contexts", identifier), TrialContext)@@ -274,9 +287,34 @@ def _snapshot_context(memories = (SignalScratchpad.objects.for_team(team.id).select_related("created_by_run", "created_by_run__task_run")+ .only(+ "team_id",+ "key",+ "content",+ "created_at",+ "updated_at",+ "expires_at",+ "created_by_identity",+ "created_by_run__skill_name",+ "created_by_run__task_run__task_id",+ ).order_by("-updated_at", "-id"))- notes = SignalScoutNote.objects.for_team(team.id).select_related("created_by").order_by("-created_at", "-id")+ notes = (+ SignalScoutNote.objects.for_team(team.id)+ .select_related("created_by")+ .only(+ "skill_name",+ "content",+ "created_at",+ "expires_at",+ "origin",+ "created_by__first_name",+ "created_by__last_name",+ "created_by__is_active",+ )+ .order_by("-created_at", "-id")+ )return TrialContext(id=identifier,team_id=team.id,@@ -294,8 +332,8 @@ def _snapshot_context(reasoning_effort=runtime.reasoning_effort,service_tier=runtime.service_tier,note=note,- memory=[cast(dict[str, JsonValue], _to_entry(row).as_dict()) for row in memories],- notes=[cast(dict[str, JsonValue], _to_note(row).as_dict()) for row in notes],+ memory=[cast(dict[str, JsonValue], _to_entry(row).as_dict()) for row in memories.iterator()],+ notes=[cast(dict[str, JsonValue], _to_note(row).as_dict()) for row in notes.iterator()],recent_runs=[cast(dict[str, JsonValue], run.as_dict())for run in search_recent_runs(team_id=team.id, skill_name=skill.name, limit=100)@@ -331,6 +369,7 @@ def create_trial_launch(user: User,launch_id: UUID,context_id: UUID | None = None,+ saved_context: TrialContext | None = None,skill_body: str | None = None,model: str | None = None,reasoning_effort: str | None = None,@@ -339,6 +378,8 @@ def create_trial_launch() -> TrialLaunch:assert_trial_environment_ready()assert_trial_work_enabled(config.team)+ if saved_context is not None:+ context_id = saved_context.idrequest_body = {"config_id": str(config.id),"user_id": user.id,@@ -357,8 +398,8 @@ def create_trial_launch(raise ScoutTrialLaunchError("This launch ID was already used with different settings.")return load_trial_launch(config.team_id, launch_id)if context_id is not None:- context = load_trial_context(config.team_id, context_id)- if context.config_id != config.id or context.user_id != user.id:+ context = saved_context if saved_context is not None else load_trial_context(config.team_id, context_id)+ if context.team_id != config.team_id or context.config_id != config.id or context.user_id != user.id:raise ScoutTrialLaunchError("The saved context belongs to another scout or operator.")if note and note != context.note:raise ScoutTrialLaunchError("All variants must use the saved comparison note.")@@ -386,6 +427,13 @@ def create_trial_launch(effort_error = get_reasoning_effort_error(adapter, selected_model, selected_effort)if model_error or effort_error:raise ScoutTrialLaunchError(model_error or effort_error or "The model settings are invalid.")+ selected_skill_body = skill_body if skill_body is not None else context.skill_body+ # Judging attaches these inputs to every completed run, so reject them before the paid runs start.+ if len(selected_skill_body.encode()) + context.evidence_bytes > MAX_EVIDENCE_BYTES:+ raise ScoutTrialLaunchError(+ "The saved scout history and instructions exceed the 128 MiB judge attachment limit. "+ "Shorten the instructions or remove old scout memory."+ )launch = TrialLaunch(id=launch_id,team_id=config.team_id,@@ -395,7 +443,7 @@ def create_trial_launch(created_at=timezone.now(),skill_name=context.skill_name,skill_version=context.skill_version,- skill_body=skill_body if skill_body is not None else context.skill_body,+ skill_body=selected_skill_body,runtime_adapter=cast(Literal["claude", "codex"], adapter.value),model=selected_model,reasoning_effort=selected_effort,diff --git a/products/signals/backend/test/test_scout_trial_evaluation.py b/products/signals/backend/test/test_scout_trial_evaluation.pyindex 27e7ea2d26fa..886b2fdb39d8 100644--- a/products/signals/backend/test/test_scout_trial_evaluation.py+++ b/products/signals/backend/test/test_scout_trial_evaluation.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport jsonimport asyncio+import hashlibfrom collections.abc import Callablefrom datetime import timedeltafrom typing import TYPE_CHECKING, Literal@@ -749,8 +750,24 @@ class TestScoutTrialEvaluation(BaseTest):source.kind == "trace" and "The final saved measurement was read back." in source.text for source in sources)- @parameterized.expand(["duplicated", "edited"])- def test_full_logs_and_reports_are_saved_as_files_outside_the_snapshot(self, report_kind: str) -> None:+ @parameterized.expand([("duplicated", 0), ("edited", 2000)])+ def test_full_logs_and_reports_are_saved_as_files_outside_the_snapshot(+ self, report_kind: str, memory_entry_count: int+ ) -> None:+ if memory_entry_count:+ self.context = self.context.model_copy(+ update={+ "memory": [+ {+ "key": f"finding:synthetic-{index}",+ "content": f"Synthetic observation {index}. " + "a" * 44_000,+ }+ for index in range(memory_entry_count)+ ]+ }+ )+ self._save("contexts", self.context.id, self.context)+ assert len(self.context.model_dump_json().encode()) > 80 * 1024 * 1024self.scout_run.summary = "Synthetic finding. " * 12000self.scout_run.save(update_fields=["summary"])final_summary = "Synthetic authored finding. " * 320@@ -801,6 +818,15 @@ class TestScoutTrialEvaluation(BaseTest):sources = self._sources(snapshot)assert next(source.text for source in sources if source.kind == "summary") == self.scout_run.summaryassert next(source.text for source in sources if source.kind == "trace") == log+ saved_context = next(source.text for source in sources if source.kind == "context")+ assert json.loads(saved_context) == {+ "memory": self.context.memory,+ "notes": self.context.notes,+ "recent_runs": self.context.recent_runs,+ }+ context_file = next(file for file in snapshot.runs[0].files if file.kind == "context")+ assert context_file.size_bytes == len(saved_context.encode())+ assert context_file.sha256 == hashlib.sha256(saved_context.encode()).hexdigest()report = next(source for source in sources if source.kind == "report")packed = json.loads(report.text)["report"]assert packed["document"] == captured_report.documentdiff --git a/products/signals/backend/test/test_scout_trials_api.py b/products/signals/backend/test/test_scout_trials_api.pyindex eb3660432654..59af23add957 100644--- a/products/signals/backend/test/test_scout_trials_api.py+++ b/products/signals/backend/test/test_scout_trials_api.py@@ -39,8 +39,10 @@ from products.signals.backend.scout_harness.trial_launch import (create_trial_launch,load_trial_context,load_trial_launch,+ read_trial_launch,resolve_trial_source_model,scout_trials_enabled,+ trial_context_evidence,)from products.signals.backend.scout_harness.trial_result import TrialWorkflowStatus, export_trial_resultfrom products.signals.backend.scout_harness.trial_state import ScoutTrialStore, TrialReport, memory_snapshot@@ -447,7 +449,31 @@ class TestScoutTrialLaunch(APIBaseTest):assert history["has_more"] is Falseassert "skill_body" not in history["results"][0]- def test_candidate_first_preserves_baseline_and_retry_identity(self) -> None:+ @parameterized.expand([1, 2048])+ def test_candidate_first_preserves_baseline_and_retry_identity(self, memory_entry_count: int) -> None:+ self.user.first_name = "Synthetic"+ self.user.last_name = "Operator"+ self.user.save(update_fields=["first_name", "last_name"])+ source_run = _make_run(self.team)+ content = "Synthetic shared observation. " + "a" * 40_960+ SignalScratchpad.objects.bulk_create(+ [+ SignalScratchpad(+ team=self.team,+ key=f"finding:synthetic-{index}",+ content=content,+ created_by_run=source_run,+ )+ for index in range(memory_entry_count)+ ]+ )+ expired_note = SignalScoutNote.objects.create(+ team=self.team,+ skill_name=source_run.skill_name,+ content="Synthetic historical guidance.",+ created_by=self.user,+ expires_at=timezone.now() - timedelta(days=1),+ )launch_id = uuid4()candidate = create_trial_launch(config=self.config,@@ -456,6 +482,17 @@ class TestScoutTrialLaunch(APIBaseTest):skill_body="Trace dependencies before reporting.",reasoning_effort="high",)+ saved_context = load_trial_context(self.team.id, candidate.context_id)+ assert len(saved_context.memory) == memory_entry_count+ assert all(entry["content"] == content for entry in saved_context.memory)+ assert all(entry["created_by_skill"] == source_run.skill_name for entry in saved_context.memory)+ assert all(str(source_run.task_run_id) in str(entry["created_by_run_url"]) for entry in saved_context.memory)+ assert saved_context.notes[0]["id"] == str(expired_note.id)+ assert saved_context.notes[0]["created_by_name"] == "Synthetic Operator"+ if memory_entry_count > 1:+ assert len(saved_context.model_dump_json().encode()) > 80 * 1024 * 1024+ SignalScratchpad.objects.for_team(self.team.id).filter(key="finding:synthetic-0").update(content="Live change.")+ expired_note.delete()baseline = create_trial_launch(config=self.config, user=self.user, launch_id=uuid4(), context_id=candidate.context_id)@@ -471,6 +508,12 @@ class TestScoutTrialLaunch(APIBaseTest):reasoning_effort="high",)assert retry == candidate+ assert baseline.context_id == candidate.context_id+ assert load_trial_context(self.team.id, baseline.context_id) == saved_context+ trial_run = _make_run(+ self.team, metadata={"scout_trial": {"version": 1, "context_id": str(candidate.context_id)}}+ )+ assert ScoutTrialStore(trial_run).search_memory(key="finding:synthetic-0")[0].content == contentwith self.assertRaisesMessage(ScoutTrialLaunchError, "different settings"):create_trial_launch(config=self.config, user=self.user, launch_id=launch_id, skill_body="Another prompt")self.skill.refresh_from_db()@@ -484,6 +527,25 @@ class TestScoutTrialLaunch(APIBaseTest):create_trial_launch(config=self.config, user=self.user, launch_id=rejected_id, reasoning_effort="invented")with self.assertRaisesMessage(ScoutTrialLaunchError, "different comparison note"):create_trial_launch(config=self.config, user=self.user, launch_id=rejected_id, note="A changed note")+ context = load_trial_context(+ self.team.id, create_trial_launch(config=self.config, user=self.user, launch_id=uuid4()).context_id+ )+ evidence_bytes = sum(+ len(text.encode()) for text in (context.skill_body, context.note, trial_context_evidence(context))+ )+ oversized_id = uuid4()+ with patch("products.signals.backend.scout_harness.trial_launch.MAX_EVIDENCE_BYTES", evidence_bytes):+ create_trial_launch(config=self.config, user=self.user, launch_id=uuid4(), context_id=context.id)+ with self.assertRaisesMessage(ScoutTrialLaunchError, "judge attachment limit"):+ create_trial_launch(+ config=self.config,+ user=self.user,+ launch_id=oversized_id,+ context_id=context.id,+ skill_body=f"{context.skill_body} Check one more source.",+ )+ with self.assertRaisesMessage(ScoutTrialLaunchError, "was not found"):+ read_trial_launch(self.team.id, oversized_id)self.config.write_scopes = ["dashboard:write"]self.config.save()with self.assertRaisesMessage(ScoutTrialLaunchError, "do not support"):@@ -889,8 +951,13 @@ class TestScoutTrialLaunch(APIBaseTest):f"{module}.get_trial_comparison_status", return_value=TrialWorkflowStatus(status="not_started")) as workflow_status,):+ storage_reads = cast(MagicMock, object_storage.read)+ storage_reads.reset_mock()interrupted = self.client.post(f"{base}trial_comparison/", payload, format="json")assert interrupted.status_code == 500+ context_key = f"signals/scout-trials/{self.team.id}/contexts/{comparison_id}.json"+ context_reads = [call for call in storage_reads.call_args_list if call.args[0] == context_key]+ assert len(context_reads) <= 2, context_readshistory = self.client.get(f"{base}trial_comparison_history/")assert history.status_code == 200, history.dataassert [item["comparison_id"] for item in history.json()["results"]] == [comparison_id]