Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(data-warehouse): stop counting pre-window jobs in the shadow report (#112537)

Tom Owers43dcf14070ed
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
index 89b2eadb09ef..1e1aba21a09f 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
@@ -1,3 +1,4 @@
+import time
from collections import Counter
from datetime import UTC, datetime, timedelta
@@ -68,15 +69,23 @@ class Command(BaseCommand):
since = datetime.now(UTC) - timedelta(hours=options["hours"])
tolerance = timedelta(seconds=options["tolerance_seconds"])
+ self.stderr.write(f"window since {since.isoformat()} (tolerance {tolerance})")
+
+ self.stderr.write("fetching decisions...")
+ started_at = time.monotonic()
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"]]
+ self.stderr.write(f"fetched {len(decisions)} decisions in {time.monotonic() - started_at:.1f}s")
+ self.stderr.write("fetching jobs...")
+ started_at = time.monotonic()
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"))
+ 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.
unmatched: dict[str, list[datetime]] = {}
@@ -86,22 +95,28 @@ class Command(BaseCommand):
matched = 0
temporal_only: list[str] = []
adhoc = 0
- for schema_uuid, workflow_id in jobs:
+ started_at = time.monotonic()
+ for job_index, (schema_uuid, workflow_id) in enumerate(jobs, start=1):
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)
+ 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
+ elif fired_at >= since:
+ # Pre-window jobs have no decision window to match.
+ temporal_only.append(schema_id)
+
+ if job_index % 25000 == 0:
+ self.stderr.write(f"matching: {job_index}/{len(jobs)} jobs")
+
+ 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]
diff --git a/products/warehouse_sources/backend/tests/test_scheduler_shadow.py b/products/warehouse_sources/backend/tests/test_scheduler_shadow.py
index 75d0d959d822..5a6b79fd69fb 100644
--- a/products/warehouse_sources/backend/tests/test_scheduler_shadow.py
+++ b/products/warehouse_sources/backend/tests/test_scheduler_shadow.py
@@ -520,6 +520,75 @@ def _free_port() -> int:
@pytest.mark.django_db
class TestShadowReport:
+ @pytest.mark.parametrize(
+ "fired_offset_minutes,due_offset_minutes,expected_matched,expected_temporal_only",
+ [
+ pytest.param(-10, 5, 1, 0, id="pre_window_job_matches"),
+ pytest.param(-10, None, 0, 0, id="unmatched_pre_window_job"),
+ pytest.param(10, None, 0, 1, id="unmatched_in_window_job"),
+ ],
+ )
+ def test_report_counts_jobs_at_window_start(
+ self, team, monkeypatch, fired_offset_minutes, due_offset_minutes, expected_matched, expected_temporal_only
+ ):
+ 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)
+ since = (datetime.now(UTC) - timedelta(hours=2)).replace(microsecond=0)
+ if due_offset_minutes is not None:
+ due_at = since + timedelta(minutes=due_offset_minutes)
+ 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},
+ )
+
+ fired_at = since + timedelta(minutes=fired_offset_minutes)
+ ExternalDataJob.objects.create(
+ team=team,
+ pipeline=source,
+ schema=schema,
+ status="Running",
+ workflow_id=f"{schema.id}-{fired_at.isoformat()}",
+ )
+
+ out = io.StringIO()
+ err = io.StringIO()
+ call_command(
+ "report_warehouse_scheduler_shadow",
+ "--since",
+ since.isoformat(),
+ "--team-id",
+ str(team.pk),
+ stdout=out,
+ stderr=err,
+ )
+
+ output = out.getvalue()
+ decision_count = int(due_offset_minutes is not None)
+ assert f"matched: {expected_matched}" in output
+ assert "shadow_only (shadow would fire, no job): 0" in output
+ assert f"temporal_only (schedule-fired job, no decision): {expected_temporal_only}" in output
+ stderr = err.getvalue().splitlines()
+ assert "fetching decisions..." in stderr
+ assert any(line.startswith(f"fetched {decision_count} decisions in ") for line in stderr)
+ assert "fetching jobs..." in stderr
+ assert any(line.startswith("fetched 1 jobs in ") for line in stderr)
+ assert any(line.startswith("matching: done in ") for line in stderr)
+
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: