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): bound the scheduler refresh memory (#111004)

Tom Owers97dcb0f04d04
diff --git a/products/warehouse_sources/backend/management/commands/run_warehouse_scheduler.py b/products/warehouse_sources/backend/management/commands/run_warehouse_scheduler.py
index da52ad01fc39..599fdb1bc592 100644
--- a/products/warehouse_sources/backend/management/commands/run_warehouse_scheduler.py
+++ b/products/warehouse_sources/backend/management/commands/run_warehouse_scheduler.py
@@ -8,7 +8,11 @@ import structlog
from posthog.product_db_migrations import collect_unapplied_product_migrations, configured_product_databases
from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
-from products.warehouse_sources.backend.scheduling.runner import ShadowScheduler, ShadowSchedulerConfig
+from products.warehouse_sources.backend.scheduling.runner import (
+ REFRESH_PAGE_SIZE,
+ ShadowScheduler,
+ ShadowSchedulerConfig,
+)
from products.warehouse_sources_queue.backend.sdk import HealthState, start_health_server
logger = structlog.get_logger(__name__)
@@ -51,6 +55,12 @@ class Command(BaseCommand):
default=30,
help="Days to keep shadow decisions before pruning (default: 30)",
)
+ parser.add_argument(
+ "--refresh-page-size",
+ type=int,
+ default=REFRESH_PAGE_SIZE,
+ help=f"Schemas read and upserted per refresh page; bounds refresh memory (default: {REFRESH_PAGE_SIZE})",
+ )
parser.add_argument(
"--health-port",
type=int,
@@ -94,6 +104,7 @@ class Command(BaseCommand):
refresh_interval_seconds=options["refresh_interval"],
claim_limit=options["claim_limit"],
decision_retention_days=options["decision_retention_days"],
+ refresh_page_size=options["refresh_page_size"],
)
logger.info(
diff --git a/products/warehouse_sources/backend/scheduling/runner.py b/products/warehouse_sources/backend/scheduling/runner.py
index 6cc1811b1f33..29df7ee54c9f 100644
--- a/products/warehouse_sources/backend/scheduling/runner.py
+++ b/products/warehouse_sources/backend/scheduling/runner.py
@@ -29,9 +29,10 @@ from products.warehouse_sources.backend.scheduling.shadow import (
SKIP_REASONS,
SYNC_EXTRACT_KIND,
TICK_SLOT_KEY,
+ InScopeSchema,
SchemaCadence,
evaluate_due,
- fetch_in_scope_schemas,
+ fetch_in_scope_schema_page,
next_due_after,
schedule_offset,
)
@@ -39,7 +40,7 @@ from products.warehouse_sources_queue.backend.sdk import DueSchedule, JobsTable,
logger = structlog.get_logger(__name__)
-UPSERT_BATCH_SIZE = 1000
+REFRESH_PAGE_SIZE = 1000
WOULD_FIRE_TOTAL = Counter(
"warehouse_pg_scheduler_would_fire_total",
@@ -100,6 +101,7 @@ class ShadowSchedulerConfig:
refresh_interval_seconds: float = 300.0
claim_limit: int = 1000
decision_retention_days: int = 30
+ refresh_page_size: int = REFRESH_PAGE_SIZE
class ShadowScheduler:
@@ -230,46 +232,54 @@ class ShadowScheduler:
refresh_start = row[0]
now_epoch = int(time.time())
- rows = await database_sync_to_async_pool(fetch_in_scope_schemas)()
- upserts: list[DueSchedule] = []
- for schema_row in rows:
- schema_id, team_id, interval, sync_time_of_day = (
- schema_row.schema_id,
- schema_row.team_id,
- schema_row.interval,
- schema_row.sync_time_of_day,
- )
- interval_seconds = int(interval.total_seconds())
- if interval_seconds <= 0:
- continue
- offset_seconds = schedule_offset(schema_id, interval, sync_time_of_day)
- cadence = SchemaCadence(interval_seconds=interval_seconds, offset_seconds=offset_seconds)
- upserts.append(
- DueSchedule(
- kind=SYNC_EXTRACT_KIND,
- schedule_key=schema_id,
- team_id=team_id,
- interval_seconds=interval_seconds,
- offset_seconds=offset_seconds,
- # Only lands for new or re-cadenced rows; a schema is never
- # due the first time the scheduler sees it.
- next_due_at=datetime.fromtimestamp(next_due_after(now_epoch, cadence), tz=UTC),
- )
+ in_scope = 0
+ after_id: str | None = None
+ # One page in memory at a time: fleet size must not set the pod's RSS.
+ while True:
+ page = await database_sync_to_async_pool(fetch_in_scope_schema_page)(
+ after_id, self._config.refresh_page_size
)
+ if not page:
+ break
+ after_id = page[-1].schema_id
+ upserts = self._build_upserts(page, now_epoch)
+ await SchedulerStateTable.upsert_states(conn, upserts)
+ in_scope += len(upserts)
- for start in range(0, len(upserts), UPSERT_BATCH_SIZE):
- await SchedulerStateTable.upsert_states(conn, upserts[start : start + UPSERT_BATCH_SIZE])
deleted = await SchedulerStateTable.delete_states_not_refreshed_since(conn, SYNC_EXTRACT_KIND, refresh_start)
pruned = await SchedulerStateTable.prune_decisions(
conn, kind=SYNC_EXTRACT_KIND, older_than_days=self._config.decision_retention_days
)
- SCHEMAS_IN_SCOPE.set(len(upserts))
+ SCHEMAS_IN_SCOPE.set(in_scope)
SCAN_DURATION_SECONDS.observe(time.monotonic() - started)
logger.info(
"scheduler_refresh",
- in_scope=len(upserts),
+ in_scope=in_scope,
stale_deleted=deleted,
decisions_pruned=pruned,
duration_seconds=round(time.monotonic() - started, 3),
)
+
+ @staticmethod
+ def _build_upserts(page: list[InScopeSchema], now_epoch: int) -> list[DueSchedule]:
+ upserts: list[DueSchedule] = []
+ for schema_row in page:
+ interval_seconds = int(schema_row.interval.total_seconds())
+ if interval_seconds <= 0:
+ continue
+ offset_seconds = schedule_offset(schema_row.schema_id, schema_row.interval, schema_row.sync_time_of_day)
+ cadence = SchemaCadence(interval_seconds=interval_seconds, offset_seconds=offset_seconds)
+ upserts.append(
+ DueSchedule(
+ kind=SYNC_EXTRACT_KIND,
+ schedule_key=schema_row.schema_id,
+ team_id=schema_row.team_id,
+ interval_seconds=interval_seconds,
+ offset_seconds=offset_seconds,
+ # Only lands for new or re-cadenced rows; a schema is never
+ # due the first time the scheduler sees it.
+ next_due_at=datetime.fromtimestamp(next_due_after(now_epoch, cadence), tz=UTC),
+ )
+ )
+ return upserts
diff --git a/products/warehouse_sources/backend/scheduling/shadow.py b/products/warehouse_sources/backend/scheduling/shadow.py
index 4c4ffc5d3452..5c63ac7b4a39 100644
--- a/products/warehouse_sources/backend/scheduling/shadow.py
+++ b/products/warehouse_sources/backend/scheduling/shadow.py
@@ -140,13 +140,20 @@ def _in_scope_queryset():
)
-def fetch_in_scope_schemas() -> list[InScopeSchema]:
- """Every schema the scheduler would manage. Read-only fleet-wide scan; call
- via the async wrapper."""
- rows = _in_scope_queryset().values_list("id", "team_id", "sync_frequency_interval", "sync_time_of_day")
+def fetch_in_scope_schema_page(after_id: str | None, limit: int) -> list[InScopeSchema]:
+ """One id-ordered page of in-scope schemas. Read-only; call via the async wrapper.
+
+ Keyset pagination, not ``QuerySet.iterator()``: behind PgBouncer Django
+ disables server-side cursors, and ``iterator()`` then loads the whole
+ result set into memory before it yields the first row.
+ """
+ queryset = _in_scope_queryset()
+ if after_id is not None:
+ queryset = queryset.filter(id__gt=after_id)
+ rows = queryset.order_by("id").values_list("id", "team_id", "sync_frequency_interval", "sync_time_of_day")[:limit]
return [
InScopeSchema(schema_id=str(schema_id), team_id=team_id, interval=interval, sync_time_of_day=sync_time)
- for schema_id, team_id, interval, sync_time in rows.iterator(chunk_size=1000)
+ for schema_id, team_id, interval, sync_time in rows
]
diff --git a/products/warehouse_sources/backend/tests/test_scheduler_shadow.py b/products/warehouse_sources/backend/tests/test_scheduler_shadow.py
index 6d647d815b15..41940dbdf907 100644
--- a/products/warehouse_sources/backend/tests/test_scheduler_shadow.py
+++ b/products/warehouse_sources/backend/tests/test_scheduler_shadow.py
@@ -1,7 +1,9 @@
import io
import time
import uuid
+import socket
import importlib
+import urllib.request
from datetime import (
UTC,
datetime,
@@ -35,7 +37,7 @@ from products.warehouse_sources.backend.scheduling.shadow import (
EvaluationResult,
SchemaCadence,
evaluate_due,
- fetch_in_scope_schemas,
+ fetch_in_scope_schema_page,
latest_fire_at,
next_due_after,
schedule_offset,
@@ -47,7 +49,7 @@ from products.warehouse_sources_queue.backend.core.scheduler_state import (
DecisionRecord,
SchedulerStateTable,
)
-from products.warehouse_sources_queue.backend.sdk import DueSchedule
+from products.warehouse_sources_queue.backend.sdk import DueSchedule, HealthState, start_health_server
from products.warehouse_sources_queue.backend.testing import ensure_scheduler_tables, get_test_database_url
# The product-structure lint reads a direct import of another product's logic
@@ -185,7 +187,7 @@ class TestScopePredicate:
source = _create_source(team, **source_overrides)
schema = _create_schema(team, source, **schema_overrides)
- in_scope_ids = {row.schema_id for row in fetch_in_scope_schemas()}
+ in_scope_ids = {row.schema_id for row in fetch_in_scope_schema_page(None, 100)}
assert (str(schema.id) in in_scope_ids) == expected_in_scope
@@ -370,6 +372,79 @@ class TestShadowSchedulerTick:
duplicate_windows.inc.assert_called_once_with(1)
[email protected]_db(transaction=True)
+class TestShadowSchedulerRefresh:
+ def _refresh(self, db_url: str, page_size: int) -> 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)
+
+ async_to_sync(run)()
+
+ def _state_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 kind = %s", (SYNC_EXTRACT_KIND,)
+ ).fetchall()
+ return {row[0] for row in rows}
+
+ def _reset_state(self) -> str:
+ db_url = get_test_database_url()
+ with psycopg.Connection.connect(db_url, autocommit=True) as conn:
+ ensure_scheduler_tables(conn)
+ conn.execute(f"TRUNCATE {SCHEDULER_DECISION_TABLE}, {SCHEDULER_STATE_TABLE}")
+ return db_url
+
+ @pytest.mark.parametrize("page_size", [1, 2, 3, 100])
+ @pytest.mark.parametrize("schema_count", [0, 1, 2, 5])
+ def test_paged_refresh_upserts_every_in_scope_schema(self, team, monkeypatch, schema_count, page_size):
+ db_url = self._reset_state()
+ source = _create_source(team)
+ schema_ids = {str(_create_schema(team, source, name=f"table_{i}").id) for i in range(schema_count)}
+ _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)
+
+ self._refresh(db_url, page_size)
+
+ assert self._state_keys(db_url) == schema_ids
+ in_scope_gauge.set.assert_called_once_with(schema_count)
+
+ @pytest.mark.parametrize("page_size", [1, 2, 10])
+ def test_paged_refresh_deletes_schemas_that_left_scope(self, team, page_size):
+ db_url = self._reset_state()
+ source = _create_source(team)
+ schemas = [_create_schema(team, source, name=f"table_{i}") for i in range(5)]
+ self._refresh(db_url, page_size)
+ assert self._state_keys(db_url) == {str(schema.id) for schema in schemas}
+
+ schemas[0].should_sync = False
+ schemas[0].save()
+ ExternalDataSchema.objects.filter(pk=schemas[4].pk).update(deleted=True)
+ self._refresh(db_url, page_size)
+
+ assert self._state_keys(db_url) == {str(schema.id) for schema in schemas[1:4]}
+
+
+class TestSchedulerMetricsEndpoint:
+ def test_metrics_endpoint_serves_scheduler_metrics(self):
+ scheduler_runner.TICKS_TOTAL.labels(outcome="follower").inc()
+ free_port = _free_port()
+ start_health_server(port=free_port, health_state=HealthState(timeout_seconds=60))
+
+ with urllib.request.urlopen(f"http://127.0.0.1:{free_port}/_metrics", timeout=5) as response:
+ body = response.read().decode()
+
+ assert "warehouse_pg_scheduler_ticks_total" in body
+
+
+def _free_port() -> int:
+ with socket.socket() as sock:
+ sock.bind(("127.0.0.1", 0))
+ return sock.getsockname()[1]
+
+
@pytest.mark.django_db
class TestShadowReport:
def test_report_matches_jobs_and_counts_adhoc(self, team, monkeypatch):