: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
feat(data-warehouse): add overlap policies to the queue scheduler (#116088)
Tom Owersf1e79ba5f436
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.pyindex 1e1aba21a09f..3dacb9620eb6 100644--- a/products/warehouse_sources/backend/management/commands/report_warehouse_scheduler_shadow.py+++ b/products/warehouse_sources/backend/management/commands/report_warehouse_scheduler_shadow.py@@ -3,6 +3,7 @@ from collections import Counterfrom datetime import UTC, datetime, timedeltafrom django.core.management.base import BaseCommand, CommandError+from django.db.models import Qimport psycopg@@ -13,6 +14,10 @@ from products.warehouse_sources.backend.scheduling.shadow import SYNC_EXTRACT_KIfrom products.warehouse_sources_queue.backend.sdk import SchedulerStateTableTOP_OFFENDERS = 10+# A job older than this at the due time is treated as an orphaned RUNNING row,+# not as a run that Temporal's SKIP overlap policy waited for.+TEMPORAL_OVERLAP_MAX_JOB_AGE = timedelta(days=7)+EARLIER_JOBS_CHUNK_SIZE = 1000def parse_schedule_fired_at(schema_id: str, workflow_id: str | None) -> datetime | None:@@ -33,6 +38,17 @@ def parse_schedule_fired_at(schema_id: str, workflow_id: str | None) -> datetimereturn fired_at+def was_in_progress_at(+ due_at: datetime, intervals: list[tuple[datetime, datetime | None]], max_job_age: timedelta+) -> bool:+ """True when a job (created_at, finished_at) was in progress at ``due_at`` and+ was created no more than ``max_job_age`` before it."""+ return any(+ due_at - max_job_age <= created_at < due_at and (finished_at is None or finished_at > due_at)+ for created_at, finished_at in intervals+ )++def _print_offenders(stdout, label: str, schema_ids: list[str]) -> None:if not schema_ids:return@@ -81,10 +97,11 @@ class Command(BaseCommand):self.stderr.write("fetching jobs...")started_at = time.monotonic()- jobs_qs = ExternalDataJob.objects.filter(created_at__gte=since - tolerance, schema_id__isnull=False)+ match_start = since - tolerance+ jobs_qs = ExternalDataJob.objects.filter(created_at__gte=match_start, 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"))+ jobs = list(jobs_qs.values_list("schema_id", "workflow_id", "created_at", "finished_at"))self.stderr.write(f"fetched {len(jobs)} jobs in {time.monotonic() - started_at:.1f}s")# One-to-one greedy matching per schema, nearest job time to due time first.@@ -95,9 +112,11 @@ class Command(BaseCommand):matched = 0temporal_only: list[str] = []adhoc = 0+ job_intervals: dict[str, list[tuple[datetime, datetime | None]]] = {}started_at = time.monotonic()- for job_index, (schema_uuid, workflow_id) in enumerate(jobs, start=1):+ for job_index, (schema_uuid, workflow_id, created_at, finished_at) in enumerate(jobs, start=1):schema_id = str(schema_uuid)+ job_intervals.setdefault(schema_id, []).append((created_at, finished_at))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@@ -118,13 +137,44 @@ class Command(BaseCommand):self.stderr.write(f"matching: done in {time.monotonic() - started_at:.1f}s")- shadow_only = [schema_id for schema_id, dues in unmatched.items() for _ in dues]+ # A long run can start before the matching window and still block a due+ # time inside it. Fetch those older runs only for the schemas that still+ # have unmatched decisions, so the report never reads days of jobs.+ unmatched_schema_ids = [schema_id for schema_id, dues in unmatched.items() if dues]+ self.stderr.write(f"fetching earlier unfinished jobs for {len(unmatched_schema_ids)} schemas...")+ started_at = time.monotonic()+ for chunk_start in range(0, len(unmatched_schema_ids), EARLIER_JOBS_CHUNK_SIZE):+ earlier_jobs = ExternalDataJob.objects.filter(+ Q(finished_at__isnull=True) | Q(finished_at__gt=since),+ schema_id__in=unmatched_schema_ids[chunk_start : chunk_start + EARLIER_JOBS_CHUNK_SIZE],+ created_at__gte=since - TEMPORAL_OVERLAP_MAX_JOB_AGE,+ created_at__lt=match_start,+ ).values_list("schema_id", "created_at", "finished_at")+ for schema_uuid, created_at, finished_at in earlier_jobs:+ job_intervals.setdefault(str(schema_uuid), []).append((created_at, finished_at))+ self.stderr.write(f"fetched earlier unfinished jobs in {time.monotonic() - started_at:.1f}s")++ # The shadow scheduler decides overlap from its own queue, which holds no+ # sync jobs in shadow mode, so it would fire windows that Temporal+ # skipped because the previous run was still in progress.+ shadow_only: list[str] = []+ temporal_overlap_skip: list[str] = []+ for schema_id, dues in unmatched.items():+ for due_at in dues:+ if was_in_progress_at(due_at, job_intervals.get(schema_id, []), TEMPORAL_OVERLAP_MAX_JOB_AGE):+ temporal_overlap_skip.append(schema_id)+ else:+ shadow_only.append(schema_id)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_overlap_skip (shadow would fire, Temporal run still in progress): {len(temporal_overlap_skip)}"+ )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_overlap_skip", temporal_overlap_skip)_print_offenders(self.stdout, "temporal_only", temporal_only)diff --git a/products/warehouse_sources/backend/scheduling/runner.py b/products/warehouse_sources/backend/scheduling/runner.pyindex 370545559d33..836fe8c37b08 100644--- a/products/warehouse_sources/backend/scheduling/runner.py+++ b/products/warehouse_sources/backend/scheduling/runner.py@@ -211,7 +211,7 @@ class ShadowScheduler: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)+ result = await evaluate_due(conn, due, now_epoch)inserted_records, refused = await SchedulerStateTable.insert_decisions(conn, list(result.records))advances = []diff --git a/products/warehouse_sources/backend/scheduling/shadow.py b/products/warehouse_sources/backend/scheduling/shadow.pyindex 5c63ac7b4a39..9a7754e74ad6 100644--- a/products/warehouse_sources/backend/scheduling/shadow.py+++ b/products/warehouse_sources/backend/scheduling/shadow.py@@ -11,6 +11,13 @@ A schema is in scope for scheduling when all of these hold:its state row and gets a ``skip_cdc_halted`` decision at fire time, so theshadow report can show what Temporal's SKIP overlap policy hides.+Overlap is decided from the queue's own job state, never from+``ExternalDataJob`` rows: a run that dies without a status update can leave its+row in RUNNING, and that row must not block the schedule. Each scheduled kind+declares its queue lane and its ``OverlapPolicy``; ``sync.extract`` uses+``SKIP``, as the Temporal schedules do. A ``skip_overlap`` decision means the+policy refused the window because of the schema's live queue jobs.+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,@@ -22,17 +29,28 @@ from __future__ import annotationsimport randomfrom datetime import UTC, datetime, time, timedelta+from typing import Any++import psycopgfrom posthog.dataclasses import frozenfrom 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+from products.warehouse_sources.backend.models import ExternalDataSchema, ExternalDataSource+from products.warehouse_sources_queue.backend.sdk import (+ DecisionRecord,+ DueSchedule,+ GroupJobState,+ JobsTable,+ OverlapPolicy,+ overlap_allows,+)SCHEDULER_LANE = "scheduler"TICK_SLOT_KEY = "tick-slot"REFRESH_SLOT_KEY = "refresh-slot"SYNC_EXTRACT_KIND = "sync.extract"+SYNC_EXTRACT_LANE = "extract"DECISION_WOULD_FIRE = "would_fire"DECISION_SKIP_OVERLAP = "skip_overlap"@@ -46,6 +64,24 @@ SKIP_REASONS = {}+@frozen+class ScheduledKind:+ """How the scheduler enqueues one kind: its queue lane and overlap policy."""++ lane: str+ overlap_policy: OverlapPolicy+++SCHEDULED_KINDS: dict[str, ScheduledKind] = {+ SYNC_EXTRACT_KIND: ScheduledKind(lane=SYNC_EXTRACT_LANE, overlap_policy=OverlapPolicy.SKIP),+}+++def queue_group_key(team_id: int, schema_id: str) -> str:+ """The queue group of a schema: one run of a schema executes at a time."""+ return f"{team_id}:{schema_id}"++@frozenclass SchemaCadence:interval_seconds: int@@ -162,16 +198,28 @@ def _fetch_due_scope(schema_ids: list[str]) -> dict[str, dict | None]: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 _fetch_group_job_states(+ conn: psycopg.AsyncConnection[Any], due: list[DueSchedule]+) -> dict[DueSchedule, GroupJobState]:+ """Live queue-job state per due row. One query per kind."""+ states: dict[DueSchedule, GroupJobState] = {}+ for kind in sorted({row.kind for row in due}):+ rows = [row for row in due if row.kind == kind]+ by_group = await JobsTable.get_group_job_states(+ conn,+ kind=kind,+ lane=SCHEDULED_KINDS[kind].lane,+ group_keys=[queue_group_key(row.team_id, row.schedule_key) for row in rows],+ )+ for row in rows:+ states[row] = by_group[queue_group_key(row.team_id, row.schedule_key)]+ return states-async def evaluate_due(due: list[DueSchedule], now_epoch: int) -> EvaluationResult:+async def evaluate_due(conn: psycopg.AsyncConnection[Any], due: list[DueSchedule], now_epoch: int) -> EvaluationResult:"""Decide, per due schema, what a real scheduler would have done.+ ``conn`` is a connection to the queue database, where the job tables live.Records exactly one decision per schema, for the latest window only: a ticklate by several intervals counts the earlier windows on the missed-windowsmetric rather than back-filling decisions Temporal never took either (its@@ -182,7 +230,7 @@ async def evaluate_due(due: list[DueSchedule], now_epoch: int) -> EvaluationResudue_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)+ group_states = await _fetch_group_job_states(conn, due)records: list[DecisionRecord] = []missed_windows = 0@@ -192,17 +240,11 @@ async def evaluate_due(due: list[DueSchedule], now_epoch: int) -> EvaluationResustored_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- )+ overlap_allowed = overlap_allows(SCHEDULED_KINDS[row.kind].overlap_policy, group_states[row])if row.schedule_key not in scope_config:decision = DECISION_SKIP_OUT_OF_SCOPE- elif had_running_job_at_boundary:+ elif not overlap_allowed:decision = DECISION_SKIP_OVERLAPelif cdc_halted_from_config(scope_config[row.schedule_key]):decision = DECISION_SKIP_CDC_HALTEDdiff --git a/products/warehouse_sources/backend/tests/test_scheduler_shadow.py b/products/warehouse_sources/backend/tests/test_scheduler_shadow.pyindex 5a6b79fd69fb..81fa57803e78 100644--- a/products/warehouse_sources/backend/tests/test_scheduler_shadow.py+++ b/products/warehouse_sources/backend/tests/test_scheduler_shadow.py@@ -36,12 +36,14 @@ from products.warehouse_sources.backend.scheduling.shadow import (DECISION_SKIP_OVERLAP,DECISION_WOULD_FIRE,SYNC_EXTRACT_KIND,+ SYNC_EXTRACT_LANE,EvaluationResult,SchemaCadence,evaluate_due,fetch_in_scope_schema_page,latest_fire_at,next_due_after,+ queue_group_key,schedule_offset,window_boundary,)@@ -51,8 +53,13 @@ from products.warehouse_sources_queue.backend.core.scheduler_state import (DecisionRecord,SchedulerStateTable,)-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+from products.warehouse_sources_queue.backend.sdk import DueSchedule, HealthState, JobsTable, start_health_server+from products.warehouse_sources_queue.backend.testing import (+ ensure_generic_job_tables,+ ensure_scheduler_tables,+ get_test_database_url,+ truncate_generic_job_tables,+)# 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@@ -205,33 +212,64 @@ def _due_row(schema_id: str, team_id: int, now_epoch: int) -> DueSchedule:)+def _reset_queue_jobs() -> str:+ db_url = get_test_database_url()+ with psycopg.Connection.connect(db_url, autocommit=True) as conn:+ ensure_generic_job_tables(conn)+ truncate_generic_job_tables(conn)+ return db_url+++def _evaluate(db_url: str, due: list[DueSchedule], now_epoch: int) -> EvaluationResult:+ async def run() -> EvaluationResult:+ async with await psycopg.AsyncConnection.connect(db_url, autocommit=True) as conn:+ return await evaluate_due(conn, due, now_epoch)++ return async_to_sync(run)()+++def _seed_extract_job(db_url: str, team_id: int, schema_id: str, state: str) -> None:+ async def run() -> None:+ async with await psycopg.AsyncConnection.connect(db_url, autocommit=True) as conn:+ job_id = await JobsTable.insert(+ conn,+ kind=SYNC_EXTRACT_KIND,+ lane=SYNC_EXTRACT_LANE,+ group_key=queue_group_key(team_id, schema_id),+ team_id=team_id,+ payload={},+ )+ assert job_id is not None+ if state != "pending":+ await JobsTable.update_status(conn, job_id=job_id, job_state=state)++ async_to_sync(run)()++@pytest.mark.django_db(transaction=True)class TestEvaluateDue:@pytest.mark.parametrize(- "job_status,sync_type_config,expected_decision",+ "queue_job_state,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("executing", {}, DECISION_SKIP_OVERLAP, id="running_queue_job_overlaps"),+ pytest.param("pending", {}, DECISION_SKIP_OVERLAP, id="pending_queue_job_overlaps"),+ pytest.param("waiting_retry", {}, DECISION_SKIP_OVERLAP, id="retrying_queue_job_overlaps"),+ pytest.param("succeeded", {}, DECISION_WOULD_FIRE, id="succeeded_queue_job_fires"),+ pytest.param("failed", {}, DECISION_WOULD_FIRE, id="failed_queue_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):+ def test_skip_reasons(self, team, queue_job_state, sync_type_config, expected_decision):+ db_url = _reset_queue_jobs()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))+ if queue_job_state is not None:+ _seed_extract_job(db_url, team.pk, str(schema.id), queue_job_state)- result = async_to_sync(evaluate_due)([_due_row(str(schema.id), team.pk, now_epoch)], now_epoch)+ result = _evaluate(db_url, [_due_row(str(schema.id), team.pk, now_epoch)], now_epoch)assert len(result.records) == 1record = result.records[0]@@ -241,7 +279,15 @@ class TestEvaluateDue:)assert result.missed_windows == 0- def test_current_boundary_temporal_job_is_not_an_overlap(self, team):+ @pytest.mark.parametrize(+ "created_before_due",+ [+ pytest.param(timedelta(seconds=1), id="just_before_boundary"),+ pytest.param(timedelta(days=120), id="orphaned_months_ago"),+ ],+ )+ def test_running_external_data_job_does_not_overlap(self, team, created_before_due):+ db_url = _reset_queue_jobs()source = _create_source(team)schema = _create_schema(team, source)now_epoch = int(time.time())@@ -249,15 +295,35 @@ class TestEvaluateDue: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)+ ExternalDataJob.objects.filter(pk=job.pk).update(created_at=due_at - created_before_due)- result = async_to_sync(evaluate_due)([_due_row(str(schema.id), team.pk, now_epoch)], now_epoch)+ result = _evaluate(db_url, [_due_row(str(schema.id), team.pk, now_epoch)], now_epoch)assert [record.decision for record in result.records] == [DECISION_WOULD_FIRE]+ def test_overlap_is_decided_per_schema(self, team):+ db_url = _reset_queue_jobs()+ source = _create_source(team)+ busy = _create_schema(team, source, name="busy")+ idle = _create_schema(team, source, name="idle")+ _seed_extract_job(db_url, team.pk, str(busy.id), "executing")+ now_epoch = int(time.time())++ result = _evaluate(+ db_url,+ [_due_row(str(busy.id), team.pk, now_epoch), _due_row(str(idle.id), team.pk, now_epoch)],+ now_epoch,+ )++ assert {record.schedule_key: record.decision for record in result.records} == {+ str(busy.id): DECISION_SKIP_OVERLAP,+ str(idle.id): DECISION_WOULD_FIRE,+ }+def test_unknown_schema_is_out_of_scope(self, team):+ db_url = _reset_queue_jobs()now_epoch = int(time.time())- result = async_to_sync(evaluate_due)([_due_row(str(uuid.uuid4()), team.pk, now_epoch)], now_epoch)+ result = _evaluate(db_url, [_due_row(str(uuid.uuid4()), team.pk, now_epoch)], now_epoch)assert [record.decision for record in result.records] == [DECISION_SKIP_OUT_OF_SCOPE]@@ -268,7 +334,9 @@ class TestShadowSchedulerTick: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)+ ensure_generic_job_tables(conn)conn.execute(f"TRUNCATE {SCHEDULER_DECISION_TABLE}, {SCHEDULER_STATE_TABLE}")+ truncate_generic_job_tables(conn)for schema_id in schema_ids:conn.execute(f"""@@ -682,6 +750,63 @@ class TestShadowReport:assert "temporal_only (schedule-fired job, no decision): 0" in outputassert "adhoc (manual/backfill runs, excluded): 1" in output+ @pytest.mark.parametrize(+ "created_before_due,finished_after_due,expected_overlap_skip",+ [+ pytest.param(timedelta(hours=1), None, 1, id="unfinished_run"),+ pytest.param(timedelta(hours=1), timedelta(minutes=5), 1, id="run_finished_after_due"),+ pytest.param(timedelta(hours=1), timedelta(minutes=-5), 0, id="run_finished_before_due"),+ pytest.param(timedelta(days=3), None, 1, id="long_run_started_before_window"),+ pytest.param(timedelta(days=8), None, 0, id="orphan_older_than_seven_days"),+ ],+ )+ def test_report_separates_temporal_overlap_skips(+ self, team, monkeypatch, created_before_due, finished_after_due, expected_overlap_skip+ ):+ 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},+ )+ created_at = due_at - created_before_due+ job = ExternalDataJob.objects.create(+ team=team,+ pipeline=source,+ schema=schema,+ status="Running" if finished_after_due is None else "Completed",+ workflow_id=f"{schema.id}-{created_at.isoformat()}",+ finished_at=None if finished_after_due is None else due_at + finished_after_due,+ )+ ExternalDataJob.objects.filter(pk=job.pk).update(created_at=created_at)++ 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 f"shadow_only (shadow would fire, no job): {1 - expected_overlap_skip}" in output+ assert (+ f"temporal_overlap_skip (shadow would fire, Temporal run still in progress): {expected_overlap_skip}"+ in output+ )+@pytest.mark.parametrize("workflow_id,expected",[diff --git a/products/warehouse_sources_queue/backend/README.md b/products/warehouse_sources_queue/backend/README.mdindex 8c670b5b80a1..206b817eb88c 100644--- a/products/warehouse_sources_queue/backend/README.md+++ b/products/warehouse_sources_queue/backend/README.md@@ -170,6 +170,18 @@ For ad-hoc inspection (state summaries, active runs, leases, force-release), useFollowers 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.+An enqueuer can pass an `OverlapPolicy` to `JobsTable.insert`.+The policy decides if a new job can join a group that has live jobs of the same kind and lane:++- `SKIP` refuses the job while the group has a pending or running job.+- `BUFFER_ONE` refuses the job only while the group has a pending job. A running job does not block, because the new job waits behind it.++A job is pending when it is in `pending` state and no consumer has claimed it.+A job is running when it is `executing`, or `waiting_retry` for its next attempt.+Pending and `waiting_retry` jobs older than the claim eligibility window, terminal jobs, and superseded jobs are not live.+The policy guard is a `NOT EXISTS` in the insert statement, like the dedup guard, so it is atomic under one enqueuer.+`JobsTable.get_group_job_states` reads the same live state for many groups in one query, and `overlap_allows` applies a policy to it.+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)@@ -180,6 +192,9 @@ The warehouse scheduler uses `sync.extract` as its kind and the schema ID as itsSQL 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.+Each scheduled kind declares its queue lane and its overlap policy; `sync.extract` uses `SKIP` on lane `extract`.+The scheduler decides overlap from the live jobs in `queuejob`, never from `ExternalDataJob` rows.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.+It counts an unmatched decision as `temporal_overlap_skip`, not `shadow_only`, when a job for that schema was in progress at the due time and was created at most 7 days before it.diff --git a/products/warehouse_sources_queue/backend/core/generic_jobs.py b/products/warehouse_sources_queue/backend/core/generic_jobs.pyindex 9319d3122b15..a58c834ea295 100644--- a/products/warehouse_sources_queue/backend/core/generic_jobs.py+++ b/products/warehouse_sources_queue/backend/core/generic_jobs.py@@ -16,13 +16,15 @@ from __future__ import annotationsimport jsonfrom datetime import datetime-from typing import Any+from typing import Any, assert_neverimport psycopgfrom psycopg.rows import dict_rowfrom posthog.dataclasses import frozen+from products.warehouse_sources_queue.backend.core.overlap import GroupJobState, OverlapPolicy+JOB_TABLE = "queuejob"JOB_STATUS_TABLE = "queuejobstatus"JOB_LEASE_TABLE = "queuejoblease"@@ -193,31 +195,93 @@ _JOB_COLUMNS = ("j.payload, j.priority, j.dedup_key, j.latest_state, j.latest_attempt, j.state_changed_at, j.created_at")-# The insert's dedup guard. A partitioned table cannot enforce a unique index-# that omits the partition key, so live-pair uniqueness is a NOT EXISTS in the-# same statement: correct under one enqueuer per key (the scheduler is-# single-flighted; followers are enqueued by the single run finalizer), and a-# rare concurrent duplicate is bounded — both rows share the dedup_key, so the-# loser is observable and the handler contract stays idempotent.-_INSERT_SQL = f"""++# Live jobs, as the overlap policies see them. A job is live while the claim+# path or a consumer can still move it forward. The claim path ignores+# 'pending' and 'waiting_retry' rows older than the claim eligibility window,+# and the recovery sweep reads 'executing' rows inside the partition window.+# Terminal and superseded jobs are not live. A 'waiting' job is not live+# either, because the generic claim path never claims it. The state filters+# match the conditions of the claimable and group-busy partial indexes.+def _pending_job_predicate(alias: str) -> str:+ return (+ f"({alias}.latest_state = 'pending'"+ f" AND {alias}.created_at > now() - interval '{JOB_CLAIM_ELIGIBILITY_INTERVAL}')"+ )+++def _running_job_predicate(alias: str) -> str:+ return (+ f"({alias}.latest_state = 'executing'"+ f" OR ({alias}.latest_state = 'waiting_retry'"+ f" AND {alias}.created_at > now() - interval '{JOB_CLAIM_ELIGIBILITY_INTERVAL}'))"+ )+++def _live_job_predicate(alias: str) -> str:+ return f"({_pending_job_predicate(alias)} OR {_running_job_predicate(alias)})"+++def _overlap_blocking_predicate(policy: OverlapPolicy, alias: str) -> str:+ """The live jobs that make ``overlap_allows`` refuse a new job for ``policy``."""+ match policy:+ case OverlapPolicy.SKIP:+ return _live_job_predicate(alias)+ case OverlapPolicy.BUFFER_ONE:+ return _pending_job_predicate(alias)+ case _:+ assert_never(policy)+++def _insert_sql(overlap_policy: OverlapPolicy | None = None) -> str:+ """Single-job insert with the dedup guard and an optional overlap guard.++ A partitioned table cannot enforce a unique index that omits the partition+ key, so live-pair uniqueness is a NOT EXISTS in the same statement: correct+ under one enqueuer per key (the scheduler is single-flighted; followers are+ enqueued by the single run finalizer), and a rare concurrent duplicate is+ bounded — both rows share the dedup_key, so the loser is observable and the+ handler contract stays idempotent. The overlap guard has the same shape and+ the same single-enqueuer assumption: it refuses the insert while the+ group's live jobs of this kind block ``overlap_policy``.+ """+ overlap_guard = ""+ if overlap_policy is not None:+ overlap_guard = f"""+ AND NOT EXISTS (+ SELECT 1 FROM {JOB_TABLE} o+ WHERE o.kind = %(kind)s::varchar+ AND o.lane = %(lane)s::varchar+ AND o.group_key = %(group_key)s::varchar+ AND o.created_at > now() - interval '{JOB_PARTITION_PRUNING_INTERVAL}'+ AND NOT o.superseded+ AND {_overlap_blocking_predicate(overlap_policy, "o")}+ )"""+ return f"""INSERT INTO {JOB_TABLE} (id, kind, lane, group_key, team_id, run_id, sequence, payload,priority, dedup_key, created_at)SELECT- gen_random_uuid(), %(kind)s::varchar, %(lane)s, %(group_key)s, %(team_id)s, %(run_id)s,+ gen_random_uuid(), %(kind)s::varchar, %(lane)s::varchar, %(group_key)s::varchar, %(team_id)s, %(run_id)s,%(sequence)s, %(payload)s::jsonb, %(priority)s, %(dedup_key)s::varchar, now()- WHERE %(dedup_key)s::varchar IS NULL OR NOT EXISTS (- SELECT 1 FROM {JOB_TABLE} d- WHERE d.kind = %(kind)s::varchar- AND d.dedup_key = %(dedup_key)s::varchar- AND d.created_at > now() - interval '{JOB_PARTITION_PRUNING_INTERVAL}'- AND d.latest_state != 'failed'- AND NOT d.superseded- )+ WHERE (+ %(dedup_key)s::varchar IS NULL OR NOT EXISTS (+ SELECT 1 FROM {JOB_TABLE} d+ WHERE d.kind = %(kind)s::varchar+ AND d.dedup_key = %(dedup_key)s::varchar+ AND d.created_at > now() - interval '{JOB_PARTITION_PRUNING_INTERVAL}'+ AND d.latest_state != 'failed'+ AND NOT d.superseded+ )+ ){overlap_guard}RETURNING id"""++_INSERT_SQL = _insert_sql()+_INSERT_WITH_OVERLAP_SQL = {policy: _insert_sql(policy) for policy in OverlapPolicy}+_INSERT_MANY_SQL = f"""WITH raw AS (SELECT value, ordinality@@ -334,10 +398,16 @@ class JobsTable:sequence: int = 0,priority: int = 0,dedup_key: str | None = None,+ overlap_policy: OverlapPolicy | None = None,) -> str | None:- """Enqueue one job. Returns the new id, or None when the dedup guard refused it."""+ """Enqueue one job. Returns the new id, or None when a guard refused it.++ With ``overlap_policy`` set, the check against the group's live jobs of+ this kind and lane runs in the insert statement, so check and insert are+ atomic under one enqueuer.+ """cursor = await conn.execute(- _INSERT_SQL,+ _INSERT_SQL if overlap_policy is None else _INSERT_WITH_OVERLAP_SQL[overlap_policy],{"kind": kind,"lane": lane,@@ -382,6 +452,48 @@ class JobsTable:rows = await cursor.fetchall()return [str(row[0]) for row in rows]+ # -- reads (producer side) -----------------------------------------------++ @staticmethod+ async def get_group_job_states(+ conn: psycopg.AsyncConnection[Any],+ *,+ kind: str,+ lane: str,+ group_keys: list[str],+ ) -> dict[str, GroupJobState]:+ """Live-job state for each of ``group_keys`` in one query.++ Every requested key is in the result; a group with no live job of this+ kind and lane maps to an empty ``GroupJobState``.+ """+ if not group_keys:+ return {}+ async with conn.cursor() as cur:+ await cur.execute(+ f"""+ SELECT+ j.group_key,+ bool_or({_running_job_predicate("j")}) AS has_running,+ bool_or({_pending_job_predicate("j")}) AS has_pending+ FROM {JOB_TABLE} j+ WHERE j.kind = %(kind)s+ AND j.lane = %(lane)s+ AND j.group_key = ANY(%(group_keys)s)+ AND j.created_at > now() - interval '{JOB_PARTITION_PRUNING_INTERVAL}'+ AND NOT j.superseded+ AND {_live_job_predicate("j")}+ GROUP BY j.group_key+ """,+ {"kind": kind, "lane": lane, "group_keys": group_keys},+ )+ rows = await cur.fetchall()+ live = {+ str(group_key): GroupJobState(has_running=bool(has_running), has_pending=bool(has_pending))+ for group_key, has_running, has_pending in rows+ }+ return {group_key: live.get(group_key, GroupJobState()) for group_key in group_keys}+# -- reads (consumer side) -----------------------------------------------@staticmethoddiff --git a/products/warehouse_sources_queue/backend/core/overlap.py b/products/warehouse_sources_queue/backend/core/overlap.pynew file mode 100644index 000000000000..8dab7b1bc55e--- /dev/null+++ b/products/warehouse_sources_queue/backend/core/overlap.py@@ -0,0 +1,46 @@+"""Overlap policies: when a scheduled fire may enqueue a job for a group.++The queue serializes jobs per ``(lane, group_key)``, so two jobs of one group+never run at the same time. An overlap policy only decides whether a new job+may join the group while earlier jobs are still live. The two policies match+the Temporal schedule overlap policies of the same name under that+serialization. The SQL that reads the live state lives in ``generic_jobs.py``.+"""++from __future__ import annotations++from enum import StrEnum+from typing import assert_never++from posthog.dataclasses import frozen+++class OverlapPolicy(StrEnum):+ # Fire only when the group has no live job: none pending and none running.+ SKIP = "skip"+ # Fire when the group has no pending job. A running job does not block,+ # because the new job waits behind it. At most one job is buffered.+ BUFFER_ONE = "buffer_one"+++@frozen+class GroupJobState:+ """The live jobs of one group, as the overlap policies see them.++ ``has_pending``: a live job that no consumer has claimed yet.+ ``has_running``: a live job that a consumer claimed and has not finished,+ including one that waits for its next retry attempt.+ """++ has_running: bool = False+ has_pending: bool = False+++def overlap_allows(policy: OverlapPolicy, state: GroupJobState) -> bool:+ match policy:+ case OverlapPolicy.SKIP:+ return not state.has_running and not state.has_pending+ case OverlapPolicy.BUFFER_ONE:+ return not state.has_pending+ case _:+ assert_never(policy)diff --git a/products/warehouse_sources_queue/backend/sdk/__init__.py b/products/warehouse_sources_queue/backend/sdk/__init__.pyindex 58219ee3ddbd..57c970516120 100644--- a/products/warehouse_sources_queue/backend/sdk/__init__.py+++ b/products/warehouse_sources_queue/backend/sdk/__init__.py@@ -33,6 +33,7 @@ from products.warehouse_sources_queue.backend.core.metrics import (ConsumerMetrics,make_consumer_metrics,)+from products.warehouse_sources_queue.backend.core.overlap import GroupJobState, OverlapPolicy, overlap_allowsfrom products.warehouse_sources_queue.backend.core.scheduler_state import (DecisionRecord,DueSchedule,@@ -70,6 +71,7 @@ __all__ = ["Fail","FollowerSpec","GenericJobAdapter",+ "GroupJobState","HealthState","Job","JobConsumer",@@ -77,6 +79,7 @@ __all__ = ["JobHandler","JobsTable","Outcome",+ "OverlapPolicy","OwnershipLostError","PendingBatch","PermanentBatchApplyError",@@ -86,5 +89,6 @@ __all__ = ["Success","latest_status_lateral","make_consumer_metrics",+ "overlap_allows","start_health_server",]diff --git a/products/warehouse_sources_queue/backend/tests/test_generic_jobs.py b/products/warehouse_sources_queue/backend/tests/test_generic_jobs.pyindex ffe3023352ce..babc6027961a 100644--- a/products/warehouse_sources_queue/backend/tests/test_generic_jobs.py+++ b/products/warehouse_sources_queue/backend/tests/test_generic_jobs.py@@ -9,6 +9,7 @@ import psycopgfrom products.warehouse_sources_queue.backend.core.batch_consumer import BatchConsumerConfig, _group_by_keyfrom products.warehouse_sources_queue.backend.core.generic_jobs import JOB_LEASE_TABLE, JOB_TABLE, Job, JobsTablefrom products.warehouse_sources_queue.backend.core.jobs_db import PendingBatch+from products.warehouse_sources_queue.backend.core.overlap import GroupJobState, OverlapPolicy, overlap_allowsfrom products.warehouse_sources_queue.backend.sdk.jobs import (Fail,FollowerSpec,@@ -118,6 +119,134 @@ class TestEnqueueDedup:assert await JobsTable.get_claimable_count(conn, lane=LANE, kinds=[KIND]) == 2+ "policy,has_running,has_pending,expected",+ [+ pytest.param(OverlapPolicy.SKIP, False, False, True, id="skip_idle_group"),+ pytest.param(OverlapPolicy.SKIP, True, False, False, id="skip_running"),+ pytest.param(OverlapPolicy.SKIP, False, True, False, id="skip_pending"),+ pytest.param(OverlapPolicy.SKIP, True, True, False, id="skip_running_and_pending"),+ pytest.param(OverlapPolicy.BUFFER_ONE, False, False, True, id="buffer_one_idle_group"),+ pytest.param(OverlapPolicy.BUFFER_ONE, True, False, True, id="buffer_one_running_buffers"),+ pytest.param(OverlapPolicy.BUFFER_ONE, False, True, False, id="buffer_one_pending"),+ pytest.param(OverlapPolicy.BUFFER_ONE, True, True, False, id="buffer_one_running_and_pending"),+ ],+)+def test_overlap_allows(policy: OverlapPolicy, has_running: bool, has_pending: bool, expected: bool) -> None:+ assert overlap_allows(policy, GroupJobState(has_running=has_running, has_pending=has_pending)) is expected+++async def _seed_job(+ conn: psycopg.AsyncConnection[Any],+ *,+ state: str,+ superseded: bool = False,+ age: str | None = None,+ **overrides: Any,+) -> None:+ job_id = await _insert(conn, **overrides)+ if state != "pending":+ await JobsTable.update_status(conn, job_id=job_id, job_state=state, attempt=1)+ async with conn.cursor() as cur:+ await cur.execute(+ f"""+ UPDATE {JOB_TABLE}+ SET superseded = %(superseded)s,+ created_at = CASE WHEN %(age)s::interval IS NULL THEN created_at ELSE now() - %(age)s::interval END+ WHERE id = %(id)s+ """,+ {"superseded": superseded, "age": age, "id": job_id},+ )+++IDLE = GroupJobState()+RUNNING = GroupJobState(has_running=True)+PENDING = GroupJobState(has_pending=True)++[email protected]_db(transaction=True)+class TestOverlapPolicy:+ @pytest.mark.parametrize("policy", list(OverlapPolicy))+ @pytest.mark.parametrize(+ "seed,expected_state",+ [+ pytest.param(None, IDLE, id="no_job"),+ pytest.param({"state": "pending"}, PENDING, id="pending"),+ pytest.param({"state": "executing"}, RUNNING, id="executing"),+ pytest.param({"state": "waiting_retry"}, RUNNING, id="waiting_retry"),+ pytest.param({"state": "succeeded"}, IDLE, id="succeeded"),+ pytest.param({"state": "failed"}, IDLE, id="failed"),+ pytest.param({"state": "pending", "superseded": True}, IDLE, id="superseded_pending"),+ pytest.param({"state": "executing", "superseded": True}, IDLE, id="superseded_executing"),+ pytest.param({"state": "waiting"}, IDLE, id="waiting_is_never_claimed"),+ pytest.param({"state": "pending", "age": "7 days"}, IDLE, id="pending_past_claim_eligibility"),+ pytest.param({"state": "waiting_retry", "age": "7 days"}, IDLE, id="waiting_retry_past_claim_eligibility"),+ pytest.param({"state": "executing", "age": "7 days"}, RUNNING, id="executing_inside_partition_window"),+ pytest.param({"state": "executing", "age": "15 days"}, IDLE, id="executing_past_partition_window"),+ pytest.param({"state": "pending", "kind": "test.other"}, IDLE, id="other_kind"),+ pytest.param({"state": "pending", "lane": "other"}, IDLE, id="other_lane"),+ pytest.param({"state": "pending", "group_key": "1:group-2"}, IDLE, id="other_group"),+ ],+ )+ @pytest.mark.asyncio+ async def test_live_state_and_insert_guard_agree(+ self,+ conn: psycopg.AsyncConnection[Any],+ policy: OverlapPolicy,+ seed: dict[str, Any] | None,+ expected_state: GroupJobState,+ ) -> None:+ group_key = JOB_DEFAULTS["group_key"]+ if seed is not None:+ await _seed_job(conn, **seed)++ states = await JobsTable.get_group_job_states(conn, kind=KIND, lane=LANE, group_keys=[group_key, "1:absent"])+ assert states == {group_key: expected_state, "1:absent": IDLE}++ inserted = await _try_insert(conn, overlap_policy=policy)+ assert (inserted is not None) is overlap_allows(policy, expected_state)++ @pytest.mark.asyncio+ async def test_lookup_reads_many_groups_in_one_call(self, conn: psycopg.AsyncConnection[Any]) -> None:+ await _seed_job(conn, state="executing", group_key="1:a", dedup_key="a-running")+ await _seed_job(conn, state="pending", group_key="1:a", dedup_key="a-pending")+ await _seed_job(conn, state="pending", group_key="1:b", dedup_key="b-pending")+ await _seed_job(conn, state="succeeded", group_key="1:c", dedup_key="c-done")++ states = await JobsTable.get_group_job_states(conn, kind=KIND, lane=LANE, group_keys=["1:a", "1:b", "1:c"])++ assert states == {"1:a": GroupJobState(has_running=True, has_pending=True), "1:b": PENDING, "1:c": IDLE}++ @pytest.mark.parametrize(+ "policy,expected_jobs",+ [+ pytest.param(OverlapPolicy.SKIP, 1, id="skip_refuses_behind_running"),+ pytest.param(OverlapPolicy.BUFFER_ONE, 2, id="buffer_one_buffers_exactly_one"),+ ],+ )+ @pytest.mark.asyncio+ async def test_repeated_enqueue_behind_a_running_job(+ self, conn: psycopg.AsyncConnection[Any], policy: OverlapPolicy, expected_jobs: int+ ) -> None:+ await _seed_job(conn, state="executing")+ for _ in range(3):+ await _try_insert(conn, overlap_policy=policy)++ async with conn.cursor() as cur:+ await cur.execute(f"SELECT count(*) FROM {JOB_TABLE}")+ assert await cur.fetchone() == (expected_jobs,)++ @pytest.mark.parametrize("policy", list(OverlapPolicy))+ @pytest.mark.asyncio+ async def test_policy_insert_keeps_the_dedup_guard(+ self, conn: psycopg.AsyncConnection[Any], policy: OverlapPolicy+ ) -> None:+ await _seed_job(conn, state="succeeded", dedup_key="k1")++ assert await _try_insert(conn, dedup_key="k1", overlap_policy=policy) is None+ assert await _try_insert(conn, dedup_key="k2", overlap_policy=policy) is not None++@pytest.mark.django_db(transaction=True)class TestClaim:@pytest.mark.asyncio