From 2ba4d0b977dd5a3a40f07f79cd4b0e9b291ed1ed Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Sat, 28 Nov 2026 12:39:47 -0800 Subject: [PATCH] fix(realtime): cap batch operation frames and persist positions in one statement 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 --- .../src/database/batch-writes.integration.ts | 126 ++++++++++++++++++ apps/realtime/src/database/operations.ts | 40 +++--- .../realtime-protocol/src/schemas.test.ts | 112 ++++++++++++++++ packages/realtime-protocol/src/schemas.ts | 93 ++++++++----- 4 files changed, 317 insertions(+), 54 deletions(-) create mode 100644 apps/realtime/src/database/batch-writes.integration.ts create mode 100644 packages/realtime-protocol/src/schemas.test.ts diff --git a/apps/realtime/src/database/batch-writes.integration.ts b/apps/realtime/src/database/batch-writes.integration.ts new file mode 100644 index 00000000000..a80862d632f --- /dev/null +++ b/apps/realtime/src/database/batch-writes.integration.ts @@ -0,0 +1,126 @@ +/** Real PostgreSQL coverage: batch position writes stay in their workflow with the last entry winning; batch subblock writes chain per block. */ +import { db } from '@sim/db' +import { user, workflow, workflowBlocks, workspace } from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { + BLOCKS_OPERATIONS, + OPERATION_TARGETS, + SUBBLOCK_OPERATIONS, +} from '@sim/realtime-protocol/constants' +import { generateId } from '@sim/utils/id' +import { eq, inArray } from 'drizzle-orm' +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' +import { persistWorkflowOperation } from '@/database/operations' + +const userId = generateId() +const workspaceId = generateId() +const workflowId = generateId() +const otherWorkflowId = generateId() +const ids = { moved: generateId(), still: generateId(), foreign: generateId() } + +function persist(target: string, operation: string, payload: unknown) { + return persistWorkflowOperation(workflowId, { + target, + operation, + payload, + timestamp: Date.now(), + userId, + }) +} + +async function readBlocks() { + const rows = await db + .select() + .from(workflowBlocks) + .where(inArray(workflowBlocks.id, Object.values(ids))) + return Object.fromEntries(rows.map((row) => [row.id, row])) +} + +describe('batch writes against PostgreSQL', () => { + beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: userId, + name: 'Batch fixture', + email: `${userId}@batch-writes.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await insertWorkspaceFixture(db, { + id: workspaceId, + name: 'Batch target', + ownerId: userId, + billedAccountUserId: userId, + }) + await db.insert(workflow).values( + [workflowId, otherWorkflowId].map((id) => ({ + id, + userId, + workspaceId, + name: id, + lastSynced: now, + createdAt: now, + updatedAt: now, + })) + ) + }) + + beforeEach(async () => { + await db.delete(workflowBlocks).where(inArray(workflowBlocks.id, Object.values(ids))) + await db.insert(workflowBlocks).values( + [ + { id: ids.moved, workflowId }, + { id: ids.still, workflowId }, + { id: ids.foreign, workflowId: otherWorkflowId }, + ].map((row) => ({ + ...row, + type: 'function', + name: row.id, + positionX: '0', + positionY: '0', + subBlocks: { code: { id: 'code', type: 'code', value: 'a' } }, + })) + ) + }) + + afterAll(async () => { + await deleteWorkspaceFixture(db, eq(workspace.ownerId, userId)) + await db.delete(user).where(eq(user.id, userId)) + }) + + it('moves only this workflow’s blocks, the last entry for a block winning', async () => { + await persist(OPERATION_TARGETS.BLOCKS, BLOCKS_OPERATIONS.BATCH_UPDATE_POSITIONS, { + updates: [ + { id: ids.moved, position: { x: 1, y: 1 } }, + { id: ids.foreign, position: { x: 9, y: 9 } }, + { id: generateId(), position: { x: 9, y: 9 } }, + { id: ids.moved, position: { x: 12.5, y: -40 } }, + ], + }) + + const blocks = await readBlocks() + const position = (id: string) => [Number(blocks[id].positionX), Number(blocks[id].positionY)] + expect(position(ids.moved)).toEqual([12.5, -40]) + expect(position(ids.still)).toEqual([0, 0]) + expect(position(ids.foreign)).toEqual([0, 0]) + }) + + it('applies repeated entries for one block in order, each seeing the one before', async () => { + await persist(OPERATION_TARGETS.SUBBLOCK, SUBBLOCK_OPERATIONS.BATCH_UPDATE, { + updates: [ + { blockId: ids.moved, subblockId: 'code', value: 'b', expectedValue: 'a' }, + { blockId: ids.moved, subblockId: 'prompt', value: 'p' }, + { blockId: ids.moved, subblockId: 'code', value: 'c', expectedValue: 'b' }, + { blockId: ids.still, subblockId: 'code', value: 'd' }, + ], + }) + + const blocks = await readBlocks() + expect(blocks[ids.moved].subBlocks).toEqual({ + code: { id: 'code', type: 'code', value: 'c' }, + prompt: { id: 'prompt', type: 'unknown', value: 'p' }, + }) + expect(blocks[ids.still].subBlocks).toEqual({ code: { id: 'code', type: 'code', value: 'd' } }) + }) +}) diff --git a/apps/realtime/src/database/operations.ts b/apps/realtime/src/database/operations.ts index 284677af888..116e1d18c92 100644 --- a/apps/realtime/src/database/operations.ts +++ b/apps/realtime/src/database/operations.ts @@ -945,22 +945,24 @@ async function handleBlocksOperationTx( switch (operation) { case BLOCKS_OPERATIONS.BATCH_UPDATE_POSITIONS: { const { updates } = payload - if (!Array.isArray(updates) || updates.length === 0) { - return - } - - for (const update of updates) { - const { id, position } = update - if (!id || !position) continue + if (!Array.isArray(updates)) return - await tx - .update(workflowBlocks) - .set({ - positionX: position.x, - positionY: position.y, - }) - .where(and(eq(workflowBlocks.id, id), eq(workflowBlocks.workflowId, workflowId))) + // UPDATE ... FROM applies an arbitrary row for a repeated id, so keep the last entry for each. + const positions = new Map() + for (const { id, position } of updates) { + if (id && position) positions.set(id, position) } + if (positions.size === 0) return + + const moved = sql.join( + Array.from(positions, ([id, { x, y }]) => sql`(${id}, ${x}::numeric, ${y}::numeric)`), + sql`, ` + ) + await tx + .update(workflowBlocks) + .set({ positionX: sql`moved.x`, positionY: sql`moved.y` }) + .from(sql`(VALUES ${moved}) AS moved(id, x, y)`) + .where(and(eq(workflowBlocks.id, sql`moved.id`), eq(workflowBlocks.workflowId, workflowId))) break } @@ -2023,6 +2025,7 @@ async function handleSubblockOperationTx( } const blocksById = await loadSubblockUpdateBlocks(tx, workflowId) + const changedBlockIds = new Set() for (const update of updates) { const { blockId, subblockId, value, expectedValue } = update @@ -2044,15 +2047,18 @@ async function handleSubblockOperationTx( ? { ...currentSubBlock, value } : { id: subblockId, type: 'unknown', value } + blocksById[blockId] = { ...block, subBlocks } + changedBlockIds.add(blockId) + } + + for (const blockId of changedBlockIds) { await tx .update(workflowBlocks) .set({ - subBlocks, + subBlocks: blocksById[blockId].subBlocks, updatedAt: new Date(), }) .where(and(eq(workflowBlocks.id, blockId), eq(workflowBlocks.workflowId, workflowId))) - - blocksById[blockId] = { ...block, subBlocks } } logger.debug(`Batch updated ${updates.length} subblocks for workflow ${workflowId}`) diff --git a/packages/realtime-protocol/src/schemas.test.ts b/packages/realtime-protocol/src/schemas.test.ts new file mode 100644 index 00000000000..4d87d8a0d7c --- /dev/null +++ b/packages/realtime-protocol/src/schemas.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, it } from 'vitest' +import { + BLOCKS_OPERATIONS, + EDGES_OPERATIONS, + OPERATION_TARGETS, + SUBBLOCK_OPERATIONS, +} from './constants' +import { WorkflowOperationSchema } from './schemas' + +const position = { x: 0, y: 0 } +const edge = { id: 'e', source: 'a', target: 'b' } +const many = (count: number, entry: T) => Array.from({ length: count }, () => entry) + +/** Each batch frame with `count` entries in its capped array, and the cap it must hold to. */ +const batches: Array<{ + operation: string + field: string + target: string + cap: number + payload: (count: number) => object +}> = [ + { + operation: BLOCKS_OPERATIONS.BATCH_UPDATE_POSITIONS, + field: 'updates', + target: OPERATION_TARGETS.BLOCKS, + cap: 2_000, + payload: (n) => ({ updates: many(n, { id: 'b', position }) }), + }, + { + operation: BLOCKS_OPERATIONS.BATCH_ADD_BLOCKS, + field: 'blocks', + target: OPERATION_TARGETS.BLOCKS, + cap: 2_000, + payload: (n) => ({ blocks: many(n, { id: 'b' }) }), + }, + { + operation: BLOCKS_OPERATIONS.BATCH_ADD_BLOCKS, + field: 'edges', + target: OPERATION_TARGETS.BLOCKS, + cap: 10_000, + payload: (n) => ({ blocks: [], edges: many(n, edge) }), + }, + { + operation: BLOCKS_OPERATIONS.BATCH_REMOVE_BLOCKS, + field: 'ids', + target: OPERATION_TARGETS.BLOCKS, + cap: 2_000, + payload: (n) => ({ ids: many(n, 'b') }), + }, + ...[ + BLOCKS_OPERATIONS.BATCH_TOGGLE_ENABLED, + BLOCKS_OPERATIONS.BATCH_TOGGLE_HANDLES, + BLOCKS_OPERATIONS.BATCH_TOGGLE_LOCKED, + ].map((operation) => ({ + operation, + field: 'blockIds', + target: OPERATION_TARGETS.BLOCKS, + cap: 2_000, + payload: (n: number) => ({ + blockIds: many(n, 'b'), + previousStates: {}, + }), + })), + { + operation: BLOCKS_OPERATIONS.BATCH_UPDATE_PARENT, + field: 'updates', + target: OPERATION_TARGETS.BLOCKS, + cap: 2_000, + payload: (n) => ({ + updates: many(n, { id: 'b', parentId: 'p', position }), + }), + }, + { + operation: EDGES_OPERATIONS.BATCH_ADD_EDGES, + field: 'edges', + target: OPERATION_TARGETS.EDGES, + cap: 10_000, + payload: (n) => ({ edges: many(n, edge) }), + }, + { + operation: EDGES_OPERATIONS.BATCH_REMOVE_EDGES, + field: 'ids', + target: OPERATION_TARGETS.EDGES, + cap: 10_000, + payload: (n) => ({ ids: many(n, 'e') }), + }, + { + operation: SUBBLOCK_OPERATIONS.BATCH_UPDATE, + field: 'updates', + target: OPERATION_TARGETS.SUBBLOCK, + cap: 10_000, + payload: (n) => ({ + updates: many(n, { blockId: 'b', subblockId: 's', value: 1 }), + }), + }, +] + +describe('WorkflowOperationSchema batch caps', () => { + it.each(batches)( + 'caps $operation $field at $cap entries', + ({ operation, target, cap, payload }) => { + const frame = (count: number) => ({ + operation, + target, + payload: payload(count), + timestamp: 1, + }) + expect(WorkflowOperationSchema.safeParse(frame(cap)).success).toBe(true) + expect(WorkflowOperationSchema.safeParse(frame(cap + 1)).success).toBe(false) + } + ) +}) diff --git a/packages/realtime-protocol/src/schemas.ts b/packages/realtime-protocol/src/schemas.ts index 2cb07c02595..277bcc8813e 100644 --- a/packages/realtime-protocol/src/schemas.ts +++ b/packages/realtime-protocol/src/schemas.ts @@ -11,6 +11,17 @@ import { WORKFLOW_OPERATIONS, } from './constants' +/** + * Most entries one batch frame may carry. Persistence spends work per entry inside the workflow's + * write lock, so the 8 MiB transport cap alone would let one frame hold a pooled connection for + * minutes. Blocks and edges mirror the workflow graph limits (`SOURCE_LIMITS`). Subblock updates + * come from a workflow-wide search-replace, one per matched field, and persist as one write per + * block. + */ +const MAX_BATCH_BLOCKS = 2_000 +const MAX_BATCH_EDGES = 10_000 +const MAX_BATCH_SUBBLOCK_UPDATES = 10_000 + const PositionSchema = z.object({ x: z.number(), y: z.number(), @@ -81,12 +92,14 @@ const BatchPositionUpdateSchema = z.object({ operation: z.literal(BLOCKS_OPERATIONS.BATCH_UPDATE_POSITIONS), target: z.literal(OPERATION_TARGETS.BLOCKS), payload: z.object({ - updates: z.array( - z.object({ - id: z.string(), - position: PositionSchema, - }) - ), + updates: z + .array( + z.object({ + id: z.string(), + position: PositionSchema, + }) + ) + .max(MAX_BATCH_BLOCKS), }), timestamp: z.number(), operationId: z.string().optional(), @@ -157,14 +170,16 @@ const SubblockOperationSchema = z.object({ operation: z.literal(SUBBLOCK_OPERATIONS.BATCH_UPDATE), target: z.literal(OPERATION_TARGETS.SUBBLOCK), payload: z.object({ - updates: z.array( - z.object({ - blockId: z.string(), - subblockId: z.string(), - value: z.any(), - expectedValue: z.any().optional(), - }) - ), + updates: z + .array( + z.object({ + blockId: z.string(), + subblockId: z.string(), + value: z.any(), + expectedValue: z.any().optional(), + }) + ) + .max(MAX_BATCH_SUBBLOCK_UPDATES), }), timestamp: z.number(), operationId: z.string().optional(), @@ -192,8 +207,8 @@ const BatchAddBlocksSchema = z.object({ operation: z.literal(BLOCKS_OPERATIONS.BATCH_ADD_BLOCKS), target: z.literal(OPERATION_TARGETS.BLOCKS), payload: z.object({ - blocks: z.array(z.record(z.string(), z.any())), - edges: z.array(AutoConnectEdgeSchema).optional(), + blocks: z.array(z.record(z.string(), z.any())).max(MAX_BATCH_BLOCKS), + edges: z.array(AutoConnectEdgeSchema).max(MAX_BATCH_EDGES).optional(), loops: z.record(z.string(), z.any()).optional(), parallels: z.record(z.string(), z.any()).optional(), subBlockValues: z.record(z.string(), z.record(z.string(), z.any())).optional(), @@ -206,7 +221,7 @@ const BatchRemoveBlocksSchema = z.object({ operation: z.literal(BLOCKS_OPERATIONS.BATCH_REMOVE_BLOCKS), target: z.literal(OPERATION_TARGETS.BLOCKS), payload: z.object({ - ids: z.array(z.string()), + ids: z.array(z.string()).max(MAX_BATCH_BLOCKS), }), timestamp: z.number(), operationId: z.string().optional(), @@ -216,7 +231,7 @@ const BatchRemoveEdgesSchema = z.object({ operation: z.literal(EDGES_OPERATIONS.BATCH_REMOVE_EDGES), target: z.literal(OPERATION_TARGETS.EDGES), payload: z.object({ - ids: z.array(z.string()), + ids: z.array(z.string()).max(MAX_BATCH_EDGES), }), timestamp: z.number(), operationId: z.string().optional(), @@ -226,15 +241,17 @@ const BatchAddEdgesSchema = z.object({ operation: z.literal(EDGES_OPERATIONS.BATCH_ADD_EDGES), target: z.literal(OPERATION_TARGETS.EDGES), payload: z.object({ - edges: z.array( - z.object({ - id: z.string(), - source: z.string(), - target: z.string(), - sourceHandle: z.string().nullable().optional(), - targetHandle: z.string().nullable().optional(), - }) - ), + edges: z + .array( + z.object({ + id: z.string(), + source: z.string(), + target: z.string(), + sourceHandle: z.string().nullable().optional(), + targetHandle: z.string().nullable().optional(), + }) + ) + .max(MAX_BATCH_EDGES), }), timestamp: z.number(), operationId: z.string().optional(), @@ -244,7 +261,7 @@ const BatchToggleEnabledSchema = z.object({ operation: z.literal(BLOCKS_OPERATIONS.BATCH_TOGGLE_ENABLED), target: z.literal(OPERATION_TARGETS.BLOCKS), payload: z.object({ - blockIds: z.array(z.string()), + blockIds: z.array(z.string()).max(MAX_BATCH_BLOCKS), previousStates: z.record(z.string(), z.boolean()), }), timestamp: z.number(), @@ -255,7 +272,7 @@ const BatchToggleHandlesSchema = z.object({ operation: z.literal(BLOCKS_OPERATIONS.BATCH_TOGGLE_HANDLES), target: z.literal(OPERATION_TARGETS.BLOCKS), payload: z.object({ - blockIds: z.array(z.string()), + blockIds: z.array(z.string()).max(MAX_BATCH_BLOCKS), previousStates: z.record(z.string(), z.boolean()), }), timestamp: z.number(), @@ -266,7 +283,7 @@ const BatchToggleLockedSchema = z.object({ operation: z.literal(BLOCKS_OPERATIONS.BATCH_TOGGLE_LOCKED), target: z.literal(OPERATION_TARGETS.BLOCKS), payload: z.object({ - blockIds: z.array(z.string()), + blockIds: z.array(z.string()).max(MAX_BATCH_BLOCKS), previousStates: z.record(z.string(), z.boolean()), }), timestamp: z.number(), @@ -277,13 +294,15 @@ const BatchUpdateParentSchema = z.object({ operation: z.literal(BLOCKS_OPERATIONS.BATCH_UPDATE_PARENT), target: z.literal(OPERATION_TARGETS.BLOCKS), payload: z.object({ - updates: z.array( - z.object({ - id: z.string(), - parentId: z.string(), - position: PositionSchema, - }) - ), + updates: z + .array( + z.object({ + id: z.string(), + parentId: z.string(), + position: PositionSchema, + }) + ) + .max(MAX_BATCH_BLOCKS), }), timestamp: z.number(), operationId: z.string().optional(),