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.

fix(data-imports): capture and propagate context for OSError in get_delta_table (#73148)

Tom Owers9bf06db26dbc
diff --git a/posthog/temporal/common/posthog_client.py b/posthog/temporal/common/posthog_client.py
index f94ae1458905..1e6e9d7ecac3 100644
--- a/posthog/temporal/common/posthog_client.py
+++ b/posthog/temporal/common/posthog_client.py
@@ -15,6 +15,7 @@ from temporalio.worker import (
)
from posthog.egress.transport.transport import EgressBudgetExhausted
+from posthog.exceptions_capture import ambient_exception_properties
from posthog.temporal.common.interceptor import ALL_TASK_QUEUES
from posthog.temporal.common.logger import get_write_only_logger
@@ -75,6 +76,11 @@ class _PostHogClientActivityInboundInterceptor(ActivityInboundInterceptor):
activity_info = activity.info()
capture_kwargs = {
"properties": {
+ # Ambient properties (e.g. warehouse-sources JobContext) first so the explicit
+ # Temporal fields below win on collision — this is the last chance to attach
+ # them, since an exception reaching here escaped uncaught past any inner
+ # capture_exception() call that would otherwise have merged them in.
+ **ambient_exception_properties(),
"temporal.execution_type": "activity",
"module": input.fn.__module__ + "." + input.fn.__qualname__,
"temporal.activity.attempt": activity_info.attempt,
@@ -110,6 +116,9 @@ class _PostHogClientWorkflowInterceptor(WorkflowInboundInterceptor):
workflow_info = workflow.info()
capture_kwargs = {
"properties": {
+ # See the matching comment in _PostHogClientActivityInboundInterceptor:
+ # ambient properties first so the explicit Temporal fields below win.
+ **ambient_exception_properties(),
"temporal.execution_type": "workflow",
"module": input.run_fn.__module__ + "." + input.run_fn.__qualname__,
"temporal.workflow.task_queue": workflow_info.task_queue,
diff --git a/posthog/temporal/tests/common/test_error_tracking.py b/posthog/temporal/tests/common/test_error_tracking.py
index 83a7dda2512e..3684693b8fe0 100644
--- a/posthog/temporal/tests/common/test_error_tracking.py
+++ b/posthog/temporal/tests/common/test_error_tracking.py
@@ -15,6 +15,7 @@ from temporalio.exceptions import ApplicationError, CancelledError
from temporalio.worker import UnsandboxedWorkflowRunner, Worker
from posthog.egress.github.transport import GitHubEgressBudgetExhausted
+from posthog.exceptions_capture import bind_exception_context
from posthog.temporal.common.posthog_client import PostHogClientInterceptor
@@ -80,6 +81,33 @@ async def failing_activity_with_properties_to_log(inputs: OptionallyFailingInput
raise ValueError("Activity failed!")
+async def failing_activity_with_ambient_context(inputs: OptionallyFailingInputs) -> None:
+ if inputs.fail:
+ # Fire-and-forget binding, mirroring how e.g. warehouse-sources' JobContext attaches
+ # sync context: no `with` block, so it stays bound for the rest of this activity
+ # attempt (including an exception that escapes uncaught to the interceptor below).
+ bind_exception_context(warehouse_sources_source_type="Stripe")
+ raise ValueError("Activity failed!")
+
+
+class FailingWorkflowWithAmbientContext:
+ @workflow.run
+ async def run(self, inputs: OptionallyFailingInputs) -> None:
+ await workflow.execute_activity(
+ failing_activity_with_ambient_context,
+ inputs,
+ start_to_close_timeout=dt.timedelta(minutes=1),
+ heartbeat_timeout=dt.timedelta(seconds=5),
+ retry_policy=RetryPolicy(
+ initial_interval=dt.timedelta(seconds=1),
+ maximum_interval=dt.timedelta(seconds=1),
+ maximum_attempts=1,
+ ),
+ )
+
+
@activity.defn
async def cancelled_activity(inputs: OptionallyFailingInputs) -> None:
raise CancelledError()
@@ -197,6 +225,39 @@ async def test_exception_capture(fail: bool, capture_additional_properties: bool
mock_ph_capture.assert_not_called()
+async def test_ambient_exception_context_reaches_top_level_capture(temporal_client: Client):
+ """An exception that escapes an activity uncaught (nothing inside called capture_exception)
+ must still carry ambient exception context bound earlier in the same activity attempt — e.g.
+ warehouse-sources' JobContext, which attaches sync/job identity via bind_exception_context so a
+ generic pipeline failure can be attributed to the source that produced it."""
+ task_queue = "TEST-TASK-QUEUE"
+ workflow_id = str(uuid.uuid4())
+
+ with patch("posthog.temporal.common.posthog_client.capture_exception") as mock_ph_capture:
+ async with Worker(
+ temporal_client,
+ task_queue=task_queue,
+ workflows=[FailingWorkflowWithAmbientContext],
+ activities=[failing_activity_with_ambient_context],
+ interceptors=[PostHogClientInterceptor()],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ with pytest.raises(WorkflowFailureError):
+ await temporal_client.execute_workflow(
+ "FailingWorkflowWithAmbientContext",
+ OptionallyFailingInputs(fail=True),
+ id=workflow_id,
+ task_queue=task_queue,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+
+ assert mock_ph_capture.call_count == 1
+ activity_call = mock_ph_capture.call_args_list[0]
+ assert activity_call[1]["properties"]["warehouse_sources_source_type"] == "Stripe"
+ assert activity_call[1]["properties"]["temporal.execution_type"] == "activity"
+
+
@pytest.mark.asyncio
async def test_cancellation_is_not_captured(temporal_client: Client):
"""A cancelled activity (worker drain, timeout, cancel) is expected control flow, not a defect,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
index 51856b5a9427..87821ee4ac3f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/delta_table_helper.py
@@ -282,9 +282,18 @@ class DeltaTableHelper:
delta_uri = await self._get_delta_table_uri()
storage_options = self._get_credentials()
- is_delta = await asyncio.to_thread(
- deltalake.DeltaTable.is_deltatable, table_uri=delta_uri, storage_options=storage_options
- )
+ try:
+ is_delta = await asyncio.to_thread(
+ deltalake.DeltaTable.is_deltatable, table_uri=delta_uri, storage_options=storage_options
+ )
+ except Exception as e:
+ # Mirrors the DeltaTable() open below: capture before propagating. Callers range from
+ # best-effort maintenance to the main write path, so this can't safely swallow the
+ # error and report "no table" here — that would trip should_overwrite_table for a
+ # table that actually exists, risking data loss.
+ capture_exception(e)
+ raise
+
if is_delta:
try:
return await asyncio.to_thread(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py
index c568e4f2c369..7442d8c198c4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline/test/test_delta_table_helper.py
@@ -379,6 +379,32 @@ class TestGetDeltaTableUnrecoverableErrors:
s3._rm.assert_not_awaited()
assert helper.is_first_sync is False
+ @pytest.mark.asyncio
+ async def test_is_deltatable_failure_is_captured_and_reraised(self):
+ """The `is_deltatable` existence check is a separate S3 call from the DeltaTable() open
+ handled above, and callers span best-effort maintenance to the main write path, so a
+ failure here can't be swallowed as "no table" (that would trip should_overwrite_table and
+ wipe an existing table) — it must be captured for visibility and reraised."""
+ helper = DeltaTableHelper(resource_name="t", job=MagicMock(), logger=_make_logger())
+ delta_uri = "s3://bucket/team_id/job_id/t"
+
+ module = "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.delta_table_helper"
+ with (
+ patch.object(helper, "_get_delta_table_uri", AsyncMock(return_value=delta_uri)),
+ patch(f"{module}.deltalake.DeltaTable") as mock_delta_table,
+ patch(f"{module}.capture_exception") as mock_capture,
+ ):
+ mock_delta_table.is_deltatable.side_effect = OSError(
+ "Generic S3 error: Received redirect without LOCATION, this normally indicates "
+ "an incorrectly configured region"
+ )
+
+ with pytest.raises(OSError, match="Received redirect without LOCATION"):
+ await helper.get_delta_table()
+
+ mock_capture.assert_called_once()
+ assert helper.is_first_sync is False
+
class TestWriteToDeltalakeCommitMetadataPassThrough:
"""Covers that commit_metadata is forwarded to deltalake.write_deltalake as CommitProperties."""