: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): keep the shadow scheduler alive through long refreshes (#111964)
Tom Owers18859386c93d
diff --git a/products/warehouse_sources/backend/scheduling/runner.py b/products/warehouse_sources/backend/scheduling/runner.pyindex 29df7ee54c9f..370545559d33 100644--- a/products/warehouse_sources/backend/scheduling/runner.py+++ b/products/warehouse_sources/backend/scheduling/runner.py@@ -73,7 +73,7 @@ SCHEMAS_IN_SCOPE = Gauge(DUE_PER_TICK = Histogram("warehouse_pg_scheduler_due_per_tick","Number of due schemas claimed per leader tick",- buckets=(0, 1, 5, 10, 25, 50, 100, 250, 500, 1000),+ buckets=(0, 1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 25000),)FIRE_LATENESS_SECONDS = Histogram(@@ -102,6 +102,19 @@ class ShadowSchedulerConfig:claim_limit: int = 1000decision_retention_days: int = 30refresh_page_size: int = REFRESH_PAGE_SIZE+ # Just under the tick interval, so a backlog drain yields to the next tick+ # and to shutdown.+ drain_budget_seconds: float = 55.0+++@frozen+class DrainBatchOutcome:+ """Counts from one claim/evaluate/advance transaction of the due scan."""++ due: int+ decisions_inserted: int+ duplicate_windows: int+ missed_windows: intclass ShadowScheduler:@@ -159,69 +172,98 @@ class ShadowScheduler:ttl_seconds=self._config.refresh_interval_seconds,)if refresh_won:- await self._refresh(conn)-- now_epoch = int(time.time())- async with conn.transaction():- due = await SchedulerStateTable.claim_due(conn, kind=SYNC_EXTRACT_KIND, limit=self._config.claim_limit)- result = await evaluate_due(due, now_epoch)- inserted_records, refused = await SchedulerStateTable.insert_decisions(conn, list(result.records))-- advances = []- for row in due:- cadence = SchemaCadence(interval_seconds=row.interval_seconds, offset_seconds=row.offset_seconds)- advances.append((row, datetime.fromtimestamp(next_due_after(now_epoch, cadence), tz=UTC)))- await SchedulerStateTable.advance_states(conn, advances)-- out_of_scope = [r.schedule_key for r in result.records if r.decision == DECISION_SKIP_OUT_OF_SCOPE]- if out_of_scope:- await SchedulerStateTable.delete_states(conn, SYNC_EXTRACT_KIND, out_of_scope)-- DUE_PER_TICK.observe(len(due))- for record in inserted_records:- FIRE_LATENESS_SECONDS.observe(record.late_seconds)- if record.decision == DECISION_WOULD_FIRE:- WOULD_FIRE_TOTAL.inc()- logger.info(- "scheduler_would_fire",- schema_id=record.schedule_key,- team_id=record.team_id,- due_at=record.due_at.isoformat(),- late_seconds=record.late_seconds,- )- else:- SKIPS_TOTAL.labels(reason=SKIP_REASONS[record.decision]).inc()- logger.info(- "scheduler_skip",- schema_id=record.schedule_key,- team_id=record.team_id,- due_at=record.due_at.isoformat(),- reason=SKIP_REASONS[record.decision],- )- if refused:- DUPLICATE_WINDOWS_TOTAL.inc(refused)- due_by_schema = {row.schedule_key: row for row in due}- inserted_missed_windows = 0- for record in inserted_records:- row = due_by_schema[record.schedule_key]- inserted_missed_windows += max(- 0, (int(record.due_at.timestamp()) - int(row.next_due_at.timestamp())) // row.interval_seconds- )- if inserted_missed_windows:- MISSED_WINDOWS_TOTAL.inc(inserted_missed_windows)+ await self._refresh(conn, health_reporter)++ # Drain the backlog in claim_limit batches, one transaction each, so+ # a backlog larger than one claim does not make every fire late.+ drain_started = time.monotonic()+ batches = 0+ due = 0+ decisions_inserted = 0+ duplicate_windows = 0+ missed_windows = 0+ while True:+ outcome = await self._drain_batch(conn)+ batches += 1+ due += outcome.due+ decisions_inserted += outcome.decisions_inserted+ duplicate_windows += outcome.duplicate_windows+ missed_windows += outcome.missed_windows+ health_reporter()+ if outcome.due < self._config.claim_limit:+ break+ if time.monotonic() - drain_started >= self._config.drain_budget_seconds:+ break+ DUE_PER_TICK.observe(due)TICKS_TOTAL.labels(outcome="leader").inc()logger.info("scheduler_tick",- due=len(due),- decisions_inserted=len(inserted_records),- duplicate_windows=refused,- missed_windows=inserted_missed_windows,+ due=due,+ decisions_inserted=decisions_inserted,+ duplicate_windows=duplicate_windows,+ missed_windows=missed_windows,+ batches=batches,refreshed=refresh_won,)- health_reporter()- async def _refresh(self, conn: psycopg.AsyncConnection) -> None:+ async def _drain_batch(self, conn: psycopg.AsyncConnection) -> DrainBatchOutcome:+ now_epoch = int(time.time())+ async with conn.transaction():+ due = await SchedulerStateTable.claim_due(conn, kind=SYNC_EXTRACT_KIND, limit=self._config.claim_limit)+ result = await evaluate_due(due, now_epoch)+ inserted_records, refused = await SchedulerStateTable.insert_decisions(conn, list(result.records))++ advances = []+ for row in due:+ cadence = SchemaCadence(interval_seconds=row.interval_seconds, offset_seconds=row.offset_seconds)+ advances.append((row, datetime.fromtimestamp(next_due_after(now_epoch, cadence), tz=UTC)))+ await SchedulerStateTable.advance_states(conn, advances)++ out_of_scope = [r.schedule_key for r in result.records if r.decision == DECISION_SKIP_OUT_OF_SCOPE]+ if out_of_scope:+ await SchedulerStateTable.delete_states(conn, SYNC_EXTRACT_KIND, out_of_scope)++ for record in inserted_records:+ FIRE_LATENESS_SECONDS.observe(record.late_seconds)+ if record.decision == DECISION_WOULD_FIRE:+ WOULD_FIRE_TOTAL.inc()+ logger.info(+ "scheduler_would_fire",+ schema_id=record.schedule_key,+ team_id=record.team_id,+ due_at=record.due_at.isoformat(),+ late_seconds=record.late_seconds,+ )+ else:+ SKIPS_TOTAL.labels(reason=SKIP_REASONS[record.decision]).inc()+ logger.info(+ "scheduler_skip",+ schema_id=record.schedule_key,+ team_id=record.team_id,+ due_at=record.due_at.isoformat(),+ reason=SKIP_REASONS[record.decision],+ )+ if refused:+ DUPLICATE_WINDOWS_TOTAL.inc(refused)+ due_by_schema = {row.schedule_key: row for row in due}+ inserted_missed_windows = 0+ for record in inserted_records:+ row = due_by_schema[record.schedule_key]+ inserted_missed_windows += max(+ 0, (int(record.due_at.timestamp()) - int(row.next_due_at.timestamp())) // row.interval_seconds+ )+ if inserted_missed_windows:+ MISSED_WINDOWS_TOTAL.inc(inserted_missed_windows)++ return DrainBatchOutcome(+ due=len(due),+ decisions_inserted=len(inserted_records),+ duplicate_windows=refused,+ missed_windows=inserted_missed_windows,+ )++ async def _refresh(self, conn: psycopg.AsyncConnection, health_reporter: Callable[[], None]) -> None:started = time.monotonic()# DB-clock cutoff: upserts stamp refreshed_at with now() server-side, so# the stale-row delete must compare against the same clock.@@ -245,6 +287,9 @@ class ShadowScheduler:upserts = self._build_upserts(page, now_epoch)await SchedulerStateTable.upsert_states(conn, upserts)in_scope += len(upserts)+ # A full refresh can outlast the liveness timeout; a pod that keeps+ # paging is healthy, and a stuck one still stops reporting.+ health_reporter()deleted = await SchedulerStateTable.delete_states_not_refreshed_since(conn, SYNC_EXTRACT_KIND, refresh_start)pruned = await SchedulerStateTable.prune_decisions(diff --git a/products/warehouse_sources/backend/tests/test_scheduler_shadow.py b/products/warehouse_sources/backend/tests/test_scheduler_shadow.pyindex 41940dbdf907..75d0d959d822 100644--- a/products/warehouse_sources/backend/tests/test_scheduler_shadow.py+++ b/products/warehouse_sources/backend/tests/test_scheduler_shadow.py@@ -1,9 +1,11 @@import io+import mathimport timeimport uuidimport socketimport importlibimport urllib.request+from collections.abc import Callablefrom datetime import (UTC,datetime,@@ -261,23 +263,92 @@ class TestEvaluateDue:@pytest.mark.django_db(transaction=True)class TestShadowSchedulerTick:- def _setup_due_state(self, team_id: int) -> tuple[str, datetime, str]:+ def _setup_due_states(self, team_id: int, schema_ids: list[str]) -> tuple[datetime, str]:db_url = get_test_database_url()- schema_id = str(uuid.uuid4())due_at = (datetime.now(UTC) - timedelta(minutes=1)).replace(microsecond=0)with psycopg.Connection.connect(db_url, autocommit=True) as conn:ensure_scheduler_tables(conn)conn.execute(f"TRUNCATE {SCHEDULER_DECISION_TABLE}, {SCHEDULER_STATE_TABLE}")- conn.execute(- f"""- INSERT INTO {SCHEDULER_STATE_TABLE}- (kind, schedule_key, team_id, interval_seconds, offset_seconds, next_due_at)- VALUES (%s, %s, %s, 3600, 0, %s)- """,- (SYNC_EXTRACT_KIND, schema_id, team_id, due_at),- )+ for schema_id in schema_ids:+ conn.execute(+ f"""+ INSERT INTO {SCHEDULER_STATE_TABLE}+ (kind, schedule_key, team_id, interval_seconds, offset_seconds, next_due_at)+ VALUES (%s, %s, %s, 3600, 0, %s)+ """,+ (SYNC_EXTRACT_KIND, schema_id, team_id, due_at),+ )+ return due_at, db_url++ def _setup_due_state(self, team_id: int) -> tuple[str, datetime, str]:+ schema_id = str(uuid.uuid4())+ due_at, db_url = self._setup_due_states(team_id, [schema_id])return schema_id, due_at, db_url+ def _setup_due_schemas(self, team, count: int) -> tuple[set[str], str]:+ source = _create_source(team)+ schema_ids = [str(_create_schema(team, source, name=f"table_{i}").id) for i in range(count)]+ _, db_url = self._setup_due_states(team.pk, schema_ids)+ return set(schema_ids), db_url++ def _decided_keys(self, db_url: str) -> set[str]:+ with psycopg.Connection.connect(db_url) as conn:+ rows = conn.execute(f"SELECT schedule_key FROM {SCHEDULER_DECISION_TABLE}").fetchall()+ return {row[0] for row in rows}++ def _overdue_keys(self, db_url: str) -> set[str]:+ with psycopg.Connection.connect(db_url) as conn:+ rows = conn.execute(+ f"SELECT schedule_key FROM {SCHEDULER_STATE_TABLE} WHERE next_due_at <= now()"+ ).fetchall()+ return {row[0] for row in rows}++ @pytest.mark.parametrize(+ "schema_count,claim_limit,expected_batches",+ [+ pytest.param(0, 2, 1, id="empty"),+ pytest.param(1, 2, 1, id="under_limit"),+ pytest.param(4, 2, 3, id="exact_multiple_needs_empty_batch"),+ pytest.param(5, 2, 3, id="backlog_over_limit"),+ ],+ )+ def test_tick_drains_backlog_and_heartbeats_per_batch(+ self, team, monkeypatch, schema_count, claim_limit, expected_batches+ ):+ schema_ids, db_url = self._setup_due_schemas(team, schema_count)+ monkeypatch.setattr(+ scheduler_runner.JobsTable, "try_acquire_sentinel_slot", AsyncMock(side_effect=[True, False])+ )+ due_per_tick = MagicMock()+ monkeypatch.setattr(scheduler_runner, "DUE_PER_TICK", due_per_tick)+ health_reporter = MagicMock()++ scheduler = ShadowScheduler(ShadowSchedulerConfig(database_url=db_url, claim_limit=claim_limit))+ async_to_sync(scheduler._tick)(health_reporter)++ assert self._decided_keys(db_url) == schema_ids+ assert self._overdue_keys(db_url) == set()+ due_per_tick.observe.assert_called_once_with(schema_count)+ assert health_reporter.call_count >= expected_batches++ def test_drain_budget_defers_remaining_backlog_to_next_tick(self, team, monkeypatch):+ schema_ids, db_url = self._setup_due_schemas(team, 3)+ monkeypatch.setattr(+ scheduler_runner.JobsTable,+ "try_acquire_sentinel_slot",+ AsyncMock(side_effect=[True, False, True, False]),+ )+ scheduler = ShadowScheduler(ShadowSchedulerConfig(database_url=db_url, claim_limit=2, drain_budget_seconds=0))++ async_to_sync(scheduler._tick)(lambda: None)+ first_tick_keys = self._decided_keys(db_url)+ assert len(first_tick_keys) == 2+ assert self._overdue_keys(db_url) == schema_ids - first_tick_keys++ async_to_sync(scheduler._tick)(lambda: None)+ assert self._decided_keys(db_url) == schema_ids+ assert self._overdue_keys(db_url) == set()+def _record(self, schema_id: str, team_id: int, due_at: datetime) -> DecisionRecord:return DecisionRecord(team_id=team_id,@@ -374,11 +445,11 @@ class TestShadowSchedulerTick:@pytest.mark.django_db(transaction=True)class TestShadowSchedulerRefresh:- def _refresh(self, db_url: str, page_size: int) -> None:+ def _refresh(self, db_url: str, page_size: int, health_reporter: Callable[[], None] = lambda: None) -> None:async def run() -> None:scheduler = ShadowScheduler(ShadowSchedulerConfig(database_url=db_url, refresh_page_size=page_size))async with await psycopg.AsyncConnection.connect(db_url, autocommit=True) as conn:- await scheduler._refresh(conn)+ await scheduler._refresh(conn, health_reporter)async_to_sync(run)()@@ -405,11 +476,13 @@ class TestShadowSchedulerRefresh:_create_schema(team, source, name="out_of_scope", should_sync=False)in_scope_gauge = MagicMock()monkeypatch.setattr(scheduler_runner, "SCHEMAS_IN_SCOPE", in_scope_gauge)+ health_reporter = MagicMock()- self._refresh(db_url, page_size)+ self._refresh(db_url, page_size, health_reporter)assert self._state_keys(db_url) == schema_idsin_scope_gauge.set.assert_called_once_with(schema_count)+ assert health_reporter.call_count >= math.ceil(schema_count / page_size)@pytest.mark.parametrize("page_size", [1, 2, 10])def test_paged_refresh_deletes_schemas_that_left_scope(self, team, page_size):diff --git a/products/warehouse_sources_queue/backend/core/scheduler_state.py b/products/warehouse_sources_queue/backend/core/scheduler_state.pyindex 174616580328..41526d9c7888 100644--- a/products/warehouse_sources_queue/backend/core/scheduler_state.py+++ b/products/warehouse_sources_queue/backend/core/scheduler_state.py@@ -51,9 +51,15 @@ _UPSERT_STATE_SQL = f"""INSERT INTO {SCHEDULER_STATE_TABLE} (kind, schedule_key, team_id, interval_seconds, offset_seconds, next_due_at, refreshed_at, updated_at)- VALUES (- %(kind)s, %(schedule_key)s, %(team_id)s, %(interval_seconds)s, %(offset_seconds)s, %(next_due_at)s, now(), now()- )+ SELECT kind, schedule_key, team_id, interval_seconds, offset_seconds, next_due_at, now(), now()+ FROM unnest(+ %(kinds)s::text[],+ %(schedule_keys)s::text[],+ %(team_ids)s::bigint[],+ %(intervals)s::bigint[],+ %(offsets)s::integer[],+ %(due_times)s::timestamptz[]+ ) AS rows(kind, schedule_key, team_id, interval_seconds, offset_seconds, next_due_at)ON CONFLICT (kind, schedule_key) DO UPDATE SETteam_id = excluded.team_id,-- A cadence change re-anchors the schedule; an unchanged cadence keeps@@ -114,24 +120,25 @@ class SchedulerStateTable:conn: psycopg.AsyncConnection[Any],rows: list[DueSchedule],) -> None:- """Refresh the fleet's cadence rows. ``next_due_at`` only lands for new- rows and for rows whose (interval, offset) changed."""+ """Refresh the fleet's cadence rows in one statement. ``next_due_at``+ only lands for new rows and for rows whose (interval, offset) changed.++ Each (kind, schedule_key) must appear at most once in ``rows``: Postgres+ refuses an upsert that touches the same row twice.+ """if not rows:returnasync with conn.cursor() as cur:- await cur.executemany(+ await cur.execute(_UPSERT_STATE_SQL,- [- {- "kind": row.kind,- "schedule_key": row.schedule_key,- "team_id": row.team_id,- "interval_seconds": row.interval_seconds,- "offset_seconds": row.offset_seconds,- "next_due_at": row.next_due_at,- }- for row in rows- ],+ {+ "kinds": [row.kind for row in rows],+ "schedule_keys": [row.schedule_key for row in rows],+ "team_ids": [row.team_id for row in rows],+ "intervals": [row.interval_seconds for row in rows],+ "offsets": [row.offset_seconds for row in rows],+ "due_times": [row.next_due_at for row in rows],+ },)@staticmethoddiff --git a/products/warehouse_sources_queue/backend/tests/test_scheduler_state.py b/products/warehouse_sources_queue/backend/tests/test_scheduler_state.pyindex a0f141f6da1d..26de62ce5515 100644--- a/products/warehouse_sources_queue/backend/tests/test_scheduler_state.py+++ b/products/warehouse_sources_queue/backend/tests/test_scheduler_state.py@@ -161,6 +161,33 @@ class TestSchedulerState:assert states[(KIND, "s1")]["interval_seconds"] == 3600assert states[(KIND, "s1")]["offset_seconds"] == 60+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "new_interval,new_offset",+ [+ pytest.param(3600, 0, id="interval_changed"),+ pytest.param(INTERVAL, 60, id="offset_changed"),+ pytest.param(3600, 60, id="both_changed"),+ ],+ )+ async def test_single_upsert_applies_due_time_rule_per_row(self, conn, new_interval, new_offset):+ unchanged = _state("unchanged", due_in_seconds=600)+ await SchedulerStateTable.upsert_states(conn, [unchanged, _state("recadenced", due_in_seconds=600)])++ recadenced = _state("recadenced", due_in_seconds=120, interval=new_interval, offset=new_offset)+ new = _state("new", due_in_seconds=300, interval=3600, offset=30)+ await SchedulerStateTable.upsert_states(conn, [_state("unchanged", due_in_seconds=9999), recadenced, new])++ states = await _fetch_states(conn)+ assert {+ key: (row["next_due_at"], row["interval_seconds"], row["offset_seconds"])+ for (_, key), row in states.items()+ } == {+ "unchanged": (unchanged.next_due_at, INTERVAL, 0),+ "recadenced": (recadenced.next_due_at, new_interval, new_offset),+ "new": (new.next_due_at, 3600, 30),+ }+@pytest.mark.asyncioasync def test_stale_state_rows_deleted_after_refresh_cutoff(self, conn):await SchedulerStateTable.upsert_states(