Skip to content

Commit 4aa6272

Browse files
committed
fix(usage): isolate failing correction cells, read marked hours live, gate reads on drained queues, and fix the summary straddle test
1 parent 041e036 commit 4aa6272

10 files changed

Lines changed: 290 additions & 65 deletions

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

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@ import { activityRollupDirty, activityRollupState, workflowExecutionLogs } from
33
import { createLogger } from '@sim/logger'
44
import { getErrorMessage } from '@sim/utils/errors'
55
import { lt, sql } from 'drizzle-orm'
6-
import { boundedTransaction, recomputeCell } from '@/lib/billing/activity-rollup/cells'
6+
import {
7+
boundedTransaction,
8+
inflightBackoffMs,
9+
recomputeCell,
10+
} from '@/lib/billing/activity-rollup/cells'
711
import { floorHour, msInterval, utcTimestamp } from '@/lib/billing/activity-rollup/source'
812
import {
913
type ActivityRollupState,
@@ -151,9 +155,14 @@ export async function processDirtyMarks(
151155
await db.delete(activityRollupDirty).where(lt(activityRollupDirty.bucketStart, coverageStart))
152156
}
153157
// `due_at` is read as text: a JS `Date` would drop the microseconds the guard compares.
154-
const marks = await db.execute<{ workspaceId: string; bucketMs: number; seen: string }>(sql`
158+
const marks = await db.execute<{
159+
workspaceId: string
160+
bucketMs: number
161+
seen: string
162+
attempts: number
163+
}>(sql`
155164
SELECT workspace_id AS "workspaceId", (extract(epoch FROM bucket_start) * 1000)::float8 AS "bucketMs",
156-
due_at::text AS seen
165+
due_at::text AS seen, attempts
157166
FROM ${activityRollupDirty}
158167
WHERE due_at <= now()
159168
AND bucket_start >= ${utcTimestamp(coverageStart)} AND bucket_start < ${utcTimestamp(freshThrough)}
@@ -164,14 +173,28 @@ export async function processDirtyMarks(
164173
for (const mark of marks) {
165174
if (Date.now() >= deadline) break
166175
const hour = new Date(Number(mark.bucketMs))
167-
await recomputeCell(mark.workspaceId, hour, async (tx) => {
168-
await tx.execute(sql`
169-
DELETE FROM ${activityRollupDirty}
170-
WHERE workspace_id = ${mark.workspaceId} AND bucket_start = ${utcTimestamp(hour)}
171-
AND due_at = ${mark.seen}::timestamptz
176+
const key = sql`workspace_id = ${mark.workspaceId} AND bucket_start = ${utcTimestamp(hour)}
177+
AND due_at = ${mark.seen}::timestamptz`
178+
try {
179+
await recomputeCell(mark.workspaceId, hour, async (tx) => {
180+
await tx.execute(sql`DELETE FROM ${activityRollupDirty} WHERE ${key}`)
181+
})
182+
processed++
183+
} catch (error) {
184+
// Retried with backoff so the rest of the queue proceeds; reads serve the hour live meanwhile.
185+
const attempts = Number(mark.attempts) + 1
186+
logger.error('Activity rollup dirty cell failed to recompute; backing off', {
187+
workspaceId: mark.workspaceId,
188+
hour: hour.toISOString(),
189+
attempts,
190+
error: getErrorMessage(error),
191+
})
192+
await db.execute(sql`
193+
UPDATE ${activityRollupDirty}
194+
SET attempts = ${attempts}, due_at = now() + ${msInterval(inflightBackoffMs(attempts - 1))}
195+
WHERE ${key}
172196
`)
173-
})
174-
processed++
197+
}
175198
}
176199
return processed
177200
}

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

Lines changed: 56 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -138,9 +138,16 @@ function startCoverage(
138138
freshThrough: settledThrough,
139139
lastEndScan: sql`(now() AT TIME ZONE 'UTC') - ${msInterval(marginMs)}`,
140140
maintainedAt: sql`now()`,
141+
correctionsAt: sql`now()`,
141142
})
142143
}
143144

145+
/**
146+
* Once this many passes in a row have failed, a deferred hour counts as a retry, so a pass that
147+
* keeps crashing while paging it backs it off instead of starting it again every tick.
148+
*/
149+
const CRASHING_PASSES = 3
150+
144151
/** How long a retry of an hour too heavy to read may page through workspaces. */
145152
const HEAVY_RETRY_MS = 2 * 60 * 1000
146153
/** A retry's budget grows with its attempts up to this, still inside the task's duration. */
@@ -183,6 +190,7 @@ async function deferPaging(hour: Date): Promise<void> {
183190
*/
184191
async function computeHour(
185192
owner: string,
193+
failedPasses: number,
186194
hour: Date,
187195
deadline: number,
188196
write: (
@@ -204,7 +212,7 @@ async function computeHour(
204212
* pass that dies paging it does not start it again at once. A deferred hour that runs out of its
205213
* own budget too is heavy after all, and is backed off from then on.
206214
*/
207-
const deferred = block?.attempts === 0
215+
const deferred = block?.attempts === 0 && failedPasses < CRASHING_PASSES
208216
let budgetMs = 0
209217
let retryInMs: number | undefined
210218
if (block) {
@@ -266,10 +274,15 @@ async function finalizeSettledHours(
266274
let current = state
267275
while (current.freshThrough && current.freshThrough < settledThrough && Date.now() < deadline) {
268276
const hour = current.freshThrough
269-
const computed = await computeHour(owner, hour, deadline, (cells, progress) =>
270-
writeHour(hour, cells, (tx) =>
271-
progress(tx, { freshThrough: new Date(hour.getTime() + HOUR_MS) })
272-
)
277+
const computed = await computeHour(
278+
owner,
279+
current.failedPasses,
280+
hour,
281+
deadline,
282+
(cells, progress) =>
283+
writeHour(hour, cells, (tx) =>
284+
progress(tx, { freshThrough: new Date(hour.getTime() + HOUR_MS) })
285+
)
273286
)
274287
if (!computed.state) break
275288
current = computed.state
@@ -297,20 +310,27 @@ async function recheckInflightCells(deadline: number): Promise<number> {
297310
if (Date.now() >= deadline) break
298311
const hour = new Date(Number(cell.bucketMs))
299312
const key = sql`workspace_id = ${cell.workspaceId} AND bucket_start = ${utcTimestamp(hour)}`
300-
await recomputeCell(cell.workspaceId, hour, async (tx, inFlight) => {
301-
if (inFlight === 0) {
302-
await tx.execute(sql`DELETE FROM ${activityRollupInflight} WHERE ${key}`)
303-
return
304-
}
305-
const attempts = Number(cell.attempts) + 1
306-
await tx.execute(sql`
307-
UPDATE ${activityRollupInflight}
308-
SET attempts = ${attempts},
309-
next_check_at = now() + ${msInterval(inflightBackoffMs(attempts))}
310-
WHERE ${key}
311-
`)
312-
})
313-
rechecked++
313+
const attempts = Number(cell.attempts) + 1
314+
const backOff = sql`UPDATE ${activityRollupInflight}
315+
SET attempts = ${attempts}, next_check_at = now() + ${msInterval(inflightBackoffMs(attempts))}
316+
WHERE ${key}`
317+
try {
318+
await recomputeCell(cell.workspaceId, hour, async (tx, inFlight) => {
319+
await tx.execute(
320+
inFlight === 0 ? sql`DELETE FROM ${activityRollupInflight} WHERE ${key}` : backOff
321+
)
322+
})
323+
rechecked++
324+
} catch (error) {
325+
// One cell that cannot be recomputed must not hold up the rest of the queue.
326+
logger.error('Activity rollup in-flight cell failed to recompute; backing off', {
327+
workspaceId: cell.workspaceId,
328+
hour: hour.toISOString(),
329+
attempts,
330+
error: getErrorMessage(error),
331+
})
332+
await db.execute(backOff)
333+
}
314334
}
315335
return rechecked
316336
}
@@ -342,18 +362,23 @@ async function backfill(
342362
}
343363
const hour = floorHour(latest.startedAt)
344364
const started = Date.now()
345-
const computed = await computeHour(owner, hour, deadline, (cells, progress) =>
346-
writeHour(hour, cells, async (tx) => {
347-
await tx
348-
.delete(workflowActivityHourly)
349-
.where(
350-
and(
351-
gte(workflowActivityHourly.bucketStart, new Date(hour.getTime() + HOUR_MS)),
352-
lt(workflowActivityHourly.bucketStart, coverageStart)
365+
const computed = await computeHour(
366+
owner,
367+
current.failedPasses,
368+
hour,
369+
deadline,
370+
(cells, progress) =>
371+
writeHour(hour, cells, async (tx) => {
372+
await tx
373+
.delete(workflowActivityHourly)
374+
.where(
375+
and(
376+
gte(workflowActivityHourly.bucketStart, new Date(hour.getTime() + HOUR_MS)),
377+
lt(workflowActivityHourly.bucketStart, coverageStart)
378+
)
353379
)
354-
)
355-
return progress(tx, { coverageStart: hour })
356-
})
380+
return progress(tx, { coverageStart: hour })
381+
})
357382
)
358383
if (!computed.state) break
359384
current = computed.state
@@ -591,6 +616,7 @@ export async function runActivityRollupPass(
591616
}
592617
result.dirtyRecomputed = await processDirtyMarks(state, deadline)
593618
result.inflightRechecked = await recheckInflightCells(deadline)
619+
state = await updateLeasedState(owner, { correctionsAt: sql`now()` })
594620
if (replicaCurrent) state = await backfill(owner, state, options, deadline, result)
595621

596622
const housekeepingDue =

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

Lines changed: 35 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { dbReplica, runOutsideTransactionContext } from '@sim/db'
2-
import { workflow, workflowActivityHourly, workspace } from '@sim/db/schema'
2+
import { activityRollupDirty, workflow, workflowActivityHourly, workspace } from '@sim/db/schema'
33
import { createLogger } from '@sim/logger'
44
import { type SQL, sql } from 'drizzle-orm'
55
import {
@@ -54,8 +54,9 @@ export interface RollupReadPlan {
5454

5555
/**
5656
* Splits `window` between the rollup and the source, or returns null when the rollup must not
57-
* serve it at all: another version's cells, no coverage yet, a stalled pass, or a window reaching
58-
* before a backfill that is still running. Once the backfill is complete, instants before the
57+
* serve it at all: another version's cells, no coverage yet, a stalled pass, correction queues
58+
* (dirty marks and in-flight rechecks) that no pass has run lately, or a window reaching before a
59+
* backfill that is still running. Once the backfill is complete, instants before the
5960
* coverage hold no runs and are read live at the cost of an index probe per workspace.
6061
*/
6162
export function planRollupRead(
@@ -66,7 +67,8 @@ export function planRollupRead(
6667
if (!state || state.version !== ACTIVITY_ROLLUP_VERSION) return null
6768
const { coverageStart, freshThrough } = state
6869
if (!coverageStart || !freshThrough) return null
69-
if (now.getTime() - freshThrough.getTime() >= MAX_FRESHNESS_LAG_MS) return null
70+
const lagging = (at: Date | null) => !at || now.getTime() - at.getTime() >= MAX_FRESHNESS_LAG_MS
71+
if (lagging(freshThrough) || lagging(state.correctionsAt)) return null
7072
if (window.from < coverageStart && !state.backfillCompletedAt) return null
7173

7274
const from = new Date(Math.max(ceilHour(window.from).getTime(), coverageStart.getTime()))
@@ -117,6 +119,19 @@ function storedCells(scope: ActivityScope, span: InstantRange): SQL {
117119
${scope.workspaceId ? sql`AND w.id = ${scope.workspaceId}` : sql``}`
118120
}
119121

122+
/**
123+
* The rollup hours of the scope's workspaces that have a pending dirty mark, as `h`: their cells
124+
* are known to be stale until the mark is processed (or while it backs off after failing), so
125+
* reads take those hours live. Read per workspace on the mark queue's key, in the read's snapshot.
126+
*/
127+
function markedHours(scope: ActivityScope, span: InstantRange): SQL {
128+
return sql`SELECT DISTINCT d.bucket_start AS h FROM ${workspace} w
129+
JOIN ${activityRollupDirty} d ON d.workspace_id = w.id
130+
AND d.bucket_start >= ${utcTimestamp(span.from)} AND d.bucket_start < ${utcTimestamp(span.to)}
131+
WHERE w.organization_id = ${scope.organizationId}
132+
${scope.workspaceId ? sql`AND w.id = ${scope.workspaceId}` : sql``}`
133+
}
134+
120135
type DayRow = Record<string, unknown> & {
121136
day: string
122137
runs: string | number
@@ -141,13 +156,15 @@ async function readWorkflowDays(
141156
): Promise<[string, ActivityStretch][]> {
142157
const local = (instant: SQL) => sql`((${instant}) AT TIME ZONE 'UTC') AT TIME ZONE ${timezone}`
143158
const day = (instant: SQL) => sql`to_char(date_trunc('day', ${local(instant)}), 'YYYY-MM-DD')`
144-
const last = sql`h + interval '1 hour' - interval '1 microsecond'`
159+
/** Parenthesized: it is subtracted below, where `- h + …` would change the arithmetic. */
160+
const last = sql`(h + interval '1 hour' - interval '1 microsecond')`
145161
const span = plan.rollup
146162
const straddles = span
147163
? sql`SELECT h FROM generate_series(${utcTimestamp(span.from)},
148164
${utcTimestamp(new Date(span.to.getTime() - HOUR_MS))}, interval '1 hour') AS h
149165
WHERE date_trunc('day', ${local(sql`h`)}) <> date_trunc('day', ${local(last)})
150-
OR ${local(sql`h`)} - h <> ${local(last)} - ${last}`
166+
OR ${local(sql`h`)} - h <> ${local(last)} - ${last}
167+
UNION ${markedHours(scope, span)}`
151168
: sql`SELECT NULL::timestamp AS h WHERE false`
152169
const live = sql`SELECT ${day(sql`a.started_at`)} AS day, ${workflowRunCounters}
153170
FROM (${organizationWorkflowRuns(scope, sql`SELECT * FROM live_ranges`)}) a
@@ -227,14 +244,20 @@ async function timedChatDays(
227244

228245
/**
229246
* Workflow runs of the window as breakdown cells: stored cells summed over the rollup span, and
230-
* the live edges, each keyed by workspace, workflow, and trigger. A stored cell's workflow is
231-
* looked up now, so one deleted since the cell was computed reads as deleted, as its runs do.
247+
* the live edges and marked hours (see {@link markedHours}), each keyed by workspace, workflow, and
248+
* trigger. A stored cell's workflow is looked up now, so one deleted since the cell was computed
249+
* reads as deleted, as its runs do.
232250
*/
233251
function workflowCells(scope: ActivityScope, plan: RollupReadPlan, resolveWorkflow: boolean) {
234-
const live = sql`SELECT a.workspace_id, a.workflow_id, a.trigger, ${workflowRunCounters}
235-
FROM (${organizationWorkflowRuns(scope, rangeRows(plan.live))}) a
252+
const liveCells = (ranges: SQL) => sql`SELECT a.workspace_id, a.workflow_id, a.trigger,
253+
${workflowRunCounters}
254+
FROM (${organizationWorkflowRuns(scope, ranges)}) a
236255
GROUP BY 1, 2, 3`
237-
if (!plan.rollup) return live
256+
if (!plan.rollup) return liveCells(rangeRows(plan.live))
257+
const marked = markedHours(scope, plan.rollup)
258+
const live = liveCells(
259+
sql`${rangeRows(plan.live)} UNION ALL SELECT m.h, m.h + interval '1 hour' FROM (${marked}) m`
260+
)
238261
const workflowId = resolveWorkflow
239262
? sql`(SELECT f.id FROM ${workflow} f WHERE f.id = nullif(r.workflow_id, ''))`
240263
: sql`NULL::text`
@@ -247,6 +270,7 @@ function workflowCells(scope: ActivityScope, plan: RollupReadPlan, resolveWorkfl
247270
sum(r.in_flight) AS in_flight, sum(r.duration_sum_ms) AS duration_sum_ms,
248271
sum(r.duration_count) AS duration_count
249272
FROM ${storedCells(scope, plan.rollup)}
273+
AND NOT EXISTS (SELECT 1 FROM (${marked}) m WHERE m.h = r.bucket_start)
250274
GROUP BY 1, 2, 3
251275
) r
252276
UNION ALL ${live}`

0 commit comments

Comments
 (0)