11import { db , dbReplica } from '@sim/db'
2- import { activityRollupInflight , workflowActivityHourly , workspace } from '@sim/db/schema'
2+ import {
3+ activityRollupInflight ,
4+ workflowActivityHourly ,
5+ workflowExecutionLogs ,
6+ } from '@sim/db/schema'
37import { createLogger } from '@sim/logger'
48import { getPostgresCancellationReason } from '@sim/utils/errors'
9+ import { chunkArray } from '@sim/utils/helpers'
510import { sql } from 'drizzle-orm'
611import {
712 HOUR_MS ,
@@ -108,13 +113,17 @@ function sumCells(parts: ActivityCell[][]): ActivityCell[] {
108113 return [ ...byKey . values ( ) ]
109114}
110115
111- /** Workspaces read per statement once a slice is too heavy to read at once. */
112- const WORKSPACE_PAGE = 500
116+ /** Distinct workspaces with runs a page walks, and how many of them one statement aggregates. */
117+ const WORKSPACE_WALK = 1000
118+ const WORKSPACE_CHUNK = 100
113119
114120/** Reads of an hour's runs, from the whole span down to one page of workspaces at a time. */
115121export interface HourReaders {
116122 span : ( range : InstantRange ) => Promise < ActivityCell [ ] >
117- /** The cells of up to a page of workspaces after `after` (by id), and the last one read. */
123+ /**
124+ * The cells of the next page of workspaces with runs in `range`, after `after` (by id), and the
125+ * last workspace the page walked, or null once every workspace with runs was walked.
126+ */
118127 workspacePage : (
119128 range : InstantRange ,
120129 after : string | null
@@ -129,6 +138,14 @@ export class HeavyHourError extends Error {
129138 }
130139}
131140
141+ /** The pass ran out of budget while paging an hour: not a sign the hour is too heavy. */
142+ export class PassDeadlineError extends Error {
143+ constructor ( hour : Date ) {
144+ super ( `Activity rollup pass budget ran out while paging hour ${ hour . toISOString ( ) } ` )
145+ this . name = 'PassDeadlineError'
146+ }
147+ }
148+
132149/** Whether a read gave up on its own statement bound, or the replica cancelled it for recovery. */
133150function isBoundedCancellation ( error : unknown ) : boolean {
134151 const reason = getPostgresCancellationReason ( error )
@@ -146,81 +163,109 @@ function onReplica<T>(read: (tx: DbTransaction) => Promise<T>): Promise<T> {
146163 )
147164}
148165
166+ /**
167+ * The next workspaces that have any run, after `after`, by a bounded loose index scan on the
168+ * activity index (one descent per workspace, never a scan of runs), each with whether it has runs
169+ * in `range` (one more descent: a LATERAL `LIMIT 1`, which the planner cannot turn into a hashed
170+ * scan of the whole range).
171+ */
172+ async function walkWorkspaces (
173+ tx : DbTransaction ,
174+ range : InstantRange ,
175+ after : string | null
176+ ) : Promise < { id : string ; active : number } [ ] > {
177+ return tx . execute < { id : string ; active : number } > ( sql `
178+ WITH RECURSIVE walk AS (
179+ (SELECT l.workspace_id AS id, 1 AS n FROM ${ workflowExecutionLogs } l
180+ ${ after === null ? sql `` : sql `WHERE l.workspace_id > ${ after } ` }
181+ ORDER BY l.workspace_id LIMIT 1)
182+ UNION ALL
183+ SELECT (
184+ SELECT l.workspace_id FROM ${ workflowExecutionLogs } l
185+ WHERE l.workspace_id > walk.id ORDER BY l.workspace_id LIMIT 1
186+ ), walk.n + 1
187+ FROM walk WHERE walk.id IS NOT NULL AND walk.n < ${ WORKSPACE_WALK }
188+ )
189+ SELECT walk.id, (hit.found IS NOT NULL)::int AS active
190+ FROM walk
191+ LEFT JOIN LATERAL (
192+ SELECT 1 AS found FROM ${ workflowExecutionLogs } l
193+ WHERE l.workspace_id = walk.id
194+ AND l.started_at >= ${ utcTimestamp ( range . from ) } AND l.started_at < ${ utcTimestamp ( range . to ) }
195+ LIMIT 1
196+ ) hit ON true
197+ WHERE walk.id IS NOT NULL
198+ ` )
199+ }
200+
149201const replicaReaders : HourReaders = {
150202 span : ( range ) => onReplica ( ( tx ) => aggregateRange ( tx , range ) ) ,
151203 workspacePage : ( range , after ) =>
152204 onReplica ( async ( tx ) => {
153- const page = await tx . execute < { id : string } > ( sql `
154- SELECT id FROM ${ workspace } ${ after === null ? sql `` : sql `WHERE id > ${ after } ` }
155- ORDER BY id LIMIT ${ WORKSPACE_PAGE }
156- ` )
157- const ids = page . map ( ( { id } ) => id )
158- if ( ids . length === 0 ) return { cells : [ ] , last : null }
159- const cells = await aggregateRange ( tx , range , ids )
160- return { cells, last : ids . length < WORKSPACE_PAGE ? null : ( ids . at ( - 1 ) ?? null ) }
205+ const walked = await walkWorkspaces ( tx , range , after )
206+ const active = walked . filter ( ( row ) => Number ( row . active ) === 1 ) . map ( ( row ) => row . id )
207+ /** Chunks hold different workspaces, so their cells never share a key. */
208+ const cells : ActivityCell [ ] = [ ]
209+ for ( const chunk of chunkArray ( active , WORKSPACE_CHUNK ) ) {
210+ cells . push ( ...( await aggregateRange ( tx , range , chunk ) ) )
211+ }
212+ const last = walked . length < WORKSPACE_WALK ? null : ( walked . at ( - 1 ) ?. id ?? null )
213+ return { cells, last }
161214 } ) ,
162215}
163216
164217/**
165218 * Every cell of one UTC hour, read on the replica, at the coarsest grain that fits the statement
166219 * bounds. A span that times out (or that the replica cancels for recovery) is read again in
167- * quarter-hour slices, and a slice that still does is read a page of workspaces at a time, each on
168- * the workspace activity index. All of these count exactly the same runs, so their cells are
169- * summed. Throws {@link HeavyHourError} when even a page of workspaces cannot be read, or the
170- * pass's `deadline` passes while paging.
220+ * quarter-hour slices; once a slice still does, the rest of the hour is read once, a page of
221+ * workspaces with runs at a time, each on the workspace activity index. All of these count exactly
222+ * the same runs, so their cells are summed. Throws {@link HeavyHourError} when even a page cannot
223+ * be read, and { @link PassDeadlineError} when `deadline` passes while paging.
171224 */
172225export async function aggregateHour (
173226 hour : Date ,
174227 deadline : number ,
175228 {
176229 readers = replicaReaders ,
177- byWorkspace : startByWorkspace = false ,
230+ byWorkspace = false ,
178231 } : {
179232 readers ?: HourReaders
180- /** Skips straight to workspace pages: a retry of an hour already known to be too heavy . */
233+ /** Skips straight to workspace pages: a retry of an hour a previous pass had to page . */
181234 byWorkspace ?: boolean
182235 } = { }
183236) : Promise < ActivityCell [ ] > {
184- if ( ! startByWorkspace ) {
185- try {
186- return await readers . span ( { from : hour , to : new Date ( hour . getTime ( ) + HOUR_MS ) } )
187- } catch ( error ) {
188- if ( ! isBoundedCancellation ( error ) ) throw error
189- logger . warn ( 'Activity rollup hour read in slices' , {
190- hour : hour . toISOString ( ) ,
191- reason : getPostgresCancellationReason ( error ) ,
192- } )
193- }
237+ const hourEnd = new Date ( hour . getTime ( ) + HOUR_MS )
238+ const wholeHour = { from : hour , to : hourEnd }
239+ if ( byWorkspace ) return readByWorkspace ( hour , wholeHour , deadline , readers )
240+ try {
241+ return await readers . span ( wholeHour )
242+ } catch ( error ) {
243+ if ( ! isBoundedCancellation ( error ) ) throw error
244+ logger . warn ( 'Activity rollup hour read in slices' , {
245+ hour : hour . toISOString ( ) ,
246+ reason : getPostgresCancellationReason ( error ) ,
247+ } )
194248 }
195249 const sliceMs = HOUR_MS / SLICES_PER_HOUR
196250 const parts : ActivityCell [ ] [ ] = [ ]
197- // Once one slice needs workspace pages, later slices skip the span read bound to fail.
198- let byWorkspace = startByWorkspace
199251 for ( let slice = 0 ; slice < SLICES_PER_HOUR ; slice ++ ) {
200252 const from = new Date ( hour . getTime ( ) + slice * sliceMs )
201- const range = { from, to : new Date ( from . getTime ( ) + sliceMs ) }
202- if ( ! byWorkspace ) {
203- try {
204- parts . push ( await readers . span ( range ) )
205- continue
206- } catch ( error ) {
207- if ( ! isBoundedCancellation ( error ) ) throw error
208- logger . warn ( 'Activity rollup slice read by workspace' , {
209- from : from . toISOString ( ) ,
210- reason : getPostgresCancellationReason ( error ) ,
211- } )
212- byWorkspace = true
213- }
253+ try {
254+ parts . push ( await readers . span ( { from, to : new Date ( from . getTime ( ) + sliceMs ) } ) )
255+ } catch ( error ) {
256+ if ( ! isBoundedCancellation ( error ) ) throw error
257+ logger . warn ( 'Activity rollup hour read by workspace' , {
258+ from : from . toISOString ( ) ,
259+ reason : getPostgresCancellationReason ( error ) ,
260+ } )
261+ parts . push ( await readByWorkspace ( hour , { from, to : hourEnd } , deadline , readers ) )
262+ break
214263 }
215- parts . push ( await readByWorkspace ( hour , range , deadline , readers ) )
216264 }
217265 return sumCells ( parts )
218266}
219267
220- /**
221- * Reads a slice a page of workspaces at a time. Gives the hour up as too heavy when a page still
222- * times out, or when the pass's budget runs out first, so a heavy hour never outlives the lease.
223- */
268+ /** Reads `range` a page of workspaces with runs at a time. */
224269async function readByWorkspace (
225270 hour : Date ,
226271 range : InstantRange ,
@@ -230,9 +275,7 @@ async function readByWorkspace(
230275 const parts : ActivityCell [ ] [ ] = [ ]
231276 let after : string | null = null
232277 for ( ; ; ) {
233- if ( Date . now ( ) >= deadline ) {
234- throw new HeavyHourError ( hour , { cause : new Error ( 'Pass budget ran out' ) } )
235- }
278+ if ( Date . now ( ) >= deadline ) throw new PassDeadlineError ( hour )
236279 try {
237280 const page = await readers . workspacePage ( range , after )
238281 parts . push ( page . cells )
0 commit comments