: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): classify suspected OOMs from workload self-reports (#76654)
Daniel RC52d9b9e4ebeb
diff --git a/posthog/settings/data_warehouse.py b/posthog/settings/data_warehouse.pyindex 105db53b7093..b3dfd6238ffa 100644--- a/posthog/settings/data_warehouse.py+++ b/posthog/settings/data_warehouse.py@@ -79,6 +79,20 @@ DATA_WAREHOUSE_REPARTITION_OOM_WINDOW_DAYS = get_from_env("DATA_WAREHOUSE_REPARTITION_OOM_WINDOW_DAYS", 7, type_cast=int)+# Classification of a suspected OOM (see ExternalDataSchemaOOMEvent). Infrastructure takes+# down many unrelated schemas at once, so an occurrence sharing a window with at least this many+# distinct schemas across the fleet is attributed to infrastructure rather than to any one table.+# The window extends this far on EACH SIDE of the occurrence being judged (total span = 2x).+DATA_WAREHOUSE_OOM_INFRA_BURST_WINDOW_SECONDS = get_from_env(+ "DATA_WAREHOUSE_OOM_INFRA_BURST_WINDOW_SECONDS", 1800, type_cast=int+)+DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_SCHEMAS = get_from_env(+ "DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_SCHEMAS", 50, type_cast=int+)+# A burst must also span this many distinct teams: one tenant's source outage kills all of that+# tenant's schemas at once, which is not infrastructure and must not suppress other tenants' counting.+DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_TEAMS = get_from_env("DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_TEAMS", 10, type_cast=int)+# Pre-write vacuum runs when this many delta commits have accrued since the last vacuum. Decoupled from# merge success so tables that OOM their merge still get their tombstones cleared (the compact-after-merge# path never runs for them). Vacuum only deletes dead files, so it's memory-safe even on oversized tables.diff --git a/products/warehouse_sources/backend/migrations/0125_oom_event_workload_evidence.py b/products/warehouse_sources/backend/migrations/0125_oom_event_workload_evidence.pynew file mode 100644index 000000000000..55fde00a7113--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0125_oom_event_workload_evidence.py@@ -0,0 +1,33 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("warehouse_sources", "0124_rename_planetscale_source_type_to_mysql")]++ operations = [+ migrations.AddField(+ model_name="externaldataschemaoomevent",+ name="self_phase",+ field=models.CharField(blank=True, max_length=32, null=True),+ ),+ migrations.AddField(+ model_name="externaldataschemaoomevent",+ name="self_report_age_at_death_seconds",+ field=models.FloatField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="externaldataschemaoomevent",+ name="self_peak_buffer_bytes",+ field=models.BigIntegerField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="externaldataschemaoomevent",+ name="co_tenant_correlated_max_peak_buffer_bytes",+ field=models.BigIntegerField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name="externaldataschemaoomevent",+ name="co_tenant_report_count",+ field=models.IntegerField(blank=True, null=True),+ ),+ ]diff --git a/products/warehouse_sources/backend/migrations/0126_oom_created_idx.py b/products/warehouse_sources/backend/migrations/0126_oom_created_idx.pynew file mode 100644index 000000000000..fb6ff98cc623--- /dev/null+++ b/products/warehouse_sources/backend/migrations/0126_oom_created_idx.py@@ -0,0 +1,17 @@+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ # Concurrent index builds cannot run inside a transaction. Lives in its own+ # migration per PostHog policy (don't mix CONCURRENTLY operations with regular DDL).+ atomic = False+ dependencies = [("warehouse_sources", "0125_oom_event_workload_evidence")]++ operations = [+ SafeAddIndexConcurrently(+ model_name="externaldataschemaoomevent",+ index=models.Index(fields=["created_at", "schema", "team"], name="dwh_oom_created_idx"),+ ),+ ]diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txtindex 6e69701bcc0f..4f861e2dfb55 100644--- a/products/warehouse_sources/backend/migrations/max_migration.txt+++ b/products/warehouse_sources/backend/migrations/max_migration.txt@@ -1 +1 @@-0124_rename_planetscale_source_type_to_mysql+0126_oom_created_idxdiff --git a/products/warehouse_sources/backend/models/oom_event.py b/products/warehouse_sources/backend/models/oom_event.pyindex 398f4335a48a..7de6542afe2e 100644--- a/products/warehouse_sources/backend/models/oom_event.py+++ b/products/warehouse_sources/backend/models/oom_event.py@@ -1,7 +1,11 @@-from datetime import timedelta-from typing import TYPE_CHECKING+from dataclasses import dataclass+from datetime import datetime, timedelta+from typing import TYPE_CHECKING, Any+from django.conf import settingsfrom django.db import models+from django.db.models import Count+from django.db.models.functions import Extract, Floorfrom django.utils import timezonefrom dateutil import parser@@ -12,13 +16,55 @@ from posthog.models.utils import UUIDModel, sane_reprif TYPE_CHECKING:from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+# Self-reported phases that rule a death out as a *merge* memory problem. Repartitioning only changes+# merge memory, so a death in any of these phases must not feed the repartition trigger, whatever+# killed the worker (an extract-phase OOM is real, but its remedy is chunking or routing, not a finer+# partition layout). An unknown phase (no report: rollout gap, expired key, Redis down) fails open.+NON_MERGE_PHASES = ("extract", "load", "finished")+++def infra_burst_window_seconds() -> int:+ return int(getattr(settings, "DATA_WAREHOUSE_OOM_INFRA_BURST_WINDOW_SECONDS", 1800))+++def infra_burst_min_schemas() -> int:+ return int(getattr(settings, "DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_SCHEMAS", 50))+++def infra_burst_min_teams() -> int:+ return int(getattr(settings, "DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_TEAMS", 10))+++def evidence_freshness_bound_seconds() -> float:+ # A phase flip reaches Redis only on the next periodic sample, so evidence up to one interval old+ # is normal. Twice the interval tolerates one missed write; beyond that the report describes what+ # the run was doing earlier, not what killed it.+ return 2.0 * float(getattr(settings, "DATA_WAREHOUSE_WORKLOAD_REPORT_INTERVAL_SECONDS", 30.0))+++@dataclass(frozen=True, kw_only=True)+class BurstBucket:+ start_epoch: float+ schemas: int+ teams: int+class ExternalDataSchemaOOMEvent(TeamScopedRootMixin, UUIDModel):- """Append-only log of detected sync OOMs (pod heartbeat-timeouts) for an external data schema.+ """Append-only log of *suspected* sync OOMs for an external data schema.++ Suspected, not confirmed, and the distinction is the point. What is actually detected is that the+ previous attempt stopped heartbeating, which is equally what a deploy, a pod eviction, a node+ drain, a native crash and a heartbeat lost by a healthy worker look like. Nothing in the signal+ itself distinguishes those from a real out-of-memory kill.- Recorded once per Temporal retry attempt that follows an OOM'd attempt — a single job can OOM- many times before its terminal status — so this is an occurrence log, not a counter. Drives the- repartition trigger via `recent_count()`; kept bounded by pruning to a retention window.+ Each row therefore snapshots the workload self-report evidence available at recording time (see+ `workload_report.py`): what phase the dead attempt was in, how big its own in-memory buffer was,+ and *aggregates only* about its pod co-tenants. Co-tenant identifiers are never stored — a pod is+ multi-tenant, so they belong to other teams, and this is a team-scoped row. Evidence is stored+ raw rather than as a baked verdict so the rules in `recent_count` stay tunable after the fact.++ A row is written once per Temporal retry attempt that follows a silent death, so this is an+ occurrence log rather than a counter."""# db_constraint=False on the Team FK: a real constraint takes a SHARE ROW EXCLUSIVE lock on the@@ -28,10 +74,22 @@ class ExternalDataSchemaOOMEvent(TeamScopedRootMixin, UUIDModel):"warehouse_sources.ExternalDataSchema", on_delete=models.CASCADE, related_name="oom_events")created_at = models.DateTimeField(auto_now_add=True)- # Context captured from the prior (OOM'd) attempt's last heartbeat.+ # Context captured from the prior attempt's last heartbeat.run_id = models.CharField(max_length=400, null=True, blank=True)host = models.CharField(max_length=400, null=True, blank=True)gap_seconds = models.FloatField(null=True, blank=True)+ # Workload self-report evidence, snapshotted at recording time because its Redis source expires.+ # Null means "no report available", which every rule treats as unknown, never as exonerating.+ # Column names deliberately differ from the telemetry event's property names where the semantics+ # differ, so joining rows to events during an incident can't silently mix the two: the event's+ # `self_report_age_seconds` is read-relative and its `co_tenant_max_peak_buffer_bytes` is the raw+ # max, while the row stores the death-relative age and the death-correlated max.+ self_phase = models.CharField(max_length=32, null=True, blank=True)+ self_report_age_at_death_seconds = models.FloatField(null=True, blank=True)+ self_peak_buffer_bytes = models.BigIntegerField(null=True, blank=True)+ # Aggregates only — never co-tenant schema/run ids (they belong to other teams).+ co_tenant_correlated_max_peak_buffer_bytes = models.BigIntegerField(null=True, blank=True)+ co_tenant_report_count = models.IntegerField(null=True, blank=True)all_teams = models.Manager() # noqa: DJ012 — both are managers, ruff misclassifies this@@ -40,28 +98,56 @@ class ExternalDataSchemaOOMEvent(TeamScopedRootMixin, UUIDModel):class Meta:# Django framework internals (cascade delete, related-object access, prefetch) read through# `_default_manager` / `_base_manager` and expect an unfiltered manager. Point them at the plain- # `all_teams` so a schema delete that cascades to `oom_events` doesn't hit the fail-closed manager.- # `objects` (from TeamScopedRootMixin) stays fail-closed for explicit app code (recent_count / recording).+ # `all_teams` so a schema delete that cascades to the log doesn't hit the fail-closed manager.+ # `objects` (from TeamScopedRootMixin) stays fail-closed for explicit app code.default_manager_name = "all_teams"indexes = [models.Index(fields=["schema", "created_at"], name="dwh_oom_schema_created_idx"),+ # The burst rule aggregates distinct schemas AND teams fleet-wide by time, which can't+ # ride the schema-scoped index above; both id columns ride along so the aggregate is an+ # index-only scan.+ models.Index(fields=["created_at", "schema", "team"], name="dwh_oom_created_idx"),]@classmethoddef recent_count(cls, schema: "ExternalDataSchema", *, days: int) -> int:- """Number of OOM occurrences recorded for this schema within the last `days`.+ """Occurrences within the last `days` that still look like this table's own merge OOM.++ Three rules narrow the raw stopped-heartbeating signal, each with a distinct evidence source,+ and each failing open (an occurrence the evidence cannot explain away stays counted):++ * **Phase** — a death self-reported in a non-merge phase is not a repartitioning problem,+ whatever killed the worker (see `NON_MERGE_PHASES`).+ * **Culprit** — a pod OOM kills every co-tenant. If something else on the pod self-reported a+ strictly larger peak buffer than us, we were plausibly collateral, not the cause. The+ snapshot only carries co-tenant peaks time-correlated with the death (see+ `enrich_death_event_properties`): a neighbour that crashed an hour earlier, or a lifetime+ peak long since released, must not exonerate a death it had nothing to do with.+ * **Infra burst** — a deploy, node drain or incident takes down many unrelated schemas at+ once; an occurrence sharing a window with a fleet-wide burst is attributed to infrastructure.+ A burst must span many distinct *teams* as well as schemas — one tenant's own outage is not+ infrastructure and must not suppress other tenants' counting.+ Judged at read time from the rows themselves, because the burst window extends past the+ occurrence being judged (later rows are part of its evidence).++ The phase and culprit rules additionally require the snapshot to be *fresh* relative to the+ death (see `_evidence_excludes`): self-reports are periodic, so stale evidence predates+ whatever killed the worker and cannot exonerate.- Every retry attempt that follows an OOM'd one counts, including repeats within a single job.- Each is a separate attempt at the same merge, rescheduled onto whichever worker picks it up, so- a job that OOMs on attempt after attempt is a table failing deterministically, which is the- clearest evidence of a memory problem this log carries.+ Every retry attempt counts, including repeats within one job: each is a separate attempt at+ the same merge, rescheduled onto whichever worker picks it up, so a job failing attempt after+ attempt is the clearest evidence the log carries.`days` is required (no default) so it stays sourced from `DATA_WAREHOUSE_REPARTITION_OOM_WINDOW_DAYS`at the call site rather than duplicating that window here where the two could silently diverge.- The window is also floored at the schema's `last_repartition_at`: a completed repartition addresses- the OOMs that preceded it, so counting them again would re-trigger a repartition on the same (now- healthy) table every cooldown until they age out. Only OOMs a repartition did not fix count.+ The window is also floored at the schema's `last_repartition_at`: a completed repartition+ addresses the OOMs that preceded it, so counting them again would re-trigger a repartition on+ the same (now healthy) table every cooldown until they age out.++ This is the *filtered* view for the split trigger, where failing open means counting. Gates+ that must stay conservative in the opposite direction (coarsening, which grows the merge+ working set) use `has_recent_occurrences` — the raw signal — instead."""since = timezone.now() - timedelta(days=days)last_repartition_at = schema.last_repartition_at@@ -70,4 +156,101 @@ class ExternalDataSchemaOOMEvent(TeamScopedRootMixin, UUIDModel):since = max(since, parser.parse(last_repartition_at))except (ValueError, TypeError):pass- return cls.objects.for_team(schema.team_id).filter(schema_id=schema.pk, created_at__gte=since).count()++ events = list(+ cls.objects.for_team(schema.team_id)+ .filter(schema_id=schema.pk, created_at__gte=since)+ .values(+ "created_at",+ "self_phase",+ "self_report_age_at_death_seconds",+ "self_peak_buffer_bytes",+ "co_tenant_correlated_max_peak_buffer_bytes",+ )+ )+ # Healthy schemas have no rows, so they pay for one indexed lookup and no rule evaluation.+ # The in-memory rules run first so exonerated rows never reach the burst check at all.+ candidates = [event for event in events if not cls._evidence_excludes(event)]+ if not candidates:+ return 0++ # Burst screening is one fleet-wide bucketed aggregate over the whole window, whatever the+ # candidate count: a half-window bucket that alone crosses the thresholds proves any window+ # fully containing it does too (distinct counts are monotone under containment), so each+ # candidate's verdict is an in-memory containment check. Bursts spread too thin for any+ # single bucket to prove fail open and count. The extra window before `since` keeps a burst+ # just outside the window boundary visible to the candidates near it.+ window = timedelta(seconds=infra_burst_window_seconds())+ buckets = cls._burst_bucket_stats(since - window, timezone.now())+ return sum(1 for event in candidates if not cls._window_has_burst_bucket(event["created_at"], buckets))++ @classmethod+ def has_recent_occurrences(cls, schema: "ExternalDataSchema", *, days: int) -> bool:+ """Whether ANY occurrence exists in the window — the raw signal, no rules applied.++ For gates whose conservative direction is inverted relative to the split trigger: coarsening+ grows the merge working set, so any recent death evidence — even one the rules would explain+ away as a victim or infrastructure — must block it. Exclusion exists to withhold a split,+ never to enable a coarsen.+ """+ since = timezone.now() - timedelta(days=days)+ return cls.objects.for_team(schema.team_id).filter(schema_id=schema.pk, created_at__gte=since).exists()++ @classmethod+ def _evidence_excludes(cls, event: dict[str, Any]) -> bool:+ # Freshness gates every exoneration: a report flushed long before the death describes an+ # earlier phase of the run (a merge that OOMs within one report interval of leaving extract+ # still shows "extract" in Redis — the exact death this log exists to catch). Stale or+ # unknown-age evidence therefore cannot exclude; it fails open like missing evidence.+ age = event["self_report_age_at_death_seconds"]+ if age is None or age > evidence_freshness_bound_seconds():+ return False+ if event["self_phase"] in NON_MERGE_PHASES:+ return True+ own_peak = event["self_peak_buffer_bytes"]+ co_tenant_max = event["co_tenant_correlated_max_peak_buffer_bytes"]+ # Strictly larger, and only when both sides are known: a missing report on either side must+ # never exonerate, or a rollout gap would silently disable the trigger.+ return own_peak is not None and co_tenant_max is not None and co_tenant_max > own_peak++ @classmethod+ def _burst_bucket_stats(cls, start: datetime, end: datetime) -> list[BurstBucket]:+ """Distinct schema/team counts per half-window bucket over [start, end] — one query.++ Half the window so that any burst concentrated enough to matter (deploys and incidents land+ within minutes) fills at least one bucket that fits fully inside every candidate window+ around it. Deliberately cross-team (all_teams): the whole point is that a burst spans+ unrelated tenants; only counts leave the query, no team data crosses the boundary. Requiring+ distinct *teams* as well as schemas (see `_window_has_burst_bucket`) is what makes the+ verdict infrastructure — one tenant's own outage takes out many of its schemas at once and+ must not classify other tenants' contemporaneous deaths as infra.+ """+ bucket_seconds = infra_burst_window_seconds() / 2+ rows = (+ cls.all_teams.filter(created_at__gte=start, created_at__lte=end)+ .annotate(bucket=Floor(Extract("created_at", "epoch") / bucket_seconds))+ .values("bucket")+ .annotate(schemas=Count("schema_id", distinct=True), teams=Count("team_id", distinct=True))+ )+ return [+ BurstBucket(start_epoch=float(row["bucket"]) * bucket_seconds, schemas=row["schemas"], teams=row["teams"])+ for row in rows+ ]++ @staticmethod+ def _window_has_burst_bucket(created_at: datetime, buckets: list[BurstBucket]) -> bool:+ # Sound in the exclusion direction only: a bucket fully inside [t - window, t + window] whose+ # own distinct counts cross the thresholds proves the window's do (distinct counts are+ # monotone under containment). No such bucket proves nothing, so the candidate counts.+ window_seconds = float(infra_burst_window_seconds())+ bucket_seconds = window_seconds / 2+ low = created_at.timestamp() - window_seconds+ high = created_at.timestamp() + window_seconds+ min_schemas, min_teams = infra_burst_min_schemas(), infra_burst_min_teams()+ return any(+ bucket.start_epoch >= low+ and bucket.start_epoch + bucket_seconds <= high+ and bucket.schemas >= min_schemas+ and bucket.teams >= min_teams+ for bucket in buckets+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/README.md b/products/warehouse_sources/backend/temporal/data_imports/README.mdindex a4c8181f0dd9..a16ece07f959 100644--- a/products/warehouse_sources/backend/temporal/data_imports/README.md+++ b/products/warehouse_sources/backend/temporal/data_imports/README.md@@ -40,7 +40,7 @@ The manual flow above re-pulls every row from the source. We also have an automaHow it works:-- **Detection.** After each sync, the controller measures per-partition bytes from the Delta log (`get_add_actions` — no S3 LIST, no scan) and always records `max_partition_bytes` on the schema for observability. It records a `repartition_pending` target (the next finer tier — md5 count grows, numerical size shrinks, datetime `month` → `week` → `day` → `hour`) when **either** the largest partition is over the budget (`trigger_reason=proactive_threshold`) **or** the schema has repeatedly OOM'd recently (`trigger_reason=oom_history`). The OOM path catches tables whose compressed at-rest size looks safe but whose real merge working set is much larger (e.g. wide nested-JSON columns) — see `ExternalDataSchemaOOMEvent`, recorded per OOM occurrence at the heartbeat-timeout detection point.+- **Detection.** After each sync, the controller measures per-partition bytes from the Delta log (`get_add_actions` — no S3 LIST, no scan) and always records `max_partition_bytes` on the schema for observability. It records a `repartition_pending` target (the next finer tier — md5 count grows, numerical size shrinks, datetime `month` → `week` → `day` → `hour`) when **either** the largest partition is over the budget (`trigger_reason=proactive_threshold`) **or** the schema has repeatedly OOM'd recently (`trigger_reason=oom_history`). The OOM path catches tables whose compressed at-rest size looks safe but whose real merge working set is much larger (e.g. wide nested-JSON columns) — see `ExternalDataSchemaOOMEvent`, recorded per occurrence at the heartbeat-timeout detection point. _Suspected_, because the raw signal ("the previous attempt stopped heartbeating") is equally a deploy, an eviction or a lost heartbeat. Each row snapshots the workload self-report evidence available at recording time (own phase, own peak buffer, co-tenant aggregates — see the self-reporting section above), and `recent_count` only counts occurrences the evidence cannot explain away: deaths self-reported outside the merge phase are excluded (their remedy is chunking or routing, not partitioning), deaths where a pod co-tenant reported a strictly larger peak buffer are excluded as collateral, and occurrences inside a fleet-wide burst of many distinct schemas are attributed to infrastructure. Exonerating evidence must also be fresh relative to the death — self-reports are periodic, so a stale snapshot describes an earlier phase of the run. Every rule fails open — missing or stale evidence never exonerates.- **What the OOM trigger requires.** The signal behind `ExternalDataSchemaOOMEvent` is "the previous attempt stopped heartbeating", which a deploy, an eviction, a node drain and a lost heartbeat all produce as readily as a real OOM, and repartitioning finer fixes none of those. The prerequisite that keeps it from acting where partition size cannot be the cause is `min_splittable_partition_bytes()`: a split has to land above the size the coarsening path treats as over-fragmented, because below it we would be splitting a table into a layout we immediately want to merge back. Since an OOM-triggered split targets half the current largest partition, the table's largest partition must be at least a quarter of the budget for the trigger to act at all. Note that every retry attempt counts, including repeats within one job: each is a separate attempt at the same merge on whichever worker picks it up, so a job that OOMs attempt after attempt is a table failing deterministically, which is the clearest evidence the log carries.- **Coarsening.** The same detection pass also runs the reverse direction (`trigger_reason=coarsening`, `select_coarsen_target`): a table split far below what memory safety needs pays for every partition on each merge, and most tables in that state were put there by the finer path reacting to failures that were never about size. A table is coarsened only when it has at least 16 partitions, its largest is under an eighth of the budget, at least a 4x reduction is available, it has no OOM history in 14 days, and its current layout is at least 7 days old. Candidate layouts are computed from the measured partitions (re-formatting datetime keys, merging md5 buckets into a divisor of the current count, multiplying numerical bucket size) rather than estimated, and the coarsest one landing under **half** the budget wins. The gap between the two triggers is what stops the controller oscillating: a coarsened table must double before the finer path can claim it, and a split one must shrink eightfold before this path can.diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.pyindex 386f203fe8db..20876617ffbb 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/extract.py@@ -164,27 +164,53 @@ def report_heartbeat_timeout(inputs: "ImportDataActivityInputs", logger: Filteri# What the dead attempt said it was doing, and what its pod neighbours said, at the moment# of death — the per-activity context this event otherwise cannot carry. Adds nothing when# no reports exist.- enrich_death_event_properties(properties, run_id=str(inputs.run_id), host=last_heartbeat_host)+ enrich_death_event_properties(+ properties, run_id=str(inputs.run_id), host=last_heartbeat_host, death_ts=last_heartbeat_timestamp+ )posthoganalytics.capture("dwh_pod_heartbeat_timeout", distinct_id=None, properties=properties)- # Durable per-occurrence OOM record for the repartition trigger to read. Best-effort:- # a write failure here must never disrupt the sync.+ # Durable per-occurrence record for the repartition trigger to read, snapshotting the+ # workload evidence the enrichment just gathered — its Redis source expires in hours, and+ # the row must remain explainable (and re-classifiable) long after. `self_*` is this+ # team's own data; the co-tenant fields are aggregates only, never other teams' ids.+ # Best-effort: a write failure here must never disrupt the sync.try:from products.warehouse_sources.backend.models.oom_event import ( # noqa: PLC0415 — Django models must not be imported at this activity module's load timeExternalDataSchemaOOMEvent,)if inputs.schema_id is not None:+ # Age of the evidence *at the death*, not at this retry: the last heartbeat is the+ # best proxy for when the worker died, and the report's own ts says when the+ # evidence was flushed. The rules refuse to exonerate on evidence older than a+ # small bound, because a phase flip (extract -> merge) reaches Redis only on the+ # next sample, and a merge that OOMs inside that window still shows "extract".+ report_ts = properties.get("self_report_ts")+ self_report_age = (+ max(0.0, last_heartbeat_timestamp - float(report_ts)) if report_ts is not None else None+ )ExternalDataSchemaOOMEvent.objects.for_team(inputs.team_id).create(team_id=inputs.team_id,schema_id=inputs.schema_id,run_id=inputs.run_id,host=last_heartbeat_host,gap_seconds=gap_between_beats,+ self_phase=properties.get("self_phase"),+ self_report_age_at_death_seconds=self_report_age,+ self_peak_buffer_bytes=properties.get("self_peak_buffer_bytes"),+ # The *correlated* max, not the raw one: raw spans keys retained for up to+ # the TTL, so a neighbour that crashed an hour ago (or a survivor's refreshed+ # report carrying a long-released lifetime peak) could exonerate a death it+ # had nothing to do with. Absent when no co-tenant reported near the death,+ # which the culprit rule treats as unknown — it fails open.+ co_tenant_correlated_max_peak_buffer_bytes=properties.get(+ "co_tenant_correlated_max_peak_buffer_bytes"+ ),+ co_tenant_report_count=properties.get("co_tenant_report_count"),)except Exception as record_error:- logger.debug(f"Failed to record OOM event for schema {inputs.schema_id}: {record_error}")+ logger.debug(f"Failed to record suspected OOM event for schema {inputs.schema_id}: {record_error}")else:logger.debug("Last heartbeat was within the heartbeat timeout window. No action needed.")except Exception as e:diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.pyindex c838a4bde4ae..e2c91c546c52 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/common/test/test_extract.py@@ -181,6 +181,70 @@ class TestReportHeartbeatTimeoutRecording(BaseTest):assert event.host == "pod-abc"assert event.run_id == "run-1"assert event.gap_seconds == pytest.approx(gap_seconds)+ # No workload reports were seeded, so evidence must be honestly absent (fails open), not 0.+ assert event.self_phase is None and event.self_peak_buffer_bytes is None+ assert event.self_report_age_at_death_seconds is None++ def test_row_snapshots_workload_evidence_without_co_tenant_identifiers(self) -> None:+ # The whole point of the stack: the dead attempt's own self-report and its pod's aggregates+ # must survive onto the durable row (the Redis source expires in hours), and nothing on the+ # row may carry another team's schema or run ids — this is a team-scoped table.+ import json as _json++ from django.forms.models import model_to_dict++ from products.warehouse_sources.backend.temporal.data_imports import workload_report++ schema = self._schema()+ inputs = MagicMock(team_id=self.team.pk, schema_id=schema.id, source_id=str(uuid.uuid4()), run_id="run-1")+ redis = workload_report._redis_client()+ assert redis is not None+ # Reports flushed 5s before the last heartbeat: fresh, so the rules may act on the evidence.+ heartbeat_ts = datetime(2026, 7, 6, 12, 0, 0, tzinfo=UTC).timestamp() - 300+ for run_id, schema_id, phase, peak, ts in (+ ("run-1", str(schema.id), "merge", 900, heartbeat_ts - 5),+ ("run-neighbour", "other-team-schema", "merge", 700_000, heartbeat_ts - 5),+ # A neighbour that crashed an hour before the death: its lingering key must not+ # reach the row's culprit evidence, however large its historical peak.+ ("run-ancient", "other-team-schema-2", "merge", 9_000_000, heartbeat_ts - 3600),+ ):+ redis.setex(+ workload_report.run_key(run_id),+ 60,+ _json.dumps(+ {+ "run_id": run_id,+ "schema_id": schema_id,+ "host": "pod-abc",+ "phase": phase,+ "buffer_bytes": peak,+ "peak_buffer_bytes": peak,+ "ts": ts,+ }+ ),+ )+ redis.sadd(workload_report.host_key("pod-abc"), run_id)++ with (+ patch(f"{_EXTRACT_MODULE}.activity.info", return_value=self._info(attempt=2, gap_seconds=300)),+ patch(f"{_EXTRACT_MODULE}.posthoganalytics"),+ ):+ report_heartbeat_timeout(inputs, MagicMock())++ event = ExternalDataSchemaOOMEvent.objects.for_team(self.team.pk).get(schema_id=schema.id)+ assert event.self_phase == "merge"+ assert event.self_report_age_at_death_seconds == pytest.approx(5.0)+ assert event.self_peak_buffer_bytes == 900+ assert event.co_tenant_correlated_max_peak_buffer_bytes == 700_000, (+ "stale neighbour peak must not reach the row"+ )+ assert event.co_tenant_report_count == 2+ # The serialized row is what any admin, API or export surface would expose: no field on it+ # may carry the co-tenant's identifiers, only the aggregates asserted above.+ serialized_row = _json.dumps({field: str(value) for field, value in model_to_dict(event).items()})+ assert "other-team-schema" not in serialized_row and "run-neighbour" not in serialized_row+ # The culprit rule then discounts this row: a strictly larger co-tenant makes us the victim.+ assert ExternalDataSchemaOOMEvent.recent_count(schema, days=7) == 0# transaction=True: handle_corrupted_delta_log writes to the DB from the async thread pooldiff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.pyindex 8b567e3d377f..1b2e1cdb10d9 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/repartition_controller.py@@ -233,9 +233,9 @@ async def maybe_flag_for_coarsening(returnif max_bytes * COARSEN_TRIGGER_DIVISOR > budget:return- # Any OOM history at all disqualifies coarsening unprompted: bigger partitions are the wrong- # direction for a table that has shown memory trouble, and this is the one change that can- # cause the failure it is meant to prevent.+ # Cheap short-circuit on the count the caller already has. NOT the OOM-free guarantee: this+ # count is rule-filtered, so a table whose deaths were all explained away passes it — the+ # authoritative raw-signal gate is `has_recent_occurrences` further down.if recent_oom_count > 0:returnlayout_age = _seconds_since_last_repartition(schema)@@ -269,12 +269,12 @@ async def maybe_flag_for_coarsening(returnif requested is None:- # The 7-day window the caller already checked can miss an OOM that a repartition has since- # reset, so re-ask over the longer window before making partitions bigger.- long_window_oom_count = await asyncio.to_thread(- ExternalDataSchemaOOMEvent.recent_count, schema, days=COARSEN_OOM_FREE_DAYS- )- if long_window_oom_count > 0:+ # Raw occurrences, not the rule-filtered `recent_count`: the rules exist to withhold splits,+ # and a death they explain away (victim, deploy, extract) is still death evidence — coarsening+ # doubles the merge working set, so any of it blocks the automatic path.+ if await asyncio.to_thread(+ ExternalDataSchemaOOMEvent.has_recent_occurrences, schema, days=COARSEN_OOM_FREE_DAYS+ ):returnif not await asyncio.to_thread(is_auto_coarsen_enabled, schema):diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.pyindex 40670f4935c3..643051809bad 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/core/test_repartition_controller.py@@ -412,6 +412,10 @@ class TestCoarsenTrigger:[# Any memory-attributed OOM means bigger partitions are the wrong direction for this table."recent_oom",+ # The gate reads the RAW signal: an occurrence the classification rules would explain+ # away (here: fresh extract-phase evidence, excluded from the split trigger) is still+ # death evidence, and exclusion must never enable a coarsen it would have blocked.+ "rule_excluded_oom",# A layout that was just rewritten hasn't had a chance to prove itself; undoing it within# the day is how the two directions would start handing the table back and forth."fresh_layout",@@ -428,6 +432,14 @@ class TestCoarsenTrigger:ExternalDataSchemaOOMEvent.objects.for_team(schema.team_id).create(team_id=schema.team_id, schema=schema, run_id="run-1")+ elif case == "rule_excluded_oom":+ ExternalDataSchemaOOMEvent.objects.for_team(schema.team_id).create(+ team_id=schema.team_id,+ schema=schema,+ run_id="run-1",+ self_phase="extract",+ self_report_age_at_death_seconds=1.0,+ )with tempfile.TemporaryDirectory() as d:delta = _write_partitioned_delta(f"{d}/t", [str(bucket) for bucket in range(16)])diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_workload_report.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_workload_report.pyindex f2869b6737bb..cf4f52a77041 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_workload_report.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_workload_report.py@@ -88,6 +88,34 @@ class TestWorkloadReporting:serialized = json.dumps(properties)assert "s-big" not in serialized and "s-small" not in serialized and "run-big" not in serialized+ def test_enrichment_correlated_max_ignores_peaks_not_near_the_death(self):+ # Run keys live for hours and peaks are lifetime-high-water marks, so the raw co-tenant max+ # can carry a neighbour's crash from an hour ago (or a long-released peak on a refreshed+ # report) into blame for a death it had nothing to do with. The correlated max — what the+ # durable row snapshots for the culprit rule — may only include reports sampled around the+ # death itself.+ redis = workload_report._redis_client()+ death_ts = 10_000.0+ _seed_report(redis, run_id="run-dead2", host="pod-b", schema_id="s-dead", phase="merge", peak=900, ts=death_ts)+ # Died alongside us: last sample one interval before the shared death.+ _seed_report(+ redis, run_id="run-with", host="pod-b", schema_id="s-w", phase="merge", peak=5000, ts=death_ts - 25+ )+ # Crashed an hour earlier; its key and huge peak linger until the TTL.+ _seed_report(+ redis, run_id="run-old", host="pod-b", schema_id="s-o", phase="merge", peak=9_000_000, ts=death_ts - 3600+ )+ # Survivor still sampling minutes after the death: its lifetime peak is not evidence either.+ _seed_report(+ redis, run_id="run-later", host="pod-b", schema_id="s-l", phase="merge", peak=7000, ts=death_ts + 300+ )++ properties: dict = {}+ enrich_death_event_properties(properties, run_id="run-dead2", host="pod-b", death_ts=death_ts)++ assert properties["co_tenant_max_peak_buffer_bytes"] == 9_000_000 # raw telemetry keeps history+ assert properties["co_tenant_correlated_max_peak_buffer_bytes"] == 5000+def test_enrichment_is_silent_when_no_reports_exist(self):# Rollout reality: workers without the reporter (old deploys, disabled fleet) must produce# byte-identical events to today, or every dashboard on this event breaks during rollout.diff --git a/products/warehouse_sources/backend/temporal/data_imports/workload_report.py b/products/warehouse_sources/backend/temporal/data_imports/workload_report.pyindex b0eb75fcba02..cb85c348beaf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workload_report.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workload_report.py@@ -357,7 +357,9 @@ def read_workload_reports(host: str) -> list[dict[str, Any]]:return []-def enrich_death_event_properties(properties: dict[str, Any], *, run_id: str, host: str | None) -> None:+def enrich_death_event_properties(+ properties: dict[str, Any], *, run_id: str, host: str | None, death_ts: float | None = None+) -> None:"""Fold workload self-reports into a `dwh_pod_heartbeat_timeout` event's properties, in place.`self_*` describes the dead attempt's own last report. `co_tenant_*` is **aggregates only** —@@ -367,6 +369,14 @@ def enrich_death_event_properties(properties: dict[str, Any], *, run_id: str, hoquestion the aggregates must still answer is "was anything on this pod holding more than us",which only needs the maximum. Absent reports (rollout, expired keys, Redis down) add nothing —the event stays exactly as it was before this existed.++ `death_ts` (the dead run's last heartbeat, same pod clock as the reports) additionally yields+ `co_tenant_correlated_max_peak_buffer_bytes`: the max peak over only the co-tenants whose report+ is time-correlated with the death. The raw max spans keys retained for up to the TTL, so a+ neighbour that crashed an hour ago — or one still running whose report has refreshed since —+ could carry a historical peak into blame for a death it had nothing to do with. A report within+ the correlation bound of the death is either the co-tenant that died alongside us (its sampler+ stopped when we did) or one sampled moments around the death; anything else is history."""try:reports = read_workload_reports(host) if host else []@@ -388,6 +398,7 @@ def enrich_death_event_properties(properties: dict[str, Any], *, run_id: str, ho"self_rss_bytes": own.get("rss_bytes"),"self_peak_rss_bytes": own.get("peak_rss_bytes"),"self_report_age_seconds": round(time.time() - own["ts"], 1) if own.get("ts") is not None else None,+ "self_report_ts": own.get("ts"),})co_tenants = [report for report in reports if report.get("run_id") != run_id]@@ -404,5 +415,14 @@ def enrich_death_event_properties(properties: dict[str, Any], *, run_id: str, ho"co_tenant_extract_count": sum(1 for phase in phases if phase == "extract"),})+ if death_ts is not None:+ bound = 2.0 * workload_report_interval_seconds()+ correlated = [+ int(report.get("peak_buffer_bytes") or 0)+ for report in co_tenants+ if report.get("ts") is not None and abs(float(report["ts"]) - death_ts) <= bound+ ]+ if correlated:+ properties["co_tenant_correlated_max_peak_buffer_bytes"] = max(correlated)except Exception:LOGGER.debug("workload_report_enrich_failed", run_id=run_id, exc_info=True)diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.pyindex 74a0269fa9ed..4a5bd4c00195 100644--- a/products/warehouse_sources/backend/tests/test_models.py+++ b/products/warehouse_sources/backend/tests/test_models.py@@ -6,15 +6,17 @@ import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import patch-from django.db import DatabaseError, OperationalError, transaction+from django.db import DatabaseError, OperationalError, connection, transactionfrom django.db.models import Model-from django.test import SimpleTestCase+from django.test import SimpleTestCase, override_settings+from django.test.utils import CaptureQueriesContextfrom django.utils import timezonefrom dateutil import parserfrom parameterized import parameterizedfrom posthog.models.signals import model_activity_signal+from posthog.models.team import Teamfrom products.warehouse_sources.backend.models.credential import DataWarehouseCredentialfrom products.warehouse_sources.backend.models.external_data_job import ExternalDataJob@@ -320,17 +322,21 @@ class TestSaveSyncTypeConfigRetriesOnConnectionDrop(BaseTest):class TestExternalDataSchemaOOMEvent(BaseTest):- def _source(self) -> ExternalDataSource:+ def _source(self, team_id: int | None = None) -> ExternalDataSource:return ExternalDataSource.objects.create(- team_id=self.team.pk,+ team_id=team_id if team_id is not None else self.team.pk,source_id=str(uuid.uuid4()),connection_id=str(uuid.uuid4()),status="Completed",source_type="Postgres",)- def _schema(self, name: str) -> ExternalDataSchema:- return ExternalDataSchema.objects.create(team_id=self.team.pk, source=self._source(), name=name)+ def _schema(self, name: str, team_id: int | None = None) -> ExternalDataSchema:+ team_id = team_id if team_id is not None else self.team.pk+ return ExternalDataSchema.objects.create(team_id=team_id, source=self._source(team_id), name=name)++ def _other_team(self) -> Team:+ return Team.objects.create(organization=self.organization)def _oom(self,@@ -338,11 +344,21 @@ class TestExternalDataSchemaOOMEvent(BaseTest):*,age_days: float = 0,run_id: str | None = None,+ self_phase: str | None = None,+ # Fresh by default: the recorder snapshots the age from the same report as the rest of the+ # evidence, so evidence-carrying rows always have one. Tests override it to model staleness.+ self_report_age_at_death_seconds: float | None = 1.0,+ self_peak_buffer_bytes: int | None = None,+ co_tenant_correlated_max_peak_buffer_bytes: int | None = None,) -> ExternalDataSchemaOOMEvent:- event = ExternalDataSchemaOOMEvent.objects.for_team(self.team.pk).create(- team_id=self.team.pk,+ event = ExternalDataSchemaOOMEvent.objects.for_team(schema.team_id).create(+ team_id=schema.team_id,schema=schema,run_id=run_id,+ self_phase=self_phase,+ self_report_age_at_death_seconds=self_report_age_at_death_seconds,+ self_peak_buffer_bytes=self_peak_buffer_bytes,+ co_tenant_correlated_max_peak_buffer_bytes=co_tenant_correlated_max_peak_buffer_bytes,)if age_days:# created_at is auto_now_add, so backdate via an update to place the row outside the window.@@ -396,6 +412,141 @@ class TestExternalDataSchemaOOMEvent(BaseTest):assert ExternalDataSchemaOOMEvent.recent_count(schema, days=7) == 5+ @parameterized.expand(+ [+ # A death self-reported mid-extract (or in the consumer's pre-merge load, or after+ # finishing) is not a merge memory problem, so a finer partition layout cannot fix it.+ # Counting these is how tables that OOM on big fetches get wrongly repartitioned.+ ("extract_phase_does_not_count", {"self_phase": "extract"}, 0),+ ("load_phase_does_not_count", {"self_phase": "load"}, 0),+ ("finished_phase_does_not_count", {"self_phase": "finished"}, 0),+ ("merge_phase_counts", {"self_phase": "merge"}, 1),+ # No workload report (rollout gap, expired key, Redis down) must fail open, or a partial+ # rollout would silently switch the trigger off.+ ("unknown_phase_counts", {}, 1),+ # A co-tenant that self-reported a strictly larger working set is the likelier culprit for+ # a pod kill; counting the victim would repartition the wrong table.+ (+ "larger_co_tenant_exonerates",+ {+ "self_phase": "merge",+ "self_peak_buffer_bytes": 1_000,+ "co_tenant_correlated_max_peak_buffer_bytes": 900_000,+ },+ 0,+ ),+ (+ "smaller_co_tenant_does_not_exonerate",+ {+ "self_phase": "merge",+ "self_peak_buffer_bytes": 900_000,+ "co_tenant_correlated_max_peak_buffer_bytes": 1_000,+ },+ 1,+ ),+ # Unknown on either side never exonerates: blame requires evidence, absence of it does not.+ (+ "unknown_own_size_still_counts",+ {"self_phase": "merge", "co_tenant_correlated_max_peak_buffer_bytes": 900_000},+ 1,+ ),+ # Reports are periodic, so a snapshot flushed long before the death describes an earlier+ # phase of the run: a merge that OOMs within one report interval of leaving extract still+ # shows "extract" in Redis. Stale or unknown-age evidence must not exonerate.+ (+ "stale_extract_phase_still_counts",+ {"self_phase": "extract", "self_report_age_at_death_seconds": 999.0},+ 1,+ ),+ (+ "unknown_age_extract_phase_still_counts",+ {"self_phase": "extract", "self_report_age_at_death_seconds": None},+ 1,+ ),+ (+ "stale_larger_co_tenant_still_counts",+ {+ "self_phase": "merge",+ "self_report_age_at_death_seconds": 999.0,+ "self_peak_buffer_bytes": 1_000,+ "co_tenant_correlated_max_peak_buffer_bytes": 900_000,+ },+ 1,+ ),+ ]+ )+ def test_recent_count_applies_workload_evidence_rules(self, _name: str, evidence: dict, expected: int) -> None:+ schema = self._schema("orders")+ self._oom(schema, **evidence)++ assert ExternalDataSchemaOOMEvent.recent_count(schema, days=7) == expected++ @override_settings(DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_SCHEMAS=3, DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_TEAMS=3)+ def test_recent_count_ignores_occurrences_inside_a_fleet_wide_burst(self) -> None:+ # A deploy or node drain kills workers fleet-wide and every syncing schema records an+ # occurrence. Counting those is what repartitioned healthy tables for reasons that had+ # nothing to do with their partitions; a burst is judged from the rows themselves.+ schema = self._schema("orders")+ self._oom(schema, self_phase="merge")+ for name in ("events", "persons"):+ self._oom(self._schema(name, team_id=self._other_team().pk))++ assert ExternalDataSchemaOOMEvent.recent_count(schema, days=7) == 0++ @override_settings(DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_SCHEMAS=3, DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_TEAMS=3)+ def test_recent_count_keeps_occurrences_when_a_burst_spans_only_one_tenant(self) -> None:+ # One tenant's source outage kills all of that tenant's schemas at once — many schemas, one+ # team. That is the tenant's own problem, not infrastructure: classifying it as a burst would+ # let one tenant's failures suppress another tenant's remediation, and (without this floor)+ # its own.+ schema = self._schema("orders")+ self._oom(schema, self_phase="merge")+ for name in ("events", "persons", "invoices"):+ self._oom(self._schema(name))++ assert ExternalDataSchemaOOMEvent.recent_count(schema, days=7) == 1++ def test_recent_count_screens_bursts_with_one_aggregate_on_a_quiet_fleet(self) -> None:+ # The burst rule must not cost one aggregate per row: a schema can carry dozens of+ # occurrences, and this runs on every detection pass. One bucketed aggregate over the whole+ # window screens them all; on a quiet fleet no bucket crosses the thresholds, so everything+ # counts.+ schema = self._schema("orders")+ for _ in range(6):+ self._oom(schema, self_phase="merge")+ self._oom(schema, self_phase="merge", age_days=5) # days apart must change nothing++ # Bounded, not exact: the team-scoped manager adds constant overhead we don't want to pin.+ with CaptureQueriesContext(connection) as queries:+ assert ExternalDataSchemaOOMEvent.recent_count(schema, days=7) == 7+ assert len(queries) <= 4, [q["sql"][:120] for q in queries.captured_queries]++ @override_settings(DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_SCHEMAS=1, DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_TEAMS=1)+ def test_recent_count_burst_screening_work_does_not_grow_with_retained_history(self) -> None:+ # The shape an adversarially (or chronically) failing schema can induce: many occurrences+ # spaced just under the window across days. Screening must stay a constant number of queries+ # — one bucketed aggregate for the whole window — never a query per occurrence.+ schema = self._schema("orders")+ for i in range(40):+ self._oom(schema, self_phase="merge", age_days=(40 - i) * 25 / (60 * 24))++ with CaptureQueriesContext(connection) as queries:+ # Thresholds of 1/1 make every occurrence its own crossing bucket, so all are excluded —+ # the point here is the query count, not the (absurd) threshold configuration.+ assert ExternalDataSchemaOOMEvent.recent_count(schema, days=7) == 0+ assert len(queries) <= 4, [q["sql"][:120] for q in queries.captured_queries]++ @override_settings(DATA_WAREHOUSE_OOM_INFRA_BURST_MIN_SCHEMAS=10)+ def test_recent_count_keeps_occurrences_below_the_burst_threshold(self) -> None:+ # The mirror case: a handful of schemas failing in one window is normal operation, and+ # discarding those would leave the trigger unable to fire at all.+ schema = self._schema("orders")+ self._oom(schema, self_phase="merge")+ for name in ("events", "persons"):+ self._oom(self._schema(name))++ assert ExternalDataSchemaOOMEvent.recent_count(schema, days=7) == 1+class TestUpdateSyncTypeConfigKeys(BaseTest):"""The locked-merge helper that keeps the CDC extract activity and concurrent API PATCHes from