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(data-warehouse): add warehouse scheduler in shadow mode (#92323)

Tom Owers312ea63cdd44
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 5c588320e3f3..e30a06322acd 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -326,6 +326,8 @@ rules:
|QuarantinedIdentifier
|QueryTabState
|QueueJob
+ |QueueSchedulerDecision
+ |QueueSchedulerState
|QuickFilter
|QuickFilterContext
|ReplayObservation
@@ -760,6 +762,8 @@ rules:
|QuarantinedIdentifier
|QueryTabState
|QueueJob
+ |QueueSchedulerDecision
+ |QueueSchedulerState
|QuickFilter
|QuickFilterContext
|ReplayObservation
diff --git a/posthog/models/scoping/baseline_unmigrated.txt b/posthog/models/scoping/baseline_unmigrated.txt
index 067735f1381f..82d3c765f71b 100644
--- a/posthog/models/scoping/baseline_unmigrated.txt
+++ b/posthog/models/scoping/baseline_unmigrated.txt
@@ -131,6 +131,8 @@ ProjectSecretAPIKey
PropertyAccessControl
QueryTabState
QueueJob
+QueueSchedulerDecision
+QueueSchedulerState
QuickFilter
QuickFilterContext
Reminder
diff --git a/products/warehouse_sources/backend/management/commands/report_warehouse_scheduler_shadow.py b/products/warehouse_sources/backend/management/commands/report_warehouse_scheduler_shadow.py
new file mode 100644
index 000000000000..89b2eadb09ef
--- /dev/null
+++ b/products/warehouse_sources/backend/management/commands/report_warehouse_scheduler_shadow.py
@@ -0,0 +1,115 @@
+from collections import Counter
+from datetime import UTC, datetime, timedelta
+
+from django.core.management.base import BaseCommand, CommandError
+
+import psycopg
+
+from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
+
+from products.warehouse_sources.backend.models import ExternalDataJob
+from products.warehouse_sources.backend.scheduling.shadow import SYNC_EXTRACT_KIND
+from products.warehouse_sources_queue.backend.sdk import SchedulerStateTable
+
+TOP_OFFENDERS = 10
+
+
+def parse_schedule_fired_at(schema_id: str, workflow_id: str | None) -> datetime | None:
+ """Fire time of a schedule-fired run, or None for ad-hoc/manual runs.
+
+ Temporal schedule-fired workflow ids look like ``{schema_id}-{ISO timestamp}``;
+ anything else (manual triggers, backfills) carries no fire time.
+ """
+ prefix = f"{schema_id}-"
+ if not workflow_id or not workflow_id.startswith(prefix):
+ return None
+ try:
+ fired_at = datetime.fromisoformat(workflow_id[len(prefix) :])
+ except ValueError:
+ return None
+ if fired_at.tzinfo is None:
+ fired_at = fired_at.replace(tzinfo=UTC)
+ return fired_at
+
+
+def _print_offenders(stdout, label: str, schema_ids: list[str]) -> None:
+ if not schema_ids:
+ return
+ stdout.write(f" top {label} schemas:")
+ for schema_id, count in Counter(schema_ids).most_common(TOP_OFFENDERS):
+ stdout.write(f" {schema_id}: {count}")
+
+
+class Command(BaseCommand):
+ help = "Compare shadow-scheduler would-fire decisions against actual ExternalDataJob rows"
+
+ def add_arguments(self, parser):
+ parser.add_argument("--hours", type=float, default=24.0, help="Window to report over (default: 24)")
+ parser.add_argument(
+ "--since", type=str, default=None, help="Window start as an ISO timestamp (overrides --hours)"
+ )
+ parser.add_argument(
+ "--tolerance-seconds",
+ type=float,
+ default=1800.0,
+ help="Maximum distance between a decision's due time and a job for them to match (default: 1800)",
+ )
+ parser.add_argument("--team-id", type=int, default=None, help="Restrict the report to one team")
+
+ def handle(self, *args, **options):
+ if options["since"]:
+ try:
+ since = datetime.fromisoformat(options["since"])
+ except ValueError as e:
+ raise CommandError(f"--since is not a valid ISO timestamp: {e}")
+ if since.tzinfo is None:
+ since = since.replace(tzinfo=UTC)
+ else:
+ since = datetime.now(UTC) - timedelta(hours=options["hours"])
+ tolerance = timedelta(seconds=options["tolerance_seconds"])
+
+ with psycopg.Connection.connect(WAREHOUSE_SOURCES_DATABASE_URL) as conn:
+ decisions = SchedulerStateTable.fetch_would_fires(conn, SYNC_EXTRACT_KIND, since)
+ if options["team_id"] is not None:
+ decisions = [d for d in decisions if d.team_id == options["team_id"]]
+
+ jobs_qs = ExternalDataJob.objects.filter(created_at__gte=since - tolerance, schema_id__isnull=False)
+ if options["team_id"] is not None:
+ jobs_qs = jobs_qs.filter(team_id=options["team_id"])
+ jobs = list(jobs_qs.values_list("schema_id", "workflow_id"))
+
+ # One-to-one greedy matching per schema, nearest job time to due time first.
+ unmatched: dict[str, list[datetime]] = {}
+ for decision in decisions:
+ unmatched.setdefault(decision.schedule_key, []).append(decision.due_at)
+
+ matched = 0
+ temporal_only: list[str] = []
+ adhoc = 0
+ for schema_uuid, workflow_id in jobs:
+ schema_id = str(schema_uuid)
+ fired_at = parse_schedule_fired_at(schema_id, workflow_id)
+ if fired_at is None:
+ # Runs with no parseable schedule id are manual or backfill
+ # runs; never let them consume a shadow decision.
+ adhoc += 1
+ continue
+
+ candidates = unmatched.get(schema_id, [])
+ best = min(candidates, key=lambda due: abs(due - fired_at), default=None)
+ if best is not None and abs(best - fired_at) <= tolerance:
+ candidates.remove(best)
+ matched += 1
+ else:
+ temporal_only.append(schema_id)
+
+ shadow_only = [schema_id for schema_id, dues in unmatched.items() for _ in dues]
+
+ self.stdout.write(f"window since {since.isoformat()} (tolerance {tolerance})")
+ self.stdout.write(f"would_fire decisions: {len(decisions)}, jobs considered: {len(jobs)}")
+ self.stdout.write(f"matched: {matched}")
+ self.stdout.write(f"shadow_only (shadow would fire, no job): {len(shadow_only)}")
+ self.stdout.write(f"temporal_only (schedule-fired job, no decision): {len(temporal_only)}")
+ self.stdout.write(f"adhoc (manual/backfill runs, excluded): {adhoc}")
+ _print_offenders(self.stdout, "shadow_only", shadow_only)
+ _print_offenders(self.stdout, "temporal_only", temporal_only)
diff --git a/products/warehouse_sources/backend/management/commands/run_warehouse_scheduler.py b/products/warehouse_sources/backend/management/commands/run_warehouse_scheduler.py
new file mode 100644
index 000000000000..da52ad01fc39
--- /dev/null
+++ b/products/warehouse_sources/backend/management/commands/run_warehouse_scheduler.py
@@ -0,0 +1,111 @@
+import signal
+import asyncio
+
+from django.core.management.base import BaseCommand, CommandError
+
+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_queue.backend.sdk import HealthState, start_health_server
+
+logger = structlog.get_logger(__name__)
+
+
+async def _run_scheduler(config: ShadowSchedulerConfig, health_reporter) -> None:
+ loop = asyncio.get_running_loop()
+ shutdown = asyncio.Event()
+ for sig in (signal.SIGTERM, signal.SIGINT):
+ loop.add_signal_handler(sig, shutdown.set)
+ # Graceful shutdown: the loop finishes the in-flight tick and returns.
+ await ShadowScheduler(config=config).run(shutdown, health_reporter)
+
+
+class Command(BaseCommand):
+ help = "Run the warehouse scheduler (shadow mode: records decisions, starts no syncs)"
+
+ def add_arguments(self, parser):
+ parser.add_argument(
+ "--tick-interval",
+ type=float,
+ default=60.0,
+ help="Seconds between scheduler ticks (default: 60.0)",
+ )
+ parser.add_argument(
+ "--refresh-interval",
+ type=float,
+ default=300.0,
+ help="Seconds between fleet-wide scope refreshes (default: 300.0)",
+ )
+ parser.add_argument(
+ "--claim-limit",
+ type=int,
+ default=1000,
+ help="Maximum due schemas claimed per tick (default: 1000)",
+ )
+ parser.add_argument(
+ "--decision-retention-days",
+ type=int,
+ default=30,
+ help="Days to keep shadow decisions before pruning (default: 30)",
+ )
+ parser.add_argument(
+ "--health-port",
+ type=int,
+ default=8080,
+ help="Port for the health check HTTP server (default: 8080)",
+ )
+ parser.add_argument(
+ "--health-timeout",
+ type=float,
+ default=180.0,
+ help="Health check timeout in seconds (default: 180.0)",
+ )
+ parser.add_argument(
+ "--skip-migrations-check",
+ action="store_true",
+ help="Skip the startup check that the queue DB has this image's migrations applied (emergency escape hatch)",
+ )
+
+ def handle(self, *args, **options):
+ # Same guard as run_warehouse_sources_load: an image that expects queue-DB
+ # migrations the DB doesn't have would otherwise start and fail at runtime
+ # (UndefinedTable), so refuse startup instead.
+ if not options.get("skip_migrations_check"):
+ if not configured_product_databases(databases={"warehouse_sources_queue"}):
+ logger.warning(
+ "migrations_check_skipped_unconfigured",
+ note="PRODUCT_DB_WAREHOUSE_SOURCES_QUEUE_* env not set; queue schema not verified against this image",
+ )
+ unapplied = collect_unapplied_product_migrations(databases={"warehouse_sources_queue"})
+ if unapplied:
+ for alias, migrations in unapplied.items():
+ logger.error("unapplied_product_migrations", database_alias=alias, migrations=migrations)
+ raise CommandError(
+ "Queue database is missing migrations this image expects: "
+ + "; ".join(f"{alias}: {', '.join(migrations)}" for alias, migrations in unapplied.items())
+ )
+
+ config = ShadowSchedulerConfig(
+ database_url=WAREHOUSE_SOURCES_DATABASE_URL,
+ tick_interval_seconds=options["tick_interval"],
+ refresh_interval_seconds=options["refresh_interval"],
+ claim_limit=options["claim_limit"],
+ decision_retention_days=options["decision_retention_days"],
+ )
+
+ logger.info(
+ "warehouse_scheduler_starting",
+ tick_interval=config.tick_interval_seconds,
+ refresh_interval=config.refresh_interval_seconds,
+ claim_limit=config.claim_limit,
+ decision_retention_days=config.decision_retention_days,
+ health_port=options["health_port"],
+ )
+
+ health_state = HealthState(timeout_seconds=options["health_timeout"])
+ start_health_server(port=options["health_port"], health_state=health_state)
+
+ asyncio.run(_run_scheduler(config, health_state.report_healthy))
diff --git a/products/warehouse_sources/backend/scheduling/__init__.py b/products/warehouse_sources/backend/scheduling/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/warehouse_sources/backend/scheduling/runner.py b/products/warehouse_sources/backend/scheduling/runner.py
new file mode 100644
index 000000000000..6cc1811b1f33
--- /dev/null
+++ b/products/warehouse_sources/backend/scheduling/runner.py
@@ -0,0 +1,275 @@
+"""Shadow-scheduler tick loop: leader election, refresh, due scan, decisions.
+
+Every pod runs the same loop; the tick sentinel single-flights each tick across
+the fleet, so followers only heartbeat. The scheduler writes decisions and
+metrics but starts no syncs — Temporal schedules stay the only thing that runs
+work while shadow mode is compared against them.
+"""
+
+from __future__ import annotations
+
+import time
+import asyncio
+from collections.abc import Callable
+from datetime import UTC, datetime
+from uuid import uuid4
+
+import psycopg
+import structlog
+from prometheus_client import Counter, Gauge, Histogram
+
+from posthog.dataclasses import frozen
+from posthog.sync import database_sync_to_async_pool
+
+from products.warehouse_sources.backend.scheduling.shadow import (
+ DECISION_SKIP_OUT_OF_SCOPE,
+ DECISION_WOULD_FIRE,
+ REFRESH_SLOT_KEY,
+ SCHEDULER_LANE,
+ SKIP_REASONS,
+ SYNC_EXTRACT_KIND,
+ TICK_SLOT_KEY,
+ SchemaCadence,
+ evaluate_due,
+ fetch_in_scope_schemas,
+ next_due_after,
+ schedule_offset,
+)
+from products.warehouse_sources_queue.backend.sdk import DueSchedule, JobsTable, SchedulerStateTable
+
+logger = structlog.get_logger(__name__)
+
+UPSERT_BATCH_SIZE = 1000
+
+WOULD_FIRE_TOTAL = Counter(
+ "warehouse_pg_scheduler_would_fire_total",
+ "Windows the shadow scheduler would have fired a sync for",
+)
+
+SKIPS_TOTAL = Counter(
+ "warehouse_pg_scheduler_skips_total",
+ "Windows the shadow scheduler would have skipped",
+ labelnames=["reason"],
+)
+
+DUPLICATE_WINDOWS_TOTAL = Counter(
+ "warehouse_pg_scheduler_duplicate_windows_total",
+ "Decision inserts refused because the (kind, schedule key, due time) tuple was already recorded",
+)
+
+SCAN_DURATION_SECONDS = Histogram(
+ "warehouse_pg_scheduler_scan_duration_seconds",
+ "Duration of the fleet-wide refresh scan",
+ buckets=(0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 15.0, 30.0, 60.0, 120.0, 300.0),
+)
+
+SCHEMAS_IN_SCOPE = Gauge(
+ "warehouse_pg_scheduler_schemas_in_scope",
+ "Schemas the scheduler currently manages state for",
+ multiprocess_mode="livesum",
+)
+
+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),
+)
+
+FIRE_LATENESS_SECONDS = Histogram(
+ "warehouse_pg_scheduler_fire_lateness_seconds",
+ "Seconds between a window's fire time and the tick that observed it",
+ buckets=(1, 5, 15, 30, 60, 120, 300, 600, 1800, 3600),
+)
+
+MISSED_WINDOWS_TOTAL = Counter(
+ "warehouse_pg_scheduler_missed_windows_total",
+ "Fire windows that passed entirely between ticks (no decision recorded)",
+)
+
+TICKS_TOTAL = Counter(
+ "warehouse_pg_scheduler_ticks_total",
+ "Scheduler tick loop iterations",
+ labelnames=["outcome"],
+)
+
+
+@frozen
+class ShadowSchedulerConfig:
+ database_url: str
+ tick_interval_seconds: float = 60.0
+ refresh_interval_seconds: float = 300.0
+ claim_limit: int = 1000
+ decision_retention_days: int = 30
+
+
+class ShadowScheduler:
+ def __init__(self, config: ShadowSchedulerConfig) -> None:
+ self._config = config
+ self._owner_token = str(uuid4())
+
+ async def run(self, shutdown: asyncio.Event, health_reporter: Callable[[], None]) -> None:
+ logger.info(
+ "scheduler_starting",
+ owner_token=self._owner_token,
+ tick_interval=self._config.tick_interval_seconds,
+ refresh_interval=self._config.refresh_interval_seconds,
+ claim_limit=self._config.claim_limit,
+ decision_retention_days=self._config.decision_retention_days,
+ )
+ while not shutdown.is_set():
+ started = time.monotonic()
+ try:
+ await self._tick(health_reporter)
+ except Exception:
+ # No health report on a failed tick: a pod that cannot complete
+ # ticks should trip the liveness timeout and restart.
+ TICKS_TOTAL.labels(outcome="error").inc()
+ logger.exception("scheduler_tick_failed")
+ remainder = self._config.tick_interval_seconds - (time.monotonic() - started)
+ if remainder > 0:
+ try:
+ await asyncio.wait_for(shutdown.wait(), timeout=remainder)
+ except TimeoutError:
+ pass
+ logger.info("scheduler_stopped", owner_token=self._owner_token)
+
+ async def _tick(self, health_reporter: Callable[[], None]) -> None:
+ async with await psycopg.AsyncConnection.connect(self._config.database_url, autocommit=True) as conn:
+ is_leader = await JobsTable.try_acquire_sentinel_slot(
+ conn,
+ lane=SCHEDULER_LANE,
+ group_key=TICK_SLOT_KEY,
+ owner_token=self._owner_token,
+ ttl_seconds=self._config.tick_interval_seconds,
+ )
+ if not is_leader:
+ TICKS_TOTAL.labels(outcome="follower").inc()
+ health_reporter()
+ return
+
+ # Refresh before the due scan so a schema created or re-cadenced
+ # moments ago is judged on this tick, not the next refresh.
+ refresh_won = await JobsTable.try_acquire_sentinel_slot(
+ conn,
+ lane=SCHEDULER_LANE,
+ group_key=REFRESH_SLOT_KEY,
+ owner_token=self._owner_token,
+ 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)
+
+ 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,
+ refreshed=refresh_won,
+ )
+ health_reporter()
+
+ async def _refresh(self, conn: psycopg.AsyncConnection) -> 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.
+ async with conn.cursor() as cur:
+ await cur.execute("SELECT now()")
+ row = await cur.fetchone()
+ assert row is not None
+ 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),
+ )
+ )
+
+ 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))
+ SCAN_DURATION_SECONDS.observe(time.monotonic() - started)
+ logger.info(
+ "scheduler_refresh",
+ in_scope=len(upserts),
+ stale_deleted=deleted,
+ decisions_pruned=pruned,
+ duration_seconds=round(time.monotonic() - started, 3),
+ )
diff --git a/products/warehouse_sources/backend/scheduling/shadow.py b/products/warehouse_sources/backend/scheduling/shadow.py
new file mode 100644
index 000000000000..4c4ffc5d3452
--- /dev/null
+++ b/products/warehouse_sources/backend/scheduling/shadow.py
@@ -0,0 +1,217 @@
+"""Shadow-scheduler decision logic: scope, cadence math, and per-window evaluation.
+
+A schema is in scope for scheduling when all of these hold:
+
+- ``should_sync`` is true and ``sync_frequency_interval`` is set,
+- the schema is not soft-deleted and its source is not soft-deleted,
+- the source's ``access_method`` is not ``direct`` (mirrors
+ ``ExternalDataSource.supports_scheduled_sync``).
+
+``cdc_halted`` is deliberately not a scope condition: a halted CDC schema keeps
+its state row and gets a ``skip_cdc_halted`` decision at fire time, so the
+shadow report can show what Temporal's SKIP overlap policy hides.
+
+Due times are epoch-aligned integers, matching Temporal's
+``ScheduleIntervalSpec`` semantics: a schedule fires at ``n * interval +
+offset`` (UTC epoch), where the offset ports ``get_sync_schedule`` exactly,
+including its deterministic per-schema jitter and its dropping of
+``sync_time_of_day`` seconds.
+"""
+
+from __future__ import annotations
+
+import random
+from datetime import UTC, datetime, time, timedelta
+
+from posthog.dataclasses import frozen
+from posthog.sync import database_sync_to_async_pool
+
+from products.warehouse_sources.backend.models import ExternalDataJob, ExternalDataSchema, ExternalDataSource
+from products.warehouse_sources_queue.backend.sdk import DecisionRecord, DueSchedule
+
+SCHEDULER_LANE = "scheduler"
+TICK_SLOT_KEY = "tick-slot"
+REFRESH_SLOT_KEY = "refresh-slot"
+SYNC_EXTRACT_KIND = "sync.extract"
+
+DECISION_WOULD_FIRE = "would_fire"
+DECISION_SKIP_OVERLAP = "skip_overlap"
+DECISION_SKIP_CDC_HALTED = "skip_cdc_halted"
+DECISION_SKIP_OUT_OF_SCOPE = "skip_out_of_scope"
+
+SKIP_REASONS = {
+ DECISION_SKIP_OVERLAP: "overlap_running",
+ DECISION_SKIP_CDC_HALTED: "cdc_halted",
+ DECISION_SKIP_OUT_OF_SCOPE: "out_of_scope",
+}
+
+
+@frozen
+class SchemaCadence:
+ interval_seconds: int
+ offset_seconds: int
+
+
+@frozen
+class InScopeSchema:
+ schema_id: str
+ team_id: int
+ interval: timedelta
+ sync_time_of_day: time | None
+
+
+@frozen
+class EvaluationResult:
+ records: tuple[DecisionRecord, ...]
+ missed_windows: int
+
+
+def _jitter_minutes(max_jitter: timedelta, rng: random.Random) -> int:
+ """Exact port of ``service._jitter_timedelta``: one uniform draw, split into
+ whole hours times sixty plus whole minutes (seconds truncated)."""
+ total_seconds = max_jitter.total_seconds()
+ jitter_seconds = rng.uniform(0, total_seconds)
+ return int(jitter_seconds // 3600) * 60 + int((jitter_seconds % 3600) // 60)
+
+
+def schedule_offset(schema_id: str, interval: timedelta, sync_time_of_day: time | None) -> int:
+ """The schema's Temporal schedule offset in whole seconds.
+
+ Ports ``get_sync_schedule`` + ``to_temporal_schedule``: an explicit
+ ``sync_time_of_day`` contributes ``hour*60 + minute`` minutes (seconds
+ dropped), otherwise a deterministic jitter seeded on the schema id is
+ bucketed by interval; either way the minutes reduce modulo the interval.
+ The rng draw and the elif chain must stay bit-identical to the service's,
+ because parity with live Temporal schedules is the whole point of shadow
+ mode.
+ """
+ if sync_time_of_day is not None:
+ minutes = sync_time_of_day.hour * 60 + sync_time_of_day.minute
+ else:
+ rng = random.Random(str(schema_id))
+ jitter_minutes = 0
+ if interval <= timedelta(minutes=5):
+ jitter_minutes = _jitter_minutes(timedelta(minutes=5), rng)
+ elif interval <= timedelta(minutes=30):
+ jitter_minutes = _jitter_minutes(timedelta(minutes=30), rng)
+ elif interval <= timedelta(hours=1):
+ jitter_minutes = _jitter_minutes(timedelta(hours=1), rng)
+ elif interval <= timedelta(hours=6):
+ jitter_minutes = _jitter_minutes(timedelta(hours=6), rng)
+ elif interval <= timedelta(hours=12):
+ jitter_minutes = _jitter_minutes(timedelta(hours=12), rng)
+ elif interval <= timedelta(days=1):
+ jitter_minutes = _jitter_minutes(timedelta(days=1), rng)
+ minutes = jitter_minutes
+ return int((timedelta(minutes=minutes) % interval).total_seconds())
+
+
+def latest_fire_at(now: int, cadence: SchemaCadence) -> int:
+ """The most recent epoch second at which this cadence fired (<= now)."""
+ return ((now - cadence.offset_seconds) // cadence.interval_seconds) * cadence.interval_seconds + (
+ cadence.offset_seconds
+ )
+
+
+def window_boundary(fire: int, cadence: SchemaCadence) -> int:
+ """The fire's offset-free cadence boundary, retained for comparison."""
+ return fire - cadence.offset_seconds
+
+
+def next_due_after(now: int, cadence: SchemaCadence) -> int:
+ return latest_fire_at(now, cadence) + cadence.interval_seconds
+
+
+def cdc_halted_from_config(sync_type_config: dict | None) -> bool:
+ """Mirror of ``ExternalDataSchema.cdc_halted``, evaluated on the fetched
+ ``sync_type_config`` dict so the due scan needs no model instances."""
+ config = sync_type_config or {}
+ return bool(config.get("cdc_broken")) or bool(config.get("cdc_extraction_paused"))
+
+
+def _in_scope_queryset():
+ return (
+ # Unscoped manager on purpose: the scheduler scans the whole fleet.
+ # `deleted` is nullable, so exclude(deleted=True), not filter(deleted=False).
+ ExternalDataSchema.objects.filter(should_sync=True, sync_frequency_interval__isnull=False)
+ .exclude(deleted=True)
+ .exclude(source__deleted=True)
+ .exclude(source__access_method=ExternalDataSource.AccessMethod.DIRECT)
+ )
+
+
+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")
+ 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)
+ ]
+
+
+def _fetch_due_scope(schema_ids: list[str]) -> dict[str, dict | None]:
+ rows = _in_scope_queryset().filter(id__in=schema_ids).values_list("id", "sync_type_config")
+ return {str(schema_id): config for schema_id, config in rows}
+
+
+def _fetch_running_jobs(schema_ids: list[str]) -> list[tuple[str, datetime]]:
+ rows = ExternalDataJob.objects.filter(schema_id__in=schema_ids, status=ExternalDataJob.Status.RUNNING).values_list(
+ "schema_id", "created_at"
+ )
+ return [(str(schema_id), created_at) for schema_id, created_at in rows]
+
+
+async def evaluate_due(due: list[DueSchedule], now_epoch: int) -> EvaluationResult:
+ """Decide, per due schema, what a real scheduler would have done.
+
+ Records exactly one decision per schema, for the latest window only: a tick
+ late by several intervals counts the earlier windows on the missed-windows
+ metric rather than back-filling decisions Temporal never took either (its
+ interval spec fires at most once per boundary that passes while up).
+ """
+ if not due:
+ return EvaluationResult(records=(), missed_windows=0)
+
+ due_ids = [row.schedule_key for row in due]
+ scope_config = await database_sync_to_async_pool(_fetch_due_scope)(due_ids)
+ running_jobs = await database_sync_to_async_pool(_fetch_running_jobs)(due_ids)
+
+ records: list[DecisionRecord] = []
+ missed_windows = 0
+ for row in due:
+ cadence = SchemaCadence(interval_seconds=row.interval_seconds, offset_seconds=row.offset_seconds)
+ fire = latest_fire_at(now_epoch, cadence)
+ stored_due_epoch = int(row.next_due_at.timestamp())
+ missed_windows += max(0, (fire - stored_due_epoch) // cadence.interval_seconds)
+
+ # Only work that existed before this boundary can overlap it. The
+ # Temporal run fired for this boundary may already be RUNNING by the
+ # time the shadow tick evaluates, but it is the run being compared.
+ had_running_job_at_boundary = any(
+ schema_id == row.schedule_key and created_at < datetime.fromtimestamp(fire, tz=UTC)
+ for schema_id, created_at in running_jobs
+ )
+
+ if row.schedule_key not in scope_config:
+ decision = DECISION_SKIP_OUT_OF_SCOPE
+ elif had_running_job_at_boundary:
+ decision = DECISION_SKIP_OVERLAP
+ elif cdc_halted_from_config(scope_config[row.schedule_key]):
+ decision = DECISION_SKIP_CDC_HALTED
+ else:
+ decision = DECISION_WOULD_FIRE
+
+ records.append(
+ DecisionRecord(
+ team_id=row.team_id,
+ kind=row.kind,
+ schedule_key=row.schedule_key,
+ window_boundary=datetime.fromtimestamp(window_boundary(fire, cadence), tz=UTC),
+ due_at=datetime.fromtimestamp(fire, tz=UTC),
+ decision=decision,
+ interval_seconds=cadence.interval_seconds,
+ late_seconds=float(now_epoch - fire),
+ )
+ )
+ return EvaluationResult(records=tuple(records), missed_windows=missed_windows)
diff --git a/products/warehouse_sources/backend/tests/test_scheduler_shadow.py b/products/warehouse_sources/backend/tests/test_scheduler_shadow.py
new file mode 100644
index 000000000000..6d647d815b15
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/test_scheduler_shadow.py
@@ -0,0 +1,482 @@
+import io
+import time
+import uuid
+import importlib
+from datetime import (
+ UTC,
+ datetime,
+ time as dt_time,
+ timedelta,
+)
+
+import pytest
+from unittest.mock import AsyncMock, MagicMock
+
+from django.core.management import call_command
+
+import psycopg
+from asgiref.sync import async_to_sync
+
+from posthog.api.test.test_organization import create_organization
+from posthog.api.test.test_team import create_team
+
+from products.warehouse_sources.backend.management.commands.report_warehouse_scheduler_shadow import (
+ parse_schedule_fired_at,
+)
+from products.warehouse_sources.backend.models import ExternalDataJob, ExternalDataSchema, ExternalDataSource
+from products.warehouse_sources.backend.scheduling import runner as scheduler_runner
+from products.warehouse_sources.backend.scheduling.runner import ShadowScheduler, ShadowSchedulerConfig
+from products.warehouse_sources.backend.scheduling.shadow import (
+ DECISION_SKIP_CDC_HALTED,
+ DECISION_SKIP_OUT_OF_SCOPE,
+ DECISION_SKIP_OVERLAP,
+ DECISION_WOULD_FIRE,
+ SYNC_EXTRACT_KIND,
+ EvaluationResult,
+ SchemaCadence,
+ evaluate_due,
+ fetch_in_scope_schemas,
+ latest_fire_at,
+ next_due_after,
+ schedule_offset,
+ window_boundary,
+)
+from products.warehouse_sources_queue.backend.core.scheduler_state import (
+ SCHEDULER_DECISION_TABLE,
+ SCHEDULER_STATE_TABLE,
+ DecisionRecord,
+ SchedulerStateTable,
+)
+from products.warehouse_sources_queue.backend.sdk import DueSchedule
+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
+# as a facade leak; tests reference cross-product internals by module path
+# instead (the cdc tests' patch targets set the precedent). Parity needs the
+# real schedule builder, not a facade contract.
+get_sync_schedule = importlib.import_module("products.data_warehouse.backend.logic.data_load.service").get_sync_schedule
+
+FIXED_SCHEMA_IDS = [
+ "0d3a4c1e-8f2b-4a6d-9c5e-1b7f3a9d2e4c",
+ "7f6e5d4c-3b2a-4918-8776-655443322110",
+ "c0ffee00-1234-4abc-8def-987654321000",
+]
+
+INTERVALS = [
+ pytest.param(timedelta(minutes=5), id="5m"),
+ pytest.param(timedelta(minutes=30), id="30m"),
+ pytest.param(timedelta(hours=1), id="1h"),
+ pytest.param(timedelta(hours=6), id="6h"),
+ pytest.param(timedelta(hours=12), id="12h"),
+ pytest.param(timedelta(days=1), id="24h"),
+ pytest.param(timedelta(days=7), id="7d"),
+]
+
+
+def organization():
+ return create_organization("test org")
+
+
+def team(organization):
+ return create_team(organization=organization)
+
+
+def _unsaved_schema(schema_id: str, interval: timedelta, sync_time_of_day: dt_time | None) -> ExternalDataSchema:
+ return ExternalDataSchema(
+ id=uuid.UUID(schema_id),
+ team_id=1,
+ source_id=uuid.uuid4(),
+ sync_frequency_interval=interval,
+ sync_time_of_day=sync_time_of_day,
+ )
+
+
+class TestOffsetParity:
+ @pytest.mark.parametrize("interval", INTERVALS)
+ @pytest.mark.parametrize("schema_id", FIXED_SCHEMA_IDS)
+ def test_jitter_offset_matches_get_sync_schedule(self, schema_id, interval):
+ schema = _unsaved_schema(schema_id, interval, None)
+ schedule = get_sync_schedule(schema)
+ assert schedule.spec.intervals[0].offset == timedelta(seconds=schedule_offset(schema_id, interval, None))
+
+ @pytest.mark.parametrize(
+ "sync_time_of_day,interval,expected_offset",
+ [
+ pytest.param(dt_time(15, 30, 0), timedelta(days=1), timedelta(minutes=930), id="24h_direct"),
+ pytest.param(dt_time(15, 30, 0), timedelta(hours=6), timedelta(minutes=210), id="6h_reduced_mod"),
+ pytest.param(dt_time(15, 30, 45), timedelta(days=1), timedelta(minutes=930), id="seconds_dropped"),
+ ],
+ )
+ def test_sync_time_offset_matches_get_sync_schedule(self, sync_time_of_day, interval, expected_offset):
+ schema = _unsaved_schema(FIXED_SCHEMA_IDS[0], interval, sync_time_of_day)
+ schedule = get_sync_schedule(schema)
+ assert schedule.spec.intervals[0].offset == expected_offset
+ assert timedelta(seconds=schedule_offset(FIXED_SCHEMA_IDS[0], interval, sync_time_of_day)) == expected_offset
+
+
+class TestEpochMath:
+ @pytest.mark.parametrize(
+ "late_by",
+ [pytest.param(0, id="on_time"), pytest.param(59, id="1m_late"), pytest.param(21599, id="just_under_interval")],
+ )
+ def test_late_ticks_do_not_drift(self, late_by):
+ cadence = SchemaCadence(interval_seconds=21600, offset_seconds=12600)
+ boundary_now = (1_756_598_400 // 21600) * 21600 + 12600
+
+ fire = latest_fire_at(boundary_now + late_by, cadence)
+ assert fire == boundary_now
+ assert (fire - cadence.offset_seconds) % cadence.interval_seconds == 0
+ assert window_boundary(fire, cadence) == fire - cadence.offset_seconds
+ assert window_boundary(fire, cadence) % cadence.interval_seconds == 0
+
+ next_fire = latest_fire_at(boundary_now + cadence.interval_seconds + late_by, cadence)
+ assert next_fire - fire == cadence.interval_seconds
+
+ @pytest.mark.parametrize(
+ "now_offset",
+ [pytest.param(0, id="at_boundary"), pytest.param(1, id="just_after"), pytest.param(21599, id="just_before")],
+ )
+ def test_next_due_after_never_returns_past_or_now(self, now_offset):
+ cadence = SchemaCadence(interval_seconds=21600, offset_seconds=12600)
+ now = (1_756_598_400 // 21600) * 21600 + 12600 + now_offset
+ assert next_due_after(now, cadence) > now
+
+
+def _create_source(team, **overrides) -> ExternalDataSource:
+ defaults = {
+ "team": team,
+ "source_id": str(uuid.uuid4()),
+ "connection_id": str(uuid.uuid4()),
+ "status": "Running",
+ "source_type": "Stripe",
+ "access_method": ExternalDataSource.AccessMethod.WAREHOUSE,
+ }
+ return ExternalDataSource.objects.create(**{**defaults, **overrides})
+
+
+def _create_schema(team, source, **overrides) -> ExternalDataSchema:
+ defaults = {
+ "team": team,
+ "source": source,
+ "name": "test_table",
+ "should_sync": True,
+ "sync_frequency_interval": timedelta(hours=6),
+ }
+ return ExternalDataSchema.objects.create(**{**defaults, **overrides})
+
+
+class TestScopePredicate:
+ @pytest.mark.parametrize(
+ "source_overrides,schema_overrides,expected_in_scope",
+ [
+ pytest.param({}, {}, True, id="baseline_included"),
+ pytest.param({}, {"should_sync": False}, False, id="sync_disabled"),
+ pytest.param({}, {"sync_frequency_interval": None}, False, id="no_interval"),
+ pytest.param({}, {"deleted": True}, False, id="schema_deleted"),
+ pytest.param({"deleted": True}, {}, False, id="source_deleted"),
+ pytest.param({"access_method": ExternalDataSource.AccessMethod.DIRECT}, {}, False, id="direct_source"),
+ pytest.param({}, {"sync_type_config": {"cdc_broken": True}}, True, id="cdc_halted_stays_in_scope"),
+ ],
+ )
+ def test_scope_predicate(self, team, source_overrides, schema_overrides, expected_in_scope):
+ 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()}
+ assert (str(schema.id) in in_scope_ids) == expected_in_scope
+
+
+def _due_row(schema_id: str, team_id: int, now_epoch: int) -> DueSchedule:
+ cadence = SchemaCadence(interval_seconds=21600, offset_seconds=0)
+ return DueSchedule(
+ kind=SYNC_EXTRACT_KIND,
+ schedule_key=schema_id,
+ team_id=team_id,
+ interval_seconds=cadence.interval_seconds,
+ offset_seconds=cadence.offset_seconds,
+ next_due_at=datetime.fromtimestamp(latest_fire_at(now_epoch, cadence), tz=UTC),
+ )
+
+
[email protected]_db(transaction=True)
+class TestEvaluateDue:
+ @pytest.mark.parametrize(
+ "job_status,sync_type_config,expected_decision",
+ [
+ pytest.param("Running", {}, DECISION_SKIP_OVERLAP, id="running_job_overlaps"),
+ pytest.param("Completed", {}, DECISION_WOULD_FIRE, id="completed_job_fires"),
+ pytest.param("Failed", {}, DECISION_WOULD_FIRE, id="failed_job_fires"),
+ pytest.param("BillingLimitReached", {}, DECISION_WOULD_FIRE, id="billing_limited_job_fires"),
+ pytest.param(None, {"cdc_broken": True}, DECISION_SKIP_CDC_HALTED, id="cdc_broken_skips"),
+ pytest.param(None, {"cdc_extraction_paused": True}, DECISION_SKIP_CDC_HALTED, id="cdc_paused_skips"),
+ pytest.param(None, {"cdc_broken": False}, DECISION_WOULD_FIRE, id="cdc_ok_fires"),
+ ],
+ )
+ def test_skip_reasons(self, team, job_status, sync_type_config, expected_decision):
+ source = _create_source(team)
+ schema = _create_schema(team, source, sync_type_config=sync_type_config)
+ now_epoch = int(time.time())
+ if job_status is not None:
+ job = ExternalDataJob.objects.create(team=team, pipeline=source, schema=schema, status=job_status)
+ if expected_decision == DECISION_SKIP_OVERLAP:
+ due_at = datetime.fromtimestamp(
+ latest_fire_at(now_epoch, SchemaCadence(interval_seconds=21600, offset_seconds=0)), tz=UTC
+ )
+ ExternalDataJob.objects.filter(pk=job.pk).update(created_at=due_at - timedelta(seconds=1))
+
+ result = async_to_sync(evaluate_due)([_due_row(str(schema.id), team.pk, now_epoch)], now_epoch)
+
+ assert len(result.records) == 1
+ record = result.records[0]
+ assert record.decision == expected_decision
+ assert record.due_at == datetime.fromtimestamp(
+ latest_fire_at(now_epoch, SchemaCadence(interval_seconds=21600, offset_seconds=0)), tz=UTC
+ )
+ assert result.missed_windows == 0
+
+ def test_current_boundary_temporal_job_is_not_an_overlap(self, team):
+ source = _create_source(team)
+ schema = _create_schema(team, source)
+ now_epoch = int(time.time())
+ due_at = datetime.fromtimestamp(
+ latest_fire_at(now_epoch, SchemaCadence(interval_seconds=21600, offset_seconds=0)), tz=UTC
+ )
+ job = ExternalDataJob.objects.create(team=team, pipeline=source, schema=schema, status="Running")
+ ExternalDataJob.objects.filter(pk=job.pk).update(created_at=due_at)
+
+ result = async_to_sync(evaluate_due)([_due_row(str(schema.id), team.pk, now_epoch)], now_epoch)
+
+ assert [record.decision for record in result.records] == [DECISION_WOULD_FIRE]
+
+ def test_unknown_schema_is_out_of_scope(self, team):
+ now_epoch = int(time.time())
+ result = async_to_sync(evaluate_due)([_due_row(str(uuid.uuid4()), team.pk, now_epoch)], now_epoch)
+ assert [record.decision for record in result.records] == [DECISION_SKIP_OUT_OF_SCOPE]
+
+
[email protected]_db(transaction=True)
+class TestShadowSchedulerTick:
+ def _setup_due_state(self, team_id: int) -> tuple[str, 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),
+ )
+ return schema_id, due_at, db_url
+
+ def _record(self, schema_id: str, team_id: int, due_at: datetime) -> DecisionRecord:
+ return DecisionRecord(
+ team_id=team_id,
+ kind=SYNC_EXTRACT_KIND,
+ schedule_key=schema_id,
+ window_boundary=due_at,
+ due_at=due_at,
+ decision=DECISION_WOULD_FIRE,
+ interval_seconds=3600,
+ late_seconds=60.0,
+ )
+
+ def test_failed_decision_write_rolls_back_state_advance(self, team, monkeypatch):
+ schema_id, due_at, db_url = self._setup_due_state(team.pk)
+ record = self._record(schema_id, team.pk, due_at)
+ original_insert = SchedulerStateTable.insert_decisions
+
+ async def insert_then_fail(conn, records):
+ await original_insert(conn, records)
+ raise RuntimeError("decision write failed")
+
+ monkeypatch.setattr(
+ scheduler_runner.JobsTable,
+ "try_acquire_sentinel_slot",
+ AsyncMock(side_effect=[True, False]),
+ )
+ monkeypatch.setattr(
+ scheduler_runner,
+ "evaluate_due",
+ AsyncMock(return_value=EvaluationResult(records=(record,), missed_windows=0)),
+ )
+ monkeypatch.setattr(SchedulerStateTable, "insert_decisions", insert_then_fail)
+
+ scheduler = ShadowScheduler(ShadowSchedulerConfig(database_url=db_url))
+ with pytest.raises(RuntimeError, match="decision write failed"):
+ async_to_sync(scheduler._tick)(lambda: None)
+
+ with psycopg.Connection.connect(db_url) as conn:
+ assert conn.execute(
+ f"SELECT next_due_at FROM {SCHEDULER_STATE_TABLE} WHERE kind = %s AND schedule_key = %s",
+ (SYNC_EXTRACT_KIND, schema_id),
+ ).fetchone() == (due_at,)
+ assert conn.execute(f"SELECT count(*) FROM {SCHEDULER_DECISION_TABLE}").fetchone() == (0,)
+
+ def test_duplicate_decision_does_not_emit_outcome_metrics(self, team, monkeypatch):
+ schema_id, due_at, db_url = self._setup_due_state(team.pk)
+ record = self._record(schema_id, team.pk, due_at)
+ with psycopg.Connection.connect(db_url, autocommit=True) as conn:
+ conn.execute(
+ f"""
+ INSERT INTO {SCHEDULER_DECISION_TABLE}
+ (team_id, kind, schedule_key, window_boundary, due_at, decision, interval_seconds, late_seconds)
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
+ """,
+ (
+ record.team_id,
+ record.kind,
+ record.schedule_key,
+ record.window_boundary,
+ record.due_at,
+ record.decision,
+ record.interval_seconds,
+ record.late_seconds,
+ ),
+ )
+
+ monkeypatch.setattr(
+ scheduler_runner.JobsTable,
+ "try_acquire_sentinel_slot",
+ AsyncMock(side_effect=[True, False]),
+ )
+ monkeypatch.setattr(
+ scheduler_runner,
+ "evaluate_due",
+ AsyncMock(return_value=EvaluationResult(records=(record,), missed_windows=0)),
+ )
+ would_fire = MagicMock()
+ skips = MagicMock()
+ lateness = MagicMock()
+ duplicate_windows = MagicMock()
+ monkeypatch.setattr(scheduler_runner, "WOULD_FIRE_TOTAL", would_fire)
+ monkeypatch.setattr(scheduler_runner, "SKIPS_TOTAL", skips)
+ monkeypatch.setattr(scheduler_runner, "FIRE_LATENESS_SECONDS", lateness)
+ monkeypatch.setattr(scheduler_runner, "DUPLICATE_WINDOWS_TOTAL", duplicate_windows)
+
+ scheduler = ShadowScheduler(ShadowSchedulerConfig(database_url=db_url))
+ async_to_sync(scheduler._tick)(lambda: None)
+
+ would_fire.inc.assert_not_called()
+ skips.labels.assert_not_called()
+ lateness.observe.assert_not_called()
+ duplicate_windows.inc.assert_called_once_with(1)
+
+
+class TestShadowReport:
+ def test_report_matches_jobs_and_counts_adhoc(self, team, monkeypatch):
+ 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}")
+ monkeypatch.setattr(
+ "products.warehouse_sources.backend.management.commands.report_warehouse_scheduler_shadow"
+ ".WAREHOUSE_SOURCES_DATABASE_URL",
+ db_url,
+ )
+
+ source = _create_source(team)
+ matched_schema = _create_schema(team, source)
+ adhoc_schema = _create_schema(team, source, name="other_table")
+
+ due_at = (datetime.now(UTC) - timedelta(minutes=10)).replace(microsecond=0)
+ with psycopg.Connection.connect(db_url, autocommit=True) as conn:
+ conn.execute(
+ f"""
+ INSERT INTO {SCHEDULER_DECISION_TABLE}
+ (team_id, kind, schedule_key, window_boundary, due_at, decision, interval_seconds, late_seconds)
+ VALUES (%(team_id)s, %(kind)s, %(schedule_key)s, %(due_at)s, %(due_at)s, 'would_fire', 21600, 1.0)
+ """,
+ {
+ "team_id": team.pk,
+ "kind": SYNC_EXTRACT_KIND,
+ "schedule_key": str(matched_schema.id),
+ "due_at": due_at,
+ },
+ )
+ conn.execute(
+ f"""
+ INSERT INTO {SCHEDULER_DECISION_TABLE}
+ (team_id, kind, schedule_key, window_boundary, due_at, decision, interval_seconds, late_seconds)
+ VALUES (%(team_id)s, 'other.kind', %(schedule_key)s, %(due_at)s, %(due_at)s, 'would_fire', 21600, 1.0)
+ """,
+ {"team_id": team.pk, "schedule_key": str(matched_schema.id), "due_at": due_at},
+ )
+
+ ExternalDataJob.objects.create(
+ team=team,
+ pipeline=source,
+ schema=matched_schema,
+ status="Running",
+ workflow_id=f"{matched_schema.id}-{due_at.isoformat()}",
+ )
+ ExternalDataJob.objects.create(
+ team=team, pipeline=source, schema=adhoc_schema, status="Running", workflow_id=None
+ )
+
+ out = io.StringIO()
+ call_command("report_warehouse_scheduler_shadow", "--team-id", str(team.pk), stdout=out)
+ output = out.getvalue()
+
+ assert "matched: 1" in output
+ assert "shadow_only (shadow would fire, no job): 0" in output
+ assert "temporal_only (schedule-fired job, no decision): 0" in output
+ assert "adhoc (manual/backfill runs, excluded): 1" in output
+
+ def test_adhoc_job_does_not_consume_nearby_decision(self, team, monkeypatch):
+ 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}")
+ monkeypatch.setattr(
+ "products.warehouse_sources.backend.management.commands.report_warehouse_scheduler_shadow"
+ ".WAREHOUSE_SOURCES_DATABASE_URL",
+ db_url,
+ )
+
+ source = _create_source(team)
+ schema = _create_schema(team, source)
+ due_at = (datetime.now(UTC) - timedelta(minutes=10)).replace(microsecond=0)
+ with psycopg.Connection.connect(db_url, autocommit=True) as conn:
+ conn.execute(
+ f"""
+ INSERT INTO {SCHEDULER_DECISION_TABLE}
+ (team_id, kind, schedule_key, window_boundary, due_at, decision, interval_seconds, late_seconds)
+ VALUES (%(team_id)s, %(kind)s, %(schedule_key)s, %(due_at)s, %(due_at)s, 'would_fire', 21600, 1.0)
+ """,
+ {"team_id": team.pk, "kind": SYNC_EXTRACT_KIND, "schedule_key": str(schema.id), "due_at": due_at},
+ )
+ ExternalDataJob.objects.create(team=team, pipeline=source, schema=schema, status="Running", workflow_id=None)
+
+ out = io.StringIO()
+ call_command("report_warehouse_scheduler_shadow", "--team-id", str(team.pk), stdout=out)
+ output = out.getvalue()
+
+ assert "matched: 0" in output
+ assert "shadow_only (shadow would fire, no job): 1" in output
+ assert "temporal_only (schedule-fired job, no decision): 0" in output
+ assert "adhoc (manual/backfill runs, excluded): 1" in output
+
+ @pytest.mark.parametrize(
+ "workflow_id,expected",
+ [
+ pytest.param(None, None, id="no_workflow_id"),
+ pytest.param("manual-run", None, id="no_schema_prefix"),
+ pytest.param("SCHEMA-not-a-timestamp", None, id="unparseable_suffix"),
+ pytest.param("SCHEMA-2026-08-31T12:00:00+00:00", datetime(2026, 8, 31, 12, 0, tzinfo=UTC), id="iso_suffix"),
+ pytest.param(
+ "SCHEMA-2026-08-31T12:00:00", datetime(2026, 8, 31, 12, 0, tzinfo=UTC), id="naive_iso_becomes_utc"
+ ),
+ ],
+ )
+ def test_parse_schedule_fired_at(self, workflow_id, expected):
+ workflow_id = workflow_id.replace("SCHEMA", "abc123") if workflow_id else workflow_id
+ assert parse_schedule_fired_at("abc123", workflow_id) == expected
diff --git a/products/warehouse_sources_queue/backend/README.md b/products/warehouse_sources_queue/backend/README.md
index c67ca51212da..7976e289f058 100644
--- a/products/warehouse_sources_queue/backend/README.md
+++ b/products/warehouse_sources_queue/backend/README.md
@@ -149,3 +149,15 @@ For ad-hoc inspection (state summaries, active runs, leases, force-release), use
Followers returned by a successful handler (`sdk.Success(followers=...)`) are enqueued in the same transaction as the terminal status write. Dedup of live `(kind, dedup_key)` pairs is enforced by the insert statement's `NOT EXISTS` guard rather than a unique index — a partitioned table cannot carry a unique index that omits the partition key.
SQL lives in `core/generic_jobs.py`; the SDK wiring (`JobHandler`, `Outcome`, `GenericJobAdapter`, `JobConsumer`) in `sdk/jobs.py`. Nothing produces or consumes these tables yet; the run orchestrator lands on them in later phases.
+
+## Scheduler state (phase 2, shadow mode)
+
+`queueschedulerstate` holds one row per `(kind, schedule_key)` with its cadence and epoch-aligned `next_due_at`.
+`queueschedulerdecision` records one decision per `(kind, schedule_key, due_at)`.
+The warehouse scheduler uses `sync.extract` as its kind and the schema ID as its schedule key.
+SQL lives in `core/scheduler_state.py`.
+The tick loop, scope predicate, and due-time math live in `products/warehouse_sources/backend/scheduling/`.
+The `run_warehouse_scheduler` command runs the tick loop.
+The scheduler uses sentinel rows in `queuejoblease` (lane `scheduler`) to select one leader across the fleet.
+It starts no syncs.
+The `report_warehouse_scheduler_shadow` command compares decisions with the `ExternalDataJob` rows that Temporal schedules created.
diff --git a/products/warehouse_sources_queue/backend/core/generic_jobs.py b/products/warehouse_sources_queue/backend/core/generic_jobs.py
index 84447180b29a..7ba392df62f9 100644
--- a/products/warehouse_sources_queue/backend/core/generic_jobs.py
+++ b/products/warehouse_sources_queue/backend/core/generic_jobs.py
@@ -650,6 +650,41 @@ class JobsTable:
{"owner": owner_token},
)
+ @staticmethod
+ async def try_acquire_sentinel_slot(
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ lane: str,
+ group_key: str,
+ owner_token: str,
+ ttl_seconds: float,
+ ) -> bool:
+ """Claim a fleet-wide single-flight slot; True means this pod runs the work.
+
+ A sentinel row in the job-lease table, CAS-acquired only when expired,
+ transplanted from ``BatchQueue.try_acquire_reconcile_sweep_slot``. There
+ is deliberately no release and no same-owner re-entrancy clause: the TTL
+ *is* the fleet-wide cadence, so at most one winner starts per TTL no
+ matter how many pods race for it, and a crashed winner's slot frees
+ itself at expiry.
+ """
+ async with conn.cursor() as cur:
+ await cur.execute(
+ f"""
+ INSERT INTO {JOB_LEASE_TABLE} (lane, group_key, owner_token, expires_at, acquired_at, updated_at)
+ VALUES (%(lane)s, %(group_key)s, %(owner)s, now() + make_interval(secs => %(ttl)s), now(), now())
+ ON CONFLICT (lane, group_key) DO UPDATE
+ SET owner_token = excluded.owner_token,
+ expires_at = excluded.expires_at,
+ acquired_at = now(),
+ updated_at = now()
+ WHERE {JOB_LEASE_TABLE}.expires_at <= now()
+ RETURNING id
+ """,
+ {"lane": lane, "group_key": group_key, "owner": owner_token, "ttl": ttl_seconds},
+ )
+ return await cur.fetchone() is not None
+
# -- sweeps and gauges -------------------------------------------------------
RECOVERY_SWEEP_GROUP_KEY = "__recovery-sweep__"
diff --git a/products/warehouse_sources_queue/backend/core/scheduler_state.py b/products/warehouse_sources_queue/backend/core/scheduler_state.py
new file mode 100644
index 000000000000..174616580328
--- /dev/null
+++ b/products/warehouse_sources_queue/backend/core/scheduler_state.py
@@ -0,0 +1,279 @@
+"""Scheduler state: SQL and row types for scheduler tables.
+
+``queueschedulerstate`` holds one row per schedule with its cadence and
+the next epoch-aligned due time; ``queueschedulerdecision`` is the append-only
+record of what the scheduler would have done at each window. Both tables are
+small (one row per schedule, decisions pruned on a retention window), so unlike
+the job tables they are not partitioned. All SQL lives here (the ``JobsTable``
+idiom); callers drive the tick loop.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import datetime
+from typing import Any
+
+import psycopg
+from psycopg.rows import dict_row
+
+SCHEDULER_STATE_TABLE = "queueschedulerstate"
+SCHEDULER_DECISION_TABLE = "queueschedulerdecision"
+
+
+@dataclass(frozen=True, kw_only=True, slots=True)
+class DueSchedule:
+ """One scheduler-state row: a schedule's cadence and its next due time."""
+
+ kind: str
+ schedule_key: str
+ team_id: int
+ interval_seconds: int
+ offset_seconds: int
+ next_due_at: datetime
+
+
+@dataclass(frozen=True, kw_only=True, slots=True)
+class DecisionRecord:
+ """One decision for a schedule's fire window."""
+
+ team_id: int
+ kind: str
+ schedule_key: str
+ window_boundary: datetime
+ due_at: datetime
+ decision: str
+ interval_seconds: int
+ late_seconds: float
+
+
+_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()
+ )
+ ON CONFLICT (kind, schedule_key) DO UPDATE SET
+ team_id = excluded.team_id,
+ -- A cadence change re-anchors the schedule; an unchanged cadence keeps
+ -- the stored due time so refreshes never move a pending fire.
+ next_due_at = CASE
+ WHEN ({SCHEDULER_STATE_TABLE}.interval_seconds, {SCHEDULER_STATE_TABLE}.offset_seconds)
+ IS DISTINCT FROM (excluded.interval_seconds, excluded.offset_seconds)
+ THEN excluded.next_due_at
+ ELSE {SCHEDULER_STATE_TABLE}.next_due_at
+ END,
+ interval_seconds = excluded.interval_seconds,
+ offset_seconds = excluded.offset_seconds,
+ refreshed_at = now(),
+ updated_at = now()
+"""
+
+_INSERT_DECISIONS_SQL = f"""
+ WITH input AS (
+ SELECT *
+ FROM unnest(
+ %(team_ids)s::bigint[],
+ %(kinds)s::text[],
+ %(schedule_keys)s::text[],
+ %(window_boundaries)s::timestamptz[],
+ %(due_times)s::timestamptz[],
+ %(decisions)s::text[],
+ %(intervals)s::bigint[],
+ %(lateness)s::double precision[]
+ ) WITH ORDINALITY AS rows(
+ team_id, kind, schedule_key, window_boundary, due_at, decision,
+ interval_seconds, late_seconds, record_index
+ )
+ ), deduplicated AS (
+ SELECT DISTINCT ON (kind, schedule_key, due_at) *
+ FROM input
+ ORDER BY kind, schedule_key, due_at, record_index
+ ), inserted AS (
+ INSERT INTO {SCHEDULER_DECISION_TABLE} (
+ team_id, kind, schedule_key, window_boundary, due_at, decision, interval_seconds, late_seconds
+ )
+ SELECT team_id, kind, schedule_key, window_boundary, due_at, decision, interval_seconds, late_seconds
+ FROM deduplicated
+ ON CONFLICT (kind, schedule_key, due_at) DO NOTHING
+ RETURNING kind, schedule_key, due_at
+ )
+ SELECT deduplicated.record_index
+ FROM deduplicated
+ INNER JOIN inserted USING (kind, schedule_key, due_at)
+ ORDER BY deduplicated.record_index
+"""
+
+
+class SchedulerStateTable:
+ """Raw SQL over the scheduler tables (the ``JobsTable`` idiom)."""
+
+ @staticmethod
+ async def upsert_states(
+ 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."""
+ if not rows:
+ return
+ async with conn.cursor() as cur:
+ await cur.executemany(
+ _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
+ ],
+ )
+
+ @staticmethod
+ async def delete_states_not_refreshed_since(
+ conn: psycopg.AsyncConnection[Any],
+ kind: str,
+ cutoff: datetime,
+ ) -> int:
+ """Drop rows the latest refresh did not touch."""
+ async with conn.cursor() as cur:
+ await cur.execute(
+ f"DELETE FROM {SCHEDULER_STATE_TABLE} WHERE kind = %(kind)s AND refreshed_at < %(cutoff)s",
+ {"kind": kind, "cutoff": cutoff},
+ )
+ return cur.rowcount
+
+ @staticmethod
+ async def claim_due(
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ kind: str,
+ limit: int,
+ ) -> list[DueSchedule]:
+ """Lock and return the due rows. Call inside a transaction and advance
+ the same rows with :meth:`advance_states` before it commits, so a
+ concurrent claimer (SKIP LOCKED) never double-observes a window."""
+ async with conn.cursor(row_factory=dict_row) as cur:
+ await cur.execute(
+ f"""
+ SELECT kind, schedule_key, team_id, interval_seconds, offset_seconds, next_due_at
+ FROM {SCHEDULER_STATE_TABLE}
+ WHERE kind = %(kind)s AND next_due_at <= now()
+ ORDER BY next_due_at
+ LIMIT %(limit)s
+ FOR UPDATE SKIP LOCKED
+ """,
+ {"kind": kind, "limit": limit},
+ )
+ rows = await cur.fetchall()
+ return [DueSchedule(**row) for row in rows]
+
+ @staticmethod
+ async def advance_states(
+ conn: psycopg.AsyncConnection[Any],
+ rows: list[tuple[DueSchedule, datetime]],
+ ) -> None:
+ """Advance claimed rows to their next due time; pair with :meth:`claim_due`."""
+ if not rows:
+ return
+ async with conn.cursor() as cur:
+ await cur.executemany(
+ f"""
+ UPDATE {SCHEDULER_STATE_TABLE}
+ SET next_due_at = %(next_due_at)s, updated_at = now()
+ WHERE kind = %(kind)s AND schedule_key = %(schedule_key)s
+ """,
+ [
+ {"kind": row.kind, "schedule_key": row.schedule_key, "next_due_at": next_due_at}
+ for row, next_due_at in rows
+ ],
+ )
+
+ @staticmethod
+ async def delete_states(
+ conn: psycopg.AsyncConnection[Any],
+ kind: str,
+ schedule_keys: list[str],
+ ) -> int:
+ """Drop specific state rows that left scope."""
+ if not schedule_keys:
+ return 0
+ async with conn.cursor() as cur:
+ await cur.execute(
+ f"DELETE FROM {SCHEDULER_STATE_TABLE} WHERE kind = %(kind)s AND schedule_key = ANY(%(schedule_keys)s)",
+ {"kind": kind, "schedule_keys": schedule_keys},
+ )
+ return cur.rowcount
+
+ @staticmethod
+ async def insert_decisions(
+ conn: psycopg.AsyncConnection[Any],
+ records: list[DecisionRecord],
+ ) -> tuple[list[DecisionRecord], int]:
+ """Record decisions and return (inserted records, refused count).
+
+ A refusal means the (kind, schedule_key, due_at) tuple was already recorded,
+ which in a single-flighted fleet indicates a duplicate-window bug
+ worth a metric.
+ """
+ if not records:
+ return ([], 0)
+ async with conn.cursor() as cur:
+ await cur.execute(
+ _INSERT_DECISIONS_SQL,
+ {
+ "team_ids": [record.team_id for record in records],
+ "kinds": [record.kind for record in records],
+ "schedule_keys": [record.schedule_key for record in records],
+ "window_boundaries": [record.window_boundary for record in records],
+ "due_times": [record.due_at for record in records],
+ "decisions": [record.decision for record in records],
+ "intervals": [record.interval_seconds for record in records],
+ "lateness": [record.late_seconds for record in records],
+ },
+ )
+ inserted_indexes = [row[0] - 1 for row in await cur.fetchall()]
+ inserted = [records[index] for index in inserted_indexes]
+ return (inserted, len(records) - len(inserted))
+
+ @staticmethod
+ async def prune_decisions(
+ conn: psycopg.AsyncConnection[Any],
+ *,
+ kind: str,
+ older_than_days: int,
+ ) -> int:
+ async with conn.cursor() as cur:
+ await cur.execute(
+ f"""
+ DELETE FROM {SCHEDULER_DECISION_TABLE}
+ WHERE kind = %(kind)s AND observed_at < now() - make_interval(days => %(days)s)
+ """,
+ {"kind": kind, "days": older_than_days},
+ )
+ return cur.rowcount
+
+ @staticmethod
+ def fetch_would_fires(
+ conn: psycopg.Connection[Any],
+ kind: str,
+ since: datetime,
+ ) -> list[DecisionRecord]:
+ """Read the would-fire decisions for one kind."""
+ with conn.cursor(row_factory=dict_row) as cur:
+ cur.execute(
+ f"""
+ SELECT team_id, kind, schedule_key, window_boundary, due_at, decision, interval_seconds, late_seconds
+ FROM {SCHEDULER_DECISION_TABLE}
+ WHERE kind = %(kind)s AND decision = 'would_fire' AND due_at >= %(since)s
+ ORDER BY due_at
+ """,
+ {"kind": kind, "since": since},
+ )
+ rows = cur.fetchall()
+ return [DecisionRecord(**row) for row in rows]
diff --git a/products/warehouse_sources_queue/backend/migrations/0012_scheduler_state.py b/products/warehouse_sources_queue/backend/migrations/0012_scheduler_state.py
new file mode 100644
index 000000000000..4d7ee98778c0
--- /dev/null
+++ b/products/warehouse_sources_queue/backend/migrations/0012_scheduler_state.py
@@ -0,0 +1,122 @@
+from django.db import migrations, models
+
+
+def _create_scheduler_tables(apps, schema_editor):
+ # One statement per execute(): psycopg3 uses the extended query protocol,
+ # which parses a single statement at a time.
+ schema_editor.execute("""
+ CREATE TABLE queueschedulerstate (
+ id BIGSERIAL PRIMARY KEY,
+ kind VARCHAR(100) NOT NULL,
+ schedule_key VARCHAR(200) NOT NULL,
+ team_id BIGINT NOT NULL,
+ interval_seconds BIGINT NOT NULL,
+ offset_seconds INT NOT NULL,
+ next_due_at TIMESTAMPTZ NOT NULL,
+ refreshed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CONSTRAINT qss_kind_key_uniq UNIQUE (kind, schedule_key)
+ )
+ """)
+ schema_editor.execute("""
+ CREATE INDEX qss_next_due_idx ON queueschedulerstate (next_due_at)
+ """)
+ schema_editor.execute("""
+ CREATE INDEX qss_refreshed_idx ON queueschedulerstate (refreshed_at)
+ """)
+ schema_editor.execute("""
+ CREATE TABLE queueschedulerdecision (
+ id BIGSERIAL PRIMARY KEY,
+ team_id BIGINT NOT NULL,
+ kind VARCHAR(100) NOT NULL,
+ schedule_key VARCHAR(200) NOT NULL,
+ window_boundary TIMESTAMPTZ NOT NULL,
+ due_at TIMESTAMPTZ NOT NULL,
+ decision VARCHAR(32) NOT NULL,
+ interval_seconds BIGINT NOT NULL,
+ late_seconds DOUBLE PRECISION NOT NULL,
+ observed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CONSTRAINT qsd_kind_key_due_uniq UNIQUE (kind, schedule_key, due_at)
+ )
+ """)
+ schema_editor.execute("""
+ CREATE INDEX qsd_observed_at_idx ON queueschedulerdecision (observed_at)
+ """)
+
+
+def _drop_scheduler_tables(apps, schema_editor):
+ schema_editor.execute("DROP TABLE IF EXISTS queueschedulerdecision CASCADE")
+ schema_editor.execute("DROP TABLE IF EXISTS queueschedulerstate CASCADE")
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("warehouse_sources_queue", "0011_generic_job_tables"),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.CreateModel(
+ name="QueueSchedulerState",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
+ ),
+ ),
+ ("kind", models.CharField(max_length=100)),
+ ("schedule_key", models.CharField(max_length=200)),
+ ("team_id", models.BigIntegerField()),
+ ("interval_seconds", models.BigIntegerField()),
+ ("offset_seconds", models.IntegerField()),
+ ("next_due_at", models.DateTimeField()),
+ ("refreshed_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ],
+ options={
+ "db_table": "queueschedulerstate",
+ "constraints": [
+ models.UniqueConstraint(fields=("kind", "schedule_key"), name="qss_kind_key_uniq")
+ ],
+ "indexes": [
+ models.Index(fields=["next_due_at"], name="qss_next_due_idx"),
+ models.Index(fields=["refreshed_at"], name="qss_refreshed_idx"),
+ ],
+ },
+ ),
+ migrations.CreateModel(
+ name="QueueSchedulerDecision",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
+ ),
+ ),
+ ("team_id", models.BigIntegerField()),
+ ("kind", models.CharField(max_length=100)),
+ ("schedule_key", models.CharField(max_length=200)),
+ ("window_boundary", models.DateTimeField()),
+ ("due_at", models.DateTimeField()),
+ ("decision", models.CharField(max_length=32)),
+ ("interval_seconds", models.BigIntegerField()),
+ ("late_seconds", models.FloatField()),
+ ("observed_at", models.DateTimeField(auto_now_add=True)),
+ ],
+ options={
+ "db_table": "queueschedulerdecision",
+ "constraints": [
+ models.UniqueConstraint(
+ fields=("kind", "schedule_key", "due_at"), name="qsd_kind_key_due_uniq"
+ )
+ ],
+ "indexes": [models.Index(fields=["observed_at"], name="qsd_observed_at_idx")],
+ },
+ ),
+ ],
+ database_operations=[],
+ ),
+ migrations.RunPython(_create_scheduler_tables, _drop_scheduler_tables),
+ ]
diff --git a/products/warehouse_sources_queue/backend/migrations/max_migration.txt b/products/warehouse_sources_queue/backend/migrations/max_migration.txt
index 4271773265b0..cdb78cfaaede 100644
--- a/products/warehouse_sources_queue/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources_queue/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0011_generic_job_tables
+0012_scheduler_state
diff --git a/products/warehouse_sources_queue/backend/models.py b/products/warehouse_sources_queue/backend/models.py
index 16068721636a..cfa2f872a41c 100644
--- a/products/warehouse_sources_queue/backend/models.py
+++ b/products/warehouse_sources_queue/backend/models.py
@@ -298,3 +298,63 @@ class QueueJobLease(models.Model):
indexes = [
models.Index(fields=["expires_at"], name="qjl_expires_at_idx"),
]
+
+
+class QueueSchedulerState(models.Model):
+ """One row per schedule: its cadence and epoch-aligned next due time.
+
+ Written by the scheduler's refresh and claim passes. All access
+ is via raw SQL in ``core/scheduler_state.py`` — this model exists for
+ migration and introspection.
+ """
+
+ kind = models.CharField(max_length=100)
+ schedule_key = models.CharField(max_length=200)
+ team_id = models.BigIntegerField()
+ interval_seconds = models.BigIntegerField()
+ offset_seconds = models.IntegerField()
+ next_due_at = models.DateTimeField()
+ refreshed_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ __repr__ = sane_repr("kind", "schedule_key", "team_id", "next_due_at")
+
+ class Meta:
+ db_table = "queueschedulerstate"
+ constraints = [
+ models.UniqueConstraint(fields=["kind", "schedule_key"], name="qss_kind_key_uniq"),
+ ]
+ indexes = [
+ models.Index(fields=["next_due_at"], name="qss_next_due_idx"),
+ models.Index(fields=["refreshed_at"], name="qss_refreshed_idx"),
+ ]
+
+
+class QueueSchedulerDecision(models.Model):
+ """Append-only scheduler decision per (kind, schedule key, due time).
+
+ The unique (kind, schedule_key, due_at) tuple allows a cadence offset change to fire
+ again inside the same offset-free boundary. All access is via raw SQL in
+ ``core/scheduler_state.py``.
+ """
+
+ team_id = models.BigIntegerField()
+ kind = models.CharField(max_length=100)
+ schedule_key = models.CharField(max_length=200)
+ window_boundary = models.DateTimeField()
+ due_at = models.DateTimeField()
+ decision = models.CharField(max_length=32)
+ interval_seconds = models.BigIntegerField()
+ late_seconds = models.FloatField()
+ observed_at = models.DateTimeField(auto_now_add=True)
+
+ __repr__ = sane_repr("kind", "schedule_key", "window_boundary", "decision")
+
+ class Meta:
+ db_table = "queueschedulerdecision"
+ constraints = [
+ models.UniqueConstraint(fields=["kind", "schedule_key", "due_at"], name="qsd_kind_key_due_uniq"),
+ ]
+ indexes = [
+ models.Index(fields=["observed_at"], name="qsd_observed_at_idx"),
+ ]
diff --git a/products/warehouse_sources_queue/backend/sdk/__init__.py b/products/warehouse_sources_queue/backend/sdk/__init__.py
index 1687d4888805..58219ee3ddbd 100644
--- a/products/warehouse_sources_queue/backend/sdk/__init__.py
+++ b/products/warehouse_sources_queue/backend/sdk/__init__.py
@@ -33,6 +33,11 @@ from products.warehouse_sources_queue.backend.core.metrics import (
ConsumerMetrics,
make_consumer_metrics,
)
+from products.warehouse_sources_queue.backend.core.scheduler_state import (
+ DecisionRecord,
+ DueSchedule,
+ SchedulerStateTable,
+)
from products.warehouse_sources_queue.backend.sdk.jobs import (
Fail,
FollowerSpec,
@@ -60,6 +65,8 @@ __all__ = [
"BatchConsumerConfig",
"BatchQueue",
"ConsumerMetrics",
+ "DecisionRecord",
+ "DueSchedule",
"Fail",
"FollowerSpec",
"GenericJobAdapter",
@@ -75,6 +82,7 @@ __all__ = [
"PermanentBatchApplyError",
"Retry",
"RunActivitySummary",
+ "SchedulerStateTable",
"Success",
"latest_status_lateral",
"make_consumer_metrics",
diff --git a/products/warehouse_sources_queue/backend/testing.py b/products/warehouse_sources_queue/backend/testing.py
index 2d6c78f84caf..ba732f8320c8 100644
--- a/products/warehouse_sources_queue/backend/testing.py
+++ b/products/warehouse_sources_queue/backend/testing.py
@@ -20,6 +20,10 @@ from products.warehouse_sources_queue.backend.core.jobs_db import (
STATUS_VIEW,
BatchQueue,
)
+from products.warehouse_sources_queue.backend.core.scheduler_state import (
+ SCHEDULER_DECISION_TABLE,
+ SCHEDULER_STATE_TABLE,
+)
def get_test_database_url() -> str:
@@ -224,3 +228,42 @@ JOB_DEFAULTS: dict[str, Any] = {
"team_id": 1,
"payload": {},
}
+
+
+def ensure_scheduler_tables(conn: psycopg.Connection[Any]) -> None:
+ conn.execute(f"""
+ CREATE TABLE IF NOT EXISTS {SCHEDULER_STATE_TABLE} (
+ id BIGSERIAL PRIMARY KEY,
+ kind VARCHAR(100) NOT NULL,
+ schedule_key VARCHAR(200) NOT NULL,
+ team_id BIGINT NOT NULL,
+ interval_seconds BIGINT NOT NULL,
+ offset_seconds INT NOT NULL,
+ next_due_at TIMESTAMPTZ NOT NULL,
+ refreshed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CONSTRAINT qss_kind_key_uniq UNIQUE (kind, schedule_key)
+ )
+ """)
+ conn.execute(f"CREATE INDEX IF NOT EXISTS qss_next_due_idx ON {SCHEDULER_STATE_TABLE} (next_due_at)")
+ conn.execute(f"CREATE INDEX IF NOT EXISTS qss_refreshed_idx ON {SCHEDULER_STATE_TABLE} (refreshed_at)")
+ conn.execute(f"""
+ CREATE TABLE IF NOT EXISTS {SCHEDULER_DECISION_TABLE} (
+ id BIGSERIAL PRIMARY KEY,
+ team_id BIGINT NOT NULL,
+ kind VARCHAR(100) NOT NULL,
+ schedule_key VARCHAR(200) NOT NULL,
+ window_boundary TIMESTAMPTZ NOT NULL,
+ due_at TIMESTAMPTZ NOT NULL,
+ decision VARCHAR(32) NOT NULL,
+ interval_seconds BIGINT NOT NULL,
+ late_seconds DOUBLE PRECISION NOT NULL,
+ observed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CONSTRAINT qsd_kind_key_due_uniq UNIQUE (kind, schedule_key, due_at)
+ )
+ """)
+ conn.execute(f"CREATE INDEX IF NOT EXISTS qsd_observed_at_idx ON {SCHEDULER_DECISION_TABLE} (observed_at)")
+
+
+def truncate_scheduler_tables(conn: psycopg.Connection[Any]) -> None:
+ conn.execute(f"TRUNCATE {SCHEDULER_DECISION_TABLE}, {SCHEDULER_STATE_TABLE} RESTART IDENTITY CASCADE")
diff --git a/products/warehouse_sources_queue/backend/tests/test_scheduler_state.py b/products/warehouse_sources_queue/backend/tests/test_scheduler_state.py
new file mode 100644
index 000000000000..a0f141f6da1d
--- /dev/null
+++ b/products/warehouse_sources_queue/backend/tests/test_scheduler_state.py
@@ -0,0 +1,193 @@
+from datetime import UTC, datetime, timedelta
+from typing import Any
+from uuid import uuid4
+
+import pytest
+
+import psycopg
+from psycopg.rows import dict_row
+
+from products.warehouse_sources_queue.backend.core.generic_jobs import JOB_LEASE_TABLE, JobsTable
+from products.warehouse_sources_queue.backend.core.scheduler_state import (
+ SCHEDULER_STATE_TABLE,
+ DecisionRecord,
+ DueSchedule,
+ SchedulerStateTable,
+)
+from products.warehouse_sources_queue.backend.testing import (
+ ensure_generic_job_tables,
+ ensure_scheduler_tables,
+ get_test_database_url,
+ truncate_generic_job_tables,
+ truncate_scheduler_tables,
+)
+
+OWNER_A = str(uuid4())
+OWNER_B = str(uuid4())
+
+INTERVAL = 21600
+KIND = "test.kind"
+
+
+def _state(
+ schedule_key: str, *, kind: str = KIND, due_in_seconds: float, interval: int = INTERVAL, offset: int = 0
+) -> DueSchedule:
+ return DueSchedule(
+ kind=kind,
+ schedule_key=schedule_key,
+ team_id=1,
+ interval_seconds=interval,
+ offset_seconds=offset,
+ next_due_at=datetime.now(UTC) + timedelta(seconds=due_in_seconds),
+ )
+
+
+def _decision(
+ schedule_key: str,
+ window_boundary: datetime,
+ decision: str = "would_fire",
+ *,
+ kind: str = KIND,
+ due_at: datetime | None = None,
+) -> DecisionRecord:
+ return DecisionRecord(
+ team_id=1,
+ kind=kind,
+ schedule_key=schedule_key,
+ window_boundary=window_boundary,
+ due_at=due_at or window_boundary,
+ decision=decision,
+ interval_seconds=INTERVAL,
+ late_seconds=1.0,
+ )
+
+
+async def _fetch_states(conn: psycopg.AsyncConnection[Any]) -> dict[tuple[str, str], dict[str, Any]]:
+ async with conn.cursor(row_factory=dict_row) as cur:
+ await cur.execute(f"SELECT * FROM {SCHEDULER_STATE_TABLE}")
+ return {(row["kind"], row["schedule_key"]): row for row in await cur.fetchall()}
+
+
[email protected](scope="session")
+def _db_url() -> str:
+ return get_test_database_url()
+
+
[email protected](scope="session", autouse=True)
+def _create_tables(_db_url: str) -> None:
+ with psycopg.Connection.connect(_db_url, autocommit=True) as conn:
+ ensure_scheduler_tables(conn)
+ ensure_generic_job_tables(conn)
+
+
[email protected](autouse=True)
+def _clean_tables(_db_url: str) -> None:
+ with psycopg.Connection.connect(_db_url, autocommit=True) as conn:
+ truncate_scheduler_tables(conn)
+ truncate_generic_job_tables(conn)
+
+
+async def conn(_db_url: str):
+ async with await psycopg.AsyncConnection.connect(_db_url, autocommit=True) as c:
+ yield c
+
+
[email protected]_db(transaction=True)
+class TestSchedulerState:
+ @pytest.mark.asyncio
+ async def test_claim_due_returns_only_due_rows_and_advances_them(self, conn):
+ await SchedulerStateTable.upsert_states(
+ conn,
+ [_state("due-schedule", due_in_seconds=-60), _state("future-schedule", due_in_seconds=3600)],
+ )
+
+ async with conn.transaction():
+ due = await SchedulerStateTable.claim_due(conn, kind=KIND, limit=10)
+ assert [row.schedule_key for row in due] == ["due-schedule"]
+ await SchedulerStateTable.advance_states(
+ conn, [(row, datetime.now(UTC) + timedelta(seconds=INTERVAL)) for row in due]
+ )
+
+ async with conn.transaction():
+ assert await SchedulerStateTable.claim_due(conn, kind=KIND, limit=10) == []
+
+ @pytest.mark.asyncio
+ async def test_decision_insert_dedups_on_kind_key_and_due_time(self, conn):
+ boundary = datetime(2026, 8, 31, 12, 0, tzinfo=UTC)
+ first = _decision("s1", boundary)
+
+ assert await SchedulerStateTable.insert_decisions(conn, [first]) == ([first], 0)
+ # The same due time again (a duplicate tick) is refused; a skip decision
+ # must not overwrite the recorded one either.
+ assert await SchedulerStateTable.insert_decisions(
+ conn, [_decision("s1", boundary, decision="skip_overlap")]
+ ) == ([], 1)
+
+ recadenced = _decision("s1", boundary, due_at=boundary + timedelta(minutes=30))
+ other_schedule = _decision("s2", boundary)
+ assert await SchedulerStateTable.insert_decisions(conn, [recadenced, other_schedule]) == (
+ [recadenced, other_schedule],
+ 0,
+ )
+ other_kind = _decision("s1", boundary, kind="other.kind")
+ assert await SchedulerStateTable.insert_decisions(conn, [other_kind]) == ([other_kind], 0)
+
+ @pytest.mark.asyncio
+ async def test_state_operations_are_scoped_to_kind(self, conn):
+ first = _state("shared", due_in_seconds=-60)
+ second = _state("shared", kind="other.kind", due_in_seconds=-60)
+ await SchedulerStateTable.upsert_states(conn, [first, second])
+
+ assert set(await _fetch_states(conn)) == {(KIND, "shared"), ("other.kind", "shared")}
+ async with conn.transaction():
+ assert await SchedulerStateTable.claim_due(conn, kind=KIND, limit=10) == [first]
+ assert await SchedulerStateTable.delete_states(conn, KIND, ["shared"]) == 1
+ assert set(await _fetch_states(conn)) == {("other.kind", "shared")}
+
+ @pytest.mark.asyncio
+ async def test_upsert_preserves_next_due_at_unless_cadence_changed(self, conn):
+ first = _state("s1", due_in_seconds=600)
+ await SchedulerStateTable.upsert_states(conn, [first])
+
+ await SchedulerStateTable.upsert_states(conn, [_state("s1", due_in_seconds=9999)])
+ states = await _fetch_states(conn)
+ assert states[(KIND, "s1")]["next_due_at"] == first.next_due_at
+
+ recadenced = _state("s1", due_in_seconds=120, interval=3600, offset=60)
+ await SchedulerStateTable.upsert_states(conn, [recadenced])
+ states = await _fetch_states(conn)
+ assert states[(KIND, "s1")]["next_due_at"] == recadenced.next_due_at
+ assert states[(KIND, "s1")]["interval_seconds"] == 3600
+ assert states[(KIND, "s1")]["offset_seconds"] == 60
+
+ @pytest.mark.asyncio
+ async def test_stale_state_rows_deleted_after_refresh_cutoff(self, conn):
+ await SchedulerStateTable.upsert_states(
+ conn, [_state("kept", due_in_seconds=600), _state("stale", due_in_seconds=600)]
+ )
+ async with conn.cursor() as cur:
+ await cur.execute("SELECT now()")
+ row = await cur.fetchone()
+ assert row is not None
+ cutoff = row[0]
+ await SchedulerStateTable.upsert_states(conn, [_state("kept", due_in_seconds=600)])
+
+ assert await SchedulerStateTable.delete_states_not_refreshed_since(conn, KIND, cutoff) == 1
+ assert set(await _fetch_states(conn)) == {(KIND, "kept")}
+
+ @pytest.mark.asyncio
+ async def test_sentinel_slot_single_flights_within_ttl(self, conn):
+ async def acquire(owner: str) -> bool:
+ return await JobsTable.try_acquire_sentinel_slot(
+ conn, lane="scheduler", group_key="tick-slot", owner_token=owner, ttl_seconds=60.0
+ )
+
+ assert await acquire(OWNER_A) is True
+ # No same-owner re-entrancy: the TTL is the fleet cadence.
+ assert await acquire(OWNER_A) is False
+ assert await acquire(OWNER_B) is False
+
+ async with conn.cursor() as cur:
+ await cur.execute(f"UPDATE {JOB_LEASE_TABLE} SET expires_at = now() - interval '1 second'")
+ assert await acquire(OWNER_B) is True