: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
feat(data-warehouse): sync activities self-report workload to Redis (#77640)
Daniel RC21dcd0209be5
diff --git a/posthog/settings/data_warehouse.py b/posthog/settings/data_warehouse.pyindex 02792a306046..df671742dc75 100644--- a/posthog/settings/data_warehouse.py+++ b/posthog/settings/data_warehouse.py@@ -43,6 +43,20 @@ DATA_WAREHOUSE_TARGET_PARTITION_BYTES = get_from_env("DATA_WAREHOUSE_TARGET_PARTITION_BYTES", 500_000_000, type_cast=int)+# How often each sync activity self-reports its workload (phase, buffer bytes, RSS) to the warehouse+# Redis, for post-mortem enrichment of silent worker deaths. Zero or negative disables reporting+# entirely (the fleet kill switch — hooks become no-ops and no thread starts).+DATA_WAREHOUSE_WORKLOAD_REPORT_INTERVAL_SECONDS = get_from_env(+ "DATA_WAREHOUSE_WORKLOAD_REPORT_INTERVAL_SECONDS", 30.0, type_cast=float+)++# A run whose peak self-reported buffer crosses this emits one `dwh_workload_high_watermark` event on+# completion. Deaths are enriched separately; this captures the tail of *surviving* runs, which is+# what calibrates OOM-classification thresholds. Zero disables the event.+DATA_WAREHOUSE_WORKLOAD_HIGH_WATERMARK_BYTES = get_from_env(+ "DATA_WAREHOUSE_WORKLOAD_HIGH_WATERMARK_BYTES", 500_000_000, type_cast=int+)+# A schema that records at least this many sync OOMs within the lookback window is force-repartitioned# even when its largest partition is within the size budget — its real merge working set is bigger than# the compressed at-rest size implies (e.g. wide nested-JSON columns). See ExternalDataSchemaOOMEvent.diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.mdindex 7fd0ab097d30..17d846f634ae 100644--- a/products/warehouse_sources/backend/temporal/data_imports/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md@@ -8,6 +8,8 @@ Typically only incremental syncs can cause an OOM on a pod, this affects all jobSome jobs may look like they cause OOMs due to how they're always running when an OOM occurs. This is usually the case for long-running jobs, such as big Stripe tables or any other full-refresh/append-only jobs. These jobs are almost always not the cause, and so it's best to just focus on the incremental jobs when this happens.+To help with exactly that attribution problem, every import activity self-reports its workload — current phase (extract/merge), its own in-memory buffer size (the same slice-accurate accounting dynamic chunking uses), process RSS, and the peaks of both — to the warehouse Redis every `DATA_WAREHOUSE_WORKLOAD_REPORT_INTERVAL_SECONDS` (default 30s; zero disables). See `workload_report.py`. When a worker dies silently, the retry reads the dead attempt's last report plus its pod co-tenants' and attaches them to the `dwh_pod_heartbeat_timeout` event — `self_phase`, `self_peak_buffer_bytes`, and co-tenant **aggregates only** (`co_tenant_max_peak_buffer_bytes`, counts by phase; never their schema or run ids, since a pod is multi-tenant and co-tenant identifiers belong to other teams) — so a death can be read as "was anything on this pod holding more memory, doing what" instead of guessing from at-rest table sizes. The v3 load consumer reports too, under a `{job_id}:load` span key of its own, since for v3 schemas the memory-heavy merge phase runs there rather than in the import activity. Runs whose peak buffer crosses `DATA_WAREHOUSE_WORKLOAD_HIGH_WATERMARK_BYTES` (default 500 MB) additionally emit one `dwh_workload_high_watermark` event on completion, capturing the tail of surviving runs. Observe-only for now: nothing acts on any of it.+## Why does this happen?This happens during a deltalake merge because we have to read the whole partition from S3 (or the whole table if partitioning isn't enabled for the table) to merge data into it. If the partition has great ordering, then a lot of data can be skipped via parquet row group min/max's, but this often isn't the case, and so we often have to load the whole partition into memory. The library we use for this attempts to be clever with how it reads the data in, but it doesn't always work out in our favour.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.pyindex 27dc86410524..f86ba8fbf78c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py@@ -34,6 +34,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql)from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.util import NonRetryableException+from products.warehouse_sources.backend.temporal.data_imports.workload_report import enrich_death_event_propertiesif TYPE_CHECKING:from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob@@ -145,24 +146,26 @@ def report_heartbeat_timeout(inputs: "ImportDataActivityInputs", logger: Filteriheartbeat_timeout_seconds=heartbeat_timeout.total_seconds(),)- posthoganalytics.capture(- "dwh_pod_heartbeat_timeout",- distinct_id=None,- properties={- "team_id": inputs.team_id,- "schema_id": str(inputs.schema_id),- "source_id": str(inputs.source_id),- "run_id": inputs.run_id,- "host": last_heartbeat_host,- "gap_between_beats": gap_between_beats,- "heartbeat_timeout_seconds": heartbeat_timeout.total_seconds(),- "task_queue": info.task_queue,- "workflow_id": info.workflow_id,- "workflow_run_id": info.workflow_run_id,- "workflow_type": info.workflow_type,- "attempt": info.attempt,- },- )+ properties = {+ "team_id": inputs.team_id,+ "schema_id": str(inputs.schema_id),+ "source_id": str(inputs.source_id),+ "run_id": inputs.run_id,+ "host": last_heartbeat_host,+ "gap_between_beats": gap_between_beats,+ "heartbeat_timeout_seconds": heartbeat_timeout.total_seconds(),+ "task_queue": info.task_queue,+ "workflow_id": info.workflow_id,+ "workflow_run_id": info.workflow_run_id,+ "workflow_type": info.workflow_type,+ "attempt": info.attempt,+ }+ # What the dead attempt said it was doing, and what its pod neighbours said, at the moment+ # of death — the per-activity context this event otherwise cannot carry. Adds nothing when+ # no reports exist.+ enrich_death_event_properties(properties, run_id=str(inputs.run_id), host=last_heartbeat_host)++ posthoganalytics.capture("dwh_pod_heartbeat_timeout", distinct_id=None, properties=properties)# Durable per-occurrence OOM record for the repartition trigger to read. Best-effort:# a write failure here must never disrupt the sync.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.pyindex bc1273286d2e..30b9f207b723 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/batcher.py@@ -11,6 +11,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.tabrecord_table_stats,table_payload_bytes,)+from products.warehouse_sources.backend.temporal.data_imports.workload_report import report_buffer_bytes, report_phaseDEFAULT_CHUNK_SIZE_BYTES: int = 200 * 1024 * 1024 # 200 MiBDEFAULT_CHUNK_SIZE: int = 500_000@@ -106,6 +107,14 @@ class Batcher:the per-table Arrow-payload cap (keeping the loader's per-batch merge bounded)."""chunks = _split_table(table, offset_limit=self._max_column_offset_bytes, bytes_limit=self._max_table_bytes)payload_bytes = table_payload_bytes(table)+ # The materialised table is this activity's true in-memory peak, already sized here for+ # chunking — feed the same number to the workload self-report at zero extra cost. Phase is+ # re-declared here because v2 interleaves extract and merge per chunk: without flipping back,+ # the writer's "merge" would latch after the first chunk and every later mid-extract death+ # would be misreported as a merge death, biasing the exact distribution this signal exists+ # to measure.+ report_phase("extract")+ report_buffer_bytes(payload_bytes)if self._source_type is not None:# The materialised table is the true in-memory peak (an unbounded source yields one giant# list -> one giant table here, before the split into bounded chunks).diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.pyindex 76535119e469..5904963186ee 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/writer.py@@ -26,6 +26,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.deldelta_merge_spill_kwargs,execute_with_conflict_retry,)+from products.warehouse_sources.backend.temporal.data_imports.workload_report import report_buffer_bytes, report_phaseif TYPE_CHECKING:from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.table import DeltaTableRef@@ -277,6 +278,15 @@ class DeltaWriter:progress_callback: Callable[[], None] | None = None,commit_metadata: dict[str, str] | None = None,) -> deltalake.DeltaTable:+ # `.nbytes` rather than the slice-accurate accounting: tables reaching the writer are+ # materialised chunks, not zero-copy slices, and the merge working set scales with the full+ # buffers delta-rs will read anyway. This reports the merge *input* only — the decompressed+ # target-partition working set lives inside delta-rs/DataFusion where we can't observe it,+ # and under deltalite the memory governor bounds it; the input batch is the per-activity+ # share we can actually attribute.+ report_phase("merge")+ report_buffer_bytes(data.nbytes)+# Guard against delta-rs aborting the worker on misaligned decimal buffers (see# realign_decimal_buffers). Sub-tables derived below via filter()/take() are# freshly allocated by pyarrow and so inherit safe alignment.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.pyindex a4134d93c270..05ba4739ecc6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/processor.py@@ -1,4 +1,5 @@import uuid+import socketfrom collections.abc import Callablefrom typing import Any, Literal@@ -74,6 +75,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline)from products.warehouse_sources.backend.temporal.data_imports.row_tracking import finish_row_trackingfrom products.warehouse_sources.backend.temporal.data_imports.util import prepare_s3_files_for_querying+from products.warehouse_sources.backend.temporal.data_imports.workload_report import workload_reportinglogger = structlog.get_logger(__name__)@@ -675,6 +677,26 @@ def process_message(re-checked before each lasting side effect since the heartbeat only detects loss between beats."""export_signal = ExportSignalMessage.from_dict(message)+ # The consumer is where v3 merges — the memory-heavy phase — actually run, so it must self-report+ # like the import activity does. Its own span key: extract (activity) and load (here) run+ # concurrently for the same job and must not clobber each other's reports.+ with workload_reporting(+ team_id=export_signal.team_id,+ schema_id=str(export_signal.schema_id),+ run_id=f"{export_signal.job_id}:load",+ host=socket.gethostname(),+ initial_phase="load",+ ):+ _process_message_reported(message, export_signal, progress_callback, verify_ownership)+++def _process_message_reported(+ message: Any,+ export_signal: "ExportSignalMessage",+ progress_callback: Callable[[], None] | None,+ verify_ownership: Callable[[], None] | None,+) -> None:+# Reconnect stale app-DB connections up front so the ORM queries below don't burn all batch attempts.close_old_connections()diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_workload_report.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_workload_report.pynew file mode 100644index 000000000000..f2869b6737bb--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_workload_report.py@@ -0,0 +1,232 @@+import json+import time++import pytest+from unittest import mock++from django.test import override_settings++from products.warehouse_sources.backend.temporal.data_imports import workload_report+from products.warehouse_sources.backend.temporal.data_imports.workload_report import (+ WorkloadReporter,+ enrich_death_event_properties,+ host_key,+ report_buffer_bytes,+ report_phase,+ run_key,+ workload_reporting,+)+++def _seed_report(redis, *, run_id: str, host: str, schema_id: str, phase: str, peak: int, ts: float = 100.0) -> None:+ redis.setex(+ run_key(run_id),+ 60,+ json.dumps(+ {+ "run_id": run_id,+ "schema_id": schema_id,+ "host": host,+ "phase": phase,+ "buffer_bytes": peak // 2,+ "peak_buffer_bytes": peak,+ "rss_bytes": None,+ "peak_rss_bytes": None,+ "ts": ts,+ }+ ),+ )+ redis.sadd(host_key(host), run_id)+++class TestWorkloadReporting:+ def test_samples_round_trip_through_redis_with_hook_values_and_peaks(self):+ # Writer and reader live on different pods at different times: the sample written before a+ # death is what the retry reads back. A drifted key or field name would silently null every+ # death enrichment, which is the whole point of this module.+ redis = workload_report._redis_client()+ assert redis is not None+ with workload_reporting(team_id=1, schema_id="s1", run_id="run-rt", host="pod-rt"):+ report_phase("merge")+ report_buffer_bytes(500)+ report_buffer_bytes(200) # current drops, peak must not+ reporter = workload_report._current_reporter.get()+ assert reporter is not None+ reporter._write_sample(redis)++ raw = redis.get(run_key("run-rt"))+ assert raw is not None+ sample = json.loads(raw)+ assert sample["phase"] == "merge"+ assert sample["buffer_bytes"] == 200+ assert sample["peak_buffer_bytes"] == 500+ assert redis.sismember(host_key("pod-rt"), "run-rt")++ # Clean completion: dropped from the running set (it is no longer a live co-tenant), but the+ # final sample survives for a death that happens moments later on the same pod.+ assert not redis.sismember(host_key("pod-rt"), "run-rt")+ assert json.loads(redis.get(run_key("run-rt")))["phase"] == "finished"++ def test_enrichment_attaches_own_report_and_aggregates_co_tenants_without_identifiers(self):+ # A pod is multi-tenant, so co-tenant reports belong to other teams: the event may carry only+ # aggregates (the max answers "was anything bigger than us"), never their schema or run ids.+ # Leaking an identifier here would put one team's schema ids in another team's failure record.+ redis = workload_report._redis_client()+ _seed_report(redis, run_id="run-dead", host="pod-a", schema_id="s-dead", phase="extract", peak=900)+ _seed_report(redis, run_id="run-big", host="pod-a", schema_id="s-big", phase="merge", peak=5000)+ _seed_report(redis, run_id="run-small", host="pod-a", schema_id="s-small", phase="extract", peak=10)++ properties: dict = {}+ enrich_death_event_properties(properties, run_id="run-dead", host="pod-a")++ assert properties["self_phase"] == "extract"+ assert properties["self_peak_buffer_bytes"] == 900+ assert properties["co_tenant_report_count"] == 2+ assert properties["co_tenant_max_peak_buffer_bytes"] == 5000+ assert properties["co_tenant_merge_count"] == 1+ assert properties["co_tenant_extract_count"] == 1+ serialized = json.dumps(properties)+ assert "s-big" not in serialized and "s-small" not in serialized and "run-big" not in serialized++ def test_enrichment_is_silent_when_no_reports_exist(self):+ # Rollout reality: workers without the reporter (old deploys, disabled fleet) must produce+ # byte-identical events to today, or every dashboard on this event breaks during rollout.+ properties = {"host": "pod-none"}+ enrich_death_event_properties(properties, run_id="run-none", host="pod-none")+ assert properties == {"host": "pod-none"}++ @override_settings(DATA_WAREHOUSE_WORKLOAD_REPORT_INTERVAL_SECONDS=0)+ def test_interval_zero_is_a_full_kill_switch(self):+ # The fleet off-switch has to mean off: no thread, hooks are no-ops, and the teardown emits+ # neither a Redis sample nor a watermark event — otherwise "disabled" still writes telemetry.+ redis = workload_report._redis_client()+ with mock.patch("posthoganalytics.capture") as capture:+ with workload_reporting(team_id=1, schema_id="s1", run_id="run-off", host="pod-off"):+ reporter = workload_report._current_reporter.get()+ assert reporter is not None and reporter._thread is None+ report_phase("merge")+ report_buffer_bytes(999_999_999_999)+ assert redis is not None and redis.get(run_key("run-off")) is None+ capture.assert_not_called()++ def test_zombie_attempt_stands_down_when_a_newer_attempt_owns_the_run_key(self):+ # Retries share the run_id, and a heartbeat-timed-out attempt keeps running as a zombie while+ # its retry reports under the same key. Without the attempt guard the zombie's sampler keeps+ # clobbering the live attempt's report, and its eventual stop() overwrites the key with+ # "finished" and SREMs the live attempt from the host set — corrupting both the next death's+ # own-report and the pod's co-tenant list.+ redis = workload_report._redis_client()+ assert redis is not None+ zombie = WorkloadReporter(team_id=1, schema_id="s1", run_id="run-z", host="pod-z", attempt=1)+ zombie._enabled = True # a started reporter, minus the sampler thread+ zombie.set_buffer_bytes(111)+ zombie._write_sample(redis) # attempt 1 owns the key while no retry exists++ retry = WorkloadReporter(team_id=1, schema_id="s1", run_id="run-z", host="pod-z", attempt=2)+ retry._enabled = True+ retry.set_buffer_bytes(222)+ retry._write_sample(redis) # the newer attempt takes the key over++ zombie.set_buffer_bytes(999)+ zombie._write_sample(redis)+ assert zombie._superseded and zombie._stop_event.is_set()+ zombie.stop()++ sample = json.loads(redis.get(run_key("run-z")))+ assert sample["attempt"] == 2 and sample["peak_buffer_bytes"] == 222 and sample["phase"] != "finished"+ assert redis.sismember(host_key("pod-z"), "run-z"), "zombie stop() must not SREM the live attempt"++ def test_stale_host_set_member_from_a_retried_run_is_excluded(self):+ # An attempt dies on pod A, its retry runs on pod B and overwrites the run key with B's+ # report while the stable run_id lingers in A's set. Counting it as an A co-tenant would+ # attribute B's workload to a death on A. Membership is not evidence; the report must claim+ # the host it is read for.+ redis = workload_report._redis_client()+ assert redis is not None+ _seed_report(redis, run_id="run-moved", host="pod-stale-b", schema_id="s-moved", phase="merge", peak=5000)+ redis.sadd(host_key("pod-stale-a"), "run-moved") # stale membership from the dead first attempt+ _seed_report(redis, run_id="run-local", host="pod-stale-a", schema_id="s-local", phase="merge", peak=10)++ reports = workload_report.read_workload_reports("pod-stale-a")+ assert [report["run_id"] for report in reports] == ["run-local"]++ def test_batcher_flips_phase_back_to_extract_after_a_merge(self):+ # v2 interleaves extract and merge per chunk. Without the batcher re-declaring "extract" on+ # each materialization, the writer's "merge" latches after the first chunk and every later+ # mid-extract death reads as a merge death — biasing the phase distribution this telemetry+ # exists to measure.+ import pyarrow as pa+ import structlog++ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.batcher import Batcher++ with workload_reporting(team_id=1, schema_id="s1", run_id="run-phase", host="pod-ph"):+ reporter = workload_report._current_reporter.get()+ assert reporter is not None+ report_phase("merge")+ batcher = Batcher(logger=structlog.get_logger())+ batcher.batch(pa.table({"id": pa.array([1, 2, 3])}))+ assert reporter._phase == "extract"++ def test_hooks_outside_a_reporting_context_are_no_ops(self):+ # Code paths shared with processes that opted out of reporting must never raise or write when+ # the hooks fire with no reporter bound.+ report_phase("merge")+ report_buffer_bytes(42)++ @override_settings(DATA_WAREHOUSE_WORKLOAD_HIGH_WATERMARK_BYTES=1000)+ def test_high_watermark_event_fires_only_above_threshold(self):+ # The watermark event is the only durable record of surviving runs' tails; firing on every run+ # would flood the event stream, and never firing would leave classification thresholds+ # calibrated on deaths alone.+ # The analytics import is deferred inside the capture helper, so patch the global module.+ with mock.patch("posthoganalytics.capture") as capture:+ with workload_reporting(team_id=1, schema_id="s1", run_id="run-low", host="pod-w"):+ report_buffer_bytes(999)+ capture.assert_not_called()++ with workload_reporting(team_id=1, schema_id="s1", run_id="run-high", host="pod-w"):+ report_buffer_bytes(5000)+ capture.assert_called_once()+ properties = capture.call_args.kwargs["properties"]+ assert properties["peak_buffer_bytes"] == 5000+ assert properties["run_id"] == "run-high"+ assert properties["outcome"] == "completed"++ # A run that raises still emits (its peak is a real observation) but must be labeled, or+ # failed runs contaminate the survivors-only distribution the thresholds come from.+ capture.reset_mock()+ with pytest.raises(RuntimeError):+ with workload_reporting(team_id=1, schema_id="s1", run_id="run-boom", host="pod-w"):+ report_buffer_bytes(7000)+ raise RuntimeError("merge failed")+ assert capture.call_args.kwargs["properties"]["outcome"] == "raised"+++class TestWorkloadReporterThread:+ def test_start_and_stop_lifecycle_writes_final_sample(self):+ # The thread is the production write path; a lifecycle regression (never starts, never joins)+ # would silently stop all sampling fleet-wide.+ reporter = WorkloadReporter(team_id=1, schema_id="s1", run_id="run-thread", host="pod-thread")+ with override_settings(DATA_WAREHOUSE_WORKLOAD_REPORT_INTERVAL_SECONDS=3600):+ reporter.start()+ assert reporter._thread is not None and reporter._thread.is_alive()++ # The first sample must land immediately, not after the first interval: the fastest OOMs die+ # inside that window and never reach stop(), so waiting would blind us to exactly them.+ redis = workload_report._redis_client()+ assert redis is not None+ deadline = time.monotonic() + 5+ while redis.get(run_key("run-thread")) is None and time.monotonic() < deadline:+ time.sleep(0.02)+ assert redis.get(run_key("run-thread")) is not None, "no immediate first sample"++ reporter.set_buffer_bytes(777)+ reporter.stop()+ assert not reporter._thread.is_alive()++ redis = workload_report._redis_client()+ assert redis is not None+ sample = json.loads(redis.get(run_key("run-thread")))+ assert sample["peak_buffer_bytes"] == 777+ assert sample["phase"] == "finished"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.pyindex af1e770e6247..3b19a147bdd5 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@@ -1,4 +1,5 @@import uuid+import socketimport asyncioimport datetime as dtimport dataclasses@@ -62,6 +63,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sql)from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.postgres.exceptions import CDCHandledExternally+from products.warehouse_sources.backend.temporal.data_imports.workload_report import aworkload_reportingfrom products.warehouse_sources.backend.types import ExternalDataSourceTypeLOGGER = get_logger(__name__)@@ -110,6 +112,21 @@ async def import_data_activity_sync(inputs: ImportDataActivityInputs) -> Pipelinawait asyncio.to_thread(report_heartbeat_timeout, inputs, logger)+ # Async variant: teardown joins the sampler thread and talks to Redis, which must not block+ # this activity's event loop (or its heartbeats).+ async with aworkload_reporting(+ team_id=inputs.team_id,+ schema_id=str(inputs.schema_id),+ run_id=str(inputs.run_id),+ host=socket.gethostname(),+ # Retries share the run_id; the attempt lets the newest reporter own the run key while a+ # zombie predecessor stands down (its heartbeat timed out, but it may still be running).+ attempt=current_activity_attempt(),+ ):+ return await _import_data_with_reporting(inputs, logger)+++async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger: FilteringBoundLogger) -> PipelineResult:async with Heartbeater(factor=30), ShutdownMonitor() as shutdown_monitor:await setup_row_tracking(inputs.team_id, inputs.schema_id)diff --git a/products/warehouse_sources/backend/temporal/data_imports/workload_report.py b/products/warehouse_sources/backend/temporal/data_imports/workload_report.pynew file mode 100644index 000000000000..b0eb75fcba02--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/workload_report.py@@ -0,0 +1,408 @@+"""Per-run workload self-reporting for warehouse sync activities.++Each import activity periodically writes what it is doing — phase, current in-memory buffer, process+RSS, and the peaks of both — to the warehouse Redis, keyed by run. The value outlives the worker, so+when a worker dies silently the retry can read the dead attempt's last report, and the reports of+everything else that was running on the same pod, and attach them to the `dwh_pod_heartbeat_timeout`+telemetry event.++Observe-only for now: nothing acts on these reports. They exist to answer, from production data, the+questions the OOM-classification work needs answered before it can pick thresholds — what phase do+silent deaths happen in, how big was the dead attempt's own working set, and how big were its+co-tenants' at that moment. A worker cannot attribute shared-process memory per activity, but it knows+its own buffer exactly (the same accounting dynamic chunking already uses), which is the per-activity+signal at-rest partition sizes cannot provide.++The write path mirrors `row_tracking.py`: per-run keys with a TTL on the warehouse Redis, plus a+per-host set so co-tenants are discoverable. Everything here is best-effort — a reporting failure+must never affect a sync.+"""++from __future__ import annotations++import json+import time+import asyncio+import threading+from collections.abc import AsyncIterator, Iterator+from contextlib import asynccontextmanager, contextmanager+from contextvars import ContextVar+from typing import Any++from django.conf import settings++from structlog import get_logger++from posthog.redis import get_client+from posthog.web_memory_sampler import current_rss_mb++LOGGER = get_logger(__name__)++# Keys live longer than any plausible gap between a death and its retry (heartbeat timeout is minutes),+# but short enough that crashed runs don't accumulate. The host set carries the same TTL, refreshed on+# every sample, so it can only outlive its members briefly.+WORKLOAD_REPORT_TTL_SECONDS = 2 * 60 * 60++_RUN_KEY_PREFIX = "posthog:data_warehouse:workload:run:"+_HOST_KEY_PREFIX = "posthog:data_warehouse:workload:host:"++_current_reporter: ContextVar[WorkloadReporter | None] = ContextVar("dwh_workload_reporter", default=None)+++def workload_report_interval_seconds() -> float:+ return float(getattr(settings, "DATA_WAREHOUSE_WORKLOAD_REPORT_INTERVAL_SECONDS", 30))+++def workload_high_watermark_bytes() -> int:+ return int(getattr(settings, "DATA_WAREHOUSE_WORKLOAD_HIGH_WATERMARK_BYTES", 500_000_000))+++def run_key(run_id: str) -> str:+ return f"{_RUN_KEY_PREFIX}{run_id}"+++def host_key(host: str) -> str:+ return f"{_HOST_KEY_PREFIX}{host}"+++def _redis_client() -> Any | None:+ host = getattr(settings, "DATA_WAREHOUSE_REDIS_HOST", None)+ port = getattr(settings, "DATA_WAREHOUSE_REDIS_PORT", None)+ if not host or not port:+ return None+ return get_client(f"redis://{host}:{port}/")+++def report_phase(phase: str) -> None:+ """Record the current phase from anywhere inside a reporting activity; no-op outside one."""+ reporter = _current_reporter.get()+ if reporter is not None:+ reporter.set_phase(phase)+++def report_buffer_bytes(buffer_bytes: int) -> None:+ """Record the activity's current in-memory buffer from anywhere inside it; no-op outside one."""+ reporter = _current_reporter.get()+ if reporter is not None:+ reporter.set_buffer_bytes(buffer_bytes)+++class WorkloadReporter:+ """Samples one activity's self-declared workload into Redis on a background thread.++ Thread-safe by construction: the hook setters only assign ints/strings under a lock, and the+ sampling thread does all Redis I/O. The sync path never blocks on reporting.+ """++ def __init__(+ self,+ *,+ team_id: int,+ schema_id: str,+ run_id: str,+ host: str,+ initial_phase: str = "extract",+ attempt: int = 1,+ ) -> None:+ self._team_id = team_id+ self._schema_id = schema_id+ self._run_id = run_id+ self._host = host+ self._attempt = attempt+ self._lock = threading.Lock()+ self._phase = initial_phase+ self._buffer_bytes = 0+ self._peak_buffer_bytes = 0+ self._peak_rss_bytes = 0+ self._started_at = time.time()+ self._stop_event = threading.Event()+ self._thread: threading.Thread | None = None+ self._enabled = False+ self._superseded = False++ def set_phase(self, phase: str) -> None:+ with self._lock:+ self._phase = phase++ def set_buffer_bytes(self, buffer_bytes: int) -> None:+ with self._lock:+ self._buffer_bytes = buffer_bytes+ self._peak_buffer_bytes = max(self._peak_buffer_bytes, buffer_bytes)++ def start(self) -> None:+ interval = workload_report_interval_seconds()+ if interval <= 0:+ return+ self._enabled = True+ self._thread = threading.Thread(+ target=self._run, args=(interval,), name=f"dwh-workload-report-{self._run_id[:8]}", daemon=True+ )+ self._thread.start()++ def stop(self, *, outcome: str = "completed") -> None:+ """Stop sampling and drop this run from its host's co-tenant set.++ The run key is left to expire naturally: a just-finished neighbour is still relevant context+ for a death that happens moments later, but it should no longer be listed as running.++ A reporter that never started (interval <= 0, the fleet kill switch) emits nothing here+ either — off must mean off. A superseded reporter (a zombie attempt outlived by its retry)+ writes nothing and removes nothing: the srem and final sample belong to the live attempt now+ sharing this run's key. Its watermark event still fires — the peak it observed is real.+ """+ if not self._enabled:+ return+ self._stop_event.set()+ if self._thread is not None:+ self._thread.join(timeout=5)+ try:+ redis = _redis_client()+ if redis is not None and not self._superseded:+ self._write_sample(redis, final=True)+ if not self._superseded:+ redis.srem(host_key(self._host), self._run_id)+ except Exception:+ LOGGER.debug("workload_report_stop_failed", run_id=self._run_id, exc_info=True)+ self._capture_high_watermark(outcome)++ def _capture_high_watermark(self, outcome: str) -> None:+ """Emit one event for runs whose peak buffer crossed the high-watermark threshold.++ Deaths are enriched via Redis; this captures the tail of runs that exited through Python —+ cleanly or by raising — which is what calibrates thresholds (how big does a working set get+ without silently killing the pod?). `outcome` distinguishes the two so a failed run cannot+ contaminate a survivors-only distribution. Emitting only above the watermark keeps this to+ the rare, high-signal tail instead of an event per sync.+ """+ try:+ threshold = workload_high_watermark_bytes()+ if threshold <= 0 or self._peak_buffer_bytes < threshold:+ return+ import posthoganalytics # noqa: PLC0415 — keeps the analytics client off this module's import path++ posthoganalytics.capture(+ "dwh_workload_high_watermark",+ distinct_id=None,+ properties={+ "team_id": self._team_id,+ "schema_id": self._schema_id,+ "run_id": self._run_id,+ "host": self._host,+ "phase": self._phase,+ "peak_buffer_bytes": self._peak_buffer_bytes,+ "peak_rss_bytes": self._peak_rss_bytes or None,+ "duration_seconds": round(time.time() - self._started_at, 1),+ "outcome": outcome,+ },+ )+ except Exception:+ LOGGER.debug("workload_report_watermark_failed", run_id=self._run_id, exc_info=True)++ def _run(self, interval: float) -> None:+ # First sample immediately: a fast OOM can kill the pod within the first interval, and a+ # killed attempt never reaches stop() — without this, the quickest deaths (the most+ # interesting ones) would have no report at all.+ try:+ redis = _redis_client()+ if redis is not None:+ self._write_sample(redis)+ except Exception:+ LOGGER.debug("workload_report_sample_failed", run_id=self._run_id, exc_info=True)+ while not self._stop_event.wait(interval):+ try:+ redis = _redis_client()+ if redis is None:+ return+ self._write_sample(redis)+ except Exception:+ # Best-effort: never let reporting noise surface anywhere near the sync.+ LOGGER.debug("workload_report_sample_failed", run_id=self._run_id, exc_info=True)++ def _write_sample(self, redis: Any, *, final: bool = False) -> None:+ # Attempts share the run key, and a heartbeat-timed-out attempt keeps running as a zombie+ # while its retry reports under the same key. The higher attempt owns the key: a reporter+ # that finds a newer attempt's report there goes permanently silent instead of fighting over+ # it. The read-then-write pair isn't atomic, but a losing interleave only survives until the+ # next sample on either side — acceptable for best-effort telemetry.+ existing = _parse_report(redis.get(run_key(self._run_id)))+ if existing is not None and int(existing.get("attempt") or 0) > self._attempt:+ self._superseded = True+ self._stop_event.set()+ return+ rss_mb = current_rss_mb()+ rss_bytes = int(rss_mb * 1024 * 1024) if rss_mb is not None else None+ with self._lock:+ if rss_bytes is not None:+ self._peak_rss_bytes = max(self._peak_rss_bytes, rss_bytes)+ payload = {+ "run_id": self._run_id,+ "team_id": self._team_id,+ "schema_id": self._schema_id,+ "host": self._host,+ "attempt": self._attempt,+ "phase": "finished" if final else self._phase,+ "buffer_bytes": self._buffer_bytes,+ "peak_buffer_bytes": self._peak_buffer_bytes,+ "rss_bytes": rss_bytes,+ "peak_rss_bytes": self._peak_rss_bytes or None,+ "started_at": self._started_at,+ "ts": time.time(),+ }+ redis.setex(run_key(self._run_id), WORKLOAD_REPORT_TTL_SECONDS, json.dumps(payload))+ if not final:+ host = host_key(self._host)+ redis.sadd(host, self._run_id)+ redis.expire(host, WORKLOAD_REPORT_TTL_SECONDS)+++@contextmanager+def _reporting_span(+ team_id: int, schema_id: str, run_id: str, host: str, initial_phase: str, attempt: int+) -> Iterator[WorkloadReporter]:+ """Shared lifecycle of both public managers: construct, start, bind the hooks, unbind.++ Exit classification and the stop() call stay with the variants — they must live in the frame+ directly around the user's block, because an inner finally unwinds before any outer handler.+ """+ reporter = WorkloadReporter(+ team_id=team_id, schema_id=schema_id, run_id=run_id, host=host, initial_phase=initial_phase, attempt=attempt+ )+ reporter.start()+ token = _current_reporter.set(reporter)+ try:+ yield reporter+ finally:+ _current_reporter.reset(token)+++@contextmanager+def workload_reporting(+ *, team_id: int, schema_id: str, run_id: str, host: str, initial_phase: str = "extract", attempt: int = 1+) -> Iterator[None]:+ """Run the wrapped block with a live workload reporter bound for `report_phase`/`report_buffer_bytes`.++ Fully inert when the interval setting is <= 0 or the warehouse Redis is unconfigured. For async+ callers use `aworkload_reporting`, which keeps the blocking teardown off the event loop.++ `attempt` disambiguates Temporal retries sharing one `run_id`: the newest attempt owns the run+ key, and an older zombie that discovers a newer report under it stops writing (see+ `_write_sample`). Callers without retry semantics can leave the default.+ """+ with _reporting_span(team_id, schema_id, run_id, host, initial_phase, attempt) as reporter:+ # Outcome must be classified in the same frame that calls stop(): an inner finally unwinds+ # before any outer except could observe the exception.+ outcome = "completed"+ try:+ yield+ except BaseException:+ outcome = "raised"+ raise+ finally:+ reporter.stop(outcome=outcome)+++@asynccontextmanager+async def aworkload_reporting(+ *, team_id: int, schema_id: str, run_id: str, host: str, initial_phase: str = "extract", attempt: int = 1+) -> AsyncIterator[None]:+ """Async variant of `workload_reporting` for the import activity.++ `stop()` joins the sampler thread and talks to Redis synchronously; run inline it would stall the+ activity's event loop (and its heartbeats) for up to the join timeout, so it is offloaded.+ """+ with _reporting_span(team_id, schema_id, run_id, host, initial_phase, attempt) as reporter:+ outcome = "completed"+ try:+ yield+ except BaseException:+ outcome = "raised"+ raise+ finally:+ await asyncio.to_thread(reporter.stop, outcome=outcome)+++def _parse_report(raw: Any) -> dict[str, Any] | None:+ if raw is None:+ return None+ try:+ parsed = json.loads(raw)+ except (TypeError, ValueError):+ return None+ return parsed if isinstance(parsed, dict) else None+++def read_workload_reports(host: str) -> list[dict[str, Any]]:+ """Last self-reports of every run recorded as running on `host`, freshest first.++ Read on the retry after a silent death, so `host` is the dead pod. Never raises; an unreadable+ Redis just means no enrichment.+ """+ try:+ redis = _redis_client()+ if redis is None:+ return []+ run_ids = [rid.decode() if isinstance(rid, bytes) else str(rid) for rid in redis.smembers(host_key(host))]+ if not run_ids:+ return []+ reports = [_parse_report(raw) for raw in redis.mget([run_key(rid) for rid in run_ids])]+ # A retry on another pod overwrites its run key with the new host while the stable run_id+ # lingers in the old pod's set; without this filter a later death on the old pod would count+ # the retry's workload as a local co-tenant. Membership alone is not evidence — the report+ # itself must claim this host. Stale members age out via the set's TTL.+ found = [report for report in reports if report is not None and report.get("host") == host]+ found.sort(key=lambda report: report.get("ts") or 0, reverse=True)+ return found+ except Exception:+ LOGGER.debug("workload_report_read_failed", host=host, exc_info=True)+ return []+++def enrich_death_event_properties(properties: dict[str, Any], *, run_id: str, host: str | None) -> None:+ """Fold workload self-reports into a `dwh_pod_heartbeat_timeout` event's properties, in place.++ `self_*` describes the dead attempt's own last report. `co_tenant_*` is **aggregates only** —+ count, max/sum of peaks, phase mix — never identifiers: a pod is multi-tenant, so co-tenant+ reports belong to other teams, and anything persisted here (or later snapshotted onto a+ team-scoped row) must not carry one team's schema/run ids into another team's data. The blame+ question the aggregates must still answer is "was anything on this pod holding more than us",+ which only needs the maximum. Absent reports (rollout, expired keys, Redis down) add nothing —+ the event stays exactly as it was before this existed.+ """+ try:+ reports = read_workload_reports(host) if host else []+ own = next((report for report in reports if report.get("run_id") == run_id), None)+ if own is None:+ # A clean earlier attempt may have SREM'd itself from the host set; the run key survives.+ redis = _redis_client()+ own = _parse_report(redis.get(run_key(run_id))) if redis is not None else None+ # Callers without a host (consumer-side deaths) still get co-tenants: the own report+ # remembers which pod it ran on.+ if own is not None and not host and own.get("host"):+ reports = read_workload_reports(str(own["host"]))+ if own is not None:+ properties.update(+ {+ "self_phase": own.get("phase"),+ "self_buffer_bytes": own.get("buffer_bytes"),+ "self_peak_buffer_bytes": own.get("peak_buffer_bytes"),+ "self_rss_bytes": own.get("rss_bytes"),+ "self_peak_rss_bytes": own.get("peak_rss_bytes"),+ "self_report_age_seconds": round(time.time() - own["ts"], 1) if own.get("ts") is not None else None,+ }+ )+ co_tenants = [report for report in reports if report.get("run_id") != run_id]+ if co_tenants:+ peaks = [int(report.get("peak_buffer_bytes") or 0) for report in co_tenants]+ currents = [int(report.get("buffer_bytes") or 0) for report in co_tenants]+ phases = [str(report.get("phase")) for report in co_tenants]+ properties.update(+ {+ "co_tenant_report_count": len(co_tenants),+ "co_tenant_max_peak_buffer_bytes": max(peaks),+ "co_tenant_sum_buffer_bytes": sum(currents),+ "co_tenant_merge_count": sum(1 for phase in phases if phase == "merge"),+ "co_tenant_extract_count": sum(1 for phase in phases if phase == "extract"),+ }+ )+ except Exception:+ LOGGER.debug("workload_report_enrich_failed", run_id=run_id, exc_info=True)