Skip to content

Commit e24dcc5

Browse files
authored
fix(realtime): cap batch operation frames and persist positions in one statement (#10497)
Batch workflow operations were accepted with unbounded arrays and persisted one awaited statement per entry inside the transaction that holds the workflow row lock, so a single frame could pin a pooled realtime connection for minutes. - cap every batch array in the realtime protocol schema (blocks 2,000, edges 10,000, subblock updates 10,000), matching the workflow graph limits - write batch positions with one UPDATE ... FROM (VALUES ...), last entry wins - write subblock batch updates once per touched block instead of once per entry
1 parent a14df32 commit e24dcc5

4 files changed

Lines changed: 317 additions & 54 deletions

File tree

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
/** Real PostgreSQL coverage: batch position writes stay in their workflow with the last entry winning; batch subblock writes chain per block. */
2+
import { db } from '@sim/db'
3+
import { user, workflow, workflowBlocks, workspace } from '@sim/db/schema'
4+
import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures'
5+
import {
6+
BLOCKS_OPERATIONS,
7+
OPERATION_TARGETS,
8+
SUBBLOCK_OPERATIONS,
9+
} from '@sim/realtime-protocol/constants'
10+
import { generateId } from '@sim/utils/id'
11+
import { eq, inArray } from 'drizzle-orm'
12+
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
13+
import { persistWorkflowOperation } from '@/database/operations'
14+
15+
const userId = generateId()
16+
const workspaceId = generateId()
17+
const workflowId = generateId()
18+
const otherWorkflowId = generateId()
19+
const ids = { moved: generateId(), still: generateId(), foreign: generateId() }
20+
21+
function persist(target: string, operation: string, payload: unknown) {
22+
return persistWorkflowOperation(workflowId, {
23+
target,
24+
operation,
25+
payload,
26+
timestamp: Date.now(),
27+
userId,
28+
})
29+
}
30+
31+
async function readBlocks() {
32+
const rows = await db
33+
.select()
34+
.from(workflowBlocks)
35+
.where(inArray(workflowBlocks.id, Object.values(ids)))
36+
return Object.fromEntries(rows.map((row) => [row.id, row]))
37+
}
38+
39+
describe('batch writes against PostgreSQL', () => {
40+
beforeAll(async () => {
41+
const now = new Date()
42+
await db.insert(user).values({
43+
id: userId,
44+
name: 'Batch fixture',
45+
email: `${userId}@batch-writes.test`,
46+
emailVerified: true,
47+
createdAt: now,
48+
updatedAt: now,
49+
})
50+
await insertWorkspaceFixture(db, {
51+
id: workspaceId,
52+
name: 'Batch target',
53+
ownerId: userId,
54+
billedAccountUserId: userId,
55+
})
56+
await db.insert(workflow).values(
57+
[workflowId, otherWorkflowId].map((id) => ({
58+
id,
59+
userId,
60+
workspaceId,
61+
name: id,
62+
lastSynced: now,
63+
createdAt: now,
64+
updatedAt: now,
65+
}))
66+
)
67+
})
68+
69+
beforeEach(async () => {
70+
await db.delete(workflowBlocks).where(inArray(workflowBlocks.id, Object.values(ids)))
71+
await db.insert(workflowBlocks).values(
72+
[
73+
{ id: ids.moved, workflowId },
74+
{ id: ids.still, workflowId },
75+
{ id: ids.foreign, workflowId: otherWorkflowId },
76+
].map((row) => ({
77+
...row,
78+
type: 'function',
79+
name: row.id,
80+
positionX: '0',
81+
positionY: '0',
82+
subBlocks: { code: { id: 'code', type: 'code', value: 'a' } },
83+
}))
84+
)
85+
})
86+
87+
afterAll(async () => {
88+
await deleteWorkspaceFixture(db, eq(workspace.ownerId, userId))
89+
await db.delete(user).where(eq(user.id, userId))
90+
})
91+
92+
it('moves only this workflow’s blocks, the last entry for a block winning', async () => {
93+
await persist(OPERATION_TARGETS.BLOCKS, BLOCKS_OPERATIONS.BATCH_UPDATE_POSITIONS, {
94+
updates: [
95+
{ id: ids.moved, position: { x: 1, y: 1 } },
96+
{ id: ids.foreign, position: { x: 9, y: 9 } },
97+
{ id: generateId(), position: { x: 9, y: 9 } },
98+
{ id: ids.moved, position: { x: 12.5, y: -40 } },
99+
],
100+
})
101+
102+
const blocks = await readBlocks()
103+
const position = (id: string) => [Number(blocks[id].positionX), Number(blocks[id].positionY)]
104+
expect(position(ids.moved)).toEqual([12.5, -40])
105+
expect(position(ids.still)).toEqual([0, 0])
106+
expect(position(ids.foreign)).toEqual([0, 0])
107+
})
108+
109+
it('applies repeated entries for one block in order, each seeing the one before', async () => {
110+
await persist(OPERATION_TARGETS.SUBBLOCK, SUBBLOCK_OPERATIONS.BATCH_UPDATE, {
111+
updates: [
112+
{ blockId: ids.moved, subblockId: 'code', value: 'b', expectedValue: 'a' },
113+
{ blockId: ids.moved, subblockId: 'prompt', value: 'p' },
114+
{ blockId: ids.moved, subblockId: 'code', value: 'c', expectedValue: 'b' },
115+
{ blockId: ids.still, subblockId: 'code', value: 'd' },
116+
],
117+
})
118+
119+
const blocks = await readBlocks()
120+
expect(blocks[ids.moved].subBlocks).toEqual({
121+
code: { id: 'code', type: 'code', value: 'c' },
122+
prompt: { id: 'prompt', type: 'unknown', value: 'p' },
123+
})
124+
expect(blocks[ids.still].subBlocks).toEqual({ code: { id: 'code', type: 'code', value: 'd' } })
125+
})
126+
})

‎apps/realtime/src/database/operations.ts‎

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -945,22 +945,24 @@ async function handleBlocksOperationTx(
945945
switch (operation) {
946946
case BLOCKS_OPERATIONS.BATCH_UPDATE_POSITIONS: {
947947
const { updates } = payload
948-
if (!Array.isArray(updates) || updates.length === 0) {
949-
return
950-
}
951-
952-
for (const update of updates) {
953-
const { id, position } = update
954-
if (!id || !position) continue
948+
if (!Array.isArray(updates)) return
955949

956-
await tx
957-
.update(workflowBlocks)
958-
.set({
959-
positionX: position.x,
960-
positionY: position.y,
961-
})
962-
.where(and(eq(workflowBlocks.id, id), eq(workflowBlocks.workflowId, workflowId)))
950+
// UPDATE ... FROM applies an arbitrary row for a repeated id, so keep the last entry for each.
951+
const positions = new Map<string, { x: number; y: number }>()
952+
for (const { id, position } of updates) {
953+
if (id && position) positions.set(id, position)
963954
}
955+
if (positions.size === 0) return
956+
957+
const moved = sql.join(
958+
Array.from(positions, ([id, { x, y }]) => sql`(${id}, ${x}::numeric, ${y}::numeric)`),
959+
sql`, `
960+
)
961+
await tx
962+
.update(workflowBlocks)
963+
.set({ positionX: sql`moved.x`, positionY: sql`moved.y` })
964+
.from(sql`(VALUES ${moved}) AS moved(id, x, y)`)
965+
.where(and(eq(workflowBlocks.id, sql`moved.id`), eq(workflowBlocks.workflowId, workflowId)))
964966
break
965967
}
966968

@@ -2023,6 +2025,7 @@ async function handleSubblockOperationTx(
20232025
}
20242026

20252027
const blocksById = await loadSubblockUpdateBlocks(tx, workflowId)
2028+
const changedBlockIds = new Set<string>()
20262029

20272030
for (const update of updates) {
20282031
const { blockId, subblockId, value, expectedValue } = update
@@ -2044,15 +2047,18 @@ async function handleSubblockOperationTx(
20442047
? { ...currentSubBlock, value }
20452048
: { id: subblockId, type: 'unknown', value }
20462049

2050+
blocksById[blockId] = { ...block, subBlocks }
2051+
changedBlockIds.add(blockId)
2052+
}
2053+
2054+
for (const blockId of changedBlockIds) {
20472055
await tx
20482056
.update(workflowBlocks)
20492057
.set({
2050-
subBlocks,
2058+
subBlocks: blocksById[blockId].subBlocks,
20512059
updatedAt: new Date(),
20522060
})
20532061
.where(and(eq(workflowBlocks.id, blockId), eq(workflowBlocks.workflowId, workflowId)))
2054-
2055-
blocksById[blockId] = { ...block, subBlocks }
20562062
}
20572063

20582064
logger.debug(`Batch updated ${updates.length} subblocks for workflow ${workflowId}`)
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import { describe, expect, it } from 'vitest'
2+
import {
3+
BLOCKS_OPERATIONS,
4+
EDGES_OPERATIONS,
5+
OPERATION_TARGETS,
6+
SUBBLOCK_OPERATIONS,
7+
} from './constants'
8+
import { WorkflowOperationSchema } from './schemas'
9+
10+
const position = { x: 0, y: 0 }
11+
const edge = { id: 'e', source: 'a', target: 'b' }
12+
const many = <T>(count: number, entry: T) => Array.from({ length: count }, () => entry)
13+
14+
/** Each batch frame with `count` entries in its capped array, and the cap it must hold to. */
15+
const batches: Array<{
16+
operation: string
17+
field: string
18+
target: string
19+
cap: number
20+
payload: (count: number) => object
21+
}> = [
22+
{
23+
operation: BLOCKS_OPERATIONS.BATCH_UPDATE_POSITIONS,
24+
field: 'updates',
25+
target: OPERATION_TARGETS.BLOCKS,
26+
cap: 2_000,
27+
payload: (n) => ({ updates: many(n, { id: 'b', position }) }),
28+
},
29+
{
30+
operation: BLOCKS_OPERATIONS.BATCH_ADD_BLOCKS,
31+
field: 'blocks',
32+
target: OPERATION_TARGETS.BLOCKS,
33+
cap: 2_000,
34+
payload: (n) => ({ blocks: many(n, { id: 'b' }) }),
35+
},
36+
{
37+
operation: BLOCKS_OPERATIONS.BATCH_ADD_BLOCKS,
38+
field: 'edges',
39+
target: OPERATION_TARGETS.BLOCKS,
40+
cap: 10_000,
41+
payload: (n) => ({ blocks: [], edges: many(n, edge) }),
42+
},
43+
{
44+
operation: BLOCKS_OPERATIONS.BATCH_REMOVE_BLOCKS,
45+
field: 'ids',
46+
target: OPERATION_TARGETS.BLOCKS,
47+
cap: 2_000,
48+
payload: (n) => ({ ids: many(n, 'b') }),
49+
},
50+
...[
51+
BLOCKS_OPERATIONS.BATCH_TOGGLE_ENABLED,
52+
BLOCKS_OPERATIONS.BATCH_TOGGLE_HANDLES,
53+
BLOCKS_OPERATIONS.BATCH_TOGGLE_LOCKED,
54+
].map((operation) => ({
55+
operation,
56+
field: 'blockIds',
57+
target: OPERATION_TARGETS.BLOCKS,
58+
cap: 2_000,
59+
payload: (n: number) => ({
60+
blockIds: many(n, 'b'),
61+
previousStates: {},
62+
}),
63+
})),
64+
{
65+
operation: BLOCKS_OPERATIONS.BATCH_UPDATE_PARENT,
66+
field: 'updates',
67+
target: OPERATION_TARGETS.BLOCKS,
68+
cap: 2_000,
69+
payload: (n) => ({
70+
updates: many(n, { id: 'b', parentId: 'p', position }),
71+
}),
72+
},
73+
{
74+
operation: EDGES_OPERATIONS.BATCH_ADD_EDGES,
75+
field: 'edges',
76+
target: OPERATION_TARGETS.EDGES,
77+
cap: 10_000,
78+
payload: (n) => ({ edges: many(n, edge) }),
79+
},
80+
{
81+
operation: EDGES_OPERATIONS.BATCH_REMOVE_EDGES,
82+
field: 'ids',
83+
target: OPERATION_TARGETS.EDGES,
84+
cap: 10_000,
85+
payload: (n) => ({ ids: many(n, 'e') }),
86+
},
87+
{
88+
operation: SUBBLOCK_OPERATIONS.BATCH_UPDATE,
89+
field: 'updates',
90+
target: OPERATION_TARGETS.SUBBLOCK,
91+
cap: 10_000,
92+
payload: (n) => ({
93+
updates: many(n, { blockId: 'b', subblockId: 's', value: 1 }),
94+
}),
95+
},
96+
]
97+
98+
describe('WorkflowOperationSchema batch caps', () => {
99+
it.each(batches)(
100+
'caps $operation $field at $cap entries',
101+
({ operation, target, cap, payload }) => {
102+
const frame = (count: number) => ({
103+
operation,
104+
target,
105+
payload: payload(count),
106+
timestamp: 1,
107+
})
108+
expect(WorkflowOperationSchema.safeParse(frame(cap)).success).toBe(true)
109+
expect(WorkflowOperationSchema.safeParse(frame(cap + 1)).success).toBe(false)
110+
}
111+
)
112+
})

0 commit comments

Comments
 (0)