: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(signals): keep scratchpad writes when a run id is unparseable (#93909)
posthog[bot]2265c95b1394
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.mdindex 7c359d837d44..fa535beddcf9 100644--- a/products/signals/backend/scout_harness/AGENTS.md+++ b/products/signals/backend/scout_harness/AGENTS.md@@ -43,6 +43,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e`remember` is a full-state upsert, so a write with no `expires_at` clears an expiry an earlier write set — sticky expiry would keep hiding an entry that has since become permanent, with no way for the rewriting scout to know a clock was on it.`search_scratchpad` drops expired rows unless `include_expired=True` (the human audit path); expiry hides a row, it never deletes one, so the key stays taken and both `forget` and the upsert still find it.A reader that goes to the manager rather than through `search_scratchpad` stays unfiltered on purpose — `derived_metadata._touched_followup_queue` is the one such reader, and has to be, since a `followup:` entry lapsing after a run doesn't undo the validation work that run did.+ `run_id` on a `remember` write is best-effort lineage, never a gate: the serializer coerces one it can't parse to `None` (`_BestEffortUUIDField`, the same stance `expires_at` takes) and the view drops one that names no run on this project, because a scout retypes the id out of its run prompt and a truncated copy must not cost the memory. When nothing usable comes off the body the view falls back to `tools/runs.run_id_for_sandbox_task`, which resolves the writing run from the task the caller's sandbox token is bound to — provenance the sandbox cannot choose, so lineage survives the typo. Non-sandbox callers and the pipeline stages resolve to no run and are unaffected.The scratchpad is shared with the report pipeline, not scout-only. `remember` / `forget` are gated on their own `signal_scratchpad_internal:write` scope rather than the wider `signal_scout_internal:write`, so the pipeline's research and implementation runs can persist what they judged without also getting `emit_signal` and `record_output`. Scouts keep both tools, because `SCOUT_INTERNAL_SCOPES` carries the scratchpad scope too; the pipeline's own postures are the `signals_research` / `signals_implementation` presets in `posthog/temporal/oauth.py`. `signals_research` withholds `task:write`: it turns the MCP read-only header off so its scratchpad tools survive, and that header was the only thing keeping the task-write toolset (report state included) away from a stage meant to read.Those stages have no `SignalScoutRun`, so `created_by_run` cannot name them. They stamp `SignalScratchpad.created_by_identity` instead — a `pipeline:*` string from `../pipeline_identity.py`, resolved server-side from the token's bound task (its `ai_stage`, written once at run creation) rather than passed in, since a writer that could name itself could name a scout's skill. `_to_entry` reads it as `created_by_skill` when there is no run, so `scout-scratchpad-search` attributes every entry the same way. Like `created_by_run` it is written on create only, so an upsert keeps the original author.- `notes.py` — `list_notes` / `leave_note` / `delete_note` backed by the `SignalScoutNote` model: steering notes humans (or other agents) leave for the fleet over the public MCP surface (`scout-notes-*` tools), the inbound counterpart to the scratchpad. A note targets one scout by `skill_name` or the whole fleet (blank), optionally expiring via `expires_at`; the run prompt's _Notes left for you_ section directs every scout to `scout-notes-list` its own notes in step 1 and treat them as advisory steering. A third audience is a stage of the report pipeline, addressed through the reserved `pipeline:*` family (`PIPELINE_AUDIENCES`, holding `pipeline:report-research` today): a pseudo-target riding the same `skill_name` column, allowlisted at write time so an unrecognized one is rejected instead of silently steering no one, and skipping the scout-skill lookup because a stage has no `LLMSkill` row. `list_notes` matches `skill_name` exactly, so no scout ever sees a pipeline note; the research loader in `../report_steering.py` reads `pipeline:report-research` alongside the report's scout target and the fleet-wide blanks. `validate_note_target`, the shared write-time rule, and the audience constants live in `../note_targets.py`, an import-light module, because the Django admin form calls the rule at registry load and importing anything under `tools/` runs that package's `__init__`, which pulls in every harness tool. Unlike the scratchpad there is no sandbox-only write gate, but writes still demand skill-authoring-level authorization (keys need `llm_skill:write` on top of `signal_scout:write`, and every writer must clear the `llm_skill` RBAC editor bar) — so a note-writer could already steer the fleet by editing its skills, and notes add no new steering power. Three more writers derive rows from inbox activity. `../dismissal_notes.py`: judging an inbox report with a note (dismiss, snooze, or restore) also leaves it here as an `origin=report_dismissal` note, targeted at the scout that authored the report, so a reviewer's verdict reaches the scout without it having to re-find the report. Resolving does not, since that says the report did its job rather than that filing it was wrong. `../discussion_notes.py`: opening a discussion on a report (the inbox "Discuss" action, which kicks off a Q&A task) also leaves the user's question here as an `origin=report_discussion` note, targeted at the authoring scout — framed as context to weigh or ignore, not a verdict, so the scout can fold a durable preference/correction into its scratchpad or dismiss it as noise. `../feedback_notes.py`: the thumbs rating at the end of a report body ("Was this report useful?") carries its optional note here as an `origin=report_feedback` note, targeted at the authoring scout. Unlike a dismissal it never falls back to a fleet-wide note — feedback is a verdict on one scout's own report, so with no resolvable authoring scout nothing is forwarded and the call is a no-op — and it never changes the report's state; the analytics event the client fires stays the durable record of the rating. All three paths re-check the same steering gate (token `scoped_teams`, canonical-project access, and the `llm_skill` editor bar) since the dismiss, discuss, and feedback actions need only `task:write`, and all forward only on the canonical team. The discuss and feedback paths additionally demand the `signal_scout:write` / `llm_skill:write` key scopes: a dismissal's text reaches runs anyway through the reports API, whereas the note is the only path a discussion question or feedback note takes to a scout, so a `task:write` credential must not open it alone. The discuss path is triggered from the tasks viewset (which holds the request the gate reads) through `facade/api.py:forward_report_discussion_note`, never from the tasks facade. On the read side, all three derived origins quote report content (report id, title, the note text), so `SignalScoutNoteViewSet.list` withholds them from any caller failing the reports read gate (`_may_read_reports`). The derived rows are context with a TTL; the `dismissal` artefact / discussion task / feedback analytics event stays the record of truth. Notes reach two surfaces outside the fleet, both through `../report_steering.py`. `load_report_steering` renders the `HUMAN`-origin ones into the description of the self-driving implementation task, so steering that used to stop at the scout also reaches the run that writes the code; the derived origins are withheld there for the reason the read gate withholds them — they quote report content, which is built from raw product data, and that run can open a PR. `load_research_steering` renders every origin into the pipeline's report-research prompt, because the derived ones are feedback on exactly the judgment that stage is about to make; that run is read-only, already holds the report's raw signals, and writes back only to the report on the same team.diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex 3bc1eb3e2661..0bf05bf1eebc 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -754,6 +754,24 @@ class _BestEffortDateTimeField(serializers.DateTimeField):return None+class _BestEffortUUIDField(serializers.UUIDField):+ """A `UUIDField` that never fails the request on an unparseable value.++ The scout reads its `run_id` out of the run prompt and retypes it into the write, so a share of+ writes carry a truncated or mistyped identifier. Lineage is optional metadata; the content is+ the memory worth keeping. Coerce an unparseable value to `None` (lineage left unstamped)+ instead of rejecting the whole write — the same best-effort stance `expires_at` takes on this+ serializer, and the stance the view already takes on a `run_id` that names no run on this+ project.+ """++ def run_validation(self, data: Any = empty) -> UUID | None:+ try:+ return super().run_validation(data)+ except serializers.ValidationError:+ return None++class RememberRequestSerializer(serializers.Serializer):"""Request body for `remember`."""@@ -770,13 +788,15 @@ class RememberRequestSerializer(serializers.Serializer):max_length=MAX_SCRATCHPAD_CONTENT_LENGTH,help_text="Prose to write. Read verbatim into future prompts.",)- run_id = serializers.UUIDField(+ run_id = _BestEffortUUIDField(required=False,allow_null=True,help_text=("Run that authored this memory; persisted as `created_by_run_id` for lineage. "- "Best-effort — a `run_id` that isn't a run on this project is dropped (lineage left "- "null), not rejected, so the memory write is never lost."+ "Best-effort — a `run_id` that is unparseable, or that isn't a run on this project, is "+ "dropped rather than rejected, so the memory write is never lost. Omit it and the "+ "lineage still lands: a write from a scout sandbox is attributed to that sandbox's own "+ "run."),)expires_at = _BestEffortDateTimeField(diff --git a/products/signals/backend/scout_harness/tools/runs.py b/products/signals/backend/scout_harness/tools/runs.pyindex 4edf8603048d..f498e3461695 100644--- a/products/signals/backend/scout_harness/tools/runs.py+++ b/products/signals/backend/scout_harness/tools/runs.py@@ -19,6 +19,7 @@ from __future__ import annotationsfrom dataclasses import asdict, dataclass, fieldfrom datetime import datetime, timedeltafrom typing import TYPE_CHECKING, Any+from uuid import UUIDfrom django.db import connectionfrom django.db.models import Q@@ -449,6 +450,29 @@ def get_run(*, team_id: int, run_id: str) -> RunDetail | None:return _to_detail(row, team_id=team_id)+def run_id_for_sandbox_task(*, task_id: UUID | None, team_id: int) -> str | None:+ """The run a scout sandbox is executing, resolved from the task its token is bound to.++ Provenance, not a claim: the sandbox cannot choose which task its OAuth token carries, so this+ names the authoring run even when the agent never supplies a `run_id` or supplies one it+ mistyped out of its prompt. Mirrors `pipeline_writer_identity`, which resolves the report+ pipeline's stages off the same binding.++ None is the answer for every non-scout caller — a human, a personal API key, and the report+ pipeline's own stages, whose tasks have no `SignalScoutRun` row. A task can hold several runs+ (a retried dispatch), so the newest wins.+ """+ if task_id is None:+ return None+ row_id = (+ SignalScoutRun.objects.filter(team_id=team_id, task_run__task_id=task_id)+ .order_by("-created_at", "-id")+ .values_list("id", flat=True)+ .first()+ )+ return str(row_id) if row_id is not None else None++def _to_summary(row: SignalScoutRun, *, team_id: int) -> RunSummary:task_run = row.task_runtask_id = str(task_run.task_id) if task_run is not None else Nonediff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex 6bb2927264df..820547b6d97e 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -145,6 +145,7 @@ from products.signals.backend.scout_harness.tools.runs import (fleet_findings_summary,get_run,recent_runs_per_scout,+ run_id_for_sandbox_task,search_recent_runs,)from products.signals.backend.scout_harness.tools.scratchpad import (@@ -1228,30 +1229,32 @@ class SignalScratchpadViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)def create(self, request: Request, *args, **kwargs) -> Response:data = request.validated_data+ team_id = _canonical_team_id(self)run_id = data.get("run_id") or None# `run_id` only stamps best-effort `created_by_run_id` lineage — a memory write must- # never be lost over it. So an unverifiable `run_id` is dropped (lineage left null),- # not rejected. We still won't stamp a `run_id` that isn't a run on this project: the- # agent's MCP token pins us to a team, but `run_id` is a free field on the body and a- # foreign-team UUID would otherwise create a cross-team `created_by_run_id` reference.- # Bad UUIDs are blocked by `UUIDField` in the serializer.- if (- run_id is not None- and not SignalScoutRun.objects.filter(id=run_id, team_id=_canonical_team_id(self)).exists()- ):+ # never be lost over it. So an unverifiable `run_id` is dropped, not rejected: the+ # serializer coerces one it can't parse to None, and one that names no run on this project+ # is dropped here. The project check is what keeps `run_id` from creating a cross-team+ # `created_by_run_id` reference — the agent's MCP token pins us to a team, but `run_id`+ # is a free field on the body.+ if run_id is not None and not SignalScoutRun.objects.filter(id=run_id, team_id=team_id).exists():run_id = None+ # Nothing usable came off the body, so fall back to the run the caller's sandbox token is+ # bound to. A scout copies `run_id` out of its prompt by hand and a share of those copies+ # arrive truncated, which used to cost the entry its run link; the token binding is the+ # server's own record of which run is writing, so lineage survives the typo.+ if run_id is None:+ run_id = run_id_for_sandbox_task(task_id=_sandbox_bound_task_id(request), team_id=team_id)try:entry = remember(- team_id=_canonical_team_id(self),+ team_id=team_id,key=data["key"],content=data["content"],run_id=str(run_id) if run_id is not None else None,# Derived from the token's bound task, never from the body: a report-pipeline# stage has no run to point `run_id` at, and a writer that could name itself# could name a scout's skill instead.- identity=pipeline_writer_identity(- task_id=_sandbox_bound_task_id(request), team_id=_canonical_team_id(self)- ),+ identity=pipeline_writer_identity(task_id=_sandbox_bound_task_id(request), team_id=team_id),expires_at=data.get("expires_at"),)except InvalidScratchpadError as exc:diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex 0e270bf4b728..f16227cd417c 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -1407,7 +1407,8 @@ class TestScoutHarnessScratchpadAPI(APIBaseTest):def test_remember_drops_run_id_from_another_team(self) -> None:# A run UUID from another team must not create cross-team lineage on this# team's memory row — but lineage is best-effort, so the write still lands- # with `created_by_run_id` left null rather than being rejected.+ # with `created_by_run_id` left null rather than being rejected. This caller's+ # token names no task, so there is no sandbox run to fall back to either.other = Team.objects.create(organization=self.organization, name="Other")other_run = _make_run(other)response = self.client.post(@@ -1421,7 +1422,8 @@ class TestScoutHarnessScratchpadAPI(APIBaseTest):def test_remember_drops_unknown_run_id(self) -> None:# A well-formed UUID that doesn't reference any run row is dropped (no orphan- # lineage), but the memory write itself must never be lost over it.+ # lineage), but the memory write itself must never be lost over it. This caller's+ # token names no task, so there is no sandbox run to fall back to either.response = self.client.post(self._list_url(),data={"key": "k1", "content": "v", "run_id": "00000000-0000-0000-0000-000000000000"},@@ -1431,14 +1433,65 @@ class TestScoutHarnessScratchpadAPI(APIBaseTest):row = SignalScratchpad.objects.get(team=self.team, key="k1")assert row.created_by_run_id is None- def test_remember_rejects_malformed_run_id(self) -> None:- # UUIDField in the serializer rejects non-UUID strings before the view runs.+ @parameterized.expand(+ [+ ("not_a_uuid", "not-a-uuid"),+ # The shape scouts actually send: a run UUID retyped out of the run prompt with a+ # group dropped.+ ("truncated_uuid", "01a0658a-30c3-7efb-bf14e4690b67"),+ ]+ )+ def test_remember_keeps_the_write_when_run_id_is_unparseable(self, _name: str, run_id: str) -> None:+ # The scout copies `run_id` out of its prompt by hand, so a share of writes carry a+ # mistyped one. Lineage is best-effort metadata and the memory is the part worth keeping,+ # so an unparseable id must not cost the whole write. Wiring guard for the best-effort field.response = self.client.post(self._list_url(),- data={"key": "k1", "content": "v", "run_id": "not-a-uuid"},+ data={"key": "k1", "content": "v", "run_id": run_id},format="json",)- assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert response.status_code == status.HTTP_200_OK, response.json()+ assert SignalScratchpad.objects.get(team=self.team, key="k1").content == "v"++ @parameterized.expand(+ [+ ("omitted", None),+ ("unparseable", "01a0658a-30c3-7efb-bf14e4690b67"),+ ("names_no_run", "00000000-0000-0000-0000-000000000000"),+ ]+ )+ def test_remember_attributes_the_entry_to_the_sandbox_run(self, _name: str, run_id: str | None) -> None:+ # The contract the scout fleet depends on: a memory written from a scout sandbox keeps its+ # run link even when the body carries no usable `run_id`. The token's bound task is the+ # server's own record of which run is writing, so the typo costs nothing.+ run = _make_run(self.team)+ _authenticate_as_scout(self, sandbox_task_id=run.task_run.task_id)+ body: dict = {"key": "k1", "content": "v"}+ if run_id is not None:+ body["run_id"] = run_id++ response = self.client.post(self._list_url(), data=body, format="json")++ assert response.status_code == status.HTTP_200_OK, response.json()+ row = SignalScratchpad.objects.get(team=self.team, key="k1")+ assert str(row.created_by_run_id) == str(run.id)++ def test_remember_prefers_a_run_id_the_body_names_over_the_sandbox_run(self) -> None:+ # The fallback only fills a gap. A scout writing on behalf of an earlier run still gets+ # the run it named.+ named = _make_run(self.team)+ sandbox_run = _make_run(self.team)+ _authenticate_as_scout(self, sandbox_task_id=sandbox_run.task_run.task_id)++ response = self.client.post(+ self._list_url(),+ data={"key": "k1", "content": "v", "run_id": str(named.id)},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ row = SignalScratchpad.objects.get(team=self.team, key="k1")+ assert str(row.created_by_run_id) == str(named.id)class TestScoutHarnessNotesAPI(APIBaseTest):diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 8a3caba94f68..c6e747a3ee9a 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -3883,7 +3883,7 @@ export interface RememberRequestApi {*/content: string/**- * Run that authored this memory; persisted as `created_by_run_id` for lineage. Best-effort — a `run_id` that isn't a run on this project is dropped (lineage left null), not rejected, so the memory write is never lost.+ * Run that authored this memory; persisted as `created_by_run_id` for lineage. Best-effort — a `run_id` that is unparseable, or that isn't a run on this project, is dropped rather than rejected, so the memory write is never lost. Omit it and the lineage still lands: a write from a scout sandbox is attributed to that sandbox's own run.* @nullable*/run_id?: string | nulldiff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex 798cbf622211..e23aa37e621e 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -1451,7 +1451,7 @@ export const SignalsScoutScratchpadRememberBody = /* @__PURE__ */ zod.uuid().nullish().describe(- "Run that authored this memory; persisted as `created_by_run_id` for lineage. Best-effort — a `run_id` that isn't a run on this project is dropped (lineage left null), not rejected, so the memory write is never lost."+ "Run that authored this memory; persisted as `created_by_run_id` for lineage. Best-effort — a `run_id` that is unparseable, or that isn't a run on this project, is dropped rather than rejected, so the memory write is never lost. Omit it and the lineage still lands: a write from a scout sandbox is attributed to that sandbox's own run."),expires_at: zod.iso.datetime({ offset: true })diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 38dbb41cc547..6eab38df784a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -74305,7 +74305,7 @@ export namespace Schemas {*/content: string;/**- * Run that authored this memory; persisted as `created_by_run_id` for lineage. Best-effort — a `run_id` that isn't a run on this project is dropped (lineage left null), not rejected, so the memory write is never lost.+ * Run that authored this memory; persisted as `created_by_run_id` for lineage. Best-effort — a `run_id` that is unparseable, or that isn't a run on this project, is dropped rather than rejected, so the memory write is never lost. Omit it and the lineage still lands: a write from a scout sandbox is attributed to that sandbox's own run.* @nullable*/run_id?: string | null;diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex bbdb694804a2..d3f704700186 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -2001,7 +2001,7 @@ export const SignalsScoutScratchpadRememberBody = () => zod.string().nullish().describe(- "Run that authored this memory; persisted as `created_by_run_id` for lineage. Best-effort — a `run_id` that isn't a run on this project is dropped (lineage left null), not rejected, so the memory write is never lost."+ "Run that authored this memory; persisted as `created_by_run_id` for lineage. Best-effort — a `run_id` that is unparseable, or that isn't a run on this project, is dropped rather than rejected, so the memory write is never lost. Omit it and the lineage still lands: a write from a scout sandbox is attributed to that sandbox's own run."),expires_at: zod.iso.datetime({ offset: true })