Skip to content

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

feat(data-modeling): per-node schedule anchors for cadence tiers (#75411)

Jovan Sakovic5e238fcb63e8
diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.py
index b959ea9ab9cf..78d8a4c8ca3b 100644
--- a/products/data_modeling/backend/facade/api.py
+++ b/products/data_modeling/backend/facade/api.py
@@ -21,6 +21,7 @@ _LAZY = {
"materialize_saved_query": "logic.node_materialization",
"saved_query_materialized_at": "logic.saved_query_freshness",
"start_node_materialization": "logic.node_materialization",
+ "apply_saved_query_frequency_anchor": "logic.schedule_reconcile",
"apply_saved_query_frequency_target": "logic.schedule_reconcile",
"tiered_schedules_enabled": "logic.schedule_reconcile",
"declared_targets_by_saved_query": "logic.node_frequency",
diff --git a/products/data_modeling/backend/logic/cohort_scheduling.py b/products/data_modeling/backend/logic/cohort_scheduling.py
index baafbe0b898d..cfce8bd76f31 100644
--- a/products/data_modeling/backend/logic/cohort_scheduling.py
+++ b/products/data_modeling/backend/logic/cohort_scheduling.py
@@ -12,27 +12,100 @@ alongside it and is the only part that touches the schedule API.
import dataclasses
from collections import defaultdict
from datetime import timedelta
+from typing import NamedTuple
+from products.data_modeling.backend.logic.freshness import format_cadence
-def bucket_into_cadence_tiers(effective: dict[str, timedelta | None]) -> dict[timedelta, set[str]]:
- """Group schedulable nodes by effective cadence.
+# An anchor is minutes past Monday 00:00 UTC. Every sub-weekly bucket divides the day,
+# so for those only `anchor % MINUTES_PER_DAY` (the time-of-day part) matters; a weekly
+# cadence reads the full value and gets day-of-week pinning from the same mod rule.
+MINUTES_PER_DAY = 24 * 60
+MINUTES_PER_WEEK = 7 * MINUTES_PER_DAY
+
+
+class Tier(NamedTuple):
+ """One schedule cohort: a cadence, plus an optional pinned phase.
+
+ `anchor_minutes=None` is the default hash-spread cohort; an anchored cohort fires at
+ times t ≡ anchor (mod interval), with t counted from the start of the UTC week.
+ """
+
+ interval: timedelta
+ anchor_minutes: int | None = None
+
+
+def tier_sort_key(tier: Tier) -> tuple[timedelta, int]:
+ """Display order: by cadence, the hash-spread cohort before anchored ones.
+
+ Sorting raw Tier tuples raises when a cadence has both an anchored and an unanchored
+ cohort, because `None` and `int` anchors don't compare.
+ """
+ return (tier.interval, -1 if tier.anchor_minutes is None else tier.anchor_minutes)
+
+
+def canonical_anchor(interval: timedelta, anchor_minutes: int) -> int:
+ """Reduce an anchor to the phase the schedule spec actually uses at this cadence.
+
+ Sub-weekly buckets divide the day, so only `anchor mod interval` matters; weekly reads
+ the full week offset; monthly pins time-of-day only (day of month stays hash-picked).
+ Raw anchors equal after reduction describe the same fire calendar, so they must key the
+ same cohort — one schedule, one run.
+ """
+ if interval <= timedelta(days=1):
+ return anchor_minutes % max(1, int(interval.total_seconds() // 60))
+ if interval <= timedelta(days=7):
+ return anchor_minutes % MINUTES_PER_WEEK
+ return anchor_minutes % MINUTES_PER_DAY
+
+
+def format_tier(tier: Tier) -> str:
+ """Human label for a tier: the cadence, plus the anchor phase when one is pinned.
+
+ Shows only what the spec uses: a weekday appears for weekly tiers alone — sub-weekly
+ specs ignore the day part, and monthly's day of month is hash-picked, not anchored.
+ """
+ if tier.anchor_minutes is None:
+ return format_cadence(tier.interval)
+ anchor = canonical_anchor(tier.interval, tier.anchor_minutes)
+ day, time_of_day = divmod(anchor, MINUTES_PER_DAY)
+ clock = f"{time_of_day // 60:02d}:{time_of_day % 60:02d}"
+ if timedelta(days=1) < tier.interval <= timedelta(days=7):
+ days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
+ return f"{format_cadence(tier.interval)}@{days[day]} {clock}"
+ return f"{format_cadence(tier.interval)}@{clock}"
+
+
+def bucket_into_cadence_tiers(
+ effective: dict[str, timedelta | None],
+ anchors: dict[str, int] | None = None,
+) -> dict[Tier, set[str]]:
+ """Group schedulable nodes into cohorts by (effective cadence, canonical anchor).
Nodes with no effective cadence (`None` — unscheduled, ride-downstream) are omitted so
- they never get a schedule of their own.
+ they never get a schedule of their own; an anchor on such a node is stored but inert.
+ Nodes sharing a cadence but not an anchor land in separate cohorts, because a cohort
+ is one Temporal schedule with one fire phase.
"""
- tiers: dict[timedelta, set[str]] = defaultdict(set)
+ tiers: dict[Tier, set[str]] = defaultdict(set)
for node_id, interval in effective.items():
if interval is not None:
- tiers[interval].add(node_id)
+ anchor = anchors.get(node_id) if anchors else None
+ if anchor is not None:
+ anchor = canonical_anchor(interval, anchor)
+ tiers[Tier(interval, anchor)].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}".
+def tier_schedule_id(dag_id: str, interval: timedelta, anchor_minutes: int | None = None) -> str:
+ """Temporal schedule id for one cohort of a DAG: "{dag_id}:{interval_seconds}", with
+ ":{anchor_minutes}" appended for an anchored cohort.
- A DAG UUID never contains a colon, so the dag id parses back off the prefix.
+ A DAG UUID never contains a colon, so the dag id parses back off the first segment.
"""
- return f"{dag_id}:{int(interval.total_seconds())}"
+ schedule_id = f"{dag_id}:{int(interval.total_seconds())}"
+ if anchor_minutes is not None:
+ schedule_id += f":{anchor_minutes}"
+ return schedule_id
def dag_id_from_schedule_id(schedule_id: str) -> str:
@@ -41,7 +114,7 @@ def dag_id_from_schedule_id(schedule_id: str) -> str:
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]
+ return schedule_id.split(":", 1)[0]
def is_tier_schedule_id(schedule_id: str) -> bool:
@@ -49,22 +122,36 @@ def is_tier_schedule_id(schedule_id: str) -> bool:
return ":" in schedule_id
+def interval_seconds_from_schedule_id(schedule_id: str) -> int | None:
+ """Recover the tier's cadence (seconds) from its schedule id, or None for the legacy
+ single schedule. An anchored id's trailing anchor segment is ignored."""
+ if is_tier_schedule_id(schedule_id):
+ return int(schedule_id.split(":")[1])
+ return None
+
+
+def anchor_minutes_from_schedule_id(schedule_id: str) -> int | None:
+ """The anchored cohort's pinned phase from its schedule id, or None when hash-spread."""
+ parts = schedule_id.split(":")
+ return int(parts[2]) if len(parts) > 2 else None
+
+
@dataclasses.dataclass
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.
+ (tier, 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_create: dict[str, tuple[Tier, set[str]]]
+ to_update: dict[str, tuple[Tier, set[str]]]
to_delete: set[str]
def plan_schedule_reconciliation(
dag_id: str,
- desired_tiers: dict[timedelta, set[str]],
+ desired_tiers: dict[Tier, set[str]],
existing_schedule_ids: set[str],
) -> ScheduleReconcilePlan:
"""Diff desired cadence tiers against a DAG's existing execute-dag schedules.
@@ -73,7 +160,10 @@ def plan_schedule_reconciliation(
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()}
+ desired = {
+ tier_schedule_id(dag_id, tier.interval, tier.anchor_minutes): (tier, node_ids)
+ for tier, 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},
diff --git a/products/data_modeling/backend/logic/node_frequency.py b/products/data_modeling/backend/logic/node_frequency.py
index cc3cf0a32d24..1a8b24c1aef3 100644
--- a/products/data_modeling/backend/logic/node_frequency.py
+++ b/products/data_modeling/backend/logic/node_frequency.py
@@ -14,6 +14,7 @@ from datetime import timedelta
from django.db.models import Q, QuerySet
+from products.data_modeling.backend.logic.cohort_scheduling import MINUTES_PER_WEEK
from products.data_modeling.backend.logic.freshness import STREAMING, all_source_floors, normalize_seed_target
from products.data_modeling.backend.models.dag import DAG
from products.data_modeling.backend.models.edge import Edge
@@ -24,6 +25,7 @@ from products.warehouse_sources.backend.facade.models import DataWarehouseTable,
_SYSTEM_KEY = "system"
_FREQUENCY_KEY = "frequency"
_TARGET_SECONDS_KEY = "target_seconds"
+_ANCHOR_MINUTES_KEY = "anchor_minutes"
# `resolve_dependency_to_node` stamps this on source (TABLE) nodes at creation.
_ORIGIN_KEY = "origin"
@@ -69,6 +71,25 @@ def set_declared_target(node: Node, target: timedelta | None) -> None:
node.save(update_fields=["properties"])
+def get_declared_anchor(node: Node) -> int | None:
+ """Return the node's declared schedule anchor (minutes past Monday 00:00 UTC), or None."""
+ return (node.properties or {}).get(_SYSTEM_KEY, {}).get(_FREQUENCY_KEY, {}).get(_ANCHOR_MINUTES_KEY)
+
+
+def set_declared_anchor(node: Node, anchor_minutes: int | None) -> None:
+ """Set (or clear, with None) the node's schedule anchor without touching sibling system state."""
+ if anchor_minutes is not None and not 0 <= anchor_minutes < MINUTES_PER_WEEK:
+ raise ValueError(f"anchor_minutes must be in [0, {MINUTES_PER_WEEK}), got {anchor_minutes}")
+ properties = node.properties or {}
+ frequency = properties.setdefault(_SYSTEM_KEY, {}).setdefault(_FREQUENCY_KEY, {})
+ if anchor_minutes is None:
+ frequency.pop(_ANCHOR_MINUTES_KEY, None)
+ else:
+ frequency[_ANCHOR_MINUTES_KEY] = anchor_minutes
+ 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.
@@ -154,6 +175,7 @@ class FrequencyGraph:
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
+ declared_anchors: dict[str, int] # declared per-node schedule anchors (minutes past Monday 00:00 UTC)
source_intervals: dict[str, timedelta] # per source (TABLE) node
best_effort_source_ids: set[str] # sources treated as STREAMING but not guaranteed
@@ -168,10 +190,14 @@ def build_frequency_graph(dag: DAG) -> FrequencyGraph:
schedulable = {str(node.id) for node in nodes if node.type != NodeType.TABLE}
declared_targets: dict[str, timedelta] = {}
+ declared_anchors: dict[str, int] = {}
for node in nodes:
target = get_declared_target(node)
if target is not None:
declared_targets[str(node.id)] = target
+ anchor = get_declared_anchor(node)
+ if anchor is not None:
+ declared_anchors[str(node.id)] = anchor
source_nodes = [node for node in nodes if node.type == NodeType.TABLE]
source_intervals, best_effort = resolve_source_intervals(source_nodes)
@@ -180,6 +206,7 @@ def build_frequency_graph(dag: DAG) -> FrequencyGraph:
nodes=schedulable,
edges=edges,
declared_targets=declared_targets,
+ declared_anchors=declared_anchors,
source_intervals=source_intervals,
best_effort_source_ids=best_effort,
)
diff --git a/products/data_modeling/backend/logic/schedule_reconcile.py b/products/data_modeling/backend/logic/schedule_reconcile.py
index 9f131ee5cf1e..e9f81d8d8aa9 100644
--- a/products/data_modeling/backend/logic/schedule_reconcile.py
+++ b/products/data_modeling/backend/logic/schedule_reconcile.py
@@ -47,7 +47,9 @@ from posthog.temporal.common.schedule import (
from posthog.temporal.common.search_attributes import POSTHOG_DAG_ID_KEY
from products.data_modeling.backend.logic.cohort_scheduling import (
+ MINUTES_PER_WEEK,
ScheduleReconcilePlan,
+ Tier,
bucket_into_cadence_tiers,
is_tier_schedule_id,
plan_schedule_reconciliation,
@@ -70,6 +72,7 @@ from products.data_modeling.backend.logic.node_frequency import (
persist_seed_targets,
schedulable_nodes,
seed_targets,
+ set_declared_anchor,
set_declared_target,
)
from products.data_modeling.backend.models.dag import DAG
@@ -223,8 +226,12 @@ def apply_saved_query_frequency_target(
"""
written = 0
with transaction.atomic():
- for node in Node.objects.filter(team=saved_query.team, saved_query=saved_query).select_related(
- "dag", "dag__team"
+ # target and anchor share one JSON field and each setter rewrites the whole blob, so an
+ # unlocked read-modify-write racing the anchor path would silently drop the other's key
+ for node in (
+ Node.objects.select_for_update(of=("self",))
+ .filter(team=saved_query.team, saved_query=saved_query)
+ .select_related("dag", "dag__team")
):
if target is None:
set_declared_target(node, None)
@@ -244,7 +251,34 @@ def apply_saved_query_frequency_target(
return written
-def reconcile_dag_schedules(dag: DAG, *, require_tiered: bool = False, graph: FrequencyGraph | None = None) -> None:
+def apply_saved_query_frequency_anchor(
+ saved_query: "DataWarehouseSavedQuery", anchor_minutes: int | None, *, reconcile: bool = True
+) -> int:
+ """Write a schedule anchor through to the DAG node(s) carrying this saved query.
+
+ The anchor pins the fire phase of whatever cohort the node lands in (minutes past
+ Monday 00:00 UTC); `anchor_minutes=None` clears it back to hash-spread. Returns the
+ number of nodes written (0 = no DAG node, so a non-None anchor was stored nowhere).
+ """
+ if anchor_minutes is not None and not 0 <= anchor_minutes < MINUTES_PER_WEEK:
+ raise ValueError(f"anchor_minutes must be in [0, {MINUTES_PER_WEEK}), got {anchor_minutes}")
+ written = 0
+ # atomic + row locks for the same reasons as the target path: all-or-nothing across a
+ # multi-DAG duplicate's nodes, and no lost update against a concurrent target write
+ with transaction.atomic():
+ for node in (
+ Node.objects.select_for_update(of=("self",))
+ .filter(team=saved_query.team, saved_query=saved_query)
+ .select_related("dag", "dag__team")
+ ):
+ set_declared_anchor(node, anchor_minutes)
+ written += 1
+ if reconcile:
+ maybe_reconcile_dag(node.dag)
+ return written
+
+
+def reconcile_dag_schedules(dag: DAG, *, require_tiered: bool = False, graph: FrequencyGraph | None = None) -> bool:
"""Make Temporal's schedules for this DAG match its nodes' effective cadences.
Converging a covered DAG to zero schedules is refused only while it still has just legacy
@@ -254,6 +288,8 @@ def reconcile_dag_schedules(dag: DAG, *, require_tiered: bool = False, graph: Fr
deliberate wind-down (last target reverted/cleared) and those tiers are torn down. With
`require_tiered`, a DAG that has no tiered schedule yet (legacy single schedule or nothing) is
left untouched.
+
+ Returns whether a reconcile was applied; False means a guard skipped it.
"""
team = dag.team
if graph is None:
@@ -262,8 +298,8 @@ def reconcile_dag_schedules(dag: DAG, *, require_tiered: bool = False, graph: Fr
nodes=graph.nodes, edges=graph.edges, declared_targets=graph.declared_targets
)
effective, _clamped = clamp_to_source_floor(effective, edges=graph.edges, source_intervals=graph.source_intervals)
- desired_tiers = bucket_into_cadence_tiers(effective)
- _apply_reconciliation(
+ desired_tiers = bucket_into_cadence_tiers(effective, graph.declared_anchors)
+ return _apply_reconciliation(
dag_id=str(dag.id),
team_id=team.pk,
organization_id=str(team.organization_id),
@@ -351,7 +387,7 @@ 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 (post-clamp)
- desired_tiers: dict[timedelta, set[str]]
+ desired_tiers: dict[Tier, set[str]]
plan: ScheduleReconcilePlan
best_effort_source_ids: set[str] # sources whose freshness is not actually guaranteed
clamped: list[ClampedCadence] # nodes coarsened to what their sources can deliver
@@ -372,7 +408,7 @@ def preview_dag_schedules(dag: DAG, *, seed: bool = False) -> DagSchedulePreview
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)
effective, clamped = clamp_to_source_floor(effective, edges=graph.edges, source_intervals=graph.source_intervals)
- desired_tiers = bucket_into_cadence_tiers(effective)
+ desired_tiers = bucket_into_cadence_tiers(effective, graph.declared_anchors)
existing_ids = list_existing_schedule_ids(str(dag.id))
plan = plan_schedule_reconciliation(str(dag.id), desired_tiers, existing_ids)
return DagSchedulePreview(
@@ -384,7 +420,7 @@ def preview_dag_schedules(dag: DAG, *, seed: bool = False) -> DagSchedulePreview
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),
+ unsupported_tiers=sorted({tier.interval for tier in desired_tiers if tier.interval not in SCHEDULABLE_BUCKETS}),
seeded=seed,
)
@@ -402,11 +438,11 @@ async def _apply_reconciliation(
team_id: int,
organization_id: str,
team_timezone: str,
- desired_tiers: dict[timedelta, set[str]],
+ desired_tiers: dict[Tier, set[str]],
require_tiered: bool = False,
has_schedulable_nodes: bool = True,
-) -> None:
- unsupported = sorted(interval for interval in desired_tiers if interval not in SCHEDULABLE_BUCKETS)
+) -> bool:
+ unsupported = sorted({tier.interval for tier in desired_tiers if tier.interval not in SCHEDULABLE_BUCKETS})
if unsupported:
tiers = ", ".join(format_cadence(interval) for interval in unsupported)
raise UnsupportedFrequencyTargetError(
@@ -417,7 +453,7 @@ async def _apply_reconciliation(
existing_ids = await _list_execute_dag_schedule_ids(temporal, dag_id)
if require_tiered and not any(is_tier_schedule_id(schedule_id) for schedule_id in existing_ids):
logger.debug("DAG not converted to cadence tiers yet, skipping reconcile", dag_id=dag_id)
- return
+ return False
# An empty tier set on a DAG that still has only legacy (non-tier) schedules means an unseeded
# conversion — protect it, but only when there is anything to seed: a DAG with no schedulable
# nodes gets its legacy schedule swept instead of firing no-op runs forever. Once tier
@@ -435,7 +471,7 @@ async def _apply_reconciliation(
dag_id=dag_id,
existing_schedule_ids=sorted(existing_ids),
)
- return
+ return False
plan = plan_schedule_reconciliation(dag_id, desired_tiers, existing_ids)
# Includes the schedule-type tag: get_v2_scheduled_dag_ids' unscoped sweep filters on
@@ -447,8 +483,8 @@ async def _apply_reconciliation(
# 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)
+ for schedule_id, (tier, node_ids) in plan.to_create.items():
+ schedule = _build_tier_schedule(dag_id, team_id, team_timezone, tier, node_ids)
try:
await a_create_schedule(
temporal, id=schedule_id, schedule=schedule, search_attributes=search_attributes
@@ -460,8 +496,8 @@ async def _apply_reconciliation(
await a_update_schedule(
temporal, id=schedule_id, schedule=schedule, search_attributes=search_attributes
)
- for schedule_id, (interval, node_ids) in plan.to_update.items():
- schedule = _build_tier_schedule(dag_id, team_id, team_timezone, interval, node_ids)
+ for schedule_id, (tier, node_ids) in plan.to_update.items():
+ schedule = _build_tier_schedule(dag_id, team_id, team_timezone, tier, node_ids)
await a_update_schedule(temporal, id=schedule_id, schedule=schedule, search_attributes=search_attributes)
except Exception:
for schedule_id in created:
@@ -479,6 +515,7 @@ async def _apply_reconciliation(
except Exception as error:
logger.exception("Failed to delete stale schedule", schedule_id=schedule_id, dag_id=dag_id)
capture_exception(error)
+ return True
async def _list_execute_dag_schedule_ids(temporal: Client, dag_id: str) -> set[str]:
@@ -495,19 +532,27 @@ async def _list_execute_dag_schedule_ids(temporal: Client, dag_id: str) -> set[s
def _build_tier_schedule(
- dag_id: str, team_id: int, team_timezone: str, interval: timedelta, node_ids: Iterable[str]
+ dag_id: str, team_id: int, team_timezone: str, tier: Tier, node_ids: Iterable[str]
) -> Schedule:
from posthog.temporal.data_modeling.workflows.execute_dag import ( # noqa: PLC0415 — the workflows package imports this product's models back; importing it lazily keeps this module importable from models code and temporal off django.setup()
ExecuteDAGInputs,
)
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)
+ spec = build_schedule_spec(
+ entity_id=uuid.UUID(dag_id),
+ interval=tier.interval,
+ team_timezone=team_timezone,
+ anchor_minutes=tier.anchor_minutes,
+ )
+ note = f"data-modeling DAG {dag_id} cadence tier {tier.interval}"
+ if tier.anchor_minutes is not None:
+ note += f" anchored at {tier.anchor_minutes}min past Monday 00:00 UTC"
return Schedule(
action=ScheduleActionStartWorkflow(
DATA_MODELING_EXECUTE_DAG_WORKFLOW,
dataclasses.asdict(inputs),
- id=f"execute-dag-{tier_schedule_id(dag_id, interval)}",
+ id=f"execute-dag-{tier_schedule_id(dag_id, tier.interval, tier.anchor_minutes)}",
task_queue=str(settings.DATA_MODELING_TASK_QUEUE),
retry_policy=RetryPolicy(
initial_interval=timedelta(seconds=10),
@@ -517,6 +562,6 @@ def _build_tier_schedule(
),
),
spec=spec,
- state=ScheduleState(note=f"data-modeling DAG {dag_id} cadence tier {interval}"),
+ state=ScheduleState(note=note),
policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
)
diff --git a/products/data_modeling/backend/logic/tier_membership.py b/products/data_modeling/backend/logic/tier_membership.py
index 2852210196c1..1a16c924b21d 100644
--- a/products/data_modeling/backend/logic/tier_membership.py
+++ b/products/data_modeling/backend/logic/tier_membership.py
@@ -18,7 +18,12 @@ from temporalio.client import Client, ScheduleActionStartWorkflow, ScheduleListA
from posthog.temporal.common.search_attributes import POSTHOG_DAG_ID_KEY
-from products.data_modeling.backend.logic.cohort_scheduling import bucket_into_cadence_tiers, is_tier_schedule_id
+from products.data_modeling.backend.logic.cohort_scheduling import (
+ Tier,
+ anchor_minutes_from_schedule_id,
+ bucket_into_cadence_tiers,
+ interval_seconds_from_schedule_id,
+)
from products.data_modeling.backend.logic.freshness import (
SCHEDULABLE_BUCKETS,
clamp_to_source_floor,
@@ -38,6 +43,7 @@ class LiveTier:
interval_seconds: int | None # None = migration-era single schedule (no cadence tier)
covers_whole_dag: bool # True when node_ids is unset — the schedule materializes every node
node_ids: frozenset[str] | None # the exact set the tier will materialize; None when whole-DAG
+ anchor_minutes: int | None = None # the cohort's pinned phase; None = hash-spread
@dataclasses.dataclass
@@ -51,6 +57,7 @@ class NodeScheduleStatus:
expected_interval: int | None # what reconcile would put it on now (None = ride-downstream opt-out)
verdict: str
dag_reconcile_blocked: bool = False # a non-bucket tier anywhere in the DAG makes reconcile refuse it
+ expected_anchor: int | None = None # the expected cohort's pinned phase; None = hash-spread
# Verdict values — a node's live scheduling vs what reconcile would currently schedule.
@@ -68,13 +75,6 @@ UNSUPPORTED_TARGET = "unsupported_target"
EPHEMERAL_SKIPPED = "ephemeral_skipped"
-def _interval_from_schedule_id(schedule_id: str) -> int | None:
- """Recover the tier's cadence (seconds) from its schedule id, or None for the legacy single schedule."""
- if is_tier_schedule_id(schedule_id):
- return int(schedule_id.rsplit(":", 1)[1])
- return None
-
-
async def _decode_node_ids(temporal: Client, action: object) -> list[str] | None:
"""Read `node_ids` from a schedule's start-workflow args, decoding the encrypted payload.
@@ -112,36 +112,33 @@ async def read_live_tiers(temporal: Client, dag_id: str) -> list[LiveTier]:
tiers.append(
LiveTier(
schedule_id=listing.id,
- interval_seconds=_interval_from_schedule_id(listing.id),
+ interval_seconds=interval_seconds_from_schedule_id(listing.id),
covers_whole_dag=node_ids is None,
node_ids=frozenset(node_ids) if node_ids is not None else None,
+ anchor_minutes=anchor_minutes_from_schedule_id(listing.id),
)
)
return tiers
-def _desired_tiers(dag: DAG) -> dict[timedelta, set[str]]:
+def _desired_tiers(dag: DAG) -> dict[Tier, set[str]]:
"""The tiers reconcile would want for this DAG: effective cadences → clamp to floor → buckets."""
graph = build_frequency_graph(dag)
effective = compute_effective_cadences(
nodes=graph.nodes, edges=graph.edges, declared_targets=graph.declared_targets
)
effective, _clamped = clamp_to_source_floor(effective, edges=graph.edges, source_intervals=graph.source_intervals)
- return bucket_into_cadence_tiers(effective)
+ return bucket_into_cadence_tiers(effective, graph.declared_anchors)
-def expected_tier_by_node(dag: DAG) -> dict[str, int]:
- """What cadence (seconds) reconcile would currently schedule each schedulable node on.
+def expected_tier_by_node(dag: DAG) -> dict[str, Tier]:
+ """The cohort reconcile would currently schedule each schedulable node on.
Mirrors `reconcile_dag_schedules` exactly (effective cadences → clamp to source floor → buckets)
so a node absent from this map is one reconcile would leave unscheduled (the ride-downstream
opt-out), not a bug.
"""
- return {
- node_id: int(interval.total_seconds())
- for interval, node_ids in _desired_tiers(dag).items()
- for node_id in node_ids
- }
+ return {node_id: tier for tier, node_ids in _desired_tiers(dag).items() for node_id in node_ids}
def dag_reconcile_would_refuse(dag: DAG) -> bool:
@@ -151,7 +148,7 @@ def dag_reconcile_would_refuse(dag: DAG) -> bool:
desired tier falls outside `SCHEDULABLE_BUCKETS`, leaving every schedule untouched. Without
this, such a node reads as `stale_needs_reconcile` — advice that would raise rather than fix.
"""
- return any(interval not in SCHEDULABLE_BUCKETS for interval in _desired_tiers(dag))
+ return any(tier.interval not in SCHEDULABLE_BUCKETS for tier in _desired_tiers(dag))
def classify_node(
@@ -162,26 +159,36 @@ def classify_node(
dag_id: str,
dag_name: str,
live_tiers: list[LiveTier],
- expected_interval: int | None,
+ expected_tier: Tier | None,
reconcile_blocked: bool = False,
has_backing_table: bool = False,
) -> NodeScheduleStatus:
"""Compare a node's live tier membership against what reconcile would schedule for it."""
- live_intervals = [
- tier.interval_seconds
- for tier in live_tiers
- if tier.covers_whole_dag or (tier.node_ids is not None and node_id in tier.node_ids)
+ covering = [
+ tier for tier in live_tiers if tier.covers_whole_dag or (tier.node_ids is not None and node_id in tier.node_ids)
]
- covered_live = bool(live_intervals)
+ live_intervals = [tier.interval_seconds for tier in covering]
+ covered_live = bool(covering)
+ expected_interval = int(expected_tier.interval.total_seconds()) if expected_tier is not None else None
if node_type == NodeType.VIEW and has_backing_table:
verdict = EPHEMERAL_SKIPPED
- elif covered_live and expected_interval is not None:
- # A whole-DAG (interval None) schedule always satisfies expectation.
- verdict = SCHEDULED if (None in live_intervals or expected_interval in live_intervals) else SCHEDULED_WRONG_TIER
- elif covered_live and expected_interval is None:
+ elif covered_live and expected_tier is not None:
+ # A whole-DAG (interval None) schedule always satisfies expectation. A tier matches on
+ # cadence AND anchor — a hash-spread schedule does not satisfy an anchored expectation,
+ # else the exact drift anchors exist to escape reads as healthy.
+ verdict = (
+ SCHEDULED
+ if any(
+ tier.interval_seconds is None
+ or (tier.interval_seconds, tier.anchor_minutes) == (expected_interval, expected_tier.anchor_minutes)
+ for tier in covering
+ )
+ else SCHEDULED_WRONG_TIER
+ )
+ elif covered_live and expected_tier is None:
verdict = OVER_SCHEDULED
- elif not covered_live and expected_interval is not None:
+ elif not covered_live and expected_tier is not None:
# Reconcile is the remediation for stale_needs_reconcile, so only report it when reconcile
# would actually run. A blocked DAG needs its unschedulable target fixed first.
verdict = UNSUPPORTED_TARGET if reconcile_blocked else STALE_NEEDS_RECONCILE
@@ -196,6 +203,7 @@ def classify_node(
dag_name=dag_name,
live_intervals=sorted(live_intervals, key=lambda i: (i is None, i or 0)),
expected_interval=expected_interval,
+ expected_anchor=expected_tier.anchor_minutes if expected_tier is not None else None,
verdict=verdict,
dag_reconcile_blocked=reconcile_blocked,
)
diff --git a/products/data_modeling/backend/logic/tier_run_report.py b/products/data_modeling/backend/logic/tier_run_report.py
index 02a147b06ec8..02c07aca612d 100644
--- a/products/data_modeling/backend/logic/tier_run_report.py
+++ b/products/data_modeling/backend/logic/tier_run_report.py
@@ -1,9 +1,14 @@
-"""What each cadence tier of a DAG declares, and what its most recent run actually did.
+"""What each cadence tier of a DAG holds, and what its most recent run actually did.
Answers "the daily tier holds N nodes — did they all run, and if not why not?" from Postgres
alone. `DataModelingJob.parent_workflow_id` carries the tier's schedule id, so a run's job rows
are attributable to the tier that produced them without asking Temporal.
+Tiers are grouped by *effective* cadence — the same propagation + source-floor clamp + bucketing
+the schedule reconciler runs — not by declared target. A declared-daily node above a 15min
+consumer runs under the 15min schedule; grouping by declared target would look it up in a daily
+run that never contains it and report it MISSING forever.
+
This is deliberately *not* a check that a node is in the live schedule's `node_ids` — that lives
in Temporal, encrypted. A node reported `MISSING` here is either absent from the live tier or was
skipped for a reason the run did not record; distinguishing those needs the Temporal read.
@@ -15,9 +20,15 @@ from datetime import datetime, timedelta
from django.db import models
-from products.data_modeling.backend.logic.cohort_scheduling import tier_schedule_id
-from products.data_modeling.backend.logic.freshness import format_cadence
-from products.data_modeling.backend.logic.node_frequency import get_declared_target
+from products.data_modeling.backend.logic.cohort_scheduling import (
+ Tier,
+ bucket_into_cadence_tiers,
+ format_tier,
+ tier_schedule_id,
+ tier_sort_key,
+)
+from products.data_modeling.backend.logic.freshness import clamp_to_source_floor, compute_effective_cadences
+from products.data_modeling.backend.logic.node_frequency import build_frequency_graph
from products.data_modeling.backend.models.dag import DAG
from products.data_modeling.backend.models.data_modeling_job import (
DataModelingJob,
@@ -75,16 +86,22 @@ class TierRun:
nodes: list[NodeRun]
# the matched run came from the DAG's pre-tier single schedule, not from this tier's own
run_is_legacy: bool = False
+ anchor_minutes: int | None = None
@property
def label(self) -> str:
- return format_cadence(self.interval)
+ return format_tier(Tier(self.interval, self.anchor_minutes))
@property
def seconds(self) -> int:
- """Anchor-safe tier identifier; `schedule_id` carries a colon."""
return int(self.interval.total_seconds())
+ @property
+ def slug(self) -> str:
+ """DOM-safe tier identifier, unique when a cadence splits into anchored and hash-spread
+ cohorts; `schedule_id` carries colons."""
+ return str(self.seconds) if self.anchor_minutes is None else f"{self.seconds}-{self.anchor_minutes}"
+
@property
def counts(self) -> dict[str, int]:
counts = dict.fromkeys(STATUS_ORDER, 0)
@@ -103,13 +120,13 @@ class TierRun:
def build_tier_runs(dag: DAG) -> list[TierRun]:
- """One TierRun per declared cadence on `dag`, finest cadence first."""
+ """One TierRun per effective cadence cohort on `dag`, finest cadence first."""
nodes = _reportable_nodes(dag)
- nodes_by_interval: dict[timedelta, list[Node]] = defaultdict(list)
- for node in nodes:
- target = get_declared_target(node)
- if target is not None:
- nodes_by_interval[target].append(node)
+ by_id = {str(node.id): node for node in nodes}
+ tiers = _desired_tiers(dag)
+ nodes_by_tier = {
+ tier: [by_id[node_id] for node_id in sorted(node_ids) if node_id in by_id] for tier, node_ids in tiers.items()
+ }
downstream = _downstream_lookup(dag)
# the runtime blocks on suspension DAG-wide, not per tier: get_dag_structure builds
@@ -118,14 +135,25 @@ def build_tier_runs(dag: DAG) -> list[TierRun]:
suspensions = {str(node.id): _suspension_detail(node) for node in nodes}
names = {str(node.id): node.name for node in nodes}
return [
- _build_tier(dag, interval, nodes_by_interval[interval], downstream, suspensions, names)
- for interval in sorted(nodes_by_interval)
+ _build_tier(dag, tier, nodes_by_tier[tier], downstream, suspensions, names)
+ for tier in sorted(nodes_by_tier, key=tier_sort_key)
]
def untargeted_nodes(dag: DAG) -> list[Node]:
- """Nodes carrying no declared target — they belong to no tier, so no schedule fires them."""
- return [node for node in _reportable_nodes(dag) if get_declared_target(node) is None]
+ """Nodes in no cohort — nothing gives them an effective cadence, so no schedule fires them."""
+ scheduled = {node_id for node_ids in _desired_tiers(dag).values() for node_id in node_ids}
+ return [node for node in _reportable_nodes(dag) if str(node.id) not in scheduled]
+
+
+def _desired_tiers(dag: DAG) -> dict[Tier, set[str]]:
+ """The cohorts the reconciler would build, mirroring its propagation + clamp + bucketing."""
+ graph = build_frequency_graph(dag)
+ effective = compute_effective_cadences(
+ nodes=graph.nodes, edges=graph.edges, declared_targets=graph.declared_targets
+ )
+ effective, _clamped = clamp_to_source_floor(effective, edges=graph.edges, source_intervals=graph.source_intervals)
+ return bucket_into_cadence_tiers(effective, graph.declared_anchors)
def _reportable_nodes(dag: DAG) -> list[Node]:
@@ -142,13 +170,13 @@ def _reportable_nodes(dag: DAG) -> list[Node]:
def _build_tier(
dag: DAG,
- interval: timedelta,
+ tier: Tier,
nodes: list[Node],
downstream: dict[str, set[str]],
suspensions: dict[str, str],
names: dict[str, str],
) -> TierRun:
- schedule_id = tier_schedule_id(str(dag.id), interval)
+ schedule_id = tier_schedule_id(str(dag.id), tier.interval, tier.anchor_minutes)
parent_workflow_id, started_at, run_is_legacy = _latest_run(dag.team_id, str(dag.id), schedule_id)
jobs = _jobs_by_saved_query(dag.team_id, parent_workflow_id)
@@ -176,12 +204,13 @@ def _build_tier(
]
runs.sort(key=lambda run: (STATUS_ORDER.index(run.status), run.name))
return TierRun(
- interval=interval,
+ interval=tier.interval,
schedule_id=schedule_id,
parent_workflow_id=parent_workflow_id,
started_at=started_at,
nodes=runs,
run_is_legacy=run_is_legacy,
+ anchor_minutes=tier.anchor_minutes,
)
diff --git a/products/data_modeling/backend/management/commands/batch_reconcile_teams.py b/products/data_modeling/backend/management/commands/batch_reconcile_teams.py
index 0fd72fcf3a81..e1e427b4bafb 100644
--- a/products/data_modeling/backend/management/commands/batch_reconcile_teams.py
+++ b/products/data_modeling/backend/management/commands/batch_reconcile_teams.py
@@ -14,7 +14,7 @@ from posthog.models.team import Team
from posthog.temporal.common.client import async_connect
from posthog.temporal.common.schedule import a_schedule_exists
-from products.data_modeling.backend.logic.cohort_scheduling import tier_schedule_id
+from products.data_modeling.backend.logic.cohort_scheduling import Tier, tier_schedule_id
from products.data_modeling.backend.logic.node_frequency import schedulable_nodes
from products.data_modeling.backend.logic.schedule_reconcile import (
convert_dag_to_tiers,
@@ -41,6 +41,11 @@ def _seconds(interval: timedelta) -> int:
return int(interval.total_seconds())
+def _tier_key(tier: Tier) -> str:
+ seconds = _seconds(tier.interval)
+ return str(seconds) if tier.anchor_minutes is None else f"{seconds}@{tier.anchor_minutes}"
+
+
@async_to_sync
async def _verify_schedules(expected: list[str], deleted: list[str]) -> tuple[list[str], list[str]]:
"""Point-read every id: planned schedules must exist, swept ones must be gone. Listing
@@ -149,8 +154,8 @@ class Command(BaseCommand):
dag_record: dict = {
"dag_id": str(dag.id),
"name": dag.name,
- "planned_tiers": sorted(_seconds(t) for t in preview.desired_tiers),
- "tier_node_counts": {str(_seconds(t)): len(nodes) for t, nodes in preview.desired_tiers.items()},
+ "planned_tiers": sorted(_seconds(t.interval) for t in preview.desired_tiers),
+ "tier_node_counts": {_tier_key(t): len(nodes) for t, nodes in preview.desired_tiers.items()},
"to_create": sorted(preview.plan.to_create),
"to_update": sorted(preview.plan.to_update),
"to_delete": sorted(preview.plan.to_delete),
@@ -200,7 +205,9 @@ class Command(BaseCommand):
raise Anomaly(f"DAG {dag.name}: {len(failed)} v1 schedule(s) failed to delete")
for dag, preview, dag_record in plans:
- expected = sorted(tier_schedule_id(str(dag.id), interval) for interval in preview.desired_tiers)
+ expected = sorted(
+ tier_schedule_id(str(dag.id), tier.interval, tier.anchor_minutes) for tier in preview.desired_tiers
+ )
missing, lingering = _verify_schedules(expected, sorted(preview.plan.to_delete))
dag_record["verified"] = not missing and not lingering
if missing or lingering:
diff --git a/products/data_modeling/backend/management/commands/check_node_tier_schedule.py b/products/data_modeling/backend/management/commands/check_node_tier_schedule.py
index 11a27e871a32..5d7449fc3d18 100644
--- a/products/data_modeling/backend/management/commands/check_node_tier_schedule.py
+++ b/products/data_modeling/backend/management/commands/check_node_tier_schedule.py
@@ -93,7 +93,7 @@ class Command(BaseCommand):
dag_id=str(node.dag_id),
dag_name=dag.name,
live_tiers=live_by_dag.get(str(node.dag_id), []),
- expected_interval=expected,
+ expected_tier=expected,
reconcile_blocked=blocked_by_dag.get(str(node.dag_id), False),
has_backing_table=node.saved_query is not None and node.saved_query.table_id is not None,
)
diff --git a/products/data_modeling/backend/management/commands/preview_freshness_schedules.py b/products/data_modeling/backend/management/commands/preview_freshness_schedules.py
index 8b2030192fa2..bd6e409f312f 100644
--- a/products/data_modeling/backend/management/commands/preview_freshness_schedules.py
+++ b/products/data_modeling/backend/management/commands/preview_freshness_schedules.py
@@ -3,7 +3,7 @@ from collections import defaultdict
from django.core.management.base import BaseCommand, CommandError
-from products.data_modeling.backend.logic.freshness import format_cadence
+from products.data_modeling.backend.logic.cohort_scheduling import format_tier, tier_sort_key
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, NodeType
@@ -55,8 +55,8 @@ class Command(BaseCommand):
self.stdout.write(f"\nDAG {dag.name} ({dag.id}) — team {dag.team_id}{seeded_note}")
tiers = " ".join(
- f"{format_cadence(interval)} x{len(node_ids)}"
- for interval, node_ids in sorted(preview.desired_tiers.items())
+ f"{format_tier(tier)} x{len(node_ids)}"
+ for tier, node_ids in sorted(preview.desired_tiers.items(), key=lambda kv: tier_sort_key(kv[0]))
)
unscheduled = sum(1 for cadence in preview.effective.values() if cadence is None)
tier_line = tiers or "(none)"
@@ -106,19 +106,19 @@ class Command(BaseCommand):
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()):
+ for tier, node_ids in sorted(preview.desired_tiers.items(), key=lambda kv: tier_sort_key(kv[0])):
members = ", ".join(sorted(names.get(node_id, node_id) for node_id in node_ids))
- self.stdout.write(f" {interval}: {members}")
+ self.stdout.write(f" {format_tier(tier)}: {members}")
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, (tier, node_ids) in sorted(plan.to_create.items()):
+ self.stdout.write(f" CREATE {schedule_id} ({format_tier(tier)}, {len(node_ids)} nodes)")
+ for schedule_id, (tier, node_ids) in sorted(plan.to_update.items()):
+ self.stdout.write(f" UPDATE {schedule_id} ({format_tier(tier)}, {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/management/commands/set_schedule_anchor.py b/products/data_modeling/backend/management/commands/set_schedule_anchor.py
new file mode 100644
index 000000000000..2a4efbdc1c29
--- /dev/null
+++ b/products/data_modeling/backend/management/commands/set_schedule_anchor.py
@@ -0,0 +1,215 @@
+import uuid
+from collections import defaultdict
+from datetime import timedelta
+
+from django.core.management.base import BaseCommand, CommandError
+from django.db import transaction
+
+import structlog
+
+from posthog.models.team import Team
+
+from products.data_modeling.backend.logic.cohort_scheduling import (
+ MINUTES_PER_DAY,
+ bucket_into_cadence_tiers,
+ format_tier,
+ tier_sort_key,
+)
+from products.data_modeling.backend.logic.freshness import clamp_to_source_floor, compute_effective_cadences
+from products.data_modeling.backend.logic.node_frequency import (
+ build_frequency_graph,
+ schedulable_nodes,
+ set_declared_anchor,
+)
+from products.data_modeling.backend.logic.schedule_reconcile import reconcile_dag_schedules, tiered_schedules_enabled
+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.node import Node
+
+logger = structlog.get_logger(__name__)
+
+WEEKDAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
+WEEKLY = timedelta(days=7)
+
+
+class Command(BaseCommand):
+ help = (
+ "Pin (or clear) the schedule anchor on a DAG's nodes or a set of saved queries, then "
+ "reconcile the affected DAGs' cadence-tier schedules. An anchored cohort fires at the "
+ "given UTC time instead of its hash-spread slot: a daily node anchored at 00:00 runs at "
+ "midnight UTC, a 6-hourly one at 00/06/12/18. Ordering is guaranteed only within one "
+ "cohort (same cadence + same anchor); anchored cohorts at different cadences fire "
+ "concurrently. Operator-only: anchors concentrate load, so hand them out deliberately."
+ )
+
+ def add_arguments(self, parser):
+ parser.add_argument("--team-id", type=int, required=True)
+ parser.add_argument("--dag-id", type=str, default=None, help="Anchor every schedulable node in this DAG")
+ parser.add_argument(
+ "--saved-query-names", nargs="+", default=None, help="Anchor only these saved queries' nodes"
+ )
+ parser.add_argument(
+ "--at",
+ type=str,
+ default=None,
+ help="UTC time to anchor to, HH:MM (e.g. 00:00). Monthly-cadence nodes keep their hash-picked day of month",
+ )
+ parser.add_argument(
+ "--on",
+ type=str,
+ default=None,
+ choices=WEEKDAYS,
+ help="Day of week for weekly-cadence nodes (required when the target set contains one)",
+ )
+ parser.add_argument(
+ "--with-upstream",
+ action="store_true",
+ default=False,
+ help="Also anchor each target's ancestor cone so the whole pipeline runs as one ordered cohort",
+ )
+ parser.add_argument("--clear", action="store_true", default=False, help="Clear anchors back to hash-spread")
+ parser.add_argument(
+ "--dry-run", action="store_true", default=False, help="Print the resulting tiers; write nothing"
+ )
+
+ def handle(self, *args, **options):
+ team = Team.objects.filter(id=options["team_id"]).first()
+ if team is None:
+ raise CommandError(f"No team with id {options['team_id']}")
+ if bool(options["dag_id"]) == bool(options["saved_query_names"]):
+ raise CommandError("Pass exactly one of --dag-id or --saved-query-names")
+ if options["clear"] == bool(options["at"]):
+ raise CommandError("Pass exactly one of --at or --clear")
+ if options["clear"] and options["on"]:
+ raise CommandError("--on has no effect with --clear")
+ if not tiered_schedules_enabled(team):
+ raise CommandError(
+ f"Team {team.pk} is not on the tiered-schedules flag; anchors only apply to cadence-tier schedules"
+ )
+
+ anchor = None if options["clear"] else self._parse_anchor(options["at"], options["on"])
+ nodes_by_dag = self._resolve_target_nodes(team, options)
+
+ # Validate every DAG before writing to any: a refusal on the second DAG must not leave the
+ # first one already anchored and reconciled.
+ plans: list[tuple[DAG, set[str], str]] = []
+ for dag, node_ids in sorted(nodes_by_dag.items(), key=lambda kv: str(kv[0].id)):
+ graph = build_frequency_graph(dag)
+ effective = compute_effective_cadences(
+ nodes=graph.nodes, edges=graph.edges, declared_targets=graph.declared_targets
+ )
+ effective, _clamped = clamp_to_source_floor(
+ effective, edges=graph.edges, source_intervals=graph.source_intervals
+ )
+
+ if options["with_upstream"]:
+ node_ids = self._expand_with_upstream(graph.edges, node_ids, graph.nodes)
+ cadences = {cadence for node_id in node_ids if (cadence := effective.get(node_id)) is not None}
+ # clearing cannot create ordering expectations, so it must stay possible
+ # on a cone whose cadences have drifted apart since it was anchored
+ if anchor is not None and len(cadences) > 1:
+ labels = ", ".join(str(c) for c in sorted(cadences))
+ raise CommandError(
+ f"DAG {dag.name} ({dag.id}): the upstream cone spans cadences ({labels}), so the "
+ "anchored cohorts would fire concurrently instead of in dependency order. Align the "
+ "cone's targets first, or anchor each cadence's nodes explicitly."
+ )
+
+ if anchor is not None and options["on"] is None:
+ weekly = [node_id for node_id in node_ids if effective.get(node_id) == WEEKLY]
+ if weekly:
+ raise CommandError(
+ f"DAG {dag.name} ({dag.id}): {len(weekly)} target node(s) are on a weekly cadence; "
+ "pass --on to pick their day instead of having one picked silently"
+ )
+
+ anchors = dict(graph.declared_anchors)
+ if anchor is None:
+ for node_id in node_ids:
+ anchors.pop(node_id, None)
+ else:
+ anchors.update(dict.fromkeys(node_ids, anchor))
+ tiers = bucket_into_cadence_tiers(effective, anchors)
+ tier_line = " ".join(
+ f"{format_tier(tier)} x{len(members)}"
+ for tier, members in sorted(tiers.items(), key=lambda kv: tier_sort_key(kv[0]))
+ )
+ plans.append((dag, node_ids, tier_line))
+
+ infinitive, past = ("clear", "cleared") if anchor is None else ("anchor", "anchored")
+ if options["dry_run"]:
+ for dag, node_ids, tier_line in plans:
+ self.stdout.write(
+ f"DAG {dag.name} ({dag.id}): would {infinitive} {len(node_ids)} node(s) → {tier_line}"
+ )
+ self.stdout.write("(dry run: nothing was written)")
+ return
+
+ for dag, node_ids, tier_line in plans:
+ written = 0
+ # locked so a concurrent frequency-target write on the same node cannot lose either
+ # key of the shared properties blob
+ with transaction.atomic():
+ for node in Node.objects.select_for_update().filter(
+ dag=dag, id__in=[uuid.UUID(node_id) for node_id in node_ids]
+ ):
+ set_declared_anchor(node, anchor)
+ written += 1
+ # require_tiered makes reconcile skip an unconverted DAG; saying "reconciled" there
+ # would tell the operator a pin took effect when it didn't
+ if reconcile_dag_schedules(dag, require_tiered=True):
+ self.stdout.write(f"DAG {dag.name} ({dag.id}): {past} {written} node(s), reconciled → {tier_line}")
+ else:
+ self.stdout.write(
+ f"DAG {dag.name} ({dag.id}): {past} {written} node(s), but the DAG is not on cadence-tier "
+ "schedules yet; anchors apply once it is converted (reconcile_freshness_schedules)"
+ )
+
+ def _parse_anchor(self, at: str, on: str | None) -> int:
+ try:
+ hour_text, minute_text = at.split(":")
+ hour, minute = int(hour_text), int(minute_text)
+ if not (0 <= hour <= 23 and 0 <= minute <= 59):
+ raise ValueError
+ except ValueError:
+ raise CommandError(f"--at must be HH:MM (24h UTC), got {at!r}")
+ day = WEEKDAYS.index(on) if on is not None else 0
+ return day * MINUTES_PER_DAY + hour * 60 + minute
+
+ def _resolve_target_nodes(self, team: Team, options: dict) -> dict[DAG, set[str]]:
+ nodes_by_dag: dict[DAG, set[str]] = defaultdict(set)
+ if options["dag_id"]:
+ try:
+ dag = DAG.objects.get(team_id=team.pk, id=uuid.UUID(options["dag_id"]))
+ except (DAG.DoesNotExist, ValueError):
+ raise CommandError(f"No DAG {options['dag_id']!r} on team {team.pk}")
+ for node_id in schedulable_nodes(dag).values_list("id", flat=True):
+ nodes_by_dag[dag].add(str(node_id))
+ else:
+ names = options["saved_query_names"]
+ queries = list(DataWarehouseSavedQuery.objects.filter(team_id=team.pk, name__in=names, deleted=False))
+ missing = set(names) - {query.name for query in queries}
+ if missing:
+ raise CommandError(f"No saved query named: {', '.join(sorted(missing))}")
+ nodes = Node.objects.filter(team_id=team.pk, saved_query__in=queries).select_related("dag")
+ for node in nodes:
+ nodes_by_dag[node.dag].add(str(node.id))
+ if not nodes_by_dag:
+ raise CommandError("The named saved queries have no DAG nodes to anchor")
+ return dict(nodes_by_dag)
+
+ def _expand_with_upstream(
+ self, edges: list[tuple[str, str]], node_ids: set[str], schedulable: set[str]
+ ) -> set[str]:
+ parents: dict[str, list[str]] = defaultdict(list)
+ for upstream, downstream in edges:
+ parents[downstream].append(upstream)
+ cone = set(node_ids)
+ frontier = list(node_ids)
+ while frontier:
+ for parent in parents.get(frontier.pop(), []):
+ # source TABLE nodes have no schedule, so the cone stays within schedulable nodes
+ if parent in schedulable and parent not in cone:
+ cone.add(parent)
+ frontier.append(parent)
+ return cone
diff --git a/products/data_modeling/backend/schedule.py b/products/data_modeling/backend/schedule.py
index 4b01e9628747..f0542d6f877b 100644
--- a/products/data_modeling/backend/schedule.py
+++ b/products/data_modeling/backend/schedule.py
@@ -256,10 +256,62 @@ def _monthly_spec(entity_id: uuid.UUID, timezone: str) -> ScheduleSpec:
)
+def _anchored_spec(entity_id: uuid.UUID, interval: timedelta, anchor_minutes: int) -> ScheduleSpec:
+ """Pinned-phase spec: fires at times t ≡ anchor (mod interval), t counted from Monday 00:00 UTC.
+
+ Always UTC (a fixed instant that does not shift with DST) and 1min jitter — an operator
+ pinning 00:00 means 00:00, not the hash paths' up-to-1hr spread. Every sub-weekly bucket
+ divides the day, so only the time-of-day part of the anchor matters there; weekly reads the
+ full value for its day. Monthly keeps its hash-picked day-of-month with the time pinned.
+ """
+ time_of_day = anchor_minutes % (24 * 60)
+ anchor_hour, anchor_min = divmod(time_of_day, 60)
+ total_hours = interval.total_seconds() / 3600
+
+ if total_hours <= 1:
+ interval_mins = int(interval.total_seconds() // 60)
+ base_min = time_of_day % interval_mins
+ mins = sorted((base_min + i * interval_mins) % 60 for i in range(60 // interval_mins))
+ calendar = ScheduleCalendarSpec(
+ comment=f"Anchored: every {interval_mins}min at minute phase {base_min}",
+ hour=[ScheduleRange(start=0, end=23)],
+ minute=[ScheduleRange(start=m, end=m) for m in mins],
+ )
+ elif total_hours <= 24:
+ interval_hours = int(total_hours)
+ base_hour = anchor_hour % interval_hours
+ hours = sorted((base_hour + i * interval_hours) % 24 for i in range(24 // interval_hours))
+ calendar = ScheduleCalendarSpec(
+ comment=f"Anchored: every {interval_hours}hr at {base_hour:02d}:{anchor_min:02d}",
+ hour=[ScheduleRange(start=h, end=h) for h in hours],
+ minute=[ScheduleRange(start=anchor_min, end=anchor_min)],
+ )
+ elif total_hours <= 168:
+ # The anchor counts days from Monday (ISO); Temporal's day_of_week counts 0 = Sunday.
+ day_of_week = (anchor_minutes // (24 * 60) + 1) % 7
+ calendar = ScheduleCalendarSpec(
+ comment=f"Anchored: weekly at day {day_of_week} {anchor_hour:02d}:{anchor_min:02d}",
+ day_of_week=[ScheduleRange(start=day_of_week, end=day_of_week)],
+ hour=[ScheduleRange(start=anchor_hour, end=anchor_hour)],
+ minute=[ScheduleRange(start=anchor_min, end=anchor_min)],
+ )
+ else:
+ day_of_month = (_deterministic_int(entity_id, "day") % 28) + 1
+ calendar = ScheduleCalendarSpec(
+ comment=f"Anchored: monthly (hash-picked day {day_of_month}) at {anchor_hour:02d}:{anchor_min:02d}",
+ day_of_month=[ScheduleRange(start=day_of_month, end=day_of_month)],
+ hour=[ScheduleRange(start=anchor_hour, end=anchor_hour)],
+ minute=[ScheduleRange(start=anchor_min, end=anchor_min)],
+ )
+
+ return ScheduleSpec(calendars=[calendar], jitter=timedelta(minutes=1), time_zone_name="UTC")
+
+
def build_schedule_spec(
entity_id: uuid.UUID,
interval: timedelta,
team_timezone: str = "UTC",
+ anchor_minutes: int | None = None,
) -> ScheduleSpec:
"""Build a Temporal ScheduleSpec for a saved query based on its sync frequency.
@@ -267,10 +319,15 @@ def build_schedule_spec(
entity_id: The saved query UUID (used for deterministic bucketing).
interval: The sync frequency interval (e.g. timedelta(hours=24)).
team_timezone: The team's timezone (e.g. "America/New_York"). Used for 6hr+ schedules.
+ anchor_minutes: When set, pin the fire phase instead of hash-spreading it — minutes
+ past Monday 00:00 UTC; the spec fires at t ≡ anchor (mod interval), always UTC.
Returns:
A ScheduleSpec ready to be used with Temporal's Schedule API.
"""
+ if anchor_minutes is not None:
+ return _anchored_spec(entity_id, interval, anchor_minutes)
+
total_hours = interval.total_seconds() / 3600
if total_hours <= 1:
diff --git a/products/data_modeling/backend/templates/admin/data_modeling/dag_tiers.html b/products/data_modeling/backend/templates/admin/data_modeling/dag_tiers.html
index 4be9227cc67f..2d2d3ea4645d 100644
--- a/products/data_modeling/backend/templates/admin/data_modeling/dag_tiers.html
+++ b/products/data_modeling/backend/templates/admin/data_modeling/dag_tiers.html
@@ -34,7 +34,7 @@
</tr>
{% for tier in tiers %}
<tr>
- <td><a href="#tier-{{ tier.seconds }}"><strong>{{ tier.label }}</strong></a></td>
+ <td><a href="#tier-{{ tier.slug }}"><strong>{{ tier.label }}</strong></a></td>
<td>
{% if temporal_ui_host %}
<a href="{{ temporal_ui_host }}/namespaces/{{ temporal_namespace }}/schedules/execute-dag-{{ tier.schedule_id }}" target="_blank" rel="noreferrer">schedule ↗</a>
@@ -65,7 +65,7 @@
</table>
{% for tier in tiers %}
-<h2 class="tier-heading" id="tier-{{ tier.seconds }}">{{ tier.label }} — {{ tier.declared }} materializing node{{ tier.declared|pluralize }}</h2>
+<h2 class="tier-heading" id="tier-{{ tier.slug }}">{{ tier.label }} — {{ tier.declared }} materializing node{{ tier.declared|pluralize }}</h2>
<p class="tier-meta">
{% if tier.run_is_legacy %}
This DAG has no schedule for this tier. The statuses below come from its pre-tier
diff --git a/products/data_modeling/backend/test/test_check_node_tier_schedule.py b/products/data_modeling/backend/test/test_check_node_tier_schedule.py
index 20aeea137251..201bd3a4beb5 100644
--- a/products/data_modeling/backend/test/test_check_node_tier_schedule.py
+++ b/products/data_modeling/backend/test/test_check_node_tier_schedule.py
@@ -1,3 +1,5 @@
+from datetime import timedelta
+
import pytest
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -10,6 +12,7 @@ from parameterized import parameterized
from posthog.models import Organization, Team
+from products.data_modeling.backend.logic.cohort_scheduling import Tier
from products.data_modeling.backend.logic.tier_membership import EPHEMERAL_SKIPPED, SCHEDULED, LiveTier, classify_node
from products.data_modeling.backend.models.dag import DAG
from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
@@ -35,7 +38,7 @@ class TestClassifyNodeEphemeral(SimpleTestCase):
dag_id="d1",
dag_name="Default",
live_tiers=[self._tier("n1")],
- expected_interval=900,
+ expected_tier=Tier(timedelta(seconds=900)),
has_backing_table=has_backing_table,
).verdict
diff --git a/products/data_modeling/backend/test/test_cohort_scheduling.py b/products/data_modeling/backend/test/test_cohort_scheduling.py
index c1ee4554188d..4800d2bd7c58 100644
--- a/products/data_modeling/backend/test/test_cohort_scheduling.py
+++ b/products/data_modeling/backend/test/test_cohort_scheduling.py
@@ -2,52 +2,119 @@ from datetime import timedelta
from unittest import TestCase
+from parameterized import parameterized
+
from products.data_modeling.backend.logic.cohort_scheduling import (
+ Tier,
bucket_into_cadence_tiers,
dag_id_from_schedule_id,
+ format_tier,
+ interval_seconds_from_schedule_id,
plan_schedule_reconciliation,
tier_schedule_id,
+ tier_sort_key,
)
DAG_ID = "018f2a00-0000-0000-0000-000000000000"
M15 = timedelta(minutes=15)
H1 = timedelta(hours=1)
H6 = timedelta(hours=6)
+H24 = timedelta(hours=24)
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"}})
+ self.assertEqual(bucket_into_cadence_tiers(effective), {Tier(M15): {"a", "b"}, Tier(H1): {"c"}})
def test_empty_graph_has_no_tiers(self):
self.assertEqual(bucket_into_cadence_tiers({}), {})
+ def test_anchored_nodes_split_from_hash_spread_cohort(self):
+ effective = {"a": H24, "b": H24, "c": H24, "d": None}
+ anchors = {"b": 0, "c": 0, "d": 0}
+ self.assertEqual(
+ bucket_into_cadence_tiers(effective, anchors),
+ {Tier(H24): {"a"}, Tier(H24, 0): {"b", "c"}},
+ )
+
+ def test_different_anchors_are_different_cohorts(self):
+ effective: dict[str, timedelta | None] = {"a": H24, "b": H24}
+ self.assertEqual(
+ bucket_into_cadence_tiers(effective, {"a": 0, "b": 360}),
+ {Tier(H24, 0): {"a"}, Tier(H24, 360): {"b"}},
+ )
+
+ @parameterized.expand(
+ [
+ # the spec ignores the day part below weekly, so anchors equal mod the cadence are
+ # one cohort — otherwise `--on tuesday` on a mixed daily+weekly selection splits
+ # daily nodes into a second schedule that fires identically
+ ("daily_day_part_inert", H24, {"a": 0, "b": 1440}, Tier(H24, 0)),
+ ("sub_daily_phase_mod_interval", H6, {"a": 1350, "b": 270}, Tier(H6, 270)),
+ ("weekly_keeps_full_offset", timedelta(days=7), {"a": 4380, "b": 4380}, Tier(timedelta(days=7), 4380)),
+ ("monthly_time_of_day_only", timedelta(days=30), {"a": 1500, "b": 60}, Tier(timedelta(days=30), 60)),
+ ]
+ )
+ def test_equivalent_anchors_collapse_into_one_cohort(self, _name, interval, anchors, expected_tier):
+ effective: dict[str, timedelta | None] = {"a": interval, "b": interval}
+ self.assertEqual(bucket_into_cadence_tiers(effective, anchors), {expected_tier: {"a", "b"}})
+
class TestTierScheduleId(TestCase):
- def test_round_trip(self):
- schedule_id = tier_schedule_id(DAG_ID, M15)
- self.assertEqual(schedule_id, f"{DAG_ID}:900")
+ @parameterized.expand(
+ [
+ ("unanchored", None, f"{DAG_ID}:900", 900),
+ ("anchored", 120, f"{DAG_ID}:900:120", 900),
+ ]
+ )
+ def test_round_trip(self, _name, anchor, expected_id, expected_seconds):
+ schedule_id = tier_schedule_id(DAG_ID, M15, anchor)
+ self.assertEqual(schedule_id, expected_id)
self.assertEqual(dag_id_from_schedule_id(schedule_id), DAG_ID)
+ self.assertEqual(interval_seconds_from_schedule_id(schedule_id), expected_seconds)
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)
+ self.assertIsNone(interval_seconds_from_schedule_id(DAG_ID))
+
+
+class TestTierDisplay(TestCase):
+ def test_sort_key_orders_hash_spread_before_anchored_within_a_cadence(self):
+ tiers = [Tier(H24, 0), Tier(H24), Tier(M15)]
+ self.assertEqual(sorted(tiers, key=tier_sort_key), [Tier(M15), Tier(H24), Tier(H24, 0)])
+
+ @parameterized.expand(
+ [
+ # only weekly gets a weekday: sub-weekly specs ignore the day part, and monthly's
+ # day of month is hash-picked — naming a day there tells the operator a fire
+ # calendar the schedule does not have
+ ("unanchored", Tier(H24), "1day"),
+ ("midnight", Tier(H24, 0), "1day@00:00"),
+ ("daily_time_only", Tier(H24, 1350), "1day@22:30"),
+ ("sub_daily_phase", Tier(H6, 1350), "6hour@04:30"),
+ ("weekly_tuesday", Tier(timedelta(days=7), 1560), "7day@tue 02:00"),
+ ("monthly_time_only", Tier(timedelta(days=30), 1560), "30day@02:00"),
+ ]
+ )
+ def test_format_tier(self, _name, tier, expected):
+ self.assertEqual(format_tier(tier), expected)
class TestPlanScheduleReconciliation(TestCase):
def test_splits_into_create_update_and_delete(self):
- desired = {M15: {"a"}, H1: {"b", "c"}}
+ desired = {Tier(M15): {"a"}, Tier(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_create, {tier_schedule_id(DAG_ID, M15): (Tier(M15), {"a"})})
+ self.assertEqual(plan.to_update, {tier_schedule_id(DAG_ID, H1): (Tier(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"})})
+ plan = plan_schedule_reconciliation(DAG_ID, {Tier(M15): {"a"}}, {DAG_ID})
+ self.assertEqual(plan.to_create, {tier_schedule_id(DAG_ID, M15): (Tier(M15), {"a"})})
self.assertEqual(plan.to_update, {})
self.assertEqual(plan.to_delete, {DAG_ID})
@@ -57,3 +124,19 @@ class TestPlanScheduleReconciliation(TestCase):
self.assertEqual(plan.to_create, {})
self.assertEqual(plan.to_update, {})
self.assertEqual(plan.to_delete, existing)
+
+ def test_anchored_and_unanchored_same_cadence_are_distinct_schedules(self):
+ # keying schedules by interval alone would collide these two cohorts,
+ # silently merging a pinned phase with the hash-spread one
+ desired = {Tier(H24): {"a"}, Tier(H24, 0): {"b"}}
+ plan = plan_schedule_reconciliation(DAG_ID, desired, set())
+ self.assertEqual(
+ set(plan.to_create),
+ {tier_schedule_id(DAG_ID, H24), tier_schedule_id(DAG_ID, H24, 0)},
+ )
+
+ def test_clearing_an_anchor_sweeps_the_anchored_schedule(self):
+ existing = {tier_schedule_id(DAG_ID, H24, 0)}
+ plan = plan_schedule_reconciliation(DAG_ID, {Tier(H24): {"a"}}, existing)
+ self.assertEqual(set(plan.to_create), {tier_schedule_id(DAG_ID, H24)})
+ self.assertEqual(plan.to_delete, existing)
diff --git a/products/data_modeling/backend/test/test_node_frequency.py b/products/data_modeling/backend/test/test_node_frequency.py
index ad2926595c11..fcbe545013cf 100644
--- a/products/data_modeling/backend/test/test_node_frequency.py
+++ b/products/data_modeling/backend/test/test_node_frequency.py
@@ -14,10 +14,12 @@ from products.data_modeling.backend.logic.freshness import (
)
from products.data_modeling.backend.logic.node_frequency import (
build_frequency_graph,
+ get_declared_anchor,
get_declared_target,
persist_seed_targets,
resolve_source_intervals,
seed_targets,
+ set_declared_anchor,
set_declared_target,
)
from products.data_modeling.backend.models.dag import DAG
@@ -65,6 +67,23 @@ class TestFrequencyTargetAccessors(BaseTest):
self.assertEqual(node.properties["system"]["suspended"], {"duckdb": True})
self.assertEqual(get_declared_target(node), H1)
+ def test_anchor_and_target_share_the_frequency_key_without_clobbering(self):
+ node = self._node()
+ set_declared_target(node, H1)
+ set_declared_anchor(node, 120)
+ node.refresh_from_db()
+ self.assertEqual(get_declared_target(node), H1)
+ self.assertEqual(get_declared_anchor(node), 120)
+ set_declared_anchor(node, None)
+ node.refresh_from_db()
+ self.assertIsNone(get_declared_anchor(node))
+ self.assertEqual(get_declared_target(node), H1)
+
+ @parameterized.expand([("negative", -1), ("full_week", 10080)])
+ def test_anchor_out_of_range_is_rejected(self, _name, anchor):
+ with self.assertRaises(ValueError):
+ set_declared_anchor(self._node(), anchor)
+
@pytest.mark.django_db
class TestResolveSourceIntervals(BaseTest):
diff --git a/products/data_modeling/backend/test/test_schedule.py b/products/data_modeling/backend/test/test_schedule.py
index ddc181b504ab..5ce52a89d553 100644
--- a/products/data_modeling/backend/test/test_schedule.py
+++ b/products/data_modeling/backend/test/test_schedule.py
@@ -455,12 +455,14 @@ class TestGetV2ScheduledDagIds:
assert result == {"dag-on-v2"}
def test_tiered_schedule_ids_resolve_to_the_dag_id(self):
- # cadence-tier schedules are "{dag_id}:{seconds}"; returning them raw would make every
+ # cadence-tier schedules are "{dag_id}:{seconds}" or "{dag_id}:{seconds}:{anchor}";
+ # returning them raw (or mis-splitting the anchored form) would make every
# v2-detection consumer treat migrated DAGs as v1 and recreate v1 schedules
listings = [
self._listing("dag-a:900", "data-modeling-execute-dag"),
self._listing("dag-a:86400", "data-modeling-execute-dag"),
self._listing("dag-b", "data-modeling-execute-dag"),
+ self._listing("dag-c:86400:120", "data-modeling-execute-dag"),
]
async def fake_list_schedules(*args, **kwargs):
@@ -478,7 +480,7 @@ class TestGetV2ScheduledDagIds:
):
result = get_v2_scheduled_dag_ids()
- assert result == {"dag-a", "dag-b"}
+ assert result == {"dag-a", "dag-b", "dag-c"}
def test_empty_candidates_skips_temporal(self):
connect = mock.AsyncMock()
@@ -486,3 +488,65 @@ class TestGetV2ScheduledDagIds:
result = get_v2_scheduled_dag_ids(set())
assert result == set()
connect.assert_not_called()
+
+
+class TestAnchoredSpec:
+ # anchored specs fire at t ≡ anchor (mod interval), t in minutes from Monday 00:00 UTC
+ @pytest.mark.parametrize(
+ "interval,anchor,expected_hours,expected_minutes",
+ [
+ # 24h @ 00:00: exactly midnight
+ (timedelta(hours=24), 0, {0}, {0}),
+ # 6h @ 07:30: phase 1:30, so 01:30 / 07:30 / 13:30 / 19:30
+ (timedelta(hours=6), 450, {1, 7, 13, 19}, {30}),
+ # 12h @ 14:00: phase 2:00, so 02:00 / 14:00
+ (timedelta(hours=12), 14 * 60, {2, 14}, {0}),
+ # 15min @ 07:00: minute phase 0, every quarter-hour of every hour
+ (timedelta(minutes=15), 420, set(range(24)), {0, 15, 30, 45}),
+ # 30min @ xx:40: minute phase 10
+ (timedelta(minutes=30), 40, set(range(24)), {10, 40}),
+ # 1h @ 01:30: minute phase 30
+ (timedelta(hours=1), 90, set(range(24)), {30}),
+ # the day part of a week-based anchor is inert below weekly cadence:
+ # Tuesday 02:00 (1560) on a daily schedule pins 02:00, same as anchor 120
+ (timedelta(hours=24), 1560, {2}, {0}),
+ ],
+ )
+ def test_fire_times(self, interval, anchor, expected_hours, expected_minutes):
+ spec = build_schedule_spec(uuid.uuid4(), interval, anchor_minutes=anchor)
+ calendar = spec.calendars[0]
+ hours = {h for r in calendar.hour for h in range(r.start, r.end + 1)}
+ minutes = {m for r in calendar.minute for m in range(r.start, r.end + 1)}
+ assert hours == expected_hours
+ assert minutes == expected_minutes
+
+ def test_weekly_anchor_pins_day_of_week(self):
+ # anchor counts days from Monday; Temporal counts day_of_week from Sunday (0),
+ # so Tuesday 02:00 (minute 1560) must land on Temporal day 2, not day 1
+ spec = build_schedule_spec(uuid.uuid4(), timedelta(days=7), anchor_minutes=1560)
+ calendar = spec.calendars[0]
+ assert [(r.start, r.end) for r in calendar.day_of_week] == [(2, 2)]
+ assert [(r.start, r.end) for r in calendar.hour] == [(2, 2)]
+ assert [(r.start, r.end) for r in calendar.minute] == [(0, 0)]
+
+ def test_monthly_anchor_pins_time_but_keeps_hashed_day(self):
+ entity_id = uuid.uuid4()
+ spec = build_schedule_spec(entity_id, timedelta(days=30), anchor_minutes=150)
+ calendar = spec.calendars[0]
+ assert [(r.start, r.end) for r in calendar.hour] == [(2, 2)]
+ assert [(r.start, r.end) for r in calendar.minute] == [(30, 30)]
+ day = calendar.day_of_month[0].start
+ assert 1 <= day <= 28
+ again = build_schedule_spec(entity_id, timedelta(days=30), anchor_minutes=150)
+ assert again.calendars[0].day_of_month == calendar.day_of_month
+
+ @pytest.mark.parametrize(
+ "interval",
+ [timedelta(minutes=15), timedelta(hours=24), timedelta(days=7), timedelta(days=30)],
+ )
+ def test_anchored_specs_are_utc_with_tight_jitter(self, interval):
+ # the hash paths jitter up to 1hr and honor team timezone; a pin of 00:00 that
+ # drifts an hour or shifts with DST is not a pin
+ spec = build_schedule_spec(uuid.uuid4(), interval, team_timezone="US/Eastern", anchor_minutes=0)
+ assert spec.time_zone_name == "UTC"
+ assert spec.jitter == timedelta(minutes=1)
diff --git a/products/data_modeling/backend/test/test_schedule_reconcile.py b/products/data_modeling/backend/test/test_schedule_reconcile.py
index c74bea4f5713..6f2eb687a8c8 100644
--- a/products/data_modeling/backend/test/test_schedule_reconcile.py
+++ b/products/data_modeling/backend/test/test_schedule_reconcile.py
@@ -10,9 +10,14 @@ 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 UnsupportedFrequencyTargetError
-from products.data_modeling.backend.logic.node_frequency import set_declared_target
+from products.data_modeling.backend.logic.node_frequency import (
+ get_declared_anchor,
+ set_declared_anchor,
+ set_declared_target,
+)
from products.data_modeling.backend.logic.saved_query_dag_sync import promote_dag_view_nodes_to_matview
from products.data_modeling.backend.logic.schedule_reconcile import (
+ apply_saved_query_frequency_anchor,
convert_dag_to_tiers,
maybe_reconcile_dag,
reconcile_dag_schedules,
@@ -122,6 +127,66 @@ class TestReconcileDagSchedules(BaseTest):
create.assert_not_called()
delete.assert_not_called()
+ def test_anchored_node_gets_its_own_pinned_schedule(self):
+ # an anchor that never reaches Temporal is a silent fleet-wide no-op: the node keeps
+ # firing on its hash slot while the operator believes it is pinned
+ dag = DAG.get_or_create_default(self.team)
+ source = _table_node(self.team, dag, "events", {"origin": "posthog"})
+ spread = _saved_query_node(self.team, dag, "spread", NodeType.MAT_VIEW)
+ pinned = _saved_query_node(self.team, dag, "pinned", NodeType.MAT_VIEW)
+ Edge.objects.create(team=self.team, dag=dag, source=source, target=spread)
+ Edge.objects.create(team=self.team, dag=dag, source=source, target=pinned)
+ set_declared_target(spread, M15)
+ set_declared_target(pinned, M15)
+ set_declared_anchor(pinned, 120)
+
+ async def fake_list_schedules(*_args, **_kwargs):
+ async def gen():
+ return
+ yield
+
+ return gen()
+
+ temporal = mock.Mock()
+ temporal.list_schedules = fake_list_schedules
+
+ with (
+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=temporal)),
+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,
+ mock.patch(f"{RECONCILE}.a_update_schedule", new=mock.AsyncMock()),
+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()),
+ ):
+ reconcile_dag_schedules(dag)
+
+ dag_id = str(dag.id)
+ created = {call.kwargs["id"]: call.kwargs["schedule"] for call in create.call_args_list}
+ # the raw anchor (02:00) reduces to phase 0 within a 15min cadence, and the schedule id
+ # carries the canonical phase so equivalent anchors share one schedule
+ self.assertEqual(set(created), {tier_schedule_id(dag_id, M15), tier_schedule_id(dag_id, M15, 0)})
+
+ anchored = created[tier_schedule_id(dag_id, M15, 0)]
+ self.assertEqual(anchored.action.args[0]["node_ids"], [str(pinned.id)])
+ self.assertEqual(anchored.spec.time_zone_name, "UTC")
+ self.assertEqual(anchored.spec.jitter, timedelta(minutes=1))
+ minutes = {r.start for r in anchored.spec.calendars[0].minute}
+ self.assertEqual(minutes, {0, 15, 30, 45})
+
+ def test_apply_saved_query_frequency_anchor_writes_nodes_and_queues_reconcile(self):
+ dag = DAG.get_or_create_default(self.team)
+ matview = _saved_query_node(self.team, dag, "mv", NodeType.MAT_VIEW)
+ assert matview.saved_query is not None
+ with mock.patch(f"{RECONCILE}.maybe_reconcile_dag") as reconcile:
+ written = apply_saved_query_frequency_anchor(matview.saved_query, 120)
+ self.assertEqual(written, 1)
+ matview.refresh_from_db()
+ self.assertEqual(get_declared_anchor(matview), 120)
+ reconcile.assert_called_once()
+
+ with mock.patch(f"{RECONCILE}.maybe_reconcile_dag"):
+ apply_saved_query_frequency_anchor(matview.saved_query, None)
+ matview.refresh_from_db()
+ self.assertIsNone(get_declared_anchor(matview))
+
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"})
diff --git a/products/data_modeling/backend/test/test_set_schedule_anchor.py b/products/data_modeling/backend/test/test_set_schedule_anchor.py
new file mode 100644
index 000000000000..2d0d59d6c321
--- /dev/null
+++ b/products/data_modeling/backend/test/test_set_schedule_anchor.py
@@ -0,0 +1,163 @@
+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 django.core.management.base import CommandError
+
+from products.data_modeling.backend.logic.node_frequency import (
+ get_declared_anchor,
+ set_declared_anchor,
+ set_declared_target,
+)
+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 NodeType
+from products.data_modeling.backend.test.helpers import (
+ saved_query_node as _saved_query_node,
+ table_node as _table_node,
+)
+
+COMMAND = "products.data_modeling.backend.management.commands.set_schedule_anchor"
+
+M15 = timedelta(minutes=15)
+H1 = timedelta(hours=1)
+WEEKLY = timedelta(days=7)
+
+
+class TestSetScheduleAnchor(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.dag = DAG.get_or_create_default(self.team)
+ self.source = _table_node(self.team, self.dag, "events", {"origin": "posthog"})
+ self.matview = _saved_query_node(self.team, self.dag, "mv", NodeType.MAT_VIEW)
+ Edge.objects.create(team=self.team, dag=self.dag, source=self.source, target=self.matview)
+ set_declared_target(self.matview, H1)
+
+ def _run(self, *args, reconcile_applied=True):
+ out = StringIO()
+ with (
+ mock.patch(f"{COMMAND}.tiered_schedules_enabled", return_value=True),
+ mock.patch(f"{COMMAND}.reconcile_dag_schedules", return_value=reconcile_applied) as reconcile,
+ ):
+ call_command("set_schedule_anchor", "--team-id", str(self.team.pk), *args, stdout=out)
+ return out.getvalue(), reconcile
+
+ def test_dag_mode_writes_anchor_and_reconciles(self):
+ output, reconcile = self._run("--dag-id", str(self.dag.id), "--at", "00:00")
+ self.matview.refresh_from_db()
+ self.assertEqual(get_declared_anchor(self.matview), 0)
+ reconcile.assert_called_once_with(self.dag, require_tiered=True)
+ self.assertIn("1hour@00:00", output)
+
+ def test_saved_query_mode_anchors_only_the_named_query(self):
+ other = _saved_query_node(self.team, self.dag, "other", NodeType.MAT_VIEW)
+ Edge.objects.create(team=self.team, dag=self.dag, source=self.source, target=other)
+ set_declared_target(other, H1)
+ self._run("--saved-query-names", "mv", "--at", "02:30")
+ self.matview.refresh_from_db()
+ other.refresh_from_db()
+ self.assertEqual(get_declared_anchor(self.matview), 150)
+ self.assertIsNone(get_declared_anchor(other))
+
+ def test_dry_run_writes_nothing_but_shows_resulting_tiers(self):
+ output, reconcile = self._run("--dag-id", str(self.dag.id), "--at", "00:00", "--dry-run")
+ self.matview.refresh_from_db()
+ self.assertIsNone(get_declared_anchor(self.matview))
+ reconcile.assert_not_called()
+ self.assertIn("1hour@00:00", output)
+
+ def test_clear_removes_anchor(self):
+ set_declared_anchor(self.matview, 120)
+ output, _reconcile = self._run("--dag-id", str(self.dag.id), "--clear")
+ self.matview.refresh_from_db()
+ self.assertIsNone(get_declared_anchor(self.matview))
+ # a clear reported as "anchored" reads as the opposite operation in operator logs
+ self.assertIn("cleared 1 node(s)", output)
+
+ def test_on_sets_the_day_component(self):
+ self._run("--saved-query-names", "mv", "--at", "02:00", "--on", "tuesday")
+ self.matview.refresh_from_db()
+ self.assertEqual(get_declared_anchor(self.matview), 1560)
+
+ def test_refuses_weekly_node_without_on(self):
+ set_declared_target(self.matview, WEEKLY)
+ with self.assertRaisesRegex(CommandError, "weekly cadence"):
+ self._run("--dag-id", str(self.dag.id), "--at", "00:00")
+ self.matview.refresh_from_db()
+ self.assertIsNone(get_declared_anchor(self.matview))
+
+ def test_refuses_upstream_cone_spanning_cadences(self):
+ downstream = _saved_query_node(self.team, self.dag, "report", NodeType.MAT_VIEW)
+ Edge.objects.create(team=self.team, dag=self.dag, source=self.matview, target=downstream)
+ set_declared_target(self.matview, M15)
+ set_declared_target(downstream, H1)
+ with self.assertRaisesRegex(CommandError, "spans cadences"):
+ self._run("--saved-query-names", "report", "--at", "00:00", "--with-upstream")
+
+ def test_clear_with_upstream_is_allowed_on_a_cone_spanning_cadences(self):
+ # a cone anchored while aligned can drift apart later; clearing must stay possible
+ downstream = _saved_query_node(self.team, self.dag, "report", NodeType.MAT_VIEW)
+ Edge.objects.create(team=self.team, dag=self.dag, source=self.matview, target=downstream)
+ set_declared_target(self.matview, M15)
+ set_declared_target(downstream, H1)
+ set_declared_anchor(self.matview, 0)
+ set_declared_anchor(downstream, 0)
+ self._run("--saved-query-names", "report", "--clear", "--with-upstream")
+ self.matview.refresh_from_db()
+ downstream.refresh_from_db()
+ self.assertIsNone(get_declared_anchor(self.matview))
+ self.assertIsNone(get_declared_anchor(downstream))
+
+ def test_untiered_dag_stores_anchor_but_says_so_instead_of_claiming_reconcile(self):
+ output, _reconcile = self._run("--dag-id", str(self.dag.id), "--at", "00:00", reconcile_applied=False)
+ self.matview.refresh_from_db()
+ self.assertEqual(get_declared_anchor(self.matview), 0)
+ self.assertIn("not on cadence-tier schedules yet", output)
+
+ def test_a_refusal_on_one_dag_writes_nothing_anywhere(self):
+ # a --saved-query-names set spanning two DAGs must validate both before writing to either:
+ # the second DAG's weekly refusal must not leave the first already anchored and reconciled
+ other_dag = DAG.objects.create(team=self.team, name="Other")
+ weekly_node = _saved_query_node(self.team, other_dag, "weekly_mv", NodeType.MAT_VIEW)
+ set_declared_target(weekly_node, WEEKLY)
+
+ with self.assertRaisesRegex(CommandError, "weekly cadence"):
+ self._run("--saved-query-names", "mv", "weekly_mv", "--at", "00:00")
+
+ self.matview.refresh_from_db()
+ weekly_node.refresh_from_db()
+ self.assertIsNone(get_declared_anchor(self.matview))
+ self.assertIsNone(get_declared_anchor(weekly_node))
+
+ def test_with_upstream_anchors_the_cone_when_cadences_align(self):
+ downstream = _saved_query_node(self.team, self.dag, "report", NodeType.MAT_VIEW)
+ Edge.objects.create(team=self.team, dag=self.dag, source=self.matview, target=downstream)
+ set_declared_target(downstream, H1)
+ self._run("--saved-query-names", "report", "--at", "00:00", "--with-upstream")
+ self.matview.refresh_from_db()
+ downstream.refresh_from_db()
+ self.assertEqual(get_declared_anchor(self.matview), 0)
+ self.assertEqual(get_declared_anchor(downstream), 0)
+
+ def test_refuses_team_off_the_tiered_flag(self):
+ with mock.patch(f"{COMMAND}.tiered_schedules_enabled", return_value=False):
+ with self.assertRaisesRegex(CommandError, "tiered-schedules flag"):
+ call_command(
+ "set_schedule_anchor", "--team-id", str(self.team.pk), "--dag-id", str(self.dag.id), "--at", "00:00"
+ )
+
+ def test_rejects_malformed_arguments(self):
+ for args, message in [
+ (["--dag-id", str(self.dag.id), "--saved-query-names", "mv", "--at", "00:00"], "exactly one of --dag-id"),
+ (["--dag-id", str(self.dag.id)], "exactly one of --at"),
+ (["--dag-id", str(self.dag.id), "--at", "00:00", "--clear"], "exactly one of --at"),
+ (["--dag-id", str(self.dag.id), "--at", "24:00"], "HH:MM"),
+ (["--dag-id", str(self.dag.id), "--clear", "--on", "monday"], "no effect with --clear"),
+ ]:
+ with self.assertRaisesRegex(CommandError, message):
+ self._run(*args)
diff --git a/products/data_modeling/backend/test/test_tier_membership.py b/products/data_modeling/backend/test/test_tier_membership.py
index 6f79d0d34325..c7a9ad10880b 100644
--- a/products/data_modeling/backend/test/test_tier_membership.py
+++ b/products/data_modeling/backend/test/test_tier_membership.py
@@ -1,10 +1,12 @@
import asyncio
+from datetime import timedelta
from unittest import mock
from parameterized import parameterized
from temporalio.client import ScheduleActionStartWorkflow, ScheduleListActionStartWorkflow
+from products.data_modeling.backend.logic.cohort_scheduling import Tier
from products.data_modeling.backend.logic.tier_membership import (
CORRECTLY_UNSCHEDULED,
OVER_SCHEDULED,
@@ -17,31 +19,44 @@ from products.data_modeling.backend.logic.tier_membership import (
read_live_tiers,
)
+DAILY = Tier(timedelta(days=1))
+DAILY_ANCHORED = Tier(timedelta(days=1), 1350)
-def _tier(interval_seconds, node_ids):
+
+def _tier(interval_seconds, node_ids, anchor_minutes=None):
+ schedule_id = "dag" if interval_seconds is None else f"dag:{interval_seconds}"
+ if anchor_minutes is not None:
+ schedule_id += f":{anchor_minutes}"
return LiveTier(
- schedule_id=f"dag:{interval_seconds}" if interval_seconds is not None else "dag",
+ schedule_id=schedule_id,
interval_seconds=interval_seconds,
covers_whole_dag=node_ids is None,
node_ids=frozenset(node_ids) if node_ids is not None else None,
+ anchor_minutes=anchor_minutes,
)
class TestClassifyNode:
@parameterized.expand(
[
- # (live_tiers, expected_interval, expected_verdict)
- ("on the tier it should be on", [_tier(86400, {"n"})], 86400, SCHEDULED),
- ("covered by a whole-DAG schedule", [_tier(None, None)], 86400, SCHEDULED),
- ("scheduled but at the wrong cadence", [_tier(3600, {"n"})], 86400, SCHEDULED_WRONG_TIER),
+ # (live_tiers, expected_tier, expected_verdict)
+ ("on the tier it should be on", [_tier(86400, {"n"})], DAILY, SCHEDULED),
+ ("covered by a whole-DAG schedule", [_tier(None, None)], DAILY, SCHEDULED),
+ ("scheduled but at the wrong cadence", [_tier(3600, {"n"})], DAILY, SCHEDULED_WRONG_TIER),
# The managed_product_lifecycle case: has a target, but no live tier lists it.
- ("has a target but no live tier covers it", [_tier(86400, {"other"})], 86400, STALE_NEEDS_RECONCILE),
- ("no tiers exist at all yet", [], 86400, STALE_NEEDS_RECONCILE),
+ ("has a target but no live tier covers it", [_tier(86400, {"other"})], DAILY, STALE_NEEDS_RECONCILE),
+ ("no tiers exist at all yet", [], DAILY, STALE_NEEDS_RECONCILE),
("in a tier reconcile would drop", [_tier(86400, {"n"})], None, OVER_SCHEDULED),
("no target and no tier — the opt-out", [_tier(86400, {"other"})], None, CORRECTLY_UNSCHEDULED),
+ # anchor drift is drift: a live hash-spread schedule does not satisfy an anchored
+ # expectation (or vice versa), else the exact state anchors are set to escape
+ # reads as healthy
+ ("anchored expectation, unanchored live tier", [_tier(86400, {"n"})], DAILY_ANCHORED, SCHEDULED_WRONG_TIER),
+ ("anchored expectation matched", [_tier(86400, {"n"}, 1350)], DAILY_ANCHORED, SCHEDULED),
+ ("unanchored expectation, anchored live tier", [_tier(86400, {"n"}, 1350)], DAILY, SCHEDULED_WRONG_TIER),
]
)
- def test_verdict(self, _name, live_tiers, expected_interval, expected_verdict):
+ def test_verdict(self, _name, live_tiers, expected_tier, expected_verdict):
status = classify_node(
node_id="n",
name="a_view",
@@ -49,7 +64,7 @@ class TestClassifyNode:
dag_id="dag",
dag_name="Default",
live_tiers=live_tiers,
- expected_interval=expected_interval,
+ expected_tier=expected_tier,
)
assert status.verdict == expected_verdict
@@ -64,7 +79,7 @@ class TestClassifyNode:
dag_id="dag",
dag_name="Default",
live_tiers=[],
- expected_interval=86400,
+ expected_tier=DAILY,
reconcile_blocked=True,
)
assert status.verdict == UNSUPPORTED_TARGET
@@ -86,11 +101,13 @@ class TestReadLiveTiers:
def test_reads_node_ids_and_ignores_non_execute_dag(self):
listings = [
self._listing("dag:86400", "data-modeling-execute-dag"),
+ self._listing("dag:86400:1350", "data-modeling-execute-dag"), # anchored cohort
self._listing("dag", "data-modeling-execute-dag"), # legacy single schedule (whole DAG)
self._listing("some-sq-id", "data-modeling-run"), # v1 — must be ignored
]
describe_by_id = {
"dag:86400": self._describe_returning(["n1", "n2"]),
+ "dag:86400:1350": self._describe_returning(["n3"]),
"dag": self._describe_returning(None),
}
@@ -107,9 +124,12 @@ class TestReadLiveTiers:
tiers = asyncio.run(read_live_tiers(temporal, "dag"))
- by_interval = {t.interval_seconds: t for t in tiers}
- assert set(by_interval) == {86400, None} # the v1 data-modeling-run schedule was skipped
- assert by_interval[86400].node_ids == frozenset({"n1", "n2"})
- assert by_interval[86400].covers_whole_dag is False
- assert by_interval[None].covers_whole_dag is True
- assert by_interval[None].node_ids is None
+ by_id = {t.schedule_id: t for t in tiers}
+ # the v1 data-modeling-run schedule was skipped
+ assert set(by_id) == {"dag:86400", "dag:86400:1350", "dag"}
+ assert by_id["dag:86400"].node_ids == frozenset({"n1", "n2"})
+ assert (by_id["dag:86400"].covers_whole_dag, by_id["dag:86400"].anchor_minutes) == (False, None)
+ assert (by_id["dag:86400:1350"].interval_seconds, by_id["dag:86400:1350"].anchor_minutes) == (86400, 1350)
+ assert by_id["dag:86400:1350"].node_ids == frozenset({"n3"})
+ assert by_id["dag"].covers_whole_dag is True
+ assert by_id["dag"].node_ids is None
diff --git a/products/data_modeling/backend/test/test_tier_run_report.py b/products/data_modeling/backend/test/test_tier_run_report.py
index b7dac5010bf1..fe2db7ba1b93 100644
--- a/products/data_modeling/backend/test/test_tier_run_report.py
+++ b/products/data_modeling/backend/test/test_tier_run_report.py
@@ -4,7 +4,7 @@ from posthog.test.base import BaseTest
from parameterized import parameterized
-from products.data_modeling.backend.logic.node_frequency import set_declared_target
+from products.data_modeling.backend.logic.node_frequency import set_declared_anchor, set_declared_target
from products.data_modeling.backend.logic.tier_run_report import (
BLOCKED,
CANCELLED,
@@ -169,6 +169,26 @@ class TestTierRunReport(BaseTest):
assert [(tier.label, tier.seconds) for tier in tiers] == [("1hour", 3600), ("1day", 86400)]
assert [[node.name for node in tier.nodes] for tier in tiers] == [["hourly_model"], ["daily_model"]]
+ def test_an_anchored_cohort_reports_its_own_schedule_and_run(self):
+ # an anchored cohort is its own Temporal schedule with a 3-segment id; grouping by bare
+ # interval or prefix-matching the 2-segment id would report every anchored node MISSING
+ # on exactly the DAGs an operator anchored for closest observation
+ anchored = self._node("anchored_model", DAILY)
+ set_declared_anchor(anchored, 1350)
+ spread = self._node("spread_model", DAILY)
+ anchored_parent = f"execute-dag-{self.dag.id}:86400:1350-2026-07-25T22:30:00Z"
+ self._job(anchored, parent_workflow_id=anchored_parent, status=DataModelingJobStatus.COMPLETED)
+ self._job(spread, parent_workflow_id=self._daily_parent(), status=DataModelingJobStatus.COMPLETED)
+
+ spread_tier, anchored_tier = build_tier_runs(self.dag)
+
+ assert anchored_tier.schedule_id == f"{self.dag.id}:86400:1350"
+ assert anchored_tier.parent_workflow_id == anchored_parent
+ assert [n.status for n in anchored_tier.nodes] == [OK]
+ assert spread_tier.schedule_id == f"{self.dag.id}:86400"
+ assert [(n.name, n.status) for n in spread_tier.nodes] == [("spread_model", OK)]
+ assert spread_tier.slug != anchored_tier.slug
+
def test_untargeted_nodes_are_reported_outside_every_tier(self):
table_node(self.team, self.dag, "source_table", {})
self._node("targeted", DAILY)
@@ -276,16 +296,32 @@ class TestTierRunReport(BaseTest):
assert {n.name: n.status for n in tier.nodes}["both"] == SUSPENDED
def test_a_node_suspended_in_another_tier_blocks_its_descendants_here(self):
- # execute_dag reads suspended_nodes for the whole DAG, so a suspension on the daily tier
- # skips hourly descendants; seeding blocks only from this tier would call them unexplained
- upstream = self._node("daily_upstream", DAILY)
- downstream = self._node("hourly_downstream", HOURLY)
+ # execute_dag reads suspended_nodes for the whole DAG, so a suspension on the hourly tier
+ # skips daily descendants; seeding blocks only from this tier would call them unexplained
+ upstream = self._node("hourly_upstream", HOURLY)
+ downstream = self._node("daily_downstream", DAILY)
Edge.objects.create(team=self.team, dag=self.dag, source=upstream, target=downstream)
self._suspend(upstream)
- hourly, _daily = build_tier_runs(self.dag)
+ _hourly, daily = build_tier_runs(self.dag)
+
+ assert {n.name: n.status for n in daily.nodes}["daily_downstream"] == BLOCKED
+
+ def test_a_node_rides_its_effective_cadence_tier_not_its_declared_one(self):
+ # schedules bucket by effective cadence (min of own target and downstream, source-clamped),
+ # so a declared-daily node above a 15min consumer runs under the 15min schedule; grouping
+ # by declared target would look it up in a daily run that never contains it
+ upstream = self._node("upstream_model", DAILY)
+ consumer = self._node("consumer_model", timedelta(minutes=15))
+ Edge.objects.create(team=self.team, dag=self.dag, source=upstream, target=consumer)
+ parent = f"execute-dag-{self.dag.id}:900-2026-07-25T03:00:00Z"
+ self._job(upstream, parent_workflow_id=parent, status=DataModelingJobStatus.COMPLETED)
+ self._job(consumer, parent_workflow_id=parent, status=DataModelingJobStatus.COMPLETED)
+
+ (tier,) = build_tier_runs(self.dag)
- assert {n.name: n.status for n in hourly.nodes}["hourly_downstream"] == BLOCKED
+ assert tier.seconds == 900
+ assert {n.name: n.status for n in tier.nodes} == {"upstream_model": OK, "consumer_model": OK}
def test_only_the_serving_engine_counts_for_suspension_and_for_jobs(self):
# the duckgres shadow suspends independently and writes its own job row; neither should