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,17 +113,23 @@ 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), the
125+ * workspace the next page starts after, and whether every workspace with runs was read. A page
126+ * stops early, before an aggregate, once `deadline` passes.
127+ */
118128 workspacePage : (
119129 range : InstantRange ,
120- after : string | null
121- ) => Promise < { cells : ActivityCell [ ] ; last : string | null } >
130+ after : string | null ,
131+ deadline : number
132+ ) => Promise < { cells : ActivityCell [ ] ; last : string | null ; done : boolean } >
122133}
123134
124135/** An hour that could not be read within the statement bounds, even a page of workspaces at a time. */
@@ -129,6 +140,14 @@ export class HeavyHourError extends Error {
129140 }
130141}
131142
143+ /** The pass ran out of budget while paging an hour: not a sign the hour is too heavy. */
144+ export class PassDeadlineError extends Error {
145+ constructor ( hour : Date ) {
146+ super ( `Activity rollup pass budget ran out while paging hour ${ hour . toISOString ( ) } ` )
147+ this . name = 'PassDeadlineError'
148+ }
149+ }
150+
132151/** Whether a read gave up on its own statement bound, or the replica cancelled it for recovery. */
133152function isBoundedCancellation ( error : unknown ) : boolean {
134153 const reason = getPostgresCancellationReason ( error )
@@ -146,81 +165,112 @@ function onReplica<T>(read: (tx: DbTransaction) => Promise<T>): Promise<T> {
146165 )
147166}
148167
168+ /**
169+ * The next workspaces that have any run, after `after`, by a bounded loose index scan on the
170+ * activity index (one descent per workspace, never a scan of runs), each with whether it has runs
171+ * in `range` (one more descent: a LATERAL `LIMIT 1`, which the planner cannot turn into a hashed
172+ * scan of the whole range).
173+ */
174+ async function walkWorkspaces (
175+ tx : DbTransaction ,
176+ range : InstantRange ,
177+ after : string | null
178+ ) : Promise < { id : string ; active : number } [ ] > {
179+ return tx . execute < { id : string ; active : number } > ( sql `
180+ WITH RECURSIVE walk AS (
181+ (SELECT l.workspace_id AS id, 1 AS n FROM ${ workflowExecutionLogs } l
182+ ${ after === null ? sql `` : sql `WHERE l.workspace_id > ${ after } ` }
183+ ORDER BY l.workspace_id LIMIT 1)
184+ UNION ALL
185+ SELECT (
186+ SELECT l.workspace_id FROM ${ workflowExecutionLogs } l
187+ WHERE l.workspace_id > walk.id ORDER BY l.workspace_id LIMIT 1
188+ ), walk.n + 1
189+ FROM walk WHERE walk.id IS NOT NULL AND walk.n < ${ WORKSPACE_WALK }
190+ )
191+ SELECT walk.id, (hit.found IS NOT NULL)::int AS active
192+ FROM walk
193+ LEFT JOIN LATERAL (
194+ SELECT 1 AS found FROM ${ workflowExecutionLogs } l
195+ WHERE l.workspace_id = walk.id
196+ AND l.started_at >= ${ utcTimestamp ( range . from ) } AND l.started_at < ${ utcTimestamp ( range . to ) }
197+ LIMIT 1
198+ ) hit ON true
199+ WHERE walk.id IS NOT NULL
200+ ` )
201+ }
202+
149203const replicaReaders : HourReaders = {
150204 span : ( range ) => onReplica ( ( tx ) => aggregateRange ( tx , range ) ) ,
151- workspacePage : ( range , after ) =>
205+ workspacePage : ( range , after , deadline ) =>
152206 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 ) }
207+ const walked = await walkWorkspaces ( tx , range , after )
208+ const active = walked . filter ( ( row ) => Number ( row . active ) === 1 ) . map ( ( row ) => row . id )
209+ /** Chunks hold different workspaces, so their cells never share a key. */
210+ const cells : ActivityCell [ ] = [ ]
211+ let last = after
212+ for ( const chunk of chunkArray ( active , WORKSPACE_CHUNK ) ) {
213+ if ( Date . now ( ) >= deadline ) return { cells, last, done : false }
214+ cells . push ( ...( await aggregateRange ( tx , range , chunk ) ) )
215+ last = chunk . at ( - 1 ) ?? last
216+ }
217+ const done = walked . length < WORKSPACE_WALK
218+ return { cells, last : done ? null : ( walked . at ( - 1 ) ?. id ?? null ) , done }
161219 } ) ,
162220}
163221
164222/**
165223 * Every cell of one UTC hour, read on the replica, at the coarsest grain that fits the statement
166224 * 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.
225+ * quarter-hour slices; once a slice still does, the rest of the hour is read once, a page of
226+ * workspaces with runs at a time, each on the workspace activity index. All of these count exactly
227+ * the same runs, so their cells are summed. Throws {@link HeavyHourError} when even a page cannot
228+ * be read, and { @link PassDeadlineError} when `deadline` passes while paging.
171229 */
172230export async function aggregateHour (
173231 hour : Date ,
174232 deadline : number ,
175233 {
176234 readers = replicaReaders ,
177- byWorkspace : startByWorkspace = false ,
235+ byWorkspace = false ,
178236 } : {
179237 readers ?: HourReaders
180- /** Skips straight to workspace pages: a retry of an hour already known to be too heavy . */
238+ /** Skips straight to workspace pages: a retry of an hour a previous pass had to page . */
181239 byWorkspace ?: boolean
182240 } = { }
183241) : 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- }
242+ const hourEnd = new Date ( hour . getTime ( ) + HOUR_MS )
243+ const wholeHour = { from : hour , to : hourEnd }
244+ if ( byWorkspace ) return readByWorkspace ( hour , wholeHour , deadline , readers )
245+ try {
246+ return await readers . span ( wholeHour )
247+ } catch ( error ) {
248+ if ( ! isBoundedCancellation ( error ) ) throw error
249+ logger . warn ( 'Activity rollup hour read in slices' , {
250+ hour : hour . toISOString ( ) ,
251+ reason : getPostgresCancellationReason ( error ) ,
252+ } )
194253 }
195254 const sliceMs = HOUR_MS / SLICES_PER_HOUR
196255 const parts : ActivityCell [ ] [ ] = [ ]
197- // Once one slice needs workspace pages, later slices skip the span read bound to fail.
198- let byWorkspace = startByWorkspace
199256 for ( let slice = 0 ; slice < SLICES_PER_HOUR ; slice ++ ) {
200257 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- }
258+ try {
259+ parts . push ( await readers . span ( { from, to : new Date ( from . getTime ( ) + sliceMs ) } ) )
260+ } catch ( error ) {
261+ if ( ! isBoundedCancellation ( error ) ) throw error
262+ logger . warn ( 'Activity rollup hour read by workspace' , {
263+ from : from . toISOString ( ) ,
264+ reason : getPostgresCancellationReason ( error ) ,
265+ } )
266+ parts . push ( await readByWorkspace ( hour , { from, to : hourEnd } , deadline , readers ) )
267+ break
214268 }
215- parts . push ( await readByWorkspace ( hour , range , deadline , readers ) )
216269 }
217270 return sumCells ( parts )
218271}
219272
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- */
273+ /** Reads `range` a page of workspaces with runs at a time. */
224274async function readByWorkspace (
225275 hour : Date ,
226276 range : InstantRange ,
@@ -230,13 +280,11 @@ async function readByWorkspace(
230280 const parts : ActivityCell [ ] [ ] = [ ]
231281 let after : string | null = null
232282 for ( ; ; ) {
233- if ( Date . now ( ) >= deadline ) {
234- throw new HeavyHourError ( hour , { cause : new Error ( 'Pass budget ran out' ) } )
235- }
283+ if ( Date . now ( ) >= deadline ) throw new PassDeadlineError ( hour )
236284 try {
237- const page = await readers . workspacePage ( range , after )
285+ const page = await readers . workspacePage ( range , after , deadline )
238286 parts . push ( page . cells )
239- if ( page . last === null ) return sumCells ( parts )
287+ if ( page . done ) return sumCells ( parts )
240288 after = page . last
241289 } catch ( error ) {
242290 throw isBoundedCancellation ( error ) ? new HeavyHourError ( hour , { cause : error } ) : error
0 commit comments