Skip to content

Commit cda9499

Browse files
authored
feat(usage): serve organization activity from an hourly rollup (#10200)
* feat(usage): serve organization activity from an hourly rollup * fix(usage): type the rollup marking hook, bump the chart version * fix(usage): address review: replica lag, retention marks, deferred chats, bounded housekeeping * fix(usage): measure replica lag with the pass's own lease as heartbeat
1 parent f9c4d7b commit cda9499

34 files changed

Lines changed: 70427 additions & 88 deletions

‎apps/docs/content/docs/platform/self-hosting/background-jobs.mdx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ Create a workflow with a Schedule trigger set to every minute, deploy it, and wa
173173
| Outbox processing | `/api/webhooks/outbox/process` | `*/1 * * * *` | Transactional-outbox retries for billing, membership, enterprise issuance, and workflow-deployment side effects |
174174
| Workspace file search dispatch | `/api/cron/workspace-file-search-dispatch` | `*/1 * * * *` | Dispatches indexing work for workspace file search |
175175
| Knowledge projection | `/api/cron/knowledge-projection` | `*/1 * * * *` | Brings knowledge base search up to date with document, permission, and chunk changes |
176+
| Activity rollup | `/api/cron/activity-rollup` | `*/2 * * * *` | Maintains the hourly workflow activity rollup that serves organization activity; idle unless `ACTIVITY_ROLLUP_MAINTENANCE` is set |
176177
| Table row-change fold | `/api/cron/fold-table-row-changes` | `*/1 * * * *` | Folds the table row-change log into each table's stored row count and version |
177178
| Connector sync | `/api/knowledge/connectors/sync` | `*/5 * * * *` | Knowledge base connector syncs |
178179
| Connector member sync | `/api/knowledge/connectors/member-sync` | `*/5 * * * *` | Per-member content/access sync for indexed connectors; live Search sources are skipped |
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { createLogger } from '@sim/logger'
2+
import { getErrorMessage } from '@sim/utils/errors'
3+
import { type NextRequest, NextResponse } from 'next/server'
4+
import { verifyCronAuth } from '@/lib/auth/internal'
5+
import { enqueueActivityRollupPass } from '@/lib/billing/activity-rollup/enqueue'
6+
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
7+
8+
const logger = createLogger('ActivityRollupCronRoute')
9+
10+
export const dynamic = 'force-dynamic'
11+
export const maxDuration = 60
12+
13+
/**
14+
* The activity rollup's cron: enqueues one maintenance pass per window while the
15+
* `activity-rollup-maintenance` flag is on, and returns once Trigger.dev accepts it.
16+
*/
17+
export const GET = withRouteHandler(async (request: NextRequest) => {
18+
const authError = verifyCronAuth(request, 'Activity rollup')
19+
if (authError) return authError
20+
21+
try {
22+
const result = await enqueueActivityRollupPass()
23+
return NextResponse.json({ success: true, ...result }, { status: result.triggered ? 202 : 200 })
24+
} catch (error) {
25+
logger.error('Activity rollup enqueue failed', { error: getErrorMessage(error) })
26+
return NextResponse.json({ success: false, error: 'Enqueue failed' }, { status: 500 })
27+
}
28+
})
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { task } from '@trigger.dev/sdk'
2+
import {
3+
ACTIVITY_ROLLUP_TASK_ID,
4+
runActivityRollupMaintenance,
5+
} from '@/lib/billing/activity-rollup/enqueue'
6+
7+
/**
8+
* Runs one activity rollup pass. One runs at a time; the cron enqueues one every two minutes, so a
9+
* failed pass is not retried: the next one starts from the state the failed one committed, since
10+
* every hour is written together with the progress it completes.
11+
*/
12+
export const activityRollupTask = task({
13+
id: ACTIVITY_ROLLUP_TASK_ID,
14+
machine: 'small-1x',
15+
maxDuration: 5 * 60,
16+
retry: { maxAttempts: 1 },
17+
queue: { name: ACTIVITY_ROLLUP_TASK_ID, concurrencyLimit: 1 },
18+
run: async () => runActivityRollupMaintenance(),
19+
})

‎apps/sim/background/cleanup-logs-files.test.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,15 @@ const payload = {
2929
retentionHours: 720,
3030
workspaceIds: ['workspace-1'],
3131
}
32+
const startedAt = new Date('2026-01-01T10:00:00.000Z')
3233
const rows = [
33-
{ id: 'log-1', files: [{ key: 'file-a' }, { key: 'file-b' }] },
34-
{ id: 'log-2', files: [{ key: 'file-c' }] },
34+
{
35+
id: 'log-1',
36+
files: [{ key: 'file-a' }, { key: 'file-b' }],
37+
workspaceId: 'workspace-1',
38+
startedAt,
39+
},
40+
{ id: 'log-2', files: [{ key: 'file-c' }], workspaceId: 'workspace-1', startedAt },
3541
]
3642

3743
describe('bounded log cleanup file failures', () => {

‎apps/sim/background/cleanup-logs.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,8 @@ describe('cleanup logs worker', () => {
105105
expect(dbChainMockFns.select).toHaveBeenCalledWith({
106106
id: schemaMock.workflowExecutionLogs.id,
107107
files: schemaMock.workflowExecutionLogs.files,
108+
workspaceId: schemaMock.workflowExecutionLogs.workspaceId,
109+
startedAt: schemaMock.workflowExecutionLogs.startedAt,
108110
})
109111
expect(dbChainMockFns.execute).not.toHaveBeenCalled()
110112
expect(mockDeleteFiles).toHaveBeenCalledWith(
@@ -159,6 +161,8 @@ describe('cleanup logs worker', () => {
159161
expect(dbChainMockFns.select).toHaveBeenCalledWith({
160162
id: schemaMock.workflowExecutionLogs.id,
161163
files: schemaMock.workflowExecutionLogs.files,
164+
workspaceId: schemaMock.workflowExecutionLogs.workspaceId,
165+
startedAt: schemaMock.workflowExecutionLogs.startedAt,
162166
})
163167
expect(dbChainMockFns.select).not.toHaveBeenCalledWith(
164168
expect.objectContaining({ executionData: expect.anything() })

‎apps/sim/background/cleanup-logs.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { createLogger } from '@sim/logger'
1212
import { chunkArray } from '@sim/utils/helpers'
1313
import { task } from '@trigger.dev/sdk'
1414
import { and, asc, eq, inArray, isNull, lt, notInArray, or, sql } from 'drizzle-orm'
15+
import { markWorkflowActivityDirty } from '@/lib/billing/activity-rollup/marks'
1516
import { type CleanupJobPayload, runCleanupWithLimits } from '@/lib/billing/cleanup-dispatcher'
1617
import {
1718
batchDeleteByWorkspaceAndTimestamp,
@@ -415,6 +416,8 @@ async function cleanupWorkflowExecutionLogs(
415416
.select({
416417
id: workflowExecutionLogs.id,
417418
files: workflowExecutionLogs.files,
419+
workspaceId: workflowExecutionLogs.workspaceId,
420+
startedAt: workflowExecutionLogs.startedAt,
418421
})
419422
.from(workflowExecutionLogs)
420423
.leftJoin(
@@ -438,6 +441,7 @@ async function cleanupWorkflowExecutionLogs(
438441
if (budget && fileStats.filesDeleteFailed) throw new Error('Log file cleanup failed')
439442
}
440443
},
444+
afterDelete: (tx, rows) => markWorkflowActivityDirty(tx, rows),
441445
batchSize: WORKFLOW_LOG_CLEANUP_BATCH_SIZE,
442446
maxBatches: WORKFLOW_LOG_CLEANUP_MAX_BATCHES,
443447
totalRowLimit: WORKFLOW_LOG_CLEANUP_ROW_LIMIT,
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import { describe, expect, it, vi } from 'vitest'
2+
import { type ActivityCell, aggregateHour } from '@/lib/billing/activity-rollup/cells'
3+
import type { InstantRange } from '@/lib/billing/activity-rollup/source'
4+
5+
const HOUR = 60 * 60 * 1000
6+
const hour = new Date('2026-05-01T10:00:00.000Z')
7+
8+
function cell(workflowId: string, runs: number, durationSumMs: number): ActivityCell {
9+
return {
10+
workspaceId: 'ws',
11+
workflowId,
12+
trigger: 'api',
13+
runs,
14+
completed: runs,
15+
failed: 0,
16+
cancelled: 0,
17+
inFlight: 0,
18+
durationSumMs,
19+
durationCount: runs,
20+
}
21+
}
22+
23+
function cancellation(message: string, code: string) {
24+
return Object.assign(new Error(message), { code })
25+
}
26+
27+
describe('aggregateHour', () => {
28+
it.each([
29+
['times out', cancellation('canceling statement due to statement timeout', '57014')],
30+
[
31+
'is cancelled by replica recovery',
32+
cancellation('canceling statement due to conflict with recovery', '40001'),
33+
],
34+
])(
35+
'reads an hour whose whole read %s in quarter-hour slices summed by cell',
36+
async (_, error) => {
37+
const read = vi.fn(async (range: InstantRange) => {
38+
if (range.to.getTime() - range.from.getTime() === HOUR) throw error
39+
const quarter = (range.from.getTime() - hour.getTime()) / (HOUR / 4)
40+
return quarter === 2 ? [cell('a', 1, 10), cell('b', 2, 30)] : [cell('a', 1, 5)]
41+
})
42+
43+
const cells = await aggregateHour(hour, read)
44+
45+
expect(read.mock.calls.map(([range]) => range.from.toISOString())).toEqual([
46+
'2026-05-01T10:00:00.000Z',
47+
'2026-05-01T10:00:00.000Z',
48+
'2026-05-01T10:15:00.000Z',
49+
'2026-05-01T10:30:00.000Z',
50+
'2026-05-01T10:45:00.000Z',
51+
])
52+
expect(read.mock.calls.at(-1)?.[0].to.toISOString()).toBe('2026-05-01T11:00:00.000Z')
53+
expect(cells).toEqual([cell('a', 4, 25), cell('b', 2, 30)])
54+
}
55+
)
56+
57+
it('fails without slicing when the read fails for any other reason', async () => {
58+
const read = vi.fn(async () => {
59+
throw cancellation('relation "workflow_execution_logs" does not exist', '42P01')
60+
})
61+
62+
await expect(aggregateHour(hour, read)).rejects.toThrow('does not exist')
63+
expect(read).toHaveBeenCalledTimes(1)
64+
})
65+
})

0 commit comments

Comments
 (0)