: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 write on an invalid expires_at (#91521)
posthog[bot]5657a86d85ad
diff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex ce38bcc3f47e..42a5cb01ff6f 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -22,6 +22,7 @@ from drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import extend_schema_fieldfrom rest_framework import serializersfrom rest_framework.exceptions import PermissionDenied+from rest_framework.fields import emptyfrom posthog.api.shared import UserBasicSerializerfrom posthog.event_usage import groups@@ -712,6 +713,22 @@ class SearchMemoryQuerySerializer(serializers.Serializer):)+class _BestEffortDateTimeField(serializers.DateTimeField):+ """A `DateTimeField` that never fails the request on an unparseable value.++ The agent computes `expires_at` itself, often from a clock it only guesses at, so a share of+ writes carry a malformed or nonsense datetime. The expiry is optional metadata; the content is+ the memory worth keeping. Coerce an unparseable value to `None` (durable) instead of rejecting+ the whole write — the same best-effort stance `run_id` takes on this serializer.+ """++ def run_validation(self, data: Any = empty) -> datetime | None:+ try:+ return super().run_validation(data)+ except serializers.ValidationError:+ return None++class RememberRequestSerializer(serializers.Serializer):"""Request body for `remember`."""@@ -737,20 +754,24 @@ class RememberRequestSerializer(serializers.Serializer):"null), not rejected, so the memory write is never lost."),)- expires_at = serializers.DateTimeField(+ expires_at = _BestEffortDateTimeField(required=False,allow_null=True,help_text=("Optional ISO-8601 expiry for a memory that's only true for a while (a cooldown, a ""window you're watching). After this time the entry drops out of searches, so you ""don't have to come back and forget it. Omit for a durable memory — every write sets "- "the whole entry, so omitting it on a later write clears an expiry set earlier."+ "the whole entry, so omitting it on a later write clears an expiry set earlier. "+ "Best-effort — a value that can't be parsed or is already in the past is dropped "+ "(the memory stays durable), not rejected, so the memory write is never lost."),)def validate_expires_at(self, value: datetime | None) -> datetime | None:+ # A past expiry would make the row invisible the moment it lands. Drop it rather than+ # rejecting the whole write — the content is the memory worth keeping, the expiry is not.if value is not None and value <= timezone.now():- raise serializers.ValidationError("expires_at must be in the future")+ return Nonereturn valuediff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex 020c048a582d..5f8e1da6761b 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -1266,7 +1266,10 @@ class SignalScratchpadViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):responses={200: OpenApiResponse(response=ScratchpadEntrySerializer, description="Memory entry written or refreshed."),400: OpenApiResponse(- description="Invalid memory shape (empty key/content, key too long, `expires_at` in the past)."+ description=(+ "Invalid memory shape (empty key/content, key too long, or an `expires_at` on a "+ "`followup:` entry). An unparseable or past `expires_at` is dropped, not rejected."+ )),},summary="Remember a scratchpad entry",diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex 283b163dc95b..deede1a2a4f2 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -1348,16 +1348,24 @@ class TestScoutHarnessScratchpadAPI(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUESTassert not SignalScratchpad.objects.filter(team=self.team).exists()- def test_remember_rejects_expires_at_in_the_past(self) -> None:- # A memory that's already lapsed on write is invisible the moment it lands, so it's a- # mistake worth a 400 rather than a silently useless row.+ @parameterized.expand(+ [+ ("past", "2020-01-01T00:00:00Z"),+ ("malformed", "in thirty days"),+ ]+ )+ def test_remember_drops_invalid_expires_at_without_losing_the_write(self, _name: str, expires_at: str) -> None:+ # The agent computes `expires_at` itself and a share of writes carry a past or unparseable+ # value. The content is the memory worth keeping, so an invalid expiry is dropped (the entry+ # lands durable) rather than rejecting the whole write. Wiring guard for the best-effort field.response = self.client.post(self._list_url(),- data={"key": "k1", "content": "v", "expires_at": "2020-01-01T00:00:00Z"},+ data={"key": "k1", "content": "v", "expires_at": expires_at},format="json",)- assert response.status_code == status.HTTP_400_BAD_REQUEST- assert not SignalScratchpad.objects.filter(team=self.team, key="k1").exists()+ assert response.status_code == status.HTTP_200_OK+ row = SignalScratchpad.objects.get(team=self.team, key="k1")+ assert row.expires_at is Nonedef test_search_does_not_leak_other_teams_memory(self) -> None:other = Team.objects.create(organization=self.organization, name="Other")diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 20d523781b49..e8da82ba6d8c 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -3844,7 +3844,7 @@ export interface RememberRequestApi {*/run_id?: string | null/**- * Optional ISO-8601 expiry for a memory that's only true for a while (a cooldown, a window you're watching). After this time the entry drops out of searches, so you don't have to come back and forget it. Omit for a durable memory — every write sets the whole entry, so omitting it on a later write clears an expiry set earlier.+ * Optional ISO-8601 expiry for a memory that's only true for a while (a cooldown, a window you're watching). After this time the entry drops out of searches, so you don't have to come back and forget it. Omit for a durable memory — every write sets the whole entry, so omitting it on a later write clears an expiry set earlier. Best-effort — a value that can't be parsed or is already in the past is dropped (the memory stays durable), not rejected, so the memory write is never lost.* @nullable*/expires_at?: string | nulldiff --git a/products/signals/frontend/generated/api.zod.ts b/products/signals/frontend/generated/api.zod.tsindex e172bb7ac504..a00778db9eeb 100644--- a/products/signals/frontend/generated/api.zod.ts+++ b/products/signals/frontend/generated/api.zod.ts@@ -1358,7 +1358,7 @@ export const SignalsScoutScratchpadRememberBody = /* @__PURE__ */ zod.datetime({ offset: true }).nullish().describe(- "Optional ISO-8601 expiry for a memory that's only true for a while (a cooldown, a window you're watching). After this time the entry drops out of searches, so you don't have to come back and forget it. Omit for a durable memory — every write sets the whole entry, so omitting it on a later write clears an expiry set earlier."+ "Optional ISO-8601 expiry for a memory that's only true for a while (a cooldown, a window you're watching). After this time the entry drops out of searches, so you don't have to come back and forget it. Omit for a durable memory — every write sets the whole entry, so omitting it on a later write clears an expiry set earlier. Best-effort — a value that can't be parsed or is already in the past is dropped (the memory stays durable), not rejected, so the memory write is never lost."),}).describe('Request body for `remember`.')diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 09f52f3570b4..104c6029c6e8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -73575,7 +73575,7 @@ export namespace Schemas {*/run_id?: string | null;/**- * Optional ISO-8601 expiry for a memory that's only true for a while (a cooldown, a window you're watching). After this time the entry drops out of searches, so you don't have to come back and forget it. Omit for a durable memory — every write sets the whole entry, so omitting it on a later write clears an expiry set earlier.+ * Optional ISO-8601 expiry for a memory that's only true for a while (a cooldown, a window you're watching). After this time the entry drops out of searches, so you don't have to come back and forget it. Omit for a durable memory — every write sets the whole entry, so omitting it on a later write clears an expiry set earlier. Best-effort — a value that can't be parsed or is already in the past is dropped (the memory stays durable), not rejected, so the memory write is never lost.* @nullable*/expires_at?: string | null;diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex f039863733e5..f09e5e363fb3 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -1866,7 +1866,7 @@ export const SignalsScoutScratchpadRememberBody = /* @__PURE__ */ zod.datetime({ offset: true }).nullish().describe(- "Optional ISO-8601 expiry for a memory that's only true for a while (a cooldown, a window you're watching). After this time the entry drops out of searches, so you don't have to come back and forget it. Omit for a durable memory — every write sets the whole entry, so omitting it on a later write clears an expiry set earlier."+ "Optional ISO-8601 expiry for a memory that's only true for a while (a cooldown, a window you're watching). After this time the entry drops out of searches, so you don't have to come back and forget it. Omit for a durable memory — every write sets the whole entry, so omitting it on a later write clears an expiry set earlier. Best-effort — a value that can't be parsed or is already in the past is dropped (the memory stays durable), not rejected, so the memory write is never lost."),}).describe('Request body for `remember`.')