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(data-warehouse): attach source context to captured import exceptions (#72877)

Tom Owers8e76305d43d7
diff --git a/posthog/exceptions_capture.py b/posthog/exceptions_capture.py
index 87d6f4d14938..a80eb12fdec5 100644
--- a/posthog/exceptions_capture.py
+++ b/posthog/exceptions_capture.py
@@ -1,3 +1,44 @@
+import contextvars
+from collections.abc import Iterator
+from contextlib import contextmanager
+
+# Ambient properties merged into every capture_exception raised within the current execution
+# context. Lets a long-running subsystem (e.g. a data warehouse import) tag captured exceptions
+# with the job/source they belong to without threading context through every call site. This is
+# exception-only and never touches ClickHouse query tags.
+_ambient_exception_properties: contextvars.ContextVar[dict[str, object] | None] = contextvars.ContextVar(
+ "ambient_exception_properties", default=None
+)
+
+
+def ambient_exception_properties() -> dict[str, object]:
+ return _ambient_exception_properties.get() or {}
+
+
+def bind_exception_context(**properties: object) -> None:
+ """Merge properties into the ambient exception context for the current execution context.
+
+ Fire-and-forget: relies on per-task contextvar isolation (temporal activities and celery tasks
+ each run in a fresh context), matching how log/query tags are bound at activity entry. Use
+ `exception_context` instead when you need the properties scoped and reset (tests, nested spans).
+ """
+ _ambient_exception_properties.set({**ambient_exception_properties(), **properties})
+
+
+@contextmanager
+def exception_context(**properties: object) -> Iterator[None]:
+ """Scope ambient exception properties to a block, resetting them on exit.
+
+ Merges with any properties already in context, so nested contexts accumulate.
+ """
+ merged = {**ambient_exception_properties(), **properties}
+ token = _ambient_exception_properties.set(merged)
+ try:
+ yield
+ finally:
+ _ambient_exception_properties.reset(token)
+
+
def celery_properties() -> dict:
try:
from celery import current_task
@@ -26,6 +67,9 @@ def capture_exception(error=None, additional_properties=None):
properties = get_query_tags().model_dump(exclude_none=True)
+ # Ambient context first, then explicit call-site properties so the latter win on collision.
+ properties.update(ambient_exception_properties())
+
if additional_properties:
properties.update(additional_properties)
diff --git a/posthog/test/test_exceptions_capture.py b/posthog/test/test_exceptions_capture.py
new file mode 100644
index 000000000000..dbda47abb0d3
--- /dev/null
+++ b/posthog/test/test_exceptions_capture.py
@@ -0,0 +1,46 @@
+from unittest import mock
+
+from posthog.exceptions_capture import (
+ ambient_exception_properties,
+ bind_exception_context,
+ capture_exception,
+ exception_context,
+)
+
+_MODULE = "posthog.exceptions_capture"
+
+
+def test_exception_context_scopes_and_restores_properties():
+ baseline = dict(ambient_exception_properties())
+ with exception_context(source="a"):
+ assert ambient_exception_properties()["source"] == "a"
+ with exception_context(schema="b"):
+ # Nested contexts accumulate.
+ assert ambient_exception_properties() == {**baseline, "source": "a", "schema": "b"}
+ assert "schema" not in ambient_exception_properties()
+ assert ambient_exception_properties() == baseline
+
+
+def test_capture_exception_merges_ambient_and_explicit_properties():
+ # Ambient context flows into captured exceptions; explicit call-site properties win on collision.
+ with (
+ mock.patch("posthog.clickhouse.query_tagging.get_query_tags") as mock_tags,
+ mock.patch("posthoganalytics.api_key", "phc_test"),
+ mock.patch("posthoganalytics.capture_exception", return_value=None) as mock_capture,
+ ):
+ mock_tags.return_value.model_dump.return_value = {}
+ error = ValueError("boom")
+ with exception_context(warehouse_sources_source_type="Elasticsearch", warehouse_sources_job_id="j1"):
+ capture_exception(error, additional_properties={"warehouse_sources_job_id": "override", "extra": 1})
+
+ props = mock_capture.call_args.kwargs["properties"]
+ assert props["warehouse_sources_source_type"] == "Elasticsearch"
+ assert props["warehouse_sources_job_id"] == "override"
+ assert props["extra"] == 1
+
+
+def test_bind_exception_context_is_fire_and_forget_within_scope():
+ with exception_context():
+ bind_exception_context(k="v")
+ assert ambient_exception_properties()["k"] == "v"
+ assert "k" not in ambient_exception_properties()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/job_context.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/job_context.py
index 7d74b2cbe96e..fbc0f284c2ef 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/job_context.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/job_context.py
@@ -26,6 +26,8 @@ from typing import TYPE_CHECKING
from structlog.contextvars import bind_contextvars, unbind_contextvars
+from posthog.exceptions_capture import bind_exception_context, exception_context
+
if TYPE_CHECKING:
import uuid
@@ -37,6 +39,11 @@ class JobContext:
external_data_source_id: str
external_data_schema_id: str
external_data_job_id: str
+ # Optional, human-facing sync metadata. Not bound as log fields (transports keep their
+ # existing label set) but attached to captured exceptions for debugging.
+ schema_name: str | None = None
+ sync_type: str | None = None
+ pipeline_version: str | None = None
def as_log_fields(self) -> dict[str, int | str]:
return {
@@ -47,6 +54,24 @@ class JobContext:
"external_data_job_id": self.external_data_job_id,
}
+ def as_exception_properties(self) -> dict[str, str | int]:
+ """Source/job identity attached to every exception captured during the sync, so a generic
+ pipeline failure (e.g. a PyArrow type mismatch) can be attributed to a connector."""
+ properties: dict[str, str | int] = {
+ "warehouse_sources_source_type": self.source_type,
+ "warehouse_sources_source_id": self.external_data_source_id,
+ "warehouse_sources_schema_id": self.external_data_schema_id,
+ "warehouse_sources_job_id": self.external_data_job_id,
+ "team_id": self.team_id,
+ }
+ if self.schema_name is not None:
+ properties["warehouse_sources_schema_name"] = self.schema_name
+ if self.sync_type is not None:
+ properties["warehouse_sources_sync_type"] = self.sync_type
+ if self.pipeline_version is not None:
+ properties["warehouse_sources_pipeline_version"] = self.pipeline_version
+ return properties
+
_current_job_context: contextvars.ContextVar[JobContext | None] = contextvars.ContextVar(
"data_imports_job_context", default=None
@@ -72,6 +97,9 @@ def _make_context(
external_data_source_id: str | uuid.UUID,
external_data_schema_id: str | uuid.UUID,
external_data_job_id: str,
+ schema_name: str | None = None,
+ sync_type: str | None = None,
+ pipeline_version: str | None = None,
) -> JobContext:
return JobContext(
team_id=team_id,
@@ -79,6 +107,9 @@ def _make_context(
external_data_source_id=str(external_data_source_id),
external_data_schema_id=str(external_data_schema_id),
external_data_job_id=external_data_job_id,
+ schema_name=schema_name,
+ sync_type=sync_type,
+ pipeline_version=pipeline_version,
)
@@ -89,8 +120,12 @@ def bind_job_context(
external_data_source_id: str | uuid.UUID,
external_data_schema_id: str | uuid.UUID,
external_data_job_id: str,
+ schema_name: str | None = None,
+ sync_type: str | None = None,
+ pipeline_version: str | None = None,
) -> JobContext:
- """Set the current `JobContext` and bind matching structlog contextvars.
+ """Set the current `JobContext`, bind matching structlog contextvars, and attach the source
+ to every exception captured for the rest of this sync.
Mirrors the existing pattern in `import_data_activity_sync` where
`bind_contextvars(team_id=...)` is called without an explicit unbind —
@@ -103,6 +138,9 @@ def bind_job_context(
external_data_source_id=external_data_source_id,
external_data_schema_id=external_data_schema_id,
external_data_job_id=external_data_job_id,
+ schema_name=schema_name,
+ sync_type=sync_type,
+ pipeline_version=pipeline_version,
)
_current_job_context.set(ctx)
bind_contextvars(
@@ -111,6 +149,7 @@ def bind_job_context(
external_data_schema_id=ctx.external_data_schema_id,
external_data_job_id=ctx.external_data_job_id,
)
+ bind_exception_context(**ctx.as_exception_properties())
return ctx
@@ -122,12 +161,14 @@ def scoped_job_context(
external_data_source_id: str | uuid.UUID,
external_data_schema_id: str | uuid.UUID,
external_data_job_id: str,
+ schema_name: str | None = None,
+ sync_type: str | None = None,
+ pipeline_version: str | None = None,
) -> Iterator[JobContext]:
"""Context-manager variant for tests / synthetic call sites.
- Resets the contextvar and unbinds structlog contextvars on exit so
- test isolation isn't dependent on subsequent activities overwriting
- state.
+ Resets the contextvar, unbinds structlog contextvars, and clears the exception context on exit
+ so test isolation isn't dependent on subsequent activities overwriting state.
"""
ctx = _make_context(
team_id=team_id,
@@ -135,6 +176,9 @@ def scoped_job_context(
external_data_source_id=external_data_source_id,
external_data_schema_id=external_data_schema_id,
external_data_job_id=external_data_job_id,
+ schema_name=schema_name,
+ sync_type=sync_type,
+ pipeline_version=pipeline_version,
)
token = _current_job_context.set(ctx)
bind_contextvars(
@@ -144,7 +188,8 @@ def scoped_job_context(
external_data_job_id=ctx.external_data_job_id,
)
try:
- yield ctx
+ with exception_context(**ctx.as_exception_properties()):
+ yield ctx
finally:
_current_job_context.reset(token)
unbind_contextvars(*_BOUND_LOG_FIELD_NAMES)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_job_context.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_job_context.py
index d931389cdf1f..6b071a7a9bd2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_job_context.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_job_context.py
@@ -1,3 +1,5 @@
+from posthog.exceptions_capture import ambient_exception_properties
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common import job_context
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import context as http_context
from products.warehouse_sources.backend.temporal.data_imports.sources.common.job_context import (
@@ -33,6 +35,41 @@ def test_scoped_job_context_sets_and_resets():
assert current_job_context() is None
+def test_scoped_job_context_binds_and_clears_exception_properties():
+ # The source/job identity must reach the ambient exception context so any exception captured
+ # during the sync carries it — and must be restored on exit so it doesn't leak between jobs.
+ baseline = dict(ambient_exception_properties())
+ with scoped_job_context(
+ team_id=1,
+ source_type="Elasticsearch",
+ external_data_source_id="s",
+ external_data_schema_id="sc",
+ external_data_job_id="j",
+ schema_name="orders",
+ sync_type="full_refresh",
+ ):
+ props = ambient_exception_properties()
+ assert props["warehouse_sources_source_type"] == "Elasticsearch"
+ assert props["warehouse_sources_schema_name"] == "orders"
+ assert props["warehouse_sources_sync_type"] == "full_refresh"
+ assert props["warehouse_sources_job_id"] == "j"
+ assert ambient_exception_properties() == baseline
+
+
+def test_exception_properties_omit_absent_optional_fields():
+ ctx = job_context.JobContext(
+ team_id=1,
+ source_type="Elasticsearch",
+ external_data_source_id="s",
+ external_data_schema_id="sc",
+ external_data_job_id="j",
+ )
+ properties = ctx.as_exception_properties()
+ assert "warehouse_sources_schema_name" not in properties
+ assert "warehouse_sources_sync_type" not in properties
+ assert "warehouse_sources_pipeline_version" not in properties
+
+
def test_bind_job_context_coerces_uuid_like_ids_to_str():
import uuid
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
index e8aab6793e14..459d1bc3fce4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py
@@ -129,6 +129,9 @@ async def import_data_activity_sync(inputs: ImportDataActivityInputs) -> Pipelin
external_data_source_id=inputs.source_id,
external_data_schema_id=inputs.schema_id,
external_data_job_id=inputs.run_id,
+ schema_name=model.schema.name if model.schema is not None else None,
+ sync_type=model.schema.sync_type if model.schema is not None else None,
+ pipeline_version=model.pipeline_version,
)
job_inputs = PipelineInputs(