: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(approvals): keep a datetime in validated_data from failing every gated flag save (#102404)
Phil Haackf99324068507
diff --git a/products/approvals/backend/decorators.py b/products/approvals/backend/decorators.pyindex 457bccf66c28..945e0a0272b0 100644--- a/products/approvals/backend/decorators.py+++ b/products/approvals/backend/decorators.py@@ -1,9 +1,11 @@+import jsonimport loggingfrom dataclasses import dataclass, fieldfrom functools import wrapsfrom typing import Any, Literal, Optional, Unionfrom django.conf import settings+from django.core.serializers.json import DjangoJSONEncoderfrom django.db import transactionfrom django.utils import timezone@@ -115,6 +117,18 @@ def _check_for_policy_conflicts(action_class, team, organization, intent_data: dreturn []+def _json_safe(value: dict[str, Any]) -> dict[str, Any]:+ """Render a payload as the plain JSON a JSONField can store.++ `intent` carries the endpoint serializer's `validated_data` verbatim, and DRF deserializes a+ typed field into its native Python object — a `DateTimeField` arrives as a `datetime`, which+ psycopg refuses to dump. Any such value made the whole save fail with an opaque+ "Failed to create approval request". DjangoJSONEncoder renders those as the ISO strings the+ serializer parses again on the apply path, so the replayed change is unchanged.+ """+ return json.loads(json.dumps(value, cls=DjangoJSONEncoder))++def _create_change_request(action_class,team,@@ -135,9 +149,9 @@ def _create_change_request(organization=organization,resource_type=action_class.resource_type,resource_id=resource_id,- intent=intent_data,- intent_display=display_data,- policy_snapshot=policy_snapshot,+ intent=_json_safe(intent_data),+ intent_display=_json_safe(display_data),+ policy_snapshot=_json_safe(policy_snapshot),created_by=user,state=ChangeRequestState.PENDING,expires_at=expires_at,diff --git a/products/approvals/backend/tests/test_decorators.py b/products/approvals/backend/tests/test_decorators.pyindex 7c107d9dbe36..556049518aa5 100644--- a/products/approvals/backend/tests/test_decorators.py+++ b/products/approvals/backend/tests/test_decorators.py@@ -1,11 +1,15 @@from contextlib import suppress+from datetime import datetime, timedeltafrom typing import Anyfrom posthog.test.base import APIBaseTestfrom unittest.mock import MagicMock, patch+from django.utils import timezone+from posthog.api.utils import ServiceRequest+from products.approvals.backend.decorators import _create_change_requestfrom products.approvals.backend.exceptions import ApprovalRequiredfrom products.approvals.backend.models import ApprovalPolicy, ChangeRequestfrom products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer@@ -155,3 +159,39 @@ class TestApprovalGateFailsClosed(APIBaseTest):flag.refresh_from_db()assert flag.active is False+++class TestChangeRequestIntentIsJsonSafe(APIBaseTest):+ """`intent` holds the endpoint serializer's validated_data, which carries native Python+ objects for typed fields. A `datetime` in there used to abort the INSERT inside psycopg and+ surface as an opaque "Failed to create approval request", blocking every gated save."""++ def _create_change_request(self, intent: dict[str, Any]) -> ChangeRequest:+ action_class = MagicMock()+ action_class.key = "feature_flag.update"+ action_class.version = 1+ action_class.resource_type = "feature_flag"++ return _create_change_request(+ action_class=action_class,+ team=self.team,+ organization=self.organization,+ resource_id="1",+ intent_data=intent,+ display_data={},+ policy_snapshot={},+ user=self.user,+ expires_at=timezone.now() + timedelta(days=14),+ )++ def test_datetime_in_intent_is_stored_as_an_iso_string(self):+ called_at = timezone.now()++ change_request = self._create_change_request(+ {"full_request_data": {"key": "test-flag", "last_called_at": called_at}}+ )++ change_request.refresh_from_db()+ stored = change_request.intent["full_request_data"]["last_called_at"]+ assert isinstance(stored, str), "the datetime must be rendered, not handed to psycopg as-is"+ assert abs(datetime.fromisoformat(stored) - called_at) < timedelta(milliseconds=1)diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.pyindex a49ccbcd591e..ec0503a8aad7 100644--- a/products/feature_flags/backend/api/feature_flag.py+++ b/products/feature_flags/backend/api/feature_flag.py@@ -1293,6 +1293,11 @@ class FeatureFlagSerializer("is_used_in_replay_settings","is_eligible_for_experiment",]+ # Server-owned timestamps. Neither is declared above, so ModelSerializer would otherwise+ # build them as writable (`auto_now` makes `updated_at` read-only, but `created_at` only+ # carries a default and `last_called_at` is a plain column). A client could then overwrite+ # the usage telemetry staleness detection reads.+ read_only_fields = ["created_at", "last_called_at"]def get_can_edit(self, feature_flag: FeatureFlag) -> bool:from typing import castdiff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.pyindex c9ae748726d5..6628df5625ac 100644--- a/products/feature_flags/backend/api/test/test_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_feature_flag.py@@ -15293,3 +15293,24 @@ class TestFeatureFlagReplayLinkFollowsRename(APIBaseTest):sibling_team.refresh_from_db()assert sibling_team.session_recording_linked_flag == {"id": flag.id, "key": "replay-gate-v2"}assert sibling_team.session_recording_trigger_groups["groups"][0]["conditions"]["flag"] == "replay-gate-v2"+++class TestFeatureFlagServerOwnedTimestamps(APIBaseTest):+ """`created_at` and `last_called_at` back staleness detection, so only the server writes them.+ The flag editor echoes the whole loaded flag back on save, which would otherwise let a client+ overwrite its own usage telemetry."""++ @parameterized.expand(["created_at", "last_called_at"])+ def test_timestamp_is_ignored_on_update(self, field: str):+ original = now() - timedelta(days=30)+ flag = FeatureFlag.objects.create(team=self.team, key="server-owned", created_by=self.user, **{field: original})++ response = self.client.patch(+ f"/api/projects/{self.team.id}/feature_flags/{flag.id}/",+ {"name": "renamed", field: (now() - timedelta(days=1)).isoformat()},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK, response.content+ flag.refresh_from_db()+ assert getattr(flag, field) == originaldiff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex 0cc99967a93f..4ab16f24bbd0 100644--- a/products/feature_flags/frontend/generated/api.schemas.ts+++ b/products/feature_flags/frontend/generated/api.schemas.ts@@ -560,7 +560,7 @@ export interface FeatureFlagApi {/** Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`). */archived?: booleanreadonly created_by: UserBasicApi- created_at?: string+ readonly created_at: string/** @nullable */readonly updated_at: string | nullversion?: number@@ -616,7 +616,7 @@ export interface FeatureFlagApi {* Last time this feature flag was called (from $feature_flag_called events)* @nullable*/- last_called_at?: string | null+ readonly last_called_at: string | null_create_in_folder?: string/** Check if any team gates session recording on this flag, by linked flag or trigger group. */readonly is_used_in_replay_settings: booleandiff --git a/products/feature_flags/frontend/generated/api.zod.ts b/products/feature_flags/frontend/generated/api.zod.tsindex 39f332236612..906c3d2f4942 100644--- a/products/feature_flags/frontend/generated/api.zod.ts+++ b/products/feature_flags/frontend/generated/api.zod.ts@@ -551,7 +551,6 @@ export const FeatureFlagsUpdateBody = /* @__PURE__ */ zod.describe('Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`).'),- created_at: zod.iso.datetime({ offset: true }).optional(),version: zod.number().default(featureFlagsUpdateBodyVersionDefault),ensure_experience_continuity: zod.boolean().nullish(),tags: zod.array(zod.unknown()).optional(),@@ -600,10 +599,6 @@ export const FeatureFlagsUpdateBody = /* @__PURE__ */ zod.describe('Identifier used for bucketing users into rollout and variants\n\n\* `distinct_id` - User ID (default)\n\* `device_id` - Device ID'),- last_called_at: zod.iso- .datetime({ offset: true })- .nullish()- .describe('Last time this feature flag was called (from $feature_flag_called events)'),_create_in_folder: zod.string().optional(),}).describe('Serializer mixin that handles tags for objects.')@@ -992,7 +987,6 @@ export const FeatureFlagsCreateStaticCohortForFlagCreateBody = /* @__PURE__ */ z.describe('Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`).'),- created_at: zod.iso.datetime({ offset: true }).optional(),version: zod.number().default(featureFlagsCreateStaticCohortForFlagCreateBodyVersionDefault),ensure_experience_continuity: zod.boolean().nullish(),tags: zod.array(zod.unknown()).optional(),@@ -1041,10 +1035,6 @@ export const FeatureFlagsCreateStaticCohortForFlagCreateBody = /* @__PURE__ */ z.describe('Identifier used for bucketing users into rollout and variants\n\n\* `distinct_id` - User ID (default)\n\* `device_id` - Device ID'),- last_called_at: zod.iso- .datetime({ offset: true })- .nullish()- .describe('Last time this feature flag was called (from $feature_flag_called events)'),_create_in_folder: zod.string().optional(),}).describe('Serializer mixin that handles tags for objects.')diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 2085ce4cfeec..d76eeb67d036 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -42424,7 +42424,7 @@ export namespace Schemas {/** Whether the flag is archived. Archived flags are hidden from the flag list by default and must be disabled (`active: false`). */archived?: boolean;readonly created_by: UserBasic;- created_at?: string;+ readonly created_at: string;/** @nullable */readonly updated_at: string | null;version?: number;@@ -42480,7 +42480,7 @@ export namespace Schemas {* Last time this feature flag was called (from $feature_flag_called events)* @nullable*/- last_called_at?: string | null;+ readonly last_called_at: string | null;_create_in_folder?: string;/** Check if any team gates session recording on this flag, by linked flag or trigger group. */readonly is_used_in_replay_settings: boolean;