:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-modeling): show the cadence a view inherits from its consumers (#125589)
Jovan Sakovic02d58e45c23c
diff --git a/frontend/src/scenes/data-warehouse/saved_queries/SyncFrequencySelect.test.ts b/frontend/src/scenes/data-warehouse/saved_queries/SyncFrequencySelect.test.tsindex 93aa6d97d1ab..b23f4ecb103d 100644--- a/frontend/src/scenes/data-warehouse/saved_queries/SyncFrequencySelect.test.ts+++ b/frontend/src/scenes/data-warehouse/saved_queries/SyncFrequencySelect.test.ts@@ -4,7 +4,10 @@ import {buildExplanation,buildOptions,defaultCadenceWithin,+ inheritedCadence,modeDisabledReason,+ SyncFrequencyValue,+ speedUpWarning,unsatisfiableReason,} from './SyncFrequencySelect'@@ -38,8 +41,8 @@ describe('SyncFrequencySelect', () => {const bySource = options.find((option) => option.value === '15min')const byConsumer = options.find((option) => option.value === '24hour')- expect(bySource?.disabledReason).toBe('More often than stripe_invoices syncs')- expect(byConsumer?.disabledReason).toBe('Too slow for daily_revenue')+ expect(bySource?.disabledReason).toBe('More often than upstream source stripe_invoices syncs')+ expect(byConsumer?.disabledReason).toBe('Too slow for downstream view daily_revenue')expect(options.find((option) => option.value === '6hour')?.disabledReason).toBeUndefined()})@@ -93,16 +96,16 @@ describe('SyncFrequencySelect', () => {it('names both ends and what to change when the bounds cross', () => {// Every cadence blocked means Materialize would 400 whatever the picker had selected.expect(unsatisfiableReason(nothingAllowed())).toBe(- 'No cadence works here: stripe_invoices only syncs every 6 hours, ' +- 'but daily_revenue refreshes every 12 hours. ' +- 'Slow down daily_revenue or speed up stripe_invoices.'+ 'No cadence works here: upstream source stripe_invoices only syncs every 6 hours, ' ++ 'but downstream view daily_revenue refreshes every 12 hours. ' ++ 'Slow down downstream view daily_revenue or speed up upstream source stripe_invoices.')})it('asks for the source to speed up when only a floor blocks every cadence', () => {expect(unsatisfiableReason(nothingAllowed({ ceiling: null }))).toBe(- 'No cadence works here: stripe_invoices only syncs every 6 hours, ' +- 'less often than anything this can refresh at. Speed up stripe_invoices first.'+ 'No cadence works here: upstream source stripe_invoices only syncs every 6 hours, ' ++ 'less often than anything this can refresh at. Speed up upstream source stripe_invoices first.')})@@ -132,10 +135,10 @@ describe('SyncFrequencySelect', () => {)expect(options.find((option) => option.value === '15min')?.disabledReason).toBe(- 'More often than the sources this view reads'+ 'More often than the upstream sources sync')expect(options.find((option) => option.value === '24hour')?.disabledReason).toBe(- 'Too slow for something built on this view'+ 'Too slow for a downstream view')})@@ -196,4 +199,102 @@ describe('SyncFrequencySelect', () => {expect(modeDisabledReason(bounds())).toBeNull()})})++ describe('speedUpWarning', () => {+ const withSpeedsUp = (names: string[], withheld = false): SyncFrequencyBoundsApi =>+ bounds({+ options: [+ {+ cadence: '6hour',+ allowed: true,+ blocked_by: null,+ blocker: null,+ speeds_up: names.map(blocker),+ speeds_up_withheld: withheld,+ },+ ],+ } as Partial<SyncFrequencyBoundsApi>)++ it.each([+ ['nothing upstream is slower', [], false, null],+ [+ 'one upstream view is slower',+ ['org_universe'],+ false,+ 'Upstream view org_universe also refreshes every 6 hours to keep up with this view.',+ ],+ [+ 'a slower upstream view is withheld',+ ['org_universe'],+ true,+ 'Upstream views org_universe and others also refresh every 6 hours to keep up with this view.',+ ],+ [+ 'every slower upstream view is withheld',+ [],+ true,+ 'Some upstream views also refresh every 6 hours to keep up with this view.',+ ],+ ])('when %s', (_case, names, withheld, expected) => {+ expect(speedUpWarning(withSpeedsUp(names, withheld), '6hour')).toBe(expected)+ })+ })++ describe('inheritedCadence', () => {+ const consumerBound = (name: string | null): SyncFrequencyBoundsApi =>+ bounds({+ options: [+ {+ cadence: '1hour',+ allowed: true,+ blocked_by: null,+ blocker: null,+ speeds_up: [],+ speeds_up_withheld: false,+ },+ {+ cadence: '6hour',+ allowed: true,+ blocked_by: null,+ blocker: null,+ speeds_up: [],+ speeds_up_withheld: false,+ },+ {+ cadence: '24hour',+ allowed: false,+ blocked_by: 'consumer',+ blocker: null,+ speeds_up: [],+ speeds_up_withheld: false,+ },+ ],+ ceiling: { label: '6 hours', blocker: name ? blocker(name) : null },+ } as Partial<SyncFrequencyBoundsApi>)++ it.each([+ ['the saved setting is allowed', consumerBound('maps'), '6hour', null],+ ['the view is paused', consumerBound('maps'), 'never', null],+ [+ 'a consumer needs it fresher',+ consumerBound('maps'),+ '24hour',+ {+ cadence: '6hour',+ note: 'Refreshes every 6 hours to keep up with downstream view maps. Your 1 day setting applies again if maps refreshes less often.',+ },+ ],+ [+ 'the consumer is withheld',+ consumerBound(null),+ '24hour',+ {+ cadence: '6hour',+ note: 'Refreshes every 6 hours to keep up with a downstream view. Your 1 day setting applies again if that view refreshes less often.',+ },+ ],+ ])('when %s', (_case, input, value, expected) => {+ expect(inheritedCadence(input, value as SyncFrequencyValue)).toEqual(expected)+ })+ })})diff --git a/frontend/src/scenes/data-warehouse/saved_queries/SyncFrequencySelect.tsx b/frontend/src/scenes/data-warehouse/saved_queries/SyncFrequencySelect.tsxindex dd47036ab195..463cece1a3c4 100644--- a/frontend/src/scenes/data-warehouse/saved_queries/SyncFrequencySelect.tsx+++ b/frontend/src/scenes/data-warehouse/saved_queries/SyncFrequencySelect.tsx@@ -1,6 +1,8 @@-import { IconRabbit, IconTortoise } from '@posthog/icons'+import { IconInfo, IconRabbit, IconTortoise } from '@posthog/icons'import { LemonLabel, LemonSegmentedButton, LemonSegmentedButtonOption, Spinner } from '@posthog/lemon-ui'+import { Tooltip } from 'lib/lemon-ui/Tooltip'+import { DataModelingSyncInterval } from '~/types'import { SyncFrequencyBoundsApi } from 'products/data_warehouse/frontend/generated/api.schemas'@@ -87,8 +89,10 @@ export function SyncFrequencySelect({disabledReason,'data-attr': dataAttr,}: SyncFrequencySelectProps): JSX.Element {+ const inherited = inheritedCadence(bounds, value)+ const selectedSpeedUp = value && value !== 'never' ? speedUpWarning(bounds, value) : nullconst options = buildOptions(bounds)- const explanation = buildExplanation(bounds)+ const explanation = buildExplanation(bounds, { omitCeiling: !!inherited })const modeReason = modeDisabledReason(bounds)const reason =disabledReason ??@@ -119,18 +123,99 @@ export function SyncFrequencySelect({<IconRabbit className={PACE_ICON_CLASS} aria-hidden /><LemonSegmentedButton<DataModelingSyncInterval>size="small"- value={value && value !== 'never' ? value : undefined}- onChange={(next) => onChange(next)}+ value={inherited?.cadence ?? (value && value !== 'never' ? value : undefined)}+ onChange={(next) => {+ if (next !== value) {+ onChange(next)+ }+ }}options={options}disabledReason={reason}/><IconTortoise className={PACE_ICON_CLASS} aria-hidden /></div>+ {inherited && (+ <span className="text-xs text-secondary max-w-prose">+ <WithUpstreamRule text={inherited.note} />+ </span>+ )}+ {selectedSpeedUp && (+ <span className="text-xs text-secondary max-w-prose">+ <WithUpstreamRule text={selectedSpeedUp} />+ </span>+ )}{explanation && <span className="text-xs text-secondary max-w-prose">{explanation}</span>}</div>)}+/**+ * What else a cadence changes, or null when it only changes this view.+ *+ * A view can't be fresher than its inputs, so a slower upstream view runs at this cadence for as long+ * as this view does. Its saved setting is left alone.+ */+export function speedUpWarning(+ bounds: SyncFrequencyBoundsApi | null | undefined,+ cadence: DataModelingSyncInterval+): string | null {+ const option = bounds?.options.find((candidate) => candidate.cadence === cadence)+ if (!option || (!option.speeds_up?.length && !option.speeds_up_withheld)) {+ return null+ }++ const named = option.speeds_up.map((view) => view.name).filter(Boolean)+ const plural = named.length > 1 || option.speeds_up_withheld || !named.length+ const subject = !named.length+ ? 'Some upstream views'+ : `${plural ? 'Upstream views' : 'Upstream view'} ${named.join(', ')}${option.speeds_up_withheld ? ' and others' : ''}`+ return `${subject} also ${plural ? 'refresh' : 'refreshes'} every ${CADENCE_LABELS[cadence]} to keep up with this view.`+}++const UPSTREAM_RULE =+ "A view can't be fresher than the data it reads, so upstream views refresh at least as often as the downstream views built on them."++function WithUpstreamRule({ text }: { text: string }): JSX.Element {+ return (+ <>+ <span>{text}</span>{' '}+ <Tooltip title={UPSTREAM_RULE}>+ <IconInfo className="inline align-text-bottom text-sm" aria-label={UPSTREAM_RULE} />+ </Tooltip>+ </>+ )+}++/**+ * The cadence a view actually runs at when its saved setting is slower than a consumer needs.+ *+ * The scheduler runs a view at the finest cadence among itself and its consumers, so the saved+ * setting is a lower bound on freshness, not the schedule. Options arrive coarsest-last, so the last+ * allowed one is the consumer ceiling.+ */+export function inheritedCadence(+ bounds: SyncFrequencyBoundsApi | null | undefined,+ value: SyncFrequencyValue | null+): { cadence: DataModelingSyncInterval; note: string } | null {+ if (!bounds || !value || value === 'never') {+ return null+ }+ const saved = bounds.options.find((option) => option.cadence === value)+ const allowed = bounds.options.filter((option) => option.allowed)+ if (!saved || saved.allowed || saved.blocked_by !== 'consumer' || !allowed.length) {+ return null+ }++ const cadence = allowed[allowed.length - 1].cadence as DataModelingSyncInterval+ const consumer = bounds.ceiling?.blocker?.name+ return {+ cadence,+ note:+ `Refreshes every ${CADENCE_LABELS[cadence]} to keep up with ${consumer ? `downstream view ${consumer}` : 'a downstream view'}. ` ++ `Your ${CADENCE_LABELS[value]} setting applies again if ${consumer ?? 'that view'} refreshes less often.`,+ }+}+export function buildOptions(bounds?: SyncFrequencyBoundsApi | null): LemonSegmentedButtonOption<DataModelingSyncInterval>[] {@@ -162,10 +247,10 @@ function segment(cadence: DataModelingSyncInterval): LemonSegmentedButtonOption<function blockedReason(option: SyncFrequencyBoundsApi['options'][number], bounds: SyncFrequencyBoundsApi): string {const name = option.blocker?.nameif (option.blocked_by === 'source' && bounds.floor) {- return name ? `More often than ${name} syncs` : 'More often than the sources this view reads'+ return name ? `More often than upstream source ${name} syncs` : 'More often than the upstream sources sync'}if (option.blocked_by === 'consumer' && bounds.ceiling) {- return name ? `Too slow for ${name}` : 'Too slow for something built on this view'+ return name ? `Too slow for downstream view ${name}` : 'Too slow for a downstream view'}return 'Not available for this view'}@@ -182,8 +267,10 @@ export function unsatisfiableReason(bounds?: SyncFrequencyBoundsApi | null): strreturn null}- const source = bounds.floor?.blocker?.name ?? 'an upstream source'- const consumer = bounds.ceiling?.blocker?.name ?? 'a view or endpoint built on this one'+ const sourceName = bounds.floor?.blocker?.name+ const consumerName = bounds.ceiling?.blocker?.name+ const source = sourceName ? `upstream source ${sourceName}` : 'an upstream source'+ const consumer = consumerName ? `downstream view ${consumerName}` : 'a downstream view or endpoint'if (bounds.floor && bounds.ceiling) {return (`No cadence works here: ${source} only syncs every ${bounds.floor.label}, ` +@@ -232,28 +319,33 @@ export function defaultCadenceWithin(return pool.reduce((coarsest, cadence) => (rank(cadence) > rank(coarsest) ? cadence : coarsest))}-export function buildExplanation(bounds?: SyncFrequencyBoundsApi | null): string | null {+export function buildExplanation(+ bounds?: SyncFrequencyBoundsApi | null,+ { omitCeiling = false }: { omitCeiling?: boolean } = {}+): string | null {if (!bounds || bounds.frequency_mode !== 'tiered') {return null}const parts: string[] = []+ const floor = bounds.floor+ const ceiling = omitCeiling ? null : bounds.ceiling// A withheld blocker still has to hold its slot in the sentence, and the two slots read// differently: one opens a sentence, one sits mid-clause.- const floorName = bounds.floor?.blocker?.name ?? 'An upstream source'- const ceilingLead = bounds.ceiling?.blocker?.name ?? 'A downstream view'- const ceilingMid = bounds.ceiling?.blocker?.name ?? 'a downstream view'+ const floorName = floor?.blocker?.name ? `Upstream source ${floor.blocker.name}` : 'An upstream source'+ const ceilingLead = ceiling?.blocker?.name ? `Downstream view ${ceiling.blocker.name}` : 'A downstream view'+ const ceilingMid = ceiling?.blocker?.name ? `downstream view ${ceiling.blocker.name}` : 'a downstream view'- if (bounds.floor && bounds.ceiling) {+ if (floor && ceiling) {parts.push(- `Pick between ${bounds.floor.label} and ${bounds.ceiling.label}. ` +- `${floorName} syncs every ${bounds.floor.label}, ` +- `and ${ceilingMid} refreshes every ${bounds.ceiling.label}.`+ `Pick between ${floor.label} and ${ceiling.label}. ` ++ `${floorName} syncs every ${floor.label}, ` ++ `and ${ceilingMid} refreshes every ${ceiling.label}.`)- } else if (bounds.floor) {- parts.push(`${floorName} syncs every ${bounds.floor.label}, so this can't refresh more often.`)- } else if (bounds.ceiling) {- parts.push(`${ceilingLead} refreshes every ${bounds.ceiling.label}, so this can't refresh less often.`)+ } else if (floor) {+ parts.push(`${floorName} syncs every ${floor.label}, so this can't refresh more often.`)+ } else if (ceiling) {+ parts.push(`${ceilingLead} refreshes every ${ceiling.label}, so this can't refresh less often.`)}const named = bounds.best_effort_sources.map((source) => source.name).filter(Boolean)diff --git a/products/data_modeling/backend/logic/node_frequency.py b/products/data_modeling/backend/logic/node_frequency.pyindex 8bf6e21d7c03..4bcf787c46b3 100644--- a/products/data_modeling/backend/logic/node_frequency.py+++ b/products/data_modeling/backend/logic/node_frequency.py@@ -21,6 +21,8 @@ from products.data_modeling.backend.logic.freshness import (TargetBounds,all_source_floors,ancestors_of,+ clamp_to_source_floor,+ compute_effective_cadences,compute_target_bounds,intersect_target_bounds,max_data_age,@@ -300,6 +302,7 @@ class SavedQueryFrequencyBounds:identities: dict[str, NodeIdentity] # node id -> the resource its name belongs tobest_effort_source_ids: set[str] # upstream sources with no schedule, so the floor is a guessmax_data_age: timedelta+ speeds_up: dict[timedelta, set[str]] # cadence -> upstream nodes that would run more often if this were set to itdef saved_query_target_bounds(team_id: int, saved_query_id: str | uuid.UUID) -> SavedQueryFrequencyBounds | None:@@ -319,6 +322,7 @@ def saved_query_target_bounds(team_id: int, saved_query_id: str | uuid.UUID) ->names: dict[str, str] = {}identities: dict[str, NodeIdentity] = {}best_effort: set[str] = set()+ speeds_up: dict[timedelta, set[str]] = {}data_ages: list[timedelta] = []graphs: dict[str, FrequencyGraph] = {}for node in nodes:@@ -338,7 +342,11 @@ def saved_query_target_bounds(team_id: int, saved_query_id: str | uuid.UUID) ->names.update(graph.names)identities.update(graph.identities)# a best-effort source elsewhere in the DAG says nothing about this node's freshness- best_effort |= graph.best_effort_source_ids & ancestors_of(str(node.id), graph.edges)+ ancestors = ancestors_of(str(node.id), graph.edges)+ best_effort |= graph.best_effort_source_ids & ancestors+ candidates = [option.value for option in per_dag[-1].options if option.allowed]+ for cadence, sped_up in _speeds_up_by_cadence(team_id, str(node.id), graph, ancestors, candidates).items():+ speeds_up.setdefault(cadence, set()).update(sped_up)data_ages.append(max_data_age(str(node.id), graph.edges, graph.source_intervals, graph.declared_targets))return SavedQueryFrequencyBounds(@@ -347,9 +355,48 @@ def saved_query_target_bounds(team_id: int, saved_query_id: str | uuid.UUID) ->identities=identities,best_effort_source_ids=best_effort,max_data_age=max(data_ages),+ speeds_up=speeds_up,)+def _speeds_up_by_cadence(+ team_id: int, node_id: str, graph: FrequencyGraph, ancestors: set[str], candidates: list[timedelta]+) -> dict[timedelta, set[str]]:+ """The materializing ancestors that would run more often if `node_id` were set to each candidate.++ Runs the scheduler's own propagation and source-floor clamp, so an ancestor its sources hold+ back, or one another consumer already drives faster, is not listed. Ephemeral views never run,+ so they are left out.+ """++ def run(declared_targets: dict[str, timedelta]) -> dict[str, timedelta | None]:+ effective = compute_effective_cadences(nodes=graph.nodes, edges=graph.edges, declared_targets=declared_targets)+ return clamp_to_source_floor(effective, edges=graph.edges, source_intervals=graph.source_intervals)[0]++ upstream = ancestors & graph.nodes+ ephemeral = {+ str(view_id)+ for view_id in Node.objects.filter(team_id=team_id, id__in=upstream, type=NodeType.VIEW).values_list(+ "id", flat=True+ )+ }+ materializing = upstream - ephemeral+ if not materializing:+ return {}++ current = run(graph.declared_targets)+ result: dict[timedelta, set[str]] = {}+ for cadence in candidates:+ proposed = run({**graph.declared_targets, node_id: cadence})+ result[cadence] = {+ ancestor+ for ancestor in materializing+ if (after := proposed.get(ancestor)) is not None+ and ((before := current.get(ancestor)) is None or after < before)+ }+ return result++def schedulable_nodes(dag: DAG) -> QuerySet[Node]:"""The DAG's schedulable nodes: everything that carries a live saved query (not a sourcetable, not a soft-deleted query). The one definition of "what gets a freshness target"."""diff --git a/products/data_modeling/backend/test/test_freshness.py b/products/data_modeling/backend/test/test_freshness.pyindex 7acd9a3e8321..621ace74663c 100644--- a/products/data_modeling/backend/test/test_freshness.py+++ b/products/data_modeling/backend/test/test_freshness.py@@ -325,6 +325,17 @@ class TestFindInvalidTargets(TestCase):{"src": STREAMING},[InvalidTarget(node_id="a", declared=H6, source_floor=STREAMING, consumer_ceiling=M15)],),+ # a stale target in the middle of a chain does not hide the 6h demand from the node above it+ (+ "stale_chain_flags_every_ancestor",+ [("src", "a"), ("a", "b"), ("b", "c")],+ {"a": DAY, "b": DAY, "c": H6},+ {"src": STREAMING},+ [+ InvalidTarget(node_id="a", declared=DAY, source_floor=STREAMING, consumer_ceiling=H6),+ InvalidTarget(node_id="b", declared=DAY, source_floor=STREAMING, consumer_ceiling=H6),+ ],+ ),# a source slowing down (6h import) pushes the floor above an existing 15min target("target_below_drifted_source_floor",diff --git a/products/data_modeling/backend/test/test_schedule_reconcile.py b/products/data_modeling/backend/test/test_schedule_reconcile.pyindex 4f79648e9c94..6629873a95d3 100644--- a/products/data_modeling/backend/test/test_schedule_reconcile.py+++ b/products/data_modeling/backend/test/test_schedule_reconcile.py@@ -15,6 +15,7 @@ from products.data_modeling.backend.logic.cohort_scheduling import tier_schedulefrom products.data_modeling.backend.logic.freshness import UnsupportedFrequencyTargetErrorfrom products.data_modeling.backend.logic.node_frequency import (get_declared_anchor,+ get_declared_target,set_declared_anchor,set_declared_target,)@@ -49,6 +50,7 @@ RECONCILE = "products.data_modeling.backend.logic.schedule_reconcile"M15 = timedelta(minutes=15)H1 = timedelta(hours=1)H6 = timedelta(hours=6)+DAY = timedelta(days=1)def _listing(schedule_id, workflow="data-modeling-execute-dag"):@@ -467,6 +469,30 @@ class TestMaybeReconcileDag(BaseTest):update.assert_called_once()self.assertEqual(update.call_args.kwargs["id"], tier_id)+ def test_upstream_slower_than_its_consumer_runs_at_the_consumer_cadence_and_keeps_its_setting(self):+ dag = DAG.get_or_create_default(self.team)+ source = _warehouse_source_node(self.team, dag, sync_frequency_interval=H1)+ upstream = _saved_query_node(self.team, dag, "org_universe", NodeType.MAT_VIEW)+ consumer = _saved_query_node(self.team, dag, "maps", NodeType.MAT_VIEW)+ Edge.objects.create(team=self.team, dag=dag, source=source, target=upstream)+ Edge.objects.create(team=self.team, dag=dag, source=upstream, target=consumer)+ set_declared_target(upstream, DAY)+ set_declared_target(consumer, H6)++ with (+ mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=self._temporal_listing([]))),+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,+ ):+ with self.captureOnCommitCallbacks(execute=True):+ maybe_reconcile_dag(dag)++ create.assert_called_once()+ self.assertEqual(create.call_args.kwargs["id"], tier_schedule_id(str(dag.id), H6))+ scheduled = create.call_args.kwargs["schedule"].action.args[0]["node_ids"]+ self.assertEqual(sorted(scheduled), sorted([str(upstream.id), str(consumer.id)]))+ upstream.refresh_from_db()+ self.assertEqual(get_declared_target(upstream), DAY)+def test_reconcile_failure_never_raises_past_commit(self):dag = self._dag_with_target()with (diff --git a/products/data_warehouse/backend/presentation/views/saved_query/sync_cadence.py b/products/data_warehouse/backend/presentation/views/saved_query/sync_cadence.pyindex 1646031805d3..8fd16799b438 100644--- a/products/data_warehouse/backend/presentation/views/saved_query/sync_cadence.py+++ b/products/data_warehouse/backend/presentation/views/saved_query/sync_cadence.py@@ -87,6 +87,16 @@ class SyncFrequencyOptionSerializer(serializers.Serializer):help_text="The source or consumer named in `blocked_by`. Null when allowed, and also when the ""blocker sits outside the caller's access grants, where `blocked_by` still gives the direction.",)+ speeds_up = SyncFrequencyBlockerSerializer(+ many=True,+ help_text="Upstream materialized views that would refresh more often than they do now if this "+ "cadence were chosen, because a view cannot be fresher than its inputs. Only views the "+ "caller may read are listed. Empty when the cadence is blocked.",+ )+ speeds_up_withheld = serializers.BooleanField(+ help_text="True when at least one view this cadence speeds up sits outside the caller's access "+ "grants, so `speeds_up` is incomplete."+ )class SyncFrequencyBoundsSerializer(serializers.Serializer):@@ -148,7 +158,7 @@ def _unbounded_frequency_payload(mode: str) -> dict[str, Any]:def _blocker_node_ids(resolved: Any) -> set[str]:"""Every node the bounds would name, across the two bounds, the options and the best-effort list."""- node_ids: set[str] = set(resolved.best_effort_source_ids)+ node_ids: set[str] = set(resolved.best_effort_source_ids).union(*resolved.speeds_up.values())for bound in (resolved.bounds.floor, resolved.bounds.ceiling):if bound is not None and bound.blocker is not None:node_ids.add(bound.blocker)@@ -226,18 +236,28 @@ def _frequency_bounds_payload(resolved: Any, visible_names: dict[str, str]) -> dreturn Nonereturn {"label": humanize_cadence(value.value), "blocker": blocker(value.blocker)}+ def sped_up(option: Any) -> list[str]:+ if not option.allowed:+ return []+ return sorted(resolved.speeds_up.get(option.value, ()))+best_effort = sorted(resolved.best_effort_source_ids)- return {- "frequency_mode": "tiered",- "options": [+ options = []+ for option in resolved.bounds.options:+ sped_up_ids = sped_up(option)+ options.append({"cadence": sync_frequency_interval_to_sync_frequency(option.value),"allowed": option.allowed,"blocked_by": option.blocked_by,"blocker": blocker(option.blocker),+ "speeds_up": [blocker(node_id) for node_id in sped_up_ids if node_id in visible_names],+ "speeds_up_withheld": any(node_id not in visible_names for node_id in sped_up_ids),}- for option in resolved.bounds.options- ],+ )+ return {+ "frequency_mode": "tiered",+ "options": options,"floor": bound(resolved.bounds.floor),"ceiling": bound(resolved.bounds.ceiling),"best_effort_sources": [blocker(node_id) for node_id in best_effort if node_id in visible_names],diff --git a/products/data_warehouse/backend/tests/api/test_saved_query.py b/products/data_warehouse/backend/tests/api/test_saved_query.pyindex 039d06ff9aad..a74a6264c432 100644--- a/products/data_warehouse/backend/tests/api/test_saved_query.py+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py@@ -1339,6 +1339,34 @@ class TestSavedQuery(APIBaseTest):self.assertEqual(response.status_code, 400, response.json())self.assertIn("consumer_view", str(response.json()))+ @parameterized.expand(+ [+ ("materialized_with_a_slower_target", NodeType.MAT_VIEW, timedelta(days=1), ["upstream_view"]),+ # with no target it would not run at all until this view drags it along+ ("materialized_without_a_target", NodeType.MAT_VIEW, None, ["upstream_view"]),+ # an ephemeral view never runs, so nothing about it speeds up+ ("ephemeral", NodeType.VIEW, timedelta(days=1), []),+ ]+ )+ def test_an_option_names_the_upstream_views_it_speeds_up(self, _name, upstream_type, upstream_target, expected):+ # A finer cadence downstream drags slower upstream views along with it. The picker has to+ # say so before the write, or the upstream cadences change behind the user's back.+ from products.data_modeling.backend.facade.api import set_declared_target++ upstream = self._create_view_with_a_consumer(consumer_target=timedelta(days=1))+ upstream_node = Node.objects.get(saved_query_id=upstream["id"])+ upstream_node.type = upstream_type+ upstream_node.save(update_fields=["type"])+ if upstream_target is not None:+ set_declared_target(upstream_node, upstream_target)+ consumer_id = DataWarehouseSavedQuery.objects.get(team=self.team, name="consumer_view").id++ options = {option["cadence"]: option for option in self._read_frequency_bounds(str(consumer_id))["options"]}++ self.assertEqual([view["name"] for view in options["6hour"]["speeds_up"]], expected)+ self.assertFalse(options["6hour"]["speeds_up_withheld"])+ self.assertEqual(options["24hour"]["speeds_up"], [])+def test_bounds_stay_off_the_list_page(self):# Bounds cost a graph walk per view, so serving them on a page of views is an N+1. The# picker only ever renders on one view's panel, so retrieve is the only place they belong.diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.tsindex 3f350aab476e..f94c2c52a3b2 100644--- a/products/data_warehouse/frontend/generated/api.schemas.ts+++ b/products/data_warehouse/frontend/generated/api.schemas.ts@@ -1871,6 +1871,10 @@ export interface SyncFrequencyOptionApi {blocked_by: SyncFrequencyBlockedByEnumApi | null/** The source or consumer named in `blocked_by`. Null when allowed, and also when the blocker sits outside the caller's access grants, where `blocked_by` still gives the direction. */blocker: SyncFrequencyBlockerApi | null+ /** Upstream materialized views that would refresh more often than they do now if this cadence were chosen, because a view cannot be fresher than its inputs. Only views the caller may read are listed. Empty when the cadence is blocked. */+ speeds_up: SyncFrequencyBlockerApi[]+ /** True when at least one view this cadence speeds up sits outside the caller's access grants, so `speeds_up` is incomplete. */+ speeds_up_withheld: boolean}export interface SyncFrequencyBoundApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 9e7b7e6173c6..9c380f213e0d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -32563,6 +32563,10 @@ export namespace Schemas {blocked_by: SyncFrequencyBlockedByEnum | null;/** The source or consumer named in `blocked_by`. Null when allowed, and also when the blocker sits outside the caller's access grants, where `blocked_by` still gives the direction. */blocker: SyncFrequencyBlocker | null;+ /** Upstream materialized views that would refresh more often than they do now if this cadence were chosen, because a view cannot be fresher than its inputs. Only views the caller may read are listed. Empty when the cadence is blocked. */+ speeds_up: SyncFrequencyBlocker[];+ /** True when at least one view this cadence speeds up sits outside the caller's access grants, so `speeds_up` is incomplete. */+ speeds_up_withheld: boolean;}export interface SyncFrequencyBound {