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.

chore(api): review timestamp ownership explicitly instead of guessing it (#104080)

Phil Haackf53eab0c74cd
diff --git a/posthog/test/repo_invariants/test_serializer_timestamp_guard.py b/posthog/test/repo_invariants/test_serializer_timestamp_guard.py
index 51dc80f4e599..bff849693808 100644
--- a/posthog/test/repo_invariants/test_serializer_timestamp_guard.py
+++ b/posthog/test/repo_invariants/test_serializer_timestamp_guard.py
@@ -7,29 +7,40 @@ client overwrite something the product reads back as server truth.
years, because a `ModelSerializer` builds every concrete column as writable unless
something says otherwise.
-Django has no declarative marker for "the server owns this column", so ownership is
-read from two kinds of evidence:
-
-- the column fills itself in (`auto_now`, `auto_now_add`, or a non-null `default`), or
-- the column is named the way audit and telemetry columns are named (`created_at`,
- `last_called_at`, `last_seen_at`, ...), which is the only signal a plain nullable
- column that only the backend writes ever gives.
-
-A bare `default=None` is not evidence: it means nullable, not server-filled, and
-flagging it caught fields a client is supposed to set (a batch export's `start_at`).
-
-To clear a violation on a field the serializer generates from the model, put it in
-`read_only_fields` on `Meta`. A field the serializer declares needs `read_only=True`
-on the declaration itself, because DRF ignores `read_only_fields` for a declared
-field. A timestamp a client is genuinely supposed to set goes in `ALLOWED_WRITABLE`
-with a one-line reason.
+Django has no declarative marker for "the server owns this column", and no property
+of the column reliably stands in for one. `auto_now` and a non-null `default` are
+evidence of self-filling, not of ownership: `published_at = DateTimeField(default=
+timezone.now)` is a field a client is meant to set. A naming convention guesses in
+both directions at once, missing `expires_at` while flagging a `last_sent_at` the
+API offers on purpose.
+
+So ownership is not inferred. Every writable `DateTimeField` a write route exposes
+must appear in `REVIEWED_WRITABLE` with a reason a person wrote. An entry whose
+reason starts with `TODO` is a hole the owning team still has to close; every other
+entry records a field a client is supposed to set, and why.
+
+The cost is one line per field. The benefit is that a new writable timestamp cannot
+reach master unnoticed, whatever the column is called and however it is declared.
+
+To close a hole on a field the serializer generates from the model, put it in
+`read_only_fields` on `Meta`, then delete its entry here. A field the serializer
+declares needs `read_only=True` on the declaration itself, because DRF ignores
+`read_only_fields` for a declared field.
+
+Two shapes are out of scope, so "every writable timestamp is reviewed" means every
+one this guard can see, not every one the API has:
+
+- A serializer with no `Meta.model` is skipped, because there is no column to read
+ ownership from. Only the view's own code says whether the value becomes server
+ truth, and this file does not read it.
+- Only top-level fields are compared. A timestamp inside a nested writable
+ serializer is not reached.
The failure message lists every violation:
pytest posthog/test/repo_invariants/test_serializer_timestamp_guard.py
"""
-import re
import ast
import sys
import inspect
@@ -53,27 +64,89 @@ from rest_framework.schemas.generators import EndpointEnumerator
WRITE_METHODS = frozenset({"POST", "PUT", "PATCH"})
-# Columns the backend writes on the user's behalf. Matching one is evidence of server
-# ownership on its own, because a plain nullable audit column carries no other signal.
-SERVER_OWNED_NAME = re.compile(
- r"^(created_at|updated_at|modified_at|deleted_at"
- r"|last_\w+_at"
- r"|\w+_(seen|synced|calculated|refreshed|computed)_at)$"
+# The ways a view names the serializer it hands a write request. One entry per distinct
+# mechanism, because `test_every_discovery_path_finds_something` asserts each still
+# finds something, and a mechanism folded into another's bucket can die unnoticed.
+SERIALIZER_SOURCES = (
+ "serializer_class attribute",
+ "serializer lookup table",
+ "get_serializer_class return",
+ "get_serializer_class local",
)
-
-# `module.Serializer.field` -> why a client is allowed to write this timestamp. A `TODO`
-# marks a hole the owning team still has to close.
-ALLOWED_WRITABLE: dict[str, str] = {
+REQUEST_BODY_SOURCE = "@extend_schema(request=...)"
+
+# `module.Serializer.field` -> why this timestamp is writable on a write route.
+# A reason starting with `TODO` marks a hole the owning team still has to close;
+# every other entry records a value a client is supposed to set. Nothing is inferred,
+# so a field missing from here fails the build until a person classifies it.
+REVIEWED_WRITABLE: dict[str, str] = {
+ "products.cdp.backend.api.hog_function.HogFunctionSerializer.base_updated_at": "Optimistic-concurrency guard: the client echoes the timestamp it loaded, and the view pops it before save",
+ "products.managed_migrations.backend.api.batch_imports.BatchImportDateRangeSourceCreateSerializer.start_date": "Client picks the import window; write-only input, never stored on the model",
+ "products.managed_migrations.backend.api.batch_imports.BatchImportDateRangeSourceCreateSerializer.end_date": "Client picks the import window; write-only input, never stored on the model",
+ "ee.api.subscription.SubscriptionSerializer.start_date": "Client sets when delivery starts",
+ "ee.api.subscription.SubscriptionSerializer.until_date": "Client sets when delivery stops, or null for indefinite",
+ "ee.api.subscription.SubscriptionWriteSerializer.start_date": "Client sets when delivery starts",
+ "ee.api.subscription.SubscriptionWriteSerializer.until_date": "Client sets when delivery stops, or null for indefinite",
"ee.clickhouse.views.groups.GroupTypeSerializer.created_at": "TODO: server-owned, the model sets it on creation itself",
- "posthog.api.advanced_activity_logs.viewset.ActivityLogSerializer.created_at": "TODO: server-owned audit timestamp, make read-only",
"posthog.api.advanced_activity_logs.viewset.ActivityLogFlatExportSerializer.created_at": "TODO: server-owned audit timestamp, make read-only",
+ "posthog.api.advanced_activity_logs.viewset.ActivityLogSerializer.created_at": "TODO: server-owned audit timestamp, make read-only",
"posthog.api.event_definition.EventDefinitionSerializer.created_at": "TODO: server-owned, set when ingestion first sees the event",
"posthog.api.event_definition.EventDefinitionSerializer.last_seen_at": "TODO: server-owned ingestion telemetry, make read-only",
+ "posthog.api.health_issue.HealthIssueSerializer.snoozed_until": "TODO: server-derived. SnoozeDurationField accepts only a relative duration such as '7d' and computes the stored instant",
"posthog.api.my_notifications.MyNotificationsSerializer.created_at": "TODO: server-owned activity log timestamp, make read-only",
"posthog.api.web_experiment.WebExperimentsAPISerializer.created_at": "TODO: server-owned creation timestamp, make read-only",
+ "posthog.session_recordings.session_recording_api.SessionRecordingSharedSerializer.end_time": "TODO: server-owned, derived from the ingested replay events",
+ "posthog.session_recordings.session_recording_api.SessionRecordingSharedSerializer.start_time": "TODO: server-owned, derived from the ingested replay events",
"products.actions.backend.api.action.ActionSerializer.last_calculated_at": "TODO: server-owned, written by the action calculation job",
+ "products.actions.backend.api.action.ActionSerializer.pinned_at": "TODO: server-derived on pin. update() discards the supplied value and stores its own now(); only the null that unpins is the client's",
+ "products.alerts.backend.presentation.views.alert.AlertSerializer.snoozed_until": "TODO: server-derived. The client sends a relative date string and update() resolves it to the stored instant",
+ "products.annotations.backend.api.annotation.AnnotationSerializer.date_marker": "Client sets when the annotation happened, to place it on a chart",
+ "products.batch_exports.backend.api.batch_export.BatchExportBackfillSerializer.adjusted_start_at": "TODO: server-owned, the backfill derives it from the earliest available data",
+ "products.batch_exports.backend.api.batch_export.BatchExportBackfillSerializer.end_at": "Client requests the data interval to backfill",
+ "products.batch_exports.backend.api.batch_export.BatchExportBackfillSerializer.finished_at": "TODO: server-owned, written by the backfill workflow when it ends",
+ "products.batch_exports.backend.api.batch_export.BatchExportBackfillSerializer.start_at": "Client requests the data interval to backfill",
+ "products.batch_exports.backend.api.batch_export.BatchExportRunSerializer.data_interval_end": "Response shape for the POST cancel and retry actions, which take no request body",
+ "products.batch_exports.backend.api.batch_export.BatchExportRunSerializer.data_interval_start": "Response shape for the POST cancel and retry actions, which take no request body",
+ "products.batch_exports.backend.api.batch_export.BatchExportRunSerializer.finished_at": "Response shape for the POST cancel and retry actions, which take no request body",
+ "products.batch_exports.backend.api.batch_export.BatchExportSerializer.end_at": "Client-supplied bound, runs after it are not triggered",
"products.batch_exports.backend.api.batch_export.BatchExportSerializer.last_paused_at": "TODO: written by the pause action, make read-only",
+ "products.batch_exports.backend.api.batch_export.BatchExportSerializer.start_at": "Client-supplied bound, runs before it are not triggered",
+ "products.billing_alerts.backend.presentation.serializers.BillingAlertConfigurationSerializer.snoozed_until": "Client-set instant: a plain DateTimeField that ModelSerializer writes to the column unchanged, with no relative-duration parsing on this path",
+ "products.conversations.backend.api.tickets.TicketSerializer.sla_due_at": "Client or a workflow sets the SLA deadline, and null clears it",
+ "products.conversations.backend.api.tickets.TicketSerializer.snoozed_until": "Client-set instant: the ticket action assigns validated_data['snoozed_until'] to ticket.snoozed_until, with no relative-duration parsing on this path",
+ "products.conversations.backend.api.tickets.TicketUpdateRequestSerializer.sla_due_at": "Client or a workflow sets the SLA deadline, and null clears it",
+ "products.conversations.backend.api.tickets.TicketUpdateRequestSerializer.snoozed_until": "Client-set instant: the ticket action assigns validated_data['snoozed_until'] to ticket.snoozed_until, with no relative-duration parsing on this path",
"products.dashboards.backend.api.dashboard.DashboardSerializer.last_accessed_at": "TODO: server-owned, written when a dashboard is opened",
+ "products.dashboards.backend.api.dashboard.DashboardSerializer.last_refresh": "TODO: server-owned, written by the dashboard refresh path",
+ "products.experiments.backend.presentation.serializers.ExperimentSerializer.end_date": "Client stops the experiment by setting this",
+ "products.experiments.backend.presentation.serializers.ExperimentSerializer.start_date": "Client launches the experiment by setting this",
+ "products.experiments.backend.presentation.serializers.ExperimentWriteSerializer.end_date": "Client stops the experiment by setting this",
+ "products.experiments.backend.presentation.serializers.ExperimentWriteSerializer.start_date": "Client launches the experiment by setting this",
+ "products.feature_flags.backend.api.scheduled_change.ScheduledChangeSerializer.end_date": "Client picks when a recurring schedule stops",
+ "products.feature_flags.backend.api.scheduled_change.ScheduledChangeSerializer.scheduled_at": "Client picks when the change is applied",
+ "products.logs.backend.presentation.views.alerts_api.LogsAlertConfigurationSerializer.snooze_until": "Client-set instant: update() pops snooze_until and assigns it to instance.snooze_until, with no relative-duration parsing on this path",
+ "products.product_tours.backend.api.product_tour.ProductTourSerializer.end_date": "Client schedules when the tour stops",
+ "products.product_tours.backend.api.product_tour.ProductTourSerializer.start_date": "Client schedules when the tour starts",
+ "products.product_tours.backend.api.product_tour.ProductTourSerializerCreateUpdateOnly.end_date": "Client schedules when the tour stops",
+ "products.product_tours.backend.api.product_tour.ProductTourSerializerCreateUpdateOnly.start_date": "Client schedules when the tour starts",
+ "products.reminders.backend.api.reminder.ReminderSerializer.end_date": "Client picks when a recurring reminder stops",
+ "products.reminders.backend.api.reminder.ReminderSerializer.scheduled_at": "Client picks when a one-off reminder fires",
+ "products.replay_vision.backend.api.observations.ReplayObservationSerializer.completed_at": "TODO: server-owned, written by the evaluation workflow",
+ "products.replay_vision.backend.api.observations.ReplayObservationSerializer.started_at": "TODO: server-owned, written by the evaluation workflow",
+ "products.replay_vision.backend.api.vision_alerts.VisionAlertConfigurationSerializer.snooze_until": "Client-set instant: update() pops snooze_until and assigns it to instance.snooze_until, with no relative-duration parsing on this path",
+ "products.surveys.backend.api.survey.SurveySerializer.current_iteration_start_date": "TODO: server-owned, the iteration task advances it",
+ "products.surveys.backend.api.survey.SurveySerializer.end_date": "Client stops the survey by setting this",
+ "products.surveys.backend.api.survey.SurveySerializer.response_sampling_start_date": "Client sets when response sampling starts",
+ "products.surveys.backend.api.survey.SurveySerializer.start_date": "Client launches the survey by setting this",
+ "products.surveys.backend.api.survey.SurveySerializerCreateUpdateOnly.current_iteration_start_date": "TODO: server-owned, the iteration task advances it",
+ "products.surveys.backend.api.survey.SurveySerializerCreateUpdateOnly.end_date": "Client stops the survey by setting this",
+ "products.surveys.backend.api.survey.SurveySerializerCreateUpdateOnly.response_sampling_start_date": "Client sets when response sampling starts",
+ "products.surveys.backend.api.survey.SurveySerializerCreateUpdateOnly.start_date": "Client launches the survey by setting this",
+ "products.surveys.backend.api.survey.SurveySerializerCreateUpdateOnlySchema.current_iteration_start_date": "TODO: server-owned, the iteration task advances it",
+ "products.surveys.backend.api.survey.SurveySerializerCreateUpdateOnlySchema.end_date": "Client stops the survey by setting this",
+ "products.surveys.backend.api.survey.SurveySerializerCreateUpdateOnlySchema.response_sampling_start_date": "Client sets when response sampling starts",
+ "products.surveys.backend.api.survey.SurveySerializerCreateUpdateOnlySchema.start_date": "Client launches the survey by setting this",
+ "products.workflows.backend.api.hog_flow.HogFlowScheduleSerializer.starts_at": "Client sets when the schedule starts",
}
# Views and serializers the guard cannot read, each with a reason. An entry hides part
@@ -273,21 +346,25 @@ def _is_super_delegation(expression: ast.expr) -> bool:
return False
-def _serializer_choices(view_class: type, action: str) -> tuple[set[type], list[str]]:
- """Every serializer a view could hand to this action, and what would not resolve.
+def _serializer_sources(view_class: type, action: str) -> tuple[dict[str, set[type]], list[str]]:
+ """Serializers this action could be handed, grouped by the mechanism that names each.
+
+ Grouped rather than merged because `test_every_discovery_path_finds_something`
+ asserts every mechanism still contributes, and a bucket that folds several together
+ stays non-empty while one of them is dead.
`get_serializer_class` is read statically rather than called, because calling it
returns the one serializer that matches a synthesized request: a view that branches
on a header or on request data would show the guard a single arm and hide the rest.
"""
- found: set[type] = set()
+ sources: dict[str, set[type]] = {name: set() for name in SERIALIZER_SOURCES}
unresolved: list[str] = []
declared = getattr(view_class, "serializer_class", None)
if _is_serializer(declared):
- found.add(declared)
+ sources["serializer_class attribute"].add(declared)
for attribute in vars(view_class).values():
if isinstance(attribute, dict):
- found.update(entry for entry in attribute.values() if _is_serializer(entry))
+ sources["serializer lookup table"].update(entry for entry in attribute.values() if _is_serializer(entry))
for klass in view_class.__mro__:
function = vars(klass).get("get_serializer_class")
if function is None or klass is GenericAPIView:
@@ -300,17 +377,23 @@ def _serializer_choices(view_class: type, action: str) -> tuple[set[type], list[
module = sys.modules.get(function.__module__)
module_scope = vars(module) if module is not None else {}
scope, locally_bound = _function_scope(tree, module_scope, view_class)
- found.update(locally_bound)
+ sources["get_serializer_class local"].update(locally_bound)
for returned, required in _returns_by_action(tree.body, view_class):
if required is not None and action not in required:
continue
resolved = _resolve(returned, scope, view_class)
serializer_classes = [entry for entry in resolved if _is_serializer(entry)]
if serializer_classes:
- found.update(serializer_classes)
+ sources["get_serializer_class return"].update(serializer_classes)
elif not resolved and not _is_super_delegation(returned):
unresolved.append(f"{klass.__qualname__}.get_serializer_class -> {ast.unparse(returned)[:60]}")
- return found, unresolved
+ return sources, unresolved
+
+
+def _serializer_choices(view_class: type, action: str) -> tuple[set[type], list[str]]:
+ """Every serializer a view could hand to this action, and what would not resolve."""
+ sources, unresolved = _serializer_sources(view_class, action)
+ return set().union(*sources.values()), unresolved
def _serializer_classes(declared: Any) -> set[type]:
@@ -375,28 +458,14 @@ def _write_exposed_serializers() -> tuple[set[type], dict[str, str]]:
return found, unresolved
-def _server_owned_reasons(model_field: models.DateTimeField) -> list[str]:
- """The evidence that the backend, not the client, owns this column."""
- return [
- name
- for name, present in (
- ("auto_now", model_field.auto_now),
- ("auto_now_add", model_field.auto_now_add),
- ("non-null default", model_field.has_default() and model_field.get_default() is not None),
- ("server-owned name", bool(SERVER_OWNED_NAME.match(model_field.name))),
- )
- if present
- ]
-
-
@functools.cache
def collect_violations() -> tuple[dict[str, str], dict[str, str]]:
- """Writable server-owned timestamps, and everything the guard could not read.
+ """Every writable timestamp a write route exposes, and what the guard could not read.
- The first mapping is keyed by `module.Serializer.field`, the second by the dotted
- name of the view or serializer that failed, and both values say why.
+ The first mapping is keyed by `module.Serializer.field` and holds the model behind
+ the column; the second is keyed by the view or serializer that failed, and says why.
"""
- violations: dict[str, str] = {}
+ writable: dict[str, str] = {}
serializer_classes, problems = _write_exposed_serializers()
for serializer_class in serializer_classes:
model = getattr(getattr(serializer_class, "Meta", None), "model", None)
@@ -410,28 +479,31 @@ def collect_violations() -> tuple[dict[str, str], dict[str, str]]:
for name, field in fields.items():
if not isinstance(field, serializers.DateTimeField) or field.read_only:
continue
+ key = f"{_dotted_name(serializer_class)}.{name}"
try:
model_field = model._meta.get_field(field.source or name)
except FieldDoesNotExist:
+ # A declared field backed by no column of its own: a write-only input, or
+ # a dotted source into a related model. It still takes a client value on a
+ # write route, so it needs a reason rather than a silent skip.
+ writable[key] = "no model column"
continue
if not isinstance(model_field, models.DateTimeField):
continue
- reasons = _server_owned_reasons(model_field)
- if reasons:
- violations[f"{_dotted_name(serializer_class)}.{name}"] = ", ".join(reasons)
- return violations, problems
+ writable[key] = model.__name__
+ return writable, problems
-def test_server_owned_timestamps_are_read_only() -> None:
- violations, _ = collect_violations()
- unexpected = sorted(f"{key} ({reasons})" for key, reasons in violations.items() if key not in ALLOWED_WRITABLE)
- assert not unexpected, (
- "These serializers let a client write a timestamp the backend owns. "
- "Add a generated field to read_only_fields on Meta; a field the serializer declares "
+def test_every_writable_timestamp_has_been_reviewed() -> None:
+ writable, _ = collect_violations()
+ unreviewed = sorted(f"{key} ({model})" for key, model in writable.items() if key not in REVIEWED_WRITABLE)
+ assert not unreviewed, (
+ "These write routes expose a timestamp nobody has classified. If the backend owns the "
+ "value, add a generated field to read_only_fields on Meta; a field the serializer declares "
"needs read_only=True on the declaration, because read_only_fields does not reach it. "
- "If a client is supposed to set it, add it to ALLOWED_WRITABLE in "
+ "If a client is supposed to set it, add it to REVIEWED_WRITABLE in "
"posthog/test/repo_invariants/test_serializer_timestamp_guard.py with a one-line reason:\n"
- + "\n".join(unexpected)
+ + "\n".join(unreviewed)
)
@@ -446,15 +518,15 @@ def test_every_write_route_can_be_checked() -> None:
)
-def test_allowlist_entries_still_match_a_violation() -> None:
- # Without this, the lists drift: an entry survives a field being made read-only,
+def test_reviewed_entries_still_match_a_writable_field() -> None:
+ # Without this, the registry drifts: an entry survives a field being made read-only,
# renamed, or dropped. It also catches the larger failure, a change that narrows
# discovery, because the fields that fall out of the sweep leave their entries
- # unmatched instead of passing as allowed.
- violations, problems = collect_violations()
- stale = sorted((set(ALLOWED_WRITABLE) - set(violations)) | (set(UNCHECKED) - set(problems)))
+ # unmatched instead of passing as reviewed.
+ writable, problems = collect_violations()
+ stale = sorted((set(REVIEWED_WRITABLE) - set(writable)) | (set(UNCHECKED) - set(problems)))
assert not stale, (
- "These ALLOWED_WRITABLE or UNCHECKED entries no longer match anything the guard found. "
+ "These REVIEWED_WRITABLE or UNCHECKED entries no longer match anything the guard found. "
"Delete them if the field is now read-only or gone. If the field still exists, discovery "
"stopped reaching it, which leaves its write route unchecked:\n" + "\n".join(stale)
)
@@ -469,6 +541,31 @@ def test_discovery_reaches_dynamically_selected_serializers() -> None:
)
+def test_every_discovery_path_finds_something() -> None:
+ # A mechanism that finds nothing on every route is indistinguishable from one with
+ # nothing to find, so a broken reader keeps passing the sweep above while silently
+ # contributing zero. Requiring each to be non-empty across the whole repository
+ # separates the two, and is what fails when a drf-spectacular upgrade moves the
+ # closure the request-body reader depends on.
+ found: dict[str, set[type]] = {name: set() for name in (*SERIALIZER_SOURCES, REQUEST_BODY_SOURCE)}
+ for _path, method, callback in EndpointEnumerator().get_api_endpoints():
+ view_class = getattr(callback, "cls", None)
+ if method not in WRITE_METHODS or view_class is None:
+ continue
+ actions = getattr(callback, "actions", None) or {}
+ action = actions.get(method.lower()) or method.lower()
+ sources, _ = _serializer_sources(view_class, action)
+ for name, serializer_classes in sources.items():
+ found[name] |= serializer_classes
+ found[REQUEST_BODY_SOURCE] |= _request_body_serializers(view_class, {method.lower(), action})
+ silent = sorted(name for name, serializer_classes in found.items() if not serializer_classes)
+ assert not silent, (
+ "These discovery paths found no serializer on any write route in the repository, so "
+ "they are contributing nothing to the sweep above. Either the code they read moved, or "
+ "they are broken:\n" + "\n".join(silent)
+ )
+
+
# Fixtures for the discovery tests below. They sit at module level because a view
# resolves a serializer name against the globals of the module that defines it, which
# is where every real serializer lives.
@@ -557,18 +654,3 @@ def test_request_body_declarations_normalize_to_classes() -> None:
assert _serializer_classes({"application/json": BodySerializer()}) == {BodySerializer}
inline = inline_serializer("InlineBody", fields={"name": serializers.CharField()})
assert _serializer_classes(inline) == {type(inline)}
-
-
-def test_nullable_column_without_a_default_is_owned_by_its_name() -> None:
- # FeatureFlag.last_called_at declares no auto_now, auto_now_add or default, so the
- # naming convention is the only thing that makes it server-owned.
- field: models.DateTimeField = models.DateTimeField(null=True, blank=True)
- field.name = "last_called_at"
- assert _server_owned_reasons(field) == ["server-owned name"]
-
-
-def test_bare_null_default_is_not_evidence_of_server_ownership() -> None:
- # A batch export's start_at is declared this way and a client is supposed to set it.
- field: models.DateTimeField = models.DateTimeField(null=True, default=None)
- field.name = "start_at"
- assert _server_owned_reasons(field) == []