: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-modeling): per-node freshness targets + schedule preview (#67395)
Jovan Sakovic0fa379d0b678
diff --git a/products/data_modeling/backend/graph.py b/products/data_modeling/backend/graph.pyindex 6b17a2e6d527..41ae9251d94e 100644--- a/products/data_modeling/backend/graph.py+++ b/products/data_modeling/backend/graph.py@@ -4,26 +4,14 @@ Loads edges once and computes upstream/downstream relationships in Pythoninstead of running recursive DB queries per node."""-from collections import defaultdict, deque+from collections import defaultdictfrom uuid import UUID+from products.data_modeling.backend.logic.graph_traversal import reachablefrom products.data_modeling.backend.models.edge import Edgefrom products.data_modeling.backend.models.node import NodeType-def _bfs(start: str, adjacency: dict[str, set[str]]) -> set[str]:- """BFS from start, returning all reachable nodes (excluding start)."""- visited: set[str] = set()- queue = deque([start])- while queue:- current = queue.popleft()- for neighbor in adjacency.get(current, set()):- if neighbor not in visited:- visited.add(neighbor)- queue.append(neighbor)- return visited--class Graph:"""In-memory representation of a DAG's edge structure.@@ -70,11 +58,11 @@ class Graph:def get_upstream(self, node_id: str | UUID) -> set[str]:"""Get all upstream (ancestor) node IDs, excluding TABLE nodes."""- return _bfs(str(node_id), self._upstream_adj)+ return reachable(str(node_id), self._upstream_adj)def get_downstream(self, node_id: str | UUID) -> set[str]:"""Get all downstream (descendant) node IDs, excluding TABLE nodes."""- return _bfs(str(node_id), self._downstream_adj)+ return reachable(str(node_id), self._downstream_adj)def get_upstream_count(self, node_id: str | UUID) -> int:return len(self.get_upstream(node_id))diff --git a/products/data_modeling/backend/logic/cohort_scheduling.py b/products/data_modeling/backend/logic/cohort_scheduling.pynew file mode 100644index 000000000000..27ff7ce7a379--- /dev/null+++ b/products/data_modeling/backend/logic/cohort_scheduling.py@@ -0,0 +1,76 @@+"""Cadence-tier scheduling for the v2 data-modeling DAG.++Turns per-node effective cadences (from `freshness.compute_effective_cadences`) into+frequency cohorts, then reconciles them against Temporal schedules — one+`data-modeling-execute-dag` schedule per distinct cadence, each scoped to that tier's+node_ids. Replaces the single-schedule-per-DAG model.++The tier/plan computation here is pure; the Temporal reconcile that applies a plan lives+alongside it and is the only part that touches the schedule API.+"""++import dataclasses+from collections import defaultdict+from datetime import timedelta+++def bucket_into_cadence_tiers(effective: dict[str, timedelta | None]) -> dict[timedelta, set[str]]:+ """Group schedulable nodes by effective cadence.++ Nodes with no effective cadence (`None` — unscheduled, ride-downstream) are omitted so+ they never get a schedule of their own.+ """+ tiers: dict[timedelta, set[str]] = defaultdict(set)+ for node_id, interval in effective.items():+ if interval is not None:+ tiers[interval].add(node_id)+ return dict(tiers)+++def tier_schedule_id(dag_id: str, interval: timedelta) -> str:+ """Temporal schedule id for one cadence tier of a DAG: "{dag_id}:{interval_seconds}".++ A DAG UUID never contains a colon, so the dag id parses back off the prefix.+ """+ return f"{dag_id}:{int(interval.total_seconds())}"+++def dag_id_from_schedule_id(schedule_id: str) -> str:+ """Recover the DAG id from a tier schedule id.++ A migration-era single schedule (id == dag_id, no colon) parses to itself, keeping the+ read side backward-compatible through the transition.+ """+ return schedule_id.rsplit(":", 1)[0]+++class ScheduleReconcilePlan:+ """What to do to Temporal to make a DAG's schedules match its desired cadence tiers.++ Keyed by schedule id. `to_create`/`to_update` map a tier's schedule id to its+ (interval, node_ids); `to_delete` is the set of schedule ids to remove.+ """++ to_create: dict[str, tuple[timedelta, set[str]]]+ to_update: dict[str, tuple[timedelta, set[str]]]+ to_delete: set[str]+++def plan_schedule_reconciliation(+ dag_id: str,+ desired_tiers: dict[timedelta, set[str]],+ existing_schedule_ids: set[str],+) -> ScheduleReconcilePlan:+ """Diff desired cadence tiers against a DAG's existing execute-dag schedules.++ Always rewrites tiers that persist (self-healing against drift) rather than diffing+ node_ids. `to_delete` is every existing schedule not backing a desired tier — which+ sweeps both removed tiers and the migration-era single `dag_id` schedule.+ """+ desired = {tier_schedule_id(dag_id, interval): (interval, node_ids) for interval, node_ids in desired_tiers.items()}+ return ScheduleReconcilePlan(+ to_create={sid: value for sid, value in desired.items() if sid not in existing_schedule_ids},+ to_update={sid: value for sid, value in desired.items() if sid in existing_schedule_ids},+ to_delete=set(existing_schedule_ids) - set(desired),+ )diff --git a/products/data_modeling/backend/logic/freshness.py b/products/data_modeling/backend/logic/freshness.pynew file mode 100644index 000000000000..d883623580a9--- /dev/null+++ b/products/data_modeling/backend/logic/freshness.py@@ -0,0 +1,242 @@+"""Per-node freshness-target propagation for the v2 data-modeling DAG.++Pure graph functions over primitives — no Django, no Temporal. A separate layer+extracts the graph (node ids, edges, declared targets, source intervals) from the+`Node`/`Edge` models and feeds it here. Keeping this pure keeps it the cheapest+rung to test and lets the whole model be validated before any scheduling changes.++Vocabulary, one term per concept:+- declared target: what a user set on a node ("data no older than X"); optional.+- effective cadence: what propagation computes for a node:+ min(own declared target, finest effective cadence among its consumers).+ None means unscheduled (no declared target, no consumer demanding freshness).+- source interval: how often a source (TABLE) node actually receives new data;+ STREAMING (timedelta zero) when continuous.+- tier: the group of nodes sharing one effective cadence; each tier gets one+ Temporal schedule (see cohort_scheduling).+- bounds: a declarable target must sit in [source floor .. consumer ceiling].+ source_floor = the slowest ancestor source interval (you cannot promise fresher+ data than your slowest source delivers); consumer_ceiling = the finest declared+ target among descendants (you cannot be staler than a consumer requires).+ In interval-space a smaller timedelta means fresher/more frequent, so as plain+ timedeltas: source_floor <= target <= consumer_ceiling.++Worked example, a chain src -> view -> endpoint:+ src is an imported table syncing every 1hour (its source interval), endpoint+ declares a 6hour target, view declares nothing. Effective cadences: endpoint+ 6hour (its own declared target), view 6hour (inherited from its finest consumer).+ One 6hour tier containing both nodes. If view later declares its own target it is+ bounded to [1hour .. 6hour]: a 30min target is rejected (finer than src delivers),+ a 12hour target is rejected (staler than endpoint requires).++Edges are (upstream_id, downstream_id): data flows upstream -> downstream, so a node's+"children"/descendants are reached by following edges forward.+"""++import dataclasses+from collections import defaultdict, deque+from datetime import timedelta++from products.data_modeling.backend.logic.graph_traversal import reachable++# A streamed source (e.g. the events table) is continuously fresh, so it imposes no+# floor: a descendant may be as tight as the buckets allow. Imported sources instead+# carry their real sync interval.+#+# STREAMING overloads timedelta(0): it sorts below every real interval, so min/max+# propagation needs no special case. Compare against STREAMING rather than a bare+# timedelta(0) so the intent stays searchable; None (elsewhere) means "unscheduled".+STREAMING = timedelta(0)++# Intervals build_schedule_spec can realize exactly (minute buckets must divide 60, hour+# buckets 24, then weekly/monthly); anything else silently degrades or crashes there.+# Spelled out literally so this module stays Django-free; a test pins each value to the+# canonical sync-frequency buckets in warehouse_sources.+SCHEDULABLE_BUCKETS: frozenset[timedelta] = frozenset(+ {+ timedelta(minutes=1),+ timedelta(minutes=5),+ timedelta(minutes=15),+ timedelta(minutes=30),+ timedelta(hours=1),+ timedelta(hours=6),+ timedelta(hours=12),+ timedelta(hours=24),+ timedelta(days=7),+ timedelta(days=30),+ }+)+++class UnsatisfiableFrequencyError(ValueError):+ """A declared target falls outside the node's legal [source_floor, consumer_ceiling] range."""+++class UnsupportedFrequencyTargetError(ValueError):+ """A declared target is not one of the schedulable cadence buckets (SCHEDULABLE_BUCKETS)."""+++def is_finer_than(cadence: timedelta, other: timedelta) -> bool:+ """Whether `cadence` refreshes more often than `other` (smaller timedelta = fresher)."""+ return cadence < other+++def is_coarser_than(cadence: timedelta, other: timedelta) -> bool:+ """Whether `cadence` refreshes less often than `other` (bigger timedelta = staler)."""+ return cadence > other+++def format_cadence(interval: timedelta) -> str:+ """Human label for a cadence, matching the sync-frequency bucket names ("15min", "6hour", "7day")."""+ seconds = int(interval.total_seconds())+ if seconds >= 86400 and seconds % 86400 == 0:+ return f"{seconds // 86400}day"+ if seconds >= 3600 and seconds % 3600 == 0:+ return f"{seconds // 3600}hour"+ if seconds >= 60 and seconds % 60 == 0:+ return f"{seconds // 60}min"+ return str(interval)+++def _adjacency(edges: list[tuple[str, str]]) -> tuple[dict[str, list[str]], dict[str, list[str]]]:+ """Return (children, parents) maps. Edges are (upstream, downstream)."""+ children: dict[str, list[str]] = defaultdict(list)+ parents: dict[str, list[str]] = defaultdict(list)+ for upstream, downstream in edges:+ children[upstream].append(downstream)+ parents[downstream].append(upstream)+ return children, parents+++def compute_effective_cadences(+ *,+ nodes: set[str],+ edges: list[tuple[str, str]],+ declared_targets: dict[str, timedelta],+) -> dict[str, timedelta | None]:+ """Resolve each node's effective cadence.++ Returns a value for every id in `nodes`. `None` means "unscheduled" — a node with+ no declared target and no scheduled descendant demanding freshness (the+ ride-downstream opt-out). Source nodes are not expected in `nodes`.+ """+ children, parents = _adjacency(edges)+ # reverse-topological pass, iterative because recursion overflows on deep chains+ out_degree = {node: sum(1 for child in children.get(node, []) if child in nodes) for node in nodes}+ queue = deque(node for node in nodes if out_degree[node] == 0)+ resolved: dict[str, timedelta | None] = {}+ while queue:+ node = queue.popleft()+ candidates: list[timedelta] = []+ if node in declared_targets:+ candidates.append(declared_targets[node])+ for child in children.get(node, []):+ if child in nodes and (child_effective := resolved[child]) is not None:+ candidates.append(child_effective)+ # min = the finest demand wins (smaller timedelta = fresher)+ resolved[node] = min(candidates) if candidates else None+ for parent in parents.get(node, []):+ if parent in nodes:+ out_degree[parent] -= 1+ if out_degree[parent] == 0:+ queue.append(parent)++ if len(resolved) != len(nodes):+ raise ValueError(f"cycle detected in DAG; unresolved nodes: {sorted(nodes - resolved.keys())}")+ return resolved+++def declared_target_bounds(+ *,+ node_id: str,+ edges: list[tuple[str, str]],+ declared_targets: dict[str, timedelta],+ source_intervals: dict[str, timedelta],+) -> tuple[timedelta, timedelta | None]:+ """Return (source_floor, consumer_ceiling) for a node's declarable target.++ source_floor = the slowest interval among ancestor source nodes (STREAMING sources+ add no floor). consumer_ceiling = the finest declared target among descendants, or+ None if no descendant declares one. A floor coarser than the ceiling means the node+ is unsatisfiable.+ """+ children, parents = _adjacency(edges)++ ancestor_source_intervals = [+ source_intervals[ancestor] for ancestor in reachable(node_id, parents) if ancestor in source_intervals+ ]+ source_floor = max(ancestor_source_intervals) if ancestor_source_intervals else STREAMING++ descendant_targets = [+ declared_targets[descendant] for descendant in reachable(node_id, children) if descendant in declared_targets+ ]+ consumer_ceiling = min(descendant_targets) if descendant_targets else None++ return source_floor, consumer_ceiling+++def validate_declared_target(+ *,+ node_id: str,+ target: timedelta,+ edges: list[tuple[str, str]],+ declared_targets: dict[str, timedelta],+ source_intervals: dict[str, timedelta],+) -> None:+ """Raise if `target` is not a schedulable bucket or falls outside the node's bounds."""+ if target not in SCHEDULABLE_BUCKETS:+ supported = ", ".join(format_cadence(interval) for interval in sorted(SCHEDULABLE_BUCKETS))+ raise UnsupportedFrequencyTargetError(+ f"Requested freshness ({format_cadence(target)}) is not a schedulable cadence; pick one of: {supported}"+ )+ source_floor, consumer_ceiling = declared_target_bounds(+ node_id=node_id, edges=edges, declared_targets=declared_targets, source_intervals=source_intervals+ )+ if is_finer_than(target, source_floor):+ raise UnsatisfiableFrequencyError(+ f"Requested freshness ({format_cadence(target)}) is more frequent than this node's sources can deliver;"+ f" the slowest upstream source syncs every {format_cadence(source_floor)}"+ )+ if consumer_ceiling is not None and is_coarser_than(target, consumer_ceiling):+ raise UnsatisfiableFrequencyError(+ f"Requested freshness ({format_cadence(target)}) is less frequent than a downstream consumer requires"+ f" (tightest downstream target: {format_cadence(consumer_ceiling)})"+ )+++class InvalidTarget:+ """A declared target that currently sits outside its node's legal bounds."""++ node_id: str+ declared: timedelta+ source_floor: timedelta+ consumer_ceiling: timedelta | None+++def find_invalid_targets(+ *,+ edges: list[tuple[str, str]],+ declared_targets: dict[str, timedelta],+ source_intervals: dict[str, timedelta],+) -> list[InvalidTarget]:+ """Re-validate every declared target against its current bounds.++ Targets drift: a descendant declaring a finer target lowers ancestors' ceilings, and+ graph edits move floors. Runtime freshness stays correct (finest demand wins) — what+ breaks is declared == effective, so run this on any graph mutation and surface the result.+ """+ invalid: list[InvalidTarget] = []+ for node_id, declared in declared_targets.items():+ source_floor, consumer_ceiling = declared_target_bounds(+ node_id=node_id, edges=edges, declared_targets=declared_targets, source_intervals=source_intervals+ )+ if is_finer_than(declared, source_floor) or (+ consumer_ceiling is not None and is_coarser_than(declared, consumer_ceiling)+ ):+ invalid.append(+ InvalidTarget(+ node_id=node_id, declared=declared, source_floor=source_floor, consumer_ceiling=consumer_ceiling+ )+ )+ return invaliddiff --git a/products/data_modeling/backend/logic/graph_traversal.py b/products/data_modeling/backend/logic/graph_traversal.pynew file mode 100644index 000000000000..bea8726e223b--- /dev/null+++ b/products/data_modeling/backend/logic/graph_traversal.py@@ -0,0 +1,21 @@+"""Pure graph-traversal primitives shared across the data-modeling DAG code.++No Django, no models — just adjacency-map reachability, so the freshness logic and the in-memory+`Graph` share one walk instead of each carrying its own copy. Adjacency values may be any iterable+(sets or lists), since callers build their maps differently.+"""++from collections.abc import Iterable, Mapping+++def reachable(start: str, adjacency: Mapping[str, Iterable[str]]) -> set[str]:+ """All nodes reachable from `start` (exclusive) by following `adjacency`."""+ seen: set[str] = set()+ stack = list(adjacency.get(start, ()))+ while stack:+ node = stack.pop()+ if node in seen:+ continue+ seen.add(node)+ stack.extend(adjacency.get(node, ()))+ return seendiff --git a/products/data_modeling/backend/logic/node_frequency.py b/products/data_modeling/backend/logic/node_frequency.pynew file mode 100644index 000000000000..627eb849c6a9--- /dev/null+++ b/products/data_modeling/backend/logic/node_frequency.py@@ -0,0 +1,186 @@+"""ORM-facing glue between the `Node` graph and the pure freshness logic.++`freshness.py` stays pure (primitives only); this module reads the declared target+off `Node.properties`, extracts the `(nodes, edges, targets)` graph for a DAG, and+resolves per-source freshness. Storing the target in `properties` is a deliberate+stopgap: it lets us validate the model with no migration before promoting it to a+typed column.+"""++import uuid+import dataclasses+from datetime import timedelta++from django.db.models import Q++from products.data_modeling.backend.logic.freshness import STREAMING+from products.data_modeling.backend.models.dag import DAG+from products.data_modeling.backend.models.edge import Edge+from products.data_modeling.backend.models.node import Node, NodeType+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema++# Declared target lives here, mirroring properties["system"]["suspended"] (circuit breaker).+_SYSTEM_KEY = "system"+_FREQUENCY_KEY = "frequency"+_TARGET_SECONDS_KEY = "target_seconds"++# `resolve_dependency_to_node` stamps this on source (TABLE) nodes at creation.+_ORIGIN_KEY = "origin"+_WAREHOUSE_TABLE_ID_KEY = "warehouse_table_id"+_ORIGIN_POSTHOG = "posthog"+_ORIGIN_WAREHOUSE = "warehouse"+++def get_declared_target(node: Node) -> timedelta | None:+ """Return the node's declared freshness target, or None if it has none."""+ seconds = (node.properties or {}).get(_SYSTEM_KEY, {}).get(_FREQUENCY_KEY, {}).get(_TARGET_SECONDS_KEY)+ return timedelta(seconds=seconds) if seconds is not None else None+++def set_declared_target(node: Node, target: timedelta | None) -> None:+ """Set (or clear, with None) the node's declared target without touching sibling system state."""+ properties = node.properties or {}+ frequency = properties.setdefault(_SYSTEM_KEY, {}).setdefault(_FREQUENCY_KEY, {})+ if target is None:+ frequency.pop(_TARGET_SECONDS_KEY, None)+ else:+ frequency[_TARGET_SECONDS_KEY] = int(target.total_seconds())+ node.properties = properties+ node.save(update_fields=["properties"])+++def _resolve_warehouse_source_intervals(nodes: list[Node]) -> dict[str, timedelta | None]:+ """Sync interval per imported (origin=warehouse) source node id, batched.++ A node maps to None when it has no schedule: manual/`never` schemas, paused schemas, and+ tables we can't resolve to a schema are all "best-effort, no floor" from a freshness+ standpoint. Tables resolve by the stamped table id first, falling back to the node name.+ """+ if not nodes:+ return {}+ team_ids = {node.team_id for node in nodes}+ table_ids = {table_id for node in nodes if (table_id := (node.properties or {}).get(_WAREHOUSE_TABLE_ID_KEY))}+ names = {node.name for node in nodes}+ tables = (+ DataWarehouseTable.objects.filter(team_id__in=team_ids)+ .filter(Q(id__in=table_ids) | Q(name__in=names))+ .exclude(deleted=True)+ )+ tables_by_id: dict[tuple[int, str], DataWarehouseTable] = {}+ tables_by_name: dict[tuple[int, str], DataWarehouseTable] = {}+ for table in tables:+ tables_by_id.setdefault((table.team_id, str(table.id)), table)+ tables_by_name.setdefault((table.team_id, table.name), table)++ schemas_by_table_id: dict[uuid.UUID, ExternalDataSchema] = {}+ for schema in ExternalDataSchema.objects.filter(table_id__in=[table.id for table in tables]).exclude(deleted=True):+ if schema.table_id is not None:+ schemas_by_table_id.setdefault(schema.table_id, schema)++ intervals: dict[str, timedelta | None] = {}+ for node in nodes:+ table_id = (node.properties or {}).get(_WAREHOUSE_TABLE_ID_KEY)+ node_table = tables_by_id.get((node.team_id, str(table_id))) if table_id else None+ if node_table is None:+ # Best-effort fallback: name is not unique per team, and on a collision the+ # index above kept an arbitrary row, so this may resolve to the wrong table.+ # Acceptable because an unresolvable/wrong match only widens the best-effort+ # set; never treat this path as authoritative.+ node_table = tables_by_name.get((node.team_id, node.name))+ node_schema = schemas_by_table_id.get(node_table.id) if node_table is not None else None+ if node_schema is None or not node_schema.should_sync:+ intervals[str(node.id)] = None+ else:+ intervals[str(node.id)] = node_schema.sync_frequency_interval+ return intervals+++def resolve_source_intervals(source_nodes: list[Node]) -> tuple[dict[str, timedelta], set[str]]:+ """Classify each source (TABLE) node into a freshness floor.++ Returns (source_intervals, best_effort_source_ids). A best-effort source is treated as+ STREAMING (no floor) but flagged so the wiring layer can warn that its downstream freshness+ is not actually guaranteed: streamed PostHog builtins are genuinely continuous, but a+ manual/paused/unresolvable import only *looks* fresh.+ """+ warehouse_intervals = _resolve_warehouse_source_intervals(+ [node for node in source_nodes if (node.properties or {}).get(_ORIGIN_KEY) == _ORIGIN_WAREHOUSE]+ )+ source_intervals: dict[str, timedelta] = {}+ best_effort: set[str] = set()+ for node in source_nodes:+ node_id = str(node.id)+ origin = (node.properties or {}).get(_ORIGIN_KEY)+ if origin == _ORIGIN_WAREHOUSE:+ interval = warehouse_intervals[node_id]+ if interval is None:+ source_intervals[node_id] = STREAMING+ best_effort.add(node_id)+ else:+ source_intervals[node_id] = interval+ elif origin == _ORIGIN_POSTHOG:+ source_intervals[node_id] = STREAMING+ else:+ # Unknown/unstamped origin: assume continuous but flag it — we can't prove a floor.+ source_intervals[node_id] = STREAMING+ best_effort.add(node_id)+ return source_intervals, best_effort+++class FrequencyGraph:+ """The primitives `freshness.py` operates on, extracted from one DAG's Node/Edge rows."""++ nodes: set[str] # schedulable (non-TABLE) node ids+ edges: list[tuple[str, str]] # (upstream_id, downstream_id), includes source tables+ declared_targets: dict[str, timedelta] # declared per-node targets+ source_intervals: dict[str, timedelta] # per source (TABLE) node+ best_effort_source_ids: set[str] # sources treated as STREAMING but not guaranteed+++def build_frequency_graph(dag: DAG) -> FrequencyGraph:+ """Extract the freshness graph for a DAG: schedulable nodes, edges, targets, source floors."""+ nodes = list(Node.objects.filter(dag=dag))+ edges = [+ (str(source_id), str(target_id))+ for source_id, target_id in Edge.objects.filter(dag=dag).values_list("source_id", "target_id")+ ]++ schedulable = {str(node.id) for node in nodes if node.type != NodeType.TABLE}+ declared_targets: dict[str, timedelta] = {}+ for node in nodes:+ target = get_declared_target(node)+ if target is not None:+ declared_targets[str(node.id)] = target++ source_nodes = [node for node in nodes if node.type == NodeType.TABLE]+ source_intervals, best_effort = resolve_source_intervals(source_nodes)++ return FrequencyGraph(+ nodes=schedulable,+ edges=edges,+ declared_targets=declared_targets,+ source_intervals=source_intervals,+ best_effort_source_ids=best_effort,+ )+++def seed_targets(dag: DAG) -> dict[str, timedelta]:+ """Derive a starting target per schedulable node from what the DAG already carries.++ A node inherits its saved query's `sync_frequency_interval` if set, else the DAG's+ `sync_frequency_interval`; nodes with neither are omitted. This deliberately preserves the+ distinct per-query frequencies of teams still on v1 (whose DAG runs several schedules at+ different cadences) rather than flattening everything to a single DAG cadence. Read-only;+ the preview overlays these in memory, and a backfill can persist them.+ """+ seeds: dict[str, timedelta] = {}+ for node in Node.objects.filter(dag=dag).exclude(type=NodeType.TABLE).select_related("saved_query"):+ interval = None+ if node.saved_query is not None and node.saved_query.sync_frequency_interval is not None:+ interval = node.saved_query.sync_frequency_interval+ elif dag.sync_frequency_interval is not None:+ interval = dag.sync_frequency_interval+ if interval is not None:+ seeds[str(node.id)] = interval+ return seedsdiff --git a/products/data_modeling/backend/logic/schedule_reconcile.py b/products/data_modeling/backend/logic/schedule_reconcile.pynew file mode 100644index 000000000000..28ef7102bdd0--- /dev/null+++ b/products/data_modeling/backend/logic/schedule_reconcile.py@@ -0,0 +1,240 @@+"""Reconcile a DAG's Temporal schedules to its per-node freshness targets.++Replaces the single per-DAG `data-modeling-execute-dag` schedule with one schedule per+distinct effective cadence (a "cohort"), each scoped to that tier's node_ids. Idempotent:+computes the desired tiers from the current graph and creates/updates/deletes schedules so+Temporal matches, converging a DAG whether it currently has the old single schedule or N+tiered ones.++The tier/plan math is pure (`cohort_scheduling`); this module is the only part that talks to+the Temporal schedule API.+"""++import uuid+import dataclasses+from collections.abc import Iterable+from datetime import timedelta++from django.conf import settings++import structlog+from asgiref.sync import async_to_sync+from temporalio.client import (+ Client,+ Schedule,+ ScheduleActionStartWorkflow,+ ScheduleListActionStartWorkflow,+ ScheduleOverlapPolicy,+ SchedulePolicy,+ ScheduleState,+)+from temporalio.common import RetryPolicy++from posthog.temporal.common.client import async_connect+from posthog.temporal.common.schedule import a_create_schedule, a_delete_schedule, a_update_schedule+from posthog.temporal.common.search_attributes import POSTHOG_DAG_ID_KEY+from posthog.temporal.data_modeling.workflows.execute_dag import ExecuteDAGInputs++from products.data_modeling.backend.logic.cohort_scheduling import (+ ScheduleReconcilePlan,+ bucket_into_cadence_tiers,+ plan_schedule_reconciliation,+ tier_schedule_id,+)+from products.data_modeling.backend.logic.freshness import (+ SCHEDULABLE_BUCKETS,+ InvalidTarget,+ UnsupportedFrequencyTargetError,+ compute_effective_cadences,+ declared_target_bounds,+ find_invalid_targets,+ format_cadence,+ is_finer_than,+)+from products.data_modeling.backend.logic.node_frequency import FrequencyGraph, build_frequency_graph, seed_targets+from products.data_modeling.backend.models.dag import DAG+from products.data_modeling.backend.schedule import (+ DATA_MODELING_EXECUTE_DAG_WORKFLOW,+ build_schedule_spec,+ dag_schedule_search_attributes,+)++logger = structlog.get_logger(__name__)+++def reconcile_dag_schedules(dag: DAG) -> None:+ """Make Temporal's schedules for this DAG match its nodes' effective cadences."""+ team = dag.team+ graph = build_frequency_graph(dag)+ effective = compute_effective_cadences(+ nodes=graph.nodes, edges=graph.edges, declared_targets=graph.declared_targets+ )+ desired_tiers = bucket_into_cadence_tiers(effective)+ _apply_reconciliation(+ dag_id=str(dag.id),+ team_id=team.pk,+ organization_id=str(team.organization_id),+ team_timezone=team.timezone,+ desired_tiers=desired_tiers,+ )+++class UnsatisfiableTier:+ """A node scheduled finer than its slowest ancestor source can actually deliver."""++ node_id: str+ effective: timedelta # cadence it would be scheduled at+ source_floor: timedelta # slowest cadence its sources can actually deliver+++class DagSchedulePreview:+ """What reconcile would do for a DAG, computed read-only (no schedule writes)."""++ effective: dict[str, timedelta | None] # every schedulable node's resolved cadence+ desired_tiers: dict[timedelta, set[str]]+ plan: ScheduleReconcilePlan+ best_effort_source_ids: set[str] # sources whose freshness is not actually guaranteed+ unsatisfiable: list[UnsatisfiableTier] # effective finer than the source floor can honor+ invalid_targets: list[InvalidTarget] # declared targets that drifted outside their bounds+ unsupported_tiers: list[timedelta] # tiers reconcile would refuse (non-bucket cadence)+ seeded: bool # whether targets were seeded in-memory from current cadence+++def preview_dag_schedules(dag: DAG, *, seed: bool = False) -> DagSchedulePreview:+ """Compute the reconciliation a DAG would undergo, without creating/updating/deleting anything.++ Reads the graph and lists the DAG's current schedules; never writes. This is the dry-run+ behind the preview management command. With `seed`, nodes lacking an explicit target fall+ back in memory to `seed_targets(dag)`, modelling the go-live plan once targets are+ backfilled, without persisting anything (explicit targets still win).+ """+ graph = build_frequency_graph(dag)+ declared = {**seed_targets(dag), **graph.declared_targets} if seed else graph.declared_targets+ effective = compute_effective_cadences(nodes=graph.nodes, edges=graph.edges, declared_targets=declared)+ desired_tiers = bucket_into_cadence_tiers(effective)+ existing_ids = _list_existing_schedule_ids(str(dag.id))+ plan = plan_schedule_reconciliation(str(dag.id), desired_tiers, existing_ids)+ return DagSchedulePreview(+ effective=effective,+ desired_tiers=desired_tiers,+ plan=plan,+ best_effort_source_ids=graph.best_effort_source_ids,+ unsatisfiable=_find_unsatisfiable(graph, effective, declared),+ invalid_targets=find_invalid_targets(+ edges=graph.edges, declared_targets=declared, source_intervals=graph.source_intervals+ ),+ unsupported_tiers=sorted(interval for interval in desired_tiers if interval not in SCHEDULABLE_BUCKETS),+ seeded=seed,+ )+++def _find_unsatisfiable(+ graph: FrequencyGraph, effective: dict[str, timedelta | None], declared_targets: dict[str, timedelta]+) -> list[UnsatisfiableTier]:+ """Flag nodes whose scheduled cadence is finer than their ancestor sources can deliver."""+ flagged: list[UnsatisfiableTier] = []+ for node_id, node_effective in effective.items():+ if node_effective is None:+ continue+ source_floor, _consumer_ceiling = declared_target_bounds(+ node_id=node_id,+ edges=graph.edges,+ declared_targets=declared_targets,+ source_intervals=graph.source_intervals,+ )+ if is_finer_than(node_effective, source_floor):+ flagged.append(UnsatisfiableTier(node_id=node_id, effective=node_effective, source_floor=source_floor))+ return flagged+++@async_to_sync+async def _list_existing_schedule_ids(dag_id: str) -> set[str]:+ temporal = await async_connect()+ return await _list_execute_dag_schedule_ids(temporal, dag_id)+++@async_to_sync+async def _apply_reconciliation(+ *,+ dag_id: str,+ team_id: int,+ organization_id: str,+ team_timezone: str,+ desired_tiers: dict[timedelta, set[str]],+) -> None:+ unsupported = sorted(interval for interval in desired_tiers if interval not in SCHEDULABLE_BUCKETS)+ if unsupported:+ tiers = ", ".join(format_cadence(interval) for interval in unsupported)+ raise UnsupportedFrequencyTargetError(+ f"refusing to reconcile DAG {dag_id}: tiers ({tiers}) are not schedulable cadence buckets"+ )++ temporal = await async_connect()+ existing_ids = await _list_execute_dag_schedule_ids(temporal, dag_id)+ plan = plan_schedule_reconciliation(dag_id, desired_tiers, existing_ids)++ # Includes the schedule-type tag: get_v2_scheduled_dag_ids' unscoped sweep filters on+ # it server-side, so an untagged tier schedule would make its DAG look un-migrated.+ search_attributes = dag_schedule_search_attributes(team_id=team_id, organization_id=organization_id, dag_id=dag_id)++ # Create/update every desired tier before deleting stale schedules so nodes are never left+ # uncovered; on failure, best-effort-delete the tiers we created (already-applied updates+ # stay — a re-run converges) without letting a failed delete mask the original error.+ created: list[str] = []+ try:+ for schedule_id, (interval, node_ids) in plan.to_create.items():+ schedule = _build_tier_schedule(dag_id, team_id, team_timezone, interval, node_ids)+ await a_create_schedule(temporal, id=schedule_id, schedule=schedule, search_attributes=search_attributes)+ created.append(schedule_id)+ for schedule_id, (interval, node_ids) in plan.to_update.items():+ schedule = _build_tier_schedule(dag_id, team_id, team_timezone, interval, node_ids)+ await a_update_schedule(temporal, id=schedule_id, schedule=schedule, search_attributes=search_attributes)+ except Exception:+ for schedule_id in created:+ try:+ await a_delete_schedule(temporal, schedule_id=schedule_id)+ except Exception:+ logger.exception("Failed to roll back created schedule", schedule_id=schedule_id, dag_id=dag_id)+ raise++ for schedule_id in plan.to_delete:+ await a_delete_schedule(temporal, schedule_id=schedule_id)+++async def _list_execute_dag_schedule_ids(temporal: Client, dag_id: str) -> set[str]:+ schedules = await temporal.list_schedules(query=f"{POSTHOG_DAG_ID_KEY.name} = '{dag_id}'")+ ids: set[str] = set()+ async for listing in schedules:+ action = listing.schedule.action if listing.schedule else None+ if (+ isinstance(action, ScheduleListActionStartWorkflow)+ and action.workflow == DATA_MODELING_EXECUTE_DAG_WORKFLOW+ ):+ ids.add(listing.id)+ return ids+++def _build_tier_schedule(+ dag_id: str, team_id: int, team_timezone: str, interval: timedelta, node_ids: Iterable[str]+) -> Schedule:+ inputs = ExecuteDAGInputs(team_id=team_id, dag_id=dag_id, node_ids=sorted(node_ids), duckgres_only=False)+ spec = build_schedule_spec(entity_id=uuid.UUID(dag_id), interval=interval, team_timezone=team_timezone)+ return Schedule(+ action=ScheduleActionStartWorkflow(+ DATA_MODELING_EXECUTE_DAG_WORKFLOW,+ dataclasses.asdict(inputs),+ id=f"execute-dag-{tier_schedule_id(dag_id, interval)}",+ task_queue=str(settings.DATA_MODELING_TASK_QUEUE),+ retry_policy=RetryPolicy(+ initial_interval=timedelta(seconds=10),+ maximum_interval=timedelta(seconds=60),+ maximum_attempts=3,+ non_retryable_error_types=["NondeterminismError", "CancelledError"],+ ),+ ),+ spec=spec,+ state=ScheduleState(note=f"data-modeling DAG {dag_id} cadence tier {interval}"),+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),+ )diff --git a/products/data_modeling/backend/management/commands/preview_freshness_schedules.py b/products/data_modeling/backend/management/commands/preview_freshness_schedules.pynew file mode 100644index 000000000000..9bb90a391394--- /dev/null+++ b/products/data_modeling/backend/management/commands/preview_freshness_schedules.py@@ -0,0 +1,90 @@+import uuid++from django.core.management.base import BaseCommand, CommandError++from products.data_modeling.backend.logic.schedule_reconcile import DagSchedulePreview, preview_dag_schedules+from products.data_modeling.backend.models.dag import DAG+from products.data_modeling.backend.models.node import Node+++class Command(BaseCommand):+ help = (+ "Dry-run: show the per-cadence-tier schedules a DAG would get from its nodes' freshness "+ "targets, and the create/update/delete plan against its current schedules. Reads only — "+ "never creates, updates, or deletes a schedule, and touches no live read/write path."+ )++ def add_arguments(self, parser):+ parser.add_argument("--team-id", type=int, required=True)+ parser.add_argument("--dag-id", type=str, default=None, help="Limit to one DAG (default: all of the team's)")+ parser.add_argument(+ "--seed",+ action="store_true",+ help="Model the go-live plan: seed a target from current cadence for nodes without one (in memory, no write)",+ )++ def handle(self, *args, **options):+ queryset = DAG.objects.filter(team_id=options["team_id"])+ if options["dag_id"]:+ try:+ queryset = queryset.filter(id=uuid.UUID(options["dag_id"]))+ except ValueError:+ raise CommandError(f"--dag-id must be a UUID, got {options['dag_id']!r}")+ dags = list(queryset)+ if not dags:+ raise CommandError("No matching DAGs")+ for dag in dags:+ self._preview(dag, seed=options["seed"])+ self.stdout.write("\n(dry run — no schedules were created, updated, or deleted)")++ def _preview(self, dag: DAG, *, seed: bool) -> None:+ preview = preview_dag_schedules(dag, seed=seed)+ names = {str(node_id): name for node_id, name in Node.objects.filter(dag=dag).values_list("id", "name")}++ seeded_note = " [targets seeded from current cadence]" if preview.seeded else ""+ self.stdout.write(f"\nDAG {dag.name} ({dag.id}) — team {dag.team_id}{seeded_note}")++ self.stdout.write(" Effective cadences:")+ for node_id, interval in sorted(preview.effective.items(), key=lambda item: names.get(item[0], item[0])):+ cadence = str(interval) if interval is not None else "unscheduled"+ self.stdout.write(f" {names.get(node_id, node_id)}: {cadence}")++ self.stdout.write(" Desired tiers:")+ for interval, node_ids in sorted(preview.desired_tiers.items()):+ members = ", ".join(sorted(names.get(node_id, node_id) for node_id in node_ids))+ self.stdout.write(f" {interval}: {members}")++ self._print_plan(preview)++ for tier in sorted(preview.unsatisfiable, key=lambda t: names.get(t.node_id, t.node_id)):+ self.stdout.write(+ f" ⚠ unsatisfiable: {names.get(tier.node_id, tier.node_id)} would run every {tier.effective} "+ f"but its sources only deliver every {tier.source_floor}"+ )++ for interval in preview.unsupported_tiers:+ self.stdout.write(f" ⚠ unsupported tier: {interval} is not a schedulable bucket — reconcile would refuse")++ for invalid in sorted(preview.invalid_targets, key=lambda t: names.get(t.node_id, t.node_id)):+ ceiling = str(invalid.consumer_ceiling) if invalid.consumer_ceiling is not None else "none"+ self.stdout.write(+ f" ⚠ invalid declared target: {names.get(invalid.node_id, invalid.node_id)} declares "+ f"{invalid.declared} but its legal range is [{invalid.source_floor} … {ceiling}]"+ )++ if preview.best_effort_source_ids:+ flagged = ", ".join(sorted(names.get(node_id, node_id) for node_id in preview.best_effort_source_ids))+ self.stdout.write(f" ⚠ best-effort sources (freshness not guaranteed): {flagged}")++ def _print_plan(self, preview: DagSchedulePreview) -> None:+ plan = preview.plan+ self.stdout.write(" Plan vs current schedules:")+ if not (plan.to_create or plan.to_update or plan.to_delete):+ self.stdout.write(" (already in sync)")+ return+ for schedule_id, (interval, node_ids) in sorted(plan.to_create.items()):+ self.stdout.write(f" CREATE {schedule_id} ({interval}, {len(node_ids)} nodes)")+ for schedule_id, (interval, node_ids) in sorted(plan.to_update.items()):+ self.stdout.write(f" UPDATE {schedule_id} ({interval}, {len(node_ids)} nodes)")+ for schedule_id in sorted(plan.to_delete):+ self.stdout.write(f" DELETE {schedule_id}")diff --git a/products/data_modeling/backend/schedule.py b/products/data_modeling/backend/schedule.pyindex fc571ae34a25..1aec6cb8a92f 100644--- a/products/data_modeling/backend/schedule.py+++ b/products/data_modeling/backend/schedule.py@@ -28,6 +28,7 @@ from posthog.temporal.common.search_attributes import (POSTHOG_TEAM_ID_KEY,)+from products.data_modeling.backend.logic.cohort_scheduling import dag_id_from_schedule_idfrom products.data_modeling.backend.models import Nodeif TYPE_CHECKING:@@ -85,9 +86,7 @@ async def get_v2_scheduled_dag_ids(candidate_dag_ids: Collection[str] | None = Nisinstance(action, ScheduleListActionStartWorkflow)and action.workflow == DATA_MODELING_EXECUTE_DAG_WORKFLOW):- # A cadence-tier schedule id is "{dag_id}:{interval_seconds}"; a legacy id is the- # bare DAG id (no colon), which rsplit leaves untouched.- dag_ids.add(listing.id.rsplit(":", 1)[0])+ dag_ids.add(dag_id_from_schedule_id(listing.id))return dag_idsdiff --git a/products/data_modeling/backend/test/test_cohort_scheduling.py b/products/data_modeling/backend/test/test_cohort_scheduling.pynew file mode 100644index 000000000000..c1ee4554188d--- /dev/null+++ b/products/data_modeling/backend/test/test_cohort_scheduling.py@@ -0,0 +1,59 @@+from datetime import timedelta++from unittest import TestCase++from products.data_modeling.backend.logic.cohort_scheduling import (+ bucket_into_cadence_tiers,+ dag_id_from_schedule_id,+ plan_schedule_reconciliation,+ tier_schedule_id,+)++DAG_ID = "018f2a00-0000-0000-0000-000000000000"+M15 = timedelta(minutes=15)+H1 = timedelta(hours=1)+H6 = timedelta(hours=6)+++class TestBucketIntoCadenceTiers(TestCase):+ def test_groups_by_interval_and_drops_unscheduled(self):+ effective = {"a": M15, "b": M15, "c": H1, "d": None}+ self.assertEqual(bucket_into_cadence_tiers(effective), {M15: {"a", "b"}, H1: {"c"}})++ def test_empty_graph_has_no_tiers(self):+ self.assertEqual(bucket_into_cadence_tiers({}), {})+++class TestTierScheduleId(TestCase):+ def test_round_trip(self):+ schedule_id = tier_schedule_id(DAG_ID, M15)+ self.assertEqual(schedule_id, f"{DAG_ID}:900")+ self.assertEqual(dag_id_from_schedule_id(schedule_id), DAG_ID)++ def test_pre_tier_schedule_id_parses_to_itself(self):+ # migration-era schedules use the bare dag id (no colon); the read side must still resolve it+ self.assertEqual(dag_id_from_schedule_id(DAG_ID), DAG_ID)+++class TestPlanScheduleReconciliation(TestCase):+ def test_splits_into_create_update_and_delete(self):+ desired = {M15: {"a"}, H1: {"b", "c"}}+ existing = {tier_schedule_id(DAG_ID, H1), tier_schedule_id(DAG_ID, H6)}+ plan = plan_schedule_reconciliation(DAG_ID, desired, existing)+ self.assertEqual(plan.to_create, {tier_schedule_id(DAG_ID, M15): (M15, {"a"})})+ self.assertEqual(plan.to_update, {tier_schedule_id(DAG_ID, H1): (H1, {"b", "c"})})+ self.assertEqual(plan.to_delete, {tier_schedule_id(DAG_ID, H6)})++ def test_migration_era_single_schedule_is_swept_into_delete(self):+ # a DAG still on the old bare-dag-id schedule gets it deleted and replaced by tiers+ plan = plan_schedule_reconciliation(DAG_ID, {M15: {"a"}}, {DAG_ID})+ self.assertEqual(plan.to_create, {tier_schedule_id(DAG_ID, M15): (M15, {"a"})})+ self.assertEqual(plan.to_update, {})+ self.assertEqual(plan.to_delete, {DAG_ID})++ def test_removing_last_target_deletes_all_schedules(self):+ existing = {tier_schedule_id(DAG_ID, M15), tier_schedule_id(DAG_ID, H1)}+ plan = plan_schedule_reconciliation(DAG_ID, {}, existing)+ self.assertEqual(plan.to_create, {})+ self.assertEqual(plan.to_update, {})+ self.assertEqual(plan.to_delete, existing)diff --git a/products/data_modeling/backend/test/test_freshness.py b/products/data_modeling/backend/test/test_freshness.pynew file mode 100644index 000000000000..f4b293b670f0--- /dev/null+++ b/products/data_modeling/backend/test/test_freshness.py@@ -0,0 +1,230 @@+from datetime import timedelta++from unittest import TestCase++from parameterized import parameterized++from products.data_modeling.backend.logic.freshness import (+ SCHEDULABLE_BUCKETS,+ STREAMING,+ InvalidTarget,+ UnsatisfiableFrequencyError,+ UnsupportedFrequencyTargetError,+ compute_effective_cadences,+ declared_target_bounds,+ find_invalid_targets,+ validate_declared_target,+)++M5 = timedelta(minutes=5)+M15 = timedelta(minutes=15)+H1 = timedelta(hours=1)+H6 = timedelta(hours=6)+DAY = timedelta(days=1)+++class TestComputeEffectiveCadences(TestCase):+ @parameterized.expand(+ [+ # chain src->a->b: a with no target inherits b's target+ ("chain_inherits", {"a", "b"}, [("src", "a"), ("a", "b")], {"b": H1}, {"a": H1, "b": H1}),+ # diamond: shared parent mA takes the tightest of its two consumers+ (+ "diamond_takes_tightest_child",+ {"mA", "epA", "epB"},+ [("src", "mA"), ("mA", "epA"), ("mA", "epB")],+ {"epA": H1, "epB": M15},+ {"mA": M15, "epA": H1, "epB": M15},+ ),+ # own target tighter than children wins (you may be more frequent than consumers need)+ (+ "own_target_tighter_than_children",+ {"mA", "epA", "epB"},+ [("mA", "epA"), ("mA", "epB")],+ {"mA": M5, "epA": H1, "epB": M15},+ {"mA": M5, "epA": H1, "epB": M15},+ ),+ # transitive demand propagates past an intermediate node with no target+ (+ "transitive_two_levels",+ {"a", "b", "c", "d"},+ [("src", "a"), ("a", "b"), ("b", "c"), ("b", "d")],+ {"c": M15, "d": H1},+ {"a": M15, "b": M15, "c": M15, "d": H1},+ ),+ # a leaf with no target and no consumers is unscheduled; its None must not poison the parent+ (+ "unscheduled_leaf_is_none",+ {"a", "b"},+ [("a", "b")],+ {"a": H1},+ {"a": H1, "b": None},+ ),+ ]+ )+ def test_effective_cadence(self, _name, nodes, edges, targets, expected):+ self.assertEqual(compute_effective_cadences(nodes=nodes, edges=edges, declared_targets=targets), expected)++ def test_deep_chain_does_not_overflow(self):+ # prod DAGs can chain far past Python's recursion limit; propagation must stay iterative+ depth = 5000+ nodes = {f"n{i}" for i in range(depth)}+ edges = [(f"n{i}", f"n{i + 1}") for i in range(depth - 1)]+ result = compute_effective_cadences(nodes=nodes, edges=edges, declared_targets={f"n{depth - 1}": H1})+ self.assertEqual(result["n0"], H1)++ def test_cycle_raises_instead_of_hanging(self):+ # corrupt graphs exist in prod; a cycle must fail loud, not loop or overflow+ with self.assertRaisesRegex(ValueError, "cycle"):+ compute_effective_cadences(nodes={"a", "b"}, edges=[("a", "b"), ("b", "a")], declared_targets={"a": H1})+++class TestFrequencyTargetBounds(TestCase):+ @parameterized.expand(+ [+ # streamed source (events) imposes no floor -> a 15min endpoint is allowed+ (+ "streamed_source_no_floor",+ "ep",+ [("src", "ep")],+ {"ep": M15},+ {"src": STREAMING},+ (STREAMING, None),+ ),+ # imported source refreshing every 6h floors an intermediate node at 6h+ (+ "imported_source_floors",+ "a",+ [("src", "a"), ("a", "ep")],+ {"ep": H1},+ {"src": H6},+ (H6, H1),+ ),+ # ceiling comes from the tightest descendant demand+ (+ "ceiling_from_tightest_descendant",+ "a",+ [("src", "a"), ("a", "epA"), ("a", "epB")],+ {"epA": H1, "epB": M15},+ {"src": STREAMING},+ (STREAMING, M15),+ ),+ # floor above ceiling: no legal target exists (unsatisfiable)+ (+ "unsatisfiable_floor_above_ceiling",+ "a",+ [("src", "a"), ("a", "ep")],+ {"ep": M15},+ {"src": H6},+ (H6, M15),+ ),+ ]+ )+ def test_bounds(self, _name, node_id, edges, targets, source_intervals, expected):+ self.assertEqual(+ declared_target_bounds(+ node_id=node_id, edges=edges, declared_targets=targets, source_intervals=source_intervals+ ),+ expected,+ )+++class TestValidateFrequencyTarget(TestCase):+ @parameterized.expand(+ [+ # in range against a streamed source -> ok+ ("streamed_15min_ok", "a", M15, [("src", "a"), ("a", "ep")], {"ep": M15}, {"src": STREAMING}, True),+ # fresher than an imported source can deliver -> rejected+ ("below_imported_floor", "a", M15, [("src", "a")], {}, {"src": H6}, False),+ # staler than a downstream consumer needs -> rejected+ ("above_descendant_ceiling", "a", DAY, [("a", "ep")], {"ep": M15}, {}, False),+ # exactly on an imported floor -> ok+ ("on_imported_floor_ok", "a", H6, [("src", "a")], {}, {"src": H6}, True),+ # exactly on a descendant ceiling -> ok (bounds are inclusive at both ends)+ ("on_descendant_ceiling_ok", "a", M15, [("a", "ep")], {"ep": M15}, {}, True),+ # floor 6h > ceiling 15min: no target is accepted, at either end of the range+ ("unsatisfiable_rejects_floor_end", "a", H6, [("src", "a"), ("a", "ep")], {"ep": M15}, {"src": H6}, False),+ (+ "unsatisfiable_rejects_ceiling_end",+ "a",+ M15,+ [("src", "a"), ("a", "ep")],+ {"ep": M15},+ {"src": H6},+ False,+ ),+ ]+ )+ def test_validate(self, _name, node_id, target, edges, targets, source_intervals, ok):+ if ok:+ validate_declared_target(+ node_id=node_id, target=target, edges=edges, declared_targets=targets, source_intervals=source_intervals+ )+ else:+ with self.assertRaises(UnsatisfiableFrequencyError):+ validate_declared_target(+ node_id=node_id,+ target=target,+ edges=edges,+ declared_targets=targets,+ source_intervals=source_intervals,+ )++ @parameterized.expand(+ [+ # 45min would silently degrade to hourly in the spec builder+ ("non_divisor_of_hour", timedelta(minutes=45)),+ # sub-minute would crash the spec builder with a zero-division+ ("sub_minute", timedelta(seconds=30)),+ ]+ )+ def test_non_bucket_target_is_rejected(self, _name, target):+ with self.assertRaises(UnsupportedFrequencyTargetError):+ validate_declared_target(node_id="a", target=target, edges=[], declared_targets={}, source_intervals={})++ def test_supported_targets_are_canonical_sync_frequency_buckets(self):+ from products.warehouse_sources.backend.facade.models import ( # noqa: PLC0415 - keeps Django off this pure test module's import path+ sync_frequency_interval_to_sync_frequency,+ sync_frequency_to_sync_frequency_interval,+ )++ for interval in SCHEDULABLE_BUCKETS:+ label = sync_frequency_interval_to_sync_frequency(interval)+ self.assertIsNotNone(label, f"{interval} is not a canonical sync-frequency bucket")+ assert label is not None+ self.assertEqual(sync_frequency_to_sync_frequency_interval(label), interval)+++class TestFindInvalidTargets(TestCase):+ @parameterized.expand(+ [+ # descendant's 15min target lowers the ancestor's ceiling below its declared 6h+ (+ "ancestor_invalidated_by_descendant_target",+ [("src", "a"), ("a", "ep")],+ {"a": H6, "ep": M15},+ {"src": STREAMING},+ [InvalidTarget(node_id="a", declared=H6, source_floor=STREAMING, consumer_ceiling=M15)],+ ),+ # a source slowing down (6h import) pushes the floor above an existing 15min target+ (+ "target_below_drifted_source_floor",+ [("src", "a")],+ {"a": M15},+ {"src": H6},+ [InvalidTarget(node_id="a", declared=M15, source_floor=H6, consumer_ceiling=None)],+ ),+ # everything within bounds -> nothing flagged+ (+ "all_valid",+ [("src", "a"), ("a", "ep")],+ {"a": M15, "ep": M15},+ {"src": STREAMING},+ [],+ ),+ ]+ )+ def test_find_invalid_targets(self, _name, edges, targets, source_intervals, expected):+ self.assertEqual(+ find_invalid_targets(edges=edges, declared_targets=targets, source_intervals=source_intervals), expected+ )diff --git a/products/data_modeling/backend/test/test_node_frequency.py b/products/data_modeling/backend/test/test_node_frequency.pynew file mode 100644index 000000000000..5977d1852b56--- /dev/null+++ b/products/data_modeling/backend/test/test_node_frequency.py@@ -0,0 +1,219 @@+from datetime import timedelta++import pytest+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.models.team import Team++from products.data_modeling.backend.logic.freshness import (+ STREAMING,+ UnsatisfiableFrequencyError,+ compute_effective_cadences,+ declared_target_bounds,+ validate_declared_target,+)+from products.data_modeling.backend.logic.node_frequency import (+ build_frequency_graph,+ get_declared_target,+ resolve_source_intervals,+ seed_targets,+ set_declared_target,+)+from products.data_modeling.backend.models.dag import DAG+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_modeling.backend.models.edge import Edge+from products.data_modeling.backend.models.node import Node, NodeType+from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType++M15 = timedelta(minutes=15)+H1 = timedelta(hours=1)+H6 = timedelta(hours=6)+DAY = timedelta(days=1)+++def _table_node(team: Team, dag: DAG, name: str, properties: dict) -> Node:+ return Node.objects.create(team=team, dag=dag, name=name, type=NodeType.TABLE, properties=properties)+++def _saved_query_node(team: Team, dag: DAG, name: str, node_type: str) -> Node:+ saved_query = DataWarehouseSavedQuery.objects.create(+ name=name, team=team, query={"query": "SELECT 1", "kind": "HogQLQuery"}+ )+ return Node.objects.create(team=team, dag=dag, saved_query=saved_query, type=node_type)+++def _warehouse_source_node(+ team: Team,+ dag: DAG,+ *,+ sync_frequency_interval: timedelta | None,+ should_sync: bool = True,+ with_schema: bool = True,+) -> Node:+ table = DataWarehouseTable.objects.create(name="stripe_charges", team=team)+ if with_schema:+ source = ExternalDataSource.objects.create(+ team=team,+ source_id="source_id",+ connection_id="connection_id",+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.STRIPE,+ prefix="posthog_test_",+ )+ ExternalDataSchema.objects.create(+ name="stripe_charges",+ team=team,+ source=source,+ table=table,+ sync_frequency_interval=sync_frequency_interval,+ should_sync=should_sync,+ )+ return _table_node(team, dag, "stripe_charges", {"origin": "warehouse", "warehouse_table_id": str(table.id)})+++class TestFrequencyTargetAccessors(BaseTest):+ def _node(self) -> Node:+ return _table_node(self.team, DAG.get_or_create_default(self.team), "events", {"origin": "posthog"})++ def test_round_trip(self):+ node = self._node()+ set_declared_target(node, M15)+ node.refresh_from_db()+ self.assertEqual(get_declared_target(node), M15)++ def test_none_clears_the_target(self):+ node = self._node()+ set_declared_target(node, M15)+ set_declared_target(node, None)+ node.refresh_from_db()+ self.assertIsNone(get_declared_target(node))++ def test_setting_target_preserves_sibling_system_state(self):+ node = self._node()+ node.properties = {"system": {"suspended": {"duckdb": True}}}+ node.save(update_fields=["properties"])+ set_declared_target(node, H1)+ node.refresh_from_db()+ self.assertEqual(node.properties["system"]["suspended"], {"duckdb": True})+ self.assertEqual(get_declared_target(node), H1)+++class TestResolveSourceIntervals(BaseTest):+ @property+ def _dag(self) -> DAG:+ return DAG.get_or_create_default(self.team)++ def test_posthog_builtin_is_streaming_unflagged(self):+ node = _table_node(self.team, self._dag, "events", {"origin": "posthog"})+ intervals, best_effort = resolve_source_intervals([node])+ self.assertEqual(intervals, {str(node.id): STREAMING})+ self.assertEqual(best_effort, set())++ def test_unknown_origin_is_streaming_but_flagged(self):+ node = _table_node(self.team, self._dag, "mystery", {})+ intervals, best_effort = resolve_source_intervals([node])+ self.assertEqual(intervals, {str(node.id): STREAMING})+ self.assertEqual(best_effort, {str(node.id)})++ def test_scheduled_import_uses_its_interval(self):+ node = _warehouse_source_node(self.team, self._dag, sync_frequency_interval=H6)+ intervals, best_effort = resolve_source_intervals([node])+ self.assertEqual(intervals, {str(node.id): H6})+ self.assertEqual(best_effort, set())++ @parameterized.expand(+ [+ ("manual_never_synced", None, True),+ ("paused_schema", H6, False),+ ]+ )+ def test_unscheduled_import_is_streaming_but_flagged(self, _name, interval, should_sync):+ node = _warehouse_source_node(self.team, self._dag, sync_frequency_interval=interval, should_sync=should_sync)+ intervals, best_effort = resolve_source_intervals([node])+ self.assertEqual(intervals, {str(node.id): STREAMING})+ self.assertEqual(best_effort, {str(node.id)})+++class TestBuildFrequencyGraph(BaseTest):+ def test_endpoint_target_propagates_to_matview_over_streamed_source(self):+ dag = DAG.get_or_create_default(self.team)+ source = _table_node(self.team, dag, "events", {"origin": "posthog"})+ matview = _saved_query_node(self.team, dag, "mv", NodeType.MAT_VIEW)+ endpoint = _saved_query_node(self.team, dag, "ep", NodeType.ENDPOINT)+ Edge.objects.create(team=self.team, dag=dag, source=source, target=matview)+ Edge.objects.create(team=self.team, dag=dag, source=matview, target=endpoint)+ set_declared_target(endpoint, M15)++ graph = build_frequency_graph(dag)+ effective = compute_effective_cadences(+ nodes=graph.nodes, edges=graph.edges, declared_targets=graph.declared_targets+ )++ self.assertEqual(effective[str(matview.id)], M15)+ floor, _ceiling = declared_target_bounds(+ node_id=str(matview.id),+ edges=graph.edges,+ declared_targets=graph.declared_targets,+ source_intervals=graph.source_intervals,+ )+ self.assertEqual(floor, STREAMING)++ def test_imported_source_floor_makes_a_tighter_descendant_unsatisfiable(self):+ dag = DAG.get_or_create_default(self.team)+ source = _warehouse_source_node(self.team, dag, sync_frequency_interval=H6)+ matview = _saved_query_node(self.team, dag, "mv", NodeType.MAT_VIEW)+ Edge.objects.create(team=self.team, dag=dag, source=source, target=matview)++ graph = build_frequency_graph(dag)+ floor, _ceiling = declared_target_bounds(+ node_id=str(matview.id),+ edges=graph.edges,+ declared_targets=graph.declared_targets,+ source_intervals=graph.source_intervals,+ )+ self.assertEqual(floor, H6)+ with self.assertRaises(UnsatisfiableFrequencyError):+ validate_declared_target(+ node_id=str(matview.id),+ target=M15,+ edges=graph.edges,+ declared_targets=graph.declared_targets,+ source_intervals=graph.source_intervals,+ )+++class TestSeedTargets(BaseTest):+ def _view_node_in_dag_with(self, *, saved_query_interval, dag_interval) -> tuple[DAG, Node]:+ dag = DAG.objects.create(team=self.team, name="seed-demo", sync_frequency_interval=dag_interval)+ saved_query = DataWarehouseSavedQuery.objects.create(+ name="v",+ team=self.team,+ query={"query": "SELECT 1", "kind": "HogQLQuery"},+ sync_frequency_interval=saved_query_interval,+ )+ node = Node.objects.create(team=self.team, dag=dag, saved_query=saved_query, type=NodeType.VIEW)+ return dag, node++ @parameterized.expand(+ [+ ("saved_query_interval_wins", H1, DAY, H1),+ ("falls_back_to_dag_interval", None, DAY, DAY),+ ("no_signal_leaves_node_unseeded", None, None, None),+ ]+ )+ def test_seed(self, _name, saved_query_interval, dag_interval, expected):+ dag, node = self._view_node_in_dag_with(saved_query_interval=saved_query_interval, dag_interval=dag_interval)+ seeds = seed_targets(dag)+ self.assertEqual(seeds, {} if expected is None else {str(node.id): expected})++ def test_source_tables_are_never_seeded(self):+ dag = DAG.objects.create(team=self.team, name="seed-demo-src", sync_frequency_interval=H1)+ _table_node(self.team, dag, "events", {"origin": "posthog"})+ self.assertEqual(seed_targets(dag), {})diff --git a/products/data_modeling/backend/test/test_preview_freshness_schedules.py b/products/data_modeling/backend/test/test_preview_freshness_schedules.pynew file mode 100644index 000000000000..116c5c62a548--- /dev/null+++ b/products/data_modeling/backend/test/test_preview_freshness_schedules.py@@ -0,0 +1,141 @@+from datetime import timedelta+from io import StringIO++import pytest+from posthog.test.base import BaseTest+from unittest import mock++from django.core.management import call_command++from products.data_modeling.backend.logic.node_frequency import set_declared_target+from products.data_modeling.backend.models.dag import DAG+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_modeling.backend.models.edge import Edge+from products.data_modeling.backend.models.node import Node, NodeType++M15 = timedelta(minutes=15)+H6 = timedelta(hours=6)+++def _no_existing_schedules():+ async def fake_list_schedules(*_args, **_kwargs):+ async def gen():+ return+ yield # pragma: no cover — empty async generator++ return gen()++ temporal = mock.Mock()+ temporal.list_schedules = fake_list_schedules+ return temporal+++def _table_node(team, dag, name, properties):+ return Node.objects.create(team=team, dag=dag, name=name, type=NodeType.TABLE, properties=properties)+++def _saved_query_node(team, dag, name, node_type):+ saved_query = DataWarehouseSavedQuery.objects.create(+ name=name, team=team, query={"query": "SELECT 1", "kind": "HogQLQuery"}+ )+ return Node.objects.create(team=team, dag=dag, saved_query=saved_query, type=node_type)+++class TestPreviewFreshnessSchedules(BaseTest):+ def test_previews_tiers_without_touching_any_schedule(self):+ dag = DAG.get_or_create_default(self.team)+ source = _table_node(self.team, dag, "events", {"origin": "posthog"})+ matview = _saved_query_node(self.team, dag, "mv", NodeType.MAT_VIEW)+ endpoint = _saved_query_node(self.team, dag, "ep", NodeType.ENDPOINT)+ Edge.objects.create(team=self.team, dag=dag, source=source, target=matview)+ Edge.objects.create(team=self.team, dag=dag, source=matview, target=endpoint)+ set_declared_target(endpoint, M15)++ async def fake_list_schedules(*_args, **_kwargs):+ async def gen():+ return+ yield # pragma: no cover — empty async generator++ return gen()++ temporal = mock.Mock()+ temporal.list_schedules = fake_list_schedules++ module = "products.data_modeling.backend.logic.schedule_reconcile"+ out = StringIO()+ with (+ mock.patch(f"{module}.async_connect", new=mock.AsyncMock(return_value=temporal)),+ mock.patch(f"{module}.a_create_schedule", new=mock.AsyncMock()) as create,+ mock.patch(f"{module}.a_update_schedule", new=mock.AsyncMock()) as update,+ mock.patch(f"{module}.a_delete_schedule", new=mock.AsyncMock()) as delete,+ ):+ call_command("preview_freshness_schedules", "--team-id", str(self.team.pk), stdout=out)++ # dry-run must not create, update, or delete any schedule+ create.assert_not_called()+ update.assert_not_called()+ delete.assert_not_called()++ output = out.getvalue()+ self.assertIn("CREATE", output)+ self.assertIn("0:15:00", output)+ self.assertIn("dry run", output)++ def test_seed_mode_models_go_live_from_current_cadence(self):+ # a DAG on a 6h cadence with no per-node targets: raw would schedule nothing, --seed+ # reproduces today's 6h cadence as a tier so go-live doesn't unschedule it.+ dag = DAG.objects.create(team=self.team, name="on-6h", sync_frequency_interval=H6)+ _saved_query_node(self.team, dag, "v", NodeType.VIEW)++ module = "products.data_modeling.backend.logic.schedule_reconcile"+ out = StringIO()+ with (+ mock.patch(f"{module}.async_connect", new=mock.AsyncMock(return_value=_no_existing_schedules())),+ mock.patch(f"{module}.a_create_schedule", new=mock.AsyncMock()) as create,+ mock.patch(f"{module}.a_delete_schedule", new=mock.AsyncMock()) as delete,+ ):+ call_command(+ "preview_freshness_schedules",+ "--team-id",+ str(self.team.pk),+ "--dag-id",+ str(dag.id),+ "--seed",+ stdout=out,+ )++ create.assert_not_called()+ delete.assert_not_called()+ output = out.getvalue()+ self.assertIn("seeded from current cadence", output)+ self.assertIn("CREATE", output)+ self.assertIn("6:00:00", output)++ def test_flags_unsupported_tier_and_invalid_declared_target(self):+ # go-live audit: a 45min legacy cadence (seeded) must be flagged as unschedulable, and a+ # declared target drifted above its descendant's demand must be flagged as invalid+ dag = DAG.objects.create(team=self.team, name="odd-cadence", sync_frequency_interval=timedelta(minutes=45))+ _saved_query_node(self.team, dag, "legacy_view", NodeType.VIEW)+ matview = _saved_query_node(self.team, dag, "mv", NodeType.MAT_VIEW)+ endpoint = _saved_query_node(self.team, dag, "ep", NodeType.ENDPOINT)+ Edge.objects.create(team=self.team, dag=dag, source=matview, target=endpoint)+ set_declared_target(matview, H6)+ set_declared_target(endpoint, M15)++ module = "products.data_modeling.backend.logic.schedule_reconcile"+ out = StringIO()+ with mock.patch(f"{module}.async_connect", new=mock.AsyncMock(return_value=_no_existing_schedules())):+ call_command(+ "preview_freshness_schedules",+ "--team-id",+ str(self.team.pk),+ "--dag-id",+ str(dag.id),+ "--seed",+ stdout=out,+ )++ output = out.getvalue()+ self.assertIn("unsupported tier: 0:45:00", output)+ self.assertIn("invalid declared target: mv", output)diff --git a/products/data_modeling/backend/test/test_schedule_reconcile.py b/products/data_modeling/backend/test/test_schedule_reconcile.pynew file mode 100644index 000000000000..4d5d2b07f1f6--- /dev/null+++ b/products/data_modeling/backend/test/test_schedule_reconcile.py@@ -0,0 +1,222 @@+from datetime import timedelta++import pytest+from posthog.test.base import BaseTest+from unittest import TestCase, mock++from parameterized import parameterized+from temporalio.client import ScheduleListActionStartWorkflow++from posthog.temporal.common.search_attributes import POSTHOG_SCHEDULE_TYPE_KEY++from products.data_modeling.backend.logic.cohort_scheduling import tier_schedule_id+from products.data_modeling.backend.logic.freshness import STREAMING, UnsupportedFrequencyTargetError+from products.data_modeling.backend.logic.node_frequency import FrequencyGraph, set_declared_target+from products.data_modeling.backend.logic.schedule_reconcile import _find_unsatisfiable, reconcile_dag_schedules+from products.data_modeling.backend.models.dag import DAG+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery+from products.data_modeling.backend.models.edge import Edge+from products.data_modeling.backend.models.node import Node, NodeType+from products.data_modeling.backend.schedule import DATA_MODELING_EXECUTE_DAG_WORKFLOW++M15 = timedelta(minutes=15)+H1 = timedelta(hours=1)+H6 = timedelta(hours=6)+++def _table_node(team, dag, name, properties):+ return Node.objects.create(team=team, dag=dag, name=name, type=NodeType.TABLE, properties=properties)+++def _saved_query_node(team, dag, name, node_type):+ saved_query = DataWarehouseSavedQuery.objects.create(+ name=name, team=team, query={"query": "SELECT 1", "kind": "HogQLQuery"}+ )+ return Node.objects.create(team=team, dag=dag, saved_query=saved_query, type=node_type)+++def _listing(schedule_id, workflow="data-modeling-execute-dag"):+ action = mock.Mock(spec=ScheduleListActionStartWorkflow, workflow=workflow)+ return mock.Mock(id=schedule_id, schedule=mock.Mock(action=action))+++class TestReconcileDagSchedules(BaseTest):+ def test_creates_tier_scoped_schedule_and_deletes_stale_one(self):+ dag = DAG.get_or_create_default(self.team)+ source = _table_node(self.team, dag, "events", {"origin": "posthog"})+ matview = _saved_query_node(self.team, dag, "mv", NodeType.MAT_VIEW)+ endpoint = _saved_query_node(self.team, dag, "ep", NodeType.ENDPOINT)+ Edge.objects.create(team=self.team, dag=dag, source=source, target=matview)+ Edge.objects.create(team=self.team, dag=dag, source=matview, target=endpoint)+ set_declared_target(endpoint, M15)++ dag_id = str(dag.id)+ stale_id = tier_schedule_id(dag_id, H1)++ async def fake_list_schedules(*_args, **_kwargs):+ async def gen():+ yield _listing(stale_id)++ return gen()++ temporal = mock.Mock()+ temporal.list_schedules = fake_list_schedules++ module = "products.data_modeling.backend.logic.schedule_reconcile"+ with (+ mock.patch(f"{module}.async_connect", new=mock.AsyncMock(return_value=temporal)),+ mock.patch(f"{module}.a_create_schedule", new=mock.AsyncMock()) as create,+ mock.patch(f"{module}.a_update_schedule", new=mock.AsyncMock()) as update,+ mock.patch(f"{module}.a_delete_schedule", new=mock.AsyncMock()) as delete,+ ):+ reconcile_dag_schedules(dag)++ # one 15min tier created, scoped to exactly the two schedulable nodes+ create.assert_called_once()+ self.assertEqual(create.call_args.kwargs["id"], tier_schedule_id(dag_id, M15))+ created_inputs = create.call_args.kwargs["schedule"].action.args[0]+ self.assertEqual(sorted(created_inputs["node_ids"]), sorted([str(matview.id), str(endpoint.id)]))++ # tagged with the schedule type: get_v2_scheduled_dag_ids' unscoped sweep filters on it,+ # so an untagged tier schedule would make its DAG look un-migrated+ created_attrs = {pair.key.name: pair.value for pair in create.call_args.kwargs["search_attributes"]}+ self.assertEqual(created_attrs[POSTHOG_SCHEDULE_TYPE_KEY.name], DATA_MODELING_EXECUTE_DAG_WORKFLOW)++ # the stale H1 schedule is removed; nothing to update+ update.assert_not_called()+ delete.assert_called_once_with(temporal, schedule_id=stale_id)++ def test_rewrites_persisting_tier_without_create_or_delete(self):+ dag = DAG.get_or_create_default(self.team)+ source = _table_node(self.team, dag, "events", {"origin": "posthog"})+ matview = _saved_query_node(self.team, dag, "mv", NodeType.MAT_VIEW)+ endpoint = _saved_query_node(self.team, dag, "ep", NodeType.ENDPOINT)+ Edge.objects.create(team=self.team, dag=dag, source=source, target=matview)+ Edge.objects.create(team=self.team, dag=dag, source=matview, target=endpoint)+ set_declared_target(endpoint, M15)++ dag_id = str(dag.id)+ existing_id = tier_schedule_id(dag_id, M15)++ async def fake_list_schedules(*_args, **_kwargs):+ async def gen():+ yield _listing(existing_id)++ return gen()++ temporal = mock.Mock()+ temporal.list_schedules = fake_list_schedules++ module = "products.data_modeling.backend.logic.schedule_reconcile"+ with (+ mock.patch(f"{module}.async_connect", new=mock.AsyncMock(return_value=temporal)),+ mock.patch(f"{module}.a_create_schedule", new=mock.AsyncMock()) as create,+ mock.patch(f"{module}.a_update_schedule", new=mock.AsyncMock()) as update,+ mock.patch(f"{module}.a_delete_schedule", new=mock.AsyncMock()) as delete,+ ):+ reconcile_dag_schedules(dag)++ # the 15min tier already exists, so it is rewritten in place — no create, no delete+ update.assert_called_once()+ self.assertEqual(update.call_args.kwargs["id"], existing_id)+ create.assert_not_called()+ delete.assert_not_called()++ def test_rolls_back_created_tiers_and_keeps_legacy_schedule_on_failure(self):+ dag = DAG.get_or_create_default(self.team)+ source = _table_node(self.team, dag, "events", {"origin": "posthog"})+ ep_fast = _saved_query_node(self.team, dag, "fast", NodeType.ENDPOINT)+ ep_slow = _saved_query_node(self.team, dag, "slow", NodeType.ENDPOINT)+ Edge.objects.create(team=self.team, dag=dag, source=source, target=ep_fast)+ Edge.objects.create(team=self.team, dag=dag, source=source, target=ep_slow)+ set_declared_target(ep_fast, M15)+ set_declared_target(ep_slow, H6)++ legacy_id = str(dag.id) # migration-era single schedule, slated for deletion once tiers exist++ async def fake_list_schedules(*_args, **_kwargs):+ async def gen():+ yield _listing(legacy_id)++ return gen()++ temporal = mock.Mock()+ temporal.list_schedules = fake_list_schedules++ created_ids: list[str] = []++ async def failing_create(*_args, **kwargs):+ created_ids.append(kwargs["id"])+ if len(created_ids) >= 2: # second tier creation fails partway through the migration+ raise RuntimeError("temporal unavailable")++ module = "products.data_modeling.backend.logic.schedule_reconcile"+ with (+ mock.patch(f"{module}.async_connect", new=mock.AsyncMock(return_value=temporal)),+ mock.patch(f"{module}.a_create_schedule", new=mock.AsyncMock(side_effect=failing_create)),+ mock.patch(f"{module}.a_update_schedule", new=mock.AsyncMock()),+ mock.patch(f"{module}.a_delete_schedule", new=mock.AsyncMock()) as delete,+ ):+ with self.assertRaises(RuntimeError):+ reconcile_dag_schedules(dag)++ # the one successfully-created tier is rolled back; the legacy schedule is never deleted,+ # so the DAG stays fully covered at its current cadence rather than opening a gap+ delete.assert_called_once_with(temporal, schedule_id=created_ids[0])+ self.assertNotEqual(created_ids[0], legacy_id)++ def test_refuses_non_bucket_tier_before_touching_temporal(self):+ # the guard must fire before any Temporal call — a non-bucket tier would crash+ # build_schedule_spec mid-apply and leave the DAG partially reconciled+ dag = DAG.get_or_create_default(self.team)+ source = _table_node(self.team, dag, "events", {"origin": "posthog"})+ endpoint = _saved_query_node(self.team, dag, "ep", NodeType.ENDPOINT)+ Edge.objects.create(team=self.team, dag=dag, source=source, target=endpoint)+ set_declared_target(endpoint, timedelta(minutes=45))++ module = "products.data_modeling.backend.logic.schedule_reconcile"+ with mock.patch(f"{module}.async_connect", new=mock.AsyncMock()) as connect:+ with self.assertRaises(UnsupportedFrequencyTargetError):+ reconcile_dag_schedules(dag)+ connect.assert_not_called()+++class TestFindUnsatisfiable(TestCase):+ @parameterized.expand(+ [+ # scheduled finer than the 6h source delivers -> flagged+ ("finer_than_source_floor", M15, H6, True),+ # exactly at the floor -> satisfiable+ ("at_floor", H6, H6, False),+ # coarser than the floor -> satisfiable+ ("coarser_than_floor", H6, H1, False),+ # streamed source imposes no floor -> satisfiable at any cadence+ ("streamed_source", M15, STREAMING, False),+ ]+ )+ def test_flags_node_finer_than_its_source(self, _name, effective, source_interval, flagged):+ graph = FrequencyGraph(+ nodes={"a"},+ edges=[("src", "a")],+ declared_targets={"a": effective},+ source_intervals={"src": source_interval},+ best_effort_source_ids=set(),+ )+ result = _find_unsatisfiable(graph, {"a": effective}, {"a": effective})+ if flagged:+ self.assertEqual(len(result), 1)+ self.assertEqual(result[0].node_id, "a")+ self.assertEqual(result[0].source_floor, source_interval)+ else:+ self.assertEqual(result, [])++ def test_unscheduled_node_is_never_flagged(self):+ graph = FrequencyGraph(+ nodes={"a"},+ edges=[("src", "a")],+ declared_targets={},+ source_intervals={"src": H6},+ best_effort_source_ids=set(),+ )+ self.assertEqual(_find_unsatisfiable(graph, {"a": None}, {}), [])