: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(data-warehouse): stop reporting refused staging writes as bugs (#104466)
Tom Owerseafac2a35288
diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.pyindex 301beab97011..1a622ef3f601 100644--- a/posthog/temporal/data_modeling/activities/materialize_view.py+++ b/posthog/temporal/data_modeling/activities/materialize_view.py@@ -331,7 +331,7 @@ class _CDPRowSink:# A missing write grant on the cdp_producer/ prefix is the same anticipated# provisioning gap `_list_files_to_produce` already tolerates quietly for reads (see its# `except PermissionError` branch) — not a bug worth paging on.- if not _is_s3_permission_denied(e):+ if not _is_s3_permission_denied(e) and not isinstance(e, NonReportableError):capture_exception(e)await self._logger.awarning(f"Failed to stage rows for CDP; discarding this run's staged rows: {e}")self.enabled = False@@ -900,7 +900,8 @@ async def _clear_person_property_staging(sink: PersonPropertyRowSink, logger: Fiawait sink.clear()except Exception as e:await logger.awarning(f"Could not clear stale person-property staging: {e}")- capture_exception(e)+ if not isinstance(e, NonReportableError):+ capture_exception(e)async def _stage_person_property_batch(@@ -927,7 +928,8 @@ async def _stage_person_property_batch(await sink.logger.awarning(f"Failed to stage person-property batch {batch_index}: {e}")if fatal:raise- capture_exception(e)+ if not isinstance(e, NonReportableError):+ capture_exception(e)FAILED_UPDATE_REASON_PREFIX = "incremental update failed: "diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_producer.pyindex 729a49b3d413..e5dc720ce7c9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_producer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/cdp_producer.py@@ -27,6 +27,9 @@ from products.cdp.backend.models.hog_functions import HogFunctionfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_warehouse.backend.facade.api import aget_s3_client, ensure_bucket_existsfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.staging_object_store import (+ aretry_staged_write,+)from products.warehouse_sources.backend.temporal.data_imports.pipelines.helpers import build_table_namefrom products.warehouse_sources.backend.temporal.data_imports.util import PostHogInternalDatabaseErrorfrom products.workflows.backend.models.hog_flow.hog_flow import HogFlow@@ -287,14 +290,19 @@ class CDPProducer:if isinstance(table, pa.RecordBatch):table = pa.Table.from_batches([table])+ path = f"{self._get_path_prefix()}/chunk_{chunk}.parquet"# Write operations in pyarrow are CPU-bound, so run in thread pool- await asyncio.to_thread(- write_table,- table,- f"{self._get_path_prefix()}/chunk_{chunk}.parquet",- filesystem=self._get_fs(),- compression="zstd",- use_dictionary=True,+ await aretry_staged_write(+ lambda: asyncio.to_thread(+ write_table,+ table,+ path,+ filesystem=self._get_fs(),+ compression="zstd",+ use_dictionary=True,+ ),+ path=path,+ logger=self.logger,)async def produce_to_kafka_from_s3(self) -> None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.pyindex ac1ba431c543..13e7c278f95d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink.py@@ -23,6 +23,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.perbinding_staged_prefix,job_staged_prefix,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.staging_object_store import (+ ObjectStoreConfigurationError,+ aretry_staged_write,+ is_object_store_configuration_error,+)# A sibling job prefix whose newest file is older than this is considered abandoned (its consumer# never ran, or gave up retrying) and is swept. Anything younger may belong to a consumer that is@@ -142,13 +147,18 @@ class PersonPropertyRowSink:await self.logger.adebug(f"Staging person-property chunk {chunk} ({len(columns)} cols) to {self._get_path_prefix()}")- await asyncio.to_thread(- write_table,- projected,- f"{self._get_path_prefix()}/chunk_{self._attempt_token}_{chunk:06d}.parquet",- filesystem=self._get_fs(),- compression="zstd",- use_dictionary=True,+ path = f"{self._get_path_prefix()}/chunk_{self._attempt_token}_{chunk:06d}.parquet"+ await aretry_staged_write(+ lambda: asyncio.to_thread(+ write_table,+ projected,+ path,+ filesystem=self._get_fs(),+ compression="zstd",+ use_dictionary=True,+ ),+ path=path,+ logger=self.logger,)async def clear(self) -> None:@@ -168,8 +178,12 @@ class PersonPropertyRowSink:ran.The two clears are independent backstops, so a failure in one (e.g. a permissions error- deleting the own prefix) must not skip the other — the sweep always runs, and any- own-prefix error is re-raised only afterward.+ deleting the own prefix) must not skip the other — the sweep always runs, and any error is+ re-raised only afterward.++ Both clears address the same binding prefix with the same credentials, so a refused grant+ fails both. That is one configuration problem, so it is raised once, as a typed error that+ a retry cannot resolve."""async with aget_s3_client() as s3_client:own_prefix_error: Exception | None = None@@ -180,9 +194,21 @@ class PersonPropertyRowSink:passexcept Exception as e:own_prefix_error = e- await self._sweep_abandoned_sibling_prefixes(s3_client)- if own_prefix_error is not None:- raise own_prefix_error++ sweep_error: Exception | None = None+ try:+ await self._sweep_abandoned_sibling_prefixes(s3_client)+ except Exception as e:+ sweep_error = e++ failure = own_prefix_error or sweep_error+ if failure is None:+ return+ if is_object_store_configuration_error(failure):+ raise ObjectStoreConfigurationError(+ f"Object store refused to clear staged person-property rows under {self._get_binding_prefix()}"+ ) from failure+ raise failureasync def _sweep_abandoned_sibling_prefixes(self, s3_client: Any) -> None:try:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.pyindex e308e44340b7..27f9b8c0a646 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/person_property_row_sink_test.py@@ -19,13 +19,25 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.perABANDONED_STAGED_PREFIX_TTL,PersonPropertyRowSink,)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.staging_object_store import (+ ObjectStoreConfigurationError,+)_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.person_property_row_sink"+_STAGING_MODULE = "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.staging_object_store"+++def _aws_write_error(code: str, detail: str) -> OSError:+ return OSError(+ "When initiating multiple part upload for key 'chunk_0.parquet' in bucket 'example-bucket': "+ f"AWS Error {code} during CreateMultipartUpload operation: {detail}"+ )def _sink(is_incremental: bool = False, binding: WarehouseBinding | None = None) -> PersonPropertyRowSink:logger = MagicMock()logger.adebug = AsyncMock()+ logger.awarning = AsyncMock()return PersonPropertyRowSink(team_id=1,binding=binding or schema_binding("schema-1"),@@ -204,6 +216,60 @@ async def test_stage_chunk_filenames_are_unique_per_attempt():assert len(set(paths)) == 2+ [+ (+ "transient_internal_error",+ _aws_write_error("INTERNAL_FAILURE", "We encountered an internal error. Please try again."),+ 2,+ None,+ ),+ ("refused_access_denied", _aws_write_error("ACCESS_DENIED", "Access Denied"), 1, ObjectStoreConfigurationError),+ (+ "refused_wrong_endpoint",+ _aws_write_error("UNKNOWN (HTTP status 301)", "Unable to parse ExceptionName: PermanentRedirect"),+ 1,+ ObjectStoreConfigurationError,+ ),+ ("unclassified_failure", RuntimeError("staging blew up"), 1, RuntimeError),+ ]+)+async def test_stage_chunk_retries_only_a_transient_object_store_failure(_name, error, expected_attempts, raises):+ # Creating the multipart upload is a single network call, so a blip on it drops the whole chunk+ # unless it is retried. A refused write is the deployment's configuration, which no retry+ # changes, so it fails once as a typed error instead of stalling the sync and paging someone.+ sink = _sink()+ to_thread = AsyncMock(side_effect=[error, None])++ with (+ patch(f"{_MODULE}.person_property_projection_for", return_value=[_projection("distinct_id", "plan")]),+ patch.object(sink, "_get_fs", return_value=MagicMock()),+ patch(f"{_MODULE}.asyncio.to_thread", new=to_thread),+ patch(f"{_STAGING_MODULE}.asyncio.sleep", new=AsyncMock()),+ ):+ if raises is not None:+ with pytest.raises(raises):+ await sink.stage_chunk(chunk=0, table=_table())+ else:+ await sink.stage_chunk(chunk=0, table=_table())++ assert to_thread.await_count == expected_attempts+++async def test_clear_raises_one_configuration_error_when_the_sweep_is_refused():+ # A refused listing of the binding prefix is the same missing grant the own-prefix delete hits,+ # so it must surface as the one typed configuration error rather than as a second raw failure.+ sink = _sink()+ s3_client = _s3_client()+ s3_client._find = AsyncMock(side_effect=PermissionError("Access Denied"))++ with patch(f"{_MODULE}.aget_s3_client", return_value=_FakeS3ClientCM(s3_client)):+ with pytest.raises(ObjectStoreConfigurationError):+ await sink.clear()++@parameterized.expand([("local_setup", True), ("non_local_setup", False)])def test_get_fs_reuses_the_same_filesystem_across_calls(_name, use_local_setup):# stage_chunk() calls _get_fs() once per chunk over a whole sync (potentially thousands of@@ -241,6 +307,7 @@ async def test_clear_still_sweeps_abandoned_siblings_when_own_prefix_delete_fail# A permissions error (or any other non-FileNotFoundError) deleting the own prefix must not# skip the sibling-sweep backstop, which is an independent cleanup — otherwise abandoned sibling# prefixes from crashed jobs never get swept on every run where the own-prefix delete fails.+ # The refusal itself is the deployment's configuration, so it is re-raised as the typed error.sink = _sink()stale_file = f"{sink._get_binding_prefix()}/job-old/chunk_0.parquet"s3_client = _s3_client(@@ -249,7 +316,7 @@ async def test_clear_still_sweeps_abandoned_siblings_when_own_prefix_delete_fails3_client._rm = AsyncMock(side_effect=[PermissionError("Access Denied"), None])with patch(f"{_MODULE}.aget_s3_client", return_value=_FakeS3ClientCM(s3_client)):- with pytest.raises(PermissionError):+ with pytest.raises(ObjectStoreConfigurationError):await sink.clear()removed = [call.args[0] for call in s3_client._rm.await_args_list]diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/staging_object_store.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/staging_object_store.pynew file mode 100644index 000000000000..9e013e8abc88--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/staging_object_store.py@@ -0,0 +1,80 @@+"""The object-store boundary the pipeline's parquet staging sinks share."""++import asyncio+from collections.abc import Callable, Coroutine+from typing import Any++from structlog.types import FilteringBoundLogger++from posthog.temporal.common.errors import NonReportableError++# AWS error codes that pyarrow's S3FileSystem puts in its OSError message when the object store+# refuses a request outright instead of failing to serve it. ACCESS_DENIED means the worker holds+# no grant on the staging prefix. PermanentRedirect means the bucket it addressed lives in another+# region, which is what a staging bucket setting that names a bucket we do not own looks like.+# Neither clears on a retry, because both describe the deployment's configuration and not the state+# of the store.+PERMANENT_OBJECT_STORE_ERRORS = ("ACCESS_DENIED", "PermanentRedirect")++# Initiating the upload is a single network call, so one blip on it costs the whole chunk. Three+# attempts spend at most 6s of backoff, which is short against a sync that runs for minutes, and+# enough for the object store to serve a request that its own SDK-level retries could not.+_STAGED_WRITE_MAX_ATTEMPTS = 3+++class ObjectStoreConfigurationError(NonReportableError):+ """The object store refused a staging request for a reason that belongs to the deployment.++ A missing grant on the staging prefix, or a staging bucket setting that addresses a bucket in+ another region, fails every attempt of every run until someone changes the configuration.+ Subclassing ``NonReportableError`` keeps that known condition out of error tracking instead of+ minting an issue for each refused chunk.+ """+++def is_object_store_configuration_error(error: BaseException) -> bool:+ """True when the object store refused a staging request permanently.++ The two clients the sinks use report the same refusal differently. s3fs/aiobotocore, which+ clears the staged prefixes, maps an AccessDenied response onto the builtin ``PermissionError``.+ pyarrow's ``S3FileSystem``, which writes the staged parquet, sets no errno, so the refusal+ arrives as a plain ``OSError`` that carries the AWS error code in its message.+ """+ if isinstance(error, ObjectStoreConfigurationError | PermissionError):+ return True+ return isinstance(error, OSError) and any(needle in str(error) for needle in PERMANENT_OBJECT_STORE_ERRORS)+++async def aretry_staged_write(+ operation: Callable[[], Coroutine[Any, Any, None]], *, path: str, logger: FilteringBoundLogger+) -> None:+ """Run one staged parquet write, retrying a transient object-store failure with backoff.++ Pass a zero-arg callable that produces the awaitable, not the awaitable itself, so a retry can+ reissue the write.++ A refused write raises ``ObjectStoreConfigurationError`` on the first attempt, because retrying+ a grant or an endpoint that the deployment got wrong only delays the same failure. An error the+ shared classifier does not recognize is not retried either, so a defect in the pipeline still+ fails as fast as it did before.+ """+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.errors import ( # noqa: PLC0415 — keeps the heavy deltalake dep off this module's top-level import path+ is_transient_object_store_error,+ )++ attempt = 0+ while True:+ attempt += 1+ try:+ await operation()+ return+ except Exception as e:+ if is_object_store_configuration_error(e):+ raise ObjectStoreConfigurationError(f"Object store refused the staged write to {path}") from e+ if attempt >= _STAGED_WRITE_MAX_ATTEMPTS or not is_transient_object_store_error(e):+ raise+ await logger.awarning(+ f"Transient object-store error staging {path} "+ f"(attempt {attempt}/{_STAGED_WRITE_MAX_ATTEMPTS}), retrying: {e}"+ )+ await asyncio.sleep(2**attempt)diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_cdp_producer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_cdp_producer.pyindex 074b58e463ea..cb149d02a405 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_cdp_producer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test/test_cdp_producer.py@@ -22,6 +22,9 @@ from products.warehouse_sources.backend.models.external_data_schema import Exterfrom products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTablefrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer import CDPProducer+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.staging_object_store import (+ ObjectStoreConfigurationError,+)from products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source import PostgresSourcefrom products.warehouse_sources.backend.temporal.data_imports.util import PostHogInternalDatabaseErrorfrom products.warehouse_sources.backend.types import ExternalDataSourceType@@ -957,6 +960,52 @@ def _make_view_producer(job_id: str) -> CDPProducer:return CDPProducer.for_view(team_id=1, saved_query_id="view_1", job_id=job_id, logger=mock.AsyncMock())+def _aws_write_error(code: str, detail: str) -> OSError:+ return OSError(+ "When initiating multiple part upload for key 'chunk_0.parquet' in bucket 'example-bucket': "+ f"AWS Error {code} during CreateMultipartUpload operation: {detail}"+ )+++ [+ (+ "transient_internal_error",+ _aws_write_error("INTERNAL_FAILURE", "We encountered an internal error. Please try again."),+ 2,+ None,+ ),+ ("refused_access_denied", _aws_write_error("ACCESS_DENIED", "Access Denied"), 1, ObjectStoreConfigurationError),+ ]+)+async def test_stage_chunk_retries_only_a_transient_object_store_failure(_name, error, expected_attempts, raises):+ # Creating the multipart upload is a single network call, so a blip on it drops the whole chunk+ # unless it is retried. A refused write is the deployment's configuration, which no retry+ # changes, so it fails once as a typed error instead of stalling the sync and paging someone.+ producer = _make_producer("job_1")+ test_data = pa.table({"id": [1], "name": ["Alice"]})++ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.cdp_producer.write_table",+ side_effect=[error, None],+ ) as mock_write_table,+ patch.object(producer, "_get_fs", return_value=MagicMock()),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.core.staging_object_store.asyncio.sleep",+ new=mock.AsyncMock(),+ ),+ ):+ if raises is not None:+ with pytest.raises(raises):+ await producer.stage_chunk(chunk=0, table=test_data)+ else:+ await producer.stage_chunk(chunk=0, table=test_data)++ assert mock_write_table.call_count == expected_attempts++@parameterized.expand([("local_setup", True), ("non_local_setup", False)])def test_get_fs_reuses_the_same_filesystem_across_calls(_name, use_local_setup):# stage_chunk() calls _get_fs() once per chunk over a whole sync (potentially thousands of