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.

feat(cdp): backfill the runtime stamp onto existing destinations (#106482)

Meikel Ratz860f0cad89f0
diff --git a/posthog/management/commands/refresh_hog_functions.py b/posthog/management/commands/refresh_hog_functions.py
index e48f5f783145..d9a49f9f3301 100644
--- a/posthog/management/commands/refresh_hog_functions.py
+++ b/posthog/management/commands/refresh_hog_functions.py
@@ -1,17 +1,163 @@
+import json
import time
+from typing import Any
from django.core.management.base import BaseCommand
from django.core.paginator import Paginator
import structlog
+from posthog.cdp.filters import DATA_WAREHOUSE_SOURCES, RUNTIME_CONTRACT, compile_filters_bytecode
+from posthog.cdp.validation import generate_template_bytecode
+from posthog.dataclasses import frozen
+
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
logger = structlog.get_logger(__name__)
+@frozen
+class Refresh:
+ stamped: int
+ skipped: int
+
+
+def _compilable_value(value: Any, item_type: str | None) -> Any:
+ """The part of a stored value the save path compiles.
+
+ An email input carries the visual editor's design beside the body, and the save path leaves it
+ out. Compiling it here would fail on designs the template parser refuses, and the input would
+ lose its stamp for a reason the save path never had.
+ """
+ if item_type in ("email", "native_email") and isinstance(value, dict):
+ return {key: value[key] for key in value if key != "design"}
+ return value
+
+
+def _item_types(inputs_schema: object) -> dict[str, str | None]:
+ if not isinstance(inputs_schema, list):
+ return {}
+ return {
+ entry["key"]: entry.get("type")
+ for entry in inputs_schema
+ if isinstance(entry, dict) and isinstance(entry.get("key"), str)
+ }
+
+
+def _mappings(hog_function: HogFunction) -> list[dict[str, Any]]:
+ return [mapping for mapping in (hog_function.mappings or []) if isinstance(mapping, dict)]
+
+
+def _refresh_store(
+ hog_function: HogFunction,
+ store: dict[str, Any],
+ item_types: dict[str, str | None],
+ is_dwh_source: bool,
+ mapping_index: int | None,
+) -> Refresh:
+ stamped = 0
+ skipped = 0
+ for key, item in store.items():
+ if not isinstance(item, dict) or item.get("templating", "hog") != "hog" or "bytecode" not in item:
+ continue
+ try:
+ bytecode = generate_template_bytecode(
+ _compilable_value(item.get("value"), item_types.get(key)),
+ set(),
+ function_type=hog_function.type,
+ is_dwh_source=is_dwh_source,
+ validate_globals=True,
+ )
+ except Exception as e:
+ skipped += 1
+ logger.warning(
+ "hog_function_input_template_no_longer_compiles",
+ hog_function_id=str(hog_function.id),
+ team_id=hog_function.team_id,
+ mapping_index=mapping_index,
+ input_key=key,
+ error=str(e),
+ )
+ continue
+ # The compiler returns opcode enums; the stored form is plain JSON, like a save writes it.
+ item["bytecode"] = json.loads(json.dumps(bytecode))
+ item["bytecode_contract"] = RUNTIME_CONTRACT
+ stamped += 1
+ return Refresh(stamped=stamped, skipped=skipped)
+
+
+def refresh_input_templates(hog_function: HogFunction) -> Refresh:
+ """
+ Recompile every hog input template from its stored value, the way a save through the API does,
+ and stamp it with the runtime it was checked against. The model's save only recompiles filters.
+ This includes the inputs of each mapping, which the runtime merges into the invocation.
+
+ An input the current guard refuses keeps its stored bytecode and gets no stamp: it fails at
+ run time exactly as before, and an unstamped failure is classified as the owner's to fix.
+ """
+ is_dwh_source = (hog_function.filters or {}).get("source") in DATA_WAREHOUSE_SOURCES
+ item_types = _item_types(hog_function.inputs_schema)
+ results: list[Refresh] = []
+ for store_name in ("inputs", "encrypted_inputs"):
+ store: dict[str, Any] = getattr(hog_function, store_name) or {}
+ result = _refresh_store(hog_function, store, item_types, is_dwh_source, mapping_index=None)
+ if result.stamped:
+ setattr(hog_function, store_name, store)
+ results.append(result)
+ for index, mapping in enumerate(_mappings(hog_function)):
+ if isinstance(mapping.get("inputs"), dict):
+ results.append(
+ _refresh_store(
+ hog_function,
+ mapping["inputs"],
+ _item_types(mapping.get("inputs_schema")),
+ is_dwh_source,
+ mapping_index=index,
+ )
+ )
+ return Refresh(stamped=sum(r.stamped for r in results), skipped=sum(r.skipped for r in results))
+
+
+def refresh_mapping_filters(hog_function: HogFunction) -> Refresh:
+ """
+ Recompile the filters of each mapping, the way a save through the API does. The model's save only
+ recompiles the top-level filters, and on a mapped destination the event filters live in the mappings.
+
+ Filters that no longer compile keep their stored bytecode and get no stamp, the same as inputs.
+ """
+ stamped = 0
+ skipped = 0
+ for index, mapping in enumerate(_mappings(hog_function)):
+ filters = mapping.get("filters")
+ if not isinstance(filters, dict) or "bytecode" not in filters:
+ continue
+ # compile_filters_bytecode nulls the bytecode on error, so it gets a copy.
+ compiled = compile_filters_bytecode({**filters}, hog_function.team)
+ if compiled.get("bytecode_error"):
+ skipped += 1
+ logger.warning(
+ "hog_function_mapping_filters_no_longer_compile",
+ hog_function_id=str(hog_function.id),
+ team_id=hog_function.team_id,
+ mapping_index=index,
+ error=compiled["bytecode_error"],
+ )
+ continue
+ mapping["filters"] = compiled
+ stamped += 1
+ return Refresh(stamped=stamped, skipped=skipped)
+
+
+def filters_error(hog_function: HogFunction) -> str | None:
+ """Why the top-level filters do not compile, without writing anything. None when they do."""
+ return compile_filters_bytecode({**(hog_function.filters or {})}, hog_function.team).get("bytecode_error")
+
+
class Command(BaseCommand):
- help = "Refresh HogFunctions (both enabled and disabled) by re-saving them to trigger filter recompilation"
+ help = (
+ "Refresh HogFunctions (both enabled and disabled) by re-saving them, which recompiles their "
+ "filters, their hog input templates and their mappings, and stamps them with the current runtime contract"
+ )
def add_arguments(self, parser):
parser.add_argument(
@@ -22,20 +168,39 @@ class Command(BaseCommand):
type=str,
help="Specific HogFunction ID to refresh (if provided, only this function is processed)",
)
+ parser.add_argument(
+ "--type",
+ action="append",
+ choices=["destination", "internal_destination"],
+ help="Function type to refresh. Repeatable. Defaults to destination.",
+ )
+ parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Recompile and report what would be stamped or skipped, without saving anything.",
+ )
def handle(self, *args, **options):
start_time = time.time()
total_processed = 0
total_updated = 0
error_count = 0
+ inputs_stamped = 0
+ inputs_skipped = 0
+ filters_stamped = 0
+ filters_skipped = 0
+ mapping_filters_stamped = 0
+ mapping_filters_skipped = 0
team_id = options.get("team_id")
hog_function_id = options.get("hog_function_id")
+ types = options.get("type") or ["destination"]
+ dry_run: bool = options.get("dry_run", False)
page_size = 1000
- self.stdout.write("Starting HogFunction refresh...")
+ self.stdout.write("Starting HogFunction refresh..." + (" (dry run, nothing is saved)" if dry_run else ""))
- queryset = HogFunction.objects.filter(deleted=False, type__in=["destination"]).select_related("team")
+ queryset = HogFunction.objects.filter(deleted=False, type__in=types).select_related("team")
if hog_function_id:
queryset = queryset.filter(id=hog_function_id)
@@ -65,8 +230,38 @@ class Command(BaseCommand):
for hog_function in page.object_list:
try:
total_processed += 1
- hog_function.save()
- total_updated += 1
+ refreshed = refresh_input_templates(hog_function)
+ refreshed_mapping_filters = refresh_mapping_filters(hog_function)
+ if dry_run:
+ error = filters_error(hog_function)
+ else:
+ hog_function.save()
+ total_updated += 1
+ # The save leaves the error beside filters that no longer compile, and keeps their bytecode.
+ error = (hog_function.filters or {}).get("bytecode_error")
+ # Counted after the save, so the summary reports what reached the database.
+ if error:
+ filters_skipped += 1
+ # A destination whose filters do not compile fails on every event, so the run
+ # names it rather than only counting it. Turning it off is the owner's call.
+ self.stdout.write(
+ self.style.WARNING(
+ f"Filters do not compile: team {hog_function.team_id}, "
+ f"function {hog_function.id} ({hog_function.name!r}): {error!r}"
+ )
+ )
+ logger.warning(
+ "hog_function_filters_no_longer_compile",
+ hog_function_id=str(hog_function.id),
+ team_id=hog_function.team_id,
+ error=error,
+ )
+ else:
+ filters_stamped += 1
+ inputs_stamped += refreshed.stamped
+ inputs_skipped += refreshed.skipped
+ mapping_filters_stamped += refreshed_mapping_filters.stamped
+ mapping_filters_skipped += refreshed_mapping_filters.skipped
except Exception as e:
error_count += 1
logger.error(
@@ -80,9 +275,15 @@ class Command(BaseCommand):
duration = time.time() - start_time
self.stdout.write(
self.style.SUCCESS(
- f"Refresh completed in {duration:.2f}s. "
+ f"{'Dry run' if dry_run else 'Refresh'} completed in {duration:.2f}s. "
f"Processed: {total_processed}, "
f"Updated: {total_updated}, "
+ f"Filters stamped: {filters_stamped}, "
+ f"Filters skipped: {filters_skipped}, "
+ f"Inputs stamped: {inputs_stamped}, "
+ f"Inputs skipped: {inputs_skipped}, "
+ f"Mapping filters stamped: {mapping_filters_stamped}, "
+ f"Mapping filters skipped: {mapping_filters_skipped}, "
f"Errors: {error_count}"
)
)
diff --git a/posthog/management/commands/test/test_refresh_hog_functions.py b/posthog/management/commands/test/test_refresh_hog_functions.py
index 9d7f070c99a6..913d0c59e121 100644
--- a/posthog/management/commands/test/test_refresh_hog_functions.py
+++ b/posthog/management/commands/test/test_refresh_hog_functions.py
@@ -1,3 +1,4 @@
+import json
from io import StringIO
from posthog.test.base import BaseTest
@@ -5,6 +6,10 @@ from unittest.mock import patch
from django.core.management import call_command
+from parameterized import parameterized
+
+from posthog.cdp.filters import RUNTIME_CONTRACT
+from posthog.cdp.validation import generate_template_bytecode
from posthog.models import Team
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
@@ -139,3 +144,213 @@ class TestRefreshHogFunctions(BaseTest):
output = out.getvalue()
self.assertIn("Found 0 HogFunctions to process", output)
self.assertIn("No HogFunctions found matching criteria", output)
+
+ def _unstamped(
+ self,
+ inputs: dict,
+ inputs_schema: list,
+ encrypted_inputs: dict | None = None,
+ mappings: list | None = None,
+ ) -> HogFunction:
+ with patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers"):
+ fn = HogFunction.objects.create(
+ team=self.team,
+ name="Saved before stamping",
+ type="destination",
+ hog="return event",
+ enabled=True,
+ inputs_schema=inputs_schema,
+ inputs=inputs,
+ encrypted_inputs=encrypted_inputs,
+ filters={"events": [{"id": "$pageview", "type": "events"}]},
+ mappings=mappings,
+ )
+ # The model save stamps the filters. Strip it so the fixture is honestly pre-stamping.
+ filters = {key: value for key, value in (fn.filters or {}).items() if key != "bytecode_contract"}
+ HogFunction.objects.filter(pk=fn.pk).update(filters=filters)
+ return HogFunction.objects.get(pk=fn.pk)
+
+ @patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers")
+ def test_stamps_filters_and_every_hog_input_of_an_unstamped_destination(self, mock_reload):
+ template = json.loads(json.dumps(generate_template_bytecode("{event.uuid}", set())))
+ fn = self._unstamped(
+ inputs={
+ "url": {"value": "{event.uuid}", "bytecode": template},
+ "body": {"value": {"id": "{event.uuid}"}, "bytecode": {"id": template}},
+ "note": {"value": "{{ event.uuid }}", "templating": "liquid"},
+ "method": {"value": "POST"},
+ "email": {
+ "value": {"subject": "{event.uuid}", "design": {"html": "{nosuch.thing}"}},
+ "bytecode": {"subject": template},
+ },
+ },
+ inputs_schema=[
+ {"key": "url", "type": "string"},
+ {"key": "body", "type": "json"},
+ {"key": "note", "type": "string"},
+ {"key": "method", "type": "string"},
+ {"key": "email", "type": "email"},
+ {"key": "token", "type": "string", "secret": True},
+ ],
+ encrypted_inputs={"token": {"value": "{event.uuid}", "bytecode": template}},
+ )
+ assert "bytecode_contract" not in (fn.filters or {})
+ assert "bytecode_contract" not in (fn.inputs or {})["url"]
+
+ out = StringIO()
+ call_command("refresh_hog_functions", hog_function_id=str(fn.id), stdout=out)
+
+ fn.refresh_from_db()
+ filters = fn.filters or {}
+ inputs = fn.inputs or {}
+ encrypted_inputs = fn.encrypted_inputs or {}
+ assert filters["bytecode_contract"] == RUNTIME_CONTRACT
+ assert inputs["url"] == {
+ "value": "{event.uuid}",
+ "bytecode": template,
+ "bytecode_contract": RUNTIME_CONTRACT,
+ }
+ assert inputs["body"]["bytecode_contract"] == RUNTIME_CONTRACT
+ assert inputs["body"]["bytecode"] == {"id": template}
+ # Secret templates are compiled the same way, and the value never leaves the process.
+ assert encrypted_inputs["token"]["bytecode_contract"] == RUNTIME_CONTRACT
+ # Liquid has no bytecode and a plain value compiles to nothing that could drift.
+ assert inputs["note"] == {"value": "{{ event.uuid }}", "templating": "liquid"}
+ assert inputs["method"] == {"value": "POST"}
+ # The visual editor's design is not compiled, so a design the parser refuses costs no stamp.
+ assert inputs["email"]["bytecode_contract"] == RUNTIME_CONTRACT
+ assert inputs["email"]["value"]["design"] == {"html": "{nosuch.thing}"}
+ assert "Inputs stamped: 4" in out.getvalue()
+ assert mock_reload.call_count == 1
+
+ @patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers")
+ def test_keeps_every_secret_in_the_encrypted_store_and_out_of_the_plain_one(self, mock_reload):
+ # The run rewrites both input stores and then saves, which re-splits them by schema. A secret
+ # has to come back with its value intact and must never land in the plain column, whether it
+ # holds a literal credential or a template the run recompiles.
+ template = json.loads(json.dumps(generate_template_bytecode("{event.uuid}", set())))
+ fn = self._unstamped(
+ inputs={"url": {"value": "{event.uuid}", "bytecode": template}},
+ inputs_schema=[
+ {"key": "url", "type": "string"},
+ {"key": "api_key", "type": "string", "secret": True},
+ {"key": "token", "type": "string", "secret": True},
+ ],
+ encrypted_inputs={
+ "api_key": {"value": "not-a-real-key", "order": 1},
+ "token": {"value": "{event.uuid}", "bytecode": template},
+ },
+ )
+
+ out = StringIO()
+ call_command("refresh_hog_functions", hog_function_id=str(fn.id), stdout=out)
+
+ fn.refresh_from_db()
+ inputs = fn.inputs or {}
+ encrypted_inputs = fn.encrypted_inputs or {}
+ # A literal credential has no bytecode to recompile, so it comes back untouched.
+ assert encrypted_inputs["api_key"] == {"value": "not-a-real-key", "order": 1}
+ # A templated secret is recompiled and stamped, and keeps the value it was written with.
+ assert encrypted_inputs["token"]["value"] == "{event.uuid}"
+ assert encrypted_inputs["token"]["bytecode_contract"] == RUNTIME_CONTRACT
+ assert "api_key" not in inputs
+ assert "token" not in inputs
+
+ @patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers")
+ def test_keeps_an_input_that_no_longer_compiles_and_leaves_it_unstamped(self, mock_reload):
+ # A template that today's guard refuses keeps running on its old bytecode. It must not get a
+ # stamp, or the runtime would read its failures as our change rather than the owner's.
+ stale = ["_H", 1, 32, "thing", 32, "nosuch", 1, 2]
+ good = json.loads(json.dumps(generate_template_bytecode("{event.uuid}", set())))
+ fn = self._unstamped(
+ inputs={
+ "url": {"value": "{event.uuid}", "bytecode": good},
+ "bad": {"value": "{nosuch.thing}", "bytecode": stale},
+ },
+ inputs_schema=[{"key": "url", "type": "string"}, {"key": "bad", "type": "string"}],
+ )
+
+ out = StringIO()
+ call_command("refresh_hog_functions", hog_function_id=str(fn.id), stdout=out)
+
+ fn.refresh_from_db()
+ inputs = fn.inputs or {}
+ assert inputs["url"]["bytecode_contract"] == RUNTIME_CONTRACT
+ assert inputs["bad"] == {"value": "{nosuch.thing}", "bytecode": stale}
+ assert (fn.filters or {})["bytecode_contract"] == RUNTIME_CONTRACT
+ assert "Inputs stamped: 1" in out.getvalue()
+ assert "Inputs skipped: 1" in out.getvalue()
+
+ @parameterized.expand([("dry_run", True), ("real_run", False)])
+ @patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers")
+ def test_reports_filters_that_no_longer_compile(self, _name, dry_run, mock_reload):
+ stale = ["_H", 1, 29]
+ refused_filters = {"properties": [{"type": "hogql", "key": "nosuch.thing"}], "bytecode": stale}
+ fn = self._unstamped(inputs={}, inputs_schema=[])
+ HogFunction.objects.filter(pk=fn.pk).update(filters=refused_filters)
+
+ out = StringIO()
+ call_command("refresh_hog_functions", hog_function_id=str(fn.id), dry_run=dry_run, stdout=out)
+
+ fn.refresh_from_db()
+ filters = fn.filters or {}
+ assert filters["bytecode"] == stale
+ assert "bytecode_contract" not in filters
+ assert "Filters stamped: 0" in out.getvalue()
+ assert "Filters skipped: 1" in out.getvalue()
+ # A count alone cannot be acted on: the run has to say which function to turn off.
+ assert f"function {fn.id}" in out.getvalue()
+ assert f"team {fn.team_id}" in out.getvalue()
+
+ @patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers")
+ def test_stamps_the_inputs_and_filters_of_each_mapping(self, mock_reload):
+ # On a mapped destination the runtime filters and builds inputs per mapping, and reads the
+ # stamps there. A mapping filter the guard now refuses keeps its stored bytecode unstamped.
+ template = json.loads(json.dumps(generate_template_bytecode("{event.uuid}", set())))
+ stale = ["_H", 1, 29]
+ refused_filters = {"properties": [{"type": "hogql", "key": "nosuch.thing"}], "bytecode": stale}
+ fn = self._unstamped(
+ inputs={},
+ inputs_schema=[],
+ mappings=[
+ {
+ "name": "Pageviews",
+ "inputs_schema": [{"key": "url", "type": "string"}],
+ "inputs": {"url": {"value": "{event.uuid}", "bytecode": template}},
+ "filters": {"events": [{"id": "$pageview", "type": "events"}], "bytecode": stale},
+ },
+ {"name": "Refused", "filters": refused_filters},
+ ],
+ )
+
+ out = StringIO()
+ call_command("refresh_hog_functions", hog_function_id=str(fn.id), stdout=out)
+
+ fn.refresh_from_db()
+ pageviews, refused = fn.mappings or []
+ assert pageviews["inputs"]["url"]["bytecode_contract"] == RUNTIME_CONTRACT
+ assert pageviews["filters"]["bytecode_contract"] == RUNTIME_CONTRACT
+ assert pageviews["filters"]["bytecode"] != stale
+ assert refused["filters"] == refused_filters
+ assert "Inputs stamped: 1" in out.getvalue()
+ assert "Mapping filters stamped: 1" in out.getvalue()
+ assert "Mapping filters skipped: 1" in out.getvalue()
+
+ @patch("products.cdp.backend.models.hog_functions.hog_function.reload_hog_functions_on_workers")
+ def test_dry_run_reports_and_writes_nothing(self, mock_reload):
+ template = json.loads(json.dumps(generate_template_bytecode("{event.uuid}", set())))
+ fn = self._unstamped(
+ inputs={"url": {"value": "{event.uuid}", "bytecode": template}},
+ inputs_schema=[{"key": "url", "type": "string"}],
+ )
+
+ out = StringIO()
+ call_command("refresh_hog_functions", hog_function_id=str(fn.id), dry_run=True, stdout=out)
+
+ fn.refresh_from_db()
+ assert "bytecode_contract" not in (fn.filters or {})
+ assert "bytecode_contract" not in (fn.inputs or {})["url"]
+ assert mock_reload.call_count == 0
+ assert "Filters stamped: 1" in out.getvalue()
+ assert "Inputs stamped: 1" in out.getvalue()
+ assert "Dry run" in out.getvalue()