Skip to content

Commit 1846952

Browse files
committed
fix(usage): read only marked workspace-hours live, mark failing in-flight cells dirty, and stamp corrections only when both queues drain
1 parent 4aa6272 commit 1846952

5 files changed

Lines changed: 160 additions & 26 deletions

File tree

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

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -144,13 +144,14 @@ export async function captureLateEnds(
144144
* meanwhile survives for the next pass. Marks of hours not covered yet wait: an hour being
145145
* finalized or backfilled is read on the replica, which may not have the change yet. Once the
146146
* backfill is complete, marks older than the coverage are dropped, since no cell holds them.
147+
* `finished` is whether every due mark was taken: false when the deadline or the batch cut it short.
147148
*/
148149
export async function processDirtyMarks(
149150
state: ActivityRollupState,
150151
deadline: number
151-
): Promise<number> {
152+
): Promise<{ processed: number; finished: boolean }> {
152153
const { coverageStart, freshThrough, backfillCompletedAt } = state
153-
if (!coverageStart || !freshThrough) return 0
154+
if (!coverageStart || !freshThrough) return { processed: 0, finished: true }
154155
if (backfillCompletedAt) {
155156
await db.delete(activityRollupDirty).where(lt(activityRollupDirty.bucketStart, coverageStart))
156157
}
@@ -171,7 +172,7 @@ export async function processDirtyMarks(
171172
`)
172173
let processed = 0
173174
for (const mark of marks) {
174-
if (Date.now() >= deadline) break
175+
if (Date.now() >= deadline) return { processed, finished: false }
175176
const hour = new Date(Number(mark.bucketMs))
176177
const key = sql`workspace_id = ${mark.workspaceId} AND bucket_start = ${utcTimestamp(hour)}
177178
AND due_at = ${mark.seen}::timestamptz`
@@ -196,5 +197,5 @@ export async function processDirtyMarks(
196197
`)
197198
}
198199
}
199-
return processed
200+
return { processed, finished: marks.length < DIRTY_BATCH }
200201
}

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

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,9 @@ async function finalizeSettledHours(
296296
* from the queue; one still unfinished is checked again later, backing off to a few hours, since
297297
* it is usually a paused run waiting on a person.
298298
*/
299-
async function recheckInflightCells(deadline: number): Promise<number> {
299+
async function recheckInflightCells(
300+
deadline: number
301+
): Promise<{ rechecked: number; finished: boolean }> {
300302
const due = await db.execute<{ workspaceId: string; bucketMs: number; attempts: number }>(sql`
301303
SELECT workspace_id AS "workspaceId", (extract(epoch FROM bucket_start) * 1000)::float8 AS "bucketMs",
302304
attempts
@@ -307,7 +309,7 @@ async function recheckInflightCells(deadline: number): Promise<number> {
307309
`)
308310
let rechecked = 0
309311
for (const cell of due) {
310-
if (Date.now() >= deadline) break
312+
if (Date.now() >= deadline) return { rechecked, finished: false }
311313
const hour = new Date(Number(cell.bucketMs))
312314
const key = sql`workspace_id = ${cell.workspaceId} AND bucket_start = ${utcTimestamp(hour)}`
313315
const attempts = Number(cell.attempts) + 1
@@ -322,17 +324,26 @@ async function recheckInflightCells(deadline: number): Promise<number> {
322324
})
323325
rechecked++
324326
} catch (error) {
325-
// One cell that cannot be recomputed must not hold up the rest of the queue.
327+
/**
328+
* One cell that cannot be recomputed must not hold up the rest of the queue. Its runs may
329+
* have finished with an end the late-end scan never sees, so it is also marked dirty: reads
330+
* serve it live, and the dirty queue retries it with its own backoff.
331+
*/
326332
logger.error('Activity rollup in-flight cell failed to recompute; backing off', {
327333
workspaceId: cell.workspaceId,
328334
hour: hour.toISOString(),
329335
attempts,
330336
error: getErrorMessage(error),
331337
})
332338
await db.execute(backOff)
339+
await db.execute(sql`
340+
INSERT INTO ${activityRollupDirty} (workspace_id, bucket_start, due_at)
341+
VALUES (${cell.workspaceId}, ${utcTimestamp(hour)}, now() + ${msInterval(inflightBackoffMs(0))})
342+
ON CONFLICT (workspace_id, bucket_start) DO NOTHING
343+
`)
333344
}
334345
}
335-
return rechecked
346+
return { rechecked, finished: due.length < INFLIGHT_BATCH }
336347
}
337348

338349
/**
@@ -614,9 +625,14 @@ export async function runActivityRollupPass(
614625
maxLagMs: MAX_REPLICA_LAG_MS,
615626
})
616627
}
617-
result.dirtyRecomputed = await processDirtyMarks(state, deadline)
618-
result.inflightRechecked = await recheckInflightCells(deadline)
619-
state = await updateLeasedState(owner, { correctionsAt: sql`now()` })
628+
const marks = await processDirtyMarks(state, deadline)
629+
const inflight = await recheckInflightCells(deadline)
630+
result.dirtyRecomputed = marks.processed
631+
result.inflightRechecked = inflight.rechecked
632+
/** Only a pass that got through every due item of both queues vouches for the cells. */
633+
if (marks.finished && inflight.finished) {
634+
state = await updateLeasedState(owner, { correctionsAt: sql`now()` })
635+
}
620636
if (replicaCurrent) state = await backfill(owner, state, options, deadline, result)
621637

622638
const housekeepingDue =

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,19 @@ export function organizationWorkflowRuns(
8787
${scope.workspaceId ? sql`AND w.id = ${scope.workspaceId}` : sql``}`
8888
}
8989

90+
/**
91+
* The runs of the workspace-hour cells `cells` returns as `(workspace_id, h)` rows, each read on the
92+
* workspace activity index, for reading single stale cells live.
93+
*/
94+
export function cellRuns(cells: SQL): SQL {
95+
return sql`SELECT l.* FROM (${cells}) c
96+
CROSS JOIN LATERAL (
97+
SELECT ${workflowRunColumns} FROM ${workflowExecutionLogs} l
98+
WHERE l.workspace_id = c.workspace_id
99+
AND l.started_at >= c.h AND l.started_at < c.h + interval '1 hour'
100+
) l`
101+
}
102+
90103
/** `ranges` as `(range_start, range_end)` rows for {@link organizationWorkflowRuns}. */
91104
export function rangeRows(ranges: InstantRange[]): SQL {
92105
if (ranges.length === 0) {

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

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { createLogger } from '@sim/logger'
44
import { type SQL, sql } from 'drizzle-orm'
55
import {
66
ceilHour,
7+
cellRuns,
78
floorHour,
89
HOUR_MS,
910
type InstantRange,
@@ -120,18 +121,24 @@ function storedCells(scope: ActivityScope, span: InstantRange): SQL {
120121
}
121122

122123
/**
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.
124+
* The rollup cells of the scope's workspaces that have a pending dirty mark, as
125+
* `(workspace_id, h)`: known to be stale until the mark is processed (or while it backs off after
126+
* failing), so reads take exactly those workspace-hours live and every other workspace's stored
127+
* cell for the hour still serves. Read on the mark queue's key, in the read's snapshot.
126128
*/
127-
function markedHours(scope: ActivityScope, span: InstantRange): SQL {
128-
return sql`SELECT DISTINCT d.bucket_start AS h FROM ${workspace} w
129+
function markedCells(scope: ActivityScope, span: InstantRange): SQL {
130+
return sql`SELECT DISTINCT d.workspace_id, d.bucket_start AS h FROM ${workspace} w
129131
JOIN ${activityRollupDirty} d ON d.workspace_id = w.id
130132
AND d.bucket_start >= ${utcTimestamp(span.from)} AND d.bucket_start < ${utcTimestamp(span.to)}
131133
WHERE w.organization_id = ${scope.organizationId}
132134
${scope.workspaceId ? sql`AND w.id = ${scope.workspaceId}` : sql``}`
133135
}
134136

137+
/** A stored cell `r` of workspace `w` whose workspace-hour is not among `marked` cells `m`. */
138+
function notMarked(marked: SQL): SQL {
139+
return sql`NOT EXISTS (SELECT 1 FROM (${marked}) m WHERE m.workspace_id = w.id AND m.h = r.bucket_start)`
140+
}
141+
135142
type DayRow = Record<string, unknown> & {
136143
day: string
137144
runs: string | number
@@ -145,7 +152,7 @@ type DayRow = Record<string, unknown> & {
145152
/**
146153
* Workflow activity per local day of the viewer. Stored hours are summed by the day they fall
147154
* on; an hour that crosses a local midnight, or a change of UTC offset, belongs to two days, so it
148-
* is read live with the edges instead. Both are found with the database's time zone rules, the
155+
* is read live with the edges instead, as is each marked cell (see {@link markedCells}). Both are found with the database's time zone rules, the
149156
* ones the legacy reads use. Only zones off the whole hour have such hours.
150157
*/
151158
async function readWorkflowDays(
@@ -163,11 +170,13 @@ async function readWorkflowDays(
163170
? sql`SELECT h FROM generate_series(${utcTimestamp(span.from)},
164171
${utcTimestamp(new Date(span.to.getTime() - HOUR_MS))}, interval '1 hour') AS h
165172
WHERE date_trunc('day', ${local(sql`h`)}) <> date_trunc('day', ${local(last)})
166-
OR ${local(sql`h`)} - h <> ${local(last)} - ${last}
167-
UNION ${markedHours(scope, span)}`
173+
OR ${local(sql`h`)} - h <> ${local(last)} - ${last}`
168174
: sql`SELECT NULL::timestamp AS h WHERE false`
169175
const live = sql`SELECT ${day(sql`a.started_at`)} AS day, ${workflowRunCounters}
170-
FROM (${organizationWorkflowRuns(scope, sql`SELECT * FROM live_ranges`)}) a
176+
FROM (
177+
${organizationWorkflowRuns(scope, sql`SELECT * FROM live_ranges`)}
178+
UNION ALL ${cellRuns(sql`SELECT * FROM marked`)}
179+
) a
171180
GROUP BY 1`
172181
const stored = span
173182
? sql`SELECT ${day(sql`r.bucket_start`)} AS day, sum(r.runs) AS runs,
@@ -176,12 +185,16 @@ async function readWorkflowDays(
176185
sum(r.duration_count) AS duration_count
177186
FROM ${storedCells(scope, span)}
178187
AND NOT EXISTS (SELECT 1 FROM straddles s WHERE s.h = r.bucket_start)
188+
AND ${notMarked(sql`SELECT * FROM marked`)}
179189
GROUP BY 1`
180190
: null
181191
const rows = await tx.execute<DayRow>(sql`
182192
WITH straddles AS (${straddles}), live_ranges AS (
183193
${rangeRows(plan.live)}
184194
UNION ALL SELECT h, h + interval '1 hour' FROM straddles
195+
), marked AS (
196+
SELECT c.* FROM (${span ? markedCells(scope, span) : sql`SELECT NULL::text AS workspace_id, NULL::timestamp AS h WHERE false`}) c
197+
WHERE NOT EXISTS (SELECT 1 FROM straddles s WHERE s.h = c.h)
185198
)
186199
${stored ? sql`${stored} UNION ALL ${live}` : live}
187200
`)
@@ -244,7 +257,7 @@ async function timedChatDays(
244257

245258
/**
246259
* Workflow runs of the window as breakdown cells: stored cells summed over the rollup span, and
247-
* the live edges and marked hours (see {@link markedHours}), each keyed by workspace, workflow, and
260+
* the live edges and marked cells (see {@link markedCells}), each keyed by workspace, workflow, and
248261
* trigger. A stored cell's workflow is looked up now, so one deleted since the cell was computed
249262
* reads as deleted, as its runs do.
250263
*/
@@ -254,10 +267,11 @@ function workflowCells(scope: ActivityScope, plan: RollupReadPlan, resolveWorkfl
254267
FROM (${organizationWorkflowRuns(scope, ranges)}) a
255268
GROUP BY 1, 2, 3`
256269
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-
)
270+
const marked = markedCells(scope, plan.rollup)
271+
const live = sql`${liveCells(rangeRows(plan.live))}
272+
UNION ALL SELECT a.workspace_id, a.workflow_id, a.trigger, ${workflowRunCounters}
273+
FROM (${cellRuns(marked)}) a
274+
GROUP BY 1, 2, 3`
261275
const workflowId = resolveWorkflow
262276
? sql`(SELECT f.id FROM ${workflow} f WHERE f.id = nullif(r.workflow_id, ''))`
263277
: sql`NULL::text`
@@ -270,7 +284,7 @@ function workflowCells(scope: ActivityScope, plan: RollupReadPlan, resolveWorkfl
270284
sum(r.in_flight) AS in_flight, sum(r.duration_sum_ms) AS duration_sum_ms,
271285
sum(r.duration_count) AS duration_count
272286
FROM ${storedCells(scope, plan.rollup)}
273-
AND NOT EXISTS (SELECT 1 FROM (${marked}) m WHERE m.h = r.bucket_start)
287+
AND ${notMarked(marked)}
274288
GROUP BY 1, 2, 3
275289
) r
276290
UNION ALL ${live}`

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

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -997,6 +997,21 @@ describe('organization activity rollup', () => {
997997
expect(await mark('ws1', healthy.hour)).toBeNull()
998998
expect(await mark('ws2', stale.hour)).toEqual({ attempts: 1, waiting: true })
999999
await expectEquivalent()
1000+
// Only the marked workspace's hour is read live: another workspace's cell there still serves.
1001+
const legacy = await legacySummary(longWindow(), 'UTC')
1002+
await connection.unsafe(
1003+
`INSERT INTO workflow_activity_hourly (workspace_id, bucket_start, workflow_id, trigger, runs,
1004+
completed, failed, cancelled, in_flight, duration_sum_ms, duration_count)
1005+
VALUES ('ws1', $1::timestamp, 'probe', 'probe', 1000, 0, 0, 0, 0, 0, 0)`,
1006+
[stale.hour]
1007+
)
1008+
try {
1009+
expect((await servedSummary(longWindow(), 'UTC', {})).totals.workflowRuns).toBe(
1010+
legacy.totals.workflowRuns + 1000
1011+
)
1012+
} finally {
1013+
await connection.unsafe(`DELETE FROM workflow_activity_hourly WHERE workflow_id = 'probe'`)
1014+
}
10001015
} finally {
10011016
await connection.unsafe(`
10021017
DROP TRIGGER fail_cell_write ON workflow_activity_hourly;
@@ -1009,6 +1024,81 @@ describe('organization activity rollup', () => {
10091024
await expectEquivalent()
10101025
}, 300_000)
10111026

1027+
it('marks a cell whose in-flight recheck keeps failing dirty, so its hour reads live', async () => {
1028+
const state = await readRollupState()
1029+
const coverageStart = state?.coverageStart
1030+
const freshThrough = state?.freshThrough
1031+
if (!coverageStart || !freshThrough) throw new Error('No coverage')
1032+
const [run] = await connection.unsafe<{ id: string; hour: string }[]>(
1033+
`SELECT id, to_char(date_trunc('hour', started_at), 'YYYY-MM-DD HH24:MI:SS') AS hour
1034+
FROM workflow_execution_logs
1035+
WHERE workspace_id = 'ws1' AND status IN ('running', 'paused', 'pending', 'redacting')
1036+
AND started_at >= $1::timestamptz AT TIME ZONE 'UTC'
1037+
AND started_at < $2::timestamptz AT TIME ZONE 'UTC'
1038+
ORDER BY started_at DESC LIMIT 1`,
1039+
[coverageStart.toISOString(), freshThrough.toISOString()]
1040+
)
1041+
if (!run) throw new Error('No unfinished covered run')
1042+
// Finishes early, so only its in-flight recheck can see the change.
1043+
await connection.unsafe(
1044+
`UPDATE workflow_execution_logs SET status = 'completed', total_duration_ms = 1234,
1045+
ended_at = started_at + interval '20 minutes' WHERE id = $1`,
1046+
[run.id]
1047+
)
1048+
await connection.unsafe(
1049+
`INSERT INTO activity_rollup_inflight VALUES ('ws1', $1::timestamp, now(), 0)
1050+
ON CONFLICT (workspace_id, bucket_start) DO UPDATE SET next_check_at = now()`,
1051+
[run.hour]
1052+
)
1053+
await connection.unsafe(`
1054+
CREATE FUNCTION fail_inflight_cell() RETURNS trigger LANGUAGE plpgsql AS $$
1055+
BEGIN
1056+
IF coalesce(NEW.workspace_id, OLD.workspace_id) = 'ws1'
1057+
AND coalesce(NEW.bucket_start, OLD.bucket_start) = '${run.hour}'::timestamp THEN
1058+
RAISE EXCEPTION 'Synthetic recompute failure';
1059+
END IF;
1060+
RETURN coalesce(NEW, OLD);
1061+
END $$;
1062+
CREATE TRIGGER fail_inflight_cell BEFORE INSERT OR UPDATE OR DELETE ON workflow_activity_hourly
1063+
FOR EACH ROW EXECUTE FUNCTION fail_inflight_cell();
1064+
`)
1065+
try {
1066+
expect((await runPass()).status).toBe('ran')
1067+
const [marked] = await connection.unsafe<{ count: number }[]>(
1068+
`SELECT count(*)::int AS count FROM activity_rollup_dirty
1069+
WHERE workspace_id = 'ws1' AND bucket_start = $1::timestamp`,
1070+
[run.hour]
1071+
)
1072+
expect(marked?.count).toBe(1)
1073+
await expectEquivalent()
1074+
} finally {
1075+
await connection.unsafe(`
1076+
DROP TRIGGER fail_inflight_cell ON workflow_activity_hourly;
1077+
DROP FUNCTION fail_inflight_cell();
1078+
`)
1079+
}
1080+
await connection.unsafe(`UPDATE activity_rollup_dirty SET due_at = now()`)
1081+
await connection.unsafe(`UPDATE activity_rollup_inflight SET next_check_at = now()`)
1082+
await runPass()
1083+
await expectEquivalent()
1084+
}, 300_000)
1085+
1086+
it('does not vouch for the corrections when the pass budget cut its queues short', async () => {
1087+
const state = await readRollupState()
1088+
if (!state?.freshThrough) throw new Error('No coverage')
1089+
await connection`UPDATE activity_rollup_state SET corrections_at = now() - interval '1 hour'`
1090+
await connection`INSERT INTO activity_rollup_dirty
1091+
VALUES ('ws1', ${state.freshThrough.toISOString()}::timestamptz AT TIME ZONE 'UTC' - interval '2 hours', now())
1092+
ON CONFLICT (workspace_id, bucket_start) DO UPDATE SET due_at = excluded.due_at`
1093+
await runPass(NOW, { budgetMs: 1 })
1094+
const [row] = await connection.unsafe<{ stale: boolean }[]>(
1095+
`SELECT corrections_at < now() - interval '50 minutes' AS stale FROM activity_rollup_state`
1096+
)
1097+
expect(row?.stale).toBe(true)
1098+
await runPass()
1099+
expect(await readRollupActivityDays(scopeOf(longWindow()), 'UTC')).not.toBeNull()
1100+
}, 300_000)
1101+
10121102
it('stops serving the rollup while no pass has run its correction queues within the bound', async () => {
10131103
await connection.unsafe(
10141104
`UPDATE activity_rollup_state SET corrections_at = now() - interval '7 hours'`

0 commit comments

Comments
 (0)