Skip to content

Commit 59ea17b

Browse files
waleedlatif1claude
andcommitted
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>
1 parent c237c42 commit 59ea17b

6 files changed

Lines changed: 45 additions & 33 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: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ const logger = createLogger('ActivityRollupMarks')
2727
/**
2828
* How far behind now the late-end scan stays: an end is stamped by the app before its write
2929
* commits, so the scan only consumes ends old enough that every write stamped with them is
30-
* 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}).
3132
*/
3233
export const LATE_END_SCAN_MARGIN_MS = 5 * 60 * 1000
3334

@@ -45,7 +46,8 @@ interface ChangedRun {
4546
/**
4647
* Marks the rollup cells of `runs` for recomputing, in the caller's transaction so the marks
4748
* commit exactly when the change does. For changes the rollup pass cannot see on its own:
48-
* 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}).
4951
*
5052
* Runs in a savepoint and never throws: a mark that fails (the table missing mid-deploy) is logged
5153
* and the caller's change goes ahead, so retention and resumes behave exactly as without the
@@ -87,17 +89,20 @@ export async function markWorkflowActivityDirty(
8789
}
8890
}
8991

92+
/** Runs younger than this lie in hours not computed yet: the settle lag less an hour of clock margin. */
93+
const FINISHED_RUN_MARK_AGE_MS = ACTIVITY_ROLLUP_SETTLE_MS - HOUR_MS
94+
9095
/**
91-
* Marks the cell of a run whose final status is being written, in the transaction that writes it,
92-
* when the run's hour may already be computed (it started at least the settle lag, less an hour of
93-
* clock margin, ago). The run's end is stamped when it finishes, before masking and usage
94-
* recording, so its write can commit after the late-end scan has passed that end, or after its
95-
* hour was computed without a late end at all; the mark leaves neither to the in-flight recheck.
96-
* Younger runs lie in hours not computed yet, and are not marked.
96+
* Marks the cells of runs whose final status is being written, in the transaction that writes it,
97+
* when their hours may already be computed. Their ends were stamped before the write, so it can
98+
* commit after the late-end scan passed the end, or after the hour was computed without a late end.
9799
*/
98-
export async function markFinishedRunDirty(tx: DbTransaction, run: ChangedRun): Promise<void> {
99-
if (Date.now() - run.startedAt.getTime() < ACTIVITY_ROLLUP_SETTLE_MS - HOUR_MS) return
100-
await markWorkflowActivityDirty(tx, [run])
100+
export async function markFinishedRunsDirty(tx: DbTransaction, runs: ChangedRun[]): Promise<void> {
101+
const settled = Date.now() - FINISHED_RUN_MARK_AGE_MS
102+
await markWorkflowActivityDirty(
103+
tx,
104+
runs.filter((run) => run.startedAt.getTime() <= settled)
105+
)
101106
}
102107

103108
/**

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

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ vi.mock('@/lib/billing/core/usage-segment-cache', () => ({
4949
},
5050
}))
5151

52-
import { markFinishedRunDirty } from '@/lib/billing/activity-rollup/marks'
52+
import { markFinishedRunsDirty } from '@/lib/billing/activity-rollup/marks'
5353
import {
5454
type ActivityRollupPassOptions,
5555
markStaleHours,
@@ -636,11 +636,10 @@ describe('organization activity rollup', () => {
636636
await expectEquivalent()
637637
}, 120_000)
638638

639-
it('reads a completion committed after the scan passed its stamped end live at once', async () => {
639+
it('marks a late-committing completion so its computed hour reads live', async () => {
640640
const run = await oneLog(
641641
`status = 'running' AND started_at < (now() AT TIME ZONE 'UTC') - interval '3 days'`
642642
)
643-
// The end is stamped when the run finished, so its write lands behind the late-end scan.
644643
await database.transaction(async (tx) => {
645644
const [finished] = await tx
646645
.update(schema.workflowExecutionLogs)
@@ -652,7 +651,7 @@ describe('organization activity rollup', () => {
652651
.where(eq(schema.workflowExecutionLogs.id, run.id))
653652
.returning()
654653
if (!finished) throw new Error('No run to finish')
655-
await markFinishedRunDirty(tx, finished)
654+
await markFinishedRunsDirty(tx, [finished])
656655
})
657656
await expectEquivalent()
658657
await runPass()

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +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 { markFinishedRunDirty } from '@/lib/billing/activity-rollup/marks'
20+
import { markFinishedRunsDirty } from '@/lib/billing/activity-rollup/marks'
2121
import { checkUsageStatus as checkResolvedUsageStatus } from '@/lib/billing/calculations/usage-monitor'
2222
import { type BillingAttributionSnapshot, toBillingContext } from '@/lib/billing/core/attribution'
2323
import { readSoftGateUsageCost } from '@/lib/billing/core/reporting-usage-cache'
@@ -1375,7 +1375,7 @@ export class ExecutionLogger {
13751375
},
13761376
completedExecutionLargeValueKeys
13771377
)
1378-
await markFinishedRunDirty(tx, log)
1378+
await markFinishedRunsDirty(tx, [log])
13791379

13801380
return { updatedLog: log, completionPersisted: true }
13811381
})

‎packages/db/migrations/0465_activity_rollup_correction_state.sql‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
-- last ran (reads require it to be recent), and per-mark failure attempts. Columns on the one-row
33
-- activity_rollup_state and the small activity_rollup_dirty queue, each nullable or with a
44
-- constant DEFAULT, so every ADD COLUMN is metadata-only.
5-
-- Earlier concurrent-index migrations end the batch transaction; keep these columns and their journal row atomic.
6-
BEGIN;--> statement-breakpoint
75
ALTER TABLE "activity_rollup_dirty" ADD COLUMN "attempts" integer DEFAULT 0 NOT NULL;--> statement-breakpoint
86
ALTER TABLE "activity_rollup_state" ADD COLUMN "failed_passes" integer DEFAULT 0 NOT NULL;--> statement-breakpoint
97
ALTER TABLE "activity_rollup_state" ADD COLUMN "corrections_at" timestamp with time zone;

0 commit comments

Comments
 (0)