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(warehouse-sources): report repartition rewrites to workload telemetry (#85718)

Daniel RC109d9cbce095
diff --git a/products/warehouse_sources/backend/models/oom_event.py b/products/warehouse_sources/backend/models/oom_event.py
index 83df4126924b..5c925ea19cce 100644
--- a/products/warehouse_sources/backend/models/oom_event.py
+++ b/products/warehouse_sources/backend/models/oom_event.py
@@ -19,7 +19,9 @@ if TYPE_CHECKING:
# Self-reported phases that rule a death out as a *merge* memory problem. Repartitioning only changes
# merge memory, so a death in any of these phases must not feed the repartition trigger, whatever
# killed the worker (an extract-phase OOM is real, but its remedy is chunking or routing, not a finer
-# partition layout). An unknown phase (no report: rollout gap, expired key, Redis down) fails open.
+# partition layout). An unknown phase (no report: rollout gap, expired key, Redis down) fails open,
+# and so does "repartition": a rewrite death held partition-sized data of this schema, which is
+# exactly the evidence the trigger runs on.
NON_MERGE_PHASES = ("extract", "load", "finished")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
index 9e12229412a5..af4c5ca2f649 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition.py
@@ -51,6 +51,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
PartitionFormat,
PartitionMode,
)
+from products.warehouse_sources.backend.temporal.data_imports.workload_report import report_buffer_bytes
from products.warehouse_sources.backend.types import IncrementalFieldType
if TYPE_CHECKING:
@@ -771,6 +772,7 @@ async def _rewrite_into_temp(
)
rows_written += combined.num_rows
commits += 1
+ report_buffer_bytes(0)
fields = progress()
await logger.ainfo(f"repartition: rewrite progress {_format_fields(fields)}", **fields)
@@ -865,6 +867,8 @@ async def _rewrite_into_temp(
buffered.append(partitioned_table)
buffered_rows += partitioned_table.num_rows
buffered_bytes += table_bytes
+ # Feeds the workload reporter bound by the repartition activity; no-op everywhere else.
+ report_buffer_bytes(buffered_bytes)
await flush()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
index 77d46df0b6f9..1f6eb5a3e6b8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition.py
@@ -1,4 +1,5 @@
import os
+import json
import asyncio
import datetime
import itertools
@@ -32,6 +33,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.rep
select_coarsen_target,
select_repartition_target,
)
+from products.warehouse_sources.backend.temporal.data_imports.workload_report import (
+ _redis_client,
+ run_key,
+ workload_reporting,
+)
logger = structlog.get_logger(__name__)
@@ -526,6 +532,33 @@ class TestRewriteIntoTemp:
for key in new_sizes:
assert key is not None and len(key) == len("2024-01-05")
+ def test_reports_buffered_bytes_to_the_workload_reporter(self, tmp_path):
+ # Dropping this hook makes rewrites invisible to the OOM classifier's culprit rule.
+ rows = [(1, datetime.datetime(2024, 1, 5)), (2, datetime.datetime(2024, 1, 20))]
+ old_delta = _write_month_partitioned(str(tmp_path / "src"), rows)
+
+ with workload_reporting(team_id=1, schema_id="s-rw", run_id="repartition:rw-test", host="pod-rw"):
+ asyncio.run(
+ _rewrite_into_temp(
+ old_delta=old_delta,
+ temp_uri=str(tmp_path / "tmp"),
+ storage_options={},
+ target=RepartitionTarget(
+ partition_keys=["created_at"],
+ trigger_reason="test",
+ partition_mode="datetime",
+ partition_format="day",
+ ),
+ batch_size=1,
+ logger=logger,
+ )
+ )
+
+ redis = _redis_client()
+ assert redis is not None
+ sample = json.loads(redis.get(run_key("repartition:rw-test")))
+ assert sample["peak_buffer_bytes"] > 0
+
def test_stops_mid_stream_once_the_deadline_passes(self, tmp_path):
rows = [
(1, datetime.datetime(2024, 1, 5)),
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py
index bba10e6c4a21..ac548485cee3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py
@@ -1,3 +1,4 @@
+import json
import uuid
import asyncio
import datetime
@@ -23,6 +24,7 @@ from products.warehouse_sources.backend.models.external_data_job import External
from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.models.oom_event import ExternalDataSchemaOOMEvent
+from products.warehouse_sources.backend.temporal.data_imports import workload_report
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core import repartition_controller as ctrl
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.consts import PARTITION_KEY
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.repartition import (
@@ -736,6 +738,36 @@ class TestRepartitionActivity:
assert "warehouse_repartition_started" in emitted
assert "warehouse_repartition_completed" in emitted
+ def test_rewrite_reports_workload_under_its_own_run_key(self, team):
+ # The import activity reports under the bare job id on this same pod; sharing that key would
+ # let a death during the import read the rewrite's report as its own last words.
+ schema = _make_schema(team, {})
+ schema.set_repartition_pending(
+ {
+ "partition_mode": "md5",
+ "partition_count": 4,
+ "partition_keys": ["id"],
+ "trigger_reason": "test",
+ "attempts": 0,
+ }
+ )
+ inputs = self._inputs(team, schema)
+ samples: list[dict] = []
+
+ async def rewrite_reading_own_report(**kwargs):
+ reporter = workload_report._current_reporter.get()
+ assert reporter is not None, "rewrite must run inside a workload reporting span"
+ redis = workload_report._redis_client()
+ assert redis is not None
+ reporter._write_sample(redis)
+ samples.append(json.loads(redis.get(workload_report.run_key(f"repartition:{inputs.job_id}"))))
+ return {"outcome": "completed", "row_count": 6, "partition_mode_after": "md5"}
+
+ self._run(inputs, AsyncMock(side_effect=rewrite_reading_own_report))
+
+ assert samples and samples[0]["phase"] == "repartition"
+ assert samples[0]["schema_id"] == str(schema.id)
+
def test_unpartitionable_clears_pending(self, team):
schema = _make_schema(team, {})
schema.set_repartition_pending(
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.py
index cf4f52a77041..3d931ab89b6f 100644
--- 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.py
@@ -65,7 +65,12 @@ class TestWorkloadReporting:
# 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"
+ final = json.loads(redis.get(run_key("run-rt")))
+ assert final["phase"] == "finished"
+ # A stale current buffer here inflates `co_tenant_sum_buffer_bytes` for a neighbour that
+ # dies afterwards; the peak stays because that is what blame is judged on.
+ assert final["buffer_bytes"] == 0
+ assert final["peak_buffer_bytes"] == 500
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
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py
index be7cb6f8b197..a8b3d6cdd831 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/repartition_table.py
@@ -11,6 +11,7 @@ policy re-runs it in this run (the workflow swallows the failure if retries exha
import time
import uuid
+import socket
import asyncio
import datetime as dt
import dataclasses
@@ -26,6 +27,7 @@ from temporalio import activity
from temporalio.exceptions import ApplicationError
from posthog.exceptions_capture import capture_exception
+from posthog.temporal.common.activity_context import current_activity_attempt
from posthog.temporal.common.heartbeat_sync import HeartbeaterSync
from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.utils import retry_on_db_connection_drop
@@ -58,6 +60,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
DELTA_REPARTITION_TOTAL,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.job_context import bind_job_context
+from products.warehouse_sources.backend.temporal.data_imports.workload_report import workload_reporting
LOGGER = get_logger(__name__)
@@ -371,7 +374,22 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
try:
# HeartbeaterSync heartbeats on a background thread while the (possibly long) rewrite streams,
# and on worker shutdown, so Temporal reschedules us instead of timing the activity out.
- with HeartbeaterSync(logger=logger):
+ # The workload reporter makes the rewrite visible to pod co-tenant accounting (see
+ # `workload_report.py`): without it a rewrite-heavy pod looks idle to the OOM classifier's
+ # culprit rule. The run_id is prefixed because the sync's import activity reports under the
+ # bare job id on this same pod, and sharing its key would let a death during that import
+ # read this rewrite's report as its own last words.
+ with (
+ HeartbeaterSync(logger=logger),
+ workload_reporting(
+ team_id=inputs.team_id,
+ schema_id=inputs.schema_id,
+ run_id=f"repartition:{inputs.job_id}",
+ host=socket.gethostname(),
+ initial_phase="repartition",
+ attempt=current_activity_attempt(),
+ ),
+ ):
result = async_to_sync(repartition_table_in_place)(
table_ref=table_ref,
schema=schema,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workload_report.py b/products/warehouse_sources/backend/temporal/data_imports/workload_report.py
index cb85c348beaf..5b03ca07296a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workload_report.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workload_report.py
@@ -1,6 +1,6 @@
-"""Per-run workload self-reporting for warehouse sync activities.
+"""Per-run workload self-reporting for warehouse sync and repartition activities.
-Each import activity periodically writes what it is doing — phase, current in-memory buffer, process
+Each reporting 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`
@@ -241,7 +241,13 @@ class WorkloadReporter:
"host": self._host,
"attempt": self._attempt,
"phase": "finished" if final else self._phase,
- "buffer_bytes": self._buffer_bytes,
+ # A run that reached teardown released its buffer while unwinding, so the last
+ # value the hooks saw is stale — a rewrite that raised mid-flush still reports the
+ # batch it was writing. Zero it for the same reason the phase becomes "finished":
+ # this run holds nothing now. `peak_buffer_bytes` keeps the real high-water mark,
+ # which is what blame is judged on. A run that died with its pod never writes a
+ # final sample at all, so this cannot erase a death's own last words.
+ "buffer_bytes": 0 if final else self._buffer_bytes,
"peak_buffer_bytes": self._peak_buffer_bytes,
"rss_bytes": rss_bytes,
"peak_rss_bytes": self._peak_rss_bytes or None,
@@ -413,6 +419,7 @@ def enrich_death_event_properties(
"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"),
+ "co_tenant_repartition_count": sum(1 for phase in phases if phase == "repartition"),
}
)
if death_ts is not None: