11import { dbReplica , runOutsideTransactionContext } from '@sim/db'
2- import { workflow , workflowActivityHourly , workspace } from '@sim/db/schema'
2+ import { activityRollupDirty , workflow , workflowActivityHourly , workspace } from '@sim/db/schema'
33import { createLogger } from '@sim/logger'
44import { type SQL , sql } from 'drizzle-orm'
55import {
@@ -54,8 +54,9 @@ export interface RollupReadPlan {
5454
5555/**
5656 * Splits `window` between the rollup and the source, or returns null when the rollup must not
57- * serve it at all: another version's cells, no coverage yet, a stalled pass, or a window reaching
58- * before a backfill that is still running. Once the backfill is complete, instants before the
57+ * serve it at all: another version's cells, no coverage yet, a stalled pass, correction queues
58+ * (dirty marks and in-flight rechecks) that no pass has run lately, or a window reaching before a
59+ * backfill that is still running. Once the backfill is complete, instants before the
5960 * coverage hold no runs and are read live at the cost of an index probe per workspace.
6061 */
6162export function planRollupRead (
@@ -66,7 +67,8 @@ export function planRollupRead(
6667 if ( ! state || state . version !== ACTIVITY_ROLLUP_VERSION ) return null
6768 const { coverageStart, freshThrough } = state
6869 if ( ! coverageStart || ! freshThrough ) return null
69- if ( now . getTime ( ) - freshThrough . getTime ( ) >= MAX_FRESHNESS_LAG_MS ) return null
70+ const lagging = ( at : Date | null ) => ! at || now . getTime ( ) - at . getTime ( ) >= MAX_FRESHNESS_LAG_MS
71+ if ( lagging ( freshThrough ) || lagging ( state . correctionsAt ) ) return null
7072 if ( window . from < coverageStart && ! state . backfillCompletedAt ) return null
7173
7274 const from = new Date ( Math . max ( ceilHour ( window . from ) . getTime ( ) , coverageStart . getTime ( ) ) )
@@ -117,6 +119,19 @@ function storedCells(scope: ActivityScope, span: InstantRange): SQL {
117119 ${ scope . workspaceId ? sql `AND w.id = ${ scope . workspaceId } ` : sql `` } `
118120}
119121
122+ /**
123+ * The rollup hours of the scope's workspaces that have a pending dirty mark, as `h`: their cells
124+ * are known to be stale until the mark is processed (or while it backs off after failing), so
125+ * reads take those hours live. Read per workspace on the mark queue's key, in the read's snapshot.
126+ */
127+ function markedHours ( scope : ActivityScope , span : InstantRange ) : SQL {
128+ return sql `SELECT DISTINCT d.bucket_start AS h FROM ${ workspace } w
129+ JOIN ${ activityRollupDirty } d ON d.workspace_id = w.id
130+ AND d.bucket_start >= ${ utcTimestamp ( span . from ) } AND d.bucket_start < ${ utcTimestamp ( span . to ) }
131+ WHERE w.organization_id = ${ scope . organizationId }
132+ ${ scope . workspaceId ? sql `AND w.id = ${ scope . workspaceId } ` : sql `` } `
133+ }
134+
120135type DayRow = Record < string , unknown > & {
121136 day : string
122137 runs : string | number
@@ -141,13 +156,15 @@ async function readWorkflowDays(
141156) : Promise < [ string , ActivityStretch ] [ ] > {
142157 const local = ( instant : SQL ) => sql `((${ instant } ) AT TIME ZONE 'UTC') AT TIME ZONE ${ timezone } `
143158 const day = ( instant : SQL ) => sql `to_char(date_trunc('day', ${ local ( instant ) } ), 'YYYY-MM-DD')`
144- const last = sql `h + interval '1 hour' - interval '1 microsecond'`
159+ /** Parenthesized: it is subtracted below, where `- h + …` would change the arithmetic. */
160+ const last = sql `(h + interval '1 hour' - interval '1 microsecond')`
145161 const span = plan . rollup
146162 const straddles = span
147163 ? sql `SELECT h FROM generate_series(${ utcTimestamp ( span . from ) } ,
148164 ${ utcTimestamp ( new Date ( span . to . getTime ( ) - HOUR_MS ) ) } , interval '1 hour') AS h
149165 WHERE date_trunc('day', ${ local ( sql `h` ) } ) <> date_trunc('day', ${ local ( last ) } )
150- OR ${ local ( sql `h` ) } - h <> ${ local ( last ) } - ${ last } `
166+ OR ${ local ( sql `h` ) } - h <> ${ local ( last ) } - ${ last }
167+ UNION ${ markedHours ( scope , span ) } `
151168 : sql `SELECT NULL::timestamp AS h WHERE false`
152169 const live = sql `SELECT ${ day ( sql `a.started_at` ) } AS day, ${ workflowRunCounters }
153170 FROM (${ organizationWorkflowRuns ( scope , sql `SELECT * FROM live_ranges` ) } ) a
@@ -227,14 +244,20 @@ async function timedChatDays(
227244
228245/**
229246 * Workflow runs of the window as breakdown cells: stored cells summed over the rollup span, and
230- * the live edges, each keyed by workspace, workflow, and trigger. A stored cell's workflow is
231- * looked up now, so one deleted since the cell was computed reads as deleted, as its runs do.
247+ * the live edges and marked hours (see {@link markedHours}), each keyed by workspace, workflow, and
248+ * trigger. A stored cell's workflow is looked up now, so one deleted since the cell was computed
249+ * reads as deleted, as its runs do.
232250 */
233251function workflowCells ( scope : ActivityScope , plan : RollupReadPlan , resolveWorkflow : boolean ) {
234- const live = sql `SELECT a.workspace_id, a.workflow_id, a.trigger, ${ workflowRunCounters }
235- FROM (${ organizationWorkflowRuns ( scope , rangeRows ( plan . live ) ) } ) a
252+ const liveCells = ( ranges : SQL ) => sql `SELECT a.workspace_id, a.workflow_id, a.trigger,
253+ ${ workflowRunCounters }
254+ FROM (${ organizationWorkflowRuns ( scope , ranges ) } ) a
236255 GROUP BY 1, 2, 3`
237- if ( ! plan . rollup ) return live
256+ if ( ! plan . rollup ) return liveCells ( rangeRows ( plan . live ) )
257+ const marked = markedHours ( scope , plan . rollup )
258+ const live = liveCells (
259+ sql `${ rangeRows ( plan . live ) } UNION ALL SELECT m.h, m.h + interval '1 hour' FROM (${ marked } ) m`
260+ )
238261 const workflowId = resolveWorkflow
239262 ? sql `(SELECT f.id FROM ${ workflow } f WHERE f.id = nullif(r.workflow_id, ''))`
240263 : sql `NULL::text`
@@ -247,6 +270,7 @@ function workflowCells(scope: ActivityScope, plan: RollupReadPlan, resolveWorkfl
247270 sum(r.in_flight) AS in_flight, sum(r.duration_sum_ms) AS duration_sum_ms,
248271 sum(r.duration_count) AS duration_count
249272 FROM ${ storedCells ( scope , plan . rollup ) }
273+ AND NOT EXISTS (SELECT 1 FROM (${ marked } ) m WHERE m.h = r.bucket_start)
250274 GROUP BY 1, 2, 3
251275 ) r
252276 UNION ALL ${ live } `
0 commit comments