Skip to content

Commit 27a73ac

Browse files
authored
fix(usage): page heavy rollup hours once over active workspaces (#10203)
1 parent 8052750 commit 27a73ac

13 files changed

Lines changed: 34793 additions & 235 deletions

‎apps/sim/lib/billing/activity-rollup/cells.test.ts‎

Lines changed: 28 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@ import { describe, expect, it, vi } from 'vitest'
22
import {
33
type ActivityCell,
44
aggregateHour,
5-
HeavyHourError,
65
type HourReaders,
6+
PassDeadlineError,
77
} from '@/lib/billing/activity-rollup/cells'
88
import type { InstantRange } from '@/lib/billing/activity-rollup/source'
99

@@ -76,52 +76,65 @@ describe('aggregateHour', () => {
7676
}
7777
)
7878

79-
it('reads a slice that still times out a page of workspaces at a time', async () => {
79+
it('pages the rest of the hour once after a slice times out, not slice by slice', async () => {
8080
const span = vi.fn(async (range: InstantRange) => {
81-
if (isWholeHour(range) || quarter(range) === 3) throw timeout()
81+
if (isWholeHour(range) || quarter(range) === 1) throw timeout()
8282
return [cell('a', 1, 5)]
8383
})
8484
const workspacePage = vi.fn(async (_range: InstantRange, after: string | null) =>
8585
after === null
86-
? { cells: [cell('a', 2, 7)], last: 'ws-500' }
87-
: { cells: [cell('b', 1, 1)], last: null }
86+
? { cells: [cell('a', 2, 7)], last: 'ws-500', done: false }
87+
: { cells: [cell('b', 1, 1)], last: null, done: true }
8888
)
8989

9090
const cells = await aggregateHour(hour, Number.POSITIVE_INFINITY, {
9191
readers: readers({ span, workspacePage }),
9292
})
9393

94-
expect(workspacePage.mock.calls.map(([range, after]) => [quarter(range), after])).toEqual([
95-
[3, null],
96-
[3, 'ws-500'],
94+
expect(
95+
span.mock.calls.map(([range]) => (isWholeHour(range) ? 'hour' : quarter(range)))
96+
).toEqual(['hour', 0, 1])
97+
expect(
98+
workspacePage.mock.calls.map(([range, after]) => [
99+
range.from.toISOString(),
100+
range.to.toISOString(),
101+
after,
102+
])
103+
).toEqual([
104+
['2026-05-01T10:15:00.000Z', '2026-05-01T11:00:00.000Z', null],
105+
['2026-05-01T10:15:00.000Z', '2026-05-01T11:00:00.000Z', 'ws-500'],
97106
])
98-
expect(cells).toEqual([cell('a', 5, 22), cell('b', 1, 1)])
107+
expect(cells).toEqual([cell('a', 3, 12), cell('b', 1, 1)])
99108
})
100109

101-
it('gives the hour up as too heavy rather than page workspaces past the pass budget', async () => {
110+
it('gives up before paging once the pass budget has run out, without calling the hour heavy', async () => {
102111
const span = vi.fn(async () => {
103112
throw timeout()
104113
})
105-
const workspacePage = vi.fn(async () => ({ cells: [], last: null }))
114+
const workspacePage = vi.fn(async () => ({ cells: [], last: null, done: true }))
106115

107116
await expect(
108117
aggregateHour(hour, Date.now() - 1, { readers: readers({ span, workspacePage }) })
109-
).rejects.toBeInstanceOf(HeavyHourError)
118+
).rejects.toBeInstanceOf(PassDeadlineError)
110119
expect(workspacePage).not.toHaveBeenCalled()
111120
})
112121

113122
it('retries an hour known to be too heavy a page of workspaces at a time from the start', async () => {
114123
const span = vi.fn(async () => [cell('a', 9, 9)])
115-
const workspacePage = vi.fn(async () => ({ cells: [cell('a', 1, 2)], last: null }))
124+
const workspacePage = vi.fn(async (_range: InstantRange) => ({
125+
cells: [cell('a', 1, 2)],
126+
last: null,
127+
done: true,
128+
}))
116129

117130
const cells = await aggregateHour(hour, Number.POSITIVE_INFINITY, {
118131
readers: readers({ span, workspacePage }),
119132
byWorkspace: true,
120133
})
121134

122135
expect(span).not.toHaveBeenCalled()
123-
expect(workspacePage).toHaveBeenCalledTimes(4)
124-
expect(cells).toEqual([cell('a', 4, 8)])
136+
expect(workspacePage.mock.calls.map(([range]) => isWholeHour(range))).toEqual([true])
137+
expect(cells).toEqual([cell('a', 1, 2)])
125138
})
126139

127140
it('fails without slicing when the read fails for any other reason', async () => {

‎apps/sim/lib/billing/activity-rollup/cells.ts‎

Lines changed: 104 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
import { 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'
37
import { createLogger } from '@sim/logger'
48
import { getPostgresCancellationReason } from '@sim/utils/errors'
9+
import { chunkArray } from '@sim/utils/helpers'
510
import { sql } from 'drizzle-orm'
611
import {
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. */
115121
export 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. */
133152
function 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+
149203
const 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
*/
172230
export 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. */
224274
async 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

Comments
 (0)