Skip to content

Commit c237c42

Browse files
waleedlatif1claude
andcommitted
fix(usage): mark finished runs whose hour may be computed, make rollup migrations atomic
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 994babd commit c237c42

8 files changed

Lines changed: 72 additions & 16 deletions

File tree

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

Lines changed: 20 additions & 1 deletion
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,
@@ -81,6 +87,19 @@ export async function markWorkflowActivityDirty(
8187
}
8288
}
8389

90+
/**
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.
97+
*/
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])
101+
}
102+
84103
/**
85104
* Marks the cells of runs that ended at least two hours after they started since the last scan,
86105
* and moves the scan forward. Their hours were computed before they ended (HITL runs resumed

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

Lines changed: 1 addition & 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

‎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: 35 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 { markFinishedRunDirty } from '@/lib/billing/activity-rollup/marks'
5153
import {
5254
type ActivityRollupPassOptions,
5355
markStaleHours,
@@ -634,6 +636,29 @@ describe('organization activity rollup', () => {
634636
await expectEquivalent()
635637
}, 120_000)
636638

639+
it('reads a completion committed after the scan passed its stamped end live at once', async () => {
640+
const run = await oneLog(
641+
`status = 'running' AND started_at < (now() AT TIME ZONE 'UTC') - interval '3 days'`
642+
)
643+
// The end is stamped when the run finished, so its write lands behind the late-end scan.
644+
await database.transaction(async (tx) => {
645+
const [finished] = await tx
646+
.update(schema.workflowExecutionLogs)
647+
.set({
648+
status: 'completed',
649+
totalDurationMs: 1800,
650+
endedAt: sql`${schema.workflowExecutionLogs.startedAt} + interval '30 minutes'`,
651+
})
652+
.where(eq(schema.workflowExecutionLogs.id, run.id))
653+
.returning()
654+
if (!finished) throw new Error('No run to finish')
655+
await markFinishedRunDirty(tx, finished)
656+
})
657+
await expectEquivalent()
658+
await runPass()
659+
await expectEquivalent()
660+
}, 120_000)
661+
637662
it('runs one pass at a time and rewrites nothing when run again', async () => {
638663
const results = await Promise.all([runPass(), runPass()])
639664
expect(results.map((result) => result.status).sort()).toEqual(['leased', 'ran'])
@@ -711,13 +736,16 @@ describe('organization activity rollup', () => {
711736
FOR EACH ROW WHEN (NEW.bucket_start = '${failing.toISOString().replace('T', ' ').slice(0, 19)}')
712737
EXECUTE FUNCTION fail_rollup_write();
713738
`)
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-
)
739+
try {
740+
await expect(runPass()).rejects.toThrow()
741+
const crashed = await readRollupState()
742+
expect(crashed?.coverageStart?.getTime()).toBeGreaterThan(failing.getTime())
743+
expect(crashed?.leaseOwner).toBeNull()
744+
} finally {
745+
await connection.unsafe(
746+
`DROP TRIGGER fail_rollup_write ON workflow_activity_hourly; DROP FUNCTION fail_rollup_write()`
747+
)
748+
}
721749
expect((await runPass()).backfillComplete).toBe(true)
722750
await expectEquivalent()
723751
}, 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 { markFinishedRunDirty } 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 markFinishedRunDirty(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,

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
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
57
ALTER TABLE "activity_rollup_dirty" ADD COLUMN "attempts" integer DEFAULT 0 NOT NULL;--> statement-breakpoint
68
ALTER TABLE "activity_rollup_state" ADD COLUMN "failed_passes" integer DEFAULT 0 NOT NULL;--> statement-breakpoint
79
ALTER TABLE "activity_rollup_state" ADD COLUMN "corrections_at" timestamp with time zone;

0 commit comments

Comments
 (0)