: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): draft and revision storage for hog functions (#75974)
Harley Alexander597218aa1d48
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yamlindex b3ad0227beae..474ed116f0c5 100644--- a/.semgrep/rules/security/idor-team-scoped-models.yaml+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml@@ -179,6 +179,7 @@ rules:|HogFlowSchedule|HogFlowTemplate|HogFunction+ |HogFunctionRevision|Hook|Insight|InsightVariable@@ -513,6 +514,7 @@ rules:|HogFlowSchedule|HogFlowTemplate|HogFunction+ |HogFunctionRevision|Hook|Insight|InsightVariablediff --git a/products/cdp/backend/migrations/0003_hog_function_drafts.py b/products/cdp/backend/migrations/0003_hog_function_drafts.pynew file mode 100644index 000000000000..2bd67501a9e0--- /dev/null+++ b/products/cdp/backend/migrations/0003_hog_function_drafts.py@@ -0,0 +1,96 @@+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models++import posthog.models.utils+import posthog.helpers.encrypted_fields+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1266_comment_convo_content_trgm"),+ ("cdp", "0002_alter_hogfunction_batch_export"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.AddField(+ model_name="hogfunction",+ name="draft",+ field=models.JSONField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="hogfunction",+ name="draft_updated_at",+ field=models.DateTimeField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="hogfunction",+ name="draft_encrypted_inputs",+ field=posthog.helpers.encrypted_fields.EncryptedJSONStringField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="hogfunction",+ name="version",+ field=models.IntegerField(db_default=1, default=1),+ ),+ migrations.CreateModel(+ name="HogFunctionRevision",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "version",+ models.IntegerField(help_text="Function version this snapshot was published as."),+ ),+ (+ "content",+ models.JSONField(+ help_text="Full snapshot of the function's config fields (hog, inputs_schema, inputs, filters, mappings, masking) at this version."+ ),+ ),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ (+ "created_by",+ models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ (+ "hog_function",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ related_name="revisions",+ to="cdp.hogfunction",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ db_constraint=False,+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ ],+ options={+ "constraints": [+ models.UniqueConstraint(+ fields=("hog_function", "version"),+ name="unique_hogfunction_revision_version",+ )+ ],+ },+ ),+ ]diff --git a/products/cdp/backend/migrations/max_migration.txt b/products/cdp/backend/migrations/max_migration.txtindex 494f158ad14b..a6a9e9c6c8b9 100644--- a/products/cdp/backend/migrations/max_migration.txt+++ b/products/cdp/backend/migrations/max_migration.txt@@ -1 +1 @@-0002_alter_hogfunction_batch_export+0003_hog_function_draftsdiff --git a/products/cdp/backend/models/__init__.py b/products/cdp/backend/models/__init__.pyindex 598267ac18fa..d3364f212c47 100644--- a/products/cdp/backend/models/__init__.py+++ b/products/cdp/backend/models/__init__.py@@ -1,5 +1,5 @@from .hog_function_template import HogFunctionTemplate-from .hog_functions import HogFunction+from .hog_functions import HogFunction, HogFunctionRevisionfrom .hog_functions.hog_function import HogFunctionStatefrom .hook import Hookfrom .plugin import (@@ -15,6 +15,7 @@ from .plugin import (__all__ = ["HogFunction",+ "HogFunctionRevision","HogFunctionState","HogFunctionTemplate","Hook",diff --git a/products/cdp/backend/models/hog_functions/__init__.py b/products/cdp/backend/models/hog_functions/__init__.pyindex 6363b39598ef..b9bac5b34d5f 100644--- a/products/cdp/backend/models/hog_functions/__init__.py+++ b/products/cdp/backend/models/hog_functions/__init__.py@@ -1,3 +1,4 @@from .hog_function import HogFunction, HogFunctionState+from .hog_function_revision import HogFunctionRevision-__all__ = ["HogFunction", "HogFunctionState"]+__all__ = ["HogFunction", "HogFunctionRevision", "HogFunctionState"]diff --git a/products/cdp/backend/models/hog_functions/hog_function.py b/products/cdp/backend/models/hog_functions/hog_function.pyindex 4f5003389fdc..a6f24ee32e9e 100644--- a/products/cdp/backend/models/hog_functions/hog_function.py+++ b/products/cdp/backend/models/hog_functions/hog_function.py@@ -1,4 +1,5 @@import enum+from collections.abc import Iterablefrom types import SimpleNamespacefrom typing import TYPE_CHECKING, Optional@@ -87,6 +88,14 @@ TYPES_THAT_CAN_RERUN = (HogFunctionType.INTERNAL_DESTINATION,)+# A save touching only these columns stages config for review — it never changes what workers+# execute, so it must skip both the worker reload and the live-column normalization in save().+DRAFT_ONLY_UPDATE_FIELDS = frozenset({"draft", "draft_updated_at", "draft_encrypted_inputs"})+++def _is_draft_only_save(update_fields: Optional[Iterable[str]]) -> bool:+ return update_fields is not None and set(update_fields) <= DRAFT_ONLY_UPDATE_FIELDS+class HogFunction(FileSystemSyncMixin, UUIDTModel):class Meta:@@ -141,6 +150,18 @@ class HogFunction(FileSystemSyncMixin, UUIDTModel):blank=True,)+ # db_default alongside default: the plugin-server test fixtures INSERT into this table with raw+ # SQL that doesn't list this column, and the test-schema builder skips migrations entirely.+ version = models.IntegerField(default=1, db_default=1)++ # Draft storage for enabled functions: stores pending edits separately from the live config.+ draft = models.JSONField(null=True, blank=True)+ draft_updated_at = models.DateTimeField(null=True, blank=True)+ # Pending secret inputs for the draft, same shape as `encrypted_inputs`. Kept separate so a+ # draft's secrets are promoted to `encrypted_inputs` on publish and dropped on discard, without+ # ever touching the live values.+ draft_encrypted_inputs: EncryptedJSONStringField = EncryptedJSONStringField(null=True, blank=True)+@classmethoddef get_file_system_unfiled(cls, team: "Team", surface: str = DEFAULT_SURFACE) -> QuerySet["HogFunction"]:base_qs = HogFunction.objects.filter(team=team, deleted=False)@@ -260,6 +281,11 @@ class HogFunction(FileSystemSyncMixin, UUIDTModel):def save(self, *args, **kwargs):from posthog.cdp.filters import compile_filters_bytecode+ if _is_draft_only_save(kwargs.get("update_fields")):+ # Nothing here writes a live column, so re-splitting live secrets and recompiling filter+ # bytecode (a DB-hitting compile) would be pure waste.+ return super().save(*args, **kwargs)+self.move_secret_inputs()if self.type not in TYPES_WITH_TRANSPILED_FILTERS:self.filters = compile_filters_bytecode(self.filters, self.team)@@ -272,6 +298,11 @@ class HogFunction(FileSystemSyncMixin, UUIDTModel):@receiver(post_save, sender=HogFunction)def hog_function_saved(sender, instance: HogFunction, created, **kwargs):+ # A draft-only write stages config for a human to review; pushing it to workers would defeat+ # the point of staging it.+ if _is_draft_only_save(kwargs.get("update_fields")):+ return+if instance.type is None or instance.type in TYPES_THAT_RELOAD_PLUGIN_SERVER:reload_hog_functions_on_workers(team_id=instance.team_id, hog_function_ids=[str(instance.id)])@@ -315,6 +346,9 @@ def cohort_saved(sender, instance, **kwargs):@mutable_receiver([post_save, post_delete], sender=HogFunction)def team_inject_web_apps_changd(sender, instance, created=None, **kwargs):+ # A draft-only write can't change which site apps /decide serves.+ if _is_draft_only_save(kwargs.get("update_fields")):+ returntry:team = instance.teamexcept Team.DoesNotExist:diff --git a/products/cdp/backend/models/hog_functions/hog_function_revision.py b/products/cdp/backend/models/hog_functions/hog_function_revision.pynew file mode 100644index 000000000000..9b4e2d05d4ab--- /dev/null+++ b/products/cdp/backend/models/hog_functions/hog_function_revision.py@@ -0,0 +1,42 @@+from typing import Any++from django.db import models++from posthog.models.scoping.root_mixin import TeamScopedRootMixin+from posthog.models.utils import UUIDModel+++class HogFunctionRevision(TeamScopedRootMixin, UUIDModel):+ """Append-only snapshot of a function's live config, written whenever that config changes.+ Rollback copies a snapshot back into the draft; workers never read this table."""++ class Meta:+ constraints = [+ models.UniqueConstraint(fields=["hog_function", "version"], name="unique_hogfunction_revision_version"),+ ]++ # db_constraint=False on team/created_by: a real FK constraint to a hot table (posthog_team,+ # posthog_user) takes a parent-table lock on creation; enforcement stays app-level.+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)+ hog_function = models.ForeignKey("cdp.HogFunction", on_delete=models.CASCADE, related_name="revisions")+ version = models.IntegerField(help_text="Function version this snapshot was published as.")+ content = models.JSONField(+ help_text="Full snapshot of the function's config fields (hog, inputs_schema, inputs, filters, mappings, masking) at this version."+ )+ created_by = models.ForeignKey(+ "posthog.User", on_delete=models.SET_NULL, null=True, blank=True, db_constraint=False+ )+ created_at = models.DateTimeField(auto_now_add=True)++ def save(self, *args: Any, **kwargs: Any) -> None:+ # Fail loudly, not with an AttributeError, when the required FK was never set.+ if not self.hog_function_id:+ raise ValueError("hog_function must be set before saving a HogFunctionRevision")+ # A revision's tenant scope always mirrors its function's. A mismatched (team, hog_function)+ # pair would leak the revision into the wrong team's history — fail-closed reads filter on+ # this row's team_id, not the function's.+ self.team_id = self.hog_function.team_id+ super().save(*args, **kwargs)++ def __str__(self) -> str:+ return f"HogFunctionRevision {self.hog_function_id} v{self.version}"