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-warehouse): drop per-table labels from loader metrics (#113534)

Tom Owers6edf675a97cf
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/source_manager.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/source_manager.py
index ae2b560676e1..91e13d302a94 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/source_manager.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/source_manager.py
@@ -389,7 +389,7 @@ async def build_output_lanes(
key_columns = [*keys, CDC_OP_COLUMN] if keys else None
position = await read_lane_position(delta_table, key_columns=key_columns if is_append else None)
positions.append(position.position)
- replay = ReplayFilter(position, team_id=job.team_id)
+ replay = ReplayFilter(position)
lanes.append(
OutputLane(
name=lane.resource_name,
@@ -515,7 +515,7 @@ class ReplayFilter:
capture would close it, and is the follow-up.
"""
- def __init__(self, position: LanePosition, *, team_id: int | None = None) -> None:
+ def __init__(self, position: LanePosition) -> None:
self._position = position.position
self._applied = {key: list(rows) for key, rows in position.applied.items()}
# Taken from the position itself, so the batch is keyed exactly as the table was read.
@@ -523,7 +523,6 @@ class ReplayFilter:
self._content_schema = position.content_schema
self._content_matched = position.content_matched
self._load_applied = position.load_applied
- self._team_id = team_id
self.rows_skipped = 0
def apply(self, table: pa.Table) -> pa.Table:
@@ -548,8 +547,8 @@ class ReplayFilter:
# `superseded` is the series the loader raised while the position lived there. It now
# comes from the extraction workers, so a dashboard filtered to the load fleet loses it.
self.rows_skipped += dropped
- if dropped and self._team_id is not None:
- CDC_SEQ_GUARD_ROWS_DROPPED_TOTAL.labels(team_id=str(self._team_id), reason=reason).inc(dropped)
+ if dropped:
+ CDC_SEQ_GUARD_ROWS_DROPPED_TOTAL.labels(reason=reason).inc(dropped)
def _drop_already_written(self, table: pa.Table) -> pa.Table:
# A source column of the same name is customer data, so comparing it against this lane's
diff --git a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_source_manager.py b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_source_manager.py
index 0f4e27addc03..f308b9fb2943 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_source_manager.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/cdc/tests/test_source_manager.py
@@ -640,9 +640,7 @@ class TestReplayFilter:
# `superseded` is the series the loader raised while the position lived there. Reporting
# the identity drop under the same name would flatten a dashboard onto one number.
counter = MagicMock()
- replay = ReplayFilter(
- LanePosition(position=20, applied=_held((2, "I")), key_columns=("id", CDC_OP_COLUMN)), team_id=7
- )
+ replay = ReplayFilter(LanePosition(position=20, applied=_held((2, "I")), key_columns=("id", CDC_OP_COLUMN)))
with patch(
"products.warehouse_sources.backend.temporal.data_imports.cdc.source_manager."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py
index 1c8be4b29b3b..094d5e896bb5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py
@@ -592,7 +592,7 @@ async def maybe_flag_for_repartition(
if target is None:
# Needs repartition but nothing finer to do (datetime at hour, numerical can't shrink, unpartitionable).
# `reason` is reported on the metric + event so a skipped table is diagnosable.
- DELTA_REPARTITION_SKIP_TOTAL.labels(team_id=str(schema.team_id), reason=reason).inc()
+ DELTA_REPARTITION_SKIP_TOTAL.labels(reason=reason).inc()
props = base_event_props(schema, source, str(job.id))
props.update(
{
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
index 0fe0225abe86..724706025293 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/metrics.py
@@ -3,20 +3,18 @@ from prometheus_client import Counter, Gauge, Histogram
DELTA_WRITE_DURATION_SECONDS = Histogram(
"warehouse_load_delta_write_duration_seconds",
"Duration of Delta Lake write operations",
- labelnames=["team_id", "schema_id", "write_type"],
+ labelnames=["write_type"],
buckets=(0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0),
)
DELTA_ROWS_WRITTEN_TOTAL = Counter(
"warehouse_load_delta_rows_written_total",
"Total rows written to Delta Lake",
- labelnames=["team_id", "schema_id"],
)
IDEMPOTENCY_HIT_TOTAL = Counter(
"warehouse_load_idempotency_hit_total",
"Total idempotency cache hits (batch already processed)",
- labelnames=["team_id", "schema_id"],
)
APPEND_ROLLBACK_TOTAL = Counter(
@@ -31,8 +29,8 @@ PARQUET_READ_DURATION_SECONDS = Histogram(
buckets=(0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0),
)
-# One series for each step and no team or schema label: every batch of every table observes each
-# step, so a tenant label would multiply the series by the number of schemas.
+# No team or schema label on any loader metric: one series per table would grow without bound on a
+# long-lived pod. Per-table detail belongs on the structured log lines.
BATCH_STEP_DURATION_SECONDS = Histogram(
"warehouse_load_batch_step_duration_seconds",
"Duration of one step of a batch load, by step",
@@ -40,26 +38,22 @@ BATCH_STEP_DURATION_SECONDS = Histogram(
buckets=(0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0),
)
-# TODO: the `team_id`/`schema_id` labels below are high cardinality — keep only for the gated rollout
-# so we can debug per-team behaviour, then drop them before fully rolling out (per-team diagnosability
-# is also covered by the `warehouse_repartition_*` capture events).
DELTA_REPARTITION_DURATION_SECONDS = Histogram(
"warehouse_load_delta_repartition_duration_seconds",
"Duration of an in-place Delta table repartition",
- labelnames=["team_id", "schema_id"],
buckets=(1.0, 5.0, 15.0, 30.0, 60.0, 120.0, 300.0, 600.0, 1800.0, 3600.0),
)
DELTA_REPARTITION_TOTAL = Counter(
"warehouse_load_delta_repartition_total",
"Total in-place Delta repartitions by outcome",
- labelnames=["team_id", "outcome"],
+ labelnames=["outcome"],
)
DELTA_REPARTITION_SKIP_TOTAL = Counter(
"warehouse_load_delta_repartition_skip_total",
"Tables over the partition-size budget that the controller skipped, by reason",
- labelnames=["team_id", "reason"],
+ labelnames=["reason"],
)
# Deliberately unlabelled by team: this fires on every sync of every over-fragmented table fleet-wide,
@@ -75,7 +69,7 @@ DELTA_COARSEN_DECLINE_TOTAL = Counter(
CDC_SEQ_GUARD_ROWS_DROPPED_TOTAL = Counter(
"warehouse_load_cdc_seq_guard_rows_dropped_total",
"CDC rows dropped before the write as already-applied, by reason",
- labelnames=["team_id", "reason"],
+ labelnames=["reason"],
)
# Non-zero means a DELETE is about to erase data the target still holds. Alert on this; enrichment
@@ -83,7 +77,6 @@ CDC_SEQ_GUARD_ROWS_DROPPED_TOTAL = Counter(
CDC_DELETE_ENRICHMENT_VIOLATIONS_TOTAL = Counter(
"warehouse_load_cdc_delete_enrichment_violations_total",
"DELETE rows that would null a data column the target currently holds",
- labelnames=["team_id"],
)
# deltalite real-write path (phase 2). `outcome` is one of:
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.py
index 23aa1f810eeb..a29dc78742cc 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
@@ -166,7 +166,6 @@ def _enrich_cdc_rows(
existing_delta_table: deltalake.DeltaTable | None,
batch_index: int,
verify_deletes: bool = False,
- team_id: str = "",
) -> pa.Table:
"""Cross-batch CDC enrichment against the existing DeltaLake state.
@@ -246,9 +245,7 @@ def _enrich_cdc_rows(
if verify_deletes and delete_key_set:
report = verify_delete_enrichment(pa_table, present_pks, existing_rows)
if not report.ok:
- CDC_DELETE_ENRICHMENT_VIOLATIONS_TOTAL.labels(team_id=team_id).inc(
- report.rows_with_nulled_columns
- )
+ CDC_DELETE_ENRICHMENT_VIOLATIONS_TOTAL.inc(report.rows_with_nulled_columns)
logger.warning(
"cdc_delete_enrichment_violation",
delete_rows_checked=report.delete_rows_checked,
@@ -269,7 +266,6 @@ def _resolve_cdc_positions(
*,
primary_keys: list[str],
cdc_write_mode: str | None,
- team_id: str,
) -> pa.Table:
"""Collapse a merge batch to one row per key — the write engine rejects duplicates."""
if not has_engine_seq(pa_table):
@@ -281,7 +277,7 @@ def _resolve_cdc_positions(
cdc_write_mode=cdc_write_mode,
)
if stats.duplicate_key:
- CDC_SEQ_GUARD_ROWS_DROPPED_TOTAL.labels(team_id=team_id, reason="duplicate_key").inc(stats.duplicate_key)
+ CDC_SEQ_GUARD_ROWS_DROPPED_TOTAL.labels(reason="duplicate_key").inc(stats.duplicate_key)
return pa_table
@@ -1107,9 +1103,6 @@ def _process_message_reported(
)
try:
- team_id_str = str(export_signal.team_id)
- schema_id_str = str(export_signal.schema_id)
-
# Build the helper early so the idempotency check can use it as a
# delta-history fallback when the Redis dedup flag is missing — the case
# where the writer crashed between `DeltaWriter.write` committing and
@@ -1186,7 +1179,7 @@ def _process_message_reported(
deliver_batch_to_destinations(export_signal)
if already_processed and not export_signal.is_final_batch:
- IDEMPOTENCY_HIT_TOTAL.labels(team_id=team_id_str, schema_id=schema_id_str).inc()
+ IDEMPOTENCY_HIT_TOTAL.inc()
logger.info(
"batch_already_processed",
team_id=export_signal.team_id,
@@ -1302,7 +1295,6 @@ def _process_message_reported(
existing_delta_table=existing_delta_table,
batch_index=export_signal.batch_index,
verify_deletes=resolution_enabled,
- team_id=team_id_str,
)
if resolution_enabled:
@@ -1310,7 +1302,6 @@ def _process_message_reported(
pa_table,
primary_keys=primary_keys or [],
cdc_write_mode=cdc_write_mode,
- team_id=team_id_str,
)
if existing_delta_table is not None:
@@ -1346,9 +1337,7 @@ def _process_message_reported(
with (
timer.step("write"),
- DELTA_WRITE_DURATION_SECONDS.labels(
- team_id=team_id_str, schema_id=schema_id_str, write_type="scd2_append"
- ).time(),
+ DELTA_WRITE_DURATION_SECONDS.labels(write_type="scd2_append").time(),
):
scd2_writer = Scd2DeltaWriter(
delta_table_ref,
@@ -1376,9 +1365,7 @@ def _process_message_reported(
with (
timer.step("write"),
- DELTA_WRITE_DURATION_SECONDS.labels(
- team_id=team_id_str, schema_id=schema_id_str, write_type=write_type
- ).time(),
+ DELTA_WRITE_DURATION_SECONDS.labels(write_type=write_type).time(),
):
delta_writer = DeltaWriter(delta_table_ref)
delta_table = async_to_sync(delta_writer.write)(
@@ -1391,7 +1378,7 @@ def _process_message_reported(
)
deltalite_file_count_change = delta_writer.deltalite_file_count_change
- DELTA_ROWS_WRITTEN_TOTAL.labels(team_id=team_id_str, schema_id=schema_id_str).inc(pa_table.num_rows)
+ DELTA_ROWS_WRITTEN_TOTAL.inc(pa_table.num_rows)
# Marked as soon as the commit lands, before post-load: the final row of a run carries its own
# data now, so a post-load failure must send the retry down the post-load-only path rather
@@ -1431,7 +1418,10 @@ def _process_message_reported(
logger.debug(
"batch_written_to_delta_lake",
+ team_id=export_signal.team_id,
+ external_data_schema_id=export_signal.schema_id,
batch_index=export_signal.batch_index,
+ rows_written=pa_table.num_rows,
batch_count=len(members),
delta_version=delta_table_ref.latest_known_version(delta_table),
file_count=file_count,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
index 5c385675eb6b..50b14eae1d37 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/load/test_processor.py
@@ -1271,7 +1271,6 @@ class TestEnrichCdcRows:
table,
primary_keys=["id"],
cdc_write_mode=cdc_write_mode,
- team_id="2",
)
def test_the_merge_lane_collapses_a_key_to_its_latest_version(self):
@@ -1320,10 +1319,9 @@ class TestEnrichCdcRows:
existing_delta_table=DeltaTable(path),
batch_index=0,
verify_deletes=True,
- team_id="2",
)
- violations.labels.assert_not_called()
+ violations.inc.assert_not_called()
def test_verification_reports_a_delete_that_would_null_target_data(self):
with tempfile.TemporaryDirectory() as path:
@@ -1342,11 +1340,9 @@ class TestEnrichCdcRows:
existing_delta_table=DeltaTable(path),
batch_index=0,
verify_deletes=True,
- team_id="2",
)
- violations.labels.assert_called_once_with(team_id="2")
- violations.labels.return_value.inc.assert_called_once_with(1)
+ violations.inc.assert_called_once_with(1)
def test_verification_is_skipped_when_the_flag_is_off(self):
with tempfile.TemporaryDirectory() as path:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
index 67654de72d39..afef0b6bfbc4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
@@ -771,7 +771,10 @@ class DeltaBatchConsumerAdapter:
)
capture_exception(e)
- async def _observe_queue_freshness(self, conn: psycopg.AsyncConnection[Any]) -> None:
+ async def observe_queue_gauges(self, conn: psycopg.AsyncConnection[Any]) -> bool:
+ return await self._observe_queue_freshness(conn)
+
+ async def _observe_queue_freshness(self, conn: psycopg.AsyncConnection[Any]) -> bool:
"""Report the age of the oldest batch no consumer has picked up yet, and the queue depth.
This is the loader's data-freshness signal: it rises whenever loading
@@ -795,6 +798,8 @@ class DeltaBatchConsumerAdapter:
and exports NaN. The whole probe also has a client timeout,
so it cannot eat the reconcile sweep's budget. Other failures are
swallowed-with-capture so a broken probe can't take the sweep down.
+
+ Returns True when this pod holds the gauge slot.
"""
clear_queue_sample_gauges()
holds_slot = False
@@ -806,7 +811,7 @@ class DeltaBatchConsumerAdapter:
if not holds_slot:
self._depth_sample = None
logger.debug("queue_gauges_slot_held_elsewhere")
- return
+ return False
await self._sample_queue_gauges(conn)
except TimeoutError:
logger.error( # noqa: TRY400 — designed degraded path, traceback is noise
@@ -816,11 +821,12 @@ class DeltaBatchConsumerAdapter:
OLDEST_UNCLAIMED_BATCH_SECONDS.set(FRESHNESS_WINDOW_SECONDS)
if holds_slot:
self._export_last_depth_sample()
- return
+ return holds_slot
except Exception as e:
logger.exception("queue_freshness_probe_failed")
capture_exception(e)
- return
+ return holds_slot
+ return True
async def _sample_queue_gauges(self, conn: psycopg.AsyncConnection[Any]) -> None:
try:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
index b678f2e44827..b1c2fe97bd12 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
@@ -1,4 +1,5 @@
import math
+import time
import asyncio
from datetime import UTC, datetime
from typing import Any, NamedTuple, cast
@@ -1056,6 +1057,71 @@ class TestAdminShutdownErrorClassification:
mock_capture.assert_not_called()
+ @pytest.mark.asyncio
+ async def test_queue_gauges_are_probed_before_the_first_poll(self):
+ consumer = _make_consumer()
+ calls: list[str] = []
+
+ async def probe(*args: Any, **kwargs: Any) -> bool:
+ calls.append("probe")
+ return True
+
+ async def first_poll(*args: Any, **kwargs: Any) -> list[PendingBatch]:
+ calls.append("poll")
+ consumer._shutdown.set()
+ return []
+
+ with (
+ patch.object(consumer, "_connect", new_callable=AsyncMock, return_value=_make_healthy_conn()),
+ patch.object(consumer, "_install_signal_handlers"),
+ patch.object(consumer._adapter, "observe_queue_gauges", side_effect=probe),
+ patch.object(consumer, "_recovery_sweep_with_timeout", new_callable=AsyncMock),
+ patch.object(consumer_module.BatchQueue, "get_unprocessed_and_lock", side_effect=first_poll),
+ patch.object(consumer_module.BatchQueue, "release_all_owned_leases", new_callable=AsyncMock),
+ ):
+ await asyncio.wait_for(consumer.run(), timeout=5.0)
+
+ assert calls[:2] == ["probe", "poll"]
+ assert consumer._holds_gauge_slot is True
+
+ @pytest.mark.parametrize(
+ "holds_slot, in_warmup, expect_probe",
+ [
+ (False, True, True),
+ (True, True, False),
+ (False, False, False),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_recovery_loop_retries_the_gauge_slot_only_while_a_new_pod_lacks_it(
+ self, holds_slot, in_warmup, expect_probe
+ ):
+ consumer = _make_consumer(recovery_interval_seconds=0.01)
+ consumer._holds_gauge_slot = holds_slot
+ consumer._gauge_warmup_deadline = time.monotonic() + (60 if in_warmup else -1)
+ second_tick = asyncio.Event()
+ sweeps = 0
+
+ async def sweep() -> None:
+ nonlocal sweeps
+ sweeps += 1
+ if sweeps == 2:
+ second_tick.set()
+
+ with (
+ patch.object(consumer, "_recovery_sweep_with_timeout", side_effect=sweep),
+ patch.object(consumer, "_reconcile_failed_runs", new_callable=AsyncMock),
+ patch.object(
+ consumer._adapter, "observe_queue_gauges", new_callable=AsyncMock, return_value=False
+ ) as probe,
+ ):
+ loop_task = asyncio.create_task(consumer._recovery_loop())
+ await asyncio.wait_for(second_tick.wait(), timeout=2.0)
+ consumer._shutdown.set()
+ await asyncio.wait_for(loop_task, timeout=5.0)
+
+ assert (probe.await_count > 0) is expect_probe
+
@pytest.mark.asyncio
async def test_recovery_sweep_does_not_report_admin_shutdown_error(self):
# Same self-healing admin-initiated disconnect, but hit by the periodic recovery
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 a33f0256ea7f..da597ec2db1d 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
@@ -464,7 +464,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
f"down until the next sync schema_id={schema.id}",
schema_id=str(schema.id),
)
- DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="killed").inc()
+ DELTA_REPARTITION_TOTAL.labels(outcome="killed").inc()
_capture_stood_down(schema, inputs, trigger_reason, "attempt_killed_without_progress", logger)
return
@@ -531,7 +531,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
f"repartition: stopped at a commit for worker shutdown, handing off rows_written={e.rows_written}",
rows_written=e.rows_written,
)
- DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="handed_off").inc()
+ DELTA_REPARTITION_TOTAL.labels(outcome="handed_off").inc()
_refund_attempt(schema, charged_attempts, logger)
_capture_stood_down(schema, inputs, trigger_reason, "worker_shutdown", logger)
raise WorkerShuttingDownError.from_activity_context() from e
@@ -542,7 +542,6 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
# progress counts toward `MAX_REPARTITION_ATTEMPTS` so a doomed rewrite still gives up.
logger.warning(f"repartition: {e}")
DELTA_REPARTITION_TOTAL.labels(
- team_id=str(inputs.team_id),
outcome=_handle_budget_exceeded(
inputs, schema, pending, trigger_reason, e, claim_token, logger, charged_attempts
),
@@ -554,7 +553,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
# but still emit the skip: a started event with no terminal event leaves `repartition_pending`
# set and no way to tell a stood-down attempt from one that vanished.
logger.info("repartition: superseded by a newer attempt, standing down")
- DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="superseded").inc()
+ DELTA_REPARTITION_TOTAL.labels(outcome="superseded").inc()
_refund_attempt(schema, charged_attempts, logger)
_capture_stood_down(schema, inputs, trigger_reason, "superseded", logger)
return
@@ -568,7 +567,6 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
# schema's imports until then (see `_import_held_for_repartition`).
logger.error("repartition: the swap landed but its scheme could not be saved; imports stay held", exc_info=True)
DELTA_REPARTITION_TOTAL.labels(
- team_id=str(inputs.team_id),
outcome=_handle_failure(inputs, schema, pending, trigger_reason, e, claim_token, logger, charged_attempts),
).inc()
return
@@ -586,7 +584,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
props = base_event_props(schema, schema.source, inputs.job_id)
props.update({"trigger_reason": trigger_reason, "reason": str(e)})
capture_repartition_event("warehouse_repartition_skipped", props)
- DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="skipped").inc()
+ DELTA_REPARTITION_TOTAL.labels(outcome="skipped").inc()
capture_exception(e)
return
except asyncio.CancelledError:
@@ -610,7 +608,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
# (e.g. it swept our temp mid-write). It owns the retry; recording our wreckage as a
# failure would burn an attempt and pollute error tracking with self-inflicted noise.
logger.info("repartition: failed after being superseded, standing down", exc_info=True)
- DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="superseded").inc()
+ DELTA_REPARTITION_TOTAL.labels(outcome="superseded").inc()
_refund_attempt(schema, charged_attempts, logger)
_capture_stood_down(schema, inputs, trigger_reason, "superseded_after_error", logger)
return
@@ -621,7 +619,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
# error tracking — a condition nobody can act on (e.g. a pgbouncer login-retry cooldown)
# shouldn't trip an issue there; the log line, the transient metric, and the skipped
# event's reason="transient_infra_error" already carry the visibility.
- DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="transient").inc()
+ DELTA_REPARTITION_TOTAL.labels(outcome="transient").inc()
if trigger_reason == "admin":
# An operator staged this rewrite precisely because syncing on the old layout is
# pathological (e.g. a badly over-partitioned table merging one commit per partition
@@ -645,7 +643,7 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
failure_outcome = _handle_failure(
inputs, schema, pending, trigger_reason, e, claim_token, logger, charged_attempts
)
- DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome=failure_outcome).inc()
+ DELTA_REPARTITION_TOTAL.labels(outcome=failure_outcome).inc()
return
except BaseException as e:
if not _is_native_panic(e):
@@ -657,14 +655,13 @@ def _maybe_repartition_table(inputs: RepartitionActivityInputs, logger: Filterin
# the remaining retries on it and holds the sync behind a rewrite that cannot finish.
logger.error("repartition: the rewrite panicked inside the native delta stack", exc_info=True)
DELTA_REPARTITION_TOTAL.labels(
- team_id=str(inputs.team_id),
outcome=_handle_failure(inputs, schema, pending, trigger_reason, e, claim_token, logger, charged_attempts),
).inc()
return
duration = time.monotonic() - start
- DELTA_REPARTITION_DURATION_SECONDS.labels(team_id=str(inputs.team_id), schema_id=inputs.schema_id).observe(duration)
- DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome=result.get("outcome", "completed")).inc()
+ DELTA_REPARTITION_DURATION_SECONDS.observe(duration)
+ DELTA_REPARTITION_TOTAL.labels(outcome=result.get("outcome", "completed")).inc()
if result.get("outcome") != "completed":
# A non-completed result is a skip that ran no rewrite (live unreadable or no delta table on
@@ -728,11 +725,9 @@ def _defer_to_full_refresh(
if not transient:
capture_exception(e)
logger.warning("repartition: could not stage the scheme for the next full refresh", exc_info=True)
- DELTA_REPARTITION_TOTAL.labels(
- team_id=str(inputs.team_id), outcome="transient" if transient else "failed"
- ).inc()
+ DELTA_REPARTITION_TOTAL.labels(outcome="transient" if transient else "failed").inc()
return
- DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="deferred").inc()
+ DELTA_REPARTITION_TOTAL.labels(outcome="deferred").inc()
props = base_event_props(schema, schema.source, inputs.job_id)
props.update({"trigger_reason": trigger_reason, **result})
capture_repartition_event("warehouse_repartition_skipped", props)
@@ -1017,7 +1012,7 @@ def _give_up(
# the controller has abandoned surfaces as an issue instead of only a metric — the sync context is
# already bound (bind_job_context) so the issue is attributed to the connector and table.
capture_exception(error)
- DELTA_REPARTITION_TOTAL.labels(team_id=str(inputs.team_id), outcome="failed").inc()
+ DELTA_REPARTITION_TOTAL.labels(outcome="failed").inc()
def _charge_attempt(
diff --git a/products/warehouse_sources_queue/backend/core/batch_consumer.py b/products/warehouse_sources_queue/backend/core/batch_consumer.py
index 4c17f4ffc8f0..3a5aaccb8b65 100644
--- a/products/warehouse_sources_queue/backend/core/batch_consumer.py
+++ b/products/warehouse_sources_queue/backend/core/batch_consumer.py
@@ -41,6 +41,9 @@ RECOVERY_GRACE_SECONDS = 300
# Reconcile sweep: catch runs whose queue batch failed but whose ExternalDataJob was left non-terminal.
RECONCILE_INTERVAL_SECONDS = 300.0
RECONCILE_GRACE_SECONDS = 120 # don't race a _fail_run that is still in flight
+# After start, a pod without the queue-gauge slot retries every recovery tick for this long, so it
+# takes the slot soon after the previous holder's lease lapses instead of at the next reconcile.
+GAUGE_SLOT_WARMUP_SECONDS = RECONCILE_INTERVAL_SECONDS
RECONCILE_LOOKBACK_SECONDS = 24 * 60 * 60 # wide enough to catch jobs orphaned by consumer outages
SHUTDOWN_DRAIN_TIMEOUT_SECONDS = 30.0
@@ -417,6 +420,10 @@ class BatchConsumerAdapter(Protocol):
limit: int,
) -> None: ...
+ async def observe_queue_gauges(self, conn: psycopg.AsyncConnection[Any]) -> bool:
+ """Sample the queue-wide gauges if this pod holds the gauge slot; True means it does."""
+ ...
+
async def should_process_batch(
self,
conn: psycopg.AsyncConnection[Any],
@@ -483,6 +490,8 @@ class BatchConsumer:
self._in_flight: dict[tuple[int, str], asyncio.Task[None]] = {}
# Monotonic stamp of the last reconcile sweep; runs inside the recovery loop so both share one connection.
self._last_reconcile_monotonic = 0.0
+ self._holds_gauge_slot = False
+ self._gauge_warmup_deadline = 0.0
# batch_id -> monotonic start, for the stuck-batch watchdog.
self._inflight_started: dict[str, float] = {}
self._inflight_progress: dict[str, BatchPhaseProgress] = {}
@@ -695,6 +704,8 @@ class BatchConsumer:
# scans the whole queue and can outlast the health server's startup
# grace window, and a pod liveness-killed mid-sweep can never boot.
self._heartbeat_task = asyncio.create_task(self._heartbeat_loop())
+ self._gauge_warmup_deadline = time.monotonic() + GAUGE_SLOT_WARMUP_SECONDS
+ await self._probe_queue_gauges()
try:
await self._recovery_sweep_with_timeout()
except psycopg.OperationalError as e:
@@ -1611,6 +1622,9 @@ class BatchConsumer:
else:
self._report_queue_failure(self._event("recovery_sweep_error"), e)
+ if not self._holds_gauge_slot and time.monotonic() < self._gauge_warmup_deadline:
+ await self._probe_queue_gauges()
+
now = time.monotonic()
if now - self._last_reconcile_monotonic >= self._config.reconcile_interval_seconds:
self._last_reconcile_monotonic = now
@@ -1638,6 +1652,21 @@ class BatchConsumer:
except Exception as e:
self._report_queue_failure(self._event("reconcile_sweep_error"), e)
+ async def _probe_queue_gauges(self) -> None:
+ """Sample the queue gauges outside the reconcile cadence; a failed probe must never stop the consumer."""
+ probe_timeout_ctx = asyncio.timeout(self._config.sweep_timeout_seconds)
+ try:
+ async with probe_timeout_ctx:
+ self._holds_gauge_slot = await self._with_queue_conn(
+ "_recovery_conn",
+ "observe_queue_gauges",
+ self._adapter.observe_queue_gauges,
+ should_abort=probe_timeout_ctx.expired,
+ )
+ except Exception:
+ self._holds_gauge_slot = False
+ logger.warning(self._event("queue_gauge_probe_failed"), exc_info=True)
+
async def _recovery_sweep_with_timeout(self) -> None:
"""Run the recovery sweep under the sweep timeout; a sweep that never returns must not stall the consumer."""
sweep_timeout_ctx = asyncio.timeout(self._config.sweep_timeout_seconds)
diff --git a/products/warehouse_sources_queue/backend/sdk/jobs.py b/products/warehouse_sources_queue/backend/sdk/jobs.py
index aa1969461964..e282d0dcebc3 100644
--- a/products/warehouse_sources_queue/backend/sdk/jobs.py
+++ b/products/warehouse_sources_queue/backend/sdk/jobs.py
@@ -342,6 +342,9 @@ class GenericJobAdapter:
# repair (the batch queue's reconcile exists for ExternalDataJob rows).
return
+ async def observe_queue_gauges(self, conn: psycopg.AsyncConnection[Any]) -> bool:
+ return False
+
async def should_process_batch(
self,
conn: psycopg.AsyncConnection[Any],