:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-modeling): offer only sync frequencies the scheduler honors (#81295)
Jovan Sakovic124fb0c96dde
diff --git a/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx b/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsxindex 25159fcad0bc..a6fcc6af8c98 100644--- a/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx+++ b/frontend/src/scenes/data-warehouse/saved_queries/MaterializationStatusPanel.tsx@@ -6,7 +6,6 @@ import { LemonBanner, LemonDialog, LemonTable, Link, Spinner } from '@posthog/leimport { FEATURE_FLAGS } from 'lib/constants'import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonProgress } from 'lib/lemon-ui/LemonProgress'-import { LemonSelect } from 'lib/lemon-ui/LemonSelect'import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'import { Tooltip } from 'lib/lemon-ui/Tooltip'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'@@ -17,18 +16,18 @@ import { LogsViewer } from 'scenes/hog-functions/logs/LogsViewer'import { teamLogic } from 'scenes/teamLogic'import { userLogic } from 'scenes/userLogic'-import {- AccessControlLevel,- AccessControlResourceType,- DataModelingJob,- DataModelingSyncInterval,- LogEntryLevel,- OrNever,-} from '~/types'+import { AccessControlLevel, AccessControlResourceType, DataModelingJob, LogEntryLevel } from '~/types'import { dataWarehouseViewsLogic } from './dataWarehouseViewsLogic'import { materializationJobsLogic } from './materializationJobsLogic'import { computeJobDuration, jobLogsWindow } from './materializationJobUtils'+import {+ SyncFrequencySelect,+ SyncFrequencyValue,+ defaultCadenceWithin,+ modeDisabledReason,+ unsatisfiableReason,+} from './SyncFrequencySelect'const LOG_LEVELS: LogEntryLevel[] = ['LOG', 'INFO', 'WARN', 'WARNING', 'ERROR']@@ -45,46 +44,6 @@ interface MaterializationStatusPanelProps {kind?: 'view' | 'endpoint'}-const RESYNC_FREQUENCY_OPTIONS = [- {- value: '15min' as DataModelingSyncInterval,- label: 'Resync every 15 mins',- },- {- value: '30min' as DataModelingSyncInterval,- label: 'Resync every 30 mins',- },- {- value: '1hour' as DataModelingSyncInterval,- label: 'Resync every 1 hour',- },- {- value: '6hour' as DataModelingSyncInterval,- label: 'Resync every 6 hours',- },- {- value: '12hour' as DataModelingSyncInterval,- label: 'Resync every 12 hours',- },- {- value: '24hour' as DataModelingSyncInterval,- label: 'Resync daily',- },- {- value: '7day' as DataModelingSyncInterval,- label: 'Resync weekly',- },- {- value: '30day' as DataModelingSyncInterval,- label: 'Resync monthly',- },-]--// `never` stops an existing schedule, so it only makes sense once a view is materialized. The-// server refuses it as the cadence to start at, which is why the pre-materialization picker-// offers RESYNC_FREQUENCY_OPTIONS on its own.-const SYNC_FREQUENCY_OPTIONS = [{ value: 'never' as OrNever, label: 'No resync' }, ...RESYNC_FREQUENCY_OPTIONS]-function getMaterializationStatusMessage(rowsMaterialized: number,progressPercentage: number,@@ -168,11 +127,6 @@ export function MaterializationStatusPanel({ viewId, kind = 'view' }: Materializconst { timezone } = useValues(teamLogic)const { user } = useValues(userLogic)const showDebugLogs = user?.is_staff || user?.is_impersonated- // The two ways a cadence write gets rejected. Single-schedule v2 teams have the cadence on the- // DAG's one schedule, which the server tells us because the flag that distinguishes per-node- // schedules is evaluated server-side and never reaches the frontend. Managed viewsets reject- // every update regardless of team.- const canEditSyncFrequency = !savedQuery?.sync_frequency_managed_by_dag && !savedQuery?.managed_viewset_kindconst materializationAccessReason = getAccessControlDisabledReason(AccessControlResourceType.WarehouseObjects,AccessControlLevel.Editor@@ -188,6 +142,9 @@ export function MaterializationStatusPanel({ viewId, kind = 'view' }: Materializconst currentJobStatus = dataModelingJobs?.results?.[0]?.status || nullconst { sync, cancel, revert } = getMaterializationDisabledReasons(currentJobStatus, startingMaterialization)+ const startingFrequency = defaultCadenceWithin(savedQuery.sync_frequency_bounds, initialSyncFrequency)+ const noCadenceReason = unsatisfiableReason(savedQuery.sync_frequency_bounds)+ const isPaused = !savedQuery.sync_frequency || savedQuery.sync_frequency === 'never'// Prefer the serving engine's entry when several engines are suspended.const suspension = savedQuery.suspended@@ -246,73 +203,96 @@ export function MaterializationStatusPanel({ viewId, kind = 'view' }: Materializ<span>Materialization scheduled</span></div>)}- <div className="flex gap-4 mt-2">- <LemonButton- className="whitespace-nowrap"- loading={startingMaterialization || currentJobStatus === 'Running'}- disabledReason={sync || materializationAccessReason}- onClick={() => {- setStartingMaterialization(true)- runDataWarehouseSavedQuery(viewId)- }}- type="secondary"- sideAction={{- icon: <IconX fontSize={16} />,- tooltip: 'Cancel materialization',- onClick: () => cancelDataWarehouseSavedQuery(viewId),- disabledReason: cancel || materializationAccessReason || undefined,- }}- >- {startingMaterialization- ? 'Starting...'- : currentJobStatus === 'Running'- ? 'Running...'- : 'Sync now'}- </LemonButton>- {kind !== 'endpoint' && canEditSyncFrequency && (- <LemonSelect- className="h-9"- disabledReason={sync || materializationAccessReason}- value={savedQuery.sync_frequency || 'never'}- onChange={(newValue) => {- if (newValue) {- updateDataWarehouseSavedQuery({- id: viewId,- sync_frequency: newValue,- types: [[]],- lifecycle: 'update',- })- }- }}+ <div className="flex flex-col gap-2 items-start mt-2">+ {kind !== 'endpoint' && (+ <SyncFrequencySelect+ bounds={savedQuery.sync_frequency_bounds}+ disabledReason={sync || materializationAccessReason || undefined}+ value={(savedQuery.sync_frequency as SyncFrequencyValue) || 'never'}+ onChange={(newValue) =>+ updateDataWarehouseSavedQuery({+ id: viewId,+ sync_frequency: newValue,+ types: [[]],+ lifecycle: 'update',+ })+ }loading={updatingDataWarehouseSavedQuery}- options={SYNC_FREQUENCY_OPTIONS}/>)}- {kind !== 'endpoint' && (+ <div className="flex items-center gap-2"><LemonButton- type="secondary"+ className="whitespace-nowrap"size="small"- tooltip="Revert materialized view to view"- disabledReason={revert || materializationAccessReason}- icon={<IconRevert />}+ loading={startingMaterialization || currentJobStatus === 'Running'}+ disabledReason={sync || materializationAccessReason}onClick={() => {- LemonDialog.open({- title: 'Revert materialization',- maxWidth: '30rem',- description:- 'Are you sure you want to revert this materialized view to a regular view? This will stop all future materializations and remove the materialized table. You will always be able to go back to a materialized view at any time.',- primaryButton: {- status: 'danger',- children: 'Revert materialization',- onClick: () => revertMaterialization(viewId),- },- secondaryButton: {- children: 'Cancel',- },- })+ setStartingMaterialization(true)+ runDataWarehouseSavedQuery(viewId)}}- />- )}+ type="secondary"+ sideAction={{+ icon: <IconX fontSize={16} />,+ tooltip: 'Cancel materialization',+ onClick: () => cancelDataWarehouseSavedQuery(viewId),+ disabledReason: cancel || materializationAccessReason || undefined,+ }}+ >+ {startingMaterialization+ ? 'Starting...'+ : currentJobStatus === 'Running'+ ? 'Running...'+ : 'Sync now'}+ </LemonButton>+ {kind !== 'endpoint' && (+ <LemonButton+ type="secondary"+ size="small"+ tooltip="Stop refreshing on a schedule. The table stays, holding what it last loaded."+ disabledReason={+ materializationAccessReason ||+ modeDisabledReason(savedQuery.sync_frequency_bounds) ||+ (isPaused ? 'Already paused. Pick a cadence to resume.' : undefined)+ }+ loading={updatingDataWarehouseSavedQuery}+ onClick={() =>+ updateDataWarehouseSavedQuery({+ id: viewId,+ sync_frequency: 'never',+ types: [[]],+ lifecycle: 'update',+ })+ }+ >+ Pause refreshes+ </LemonButton>+ )}+ {kind !== 'endpoint' && (+ <LemonButton+ type="secondary"+ size="small"+ tooltip="Revert materialized view to view"+ disabledReason={revert || materializationAccessReason}+ icon={<IconRevert />}+ onClick={() => {+ LemonDialog.open({+ title: 'Revert materialization',+ maxWidth: '30rem',+ description:+ 'Are you sure you want to revert this materialized view to a regular view? This will stop all future materializations and remove the materialized table. You will always be able to go back to a materialized view at any time.',+ primaryButton: {+ status: 'danger',+ children: 'Revert materialization',+ onClick: () => revertMaterialization(viewId),+ },+ secondaryButton: {+ children: 'Cancel',+ },+ })+ }}+ />+ )}+ </div></div></div>) : (@@ -330,26 +310,25 @@ export function MaterializationStatusPanel({ viewId, kind = 'view' }: Materializ</Link>.</p>- <div className="flex gap-4">+ <div className="flex flex-col gap-2 items-start">+ {kind !== 'endpoint' && (+ <SyncFrequencySelect+ data-attr="initial-sync-frequency"+ bounds={savedQuery.sync_frequency_bounds}+ disabledReason={materializationAccessReason || undefined}+ value={startingFrequency}+ onChange={(newValue) => setInitialSyncFrequency(newValue)}+ />+ )}<LemonButtonsize="small"- onClick={() => materializeDataWarehouseSavedQuery(viewId, initialSyncFrequency)}+ onClick={() => materializeDataWarehouseSavedQuery(viewId, startingFrequency)}type="primary"loading={updatingDataWarehouseSavedQuery}- disabledReason={materializationAccessReason}+ disabledReason={materializationAccessReason || noCadenceReason}>Materialize</LemonButton>- {kind !== 'endpoint' && canEditSyncFrequency && (- <LemonSelect- className="h-9"- data-attr="initial-sync-frequency"- disabledReason={materializationAccessReason}- value={initialSyncFrequency}- onChange={(newValue) => setInitialSyncFrequency(newValue)}- options={RESYNC_FREQUENCY_OPTIONS}- />- )}</div></div>)}diff --git a/frontend/src/scenes/data-warehouse/saved_queries/SyncFrequencySelect.test.ts b/frontend/src/scenes/data-warehouse/saved_queries/SyncFrequencySelect.test.tsnew file mode 100644index 000000000000..1e8a70140bea--- /dev/null+++ b/frontend/src/scenes/data-warehouse/saved_queries/SyncFrequencySelect.test.ts@@ -0,0 +1,200 @@+import { SyncFrequencyBoundsApi } from 'products/data_warehouse/frontend/generated/api.schemas'++import {+ buildExplanation,+ buildOptions,+ defaultCadenceWithin,+ modeDisabledReason,+ unsatisfiableReason,+} from './SyncFrequencySelect'++describe('SyncFrequencySelect', () => {+ const blocker = (name: string): { id: string; name: string } => ({ id: `id-${name}`, name })++ const bounds = (overrides: Partial<SyncFrequencyBoundsApi> = {}): SyncFrequencyBoundsApi =>+ ({+ frequency_mode: 'tiered',+ options: [+ { cadence: '15min', allowed: false, blocked_by: 'source', blocker: blocker('stripe_invoices') },+ { cadence: '6hour', allowed: true, blocked_by: null, blocker: null },+ { cadence: '24hour', allowed: false, blocked_by: 'consumer', blocker: blocker('daily_revenue') },+ ],+ floor: { label: '6 hours', blocker: blocker('stripe_invoices') },+ ceiling: { label: '12 hours', blocker: blocker('daily_revenue') },+ best_effort_sources: [],+ best_effort_sources_withheld: false,+ ...overrides,+ }) as SyncFrequencyBoundsApi++ it('offers every cadence when the backend sends no bounds', () => {+ const options = buildOptions(null)++ expect(options).toHaveLength(8)+ expect(options.every((option) => !option.disabledReason)).toBe(true)+ })++ it('disables a blocked cadence and names what blocks it', () => {+ const options = buildOptions(bounds())++ 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(options.find((option) => option.value === '6hour')?.disabledReason).toBeUndefined()+ })++ it('explains the range only where a per-view cadence is writable', () => {+ expect(buildExplanation(bounds())).toContain('Pick between 6 hours and 12 hours.')+ expect(buildExplanation(bounds({ frequency_mode: 'dag_schedule' }))).toBeNull()+ expect(buildExplanation(bounds({ floor: null, ceiling: null }))).toBeNull()+ })++ describe('defaultCadenceWithin', () => {+ const withAllowed = (...allowed: string[]): SyncFrequencyBoundsApi =>+ bounds({+ options: ['15min', '30min', '1hour', '6hour', '12hour', '24hour', '7day', '30day'].map((cadence) => ({+ cadence,+ allowed: allowed.includes(cadence),+ blocked_by: null,+ blocker: null,+ })),+ } as Partial<SyncFrequencyBoundsApi>)++ it('keeps the preferred cadence when the lineage allows it', () => {+ expect(defaultCadenceWithin(withAllowed('6hour', '24hour'), '24hour')).toBe('24hour')+ })++ it('drops to the coarsest allowed cadence when a consumer rules the default out', () => {+ // A sub-daily consumer is exactly the case that made Materialize a dead end.+ expect(defaultCadenceWithin(withAllowed('15min', '30min', '1hour'), '24hour')).toBe('1hour')+ })++ it('goes finer only when nothing coarser than the default is allowed', () => {+ expect(defaultCadenceWithin(withAllowed('7day', '30day'), '24hour')).toBe('30day')+ })++ it('leaves the preferred cadence alone when there are no bounds to honor', () => {+ expect(defaultCadenceWithin(null, '24hour')).toBe('24hour')+ })+ })++ describe('unsatisfiableReason', () => {+ const nothingAllowed = (overrides: Partial<SyncFrequencyBoundsApi> = {}): SyncFrequencyBoundsApi =>+ bounds({+ options: ['15min', '6hour', '24hour'].map((cadence) => ({+ cadence,+ allowed: false,+ blocked_by: null,+ blocker: null,+ })),+ ...overrides,+ } as Partial<SyncFrequencyBoundsApi>)++ 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.'+ )+ })++ 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.'+ )+ })++ it('stays silent while any cadence is still allowed', () => {+ expect(unsatisfiableReason(bounds())).toBeNull()+ expect(unsatisfiableReason(null)).toBeNull()+ })+ })++ it('warns that a source with no schedule makes the floor a guess', () => {+ const explanation = buildExplanation(bounds({ best_effort_sources: [blocker('hubspot_contacts')] }))++ expect(explanation).toContain('hubspot_contacts has no sync schedule')+ })++ describe('a blocker outside the caller access grants', () => {+ // The backend nulls the whole blocker rather than blanking its name, so every surface that+ // would have named it has to still say which direction blocks the cadence.+ it('keeps the direction on a blocked segment', () => {+ const options = buildOptions(+ bounds({+ options: [+ { cadence: '15min', allowed: false, blocked_by: 'source', blocker: null },+ { cadence: '24hour', allowed: false, blocked_by: 'consumer', blocker: null },+ ],+ } as Partial<SyncFrequencyBoundsApi>)+ )++ expect(options.find((option) => option.value === '15min')?.disabledReason).toBe(+ 'More often than the sources this view reads'+ )+ expect(options.find((option) => option.value === '24hour')?.disabledReason).toBe(+ 'Too slow for something built on this view'+ )+ })++ it('still states the range under the bar', () => {+ const explanation = buildExplanation(+ bounds({+ floor: { label: '6 hours', blocker: null },+ ceiling: { label: '12 hours', blocker: null },+ })+ )++ expect(explanation).toBe(+ 'Pick between 6 hours and 12 hours. An upstream source syncs every 6 hours, ' ++ 'and a downstream view refreshes every 12 hours.'+ )+ })++ it('still explains why no cadence works', () => {+ const nothingAllowed = bounds({+ options: [{ cadence: '6hour', allowed: false, blocked_by: 'source', blocker: null }],+ floor: { label: '6 hours', blocker: null },+ ceiling: null,+ } as Partial<SyncFrequencyBoundsApi>)++ expect(unsatisfiableReason(nothingAllowed)).toBe(+ 'No cadence works here: an upstream source only syncs every 6 hours, ' ++ 'less often than anything this can refresh at. Speed up an upstream source first.'+ )+ })++ it('keeps the best-effort caveat when every such source is withheld', () => {+ const explanation = buildExplanation(+ bounds({ best_effort_sources: [], best_effort_sources_withheld: true })+ )++ expect(explanation).toContain('Some sources upstream have no sync schedule')+ })++ it('says there are more when only some are withheld', () => {+ const explanation = buildExplanation(+ bounds({ best_effort_sources: [blocker('hubspot_contacts')], best_effort_sources_withheld: true })+ )++ expect(explanation).toContain('hubspot_contacts and other sources upstream have no sync schedule')+ })+ })+ describe('modeDisabledReason', () => {+ it.each([+ ['dag_schedule', "This project runs one schedule per DAG, so this view follows its DAG's frequency."],+ ['managed_viewset', 'PostHog manages this view, including how often it refreshes.'],+ ['no_node', 'This view is not set up for scheduled refreshes yet. Save it again, then pick a cadence.'],+ ])('locks %s, where the backend refuses the write', (mode, reason) => {+ const locked = bounds({ frequency_mode: mode as SyncFrequencyBoundsApi['frequency_mode'] })++ expect(modeDisabledReason(locked)).toBe(reason)+ })++ it('leaves a tiered view editable', () => {+ expect(modeDisabledReason(bounds())).toBeNull()+ })+ })+})diff --git a/frontend/src/scenes/data-warehouse/saved_queries/SyncFrequencySelect.tsx b/frontend/src/scenes/data-warehouse/saved_queries/SyncFrequencySelect.tsxnew file mode 100644index 000000000000..442d7f2786e4--- /dev/null+++ b/frontend/src/scenes/data-warehouse/saved_queries/SyncFrequencySelect.tsx@@ -0,0 +1,256 @@+import { IconRabbit, IconTortoise } from '@posthog/icons'+import { LemonLabel, LemonSegmentedButton, LemonSegmentedButtonOption } from '@posthog/lemon-ui'++import { DataModelingSyncInterval } from '~/types'++import { SyncFrequencyBoundsApi } from 'products/data_warehouse/frontend/generated/api.schemas'++export type SyncFrequencyValue = DataModelingSyncInterval | 'never'++/**+ * Interval wording ("refresh every X"), which the bounds are what make truthful: a view may only be+ * set at or below its consumers' cadence, so the value picked here is the cadence that runs, not a+ * request the scheduler quietly tightens. The bar carries the wording once in its label, so each+ * segment only has to say which duration it is.+ */+const CADENCE_LABELS: Record<DataModelingSyncInterval, string> = {+ '15min': '15 minutes',+ '30min': '30 minutes',+ '1hour': '1 hour',+ '6hour': '6 hours',+ '12hour': '12 hours',+ '24hour': '1 day',+ '7day': '7 days',+ '30day': '30 days',+}++const CADENCE_SEGMENTS: Record<DataModelingSyncInterval, string> = {+ '15min': '15m',+ '30min': '30m',+ '1hour': '1h',+ '6hour': '6h',+ '12hour': '12h',+ '24hour': '1d',+ '7day': '7d',+ '30day': '30d',+}++const ORDERED_CADENCES = Object.keys(CADENCE_LABELS) as DataModelingSyncInterval[]++/**+ * Decorative, so `aria-hidden`: they only restate which way the bar runs, which the segment labels+ * already say outright.+ */+const PACE_ICON_CLASS = 'text-xl text-secondary shrink-0'++/**+ * Why the cadence controls are read-only, for the modes where cadence is not this view's to set.+ *+ * `no_node` belongs here despite having no bounds to show: the missing-node guard refuses every+ * cadence write, so a live control only buys a 400. The reason carries the way out instead.+ */+const MODE_DISABLED_REASONS: Record<string, string> = {+ dag_schedule: "This project runs one schedule per DAG, so this view follows its DAG's frequency.",+ managed_viewset: 'PostHog manages this view, including how often it refreshes.',+ no_node: 'This view is not set up for scheduled refreshes yet. Save it again, then pick a cadence.',+}++/** Why the view's frequency mode locks its cadence controls, or null where the mode allows them. */+export function modeDisabledReason(bounds?: SyncFrequencyBoundsApi | null): string | null {+ return (bounds && MODE_DISABLED_REASONS[bounds.frequency_mode]) || null+}++export interface SyncFrequencySelectProps {+ /** Bounds from the saved query. Undefined while loading, or on surfaces that don't fetch them. */+ bounds?: SyncFrequencyBoundsApi | null+ /** A paused view ("never") leaves the bar with nothing selected, since pausing is not a cadence. */+ value: SyncFrequencyValue | null+ onChange: (value: DataModelingSyncInterval) => void+ /** Locks the bar while a change is in flight, so one click can't queue eight cadence writes. */+ loading?: boolean+ /** Takes precedence over the mode's own reason, so access checks win over scheduling ones. */+ disabledReason?: string+ 'data-attr'?: string+}++/**+ * A cadence picker that offers only what the scheduler will honor, and names what withholds the rest.+ *+ * Without bounds it degrades to every cadence, which is what teams whose backend accepts any of them+ * should see.+ */+export function SyncFrequencySelect({+ bounds,+ value,+ onChange,+ loading,+ disabledReason,+ 'data-attr': dataAttr,+}: SyncFrequencySelectProps): JSX.Element {+ const options = buildOptions(bounds)+ const explanation = buildExplanation(bounds)+ const reason =+ disabledReason ??+ (loading ? 'Saving the new cadence.' : undefined) ??+ unsatisfiableReason(bounds) ??+ modeDisabledReason(bounds) ??+ undefined++ return (+ <div className="flex flex-col gap-1 items-start" data-attr={dataAttr}>+ <LemonLabel>Refresh every</LemonLabel>+ <div className="flex items-center gap-2">+ <IconRabbit className={PACE_ICON_CLASS} aria-hidden />+ <LemonSegmentedButton<DataModelingSyncInterval>+ size="small"+ value={value && value !== 'never' ? value : undefined}+ onChange={(next) => onChange(next)}+ options={options}+ disabledReason={reason}+ />+ <IconTortoise className={PACE_ICON_CLASS} aria-hidden />+ </div>+ {explanation && <span className="text-xs text-secondary max-w-prose">{explanation}</span>}+ </div>+ )+}++export function buildOptions(+ bounds?: SyncFrequencyBoundsApi | null+): LemonSegmentedButtonOption<DataModelingSyncInterval>[] {+ if (!bounds?.options.length) {+ return ORDERED_CADENCES.map((cadence) => segment(cadence))+ }++ return bounds.options.map((option) => {+ const cadence = option.cadence as DataModelingSyncInterval+ return {+ ...segment(cadence),+ disabledReason: option.allowed ? undefined : blockedReason(option, bounds),+ }+ })+}++/** Abbreviated on the bar, spelled out on hover, so eight segments stay readable at one glance. */+function segment(cadence: DataModelingSyncInterval): LemonSegmentedButtonOption<DataModelingSyncInterval> {+ return { value: cadence, label: CADENCE_SEGMENTS[cadence], tooltip: `Every ${CADENCE_LABELS[cadence]}` }+}++/**+ * Terse on purpose: the line under the bar already spells out both bounds, so a segment only has to+ * say which direction it falls outside and who holds that end.+ *+ * A blocker the caller may not read arrives as `null`, so keep the direction and drop the name+ * rather than falling through to something that says neither.+ */+function blockedReason(option: SyncFrequencyBoundsApi['options'][number], bounds: SyncFrequencyBoundsApi): string {+ const name = option.blocker?.name+ if (option.blocked_by === 'source' && bounds.floor) {+ return name ? `More often than ${name} syncs` : 'More often than the sources this view reads'+ }+ if (option.blocked_by === 'consumer' && bounds.ceiling) {+ return name ? `Too slow for ${name}` : 'Too slow for something built on this view'+ }+ return 'Not available for this view'+}++/**+ * Why no cadence at all can be picked, when a view's lineage leaves an empty range.+ *+ * Not the same as having no bounds: an empty `options` list means unbounded, while options that are+ * all blocked mean a floor above the ceiling, which the backend refuses whatever gets submitted.+ * Callers offering a Materialize action must gate it on this, since there is nothing to fall back to.+ */+export function unsatisfiableReason(bounds?: SyncFrequencyBoundsApi | null): string | null {+ if (!bounds?.options.length || bounds.options.some((option) => option.allowed)) {+ return null+ }++ const source = bounds.floor?.blocker?.name ?? 'an upstream source'+ const consumer = bounds.ceiling?.blocker?.name ?? 'a view or endpoint built on this one'+ if (bounds.floor && bounds.ceiling) {+ return (+ `No cadence works here: ${source} only syncs every ${bounds.floor.label}, ` ++ `but ${consumer} refreshes every ${bounds.ceiling.label}. ` ++ `Slow down ${consumer} or speed up ${source}.`+ )+ }+ if (bounds.floor) {+ return (+ `No cadence works here: ${source} only syncs every ${bounds.floor.label}, ` ++ `less often than anything this can refresh at. Speed up ${source} first.`+ )+ }+ if (bounds.ceiling) {+ return (+ `No cadence works here: ${consumer} refreshes every ${bounds.ceiling.label}, ` ++ `more often than anything this can refresh at. Slow down ${consumer} first.`+ )+ }+ return 'No cadence works here.'+}++/**+ * A cadence to start a never-materialized view on, given what its lineage allows.+ *+ * `preferred` is a fixed default, so on a view with a sub-daily consumer it names a cadence the+ * backend refuses — the picker would open on a greyed-out row and Materialize would 400. Falls back+ * to the coarsest allowed cadence no coarser than `preferred`, so a first run stays as cheap as the+ * lineage permits. When nothing is allowed there is no such fallback, so it returns `preferred`+ * unchanged and `unsatisfiableReason` is what keeps the action out of reach.+ */+export function defaultCadenceWithin(+ bounds: SyncFrequencyBoundsApi | null | undefined,+ preferred: DataModelingSyncInterval+): DataModelingSyncInterval {+ const allowed = (bounds?.options ?? [])+ .filter((option) => option.allowed)+ .map((option) => option.cadence as DataModelingSyncInterval)+ if (!allowed.length || allowed.includes(preferred)) {+ return preferred+ }++ const rank = (cadence: DataModelingSyncInterval): number => ORDERED_CADENCES.indexOf(cadence)+ const upToPreferred = allowed.filter((cadence) => rank(cadence) <= rank(preferred))+ const pool = upToPreferred.length ? upToPreferred : allowed+ return pool.reduce((coarsest, cadence) => (rank(cadence) > rank(coarsest) ? cadence : coarsest))+}++export function buildExplanation(bounds?: SyncFrequencyBoundsApi | null): string | null {+ if (!bounds || bounds.frequency_mode !== 'tiered') {+ return null+ }++ const parts: string[] = []+ // 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'++ if (bounds.floor && bounds.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}.`+ )+ } 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.`)+ }++ const named = bounds.best_effort_sources.map((source) => source.name).filter(Boolean)+ if (named.length || bounds.best_effort_sources_withheld) {+ const subject = named.length+ ? `${named.join(', ')}${bounds.best_effort_sources_withheld ? ' and other sources upstream' : ''}`+ : 'Some sources upstream'+ const plural = named.length > 1 || bounds.best_effort_sources_withheld || !named.length+ parts.push(+ `${subject} ${plural ? 'have' : 'has'} no sync schedule, ` ++ `so refreshing more often won't make that data any newer.`+ )+ }++ return parts.length ? parts.join(' ') : null+}diff --git a/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.ts b/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.tsindex 45a50eba5ca6..6fb945078591 100644--- a/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/saved_queries/dataWarehouseViewsLogic.test.ts@@ -13,7 +13,7 @@ import { dataWarehouseViewsLogic } from './dataWarehouseViewsLogic'const rejection = {type: 'validation_error',code: 'invalid_input',- detail: "Can't refresh every 1 day: a view or endpoint built on this one needs data no older than 15 minutes. Pick 15 minutes instead.",+ detail: "Can't refresh every 1 day: a view or endpoint built on this one refreshes every 15 minutes. Pick 15 minutes instead.",attr: null,}diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 9de98b31961c..bffb17c16a73 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -81,7 +81,10 @@ import type {import { QueryContext } from '~/queries/types'import { AlertType } from 'products/alerts/frontend/types'-import type { DataWarehouseSavedQueryApiSuspended } from 'products/data_warehouse/frontend/generated/api.schemas'+import type {+ DataWarehouseSavedQueryApiSuspended,+ SyncFrequencyBoundsApi,+} from 'products/data_warehouse/frontend/generated/api.schemas'import type { ExperimentFeatureFlagInputApi } from 'products/experiments/frontend/generated/api.schemas'import type { CommentSlackThreadRefApi } from 'products/platform_features/frontend/generated/api.schemas'import type { InsightFilterOverrideContextApi } from 'products/product_analytics/frontend/generated/api.schemas'@@ -6191,6 +6194,8 @@ export interface DataWarehouseSavedQuery {sync_frequency?: string/** True when the DAG's single schedule owns the cadence, so `sync_frequency` is not editable per view */sync_frequency_managed_by_dag?: boolean+ /** Which cadences this view's lineage allows, and what withholds the rest. Single fetches only */+ sync_frequency_bounds?: SyncFrequencyBoundsApistatus?: stringmanaged_viewset_kind: DataWarehouseManagedViewsetKind | nullfolder_id?: string | nulldiff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex 4d19774bafa3..6380b496b3cb 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -773,6 +773,23 @@ SPECTACULAR_SETTINGS = {"7day","30day",],+ # Same member set minus `never`, shared by the `materialize` body and by each cadence the+ # saved-query sync frequency bounds offer. Both mean "a cadence to run at", so one name.+ "MaterializeSyncFrequencyEnum": [+ "15min",+ "30min",+ "1hour",+ "6hour",+ "12hour",+ "24hour",+ "7day",+ "30day",+ ],+ # Two unrelated products now expose a `blocked_by` ChoiceField. Collision resolution keys off+ # how many choice sets share the field name and ignores overrides, so pinning only one still+ # component-prefixes the other. Both are pinned to keep either name stable as more appear.+ "SyncFrequencyBlockedByEnum": ["source", "consumer"],+ "BlockedByEnum": ["x_frame_options", "frame_ancestors"],# Signals now has two serializers (single SignalReportStateRequest + bulk# SignalReportBulkStateRequest) that both expose the same `state` ChoiceField. Pin the# shared enum to a stable name so it doesn't collide with the other `state` enumsdiff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.pyindex 0dd42befddba..c9c69f9ab681 100644--- a/products/data_modeling/backend/facade/api.py+++ b/products/data_modeling/backend/facade/api.py@@ -12,6 +12,7 @@ _B = "products.data_modeling.backend."_LAZY = {"UnsatisfiableFrequencyError": "logic.freshness","UnsupportedFrequencyTargetError": "logic.freshness",+ "humanize_cadence": "logic.freshness","HasDependentsError": "logic.saved_query_dag_sync","delete_node_from_dag": "logic.saved_query_dag_sync","promote_view_nodes_to_matview": "logic.saved_query_dag_sync",@@ -27,9 +28,11 @@ _LAZY = {"delete_team_data_modeling_schedules": "logic.schedule_reconcile","apply_saved_query_frequency_anchor": "logic.schedule_reconcile","apply_saved_query_frequency_target": "logic.schedule_reconcile",+ "check_saved_query_frequency_target": "logic.schedule_reconcile","tiered_schedules_enabled": "logic.schedule_reconcile","declared_targets_by_saved_query": "logic.node_frequency","get_declared_target": "logic.node_frequency",+ "saved_query_target_bounds": "logic.node_frequency","clear_node_suspension": "logic.node_suspension","is_node_suspended": "logic.node_suspension","mark_node_suspended": "logic.node_suspension",diff --git a/products/data_modeling/backend/logic/freshness.py b/products/data_modeling/backend/logic/freshness.pyindex 0bf78316e42d..fc13f8227ee5 100644--- a/products/data_modeling/backend/logic/freshness.py+++ b/products/data_modeling/backend/logic/freshness.py@@ -37,7 +37,9 @@ Edges are (upstream_id, downstream_id): data flows upstream -> downstream, so aimport dataclassesfrom collections import defaultdict, deque+from collections.abc import Iterable, Mappingfrom datetime import timedelta+from typing import Literal# A streamed source (e.g. the events table) is continuously fresh, so it imposes no# floor: a descendant may be as tight as the buckets allow. Imported sources instead@@ -48,14 +50,13 @@ from datetime import timedelta# timedelta(0) so the intent stays searchable; None (elsewhere) means "unscheduled".STREAMING = timedelta(0)-# Intervals build_schedule_spec can realize exactly (minute buckets must divide 60, hour-# buckets 24, then weekly/monthly); anything else silently degrades or crashes there.+# Intervals a model tier can run at. 15min is the floor: a model rebuild is not a source sync,+# and running one every minute costs more than the freshness is worth. Sources still sync as+# fast as 1min, so a floor derived from one rounds up into this set rather than escaping it.# Spelled out literally so this module stays Django-free; a test pins each value to the# canonical sync-frequency buckets in warehouse_sources.SCHEDULABLE_BUCKETS: frozenset[timedelta] = frozenset({- timedelta(minutes=1),- timedelta(minutes=5),timedelta(minutes=15),timedelta(minutes=30),timedelta(hours=1),@@ -73,7 +74,7 @@ class UnsatisfiableFrequencyError(ValueError):class UnsupportedFrequencyTargetError(ValueError):- """A declared target is not one of the schedulable cadence buckets (SCHEDULABLE_BUCKETS)."""+ """A declared target is not one of the cadences a person may pick (SCHEDULABLE_BUCKETS)."""def is_finer_than(cadence: timedelta, other: timedelta) -> bool:@@ -165,8 +166,47 @@ def compute_effective_cadences(return resolved-def all_source_floors(edges: list[tuple[str, str]], source_intervals: dict[str, timedelta]) -> dict[str, timedelta]:- """Every node's source floor in one forward pass.[email protected](frozen=True, kw_only=True, slots=True)+class Bound:+ """A bound and the node that set it, so a refusal can name what someone has to change.++ `blocker` is the node the value originates from, carried across the whole traversal rather+ than the immediate neighbour: a floor propagated down four views still points at the source+ that delivers slowly, which is the thing a person can act on.+ """++ value: timedelta+ blocker: str | None # None when nothing set it (a derived node with no parents)+++def _bound_sort_key(bound: Bound) -> tuple[timedelta, str]:+ """Order bounds by cadence, ties broken by blocker id so a graph always yields the same blame."""+ return (bound.value, bound.blocker or "")+++def _finest(bounds: list[Bound]) -> Bound:+ return min(bounds, key=_bound_sort_key)+++def ancestors_of(node_id: str, edges: list[tuple[str, str]]) -> set[str]:+ """Every node upstream of `node_id`, however far — the cone whose delivery it inherits."""+ parents: dict[str, list[str]] = defaultdict(list)+ for upstream, downstream in edges:+ parents[downstream].append(upstream)++ seen: set[str] = set()+ queue = deque(parents[node_id])+ while queue:+ current = queue.popleft()+ if current in seen:+ continue+ seen.add(current)+ queue.extend(parents[current])+ return seen+++def all_source_floor_bounds(edges: list[tuple[str, str]], source_intervals: dict[str, timedelta]) -> dict[str, Bound]:+ """Every node's source floor, with the source that set it, in one forward pass.A source node's floor is its own sync interval. A derived node's floor is the finest (min)among its parents' floors, because its output changes whenever any input changes: a view@@ -181,13 +221,14 @@ def all_source_floors(edges: list[tuple[str, str]], source_intervals: dict[str,all_ids = set(source_intervals) | {node for edge in edges for node in edge}in_degree = {node: len(adj.parents.get(node, [])) for node in all_ids}queue = deque(node for node in all_ids if in_degree[node] == 0)- floor: dict[str, timedelta] = {}+ floor: dict[str, Bound] = {}while queue:node = queue.popleft()if node in source_intervals:- floor[node] = source_intervals[node]+ floor[node] = Bound(value=source_intervals[node], blocker=node)else:- floor[node] = min((floor[parent] for parent in adj.parents.get(node, [])), default=STREAMING)+ inherited = [floor[parent] for parent in adj.parents.get(node, [])]+ floor[node] = _finest(inherited) if inherited else Bound(value=STREAMING, blocker=None)for child in adj.children.get(node, []):in_degree[child] -= 1if in_degree[child] == 0:@@ -195,21 +236,28 @@ def all_source_floors(edges: list[tuple[str, str]], source_intervals: dict[str,return floor-def all_consumer_ceilings(+def all_consumer_ceiling_bounds(edges: list[tuple[str, str]], declared_targets: dict[str, timedelta]-) -> dict[str, timedelta | None]:- """Every node's consumer ceiling (finest declared target among strict descendants) in one- reverse pass. None when no descendant declares a target. Cyclic nodes are omitted."""+) -> dict[str, Bound | None]:+ """Every node's consumer ceiling, with the descendant that declared it, in one reverse pass.++ The ceiling is the finest declared target among strict descendants; None when no descendant+ declares one. Cyclic nodes are omitted.+ """adj = _adjacency(edges)all_ids = set(declared_targets) | {node for edge in edges for node in edge}out_degree = {node: len(adj.children.get(node, [])) for node in all_ids}queue = deque(node for node in all_ids if out_degree[node] == 0)- ceiling: dict[str, timedelta | None] = {}+ ceiling: dict[str, Bound | None] = {}while queue:node = queue.popleft()- candidates = [declared_targets[child] for child in adj.children.get(node, []) if child in declared_targets]- candidates += [c for child in adj.children.get(node, []) if (c := ceiling.get(child)) is not None]- ceiling[node] = min(candidates) if candidates else None+ candidates = [+ Bound(value=declared_targets[child], blocker=child)+ for child in adj.children.get(node, [])+ if child in declared_targets+ ]+ candidates += [bound for child in adj.children.get(node, []) if (bound := ceiling.get(child)) is not None]+ ceiling[node] = _finest(candidates) if candidates else Nonefor parent in adj.parents.get(node, []):out_degree[parent] -= 1if out_degree[parent] == 0:@@ -217,6 +265,21 @@ def all_consumer_ceilings(return ceiling+def all_source_floors(edges: list[tuple[str, str]], source_intervals: dict[str, timedelta]) -> dict[str, timedelta]:+ """Every node's source floor, for callers that need the value and not the blame."""+ return {node: bound.value for node, bound in all_source_floor_bounds(edges, source_intervals).items()}+++def all_consumer_ceilings(+ edges: list[tuple[str, str]], declared_targets: dict[str, timedelta]+) -> dict[str, timedelta | None]:+ """Every node's consumer ceiling, for callers that need the value and not the blame."""+ return {+ node: (bound.value if bound is not None else None)+ for node, bound in all_consumer_ceiling_bounds(edges, declared_targets).items()+ }++def nearest_schedulable_bucket_at_least(floor: timedelta) -> timedelta:"""The finest schedulable bucket no finer than `floor` — coarsen up to a runnable cadence.@@ -226,17 +289,25 @@ def nearest_schedulable_bucket_at_least(floor: timedelta) -> timedelta:coarsest bucket: running more often than a source delivers only wastes a run, never breaksfreshness. Mirrors nearest_schedulable_bucket_at_most's "fresher is always safe" fallback."""- coarser_or_equal = [bucket for bucket in SCHEDULABLE_BUCKETS if bucket >= floor]- return min(coarser_or_equal) if coarser_or_equal else max(SCHEDULABLE_BUCKETS)+ return _nearest_at_least(floor, SCHEDULABLE_BUCKETS)def nearest_schedulable_bucket_at_most(cadence: timedelta) -> timedelta:"""The coarsest schedulable bucket no coarser than `cadence` — round a non-bucket seed down to a- finer bucket so "no older than `cadence`" stays honored (fresher is always safe). Falls back to- the finest bucket for a sub-minute cadence, the finest anything can actually be scheduled at.+ finer bucket so "no older than `cadence`" stays honored (fresher is always safe). A cadence+ finer than every bucket falls back to the finest one, since nothing runs faster than that."""- finer_or_equal = [bucket for bucket in SCHEDULABLE_BUCKETS if bucket <= cadence]- return max(finer_or_equal) if finer_or_equal else min(SCHEDULABLE_BUCKETS)+ return _nearest_at_most(cadence, SCHEDULABLE_BUCKETS)+++def _nearest_at_least(value: timedelta, buckets: frozenset[timedelta]) -> timedelta:+ coarser_or_equal = [bucket for bucket in buckets if bucket >= value]+ return min(coarser_or_equal) if coarser_or_equal else max(buckets)+++def _nearest_at_most(value: timedelta, buckets: frozenset[timedelta]) -> timedelta:+ finer_or_equal = [bucket for bucket in buckets if bucket <= value]+ return max(finer_or_equal) if finer_or_equal else min(buckets)@dataclasses.dataclass@@ -289,13 +360,138 @@ def normalize_seed_target(seed: timedelta, source_floor: timedelta) -> timedeltato the source floor if the source cannot deliver that fast. So a go-live backfill persists atarget that equals what the scheduler will run, rather than an unschedulable (45min) orunsatisfiable (finer than the source) one that reconcile would have to clamp anyway.++ A sub-15min v1 seed lands on 15min, the same coarsening migration 0031 applied to saved queries."""- bucket = nearest_schedulable_bucket_at_most(seed)+ bucket = _nearest_at_most(seed, SCHEDULABLE_BUCKETS)if is_finer_than(bucket, source_floor):- return nearest_schedulable_bucket_at_least(source_floor)+ return _nearest_at_least(source_floor, SCHEDULABLE_BUCKETS)return bucket+BlockedBy = Literal["source", "consumer"]++[email protected](frozen=True, kw_only=True, slots=True)+class TargetOption:+ """One cadence a person could pick, and why it is withheld when it is."""++ value: timedelta+ allowed: bool+ blocked_by: BlockedBy | None = None+ blocker: str | None = None # node id of the source or consumer that withholds it++[email protected](frozen=True, kw_only=True, slots=True)+class TargetBounds:+ """Every selectable cadence for one node, each marked allowed or blocked with its cause.++ `floor` and `ceiling` are reported only when they actually withhold an option. A 5min source+ delivers faster than any tier runs, so it withholds nothing, and reporting it would explain a+ restriction the person cannot see.+ """++ options: tuple[TargetOption, ...] # ascending by cadence+ floor: Bound | None = None+ ceiling: Bound | None = None++ @property+ def allowed(self) -> tuple[timedelta, ...]:+ return tuple(option.value for option in self.options if option.allowed)++ @property+ def satisfiable(self) -> bool:+ """False when nothing is legal: bounds that cross, or a source slower than every target."""+ return bool(self.allowed)++ def option_for(self, target: timedelta) -> TargetOption | None:+ return next((option for option in self.options if option.value == target), None)+++def compute_target_bounds(+ *,+ node_id: str,+ edges: list[tuple[str, str]],+ declared_targets: dict[str, timedelta],+ source_intervals: dict[str, timedelta],+) -> TargetBounds:+ """Resolve one node's selectable cadences, marking each blocked option with what blocks it.++ The single answer to "what may this node be set to, and why not the rest" — the validator, the+ API payload, and any UI that offers a choice all read this, so a refusal and a disabled option+ can never disagree about the same node.+ """+ floor = all_source_floor_bounds(edges, source_intervals).get(node_id, Bound(value=STREAMING, blocker=None))+ ceiling = all_consumer_ceiling_bounds(edges, declared_targets).get(node_id)+ return _bounds_from(floor=floor, ceiling=ceiling)+++def _bounds_from(*, floor: Bound, ceiling: Bound | None) -> TargetBounds:+ """Mark every cadence against one pair of bounds, reporting each bound only if it blocks."""+ options: list[TargetOption] = []+ for value in sorted(SCHEDULABLE_BUCKETS):+ if is_finer_than(value, floor.value):+ options.append(TargetOption(value=value, allowed=False, blocked_by="source", blocker=floor.blocker))+ elif ceiling is not None and is_coarser_than(value, ceiling.value):+ options.append(TargetOption(value=value, allowed=False, blocked_by="consumer", blocker=ceiling.blocker))+ else:+ options.append(TargetOption(value=value, allowed=True))++ blocked = {option.blocked_by for option in options if not option.allowed}+ return TargetBounds(+ options=tuple(options),+ floor=floor if "source" in blocked else None,+ ceiling=ceiling if "consumer" in blocked else None,+ )+++def intersect_target_bounds(bounds: Iterable[TargetBounds]) -> TargetBounds:+ """Fold one node's bounds across the several DAGs it can appear in, tightest side winning.++ A saved query duplicated into more than one DAG has a node in each, and the write path+ validates against every one of them. Offering the union of what any single DAG allows would+ hand someone an option their own save then refuses, so intersect: the coarsest floor and the+ finest ceiling. Bounds that block nothing are absent, and absent is the identity here.+ """+ per_dag = list(bounds)+ floors = [bound.floor for bound in per_dag if bound.floor is not None]+ ceilings = [bound.ceiling for bound in per_dag if bound.ceiling is not None]+ return _bounds_from(+ floor=max(floors, key=_bound_sort_key) if floors else Bound(value=STREAMING, blocker=None),+ ceiling=min(ceilings, key=_bound_sort_key) if ceilings else None,+ )+++def _describe(node_id: str | None, names: Mapping[str, str] | None, fallback: str) -> str:+ """Name a blocking node when the caller supplied names, else fall back to a generic phrase."""+ name = (names or {}).get(node_id or "")+ return name or fallback+++def _nothing_satisfiable_message(bounds: TargetBounds, names: Mapping[str, str] | None) -> str:+ """Explain a node with no legal cadence at all: crossed bounds, or a source slower than 30 days."""+ floor, ceiling = bounds.floor, bounds.ceiling+ source = _describe(floor.blocker, names, "an upstream source") if floor else ""+ consumer = _describe(ceiling.blocker, names, "a view or endpoint built on this one") if ceiling else ""+ if floor is not None and ceiling is not None:+ return (+ f"No cadence works here: {source} only syncs every {humanize_cadence(floor.value)},"+ f" but {consumer} refreshes every {humanize_cadence(ceiling.value)}."+ f" Slow down {consumer} or speed up {source}."+ )+ if floor is not None:+ return (+ f"No cadence works here: {source} only syncs every {humanize_cadence(floor.value)},"+ f" less often than anything this can refresh at. Speed up {source} first."+ )+ if ceiling is not None:+ return (+ f"No cadence works here: {consumer} refreshes every {humanize_cadence(ceiling.value)},"+ f" more often than anything this can refresh at. Slow down {consumer} first."+ )+ return "No cadence works here."++def validate_declared_target(*,node_id: str,@@ -303,27 +499,45 @@ def validate_declared_target(edges: list[tuple[str, str]],declared_targets: dict[str, timedelta],source_intervals: dict[str, timedelta],+ names: Mapping[str, str] | None = None,) -> None:- """Raise if `target` is not a schedulable bucket or falls outside the node's bounds."""+ """Raise if `target` is not selectable or falls outside the node's bounds.++ `names` maps node ids to display names; supply it to have refusals name the source or view+ that blocks the target, which is the thing a person has to change to unblock it.+ """if target not in SCHEDULABLE_BUCKETS:supported = ", ".join(format_cadence(interval) for interval in sorted(SCHEDULABLE_BUCKETS))raise UnsupportedFrequencyTargetError(f"Can't refresh every {humanize_cadence(target)}. Pick one of: {supported}.")- source_floor = all_source_floors(edges, source_intervals).get(node_id, STREAMING)- consumer_ceiling = all_consumer_ceilings(edges, declared_targets).get(node_id)- # Both messages name the bound itself rather than a direction. Bounds are inclusive, so the- # bound is always a legal answer, while "or faster"/"or slower" promises room that may not- # exist: a 15min ceiling has nothing faster to offer through the cadence picker.- if is_finer_than(target, source_floor):++ bounds = compute_target_bounds(+ node_id=node_id, edges=edges, declared_targets=declared_targets, source_intervals=source_intervals+ )+ option = bounds.option_for(target)+ if option is None or option.allowed:+ return++ # Nothing legal to fall back to, so no message here can end in "pick X instead"+ if not bounds.satisfiable:+ raise UnsatisfiableFrequencyError(_nothing_satisfiable_message(bounds, names))++ # Suggest a cadence the same call would accept, and name the bound itself rather than a+ # direction. Bounds are inclusive, so the bound is always a legal answer, while "or slower" /+ # "or faster" promises room that may not exist: a 15min ceiling has nothing fresher to offer.+ if option.blocked_by == "source" and bounds.floor is not None:+ source = _describe(option.blocker, names, "an upstream source")raise UnsatisfiableFrequencyError(- f"Can't refresh every {humanize_cadence(target)}: the sources this query reads only deliver new data"- f" every {humanize_cadence(source_floor)}. Pick {humanize_cadence(source_floor)} instead."+ f"Can't refresh every {humanize_cadence(target)}: {source} only syncs every"+ f" {humanize_cadence(bounds.floor.value)}."+ f" Pick {humanize_cadence(min(bounds.allowed))} instead.")- if consumer_ceiling is not None and is_coarser_than(target, consumer_ceiling):+ if option.blocked_by == "consumer" and bounds.ceiling is not None:+ consumer = _describe(option.blocker, names, "a view or endpoint built on this one")raise UnsatisfiableFrequencyError(- f"Can't refresh every {humanize_cadence(target)}: a view or endpoint built on this one needs data no"- f" older than {humanize_cadence(consumer_ceiling)}. Pick {humanize_cadence(consumer_ceiling)} instead."+ f"Can't refresh every {humanize_cadence(target)}: {consumer} refreshes every"+ f" {humanize_cadence(bounds.ceiling.value)}. Pick {humanize_cadence(max(bounds.allowed))} instead.")diff --git a/products/data_modeling/backend/logic/node_frequency.py b/products/data_modeling/backend/logic/node_frequency.pyindex 1a8b24c1aef3..afc9f7789cfc 100644--- a/products/data_modeling/backend/logic/node_frequency.py+++ b/products/data_modeling/backend/logic/node_frequency.py@@ -15,7 +15,15 @@ from datetime import timedeltafrom django.db.models import Q, QuerySetfrom 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.logic.freshness import (+ STREAMING,+ TargetBounds,+ all_source_floors,+ ancestors_of,+ compute_target_bounds,+ intersect_target_bounds,+ normalize_seed_target,+)from products.data_modeling.backend.models.dag import DAGfrom products.data_modeling.backend.models.edge import Edgefrom products.data_modeling.backend.models.node import Node, NodeType@@ -34,6 +42,32 @@ _ORIGIN_POSTHOG = "posthog"_ORIGIN_WAREHOUSE = "warehouse"[email protected](frozen=True, kw_only=True, slots=True)+class NodeIdentity:+ """What a node is in access-control terms, so a caller can decide whether to name it.++ All three empty means the node predates the origin stamp, and a caller that redacts should+ treat it as withheld rather than guess.+ """++ saved_query_id: str | None # views, materialized views and endpoints, under `warehouse_view`+ warehouse_table_id: str | None # imported source tables, under `warehouse_table`+ is_posthog_table: bool # `events`, `persons` and friends, readable by anyone on the project+++def node_identity(node: Node) -> NodeIdentity:+ """Resolve one node to the resource its name belongs to."""+ if node.saved_query_id is not None:+ return NodeIdentity(saved_query_id=str(node.saved_query_id), warehouse_table_id=None, is_posthog_table=False)+ properties = node.properties or {}+ table_id = properties.get(_WAREHOUSE_TABLE_ID_KEY)+ return NodeIdentity(+ saved_query_id=None,+ warehouse_table_id=str(table_id) if table_id else None,+ is_posthog_table=properties.get(_ORIGIN_KEY) == _ORIGIN_POSTHOG,+ )++def get_declared_target(node: Node) -> timedelta | None:"""Return the node's declared freshness target, or None if it has none."""seconds = (node.properties or {}).get(_SYSTEM_KEY, {}).get(_FREQUENCY_KEY, {}).get(_TARGET_SECONDS_KEY)@@ -178,6 +212,8 @@ class FrequencyGraph:declared_anchors: dict[str, int] # declared per-node schedule anchors (minutes past Monday 00:00 UTC)source_intervals: dict[str, timedelta] # per source (TABLE) nodebest_effort_source_ids: set[str] # sources treated as STREAMING but not guaranteed+ names: dict[str, str] # node id -> display name, so a bound can name what set it+ identities: dict[str, NodeIdentity] # node id -> the resource its name belongs todef build_frequency_graph(dag: DAG) -> FrequencyGraph:@@ -209,6 +245,63 @@ def build_frequency_graph(dag: DAG) -> FrequencyGraph:declared_anchors=declared_anchors,source_intervals=source_intervals,best_effort_source_ids=best_effort,+ names={str(node.id): node.name for node in nodes},+ identities={str(node.id): node_identity(node) for node in nodes},+ )++[email protected](frozen=True, kw_only=True, slots=True)+class SavedQueryFrequencyBounds:+ """A saved query's selectable cadences, plus what a caller needs to name the blockers."""++ bounds: TargetBounds+ names: dict[str, str] # node id -> display name, covering every blocker the bounds reference+ identities: dict[str, NodeIdentity] # node id -> the resource its name belongs to+ best_effort_source_ids: set[str] # upstream sources with no schedule, so the floor is a guess+++def saved_query_target_bounds(team_id: int, saved_query_id: str | uuid.UUID) -> SavedQueryFrequencyBounds | None:+ """Every cadence this saved query may be set to, folded across each DAG holding a node for it.++ The read-side twin of `apply_saved_query_frequency_target`: same nodes, same per-DAG graphs,+ same validator input, so a cadence offered here cannot be refused by the write that follows.++ None means no DAG node carries this saved query, which is not "anything goes" — it is a target+ with nowhere to be stored, and the caller owes the reader a different answer than a picker.+ """+ nodes = list(Node.objects.filter(team_id=team_id, saved_query_id=saved_query_id).select_related("dag"))+ if not nodes:+ return None++ per_dag: list[TargetBounds] = []+ names: dict[str, str] = {}+ identities: dict[str, NodeIdentity] = {}+ best_effort: set[str] = set()+ graphs: dict[str, FrequencyGraph] = {}+ for node in nodes:+ # a saved query can hold two nodes in one DAG, and that DAG's graph is the same for both+ dag_key = str(node.dag_id)+ if dag_key not in graphs:+ graphs[dag_key] = build_frequency_graph(node.dag)+ graph = graphs[dag_key]+ per_dag.append(+ compute_target_bounds(+ node_id=str(node.id),+ edges=graph.edges,+ declared_targets=graph.declared_targets,+ source_intervals=graph.source_intervals,+ )+ )+ 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)++ return SavedQueryFrequencyBounds(+ bounds=intersect_target_bounds(per_dag),+ names=names,+ identities=identities,+ 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.pyindex 0c22bd6f5657..8391202624ca 100644--- a/products/data_modeling/backend/logic/schedule_reconcile.py+++ b/products/data_modeling/backend/logic/schedule_reconcile.py@@ -12,7 +12,7 @@ the Temporal schedule API.import uuidimport dataclasses-from collections.abc import Iterable+from collections.abc import Iterable, Mappingfrom datetime import timedeltafrom typing import TYPE_CHECKING@@ -206,7 +206,11 @@ def _warn_on_invalid_targets(dag: DAG, graph: FrequencyGraph | None = None) -> Ndef apply_saved_query_frequency_target(- saved_query: "DataWarehouseSavedQuery", target: timedelta | None, *, reconcile: bool = True+ saved_query: "DataWarehouseSavedQuery",+ target: timedelta | None,+ *,+ reconcile: bool = True,+ visible_names: Mapping[str, str] | None = None,) -> int:"""Write a frequency target through to the DAG node(s) carrying this saved query.@@ -219,6 +223,12 @@ def apply_saved_query_frequency_target(Returns the number of nodes written (0 = no DAG node, so a non-None target was stored nowhere).+ `visible_names` is the set of node names a refusal is allowed to use. It defaults to naming+ nothing, because a refusal travels: `schedule_materialization` re-raises it and the endpoints+ API returns its text verbatim, so a default of "name everything" would hand a caller the name+ of a node they may not read. Callers holding a per-user map (the saved-query surfaces) pass it+ and get the better message; everything left out falls back to generic prose.+Atomic because a saved query can still carry nodes in several DAGs while duplicates are beingconsolidated away: without it, a target rejected by the third node stays written on the firsttwo, and their reconciles are already queued. One node per saved query is the end state, which@@ -243,6 +253,7 @@ def apply_saved_query_frequency_target(edges=graph.edges,declared_targets=graph.declared_targets,source_intervals=graph.source_intervals,+ names=visible_names or {},)set_declared_target(node, target)written += 1@@ -251,6 +262,27 @@ def apply_saved_query_frequency_target(return written+def check_saved_query_frequency_target(+ saved_query: "DataWarehouseSavedQuery", target: timedelta, *, visible_names: Mapping[str, str] | None = None+) -> None:+ """Raise if this target cannot be honored on any of the saved query's nodes, writing nothing.++ The write path validates too, but only after its caller has committed state it then has to undo+ by hand. Callers serving a user can ask first and refuse before touching anything. See+ `apply_saved_query_frequency_target` for `visible_names`.+ """+ for node in Node.objects.filter(team=saved_query.team, saved_query=saved_query).select_related("dag", "dag__team"):+ graph = build_frequency_graph(node.dag)+ validate_declared_target(+ node_id=str(node.id),+ target=target,+ edges=graph.edges,+ declared_targets=graph.declared_targets,+ source_intervals=graph.source_intervals,+ names=visible_names or {},+ )++def apply_saved_query_frequency_anchor(saved_query: "DataWarehouseSavedQuery", anchor_minutes: int | None, *, reconcile: bool = True) -> int:diff --git a/products/data_modeling/backend/test/test_freshness.py b/products/data_modeling/backend/test/test_freshness.pyindex dd33f6be84d5..7f4e1707f6a9 100644--- a/products/data_modeling/backend/test/test_freshness.py+++ b/products/data_modeling/backend/test/test_freshness.py@@ -14,7 +14,9 @@ from products.data_modeling.backend.logic.freshness import (all_source_floors,clamp_to_source_floor,compute_effective_cadences,+ compute_target_bounds,find_invalid_targets,+ intersect_target_bounds,normalize_seed_target,validate_declared_target,)@@ -25,6 +27,7 @@ M30 = timedelta(minutes=30)M45 = timedelta(minutes=45)H1 = timedelta(hours=1)H6 = timedelta(hours=6)+H12 = timedelta(hours=12)DAY = timedelta(days=1)DAY30 = timedelta(days=30)DAY45 = timedelta(days=45)@@ -161,6 +164,35 @@ class TestValidateFrequencyTarget(TestCase):assert "or faster" not in messageassert "or slower" not in message+ def test_crossed_bounds_name_both_sides_and_suggest_no_cadence(self):+ # 6h source under a 15min endpoint: every cadence is illegal, so a "pick X instead"+ # here would name a value the picker cannot offer.+ with self.assertRaises(UnsatisfiableFrequencyError) as raised:+ validate_declared_target(+ node_id="a",+ target=H6,+ edges=[("src", "a"), ("a", "ep")],+ declared_targets={"ep": M15},+ source_intervals={"src": H6},+ names={"src": "stripe_invoices", "ep": "daily_revenue"},+ )+ message = str(raised.exception)+ self.assertIn("stripe_invoices", message)+ self.assertIn("daily_revenue", message)+ self.assertNotIn("Pick ", message)++ # sources sync this fast, model tiers do not run this fast+ @parameterized.expand([("one_minute", timedelta(minutes=1)), ("five_minutes", M5)])+ def test_sub_15min_target_is_refused_even_when_the_source_delivers_that_fast(self, _name, target):+ with self.assertRaises(UnsupportedFrequencyTargetError):+ validate_declared_target(+ node_id="a",+ target=target,+ edges=[("src", "a")],+ declared_targets={},+ source_intervals={"src": target},+ )+def test_supported_targets_are_canonical_sync_frequency_buckets(self):from products.warehouse_sources.backend.facade.models import ( # noqa: PLC0415 - keeps Django off this pure test module's import pathsync_frequency_interval_to_sync_frequency,@@ -174,6 +206,94 @@ class TestValidateFrequencyTarget(TestCase):self.assertEqual(sync_frequency_to_sync_frequency_interval(label), interval)+class TestComputeTargetBounds(TestCase):+ # src syncs every 6h, and endpoint `ep` downstream refreshes every 12h,+ # so only 6h and 12h are legal for `a` — every other cadence is withheld by one side or the other.+ EDGES = [("src", "a"), ("a", "ep")]+ TARGETS = {"ep": H12}+ INTERVALS = {"src": H6}++ def _options(self, **overrides):+ bounds = compute_target_bounds(+ node_id=overrides.pop("node_id", "a"),+ edges=overrides.pop("edges", self.EDGES),+ declared_targets=overrides.pop("declared_targets", self.TARGETS),+ source_intervals=overrides.pop("source_intervals", self.INTERVALS),+ )+ return bounds, {option.value: option for option in bounds.options}++ @parameterized.expand(+ [+ ("below_floor", M15, "source", "src"),+ ("at_floor", H6, None, None),+ ("at_ceiling", H12, None, None),+ ("above_ceiling", DAY, "consumer", "ep"),+ ]+ )+ def test_each_option_carries_the_node_that_withholds_it(self, _name, value, blocked_by, blocker):+ _, options = self._options()+ option = options[value]+ self.assertEqual(option.allowed, blocked_by is None)+ self.assertEqual(option.blocked_by, blocked_by)+ self.assertEqual(option.blocker, blocker)++ def test_blame_names_the_originating_source_not_the_nearest_parent(self):+ bounds, _ = self._options(node_id="c", edges=[("src", "a"), ("a", "b"), ("b", "c")], declared_targets={})+ assert bounds.floor is not None+ self.assertEqual(bounds.floor.blocker, "src")++ # a 5min source delivers faster than any tier runs, so it blocks nothing and needs no explaining+ def test_a_source_faster_than_every_cadence_sets_no_visible_floor(self):+ bounds, options = self._options(declared_targets={}, source_intervals={"src": M5})+ self.assertIsNone(bounds.floor)+ self.assertTrue(all(option.allowed for option in options.values()))++ def test_crossed_bounds_leave_nothing_pickable(self):+ bounds, _ = self._options(declared_targets={"ep": M15})+ self.assertFalse(bounds.satisfiable)+++class TestIntersectTargetBounds(TestCase):+ # the same saved query has a node in two DAGs: one bounded by a 6h source, the other by a+ # 12h consumer. The save path validates against both, so the picker has to as well.+ def _fold(self, *per_dag):+ bounds = intersect_target_bounds(+ compute_target_bounds(node_id="a", edges=edges, declared_targets=targets, source_intervals=intervals)+ for edges, targets, intervals in per_dag+ )+ return bounds, {option.value: option for option in bounds.options}++ # (edges, declared targets, source intervals) for one DAG the saved query has a node in+ OneDag = tuple[list[tuple[str, str]], dict[str, timedelta], dict[str, timedelta]]++ SLOW_SOURCE: OneDag = ([("src", "a")], {}, {"src": H6})+ FAST_CONSUMER: OneDag = ([("a", "ep")], {"ep": H12}, {})++ def test_the_tightest_bound_from_any_dag_wins(self):+ bounds, options = self._fold(self.SLOW_SOURCE, self.FAST_CONSUMER)+ self.assertFalse(options[M15].allowed)+ self.assertFalse(options[DAY].allowed)+ self.assertEqual([option.value for option in bounds.options if option.allowed], [H6, H12])++ def test_each_side_keeps_the_blame_from_the_dag_that_set_it(self):+ bounds, _ = self._fold(self.SLOW_SOURCE, self.FAST_CONSUMER)+ assert bounds.floor is not None and bounds.ceiling is not None+ self.assertEqual((bounds.floor.blocker, bounds.ceiling.blocker), ("src", "ep"))++ def test_a_dag_that_blocks_nothing_widens_nothing(self):+ # an unbounded second node must not re-open what the first DAG withholds+ bounds, options = self._fold(self.SLOW_SOURCE, ([("free", "a")], {}, {"free": STREAMING}))+ assert bounds.floor is not None+ self.assertEqual(bounds.floor.blocker, "src")+ self.assertFalse(options[M15].allowed)++ def test_no_bounds_anywhere_allows_everything(self):+ bounds, options = self._fold(([("free", "a")], {}, {"free": STREAMING}))+ self.assertIsNone(bounds.floor)+ self.assertIsNone(bounds.ceiling)+ self.assertTrue(all(option.allowed for option in options.values()))++class TestFindInvalidTargets(TestCase):@parameterized.expand([@@ -253,6 +373,8 @@ class TestNormalizeSeedTarget(TestCase):("finer_than_floor_coarsens", M15, H1, H1),# non-bucket over a slow source: snap down then coarsen to the floor("snaps_then_coarsens_to_floor", M45, H6, H6),+ # a v1 seed below the finest tier rounds up, matching migration 0031's coarsening+ ("sub_15min_seed_rounds_up", M5, M5, M15),# already coarser than the floor -> left alone("coarser_than_floor_stays", DAY, H6, DAY),]diff --git a/products/data_warehouse/backend/presentation/views/saved_query.py b/products/data_warehouse/backend/presentation/views/saved_query.pyindex 0ffc574e64f9..ab67e940d073 100644--- a/products/data_warehouse/backend/presentation/views/saved_query.py+++ b/products/data_warehouse/backend/presentation/views/saved_query.py@@ -5,7 +5,7 @@ from typing import Any, castfrom django.conf import settingsfrom django.db import transaction-from django.db.models import Count, OuterRef, Prefetch, Q, Subquery, TextField+from django.db.models import Count, Model, OuterRef, Prefetch, Q, Subquery, TextFieldfrom django.db.models.functions import Castimport structlog@@ -44,7 +44,7 @@ from posthog.models.activity_logging.activity_page import activity_page_responsefrom posthog.rate_limit import MaterializationRateThrottle, RunSavedQueryRateThrottlefrom posthog.rbac.access_control_api_mixin import AccessControlViewSetMixinfrom posthog.rbac.query_access import assert_user_can_read_query-from posthog.rbac.user_access_control import UserAccessControlSerializerMixin+from posthog.rbac.user_access_control import UserAccessControl, UserAccessControlSerializerMixinfrom posthog.temporal.common.client import sync_connectfrom products.data_modeling.backend.facade.modeling import DataWarehouseModelPath@@ -71,6 +71,7 @@ from products.warehouse_sources.backend.facade.hogql import (get_view_or_table_by_name,)from products.warehouse_sources.backend.facade.models import (+ DataWarehouseTable,sync_frequency_interval_to_sync_frequency,sync_frequency_to_sync_frequency_interval,)@@ -129,6 +130,205 @@ SYNC_FREQUENCY_MANAGED_BY_DAG_HELP_TEXT = ()+class SyncFrequencyBlockerSerializer(serializers.Serializer):+ """The node holding a cadence back, named so a refusal points at something a person can open."""++ id = serializers.CharField(help_text="Data modeling node ID of the source or view.")+ name = serializers.CharField(help_text="Node name, as it appears in the data modeling graph.")+++class SyncFrequencyBoundSerializer(serializers.Serializer):+ label = serializers.CharField( # type: ignore[assignment] # field name intentionally shadows Field.label+ help_text="The bounding cadence in plain English, for example '6 hours'. Matches the wording "+ "used in the error raised when an out-of-bounds cadence is written. Prose rather than a "+ "`sync_frequency` value because a source can deliver on a cadence no `sync_frequency` names."+ )+ blocker = SyncFrequencyBlockerSerializer(+ allow_null=True,+ help_text="Node that set this bound. Null when nothing identifiable set it, and also when it "+ "sits outside the caller's access grants: the bound still applies, it just goes unnamed.",+ )+++class SyncFrequencyOptionSerializer(serializers.Serializer):+ cadence = serializers.ChoiceField(choices=MATERIALIZE_SYNC_FREQUENCY_CHOICES, help_text="A `sync_frequency` value.")+ allowed = serializers.BooleanField(help_text="False when writing this cadence would be rejected.")+ blocked_by = serializers.ChoiceField(+ choices=[("source", "source"), ("consumer", "consumer")],+ allow_null=True,+ help_text="Which side withholds this cadence: 'source' when no upstream source syncs that "+ "often, 'consumer' when a downstream view or endpoint refreshes more often than this. "+ "Null when the cadence is allowed.",+ )+ blocker = SyncFrequencyBlockerSerializer(+ allow_null=True,+ 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.",+ )+++class SyncFrequencyBoundsSerializer(serializers.Serializer):+ frequency_mode = serializers.ChoiceField(+ choices=[+ ("tiered", "tiered"),+ ("dag_schedule", "dag_schedule"),+ ("managed_viewset", "managed_viewset"),+ ("legacy", "legacy"),+ ("no_node", "no_node"),+ ],+ help_text="What governs this view's cadence. 'tiered' is the only mode where `options` is "+ "meaningful and `sync_frequency` is writable per view. 'dag_schedule' means the team's single "+ "DAG schedule owns it, 'managed_viewset' means PostHog owns the view, 'legacy' means the v1 "+ "backend, where any cadence is accepted and no bounds apply, and 'no_node' means the view has "+ "no data modeling node to store a cadence on.",+ )+ options = SyncFrequencyOptionSerializer(+ many=True,+ help_text="Every cadence a picker may show, coarsest-last, each marked allowed or blocked with "+ "its cause. Empty outside 'tiered' mode.",+ )+ floor = SyncFrequencyBoundSerializer(+ allow_null=True,+ help_text="The fastest bound: no cadence finer than this is allowed, because the source named "+ "here does not sync more often. Null when no source withholds a cadence.",+ )+ ceiling = SyncFrequencyBoundSerializer(+ allow_null=True,+ help_text="The slowest bound: no cadence coarser than this is allowed, because the consumer "+ "named here refreshes that often. Null when no consumer withholds a cadence.",+ )+ best_effort_sources = SyncFrequencyBlockerSerializer(+ many=True,+ help_text="Upstream sources with no sync schedule, so the floor is a guess: these arrive when "+ "someone runs them, and refreshing more often than they really sync will serve stale data. "+ "Only sources the caller may read are listed.",+ )+ best_effort_sources_withheld = serializers.BooleanField(+ help_text="True when at least one such source sits outside the caller's access grants, so the "+ "list above is incomplete and the caveat still applies."+ )+++SYNC_FREQUENCY_BOUNDS_HELP_TEXT = (+ "Which cadences this view can actually be set to, and what withholds the rest. Computed from the "+ "view's data modeling lineage: upstream source sync frequencies set a floor, downstream cadences "+ "set a ceiling. Read-only, and present on retrieve, create and update responses only."+)+++def _unbounded_frequency_payload(mode: str) -> dict[str, Any]:+ """The payload for a view whose cadence no lineage governs, so there is nothing to withhold."""+ return {+ "frequency_mode": mode,+ "options": [],+ "floor": None,+ "ceiling": None,+ "best_effort_sources": [],+ "best_effort_sources_withheld": False,+ }+++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)+ 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)+ node_ids.update(option.blocker for option in resolved.bounds.options if option.blocker is not None)+ return node_ids+++def visible_blocker_names(+ resolved: Any, user_access_control: UserAccessControl | None, *, team_id: int+) -> dict[str, str]:+ """The blocker names this caller may read, keyed by node id.++ Fails closed, and withholds the node id along with the name: an id on its own still answers+ "something upstream of this view exists", which is what the grant is there to withhold. A node+ with no resolvable resource (predating the origin stamp) is withheld for the same reason.+ """+ node_ids = _blocker_node_ids(resolved)+ if not node_ids or user_access_control is None:+ return {}++ visible: dict[str, str] = {}+ # Lists, not single ids: one saved query or table can hold a node in several DAGs, and a grant+ # covers the resource, so every node of it becomes visible together.+ node_ids_by_saved_query: dict[str, list[str]] = {}+ node_ids_by_table: dict[str, list[str]] = {}+ for node_id in node_ids:+ identity = resolved.identities.get(node_id)+ name = resolved.names.get(node_id)+ if identity is None or name is None:+ continue+ if identity.is_posthog_table:+ visible[node_id] = name # events, persons and friends: readable by anyone on the project+ elif identity.saved_query_id is not None:+ node_ids_by_saved_query.setdefault(identity.saved_query_id, []).append(node_id)+ elif identity.warehouse_table_id is not None:+ node_ids_by_table.setdefault(identity.warehouse_table_id, []).append(node_id)++ def reveal(resource_node_ids: list[str]) -> None:+ visible.update({node_id: resolved.names[node_id] for node_id in resource_node_ids})++ if node_ids_by_saved_query:+ creators = DataWarehouseSavedQuery.objects.filter(id__in=node_ids_by_saved_query, team_id=team_id).values_list(+ "id", "created_by_id"+ )+ levels = user_access_control.bulk_object_access_levels(+ "warehouse_view", [(str(pk), created_by) for pk, created_by in creators]+ )+ for saved_query_id, level in levels.items():+ if level is not None and level != "none":+ reveal(node_ids_by_saved_query[saved_query_id])++ if node_ids_by_table:+ # One at a time rather than in bulk: `warehouse_table` falls back to `external_data_source`,+ # and the bulk call refuses any resource with a fallback parent. Per object is also what+ # honours a deny on one table, or on the source it came from. A table that no longer+ # resolves keeps its name withheld.+ tables = list(+ DataWarehouseTable.objects.filter(id__in=node_ids_by_table, team_id=team_id).exclude(deleted=True)+ )+ user_access_control.preload_object_access_controls(cast(list[Model], tables))+ for table in tables:+ if user_access_control.check_access_level_for_object(table, "viewer"):+ reveal(node_ids_by_table[str(table.id)])+ return visible+++def _frequency_bounds_payload(resolved: Any, visible_names: dict[str, str]) -> dict[str, Any]:+ from products.data_modeling.backend.facade.api import humanize_cadence++ def blocker(node_id: str | None) -> dict[str, str] | None:+ if node_id is None or node_id not in visible_names:+ return None+ return {"id": node_id, "name": visible_names[node_id]}++ def bound(value: Any) -> dict[str, Any] | None:+ if value is None:+ return None+ return {"label": humanize_cadence(value.value), "blocker": blocker(value.blocker)}++ best_effort = sorted(resolved.best_effort_source_ids)+ return {+ "frequency_mode": "tiered",+ "options": [+ {+ "cadence": sync_frequency_interval_to_sync_frequency(option.value),+ "allowed": option.allowed,+ "blocked_by": option.blocked_by,+ "blocker": blocker(option.blocker),+ }+ for option in resolved.bounds.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],+ "best_effort_sources_withheld": any(node_id not in visible_names for node_id in best_effort),+ }++def _node_frequency_targets(root: serializers.BaseSerializer, view: DataWarehouseSavedQuery) -> dict[str, timedelta]:"""Declared node targets for every view the root serializer renders, fetched once.@@ -268,6 +468,22 @@ class DataWarehouseSavedQuerySerializerMixin:def get_sync_frequency_managed_by_dag(self, view: DataWarehouseSavedQuery) -> bool:return bool(self.context.get("sync_frequency_managed_by_dag", False)) # type: ignore[attr-defined]+ @extend_schema_field(SyncFrequencyBoundsSerializer())+ def get_sync_frequency_bounds(self, view: DataWarehouseSavedQuery) -> dict[str, Any]:+ from products.data_modeling.backend.facade.api import saved_query_target_bounds++ team_mode = self.context.get("team_frequency_mode", "legacy") # type: ignore[attr-defined]+ if view.managed_viewset is not None:+ return _unbounded_frequency_payload("managed_viewset")+ if team_mode != "tiered":+ return _unbounded_frequency_payload(team_mode)++ resolved = saved_query_target_bounds(view.team_id, view.pk)+ if resolved is None:+ return _unbounded_frequency_payload("no_node")+ visible = visible_blocker_names(resolved, self.user_access_control, team_id=view.team_id) # type: ignore[attr-defined]+ return _frequency_bounds_payload(resolved, visible)+@extend_schema_field(serializers.CharField(allow_null=True))def get_managed_viewset_kind(self, view: DataWarehouseSavedQuery) -> DataWarehouseManagedViewsetKind | None:return cast(DataWarehouseManagedViewsetKind, view.managed_viewset.kind) if view.managed_viewset else None@@ -388,6 +604,7 @@ class DataWarehouseSavedQuerySerializer(sync_frequency_managed_by_dag = serializers.SerializerMethodField(read_only=True, help_text=SYNC_FREQUENCY_MANAGED_BY_DAG_HELP_TEXT)+ sync_frequency_bounds = serializers.SerializerMethodField(read_only=True, help_text=SYNC_FREQUENCY_BOUNDS_HELP_TEXT)latest_history_id = serializers.SerializerMethodField(read_only=True)last_run_at = serializers.SerializerMethodField(read_only=True)managed_viewset_kind = serializers.SerializerMethodField(read_only=True)@@ -436,6 +653,7 @@ class DataWarehouseSavedQuerySerializer("description","sync_frequency","sync_frequency_managed_by_dag",+ "sync_frequency_bounds","columns","status","last_run_at",@@ -463,6 +681,7 @@ class DataWarehouseSavedQuerySerializer("last_run_at","managed_viewset_kind","sync_frequency_managed_by_dag",+ "sync_frequency_bounds","folder_name","latest_error","latest_history_id",@@ -706,16 +925,26 @@ class DataWarehouseSavedQuerySerializer(UnsupportedFrequencyTargetError,apply_saved_query_frequency_target,declared_targets_by_saved_query,+ saved_query_target_bounds,)target = (None if sync_frequency == "never" else sync_frequency_to_sync_frequency_interval(sync_frequency))previous_target = declared_targets_by_saved_query(view.team_id, [view.pk]).get(str(view.pk))+ # A refusal names what blocks the cadence, so it obeys the same grants the read+ # payload does — otherwise one rejected PATCH reads back a name the caller was+ # never shown. Withheld nodes fall back to generic prose inside the refusal.+ bounds = saved_query_target_bounds(view.team_id, view.pk)+ visible = (+ visible_blocker_names(bounds, self.user_access_control, team_id=view.team_id)+ if bounds is not None+ else {}+ )try:# Validates inside the transaction (a rejected frequency rolls the whole# update back) and queues the schedule reconcile for after commit.- nodes_written = apply_saved_query_frequency_target(view, target)+ nodes_written = apply_saved_query_frequency_target(view, target, visible_names=visible)except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError) as e:raise serializers.ValidationError(str(e))if target is not None and nodes_written == 0:@@ -1050,16 +1279,17 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSeif should_include_database:context["database"] = Database.create_for(team_id=self.team_id, user=cast(User, self.request.user))- context["sync_frequency_managed_by_dag"] = self._sync_frequency_managed_by_dag()+ context["team_frequency_mode"] = self._team_frequency_mode()+ context["sync_frequency_managed_by_dag"] = context["team_frequency_mode"] == "dag_schedule"return context- def _sync_frequency_managed_by_dag(self) -> bool:- """Whether the DAG's single schedule owns cadence for this team.+ def _team_frequency_mode(self) -> str:+ """Which backend owns materialization cadence for this team.- On single-schedule v2 the DAG's one schedule owns cadence, so per-view frequency writes are- rejected; per-node (tiered) schedules and the v1 backend both accept them. This covers only- that one of `update()`'s rejections — it is team-scoped, so the per-view managed-viewset- rejection is not and cannot be reflected here.+ Mirrors the branch `update()` takes on a `sync_frequency` write: `legacy` writes the interval+ column, `tiered` writes the DAG node's freshness target and is the only mode with bounds, and+ `dag_schedule` rejects the write because the team's one DAG schedule owns cadence. Team-scoped,+ so the per-view rejections (managed viewsets, views with no node) are not reflected here."""from products.data_modeling.backend.facade.api import tiered_schedules_enabled@@ -1069,7 +1299,9 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSegroups={"organization": str(self.team.organization_id), "project": str(self.team.id)},send_feature_flag_events=False,)- return bool(v2_enabled) and not tiered_schedules_enabled(self.team)+ if not v2_enabled:+ return "legacy"+ return "tiered" if tiered_schedules_enabled(self.team) else "dag_schedule"def get_serializer_class(self):if self.action == "list":@@ -1290,6 +1522,29 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSeparams.is_valid(raise_exception=True)sync_frequency_interval = sync_frequency_to_sync_frequency_interval(params.validated_data["sync_frequency"])+ from products.data_modeling.backend.facade.api import (+ UnsatisfiableFrequencyError,+ UnsupportedFrequencyTargetError,+ check_saved_query_frequency_target,+ saved_query_target_bounds,+ )++ if sync_frequency_interval is not None and self._team_frequency_mode() == "tiered":+ # Ask before writing, so the ordinary refusal never has to be undone below. Names only+ # what this caller may read, matching the bounds payload — otherwise one rejected+ # materialize reads back a node they were never shown.+ bounds = saved_query_target_bounds(self.team_id, saved_query.pk)+ try:+ check_saved_query_frequency_target(+ saved_query,+ sync_frequency_interval,+ visible_names=(+ visible_blocker_names(bounds, self.user_access_control, team_id=self.team_id) if bounds else {}+ ),+ )+ except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError) as e:+ raise serializers.ValidationError(str(e))+should_unpause = saved_query.sync_frequency_interval is Noneprevious_interval = saved_query.sync_frequency_intervalpreviously_materialized = saved_query.is_materialized@@ -1298,25 +1553,23 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSesaved_query.is_materialized = Truesaved_query.save(update_fields=["sync_frequency_interval", "is_materialized"])- from products.data_modeling.backend.facade.api import (- UnsatisfiableFrequencyError,- UnsupportedFrequencyTargetError,- )-# Enable materialization - this handles model path setup and schedule creation# If this fails, it will set is_materialized = Falsetry:saved_query.schedule_materialization(unpause=should_unpause, trigger_immediate_run=True)- except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError) as e:- # The requested cadence can't be honored (e.g. finer than an upstream source- # delivers) — a request problem, not a server one. `schedule_materialization`- # deliberately re-raises these without applying its disable-on-failure contract, and- # this action is not inside an atomic block, so undo the enable by hand: otherwise the- # 400 leaves is_materialized=True behind and the UI reads the rejection as a success.+ except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError):+ # The check above already refused every cadence the lineage forbids, so reaching here+ # means the lineage moved mid-request. Say so plainly rather than forwarding a message+ # built from unredacted names. `schedule_materialization` re-raises these without+ # applying its disable-on-failure contract, and this action is not inside an atomic+ # block, so undo the enable by hand: otherwise the 400 leaves is_materialized=True+ # behind and the UI reads the rejection as a success.saved_query.sync_frequency_interval = previous_intervalsaved_query.is_materialized = previously_materializedsaved_query.save(update_fields=["sync_frequency_interval", "is_materialized"])- raise serializers.ValidationError(str(e))+ raise serializers.ValidationError(+ "This view's lineage changed while we were setting it up. Reopen it and pick a cadence again."+ )# Refresh from DB to check if schedule_materialization set is_materialized = False on failuresaved_query.refresh_from_db()diff --git a/products/data_warehouse/backend/tests/api/test_saved_query.py b/products/data_warehouse/backend/tests/api/test_saved_query.pyindex 006dc6239d37..b3aca390bb70 100644--- a/products/data_warehouse/backend/tests/api/test_saved_query.py+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py@@ -1041,6 +1041,134 @@ class TestSavedQuery(APIBaseTest):field = DataWarehouseSavedQuerySerializer().fields["sync_frequency"]self.assertFalse(field.read_only)+ def _create_view_with_a_consumer(self, consumer_target: timedelta) -> dict:+ """An upstream view whose only downstream consumer declares `consumer_target`.++ A consumer ceiling is the cheapest real bound to build here: it needs one extra saved+ query, where a source floor would need a warehouse table plus a schema to hang an+ interval off. The bound arithmetic itself is covered in test_freshness.+ """+ from products.data_modeling.backend.logic.node_frequency import set_declared_target++ upstream = self._create_saved_query_for_frequency_tests(name="upstream_view")+ consumer = self.client.post(+ f"/api/environments/{self.team.id}/warehouse_saved_queries/",+ {"name": "consumer_view", "query": {"kind": "HogQLQuery", "query": "select event from upstream_view"}},+ )+ self.assertEqual(consumer.status_code, 201, consumer.json())+ set_declared_target(Node.objects.get(saved_query_id=consumer.json()["id"]), consumer_target)+ return upstream++ def _read_frequency_bounds(self, saved_query_id: str, *, tiered: bool = True, v2: bool = True) -> dict:+ with (+ patch(+ "products.data_warehouse.backend.presentation.views.saved_query.posthoganalytics.feature_enabled",+ side_effect=lambda key, *args, **kwargs: v2 and key == "data-modeling-backend-v2",+ ),+ patch(+ "products.data_modeling.backend.logic.schedule_reconcile.tiered_schedules_enabled",+ return_value=tiered,+ ),+ ):+ response = self.client.get(+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query_id}",+ )+ self.assertEqual(response.status_code, 200, response.json())+ return response.json()["sync_frequency_bounds"]++ @parameterized.expand(+ [+ ("v1_team", False, False, "legacy"),+ ("v2_single_schedule", True, False, "dag_schedule"),+ ("v2_tiered", True, True, "tiered"),+ ]+ )+ def test_bounds_are_offered_only_where_a_per_view_cadence_is_writable(+ self, _name: str, v2: bool, tiered: bool, expected_mode: str+ ):+ # The picker renders from this payload. Offering options to a team whose writes the DAG+ # owns puts a control on screen that can only 400, which is the bug this field exists+ # to close; serving none to a tiered team hides a control that does work.+ saved_query = self._create_saved_query_for_frequency_tests()++ bounds = self._read_frequency_bounds(saved_query["id"], tiered=tiered, v2=v2)++ self.assertEqual(bounds["frequency_mode"], expected_mode)+ self.assertEqual(bool(bounds["options"]), expected_mode == "tiered")++ def test_every_offered_cadence_is_accepted_and_every_withheld_one_is_refused(self):+ # The whole point of serving bounds is that the picker and the write path cannot+ # disagree. Walk every option the API offered and hold the PATCH to that promise.+ upstream = self._create_view_with_a_consumer(consumer_target=timedelta(hours=6))+ options = self._read_frequency_bounds(upstream["id"])["options"]+ self.assertTrue(any(option["allowed"] for option in options))+ self.assertTrue(any(not option["allowed"] for option in options))++ for option in options:+ with (+ patch(+ "products.data_warehouse.backend.presentation.views.saved_query.posthoganalytics.feature_enabled",+ side_effect=self._v2_flag_only,+ ),+ patch(+ "products.data_modeling.backend.logic.schedule_reconcile.tiered_schedules_enabled",+ return_value=True,+ ),+ patch("products.data_modeling.backend.logic.schedule_reconcile.maybe_reconcile_dag"),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{upstream['id']}",+ {"sync_frequency": option["cadence"]},+ )+ self.assertEqual(response.status_code, 200 if option["allowed"] else 400, (option, response.json()))++ def test_a_withheld_cadence_names_the_view_that_withholds_it(self):+ # A disabled option with no reason reads as a broken control. Every block carries the+ # node someone would have to change, by name, not just an id.+ upstream = self._create_view_with_a_consumer(consumer_target=timedelta(hours=6))++ bounds = self._read_frequency_bounds(upstream["id"])++ blocked = {option["cadence"]: option for option in bounds["options"] if not option["allowed"]}+ self.assertEqual(sorted(blocked), ["12hour", "24hour", "30day", "7day"])+ self.assertEqual(blocked["24hour"]["blocked_by"], "consumer")+ self.assertEqual(blocked["24hour"]["blocker"]["name"], "consumer_view")+ self.assertEqual(bounds["ceiling"], {"label": "6 hours", "blocker": blocked["24hour"]["blocker"]})+ self.assertIsNone(bounds["floor"])++ def test_the_refusal_names_the_same_view_the_bounds_blamed(self):+ # Bounds and refusals are two views of one rule, so a caller that ignores the bounds and+ # writes anyway must be told the same thing the picker would have shown.+ upstream = self._create_view_with_a_consumer(consumer_target=timedelta(hours=6))++ with (+ patch(+ "products.data_warehouse.backend.presentation.views.saved_query.posthoganalytics.feature_enabled",+ side_effect=self._v2_flag_only,+ ),+ patch(+ "products.data_modeling.backend.logic.schedule_reconcile.tiered_schedules_enabled",+ return_value=True,+ ),+ patch("products.data_modeling.backend.logic.schedule_reconcile.maybe_reconcile_dag"),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{upstream['id']}",+ {"sync_frequency": "24hour"},+ )++ self.assertEqual(response.status_code, 400, response.json())+ self.assertIn("consumer_view", str(response.json()))++ 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.+ from products.data_warehouse.backend.presentation.views.saved_query import (+ DataWarehouseSavedQueryMinimalSerializer,+ )++ self.assertNotIn("sync_frequency_bounds", DataWarehouseSavedQueryMinimalSerializer().fields)+def _create_saved_query(self) -> dict:response = self.client.post(f"/api/environments/{self.team.id}/warehouse_saved_queries/",diff --git a/products/data_warehouse/backend/tests/api/test_saved_query_access_control.py b/products/data_warehouse/backend/tests/api/test_saved_query_access_control.pyindex 54274d93b29d..f34b4aee5d72 100644--- a/products/data_warehouse/backend/tests/api/test_saved_query_access_control.py+++ b/products/data_warehouse/backend/tests/api/test_saved_query_access_control.py@@ -1,3 +1,5 @@+from datetime import timedelta+import pytestfrom unittest.mock import Mock, patch@@ -7,9 +9,16 @@ from rest_framework import statusfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.user import User-from products.data_modeling.backend.facade.models import DAG, DataWarehouseSavedQuery, Node, NodeType+from products.data_modeling.backend.facade.models import DAG, DataWarehouseSavedQuery, Edge, Node, NodeType+from products.data_modeling.backend.logic.node_frequency import set_declared_targetfrom products.data_tools.backend.models.datawarehouse_saved_query_folder import DataWarehouseSavedQueryFolder-from products.warehouse_sources.backend.facade.models import DataWarehouseCredential, DataWarehouseTable+from products.warehouse_sources.backend.facade.models import (+ DataWarehouseCredential,+ DataWarehouseTable,+ ExternalDataSchema,+ ExternalDataSource,+)+from products.warehouse_sources.backend.facade.types import ExternalDataSourceTypefrom products.warehouse_sources.backend.tests.api._access_control_base import WarehouseAccessControlTestMixintry:@@ -374,3 +383,317 @@ class TestMaterializationRequiresUnderlyingAccess(WarehouseAccessControlTestMixiresponse = self.client.post(f"{self._base()}/materialize/")self.assertNotEqual(response.status_code, status.HTTP_403_FORBIDDEN)+++class TestSyncFrequencyBoundsAccessControl(WarehouseAccessControlTestMixin):+ """The cadence bounds name what blocks a cadence, so they answer to the same grants the rest does."""++ resource = "warehouse_objects"++ def setUp(self):+ super().setUp()+ self.upstream = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="upstream_view",+ query={"kind": "HogQLQuery", "query": "select 1 as event"},+ created_by=self.user,+ )+ self.consumer = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="consumer_view",+ query={"kind": "HogQLQuery", "query": "select event from upstream_view"},+ created_by=self.user,+ )+ dag = DAG.objects.create(team=self.team, name="dag")+ self.upstream_node = Node.objects.create(+ team=self.team, dag=dag, name=self.upstream.name, saved_query=self.upstream, type=NodeType.VIEW+ )+ self.consumer_node = Node.objects.create(+ team=self.team, dag=dag, name=self.consumer.name, saved_query=self.consumer, type=NodeType.VIEW+ )+ Edge.objects.create(team=self.team, dag=dag, source=self.upstream_node, target=self.consumer_node)+ set_declared_target(self.consumer_node, timedelta(hours=6))++ def _tiered(self):+ return (+ patch(+ "products.data_warehouse.backend.presentation.views.saved_query.posthoganalytics.feature_enabled",+ side_effect=lambda key, *args, **kwargs: key == "data-modeling-backend-v2",+ ),+ patch(+ "products.data_modeling.backend.logic.schedule_reconcile.tiered_schedules_enabled",+ return_value=True,+ ),+ )++ def _read_upstream(self) -> tuple[dict, str]:+ v2, tiered = self._tiered()+ with v2, tiered:+ response = self.client.get(f"/api/environments/{self.team.pk}/warehouse_saved_queries/{self.upstream.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ return response.json()["sync_frequency_bounds"], response.content.decode()++ def _deny_the_consumer(self, user):+ self._create_access_control(+ user, resource="warehouse_view", resource_id=str(self.consumer.id), access_level="none"+ )++ def test_a_denied_consumer_sets_the_bound_without_being_named(self):+ self._create_access_control(self.viewer_user, access_level="viewer")+ self._deny_the_consumer(self.viewer_user)+ self.client.force_login(self.viewer_user)++ bounds, body = self._read_upstream()++ # The bound itself survives: the caller still learns 24hour is out, and that a consumer did it.+ self.assertEqual(bounds["ceiling"]["label"], "6 hours")+ self.assertIsNone(bounds["ceiling"]["blocker"])+ blocked = {option["cadence"]: option for option in bounds["options"] if not option["allowed"]}+ self.assertEqual(blocked["24hour"]["blocked_by"], "consumer")+ self.assertIsNone(blocked["24hour"]["blocker"])+ # Neither the name nor the node id reaches the wire.+ self.assertNotIn("consumer_view", body)+ self.assertNotIn(str(self.consumer_node.id), body)++ def test_the_same_consumer_is_named_for_a_caller_who_may_read_it(self):+ self._create_access_control(self.viewer_user, access_level="viewer")+ self.client.force_login(self.viewer_user)++ bounds, body = self._read_upstream()++ self.assertEqual(bounds["ceiling"]["blocker"]["name"], "consumer_view")+ self.assertEqual(bounds["ceiling"]["blocker"]["id"], str(self.consumer_node.id))+ self.assertIn("consumer_view", body)++ def test_a_refused_cadence_withholds_the_name_the_read_withheld(self):+ self._create_access_control(self.editor_user, access_level="editor")+ self._deny_the_consumer(self.editor_user)+ self.client.force_login(self.editor_user)++ v2, tiered = self._tiered()+ with v2, tiered, patch("products.data_modeling.backend.logic.schedule_reconcile.maybe_reconcile_dag"):+ response = self.client.patch(+ f"/api/environments/{self.team.pk}/warehouse_saved_queries/{self.upstream.id}/",+ {"sync_frequency": "24hour"},+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)+ detail = response.content.decode()+ self.assertNotIn("consumer_view", detail)+ self.assertIn("6 hours", detail)++ def test_a_refused_cadence_names_the_consumer_for_a_caller_who_may_read_it(self):+ self._create_access_control(self.editor_user, access_level="editor")+ self.client.force_login(self.editor_user)++ v2, tiered = self._tiered()+ with v2, tiered, patch("products.data_modeling.backend.logic.schedule_reconcile.maybe_reconcile_dag"):+ response = self.client.patch(+ f"/api/environments/{self.team.pk}/warehouse_saved_queries/{self.upstream.id}/",+ {"sync_frequency": "24hour"},+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)+ self.assertIn("consumer_view", response.content.decode())++ def test_a_refusal_names_nothing_when_the_caller_passes_no_visible_names(self):+ """The default the endpoints API depends on: `schedule_materialization` re-raises this+ refusal and the endpoints materialization view returns its text verbatim, with no per-user+ name map to hand down. Naming by default there would leak past every grant."""+ from products.data_modeling.backend.facade.api import (+ UnsatisfiableFrequencyError,+ apply_saved_query_frequency_target,+ )++ with patch("products.data_modeling.backend.logic.schedule_reconcile.maybe_reconcile_dag"):+ with self.assertRaises(UnsatisfiableFrequencyError) as caught:+ apply_saved_query_frequency_target(self.upstream, timedelta(days=1))++ message = str(caught.exception)+ self.assertNotIn("consumer_view", message)+ self.assertNotIn(str(self.consumer_node.id), message)+ # Still actionable: it names the cadence to pick instead, just not who withheld the other.+ self.assertIn("6 hours", message)+++class TestSyncFrequencyTableBlockerAccessControl(WarehouseAccessControlTestMixin):+ """A source table sets the floor, and is named only for a caller who may read the table itself."""++ resource = "warehouse_objects"++ def setUp(self):+ super().setUp()+ self.view = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="downstream_view",+ query={"kind": "HogQLQuery", "query": "select 1 as event"},+ created_by=self.user,+ )+ self.source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="source_id",+ connection_id="connection_id",+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.STRIPE,+ prefix="posthog_test_",+ )+ # The FK, not just the schema link: it is what `warehouse_table` falls back through, and+ # what the import pipeline sets on a real imported table.+ self.table = DataWarehouseTable.objects.create(+ name="stripe_charges", team=self.team, external_data_source=self.source+ )+ ExternalDataSchema.objects.create(+ name="stripe_charges",+ team=self.team,+ source=self.source,+ table=self.table,+ sync_frequency_interval=timedelta(hours=6),+ )+ dag = DAG.objects.create(team=self.team, name="dag")+ source_node = Node.objects.create(+ team=self.team,+ dag=dag,+ name="stripe_charges",+ type=NodeType.TABLE,+ properties={"origin": "warehouse", "warehouse_table_id": str(self.table.id)},+ )+ self.view_node = Node.objects.create(+ team=self.team, dag=dag, name=self.view.name, saved_query=self.view, type=NodeType.VIEW+ )+ Edge.objects.create(team=self.team, dag=dag, source=source_node, target=self.view_node)++ def _read_view(self) -> tuple[dict, str]:+ with (+ patch(+ "products.data_warehouse.backend.presentation.views.saved_query.posthoganalytics.feature_enabled",+ side_effect=lambda key, *args, **kwargs: key == "data-modeling-backend-v2",+ ),+ patch(+ "products.data_modeling.backend.logic.schedule_reconcile.tiered_schedules_enabled",+ return_value=True,+ ),+ ):+ response = self.client.get(f"/api/environments/{self.team.pk}/warehouse_saved_queries/{self.view.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ return response.json()["sync_frequency_bounds"], response.content.decode()++ def test_the_source_table_is_named_for_a_caller_who_may_read_it(self):+ self._create_access_control(self.viewer_user, access_level="viewer")+ self.client.force_login(self.viewer_user)++ bounds, body = self._read_view()++ self.assertEqual(bounds["floor"]["label"], "6 hours")+ self.assertEqual(bounds["floor"]["blocker"]["name"], "stripe_charges")+ self.assertIn("stripe_charges", body)++ @parameterized.expand(+ [+ # Denying the table itself, and denying the source it came from: `warehouse_table` falls+ # back to `external_data_source`, so a deny on the source has to withhold the name too.+ ("table_denied", "warehouse_table"),+ ("source_denied", "external_data_source"),+ ]+ )+ def test_a_denied_source_table_sets_the_floor_without_being_named(self, _name, resource):+ self._create_access_control(self.viewer_user, access_level="viewer")+ self._create_access_control(+ self.viewer_user,+ resource=resource,+ resource_id=str(self.table.id if resource == "warehouse_table" else self.source.id),+ access_level="none",+ )+ self.client.force_login(self.viewer_user)++ bounds, body = self._read_view()++ # The floor still applies and still says a source set it. Only the identity is withheld.+ self.assertEqual(bounds["floor"]["label"], "6 hours")+ self.assertIsNone(bounds["floor"]["blocker"])+ blocked = {option["cadence"]: option for option in bounds["options"] if not option["allowed"]}+ self.assertEqual(blocked["15min"]["blocked_by"], "source")+ self.assertIsNone(blocked["15min"]["blocker"])+ self.assertNotIn("stripe_charges", body)+++class TestSyncFrequencyDuplicateResourceAcrossDags(WarehouseAccessControlTestMixin):+ """A grant covers a resource, not a node: a table holding a node in two DAGs is named in both."""++ resource = "warehouse_objects"++ def setUp(self):+ super().setUp()+ self.view = DataWarehouseSavedQuery.objects.create(+ team=self.team,+ name="downstream_view",+ query={"kind": "HogQLQuery", "query": "select 1 as event"},+ created_by=self.user,+ )+ self.source = ExternalDataSource.objects.create(+ team=self.team,+ source_id="source_id",+ connection_id="connection_id",+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.STRIPE,+ prefix="posthog_test_",+ )+ # Deliberately no schema: a source with no sync schedule is what lands in best-effort, and+ # best-effort ids union across DAGs. That union is the one place a single resource reaches+ # the payload under two node ids.+ self.table = DataWarehouseTable.objects.create(+ name="unscheduled_source", team=self.team, external_data_source=self.source+ )+ for dag_name in ("dag_one", "dag_two"):+ dag = DAG.objects.create(team=self.team, name=dag_name)+ source_node = Node.objects.create(+ team=self.team,+ dag=dag,+ name="unscheduled_source",+ type=NodeType.TABLE,+ properties={"origin": "warehouse", "warehouse_table_id": str(self.table.id)},+ )+ view_node = Node.objects.create(+ team=self.team, dag=dag, name=self.view.name, saved_query=self.view, type=NodeType.VIEW+ )+ Edge.objects.create(team=self.team, dag=dag, source=source_node, target=view_node)++ def _read_view(self) -> dict:+ with (+ patch(+ "products.data_warehouse.backend.presentation.views.saved_query.posthoganalytics.feature_enabled",+ side_effect=lambda key, *args, **kwargs: key == "data-modeling-backend-v2",+ ),+ patch(+ "products.data_modeling.backend.logic.schedule_reconcile.tiered_schedules_enabled",+ return_value=True,+ ),+ ):+ response = self.client.get(f"/api/environments/{self.team.pk}/warehouse_saved_queries/{self.view.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)+ return response.json()["sync_frequency_bounds"]++ def test_a_readable_table_is_named_through_every_dag_that_holds_a_node_for_it(self):+ self._create_access_control(self.viewer_user, access_level="viewer")+ self.client.force_login(self.viewer_user)++ bounds = self._read_view()++ self.assertTrue(bounds["best_effort_sources"], "the unscheduled source should reach the payload")+ self.assertTrue(all(source["name"] == "unscheduled_source" for source in bounds["best_effort_sources"]))+ # The caller may read the only table involved, so nothing is cut and the copy says so.+ self.assertFalse(bounds["best_effort_sources_withheld"])++ def test_a_denied_table_stays_withheld_through_every_dag(self):+ self._create_access_control(self.viewer_user, access_level="viewer")+ self._create_access_control(+ self.viewer_user, resource="warehouse_table", resource_id=str(self.table.id), access_level="none"+ )+ self.client.force_login(self.viewer_user)++ bounds = self._read_view()++ self.assertTrue(bounds["best_effort_sources_withheld"])+ self.assertEqual(bounds["best_effort_sources"], [])diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.tsindex 5b15be3deabd..7d2e18f65ce2 100644--- a/products/data_warehouse/frontend/generated/api.schemas.ts+++ b/products/data_warehouse/frontend/generated/api.schemas.ts@@ -1074,6 +1074,120 @@ export const SavedQuerySyncFrequencyEnumApi = {'30day': '30day',} as const+/**+ * * `tiered` - tiered+ * * `dag_schedule` - dag_schedule+ * * `managed_viewset` - managed_viewset+ * * `legacy` - legacy+ * * `no_node` - no_node+ */+export type FrequencyModeEnumApi = (typeof FrequencyModeEnumApi)[keyof typeof FrequencyModeEnumApi]++export const FrequencyModeEnumApi = {+ Tiered: 'tiered',+ DagSchedule: 'dag_schedule',+ ManagedViewset: 'managed_viewset',+ Legacy: 'legacy',+ NoNode: 'no_node',+} as const++/**+ * * `15min` - 15min+ * * `30min` - 30min+ * * `1hour` - 1hour+ * * `6hour` - 6hour+ * * `12hour` - 12hour+ * * `24hour` - 24hour+ * * `7day` - 7day+ * * `30day` - 30day+ */+export type MaterializeSyncFrequencyEnumApi =+ (typeof MaterializeSyncFrequencyEnumApi)[keyof typeof MaterializeSyncFrequencyEnumApi]++export const MaterializeSyncFrequencyEnumApi = {+ '15min': '15min',+ '30min': '30min',+ '1hour': '1hour',+ '6hour': '6hour',+ '12hour': '12hour',+ '24hour': '24hour',+ '7day': '7day',+ '30day': '30day',+} as const++/**+ * * `source` - source+ * * `consumer` - consumer+ */+export type SyncFrequencyBlockedByEnumApi =+ (typeof SyncFrequencyBlockedByEnumApi)[keyof typeof SyncFrequencyBlockedByEnumApi]++export const SyncFrequencyBlockedByEnumApi = {+ Source: 'source',+ Consumer: 'consumer',+} as const++/**+ * The node holding a cadence back, named so a refusal points at something a person can open.+ */+export interface SyncFrequencyBlockerApi {+ /** Data modeling node ID of the source or view. */+ id: string+ /** Node name, as it appears in the data modeling graph. */+ name: string+}++export interface SyncFrequencyOptionApi {+ /** A `sync_frequency` value.+ *+ * * `15min` - 15min+ * * `30min` - 30min+ * * `1hour` - 1hour+ * * `6hour` - 6hour+ * * `12hour` - 12hour+ * * `24hour` - 24hour+ * * `7day` - 7day+ * * `30day` - 30day */+ cadence: MaterializeSyncFrequencyEnumApi+ /** False when writing this cadence would be rejected. */+ allowed: boolean+ /** Which side withholds this cadence: 'source' when no upstream source syncs that often, 'consumer' when a downstream view or endpoint refreshes more often than this. Null when the cadence is allowed.+ *+ * * `source` - source+ * * `consumer` - consumer */+ 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+}++export interface SyncFrequencyBoundApi {+ /** The bounding cadence in plain English, for example '6 hours'. Matches the wording used in the error raised when an out-of-bounds cadence is written. Prose rather than a `sync_frequency` value because a source can deliver on a cadence no `sync_frequency` names. */+ label: string+ /** Node that set this bound. Null when nothing identifiable set it, and also when it sits outside the caller's access grants: the bound still applies, it just goes unnamed. */+ blocker: SyncFrequencyBlockerApi | null+}++export interface SyncFrequencyBoundsApi {+ /** What governs this view's cadence. 'tiered' is the only mode where `options` is meaningful and `sync_frequency` is writable per view. 'dag_schedule' means the team's single DAG schedule owns it, 'managed_viewset' means PostHog owns the view, 'legacy' means the v1 backend, where any cadence is accepted and no bounds apply, and 'no_node' means the view has no data modeling node to store a cadence on.+ *+ * * `tiered` - tiered+ * * `dag_schedule` - dag_schedule+ * * `managed_viewset` - managed_viewset+ * * `legacy` - legacy+ * * `no_node` - no_node */+ frequency_mode: FrequencyModeEnumApi+ /** Every cadence a picker may show, coarsest-last, each marked allowed or blocked with its cause. Empty outside 'tiered' mode. */+ options: SyncFrequencyOptionApi[]+ /** The fastest bound: no cadence finer than this is allowed, because the source named here does not sync more often. Null when no source withholds a cadence. */+ floor: SyncFrequencyBoundApi | null+ /** The slowest bound: no cadence coarser than this is allowed, because the consumer named here refreshes that often. Null when no consumer withholds a cadence. */+ ceiling: SyncFrequencyBoundApi | null+ /** Upstream sources with no sync schedule, so the floor is a guess: these arrive when someone runs them, and refreshing more often than they really sync will serve stale data. Only sources the caller may read are listed. */+ best_effort_sources: SyncFrequencyBlockerApi[]+ /** True when at least one such source sits outside the caller's access grants, so the list above is incomplete and the caveat still applies. */+ best_effort_sources_withheld: boolean+}+/*** Shared methods for DataWarehouseSavedQuery serializers.*@@ -1111,6 +1225,8 @@ export interface DataWarehouseSavedQueryApi {sync_frequency?: SavedQuerySyncFrequencyEnumApi | null/** True when this team's DAG owns the materialization cadence through a single schedule, so `sync_frequency` cannot be set per view and writes to it are rejected. False when per-node DAG schedules are in use or the team is on the v1 backend. False does not on its own mean the cadence is writable: a view belonging to a managed viewset rejects every update regardless, which `managed_viewset_kind` reports. */readonly sync_frequency_managed_by_dag: boolean+ /** Which cadences this view can actually be set to, and what withholds the rest. Computed from the view's data modeling lineage: upstream source sync frequencies set a floor, downstream cadences set a ceiling. Read-only, and present on retrieve, create and update responses only. */+ readonly sync_frequency_bounds: SyncFrequencyBoundsApireadonly columns: readonly DataWarehouseSavedQueryApiColumnsItem[]/** The status of when this SavedQuery last ran.*@@ -1236,6 +1352,8 @@ export interface PatchedDataWarehouseSavedQueryApi {sync_frequency?: SavedQuerySyncFrequencyEnumApi | null/** True when this team's DAG owns the materialization cadence through a single schedule, so `sync_frequency` cannot be set per view and writes to it are rejected. False when per-node DAG schedules are in use or the team is on the v1 backend. False does not on its own mean the cadence is writable: a view belonging to a managed viewset rejects every update regardless, which `managed_viewset_kind` reports. */readonly sync_frequency_managed_by_dag?: boolean+ /** Which cadences this view can actually be set to, and what withholds the rest. Computed from the view's data modeling lineage: upstream source sync frequencies set a floor, downstream cadences set a ceiling. Read-only, and present on retrieve, create and update responses only. */+ readonly sync_frequency_bounds?: SyncFrequencyBoundsApireadonly columns?: readonly PatchedDataWarehouseSavedQueryApiColumnsItem[]/** The status of when this SavedQuery last ran.*@@ -1302,30 +1420,6 @@ export interface PatchedDataWarehouseSavedQueryApi {readonly suspended?: PatchedDataWarehouseSavedQueryApiSuspended}-/**- * * `15min` - 15min- * * `30min` - 30min- * * `1hour` - 1hour- * * `6hour` - 6hour- * * `12hour` - 12hour- * * `24hour` - 24hour- * * `7day` - 7day- * * `30day` - 30day- */-export type SavedQueryMaterializeSyncFrequencyEnumApi =- (typeof SavedQueryMaterializeSyncFrequencyEnumApi)[keyof typeof SavedQueryMaterializeSyncFrequencyEnumApi]--export const SavedQueryMaterializeSyncFrequencyEnumApi = {- '15min': '15min',- '30min': '30min',- '1hour': '1hour',- '6hour': '6hour',- '12hour': '12hour',- '24hour': '24hour',- '7day': '7day',- '30day': '30day',-} as const-/*** Body of the `materialize` action: which cadence to enable materialization at.*/@@ -1340,7 +1434,7 @@ export interface SavedQueryMaterializeApi {* * `24hour` - 24hour* * `7day` - 7day* * `30day` - 30day */- sync_frequency?: SavedQueryMaterializeSyncFrequencyEnumApi+ sync_frequency?: MaterializeSyncFrequencyEnumApi}export interface SavedQueryResumeApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 6e44e247b221..d4c4eb20ce75 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -19272,6 +19272,121 @@ export namespace Schemas {'30day': '30day',} as const;+ /**+ * * `tiered` - tiered+ * * `dag_schedule` - dag_schedule+ * * `managed_viewset` - managed_viewset+ * * `legacy` - legacy+ * * `no_node` - no_node+ */+ export type FrequencyModeEnum = typeof FrequencyModeEnum[keyof typeof FrequencyModeEnum];+++ export const FrequencyModeEnum = {+ Tiered: 'tiered',+ DagSchedule: 'dag_schedule',+ ManagedViewset: 'managed_viewset',+ Legacy: 'legacy',+ NoNode: 'no_node',+ } as const;++ /**+ * * `15min` - 15min+ * * `30min` - 30min+ * * `1hour` - 1hour+ * * `6hour` - 6hour+ * * `12hour` - 12hour+ * * `24hour` - 24hour+ * * `7day` - 7day+ * * `30day` - 30day+ */+ export type MaterializeSyncFrequencyEnum = typeof MaterializeSyncFrequencyEnum[keyof typeof MaterializeSyncFrequencyEnum];+++ export const MaterializeSyncFrequencyEnum = {+ '15min': '15min',+ '30min': '30min',+ '1hour': '1hour',+ '6hour': '6hour',+ '12hour': '12hour',+ '24hour': '24hour',+ '7day': '7day',+ '30day': '30day',+ } as const;++ /**+ * * `source` - source+ * * `consumer` - consumer+ */+ export type SyncFrequencyBlockedByEnum = typeof SyncFrequencyBlockedByEnum[keyof typeof SyncFrequencyBlockedByEnum];+++ export const SyncFrequencyBlockedByEnum = {+ Source: 'source',+ Consumer: 'consumer',+ } as const;++ /**+ * The node holding a cadence back, named so a refusal points at something a person can open.+ */+ export interface SyncFrequencyBlocker {+ /** Data modeling node ID of the source or view. */+ id: string;+ /** Node name, as it appears in the data modeling graph. */+ name: string;+ }++ export interface SyncFrequencyOption {+ /** A `sync_frequency` value.+ *+ * * `15min` - 15min+ * * `30min` - 30min+ * * `1hour` - 1hour+ * * `6hour` - 6hour+ * * `12hour` - 12hour+ * * `24hour` - 24hour+ * * `7day` - 7day+ * * `30day` - 30day */+ cadence: MaterializeSyncFrequencyEnum;+ /** False when writing this cadence would be rejected. */+ allowed: boolean;+ /** Which side withholds this cadence: 'source' when no upstream source syncs that often, 'consumer' when a downstream view or endpoint refreshes more often than this. Null when the cadence is allowed.+ *+ * * `source` - source+ * * `consumer` - consumer */+ 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;+ }++ export interface SyncFrequencyBound {+ /** The bounding cadence in plain English, for example '6 hours'. Matches the wording used in the error raised when an out-of-bounds cadence is written. Prose rather than a `sync_frequency` value because a source can deliver on a cadence no `sync_frequency` names. */+ label: string;+ /** Node that set this bound. Null when nothing identifiable set it, and also when it sits outside the caller's access grants: the bound still applies, it just goes unnamed. */+ blocker: SyncFrequencyBlocker | null;+ }++ export interface SyncFrequencyBounds {+ /** What governs this view's cadence. 'tiered' is the only mode where `options` is meaningful and `sync_frequency` is writable per view. 'dag_schedule' means the team's single DAG schedule owns it, 'managed_viewset' means PostHog owns the view, 'legacy' means the v1 backend, where any cadence is accepted and no bounds apply, and 'no_node' means the view has no data modeling node to store a cadence on.+ *+ * * `tiered` - tiered+ * * `dag_schedule` - dag_schedule+ * * `managed_viewset` - managed_viewset+ * * `legacy` - legacy+ * * `no_node` - no_node */+ frequency_mode: FrequencyModeEnum;+ /** Every cadence a picker may show, coarsest-last, each marked allowed or blocked with its cause. Empty outside 'tiered' mode. */+ options: SyncFrequencyOption[];+ /** The fastest bound: no cadence finer than this is allowed, because the source named here does not sync more often. Null when no source withholds a cadence. */+ floor: SyncFrequencyBound | null;+ /** The slowest bound: no cadence coarser than this is allowed, because the consumer named here refreshes that often. Null when no consumer withholds a cadence. */+ ceiling: SyncFrequencyBound | null;+ /** Upstream sources with no sync schedule, so the floor is a guess: these arrive when someone runs them, and refreshing more often than they really sync will serve stale data. Only sources the caller may read are listed. */+ best_effort_sources: SyncFrequencyBlocker[];+ /** True when at least one such source sits outside the caller's access grants, so the list above is incomplete and the caveat still applies. */+ best_effort_sources_withheld: boolean;+ }+/*** * `Cancelled` - Cancelled* * `Modified` - Modified@@ -19341,6 +19456,8 @@ export namespace Schemas {sync_frequency?: SavedQuerySyncFrequencyEnum | null;/** True when this team's DAG owns the materialization cadence through a single schedule, so `sync_frequency` cannot be set per view and writes to it are rejected. False when per-node DAG schedules are in use or the team is on the v1 backend. False does not on its own mean the cadence is writable: a view belonging to a managed viewset rejects every update regardless, which `managed_viewset_kind` reports. */readonly sync_frequency_managed_by_dag: boolean;+ /** Which cadences this view can actually be set to, and what withholds the rest. Computed from the view's data modeling lineage: upstream source sync frequencies set a floor, downstream cadences set a ceiling. Read-only, and present on retrieve, create and update responses only. */+ readonly sync_frequency_bounds: SyncFrequencyBounds;readonly columns: readonly DataWarehouseSavedQueryColumnsItem[];/** The status of when this SavedQuery last ran.*@@ -54373,6 +54490,8 @@ export namespace Schemas {sync_frequency?: SavedQuerySyncFrequencyEnum | null;/** True when this team's DAG owns the materialization cadence through a single schedule, so `sync_frequency` cannot be set per view and writes to it are rejected. False when per-node DAG schedules are in use or the team is on the v1 backend. False does not on its own mean the cadence is writable: a view belonging to a managed viewset rejects every update regardless, which `managed_viewset_kind` reports. */readonly sync_frequency_managed_by_dag?: boolean;+ /** Which cadences this view can actually be set to, and what withholds the rest. Computed from the view's data modeling lineage: upstream source sync frequencies set a floor, downstream cadences set a ceiling. Read-only, and present on retrieve, create and update responses only. */+ readonly sync_frequency_bounds?: SyncFrequencyBounds;readonly columns?: readonly PatchedDataWarehouseSavedQueryColumnsItem[];/** The status of when this SavedQuery last ran.*@@ -68502,30 +68621,6 @@ export namespace Schemas {block_consent_modals?: boolean;}- /**- * * `15min` - 15min- * * `30min` - 30min- * * `1hour` - 1hour- * * `6hour` - 6hour- * * `12hour` - 12hour- * * `24hour` - 24hour- * * `7day` - 7day- * * `30day` - 30day- */- export type SavedQueryMaterializeSyncFrequencyEnum = typeof SavedQueryMaterializeSyncFrequencyEnum[keyof typeof SavedQueryMaterializeSyncFrequencyEnum];--- export const SavedQueryMaterializeSyncFrequencyEnum = {- '15min': '15min',- '30min': '30min',- '1hour': '1hour',- '6hour': '6hour',- '12hour': '12hour',- '24hour': '24hour',- '7day': '7day',- '30day': '30day',- } as const;-/*** Body of the `materialize` action: which cadence to enable materialization at.*/@@ -68540,7 +68635,7 @@ export namespace Schemas {* * `24hour` - 24hour* * `7day` - 7day* * `30day` - 30day */- sync_frequency?: SavedQueryMaterializeSyncFrequencyEnum;+ sync_frequency?: MaterializeSyncFrequencyEnum;}export interface SavedQueryResume {