Skip to content

Commit 627d213

Browse files
waleedlatif1claude
andauthored
fix(usage): make rollup migrations atomic and mark late-committing finished runs (#10212)
* fix(usage): mark finished runs whose hour may be computed, make rollup migrations atomic Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(usage): mark swept runs too, share the finished-run mark, drop the redundant 0465 BEGIN Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(usage): lock activity rollup marks in key order Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 994babd commit 627d213

9 files changed

Lines changed: 104 additions & 32 deletions

File tree

‎apps/sim/background/cleanup-stale-executions.test.ts‎

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,11 @@ function collectSqlParams(fragment: unknown): unknown[] {
8080
})
8181
}
8282

83+
/** A swept log as the sweep's update returns it: recent, so it is not marked for the rollup. */
84+
function sweptRun(id: string) {
85+
return { id, workspaceId: 'workspace-1', startedAt: new Date() }
86+
}
87+
8388
describe('stale execution cleanup deadline grace', () => {
8489
beforeEach(() => {
8590
resetDbChainMock()
@@ -324,9 +329,9 @@ describe('stale execution cleanup deadline grace', () => {
324329
}))
325330

326331
for (let batch = 0; batch < 10; batch++) {
327-
const workflowBatch = Array.from({ length: 100 }, (_, index) => ({
328-
id: `workflow-state-${batch}-${index}`,
329-
}))
332+
const workflowBatch = Array.from({ length: 100 }, (_, index) =>
333+
sweptRun(`workflow-state-${batch}-${index}`)
334+
)
330335
queueTableRows(workflowExecutionLogs, workflowBatch)
331336
dbChainMockFns.returning.mockResolvedValueOnce(workflowBatch)
332337
}
@@ -396,12 +401,10 @@ describe('stale execution cleanup deadline grace', () => {
396401
})
397402

398403
it('preserves committed workflow cleanup counts when a later batch fails', async () => {
399-
const firstBatch = Array.from({ length: 100 }, (_, index) => ({
400-
id: `execution-${index}`,
401-
}))
402-
const failedBatch = Array.from({ length: 37 }, (_, index) => ({
403-
id: `failed-execution-${index}`,
404-
}))
404+
const firstBatch = Array.from({ length: 100 }, (_, index) => sweptRun(`execution-${index}`))
405+
const failedBatch = Array.from({ length: 37 }, (_, index) =>
406+
sweptRun(`failed-execution-${index}`)
407+
)
405408
queueTableRows(workflowExecutionLogs, firstBatch)
406409
queueTableRows(workflowExecutionLogs, failedBatch)
407410
queueTableRows(asyncJobs, [{ id: 'async-job-1' }])
@@ -426,11 +429,11 @@ describe('stale execution cleanup deadline grace', () => {
426429
})
427430

428431
it('continues draining when an atomic race updates fewer rows than were selected', async () => {
429-
const firstCandidates = Array.from({ length: 100 }, (_, index) => ({
430-
id: `execution-${index}`,
431-
}))
432+
const firstCandidates = Array.from({ length: 100 }, (_, index) =>
433+
sweptRun(`execution-${index}`)
434+
)
432435
const firstUpdated = firstCandidates.slice(0, 99)
433-
const secondBatch = [{ id: 'execution-100' }]
436+
const secondBatch = [sweptRun('execution-100')]
434437
queueTableRows(workflowExecutionLogs, firstCandidates)
435438
queueTableRows(workflowExecutionLogs, secondBatch)
436439
dbChainMockFns.returning.mockResolvedValueOnce(firstUpdated).mockResolvedValueOnce(secondBatch)

‎apps/sim/background/cleanup-stale-executions.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { toError } from '@sim/utils/errors'
1313
import { task } from '@trigger.dev/sdk'
1414
import { and, eq, exists, gt, inArray, isNull, lt, ne, or, sql } from 'drizzle-orm'
1515
import { alias } from 'drizzle-orm/pg-core'
16+
import { markFinishedRunsDirty } from '@/lib/billing/activity-rollup/marks'
1617
import {
1718
JOB_PENDING_RETENTION_HOURS,
1819
JOB_RETENTION_HOURS,
@@ -287,7 +288,13 @@ export async function runCleanupStaleExecutions() {
287288
)
288289
)
289290
)
290-
.returning({ id: workflowExecutionLogs.id })
291+
.returning({
292+
id: workflowExecutionLogs.id,
293+
workspaceId: workflowExecutionLogs.workspaceId,
294+
startedAt: workflowExecutionLogs.startedAt,
295+
})
296+
// Every batch reuses the sweep's one end stamp, so a late batch can commit behind the scan.
297+
await markFinishedRunsDirty(tx, updatedExecutions)
291298

292299
return { candidates, updatedExecutions }
293300
})

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

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,13 @@ import {
88
inflightBackoffMs,
99
recomputeCell,
1010
} from '@/lib/billing/activity-rollup/cells'
11-
import { floorHour, msInterval, utcTimestamp } from '@/lib/billing/activity-rollup/source'
11+
import {
12+
ACTIVITY_ROLLUP_SETTLE_MS,
13+
floorHour,
14+
HOUR_MS,
15+
msInterval,
16+
utcTimestamp,
17+
} from '@/lib/billing/activity-rollup/source'
1218
import {
1319
type ActivityRollupState,
1420
MAINTENANCE_GAP_MS,
@@ -21,7 +27,8 @@ const logger = createLogger('ActivityRollupMarks')
2127
/**
2228
* How far behind now the late-end scan stays: an end is stamped by the app before its write
2329
* commits, so the scan only consumes ends old enough that every write stamped with them is
24-
* visible. Ends younger than this are read by a later pass.
30+
* visible. Ends younger than this are read by a later pass. A writer whose stamp can trail its
31+
* commit by longer marks the runs it finishes itself (see {@link markFinishedRunsDirty}).
2532
*/
2633
export const LATE_END_SCAN_MARGIN_MS = 5 * 60 * 1000
2734

@@ -39,7 +46,8 @@ interface ChangedRun {
3946
/**
4047
* Marks the rollup cells of `runs` for recomputing, in the caller's transaction so the marks
4148
* commit exactly when the change does. For changes the rollup pass cannot see on its own:
42-
* deleted runs, and finished runs reopened without an end.
49+
* deleted runs, finished runs reopened without an end, and runs whose end committed too late for
50+
* the late-end scan (see {@link markFinishedRunsDirty}).
4351
*
4452
* Runs in a savepoint and never throws: a mark that fails (the table missing mid-deploy) is logged
4553
* and the caller's change goes ahead, so retention and resumes behave exactly as without the
@@ -70,6 +78,8 @@ export async function markWorkflowActivityDirty(
7078
SELECT 1 FROM ${activityRollupState}
7179
WHERE maintained_at > now() - ${msInterval(MAINTENANCE_GAP_MS)}
7280
)
81+
-- Writers of several marks lock them in key order, so two can never deadlock.
82+
ORDER BY 1, 2
7383
ON CONFLICT (workspace_id, bucket_start) DO UPDATE SET due_at = excluded.due_at
7484
`)
7585
})
@@ -81,6 +91,22 @@ export async function markWorkflowActivityDirty(
8191
}
8292
}
8393

94+
/** Runs younger than this lie in hours not computed yet: the settle lag less an hour of clock margin. */
95+
const FINISHED_RUN_MARK_AGE_MS = ACTIVITY_ROLLUP_SETTLE_MS - HOUR_MS
96+
97+
/**
98+
* Marks the cells of runs whose final status is being written, in the transaction that writes it,
99+
* when their hours may already be computed. Their ends were stamped before the write, so it can
100+
* commit after the late-end scan passed the end, or after the hour was computed without a late end.
101+
*/
102+
export async function markFinishedRunsDirty(tx: DbTransaction, runs: ChangedRun[]): Promise<void> {
103+
const settled = Date.now() - FINISHED_RUN_MARK_AGE_MS
104+
await markWorkflowActivityDirty(
105+
tx,
106+
runs.filter((run) => run.startedAt.getTime() <= settled)
107+
)
108+
}
109+
84110
/**
85111
* Marks the cells of runs that ended at least two hours after they started since the last scan,
86112
* and moves the scan forward. Their hours were computed before they ended (HITL runs resumed
@@ -123,6 +149,7 @@ export async function captureLateEnds(
123149
FROM ${workflowExecutionLogs} l, bound
124150
WHERE l.ended_at >= l.started_at + interval '2 hours'
125151
AND l.ended_at > bound.cursor AND l.ended_at <= bound.boundary
152+
ORDER BY 1, 2
126153
ON CONFLICT (workspace_id, bucket_start) DO NOTHING
127154
RETURNING 1
128155
), moved AS (

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

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
processDirtyMarks,
3232
} from '@/lib/billing/activity-rollup/marks'
3333
import {
34+
ACTIVITY_ROLLUP_SETTLE_MS,
3435
floorHour,
3536
HOUR_MS,
3637
type InstantRange,
@@ -56,14 +57,6 @@ import type { DbTransaction } from '@/lib/db/types'
5657

5758
const logger = createLogger('ActivityRollupPass')
5859

59-
/**
60-
* How long after an hour ends before it is computed. A run that ends within two hours of its start
61-
* (the predicate of `workflow_execution_logs_late_end_idx`) has ended, and its write committed, by
62-
* then; one that ends later is found by its late end. The hour of margin covers commit and replica
63-
* lag, so this must stay at least an hour above that threshold.
64-
*/
65-
const ACTIVITY_ROLLUP_SETTLE_MS = 3 * HOUR_MS
66-
6760
/** The lease a heavy-hour retry adds on top of its own budget, for the statements around it. */
6861
const LEASE_MARGIN_MS = 60 * 1000
6962

@@ -479,6 +472,7 @@ export function markStaleHours(workspaceId: string, range: InstantRange): Promis
479472
SELECT 1 FROM ${activityRollupInflight} q
480473
WHERE q.workspace_id = ${workspaceId} AND q.bucket_start = d.hour
481474
)
475+
ORDER BY d.hour
482476
ON CONFLICT (workspace_id, bucket_start) DO NOTHING
483477
`)
484478
return marked.count

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,14 @@ export interface InstantRange {
1616

1717
export const HOUR_MS = 60 * 60 * 1000
1818

19+
/**
20+
* How long after an hour ends before it is computed. A run that ends within two hours of its start
21+
* (the predicate of `workflow_execution_logs_late_end_idx`) has ended by then; one that ends later
22+
* is found by its late end, or marked when its end commits. The hour of margin covers commit and
23+
* replica lag, so this must stay at least an hour above that threshold.
24+
*/
25+
export const ACTIVITY_ROLLUP_SETTLE_MS = 3 * HOUR_MS
26+
1927
/** An instant as the UTC wall clock `started_at` stores, whatever the session's time zone. */
2028
export function utcTimestamp(instant: Date): SQL {
2129
return sql`(${instant.toISOString()}::timestamptz AT TIME ZONE 'UTC')`

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

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as schema from '@sim/db/schema'
22
import { readTestDatabaseUrl } from '@sim/db/testing/test-infrastructure'
33
import { generateId } from '@sim/utils/id'
4+
import { eq, sql } from 'drizzle-orm'
45
import { drizzle } from 'drizzle-orm/postgres-js'
56
import postgres from 'postgres'
67
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
@@ -48,6 +49,7 @@ vi.mock('@/lib/billing/core/usage-segment-cache', () => ({
4849
},
4950
}))
5051

52+
import { markFinishedRunsDirty } from '@/lib/billing/activity-rollup/marks'
5153
import {
5254
type ActivityRollupPassOptions,
5355
markStaleHours,
@@ -634,6 +636,28 @@ describe('organization activity rollup', () => {
634636
await expectEquivalent()
635637
}, 120_000)
636638

639+
it('marks a late-committing completion so its computed hour reads live', async () => {
640+
const run = await oneLog(
641+
`status = 'running' AND started_at < (now() AT TIME ZONE 'UTC') - interval '3 days'`
642+
)
643+
await database.transaction(async (tx) => {
644+
const [finished] = await tx
645+
.update(schema.workflowExecutionLogs)
646+
.set({
647+
status: 'completed',
648+
totalDurationMs: 1800,
649+
endedAt: sql`${schema.workflowExecutionLogs.startedAt} + interval '30 minutes'`,
650+
})
651+
.where(eq(schema.workflowExecutionLogs.id, run.id))
652+
.returning()
653+
if (!finished) throw new Error('No run to finish')
654+
await markFinishedRunsDirty(tx, [finished])
655+
})
656+
await expectEquivalent()
657+
await runPass()
658+
await expectEquivalent()
659+
}, 120_000)
660+
637661
it('runs one pass at a time and rewrites nothing when run again', async () => {
638662
const results = await Promise.all([runPass(), runPass()])
639663
expect(results.map((result) => result.status).sort()).toEqual(['leased', 'ran'])
@@ -711,13 +735,16 @@ describe('organization activity rollup', () => {
711735
FOR EACH ROW WHEN (NEW.bucket_start = '${failing.toISOString().replace('T', ' ').slice(0, 19)}')
712736
EXECUTE FUNCTION fail_rollup_write();
713737
`)
714-
await expect(runPass()).rejects.toThrow()
715-
const crashed = await readRollupState()
716-
expect(crashed?.coverageStart?.getTime()).toBeGreaterThan(failing.getTime())
717-
expect(crashed?.leaseOwner).toBeNull()
718-
await connection.unsafe(
719-
`DROP TRIGGER fail_rollup_write ON workflow_activity_hourly; DROP FUNCTION fail_rollup_write()`
720-
)
738+
try {
739+
await expect(runPass()).rejects.toThrow()
740+
const crashed = await readRollupState()
741+
expect(crashed?.coverageStart?.getTime()).toBeGreaterThan(failing.getTime())
742+
expect(crashed?.leaseOwner).toBeNull()
743+
} finally {
744+
await connection.unsafe(
745+
`DROP TRIGGER fail_rollup_write ON workflow_activity_hourly; DROP FUNCTION fail_rollup_write()`
746+
)
747+
}
721748
expect((await runPass()).backfillComplete).toBe(true)
722749
await expectEquivalent()
723750
}, 300_000)

‎apps/sim/lib/logs/execution/logger.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
import { generateId } from '@sim/utils/id'
1818
import { filterUndefined, isRecordLike } from '@sim/utils/object'
1919
import { and, eq, inArray, sql } from 'drizzle-orm'
20+
import { markFinishedRunsDirty } from '@/lib/billing/activity-rollup/marks'
2021
import { checkUsageStatus as checkResolvedUsageStatus } from '@/lib/billing/calculations/usage-monitor'
2122
import { type BillingAttributionSnapshot, toBillingContext } from '@/lib/billing/core/attribution'
2223
import { readSoftGateUsageCost } from '@/lib/billing/core/reporting-usage-cache'
@@ -1374,6 +1375,7 @@ export class ExecutionLogger {
13741375
},
13751376
completedExecutionLargeValueKeys
13761377
)
1378+
await markFinishedRunsDirty(tx, [log])
13771379

13781380
return { updatedLog: log, completionPersisted: true }
13791381
})

‎packages/db/migrations/0462_workflow_activity_rollup.sql‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
-- activity-rollup-maintenance and organization-activity-rollup-reads flags are turned on, so the
55
-- deployed app is unaffected. The tables are new, so their indexes build on empty tables inside
66
-- this migration's transaction.
7+
-- 0461 ends the batch transaction with a concurrent index build; keep these tables and their journal row atomic.
8+
BEGIN;--> statement-breakpoint
79
CREATE TABLE "activity_rollup_dirty" (
810
"workspace_id" text NOT NULL,
911
"bucket_start" timestamp NOT NULL,

‎packages/db/migrations/0464_activity_rollup_maintenance_state.sql‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
-- when a pass last completed (which gates writers' marks and decides a rebuild after a gap). A new
33
-- table, and a nullable column on the one-row activity_rollup_state, which no deployed code
44
-- writes: metadata-only and invisible to the running app.
5+
-- 0463 ends the batch transaction with a concurrent index build; keep this table and its journal row atomic.
6+
BEGIN;--> statement-breakpoint
57
CREATE TABLE "activity_rollup_blocked" (
68
"bucket_start" timestamp PRIMARY KEY NOT NULL,
79
"attempts" integer NOT NULL,

0 commit comments

Comments
 (0)