: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
fix(session-replay): stop Temporal loggers crashing on keyword fields (#91586)
posthog[bot]f41fbb41a12e
diff --git a/.semgrep/rules/devex/temporal-logger-no-keyword-fields.yaml b/.semgrep/rules/devex/temporal-logger-no-keyword-fields.yamlnew file mode 100644index 000000000000..2ff6afd68dfc--- /dev/null+++ b/.semgrep/rules/devex/temporal-logger-no-keyword-fields.yaml@@ -0,0 +1,46 @@+rules:+ - id: temporal-logger-no-keyword-fields+ message: |+ `activity.logger` and `workflow.logger` are stdlib `logging.LoggerAdapter`+ instances. They forward `**kwargs` to `Logger._log()`, which accepts only+ `exc_info`, `stack_info`, `stacklevel` and `extra` — any other keyword+ raises `TypeError: Logger._log() got an unexpected keyword argument '<name>'`.++ Pass structured fields one of two ways:++ - In an activity, log through the module's structlog logger, which takes+ keyword fields directly. `merge_temporal_context` is registered as a+ global processor, so activity id, workflow id and attempt are still+ attached.+ - In a workflow, keep `workflow.logger` (it suppresses duplicate logs+ during replay) and move the fields into `extra={...}`.++ Why this is easy to miss: `LoggerAdapter.log` checks `isEnabledFor(level)`+ before it touches the kwargs, so a bad `info()` call is inert below INFO.+ Tests default to WARNING and pass; the production worker runs at INFO and+ raises on every call. In a workflow that surfaces as a workflow *task*+ failure, which Temporal retries indefinitely, so the run wedges until its+ execution timeout instead of failing — no error status, no metrics, no alert.+ languages: [python]+ severity: ERROR+ paths:+ include:+ - 'posthog/temporal/'+ - 'products/*/backend/temporal/'+ pattern-either:+ - patterns:+ - pattern-either:+ - pattern: activity.logger.$LEVEL(..., $KEY=$VALUE, ...)+ - pattern: workflow.logger.$LEVEL(..., $KEY=$VALUE, ...)+ - metavariable-regex:+ metavariable: $LEVEL+ regex: '^(debug|info|warning|warn|error|critical|exception|log)$'+ - metavariable-regex:+ metavariable: $KEY+ regex: '^(?!exc_info$|stack_info$|stacklevel$|extra$).*'+ metadata:+ category: correctness+ subcategory:+ - audit+ technology:+ - temporaldiff --git a/posthog/temporal/AGENTS.md b/posthog/temporal/AGENTS.mdindex 7438132a2045..4a5e18b4f10d 100644--- a/posthog/temporal/AGENTS.md+++ b/posthog/temporal/AGENTS.md@@ -6,6 +6,21 @@ Pointers, not content. Read the linked docs before changing code or tests in thi- [Temporal at PostHog](./README.md) — concepts, workflows, activities, the conventions we use, common pitfalls, links to the upstream Temporal SDK docs.+## Logging++Never pass structured fields as keyword arguments to `activity.logger` or `workflow.logger`.+Both are stdlib `logging.LoggerAdapter` instances, which forward keyword arguments to `Logger._log()`.+That method accepts only `exc_info`, `stack_info`, `stacklevel` and `extra`, so any other field raises `TypeError`.++- **In an activity, log through the module's structlog logger.** It takes keyword fields directly, and `merge_temporal_context` is registered as a global processor, so the activity id, workflow id and attempt are still attached. See [Logging](./README.md#logging).+- **In a workflow, keep `workflow.logger` and pass fields via `extra={...}`.** Do not switch a workflow to structlog: `workflow.logger` suppresses duplicate logs during replay, and a structlog logger re-logs every replayed line.++`LoggerAdapter.log` checks `isEnabledFor(level)` before it reads the keyword arguments, so a bad `info` call is inert at the default test level of WARNING and fails only in production, which runs at INFO.+In a workflow the crash is a workflow _task_ failure, which Temporal retries forever, so the run wedges instead of failing and reports no error status.+Tests that exercise a workflow end to end should pin `temporalio.activity` and `temporalio.workflow` to INFO, and set an `execution_timeout` so a wedged run fails rather than hangs.++The semgrep rule `temporal-logger-no-keyword-fields` blocks this at review time.+## Writing or modifying tests in this tree- [Testing patterns](./README.md#testing-patterns) — when to use real Worker vs `ActivityEnvironment` vs no harness, why some files need `@pytest.mark.django_db(transaction=True)`, the module-scoped Worker pattern that avoids booting the temporal-test-server per test, the `connection.connect()` monkeypatch escape hatch, and the parametrize-don't-copy-paste rule.diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/activities.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/activities.pyindex d5db7fc134f8..d5319c8cc779 100644--- a/posthog/temporal/session_replay/surfacing_score_export_sweep/activities.py+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/activities.py@@ -195,7 +195,7 @@ async def export_scores_partition_activity(spec: ExportPartitionSpec) -> ExportPkey = score_export_object_key(spec.day, spec.chunk_id, spec.of_chunks)await sync_to_async(_upload, thread_sensitive=False)(key, body)- activity.logger.info(+ logger.info("surfacing_score_export_sweep.partition_done",day=spec.day,chunk_id=spec.chunk_id,diff --git a/posthog/temporal/session_replay/surfacing_score_export_sweep/workflow.py b/posthog/temporal/session_replay/surfacing_score_export_sweep/workflow.pyindex 864663b42ac3..f6b6f3a640ec 100644--- a/posthog/temporal/session_replay/surfacing_score_export_sweep/workflow.py+++ b/posthog/temporal/session_replay/surfacing_score_export_sweep/workflow.py@@ -50,7 +50,9 @@ class ExportSurfacingScoresWorkflow(PostHogWorkflow):)if plan.disabled_reason is not None:- workflow.logger.warning("surfacing_score_export_sweep.disabled", disabled_reason=plan.disabled_reason)+ workflow.logger.warning(+ "surfacing_score_export_sweep.disabled", extra={"disabled_reason": plan.disabled_reason}+ )return ExportScoresSweepResult(disabled_reason=plan.disabled_reason)if not plan.partitions:@@ -101,15 +103,18 @@ def _summarize(if isinstance(r, BaseException):summary.partitions_failed += 1workflow.logger.warning(- "surfacing_score_export_sweep.partition_failed", error=str(r), error_type=type(r).__name__+ "surfacing_score_export_sweep.partition_failed",+ extra={"error": str(r), "error_type": type(r).__name__},)continuesummary.total_rows += r.rowsworkflow.logger.info("surfacing_score_export_sweep.tick_done",- partitions_dispatched=summary.partitions_dispatched,- partitions_failed=summary.partitions_failed,- total_rows=summary.total_rows,+ extra={+ "partitions_dispatched": summary.partitions_dispatched,+ "partitions_failed": summary.partitions_failed,+ "total_rows": summary.total_rows,+ },)record_tick_summary(partitions_dispatched=summary.partitions_dispatched,diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/activities.py b/posthog/temporal/session_replay/surfacing_scoring_sweep/activities.pyindex c6f96c778df5..cd56598f8c8b 100644--- a/posthog/temporal/session_replay/surfacing_scoring_sweep/activities.py+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/activities.py@@ -281,7 +281,7 @@ async def score_chunk_activity(spec: ChunkSpec) -> ChunkResult:feature_names = await sync_to_async(get_feature_names, thread_sensitive=False)()- activity.logger.info(+ logger.info("surfacing_scoring_sweep.fetched",chunk_id=spec.chunk_id,rows=len(df),@@ -303,7 +303,7 @@ async def score_chunk_activity(spec: ChunkSpec) -> ChunkResult:# chunk would deterministically re-fail this hash bucket every tick.bad_rows = out_of_contract_row_mask(df, feature_names=feature_names)if bad_rows.any():- activity.logger.warning(+ logger.warning("surfacing_scoring_sweep.rows_out_of_contract",chunk_id=spec.chunk_id,dropped=int(bad_rows.sum()),@@ -319,7 +319,7 @@ async def score_chunk_activity(spec: ChunkSpec) -> ChunkResult:activity.heartbeat({"phase": "publish", "chunk_id": spec.chunk_id, "rows": len(df)})published = await sync_to_async(_publish_scores, thread_sensitive=False)(df, scores)- activity.logger.info(+ logger.info("surfacing_scoring_sweep.chunk_done",chunk_id=spec.chunk_id,scored=published,diff --git a/posthog/temporal/session_replay/surfacing_scoring_sweep/workflow.py b/posthog/temporal/session_replay/surfacing_scoring_sweep/workflow.pyindex 7fb41bcd260a..e753fb7b8221 100644--- a/posthog/temporal/session_replay/surfacing_scoring_sweep/workflow.py+++ b/posthog/temporal/session_replay/surfacing_scoring_sweep/workflow.py@@ -68,7 +68,9 @@ class ScoreSessionsBatchWorkflow(PostHogWorkflow):)if not plan.chunks:- workflow.logger.info("surfacing_scoring_sweep.no_work", estimated=plan.estimated_unscored_sessions)+ workflow.logger.info(+ "surfacing_scoring_sweep.no_work", extra={"estimated": plan.estimated_unscored_sessions}+ )return ScoreSessionsBatchResult()results = await asyncio.gather(@@ -108,17 +110,19 @@ def _summarize(chunks: list[ChunkSpec], results: list[ChunkResult | BaseExceptioif isinstance(r, ActivityError):workflow.logger.warning("surfacing_scoring_sweep.chunk_activity_failed",- error=str(r),+ extra={"error": str(r)},)continuesummary.total_scored += r.scoredsummary.total_fetched += r.fetchedworkflow.logger.info("surfacing_scoring_sweep.tick_done",- chunks_dispatched=summary.chunks_dispatched,- chunks_failed=summary.chunks_failed,- total_scored=summary.total_scored,- total_fetched=summary.total_fetched,+ extra={+ "chunks_dispatched": summary.chunks_dispatched,+ "chunks_failed": summary.chunks_failed,+ "total_scored": summary.total_scored,+ "total_fetched": summary.total_fetched,+ },)record_tick_summary(total_scored=summary.total_scored,diff --git a/posthog/temporal/tests/session_replay/surfacing_score_export_sweep/conftest.py b/posthog/temporal/tests/session_replay/surfacing_score_export_sweep/conftest.pynew file mode 100644index 000000000000..b5487f53f22e--- /dev/null+++ b/posthog/temporal/tests/session_replay/surfacing_score_export_sweep/conftest.py@@ -0,0 +1,18 @@+from __future__ import annotations++import logging++import pytest++[email protected](autouse=True)+def _temporal_loggers_at_info(caplog: pytest.LogCaptureFixture) -> None:+ """Run the Temporal loggers at INFO, as the production worker does.++ The Temporal loggers are stdlib `LoggerAdapter`s that reject structured+ keyword fields, and they only reach the rejecting call once the level lets+ the record through. At the default WARNING level an `info` call with a bad+ field is inert, so a crash that happens on every production tick passes here.+ """+ caplog.set_level(logging.INFO, logger="temporalio.activity")+ caplog.set_level(logging.INFO, logger="temporalio.workflow")diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/conftest.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/conftest.pyindex 166cbc7ed5d9..f27ca7d751b9 100644--- a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/conftest.py+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/conftest.py@@ -11,6 +11,7 @@ behind a mocked S3 fetch so tests exercise the production code pathfrom __future__ import annotations+import loggingfrom collections.abc import Generatorfrom pathlib import Path@@ -53,6 +54,19 @@ def reset_scorer_singleton() -> None:scorer_mod._S3_CACHED_PATH = None[email protected](autouse=True)+def _temporal_loggers_at_info(caplog: pytest.LogCaptureFixture) -> None:+ """Run the Temporal loggers at INFO, as the production worker does.++ The Temporal loggers are stdlib `LoggerAdapter`s that reject structured+ keyword fields, and they only reach the rejecting call once the level lets+ the record through. At the default WARNING level an `info` call with a bad+ field is inert, so a crash that happens on every production tick passes here.+ """+ caplog.set_level(logging.INFO, logger="temporalio.activity")+ caplog.set_level(logging.INFO, logger="temporalio.workflow")++@pytest.fixture(autouse=True)def _scorer_singleton_clean_slate() -> Generator[None]:"""Every test in this directory starts and ends with a fresh scorer singleton."""diff --git a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_workflow.py b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_workflow.pyindex 1c9953e5b477..8d518bac0e21 100644--- a/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_workflow.py+++ b/posthog/temporal/tests/session_replay/surfacing_scoring_sweep/test_workflow.py@@ -1,6 +1,7 @@from __future__ import annotationsimport uuid+from datetime import timedeltaimport pytestfrom unittest import mock@@ -172,6 +173,10 @@ async def test_workflow_tolerates_partial_chunk_failures() -> None:ScoreSessionsBatchInputs(),id=str(uuid.uuid4()),task_queue=task_queue,+ # A crash in workflow code is a workflow *task* failure, which Temporal+ # retries forever, so a regression here wedges instead of failing. Cap it+ # so the test reports a timeout rather than hanging the suite.+ execution_timeout=timedelta(seconds=30),)parsed = _as_batch_result(result)diff --git a/products/conversations/backend/temporal/coordinator.py b/products/conversations/backend/temporal/coordinator.pyindex c000d7772d5f..56fdaaf286b5 100644--- a/products/conversations/backend/temporal/coordinator.py+++ b/products/conversations/backend/temporal/coordinator.py@@ -260,8 +260,7 @@ class SupportReplyCoordinatorWorkflow:except WorkflowAlreadyStartedError:workflow.logger.info("support_reply coordinator: child already running",- ticket_id=ticket.ticket_id,- child_id=child_id,+ extra={"ticket_id": ticket.ticket_id, "child_id": child_id},)skipped += 1diff --git a/products/conversations/backend/temporal/pipeline.py b/products/conversations/backend/temporal/pipeline.pyindex 46371ee2637f..750e27290a00 100644--- a/products/conversations/backend/temporal/pipeline.py+++ b/products/conversations/backend/temporal/pipeline.py@@ -106,7 +106,7 @@ class SupportReplyWorkflow:retry_policy=RetryPolicy(maximum_attempts=3),)except Exception:- workflow.logger.warning("support_reply: failed to record triage", status=patch.get("status"))+ workflow.logger.warning("support_reply: failed to record triage", extra={"status": patch.get("status")})async def _persist_gaps(gap_missing: list[str], gap_ticket_type: str, gap_outcome: str) -> None:"""Best-effort: record knowledge gaps without breaking the pipeline."""@@ -163,8 +163,7 @@ class SupportReplyWorkflow:)if not safety_output.safe:workflow.logger.info(- "support_reply: ticket blocked by safety filter",- threat_type=safety_output.threat_type,+ "support_reply: ticket blocked by safety filter", extra={"threat_type": safety_output.threat_type})outcome = {"result": "blocked_unsafe"}return "blocked_unsafe"@@ -309,8 +308,7 @@ class SupportReplyWorkflow:)if not review_output.safe:workflow.logger.info(- "support_reply: reply blocked by output review",- reason=review_output.reason,+ "support_reply: reply blocked by output review", extra={"reason": review_output.reason})outcome = {"result": "blocked_unsafe_reply",@@ -373,8 +371,7 @@ class SupportReplyWorkflow:)if not review_output.safe:workflow.logger.info(- "support_reply: reply blocked by output review",- reason=review_output.reason,+ "support_reply: reply blocked by output review", extra={"reason": review_output.reason})outcome = {"result": "blocked_unsafe_reply",diff --git a/products/logs/backend/temporal/workflow.py b/products/logs/backend/temporal/workflow.pyindex 754d811c8725..11460283eee9 100644--- a/products/logs/backend/temporal/workflow.py+++ b/products/logs/backend/temporal/workflow.py@@ -95,7 +95,7 @@ class LogsAlertCheckWorkflow(PostHogWorkflow):# Batch's retries exhausted — count its alerts as errored, keep going.workflow.logger.warning("Cohort batch activity failed; counting batch alerts as errored",- cohort_count=len(batch.manifests),+ extra={"cohort_count": len(batch.manifests)},)alerts_errored += sum(len(m.alert_ids) for m in batch.manifests)elif isinstance(result, BaseException):diff --git a/products/managed_warehouse/backend/temporal/ducklake_copy_data_modeling_workflow.py b/products/managed_warehouse/backend/temporal/ducklake_copy_data_modeling_workflow.pyindex e6a67451eff1..65387a06c4c2 100644--- a/products/managed_warehouse/backend/temporal/ducklake_copy_data_modeling_workflow.py+++ b/products/managed_warehouse/backend/temporal/ducklake_copy_data_modeling_workflow.py@@ -489,10 +489,7 @@ class DuckLakeCopyDataModelingWorkflow(PostHogWorkflow):retry_policy=RetryPolicy(maximum_attempts=2),)except Exception:- workflow.logger.warning(- "Failed to clean up staging files",- staging_uri=staging_uri,- )+ workflow.logger.warning("Failed to clean up staging files", extra={"staging_uri": staging_uri})if not failed:get_ducklake_copy_data_modeling_finished_metric(status="completed").add(1)diff --git a/products/replay_vision/backend/temporal/vision_alerts/workflow.py b/products/replay_vision/backend/temporal/vision_alerts/workflow.pyindex 53441687bcc2..f2482169eab9 100644--- a/products/replay_vision/backend/temporal/vision_alerts/workflow.py+++ b/products/replay_vision/backend/temporal/vision_alerts/workflow.py@@ -70,7 +70,7 @@ class VisionAlertCheckWorkflow(PostHogWorkflow):for batch, result in zip(discovery.batches, results):if isinstance(result, ActivityError):workflow.logger.warning(- "Vision alert batch failed; counting its alerts as errored", batch_size=len(batch)+ "Vision alert batch failed; counting its alerts as errored", extra={"batch_size": len(batch)})output.alerts_errored += len(batch)elif isinstance(result, BaseException):diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.pyindex ab909c6a69e2..8577fe06f4ec 100644--- a/products/signals/backend/temporal/agentic/scout_coordinator.py+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py@@ -752,9 +752,7 @@ async def _start_child(*, planned: PlannedRun, tick_id: str, idx: int) -> bool:except WorkflowAlreadyStartedError:workflow.logger.info("signals_scout coordinator: child already running, skipping",- team_id=planned.team_id,- skill_name=planned.skill_name,- child_id=child_id,+ extra={"team_id": planned.team_id, "skill_name": planned.skill_name, "child_id": child_id},)return Falsediff --git a/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py b/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.pyindex 86e48abefdab..c4c28d0ad3ec 100644--- a/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py+++ b/products/tasks/backend/temporal/execute_sandbox/tests/test_execute_sandbox_workflow.py@@ -764,8 +764,7 @@ class TestRun:refresh_loop_mock.assert_awaited_once_with(workflow.context, "sandbox-123")silent_workflow_logger.warning.assert_called_once_with("execute_sandbox_sandbox_gone_detected",- run_id="run-id",- sandbox_id="sandbox-123",+ extra={"run_id": "run-id", "sandbox_id": "sandbox-123"},)async def test_credential_refresh_task_gone_marks_the_run_failed(self, monkeypatch, silent_workflow_logger):@@ -799,8 +798,7 @@ class TestRun:assert workflow._sandbox_gone is Falsesilent_workflow_logger.warning.assert_called_once_with("execute_sandbox_credential_refresh_stopped_credentials_unavailable",- run_id="run-id",- sandbox_id="sandbox-123",+ extra={"run_id": "run-id", "sandbox_id": "sandbox-123"},)@pytest.mark.parametrize(diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.pyindex e3f39b6939e5..63da7901d535 100644--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py@@ -437,8 +437,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):if task.exception():workflow.logger.warning("execute_sandbox_event_wait_failed",- run_id=self.context.run_id,- error=str(task.exception()),+ extra={"run_id": self.context.run_id, "error": str(task.exception())},)continuereturn task.result()@@ -544,8 +543,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):if self._heartbeat_received and not self._task_completed:workflow.logger.info(- "execute_sandbox_heartbeat_reset",- run_id=self.context.run_id,+ "execute_sandbox_heartbeat_reset", extra={"run_id": self.context.run_id})self._heartbeat_received = Falsecontinue@@ -811,11 +809,13 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):context = self._contextworkflow.logger.info("execute_sandbox_followup_signal_received",- run_id=context.run_id if context is not None else None,- message_length=len(message or ""),- artifact_count=len(artifact_ids or []),- source=source,- ack_id=ack_id,+ extra={+ "run_id": context.run_id if context is not None else None,+ "message_length": len(message or ""),+ "artifact_count": len(artifact_ids or []),+ "source": source,+ "ack_id": ack_id,+ },)# Already dispatched (or rejected) — re-ack and skip.if self._is_duplicate_signal(signal_name, ack_id):@@ -878,8 +878,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):if self._should_skip_followup(followup.message, followup.artifact_ids):workflow.logger.warning("execute_sandbox_empty_followup_skipped",- run_id=self.context.run_id,- ack_id=followup.ack_id,+ extra={"run_id": self.context.run_id, "ack_id": followup.ack_id},)self._enqueue_ack(signal_name=signal_name,@@ -921,9 +920,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):cause_message = error_properties.get("cause_error_message")workflow.logger.warning("execute_sandbox_send_followup_failed",- run_id=self.context.run_id,- error=str(e),- **error_properties,+ extra={"run_id": self.context.run_id, "error": str(e), **error_properties},)peer_message_id = peer_message_id_from_context(followup.context)if peer_message_id is not None:@@ -977,8 +974,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):except Exception:workflow.logger.warning("peer_message_failure_record_failed",- run_id=self.context.run_id,- peer_message_id=peer_message_id,+ extra={"run_id": self.context.run_id, "peer_message_id": peer_message_id},)def _is_duplicate_signal(self, signal_name: str, ack_id: Optional[str]) -> bool:@@ -1045,18 +1041,22 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):self._pending_outbound.clear()workflow.logger.info("execute_sandbox_parent_signal_delivery_closed",- run_id=self.context.run_id if self._context else None,- target_signal=outbound.target_signal,- correlation_id=outbound.correlation_id,- error=str(e),+ extra={+ "run_id": self.context.run_id if self._context else None,+ "target_signal": outbound.target_signal,+ "correlation_id": outbound.correlation_id,+ "error": str(e),+ },)returnworkflow.logger.warning("execute_sandbox_outbound_signal_failed",- run_id=self.context.run_id if self._context else None,- target_signal=outbound.target_signal,- correlation_id=outbound.correlation_id,- error=str(e),+ extra={+ "run_id": self.context.run_id if self._context else None,+ "target_signal": outbound.target_signal,+ "correlation_id": outbound.correlation_id,+ "error": str(e),+ },)if self._ordered_outbound_delivery:# Keep the failed ACK and every later signal ahead of@@ -1084,9 +1084,11 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):):workflow.logger.warning("execute_sandbox_final_outbound_retries_exhausted",- run_id=self.context.run_id if self._context else None,- attempts=attempts,- undelivered=len(self._pending_outbound),+ extra={+ "run_id": self.context.run_id if self._context else None,+ "attempts": attempts,+ "undelivered": len(self._pending_outbound),+ },)self._pending_outbound.clear()@@ -1244,9 +1246,11 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):if result.reaped_sandbox_id is not None:workflow.logger.info("execute_sandbox_reaped_orphan",- run_id=run_id,- sandbox_id=result.reaped_sandbox_id,- destroy_succeeded=result.destroy_succeeded,+ extra={+ "run_id": run_id,+ "sandbox_id": result.reaped_sandbox_id,+ "destroy_succeeded": result.destroy_succeeded,+ },)# Don't fail the run if persistence flakes — Modal TTL will catch the@@ -1404,22 +1408,18 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):exit_reason = await run_credential_refresh_loop(self.context, sandbox_id)if exit_reason == CredentialRefreshExitReason.SANDBOX_GONE:workflow.logger.warning(- "execute_sandbox_sandbox_gone_detected",- run_id=self.context.run_id,- sandbox_id=sandbox_id,+ "execute_sandbox_sandbox_gone_detected", extra={"run_id": self.context.run_id, "sandbox_id": sandbox_id})self._sandbox_gone = Trueelif exit_reason == CredentialRefreshExitReason.CREDENTIALS_UNAVAILABLE:workflow.logger.warning("execute_sandbox_credential_refresh_stopped_credentials_unavailable",- run_id=self.context.run_id,- sandbox_id=sandbox_id,+ extra={"run_id": self.context.run_id, "sandbox_id": sandbox_id},)elif exit_reason == CredentialRefreshExitReason.TASK_GONE:workflow.logger.warning("execute_sandbox_task_rows_gone_detected",- run_id=self.context.run_id,- sandbox_id=sandbox_id,+ extra={"run_id": self.context.run_id, "sandbox_id": sandbox_id},)# Ends the main loop through the sandbox-gone event so the workflow winds down# instead of waiting on signals that can never arrive. Recording failure here is@@ -1517,9 +1517,11 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):) -> str | None:workflow.logger.info("execute_sandbox_send_followup_begin",- run_id=self.context.run_id,- message_length=len(message or ""),- artifact_count=len(artifact_ids),+ extra={+ "run_id": self.context.run_id,+ "message_length": len(message or ""),+ "artifact_count": len(artifact_ids),+ },)return await workflow.execute_activity(send_followup_to_sandbox,diff --git a/products/tasks/backend/temporal/process_task/activities/get_pr_babysit_snapshot.py b/products/tasks/backend/temporal/process_task/activities/get_pr_babysit_snapshot.pyindex 66fa32a9092d..3c6cc4f73b63 100644--- a/products/tasks/backend/temporal/process_task/activities/get_pr_babysit_snapshot.py+++ b/products/tasks/backend/temporal/process_task/activities/get_pr_babysit_snapshot.py@@ -41,7 +41,7 @@ def get_pr_babysit_snapshot(input: GetPrBabysitSnapshotInput) -> PRSnapshot | Notry:task_run = TaskRun.objects.get(id=ctx.run_id)except TaskRun.DoesNotExist:- activity.logger.warning("get_pr_babysit_snapshot_task_run_not_found", run_id=ctx.run_id)+ activity.logger.warning("get_pr_babysit_snapshot_task_run_not_found", extra={"run_id": ctx.run_id})return Nonepr_url = (task_run.output or {}).get("pr_url")@@ -57,8 +57,10 @@ def get_pr_babysit_snapshot(input: GetPrBabysitSnapshotInput) -> PRSnapshot | Noexcept ObjectDoesNotExist:activity.logger.warning("get_pr_babysit_snapshot_github_integration_not_found",- github_integration_id=ctx.github_integration_id,- github_user_integration_id=ctx.github_user_integration_id,+ extra={+ "github_integration_id": ctx.github_integration_id,+ "github_user_integration_id": ctx.github_user_integration_id,+ },)return None@@ -89,9 +91,7 @@ def get_pr_babysit_snapshot(input: GetPrBabysitSnapshotInput) -> PRSnapshot | Noif not raw.get("success"):activity.logger.warning("get_pr_babysit_snapshot_failed",- run_id=ctx.run_id,- pr_url=pr_url,- error=raw.get("error"),+ extra={"run_id": ctx.run_id, "pr_url": pr_url, "error": raw.get("error")},)increment_pr_babysit_snapshot("unavailable")return Nonediff --git a/products/tasks/backend/temporal/process_task/activities/get_pr_context.py b/products/tasks/backend/temporal/process_task/activities/get_pr_context.pyindex 18a3985b907e..e34ddd8a1468 100644--- a/products/tasks/backend/temporal/process_task/activities/get_pr_context.py+++ b/products/tasks/backend/temporal/process_task/activities/get_pr_context.py@@ -108,7 +108,7 @@ def get_pr_context(input: GetPrContextInput) -> GetPrContextOutput | None:try:task_run = TaskRun.objects.get(id=ctx.run_id)except TaskRun.DoesNotExist:- activity.logger.warning("get_pr_context_task_run_not_found", run_id=ctx.run_id)+ activity.logger.warning("get_pr_context_task_run_not_found", extra={"run_id": ctx.run_id})return Nonepr_url = (task_run.output or {}).get("pr_url")@@ -124,8 +124,10 @@ def get_pr_context(input: GetPrContextInput) -> GetPrContextOutput | None:except ObjectDoesNotExist:activity.logger.warning("get_pr_context_github_integration_not_found",- github_integration_id=ctx.github_integration_id,- github_user_integration_id=ctx.github_user_integration_id,+ extra={+ "github_integration_id": ctx.github_integration_id,+ "github_user_integration_id": ctx.github_user_integration_id,+ },)return Nonediff --git a/products/tasks/backend/temporal/task_management/workflow.py b/products/tasks/backend/temporal/task_management/workflow.pyindex 639e3e2c778a..3982b67286b9 100644--- a/products/tasks/backend/temporal/task_management/workflow.py+++ b/products/tasks/backend/temporal/task_management/workflow.py@@ -605,9 +605,7 @@ class TaskManagementWorkflow(PostHogWorkflow):for task in done:if task.exception():workflow.logger.warning(- "task_management_event_wait_failed",- run_id=self._run_id,- error=str(task.exception()),+ "task_management_event_wait_failed", extra={"run_id": self._run_id, "error": str(task.exception())})continuereturn task.result()@@ -634,15 +632,11 @@ class TaskManagementWorkflow(PostHogWorkflow):await self._wait_before_replacement_sandbox()workflow.logger.info("task_management_rebootstrapping_for_followup",- run_id=self._run_id,- pending=len(self._pending_external_followups),+ extra={"run_id": self._run_id, "pending": len(self._pending_external_followups)},)await self._ensure_sandbox_workflow_started()elif self._pending_external_complete is not None:- workflow.logger.info(- "task_management_complete_dropped_no_sandbox",- run_id=self._run_id,- )+ workflow.logger.info("task_management_complete_dropped_no_sandbox", extra={"run_id": self._run_id})self._pending_external_complete = Nonereturn@@ -683,9 +677,7 @@ class TaskManagementWorkflow(PostHogWorkflow):if slot is None:workflow.logger.debug("task_management_ack_unmatched",- run_id=self._run_id,- signal_name=ack.signal_name,- ack_id=ack.ack_id,+ extra={"run_id": self._run_id, "signal_name": ack.signal_name, "ack_id": ack.ack_id},)continueif not ack.accepted and ack.detail == SHUTDOWN_REJECTION_DETAIL:@@ -701,12 +693,14 @@ class TaskManagementWorkflow(PostHogWorkflow):self._consecutive_sandbox_replacement_failures = 0workflow.logger.info("task_management_ack_received",- run_id=self._run_id,- signal_name=ack.signal_name,- ack_id=ack.ack_id,- accepted=ack.accepted,- latency_ms=int((ack.received_at - slot.sent_at).total_seconds() * 1000),- detail=ack.detail,+ extra={+ "run_id": self._run_id,+ "signal_name": ack.signal_name,+ "ack_id": ack.ack_id,+ "accepted": ack.accepted,+ "latency_ms": int((ack.received_at - slot.sent_at).total_seconds() * 1000),+ "detail": ack.detail,+ },)self._heartbeat_received = Falsefor followup in requeued_followups:@@ -723,14 +717,12 @@ class TaskManagementWorkflow(PostHogWorkflow):if slot.signal_name in {SEND_FOLLOWUP_SIGNAL, SEND_STEER_SIGNAL} and slot.signal_args is not None:workflow.logger.warning("task_management_followup_requeued_after_shutdown",- run_id=self._run_id,- source=slot.signal_args[3],+ extra={"run_id": self._run_id, "source": slot.signal_args[3]},)return self._external_followup_from_slot(slot)workflow.logger.info("task_management_shutdown_rejection_ignored",- run_id=self._run_id,- signal_name=slot.signal_name,+ extra={"run_id": self._run_id, "signal_name": slot.signal_name},)return None@@ -793,17 +785,14 @@ class TaskManagementWorkflow(PostHogWorkflow):)workflow.logger.warning("task_management_sandbox_replacement_budget_persist_failed",- run_id=self._run_id,- consecutive_failures=failures,+ extra={"run_id": self._run_id, "consecutive_failures": failures},)if failures == 0:returndelay_seconds = min(2 ** (failures - 1), MAX_SANDBOX_REPLACEMENT_BACKOFF_SECONDS)workflow.logger.warning("task_management_sandbox_replacement_backoff",- run_id=self._run_id,- consecutive_failures=failures,- delay_seconds=delay_seconds,+ extra={"run_id": self._run_id, "consecutive_failures": failures, "delay_seconds": delay_seconds},)await workflow.sleep(delay_seconds)@@ -832,9 +821,7 @@ class TaskManagementWorkflow(PostHogWorkflow):self._record_sandbox_replacement_failure()workflow.logger.warning("task_management_closed_sandbox_recovered",- run_id=self._run_id,- requeued=requeued,- error=str(error),+ extra={"run_id": self._run_id, "requeued": requeued, "error": str(error)},)self._pending_ack_slots.clear()self._child_acks.clear()@@ -864,11 +851,13 @@ class TaskManagementWorkflow(PostHogWorkflow):assert completion is not Noneworkflow.logger.info("task_management_sandbox_session_ended",- run_id=self._run_id,- success=completion.success,- sandbox_id=completion.sandbox_id,- timed_out=completion.timed_out,- error=completion.error,+ extra={+ "run_id": self._run_id,+ "success": completion.success,+ "sandbox_id": completion.sandbox_id,+ "timed_out": completion.timed_out,+ "error": completion.error,+ },)# Best-effort re-queue: any followup slot still awaiting an ACK at@@ -882,9 +871,7 @@ class TaskManagementWorkflow(PostHogWorkflow):requeued += 1if requeued:workflow.logger.warning(- "task_management_unacked_followups_requeued",- run_id=self._run_id,- count=requeued,+ "task_management_unacked_followups_requeued", extra={"run_id": self._run_id, "count": requeued})self._record_sandbox_replacement_failure()@@ -919,9 +906,7 @@ class TaskManagementWorkflow(PostHogWorkflow):)except Exception as e:workflow.logger.warning(- "task_management_restore_pending_failed",- run_id=self._run_id,- error=str(e),+ "task_management_restore_pending_failed", extra={"run_id": self._run_id, "error": str(e)})returnif not result.followups:@@ -952,9 +937,7 @@ class TaskManagementWorkflow(PostHogWorkflow):# call detects state-vs-DB equality and skips a redundant write.self._last_persisted_followups = [asdict(f) for f in self._pending_external_followups]workflow.logger.info(- "task_management_restored_pending_followups",- run_id=self._run_id,- count=len(result.followups),+ "task_management_restored_pending_followups", extra={"run_id": self._run_id, "count": len(result.followups)})async def _persist_pending_followups(self) -> bool:@@ -994,9 +977,7 @@ class TaskManagementWorkflow(PostHogWorkflow):return Trueexcept Exception as e:workflow.logger.warning(- "task_management_persist_pending_failed",- run_id=self._run_id,- error=str(e),+ "task_management_persist_pending_failed", extra={"run_id": self._run_id, "error": str(e)})return False@@ -1113,9 +1094,7 @@ class TaskManagementWorkflow(PostHogWorkflow):) -> bool | None:if self._sandbox_workflow_id is None:workflow.logger.warning(- "task_management_followup_dropped_no_sandbox",- run_id=self._run_id,- source=source,+ "task_management_followup_dropped_no_sandbox", extra={"run_id": self._run_id, "source": source})return Noneack_id = self._new_ack_id()@@ -1157,9 +1136,7 @@ class TaskManagementWorkflow(PostHogWorkflow):# branch the design relies on.workflow.logger.warning("task_management_signal_followup_failed",- run_id=self._run_id,- source=source,- error=str(e),+ extra={"run_id": self._run_id, "source": source, "error": str(e)},)return True@@ -1183,9 +1160,7 @@ class TaskManagementWorkflow(PostHogWorkflow):await self._recover_closed_sandbox(e)returnworkflow.logger.warning(- "task_management_signal_complete_failed",- run_id=self._run_id,- error=str(e),+ "task_management_signal_complete_failed", extra={"run_id": self._run_id, "error": str(e)})async def _retry_stale_acks(self) -> None:@@ -1205,18 +1180,14 @@ class TaskManagementWorkflow(PostHogWorkflow):if slot.retry_count >= MAX_ACK_RETRIES:workflow.logger.warning("task_management_ack_retry_exhausted",- run_id=self._run_id,- ack_id=ack_id,- signal_name=slot.signal_name,+ extra={"run_id": self._run_id, "ack_id": ack_id, "signal_name": slot.signal_name},)self._pending_ack_slots.pop(ack_id, None)continueif slot.signal_args is None:workflow.logger.warning("task_management_ack_retry_skipped_no_args",- run_id=self._run_id,- ack_id=ack_id,- signal_name=slot.signal_name,+ extra={"run_id": self._run_id, "ack_id": ack_id, "signal_name": slot.signal_name},)self._pending_ack_slots.pop(ack_id, None)continue@@ -1226,10 +1197,12 @@ class TaskManagementWorkflow(PostHogWorkflow):slot.retry_count += 1workflow.logger.info("task_management_ack_retry",- run_id=self._run_id,- ack_id=ack_id,- signal_name=slot.signal_name,- retry_count=slot.retry_count,+ extra={+ "run_id": self._run_id,+ "ack_id": ack_id,+ "signal_name": slot.signal_name,+ "retry_count": slot.retry_count,+ },)except Exception as e:if _child_cannot_receive_signals(e) and _patch_enabled(_PATCH_ID_CLOSED_CHILD_ACK_RETRY_RECOVERY):@@ -1239,10 +1212,7 @@ class TaskManagementWorkflow(PostHogWorkflow):# at the next deadline rather than push it out by ACK_TIMEOUT.workflow.logger.warning("task_management_ack_retry_failed",- run_id=self._run_id,- ack_id=ack_id,- signal_name=slot.signal_name,- error=str(e),+ extra={"run_id": self._run_id, "ack_id": ack_id, "signal_name": slot.signal_name, "error": str(e)},)def _new_ack_id(self) -> str:@@ -1262,10 +1232,7 @@ class TaskManagementWorkflow(PostHogWorkflow):# No PR will ever appear — stop the CI loop entirely so the# CI timer branch drops out of the wait set.self._ci_repetitions = MAX_CI_REPETITIONS- workflow.logger.info(- "task_management_ci_loop_stopped_no_pr",- run_id=self._run_id,- )+ workflow.logger.info("task_management_ci_loop_stopped_no_pr", extra={"run_id": self._run_id})case CIFollowUpDecision.SKIP:# Bound the next get_pr_context call to +CI_FOLLOW_UP_DELAY.# Mirrors process_task: without this, the next iteration@@ -1286,9 +1253,7 @@ class TaskManagementWorkflow(PostHogWorkflow):return CIFollowUpDecision.NO_PRif pr_context.pr_state in ("closed", "merged"):workflow.logger.info(- "task_management_ci_skipped_pr_closed",- run_id=self._run_id,- pr_url=pr_context.pr_url,+ "task_management_ci_skipped_pr_closed", extra={"run_id": self._run_id, "pr_url": pr_context.pr_url})return CIFollowUpDecision.SKIPfingerprint_changed = self._pr_fingerprint != pr_context.fingerprint@@ -1305,23 +1270,23 @@ class TaskManagementWorkflow(PostHogWorkflow):self._pr_unresolved_threads = pr_context.unresolved_threadsif not fingerprint_changed and not new_feedback:workflow.logger.info(- "task_management_ci_skipped_pr_unchanged",- run_id=self._run_id,- pr_url=pr_context.pr_url,+ "task_management_ci_skipped_pr_unchanged", extra={"run_id": self._run_id, "pr_url": pr_context.pr_url})return CIFollowUpDecision.SKIPself._pr_fingerprint = pr_context.fingerprintfire = (fingerprint_changed and is_pr_actionable(pr_context)) or new_feedbackworkflow.logger.info("task_management_ci_decision",- run_id=self._run_id,- pr_url=pr_context.pr_url,- ci_status=pr_context.ci_status,- changes_requested=pr_context.changes_requested,- unresolved_threads=pr_context.unresolved_threads,- new_feedback=new_feedback,- fire=fire,- repetitions=self._ci_repetitions,+ extra={+ "run_id": self._run_id,+ "pr_url": pr_context.pr_url,+ "ci_status": pr_context.ci_status,+ "changes_requested": pr_context.changes_requested,+ "unresolved_threads": pr_context.unresolved_threads,+ "new_feedback": new_feedback,+ "fire": fire,+ "repetitions": self._ci_repetitions,+ },)return CIFollowUpDecision.FIRE if fire else CIFollowUpDecision.SKIPdiff --git a/products/web_analytics/backend/temporal/digest_notification/workflows.py b/products/web_analytics/backend/temporal/digest_notification/workflows.pyindex bddf4556fa97..54078de69a59 100644--- a/products/web_analytics/backend/temporal/digest_notification/workflows.py+++ b/products/web_analytics/backend/temporal/digest_notification/workflows.py@@ -68,10 +68,12 @@ class WADigestNotificationWorkflow(PostHogWorkflow):if page.batches:workflow.logger.info("Fanning out WA digest notification page",- batches=len(page.batches),- orgs=page.org_count,- cursor=cursor,- next_cursor=page.cursor,+ extra={+ "batches": len(page.batches),+ "orgs": page.org_count,+ "cursor": cursor,+ "next_cursor": page.cursor,+ },)batch_count += len(page.batches)diff --git a/products/web_analytics/backend/temporal/weekly_digest/workflows.py b/products/web_analytics/backend/temporal/weekly_digest/workflows.pyindex 3f8ba9c2efcb..126d5cd70c7a 100644--- a/products/web_analytics/backend/temporal/weekly_digest/workflows.py+++ b/products/web_analytics/backend/temporal/weekly_digest/workflows.py@@ -69,10 +69,12 @@ class WAWeeklyDigestWorkflow(PostHogWorkflow):if page.batches:workflow.logger.info("Fanning out WA digest page",- batches=len(page.batches),- orgs=page.org_count,- cursor=cursor,- next_cursor=page.cursor,+ extra={+ "batches": len(page.batches),+ "orgs": page.org_count,+ "cursor": cursor,+ "next_cursor": page.cursor,+ },)batch_count += len(page.batches)