: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): retry transient S3 5xx/throttle during duckling registration (#66035)
Benjamin Knofe-Vider33b2103d3666
diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.pyindex 74b6bcb8eddb..851948251951 100644--- a/posthog/dags/events_backfill_to_duckling.py+++ b/posthog/dags/events_backfill_to_duckling.py@@ -405,6 +405,38 @@ def _connection_dropped(exc: BaseException) -> bool:return False+# Transient S3 responses (5xx and throttling) that DuckLake surfaces back through the PG+# wire while touching object storage: glob() listing the run's files, ducklake_add_data_files+# reading Parquet footers, and the ranged DELETE's data-file rewrites. S3 occasionally returns+# 503 SlowDown/Service Unavailable or 500 InternalError under load (e.g. right after an export+# writes a fan-out of files and registration immediately lists them).+_TRANSIENT_S3_MARKERS = (+ "http 503",+ "service unavailable",+ "http 500",+ "internalerror",+ "http 429",+ "too many requests",+ "slowdown",+ "slow down",+ "reduce your request rate",+)+++def _is_transient_s3_error(exc: BaseException) -> bool:+ """True when `exc` is a transient S3 5xx/throttle surfaced by duckgres while reading or+ listing object storage. Unlike _connection_dropped the worker is healthy — S3 just+ hiccuped — so it is retryable on the SAME connection (no reconnect) after a backoff.++ Gated on the message actually referencing object storage / an HTTP transport error so a+ genuine SQL error that merely contains a number like "500" can't be misclassified.+ """+ msg = str(exc).lower()+ if not any(token in msg for token in ("s3://", "http error", "http get", "http put", "http head")):+ return False+ return any(marker in msg for marker in _TRANSIENT_S3_MARKERS)++class _DuckgresSession:"""A duckgres connection that transparently reconnects to a fresh worker whenthe current worker drops mid-statement.@@ -443,35 +475,56 @@ class _DuckgresSession:return self._conndef run(self, what: str, op: Callable[[psycopg.Connection[Any]], Any]) -> Any:- """Run `op(conn)`, reconnecting to a fresh worker and retrying if the- worker/connection drops mid-statement. Non-connection errors propagate- immediately (no retry); the last connection error is re-raised once the- attempt budget is exhausted.+ """Run `op(conn)`, retrying on two recoverable failure classes:++ * worker/connection drop mid-statement → reconnect to a fresh worker and replay;+ * transient S3 5xx/throttle while touching object storage → replay on the SAME+ connection (the worker is healthy) after a backoff.++ Any other (genuine SQL/logic) error propagates immediately. The last recoverable+ error is re-raised once the attempt budget is exhausted. `op` MUST be idempotent —+ a replay can re-run an already-applied op (see the class docstring)."""last_exc: Exception | None = Nonefor attempt in range(1, self.MAX_ATTEMPTS + 1):try:return op(self._conn)except Exception as exc:- if not _connection_dropped(exc):+ dropped = _connection_dropped(exc)+ transient_s3 = _is_transient_s3_error(exc)+ if not (dropped or transient_s3):raiselast_exc = excif attempt == self.MAX_ATTEMPTS:break- self._context.log.warning(- f"duckgres worker/connection dropped during {what} "- f"(attempt {attempt}/{self.MAX_ATTEMPTS}); reconnecting to a fresh worker: {exc}"- )- logger.warning(- "duckling_duckgres_reconnect",- what=what,- attempt=attempt,- error=str(exc),- error_type=type(exc).__name__,- )- self._reconnect()+ if dropped:+ self._context.log.warning(+ f"duckgres worker/connection dropped during {what} "+ f"(attempt {attempt}/{self.MAX_ATTEMPTS}); reconnecting to a fresh worker: {exc}"+ )+ logger.warning(+ "duckling_duckgres_reconnect",+ what=what,+ attempt=attempt,+ error=str(exc),+ error_type=type(exc).__name__,+ )+ self._reconnect()+ else:+ # Transient S3 hiccup — the worker is fine, just back off and replay.+ self._context.log.warning(+ f"transient S3 error during {what} "+ f"(attempt {attempt}/{self.MAX_ATTEMPTS}); retrying after backoff: {exc}"+ )+ logger.warning(+ "duckling_duckgres_transient_s3_retry",+ what=what,+ attempt=attempt,+ error=str(exc),+ error_type=type(exc).__name__,+ )time.sleep(min(2**attempt, 30))- assert last_exc is not None # only reached after a connection-drop break+ assert last_exc is not None # only reached after a recoverable-error breakraise last_excdef _reconnect(self) -> None:diff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.pyindex 915f58cda9af..084a506a4265 100644--- a/posthog/dags/test_events_backfill_to_duckling.py+++ b/posthog/dags/test_events_backfill_to_duckling.py@@ -35,6 +35,7 @@ from posthog.dags.events_backfill_to_duckling import (_execute_export_with_retry,_get_cluster,_glob_run_files,+ _is_transient_s3_error,_resolve_duckling_target,_resolve_table_names,_set_table_partitioning,@@ -1103,6 +1104,54 @@ class TestConnectionDropped:assert _connection_dropped(exc) is False+# The exact shape duckgres surfaces when S3 5xx/throttles mid-glob (HTTP GET listing the run's+# files); a ProgrammingError, NOT a connection drop — so it needs its own retry path.+_S3_503_GLOB_ERROR = psycopg.errors.SyntaxErrorOrAccessRuleViolation(+ "rpc error: code = Unknown desc = HTTP Error: HTTP GET error reading "+ "'s3://posthog-duckling-x-mw-prod-us/backfill/events/55513/year=2019/month=12/day=21/abc_' "+ "in region 'us-east-1' (HTTP 503 Service Unavailable)"+)+++class TestIsTransientS3Error:+ """_is_transient_s3_error retries S3 5xx/throttles surfaced through the PG wire, but only+ when the message is genuinely about object storage (so a plain SQL error can't match)."""++ @parameterized.expand(+ [+ ("glob_503", _S3_503_GLOB_ERROR),+ (+ "add_files_500",+ psycopg.errors.InternalError(+ "HTTP Error: HTTP GET error reading 's3://b/f.parquet' (HTTP 500 InternalError)"+ ),+ ),+ (+ "slowdown_throttle",+ psycopg.OperationalError("HTTP PUT error writing 's3://b/f' (HTTP 503 SlowDown: Please reduce ...)"),+ ),+ ("too_many_requests", psycopg.errors.InternalError("HTTP GET 's3://b/x' HTTP 429 Too Many Requests")),+ ]+ )+ def test_transient_s3_errors_are_retryable(self, _label, exc):+ assert _is_transient_s3_error(exc) is True++ @parameterized.expand(+ [+ # 404/403 are permanent S3 responses — not retryable.+ ("not_found", psycopg.errors.InternalError("HTTP GET error reading 's3://b/missing' (HTTP 404 Not Found)")),+ ("access_denied", psycopg.errors.InternalError("HTTP GET 's3://b/x' (HTTP 403 Forbidden)")),+ # A genuine SQL error that merely contains a number must not match (no S3/HTTP token).+ ("sql_error_with_500", psycopg.errors.SyntaxErrorOrAccessRuleViolation("error near column 500")),+ ("binder_error", psycopg.errors.InternalError("Binder Error: Referenced column not found")),+ # 503 text without any object-storage context must not match either.+ ("bare_503", psycopg.OperationalError("service had 503 issues")),+ ]+ )+ def test_non_transient_errors_are_not_retryable(self, _label, exc):+ assert _is_transient_s3_error(exc) is False++class TestConnectDuckgres:"""_connect_duckgres pins the session to UTC so ranged DELETEs align with the UTC daythe export wrote, but never fails a connection if the server can't set it."""@@ -1213,6 +1262,31 @@ class TestDuckgresSessionRetry:conn0.close.assert_called_once()conn1.close.assert_called_once()+ @patch("posthog.dags.events_backfill_to_duckling.time.sleep")+ @patch("posthog.dags.events_backfill_to_duckling._connect_duckgres")+ def test_transient_s3_retries_on_same_connection(self, mock_connect, _sleep):+ # A transient S3 5xx is the worker hiccuping on object storage, not a worker drop —+ # so it replays on the SAME connection (no reconnect) and eventually succeeds.+ mock_connect.return_value = MagicMock()+ session = _DuckgresSession(MagicMock(), MagicMock())+ op = MagicMock(side_effect=[_S3_503_GLOB_ERROR, _S3_503_GLOB_ERROR, "ok"])++ assert session.run("register", op) == "ok"+ assert op.call_count == 3+ assert mock_connect.call_count == 1 # initial connect only — never reconnected++ @patch("posthog.dags.events_backfill_to_duckling.time.sleep")+ @patch("posthog.dags.events_backfill_to_duckling._connect_duckgres")+ def test_transient_s3_gives_up_after_max_attempts(self, mock_connect, _sleep):+ mock_connect.return_value = MagicMock()+ session = _DuckgresSession(MagicMock(), MagicMock())+ op = MagicMock(side_effect=_S3_503_GLOB_ERROR)++ with pytest.raises(psycopg.errors.SyntaxErrorOrAccessRuleViolation):+ session.run("register", op)+ assert op.call_count == _DuckgresSession.MAX_ATTEMPTS+ assert mock_connect.call_count == 1 # never reconnects for an S3 hiccup+class TestDuckgresBackfillOptions:"""_duckgres_backfill_options() builds the libpq startup `options` string that