: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(batch-exports): add user metadata to temporal workflows (#70053)
Rossebb1cca3bb54
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex 5eaf54a136ef..fcd0039502b7 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -36,6 +36,10 @@ TEMPORAL_COMBINED_METRICS_SERVER_ENABLED: bool = get_from_env("TEMPORAL_COMBINED_METRICS_SERVER_ENABLED", True, type_cast=str_to_bool)+# PostHog project where Temporal worker logs are ingested, used to build logs links+# in Temporal UI workflow details. Set to 0 to disable the links.+TEMPORAL_LOGS_PROJECT_ID: int = get_from_env("TEMPORAL_LOGS_PROJECT_ID", 1, type_cast=int)+TEMPORAL_LOG_LEVEL: str = os.getenv("TEMPORAL_LOG_LEVEL", "INFO")TEMPORAL_OTEL_PLUGIN_ENABLED: bool = get_from_env("TEMPORAL_OTEL_PLUGIN_ENABLED", False, type_cast=str_to_bool)TEMPORAL_OTEL_LIBRARIES_TO_INSTRUMENT: list[str] = get_list(os.getenv("TEMPORAL_OTEL_LIBRARIES_TO_INSTRUMENT", ""))diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.pyindex e67422807e16..ee7e6d132be4 100644--- a/products/batch_exports/backend/service.py+++ b/products/batch_exports/backend/service.py@@ -46,6 +46,7 @@ from products.batch_exports.backend.models.batch_export import (BatchExportOnDemand,BatchExportRun,)+from products.batch_exports.backend.temporal.workflow_metadata import build_static_summarylogger = structlog.get_logger(__name__)@@ -904,13 +905,25 @@ def backfill_export(workflow_id = f"{inputs.batch_export_id}-Backfill-{start_at_utc_str}-{end_at_utc_str}"- workflow_id = start_backfill_batch_export_workflow(temporal, workflow_id, inputs=inputs)+ workflow_id = start_backfill_batch_export_workflow(+ temporal,+ workflow_id,+ inputs=inputs,+ destination_type=batch_export.destination.type,+ model=batch_export.model or "events",+ interval=batch_export.interval,+ )return workflow_id@async_to_syncasync def start_backfill_batch_export_workflow(- temporal: Client, workflow_id: str, inputs: BackfillBatchExportInputs+ temporal: Client,+ workflow_id: str,+ inputs: BackfillBatchExportInputs,+ destination_type: str,+ model: str,+ interval: str,) -> str:"""Async call to start a BackfillBatchExportWorkflow."""await temporal.start_workflow(@@ -918,6 +931,7 @@ async def start_backfill_batch_export_workflow(inputs,id=workflow_id,task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,+ static_summary=build_static_summary(destination_type, model, interval, is_backfill=True),)return workflow_id@@ -1189,6 +1203,9 @@ def sync_batch_export(batch_export: BatchExport, created: bool):maximum_attempts=2,non_retryable_error_types=["ActivityError", "ApplicationError", "CancelledError"],),+ static_summary=build_static_summary(+ batch_export.destination.type, batch_export.model or "events", batch_export.interval+ ),),spec=_get_schedule_spec(batch_export),state=state,diff --git a/products/batch_exports/backend/temporal/backfill_batch_export.py b/products/batch_exports/backend/temporal/backfill_batch_export.pyindex 28aee2c573f8..5adfca026e6c 100644--- a/products/batch_exports/backend/temporal/backfill_batch_export.py+++ b/products/batch_exports/backend/temporal/backfill_batch_export.py@@ -45,6 +45,11 @@ from products.batch_exports.backend.service import (from products.batch_exports.backend.temporal.metrics import log_query_durationfrom products.batch_exports.backend.temporal.record_batch_model import SessionsRecordBatchModelfrom products.batch_exports.backend.temporal.spmc import compose_filters_clause+from products.batch_exports.backend.temporal.workflow_metadata import (+ WorkflowDetails,+ build_logs_link,+ build_team_admin_link,+)LOGGER = get_write_only_logger(__name__)@@ -768,6 +773,9 @@ async def backfill_schedule(inputs: BackfillScheduleInputs) -> None:task_timeout=schedule_action.task_timeout,id_reuse_policy=temporalio.common.WorkflowIDReusePolicy.ALLOW_DUPLICATE,search_attributes=temporalio.common.TypedSearchAttributes(search_attributes=search_attributes),+ # casts required to satisfy type checking+ static_summary=typing.cast(str | None, schedule_action.static_summary),+ static_details=typing.cast(str | None, schedule_action.static_details),)except temporalio.exceptions.WorkflowAlreadyStartedError:workflow_handle = client.get_workflow_handle(f"{description.id}-{backfill_end_at:%Y-%m-%dT%H:%M:%S}Z")@@ -879,6 +887,12 @@ class BackfillBatchExportWorkflow(PostHogWorkflow):)logger = LOGGER.bind()+ base_details = WorkflowDetails(footer=build_logs_link(temporalio.workflow.info().workflow_id)).add(+ "Team", build_team_admin_link(inputs.team_id)+ )+ backfill_range = f"`{inputs.start_at or 'earliest'}` → `{inputs.end_at or 'realtime'}`"+ temporalio.workflow.set_current_details(base_details.text(f"Backfilling {backfill_range}").render())+# Step 1: Create backfill model with STARTING statusbackfill_id = await temporalio.workflow.execute_activity(create_batch_export_backfill_model,@@ -928,6 +942,15 @@ class BackfillBatchExportWorkflow(PostHogWorkflow):# If estimated count is 0, complete early; if None (sessions/other models), proceed normallyshould_complete_early = backfill_info.total_records_count == 0+ if backfill_info.adjusted_start_at is not None and backfill_info.adjusted_start_at != inputs.start_at:+ backfill_range = f"`{backfill_info.adjusted_start_at}` → `{inputs.end_at or 'realtime'}`"+ if backfill_info.total_records_count is not None:+ temporalio.workflow.set_current_details(+ base_details.text(f"Backfilling {backfill_range}")+ .add("Estimated records", backfill_info.total_records_count)+ .render()+ )+await temporalio.workflow.execute_activity(update_batch_export_backfill_model,UpdateBatchExportBackfillInputs(@@ -1014,6 +1037,13 @@ class BackfillBatchExportWorkflow(PostHogWorkflow):raisefinally:+ temporalio.workflow.set_current_details(+ base_details.add("Range", backfill_range)+ .add("Status", update_inputs.status)+ .code_block("Error", update_inputs.latest_error)+ .render()+ )+if not completed_early:await temporalio.workflow.execute_activity(update_batch_export_backfill_model,diff --git a/products/batch_exports/backend/temporal/pipeline/entrypoint.py b/products/batch_exports/backend/temporal/pipeline/entrypoint.pyindex 950331405da1..acac6bc6971d 100644--- a/products/batch_exports/backend/temporal/pipeline/entrypoint.py+++ b/products/batch_exports/backend/temporal/pipeline/entrypoint.py@@ -24,6 +24,12 @@ from products.batch_exports.backend.temporal.pipeline.internal_stage import (insert_into_internal_stage_activity,)from products.batch_exports.backend.temporal.pipeline.types import BatchExportResult+from products.batch_exports.backend.temporal.workflow_metadata import (+ WorkflowDetails,+ build_logs_link,+ build_team_admin_link,+ humanize_bytes,+)LOGGER = get_write_only_logger(__name__)@@ -108,6 +114,16 @@ async def execute_batch_export_using_internal_stage(model_name = batch_export_inputs.batch_export_model.name if batch_export_inputs.batch_export_model else "events"get_export_started_metric(model=model_name).add(1)+ data_window = f"`{batch_export_inputs.data_interval_start}` → `{batch_export_inputs.data_interval_end}`"+ interval_value = data_window if batch_export_inputs.on_demand else f"{interval} {data_window}"+ details = (+ WorkflowDetails(footer=build_logs_link(workflow.info().workflow_id))+ .add("Team", build_team_admin_link(batch_export_inputs.team_id))+ .add("Interval", interval_value)+ .add("Model", model_name)+ )+ workflow.set_current_details(details.render())+assert batch_export_inputs.batch_export_id is not Noneassert batch_export_inputs.run_id is not None@@ -184,6 +200,8 @@ async def execute_batch_export_using_internal_stage()batch_export_inputs.stage_folder = stage_result.stage_folderbatch_export_inputs.records_total = stage_result.records_total+ if stage_result.records_total is not None:+ workflow.set_current_details(details.add("Staged records", stage_result.records_total).render())else:# Pass the activity by name (not the typed callable): `execute_activity` overrides# `result_type` with the callable's annotation, which would force the old recorded@@ -227,6 +245,17 @@ async def execute_batch_export_using_internal_stage(finally:get_export_finished_metric(status=finish_inputs.status.lower(), model=model_name).add(1)+ bytes_exported = (+ humanize_bytes(finish_inputs.bytes_exported) if finish_inputs.bytes_exported is not None else None+ )+ workflow.set_current_details(+ details.add("Status", finish_inputs.status)+ .add("Records completed", finish_inputs.records_completed)+ .add("Bytes exported", bytes_exported)+ .code_block("Error", finish_inputs.latest_error)+ .render()+ )+await workflow.execute_activity(finish_batch_export_run,finish_inputs,diff --git a/products/batch_exports/backend/temporal/workflow_metadata.py b/products/batch_exports/backend/temporal/workflow_metadata.pynew file mode 100644index 000000000000..59cefa0b9eeb--- /dev/null+++ b/products/batch_exports/backend/temporal/workflow_metadata.py@@ -0,0 +1,138 @@+"""Helpers for the user metadata shown next to batch export workflows in the Temporal UI.++Temporal exposes a static summary (a one-line description), and per-run current+details (a markdown panel). These helpers build that content: the summary string,+the markdown links to a team's admin page and the worker logs, and the+``WorkflowDetails`` builder used to assemble the details panel.+"""++import re+import json+from urllib.parse import quote, urlencode++from django.conf import settings++import humanize++# Temporal caps the static summary at 200 bytes; longer values are rejected.+STATIC_SUMMARY_MAX_BYTES = 200+++def humanize_interval(interval: str) -> str:+ """Phrase a batch export interval for display, e.g. "hour" -> "every hour"."""+ return interval if interval.startswith("every") else f"every {interval}"+++def humanize_bytes(num_bytes: int) -> str:+ """Format a byte count for display, e.g. 1572864 -> "1.5 MiB"."""+ return humanize.naturalsize(num_bytes, binary=True)+++def _truncate_to_bytes(text: str, max_bytes: int) -> str:+ """Truncate to at most max_bytes of UTF-8, appending an ellipsis, without splitting a character."""+ if len(text.encode("utf-8")) <= max_bytes:+ return text+ ellipsis = "…"+ budget = max_bytes - len(ellipsis.encode("utf-8"))+ return text.encode("utf-8")[:budget].decode("utf-8", errors="ignore") + ellipsis+++def build_static_summary(destination_type: str, model: str, interval: str, *, is_backfill: bool = False) -> str:+ """Build the Temporal static_summary shown next to a workflow in the UI."""+ prefix = "Backfill batch export" if is_backfill else "Batch export"+ summary = f"{prefix} {model} {humanize_interval(interval)} to {destination_type}"+ return _truncate_to_bytes(summary, STATIC_SUMMARY_MAX_BYTES)+++def build_team_admin_link(team_id: int) -> str:+ """Build a markdown link to a team's Django admin page.++ Shown in the Temporal UI as part of a workflow's user metadata details.+ """+ return f"[{team_id}]({settings.SITE_URL}/admin/posthog/team/{team_id}/change/)"+++def build_logs_link(workflow_id: str) -> str | None:+ """Build a markdown link to worker logs for a batch export workflow.++ Shown in the Temporal UI as part of a workflow's user metadata details.+ Returns None if TEMPORAL_LOGS_PROJECT_ID is not configured.+ """+ project_id = settings.TEMPORAL_LOGS_PROJECT_ID+ if not project_id:+ return None++ base_url = f"{settings.SITE_URL}/project/{project_id}/logs"+ filter_group = json.dumps(+ {+ "type": "AND",+ "values": [+ {+ "type": "AND",+ "values": [+ {+ "key": "workflow_id",+ "value": [workflow_id],+ "operator": "exact",+ "type": "log_attribute",+ }+ ],+ }+ ],+ }+ )+ query_string = urlencode(+ {+ "serviceNames": json.dumps(["temporal-worker-batch-exports"]),+ "filterGroup": filter_group,+ "dateRange": json.dumps({"date_from": "-1d", "date_to": None}),+ },+ quote_via=quote,+ )+ return f"[View logs in PostHog]({base_url}?{query_string})"+++class WorkflowDetails:+ """Builds the markdown for a Temporal workflow's current details panel.++ Rows render as blank-line-separated lines, with an optional footer (e.g. a+ logs link) always rendered last. Rows with a ``None`` value are skipped, so+ optional fields can be added unconditionally. Every method returns a new+ instance, so a base set of rows can be reused across multiple+ ``set_current_details`` calls without accumulating.+ """++ def __init__(self, footer: str | None = None, rows: tuple[str, ...] = ()) -> None:+ self._footer = footer+ self._rows = rows++ def add(self, label: str, value: object | None) -> "WorkflowDetails":+ """Append a ``label: value`` row, or nothing if ``value`` is None."""+ if value is None:+ return self+ return WorkflowDetails(self._footer, (*self._rows, f"{label}: {value}"))++ def text(self, value: str | None) -> "WorkflowDetails":+ """Append a free-form line (no label), or nothing if ``value`` is None."""+ if value is None:+ return self+ return WorkflowDetails(self._footer, (*self._rows, value))++ def code_block(self, label: str, value: object | None) -> "WorkflowDetails":+ """Append a ``label`` followed by ``value`` in a fenced code block, or nothing if None.++ Used for code blocks, but also, untrusted, potentially multi-line values (e.g. destination+ error text) so the Temporal UI does not render them as markdown. The fence is one backtick+ longer than the longest backtick run in the value, so the value cannot close the block early+ and escape it.+ """+ if value is None:+ return self+ text = str(value)+ longest_backtick_run = max((len(run) for run in re.findall(r"`+", text)), default=0)+ fence = "`" * max(3, longest_backtick_run + 1)+ return WorkflowDetails(self._footer, (*self._rows, f"{label}:\n{fence}\n{text}\n{fence}"))++ def render(self) -> str:+ parts = self._rows if self._footer is None else (*self._rows, self._footer)+ return "\n\n".join(parts)diff --git a/products/batch_exports/backend/tests/api/test_create.py b/products/batch_exports/backend/tests/api/test_create.pyindex 74b14ae7c364..06b2ca34d4cf 100644--- a/products/batch_exports/backend/tests/api/test_create.py+++ b/products/batch_exports/backend/tests/api/test_create.py@@ -118,6 +118,11 @@ def test_create_batch_export_with_interval_schedule(assert args["aws_secret_access_key"] == "secret"assert args["use_virtual_style_addressing"]+ # Temporal UI metadata should be set on the schedule's action+ assert schedule.schedule.action.static_summary is not None+ decoded_summary = async_to_sync(encryption_codec.decode)([schedule.schedule.action.static_summary])+ assert json.loads(decoded_summary[0].data) == "Batch export events every hour to S3Compatible"+@pytest.mark.parametrize("interval,timezone,offset_day,offset_hour,expected_interval_offset",diff --git a/products/batch_exports/backend/tests/temporal/test_workflow_metadata.py b/products/batch_exports/backend/tests/temporal/test_workflow_metadata.pynew file mode 100644index 000000000000..dec21a998139--- /dev/null+++ b/products/batch_exports/backend/tests/temporal/test_workflow_metadata.py@@ -0,0 +1,124 @@+import re+import json+from urllib.parse import parse_qs, urlparse++import pytest++from products.batch_exports.backend.temporal.workflow_metadata import (+ STATIC_SUMMARY_MAX_BYTES,+ WorkflowDetails,+ build_logs_link,+ build_static_summary,+ humanize_bytes,+)+++def test_build_logs_link_filters_logs_by_workflow_id(settings):+ settings.TEMPORAL_LOGS_PROJECT_ID = 123+ settings.SITE_URL = "https://example.com"++ link = build_logs_link("a-workflow-id")++ assert link is not None+ markdown_match = re.fullmatch(r"\[View logs in PostHog\]\((.+)\)", link)+ assert markdown_match is not None++ url = urlparse(markdown_match.group(1))+ assert url.path == "/project/123/logs"++ params = parse_qs(url.query)+ filter_group = json.loads(params["filterGroup"][0])+ assert filter_group == {+ "type": "AND",+ "values": [+ {+ "type": "AND",+ "values": [+ {+ "key": "workflow_id",+ "value": ["a-workflow-id"],+ "operator": "exact",+ "type": "log_attribute",+ }+ ],+ }+ ],+ }+ # An explicit date range is set so the logs UI shows enough history to find the run.+ assert json.loads(params["dateRange"][0]) == {"date_from": "-1d", "date_to": None}+++def test_build_logs_link_disabled_when_no_project_configured(settings):+ settings.TEMPORAL_LOGS_PROJECT_ID = 0+ assert build_logs_link("a-workflow-id") is None+++ "interval,is_backfill,expected",+ [+ ("hour", False, "Batch export events every hour to S3"),+ ("day", False, "Batch export events every day to S3"),+ ("every 5 minutes", False, "Batch export events every 5 minutes to S3"),+ ("hour", True, "Backfill batch export events every hour to S3"),+ ],+)+def test_build_static_summary(interval, is_backfill, expected):+ assert build_static_summary("S3", "events", interval, is_backfill=is_backfill) == expected+++def test_build_static_summary_truncated_to_temporal_byte_limit():+ # A long model name would otherwise push the summary past Temporal's 200-byte cap and be rejected.+ summary = build_static_summary("S3", "events_" * 50, "hour")+ assert len(summary.encode("utf-8")) <= STATIC_SUMMARY_MAX_BYTES+ assert summary.endswith("…")+++ "num_bytes,expected",+ [+ (0, "0 Bytes"),+ (512, "512 Bytes"),+ (1024, "1.0 KiB"),+ (1572864, "1.5 MiB"),+ ],+)+def test_humanize_bytes(num_bytes, expected):+ assert humanize_bytes(num_bytes) == expected+++def test_workflow_details_renders_rows_with_footer_last():+ details = (+ WorkflowDetails(footer="[logs](https://example.com)")+ .add("Team", "1")+ .text("Backfilling `a` → `b`")+ .add("Status", "Completed")+ )+ assert details.render() == "Team: 1\n\nBackfilling `a` → `b`\n\nStatus: Completed\n\n[logs](https://example.com)"+++def test_workflow_details_skips_none_values():+ details = WorkflowDetails().add("Records", 0).add("Bytes", None).text(None).add("Status", "Completed")+ # 0 is kept (only None is skipped); None rows and a None footer drop out entirely.+ assert details.render() == "Records: 0\n\nStatus: Completed"+++def test_workflow_details_code_block_prevents_markdown_injection():+ # A destination error is user-influenced text; it must render inside a fence, and a fence that+ # the error's own backticks cannot break out of, so a crafted "[link](...)" can't reach the UI.+ error = "boom ``` [View logs](https://attacker.example)"+ rendered = WorkflowDetails().code_block("Error", error).render()++ fence = "````" # grown past the triple-backtick run in the error+ assert rendered == f"Error:\n{fence}\n{error}\n{fence}"+++def test_workflow_details_is_immutable_so_a_base_can_be_reused():+ base = WorkflowDetails().add("Team", "1")++ staged = base.add("Staged records", 5)+ finished = base.add("Status", "Completed")++ # Extending the base does not mutate it, so each render reflects only its own additions.+ assert base.render() == "Team: 1"+ assert staged.render() == "Team: 1\n\nStaged records: 5"+ assert finished.render() == "Team: 1\n\nStatus: Completed"