Skip to content

Commit 05e09d7

Browse files
committed
fix(usage): page heavy rollup hours once over active workspaces
1 parent 8052750 commit 05e09d7

10 files changed

Lines changed: 34273 additions & 154 deletions

File tree

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

Lines changed: 20 additions & 11 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,9 +76,9 @@ 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) =>
@@ -91,22 +91,31 @@ describe('aggregateHour', () => {
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
})
105114
const workspacePage = vi.fn(async () => ({ cells: [], last: null }))
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

@@ -120,8 +129,8 @@ describe('aggregateHour', () => {
120129
})
121130

122131
expect(span).not.toHaveBeenCalled()
123-
expect(workspacePage).toHaveBeenCalledTimes(4)
124-
expect(cells).toEqual([cell('a', 4, 8)])
132+
expect(workspacePage.mock.calls.map(([range]) => isWholeHour(range))).toEqual([true])
133+
expect(cells).toEqual([cell('a', 1, 2)])
125134
})
126135

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

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

Lines changed: 94 additions & 51 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,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. */
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), 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. */
133150
function 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+
149201
const 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
*/
172225
export 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. */
224269
async 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

Comments
 (0)