Skip to content

Commit 503fff1

Browse files
committed
fix(usage): defer budget-cut hours without backoff, check the deadline per aggregate, renew the heartbeat by the database clock
1 parent 05e09d7 commit 503fff1

5 files changed

Lines changed: 93 additions & 34 deletions

File tree

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

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,8 @@ describe('aggregateHour', () => {
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, {
@@ -111,7 +111,7 @@ describe('aggregateHour', () => {
111111
const span = vi.fn(async () => {
112112
throw timeout()
113113
})
114-
const workspacePage = vi.fn(async () => ({ cells: [], last: null }))
114+
const workspacePage = vi.fn(async () => ({ cells: [], last: null, done: true }))
115115

116116
await expect(
117117
aggregateHour(hour, Date.now() - 1, { readers: readers({ span, workspacePage }) })
@@ -121,7 +121,11 @@ describe('aggregateHour', () => {
121121

122122
it('retries an hour known to be too heavy a page of workspaces at a time from the start', async () => {
123123
const span = vi.fn(async () => [cell('a', 9, 9)])
124-
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+
}))
125129

126130
const cells = await aggregateHour(hour, Number.POSITIVE_INFINITY, {
127131
readers: readers({ span, workspacePage }),

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

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -121,13 +121,15 @@ const WORKSPACE_CHUNK = 100
121121
export interface HourReaders {
122122
span: (range: InstantRange) => Promise<ActivityCell[]>
123123
/**
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.
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.
126127
*/
127128
workspacePage: (
128129
range: InstantRange,
129-
after: string | null
130-
) => Promise<{ cells: ActivityCell[]; last: string | null }>
130+
after: string | null,
131+
deadline: number
132+
) => Promise<{ cells: ActivityCell[]; last: string | null; done: boolean }>
131133
}
132134

133135
/** An hour that could not be read within the statement bounds, even a page of workspaces at a time. */
@@ -200,17 +202,20 @@ async function walkWorkspaces(
200202

201203
const replicaReaders: HourReaders = {
202204
span: (range) => onReplica((tx) => aggregateRange(tx, range)),
203-
workspacePage: (range, after) =>
205+
workspacePage: (range, after, deadline) =>
204206
onReplica(async (tx) => {
205207
const walked = await walkWorkspaces(tx, range, after)
206208
const active = walked.filter((row) => Number(row.active) === 1).map((row) => row.id)
207209
/** Chunks hold different workspaces, so their cells never share a key. */
208210
const cells: ActivityCell[] = []
211+
let last = after
209212
for (const chunk of chunkArray(active, WORKSPACE_CHUNK)) {
213+
if (Date.now() >= deadline) return { cells, last, done: false }
210214
cells.push(...(await aggregateRange(tx, range, chunk)))
215+
last = chunk.at(-1) ?? last
211216
}
212-
const last = walked.length < WORKSPACE_WALK ? null : (walked.at(-1)?.id ?? null)
213-
return { cells, last }
217+
const done = walked.length < WORKSPACE_WALK
218+
return { cells, last: done ? null : (walked.at(-1)?.id ?? null), done }
214219
}),
215220
}
216221

@@ -277,9 +282,9 @@ async function readByWorkspace(
277282
for (;;) {
278283
if (Date.now() >= deadline) throw new PassDeadlineError(hour)
279284
try {
280-
const page = await readers.workspacePage(range, after)
285+
const page = await readers.workspacePage(range, after, deadline)
281286
parts.push(page.cells)
282-
if (page.last === null) return sumCells(parts)
287+
if (page.done) return sumCells(parts)
283288
after = page.last
284289
} catch (error) {
285290
throw isBoundedCancellation(error) ? new HeavyHourError(hour, { cause: error }) : error

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

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,8 @@ import {
4444
type ActivityRollupState,
4545
acquireLease,
4646
extendLease,
47-
MAINTENANCE_GAP_MS,
4847
readRollupState,
48+
refreshHeartbeat,
4949
releaseLease,
5050
resetRollup,
5151
truncateRollupBatch,
@@ -196,9 +196,12 @@ async function computeHour(
196196
.from(activityRollupBlocked)
197197
.where(eq(activityRollupBlocked.bucketStart, hour))
198198
if (block && block.retryAt.getTime() > Date.now()) return { state: null, runs: 0 }
199+
/** An hour a pass ran out of budget paging: paged from the start, with no backoff or attempt. */
200+
const deferred = block?.attempts === 0
201+
const retry = block !== undefined && !deferred
199202
let retryBudgetMs = 0
200203
let retryInMs: number | undefined
201-
if (block) {
204+
if (retry) {
202205
/**
203206
* The retry's backoff is committed before it starts, so a retry that crashes or loses its
204207
* lease is not tried again until the backoff passes.
@@ -210,11 +213,11 @@ async function computeHour(
210213
}
211214
let cells: ActivityCell[]
212215
try {
213-
cells = await aggregateHour(hour, block ? Date.now() + retryBudgetMs : deadline, {
214-
byWorkspace: Boolean(block),
216+
cells = await aggregateHour(hour, retry ? Date.now() + retryBudgetMs : deadline, {
217+
byWorkspace: block !== undefined,
215218
})
216219
} catch (error) {
217-
if (error instanceof PassDeadlineError && !block) {
220+
if (error instanceof PassDeadlineError && !retry) {
218221
await deferPaging(hour)
219222
return { state: null, runs: 0 }
220223
}
@@ -478,18 +481,14 @@ async function runHousekeeping(
478481
}
479482

480483
/**
481-
* Why the rollup must start over, or null: a pass on newer code; coverage with an end missing
482-
* (cleared by hand to force a rebuild, or never started); or a maintenance gap, no pass past its reset
483-
* decision within {@link MAINTENANCE_GAP_MS}, during which writers stopped marking the deletes and reopened
484-
* runs the cells would need. Read from the state alone, so a pass that fails before its reset
485-
* commits leaves the next pass the same reason.
484+
* Why the rollup must start over regardless of its heartbeat, or null: a pass on newer code, or
485+
* coverage with an end missing (cleared by hand to force a rebuild, or never started). A maintenance
486+
* gap (see {@link refreshHeartbeat}) is the third reason. Read from the state alone, so a pass that
487+
* fails before its reset commits leaves the next pass the same reason.
486488
*/
487489
function resetReason(state: ActivityRollupState): ActivityRollupPassResult['reset'] {
488490
if (state.version < ACTIVITY_ROLLUP_VERSION) return 'version'
489491
if (!state.coverageStart || !state.freshThrough) return 'coverage'
490-
if (!state.maintainedAt || Date.now() - state.maintainedAt.getTime() > MAINTENANCE_GAP_MS) {
491-
return 'maintenance-gap'
492-
}
493492
return null
494493
}
495494

@@ -539,6 +538,19 @@ export async function runActivityRollupPass(
539538

540539
const settledThrough = new Date(floorHour(now()).getTime() - ACTIVITY_ROLLUP_SETTLE_MS)
541540
result.reset = resetReason(state)
541+
if (!result.reset) {
542+
/**
543+
* A pass at this version that got past its reset decision is maintaining the rollup: marks
544+
* written from now on will be consumed by it or the next. A step failing later loses no mark
545+
* (marks persist until a recompute removes them), so the heartbeat does not wait on the
546+
* steps, and a failure is counted and logged instead of forcing rebuilds every gap. The
547+
* heartbeat is renewed only if it has not expired by the database's clock, which writers
548+
* mark by; an expired one means marks may have been skipped, so the rollup is rebuilt.
549+
*/
550+
const refreshed = await refreshHeartbeat(owner)
551+
if (refreshed) state = refreshed
552+
else result.reset = 'maintenance-gap'
553+
}
542554
if (result.reset) {
543555
if (state.coverageStart || result.reset !== 'coverage') {
544556
logger.warn('Activity rollup starting over', { reason: result.reset })
@@ -548,14 +560,6 @@ export async function runActivityRollupPass(
548560
if (Date.now() >= deadline) return { ...result, status: 'truncating' }
549561
}
550562
state = await startCoverage(owner, settledThrough, lateEndMarginMs)
551-
} else {
552-
/**
553-
* A pass at this version that got past its reset decision is maintaining the rollup: marks
554-
* written from now on will be consumed by it or the next. A step failing later loses no mark
555-
* (marks persist until a recompute removes them), so the heartbeat does not wait on the
556-
* steps, and a failure is counted and logged instead of forcing rebuilds every gap.
557-
*/
558-
state = await updateLeasedState(owner, { maintainedAt: sql`now()` })
559563
}
560564

561565
result.lateEndMarks = await captureLateEnds(deadline, {

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

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,31 @@ export async function updateLeasedState(
118118
return state
119119
}
120120

121+
/**
122+
* Moves the maintenance heartbeat to now only if it is still within the gap by the database's
123+
* clock, the clock writers use to decide whether to mark, in the same statement. Null means it had
124+
* expired (writers may already have skipped marks), so the caller must rebuild instead of renewing
125+
* it. Throws when the lease is gone.
126+
*/
127+
export async function refreshHeartbeat(owner: string): Promise<ActivityRollupState | null> {
128+
const [state] = await db
129+
.update(activityRollupState)
130+
.set({ maintainedAt: sql`now()`, updatedAt: sql`now()` })
131+
.where(
132+
and(
133+
eq(activityRollupState.id, WORKFLOW_ROLLUP_ID),
134+
eq(activityRollupState.leaseOwner, owner),
135+
gt(activityRollupState.leaseExpiresAt, sql`now()`),
136+
gt(activityRollupState.maintainedAt, sql`now() - ${msInterval(MAINTENANCE_GAP_MS)}`)
137+
)
138+
)
139+
.returning()
140+
if (state) return state
141+
const current = await readRollupState()
142+
if (current?.leaseOwner !== owner) throw new Error('Activity rollup lease lost')
143+
return null
144+
}
145+
121146
/**
122147
* Pushes the lease out to cover work that may run past the pass's budget (a retry of an hour too
123148
* heavy to read), while `owner` still holds it.

‎apps/sim/lib/billing/core/organization-activity-rollup.integration.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -805,6 +805,19 @@ describe('organization activity rollup', () => {
805805
await expectEquivalent()
806806
}, 300_000)
807807

808+
it('judges the maintenance gap by the database clock, not a worker clock behind it', async () => {
809+
await connection.unsafe(
810+
`UPDATE activity_rollup_state SET maintained_at = now() - interval '6 hours 10 minutes'`
811+
)
812+
vi.useFakeTimers({ toFake: ['Date'], now: Date.now() - 60 * 60 * 1000 })
813+
try {
814+
expect((await runPass(new Date())).reset).toBe('maintenance-gap')
815+
} finally {
816+
vi.useRealTimers()
817+
}
818+
await expectEquivalent()
819+
}, 300_000)
820+
808821
it('keeps the heartbeat through a failing step and counts the failures instead of rebuilding', async () => {
809822
const state = await readRollupState()
810823
if (!state?.freshThrough) throw new Error('No coverage')
@@ -849,6 +862,14 @@ describe('organization activity rollup', () => {
849862
} finally {
850863
await ungateHour()
851864
}
865+
// Paging it again is not a retry: a pass that dies paging it counts no attempt.
866+
await gateHour(hour, `RAISE EXCEPTION 'Synthetic connection loss';`)
867+
try {
868+
await expect(runPass()).rejects.toThrow()
869+
expect(await blockedAttempts(hour)).toBe(0)
870+
} finally {
871+
await ungateHour()
872+
}
852873
expect(await runPass()).toMatchObject({ finalizedHours: 1, blockedHours: 0 })
853874
await expectEquivalent()
854875
}, 300_000)

0 commit comments

Comments
 (0)