: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
feat(cdp): record when terraform last read a hog function (#120619)
Jimmy Zhu9c42adf25a54
diff --git a/products/cdp/backend/api/hog_function.py b/products/cdp/backend/api/hog_function.pyindex 0fb4bc524bd6..8df10aeb1498 100644--- a/products/cdp/backend/api/hog_function.py+++ b/products/cdp/backend/api/hog_function.py@@ -28,7 +28,7 @@ from posthog.api.log_entries import LogEntryMixinfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import SearchMatchTypeSerializerMixin, UserBasicSerializerfrom posthog.api.utils import action, log_activity_from_viewset-from posthog.event_usage import AGENT_EVENT_SOURCES, get_event_source+from posthog.event_usage import AGENT_EVENT_SOURCES, EventSource, get_event_sourcefrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.impersonation import is_impersonatedfrom posthog.helpers.trigram_search import (@@ -1223,6 +1223,16 @@ class HogFunctionViewSet(span.set_attribute("hog_function.search.empty", results_len == 0)return response+ def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ instance = self.get_object()+ response = Response(self.get_serializer(instance).data)+ if get_event_source(request) == EventSource.TERRAFORM:+ try:+ instance.record_terraform_read()+ except Exception as e:+ capture_exception(e)+ return response+@staticmethod@tracer.start_as_current_span("HogFunctionViewSet._apply_search")def _apply_search(queryset: QuerySet, search: str) -> QuerySet:diff --git a/products/cdp/backend/api/test/test_hog_function.py b/products/cdp/backend/api/test/test_hog_function.pyindex fab12008b345..e68d3d566a74 100644--- a/products/cdp/backend/api/test/test_hog_function.py+++ b/products/cdp/backend/api/test/test_hog_function.py@@ -1,4 +1,5 @@import json+from datetime import UTC, datetimefrom typing import Any, Optionalimport time_machine@@ -513,6 +514,42 @@ class TestHogFunctionAPI(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):else:return actual_data+ def test_retrieve_records_terraform_read_at_most_once_a_day(self):+ function = HogFunction.objects.create(team=self.team, name="Insight alert", hog="return null")+ url = f"/api/projects/{self.team.id}/hog_functions/{function.id}/"+ terraform_ua = "posthog/terraform-provider; version: 1.0.22"++ def stored() -> tuple:+ return HogFunction.objects.values_list("last_terraform_read_at", "updated_at").get(pk=function.pk)++ with time_machine.travel("2026-01-01T00:00:00Z", tick=False):+ self.client.get(url)+ assert stored() == (None, function.updated_at)++ response = self.client.get(url, headers={"user-agent": terraform_ua})+ assert response.status_code == status.HTTP_200_OK+ assert "last_terraform_read_at" not in response.json()++ with time_machine.travel("2026-01-01T23:00:00Z", tick=False):+ self.client.get(url, headers={"user-agent": terraform_ua})+ assert stored() == (datetime(2026, 1, 1, tzinfo=UTC), function.updated_at)++ with time_machine.travel("2026-01-02T01:00:00Z", tick=False):+ self.client.get(url, headers={"user-agent": terraform_ua})+ assert stored() == (datetime(2026, 1, 2, 1, tzinfo=UTC), function.updated_at)++ def test_retrieve_succeeds_when_recording_terraform_read_fails(self):+ function = HogFunction.objects.create(team=self.team, name="Insight alert", hog="return null")++ with patch.object(HogFunction, "record_terraform_read", side_effect=Exception("db down")):+ response = self.client.get(+ f"/api/projects/{self.team.id}/hog_functions/{function.id}/",+ headers={"user-agent": "posthog/terraform-provider; version: 1.0.22"},+ )++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["id"] == str(function.id)+def _create_hidden_template(self) -> None:HogFunctionTemplate.objects.create(template_id="template-hidden-dest",diff --git a/products/cdp/backend/migrations/0006_hogfunction_last_terraform_read_at.py b/products/cdp/backend/migrations/0006_hogfunction_last_terraform_read_at.pynew file mode 100644index 000000000000..2e0c894c551d--- /dev/null+++ b/products/cdp/backend/migrations/0006_hogfunction_last_terraform_read_at.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.18 on 2026-10-20 18:57++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("cdp", "0005_repair_hogfunction_batch_export_id_index"),+ ]++ operations = [+ migrations.AddField(+ model_name="hogfunction",+ name="last_terraform_read_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ ]diff --git a/products/cdp/backend/migrations/max_migration.txt b/products/cdp/backend/migrations/max_migration.txtindex a51388e79621..a3f7d1bad896 100644--- a/products/cdp/backend/migrations/max_migration.txt+++ b/products/cdp/backend/migrations/max_migration.txt@@ -1 +1 @@-0005_repair_hogfunction_batch_export_id_index+0006_hogfunction_last_terraform_read_atdiff --git a/products/cdp/backend/models/hog_functions/hog_function.py b/products/cdp/backend/models/hog_functions/hog_function.pyindex 7df33e2267a5..e6e64249335d 100644--- a/products/cdp/backend/models/hog_functions/hog_function.py+++ b/products/cdp/backend/models/hog_functions/hog_function.py@@ -1,13 +1,15 @@import enumfrom collections.abc import Iterable+from datetime import timedeltafrom types import SimpleNamespacefrom typing import TYPE_CHECKING, Optionalfrom django.conf import settingsfrom django.db import models, transaction-from django.db.models import QuerySet+from django.db.models import Q, QuerySetfrom django.db.models.signals import post_delete, post_savefrom django.dispatch.dispatcher import receiver+from django.utils import timezoneimport structlogfrom prometheus_client import Counter@@ -172,6 +174,17 @@ class HogFunction(FileSystemSyncMixin, UUIDTModel):# ever touching the live values.draft_encrypted_inputs: EncryptedJSONStringField = EncryptedJSONStringField(null=True, blank=True)+ # Not serialized. A recent value means a Terraform state still manages this function.+ last_terraform_read_at = models.DateTimeField(null=True, blank=True)++ def record_terraform_read(self) -> None:+ # Every `terraform plan` reads every managed function, so write at most once a day. A queryset+ # update skips the save signals and leaves updated_at, which base_updated_at compares, alone.+ now = timezone.now()+ HogFunction.objects.filter(pk=self.pk).filter(+ Q(last_terraform_read_at__isnull=True) | Q(last_terraform_read_at__lt=now - timedelta(days=1))+ ).update(last_terraform_read_at=now)+@classmethoddef get_file_system_unfiled(cls, team: "Team", surface: str = DEFAULT_SURFACE) -> QuerySet["HogFunction"]:base_qs = HogFunction.objects.filter(team=team, deleted=False)