diff --git a/apps/realtime/src/database/batch-add-cap.integration.ts b/apps/realtime/src/database/batch-add-cap.integration.ts new file mode 100644 index 00000000000..4924434124c --- /dev/null +++ b/apps/realtime/src/database/batch-add-cap.integration.ts @@ -0,0 +1,187 @@ +/** Real PostgreSQL coverage: a realtime batch add never grows a workflow past the shared block cap, nor leaves subflow rows without their block. */ +import { mkdir, writeFile } from 'node:fs/promises' +import { dirname, resolve } from 'node:path' +import { db } from '@sim/db' +import { + user, + workflow, + workflowBlocks, + workflowEdges, + workflowSubflows, + workspace, +} from '@sim/db/schema' +import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' +import { BLOCKS_OPERATIONS, OPERATION_TARGETS } from '@sim/realtime-protocol/constants' +import { WorkflowOperationSchema } from '@sim/realtime-protocol/schemas' +import { getErrorMessage } from '@sim/utils/errors' +import { generateId } from '@sim/utils/id' +import { MAX_WORKFLOW_BLOCKS, MAX_WORKFLOW_EDGES } from '@sim/workflow-types/workflow' +import { count, eq } 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 existingIds = Array.from({ length: MAX_WORKFLOW_BLOCKS - 1 }, () => generateId()) +const checks: { name: string; status: 'passed' | 'failed'; durationMs: number; error?: string }[] = + [] + +/** Registers a test and records its status and duration in the suite report. */ +function check(name: string, run: () => Promise) { + it(name, async () => { + const started = performance.now() + try { + await run() + checks.push({ name, status: 'passed', durationMs: performance.now() - started }) + } catch (error) { + checks.push({ + name, + status: 'failed', + durationMs: performance.now() - started, + error: getErrorMessage(error), + }) + throw error + } + }) +} + +function payloadBlock(id: string) { + return { id, type: 'function', name: id, position: { x: 0, y: 0 }, subBlocks: {} } +} + +function batchAdd(payload: Record) { + return { + operation: BLOCKS_OPERATIONS.BATCH_ADD_BLOCKS, + target: OPERATION_TARGETS.BLOCKS, + payload, + timestamp: Date.now(), + } +} + +function persist(payload: Record) { + return persistWorkflowOperation(workflowId, { ...batchAdd(payload), userId }) +} + +async function countRows( + table: typeof workflowBlocks | typeof workflowEdges | typeof workflowSubflows +) { + const [row] = await db.select({ n: count() }).from(table).where(eq(table.workflowId, workflowId)) + return row.n +} + +describe('realtime batch-add block cap against PostgreSQL', () => { + beforeAll(async () => { + const now = new Date() + await db.insert(user).values({ + id: userId, + name: 'Cap fixture', + email: `${userId}@batch-add-cap.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await insertWorkspaceFixture(db, { + id: workspaceId, + name: 'Cap target', + ownerId: userId, + billedAccountUserId: userId, + }) + await db.insert(workflow).values({ + id: workflowId, + userId, + workspaceId, + name: 'Nearly full', + lastSynced: now, + createdAt: now, + updatedAt: now, + }) + }) + + beforeEach(async () => { + await db.delete(workflowSubflows).where(eq(workflowSubflows.workflowId, workflowId)) + await db.delete(workflowEdges).where(eq(workflowEdges.workflowId, workflowId)) + await db.delete(workflowBlocks).where(eq(workflowBlocks.workflowId, workflowId)) + await db.insert(workflowBlocks).values( + existingIds.map((id) => ({ + id, + workflowId, + type: 'function', + name: id, + positionX: '0', + positionY: '0', + })) + ) + }) + + afterAll(async () => { + const reportPath = + process.env.REALTIME_BATCH_ADD_CAP_REPORT_PATH ?? + resolve('test-results/realtime-batch-add-cap.json') + await mkdir(dirname(reportPath), { recursive: true }) + await writeFile(reportPath, JSON.stringify({ checks }, null, 2)) + await deleteWorkspaceFixture(db, eq(workspace.ownerId, userId)) + await db.delete(user).where(eq(user.id, userId)) + }) + + check('a single message over the cap fails protocol validation', async () => { + const blocks = Array.from({ length: MAX_WORKFLOW_BLOCKS + 1 }, () => payloadBlock(generateId())) + const edges = Array.from({ length: MAX_WORKFLOW_EDGES + 1 }, () => ({ + id: generateId(), + source: 'a', + target: 'b', + })) + const loops = Object.fromEntries(blocks.map((block) => [block.id, {}])) + + expect(WorkflowOperationSchema.safeParse(batchAdd({ blocks })).success).toBe(false) + expect(WorkflowOperationSchema.safeParse(batchAdd({ blocks: [], edges })).success).toBe(false) + expect(WorkflowOperationSchema.safeParse(batchAdd({ blocks: [], loops })).success).toBe(false) + expect( + WorkflowOperationSchema.safeParse(batchAdd({ blocks: blocks.slice(1), edges: [] })).success + ).toBe(true) + }) + + check('a batch that would push the workflow past the cap writes nothing', async () => { + const [first, second] = [generateId(), generateId()] + const result = await persist({ + blocks: [payloadBlock(first), payloadBlock(second)], + edges: [{ id: generateId(), source: first, target: second }], + }) + + expect(result).toEqual({ reconcile: true }) + expect(await countRows(workflowBlocks)).toBe(MAX_WORKFLOW_BLOCKS - 1) + expect(await countRows(workflowEdges)).toBe(0) + }) + + check('re-sent existing blocks do not count toward the cap', async () => { + const added = generateId() + const result = await persist({ + blocks: [...existingIds.slice(0, 10).map(payloadBlock), payloadBlock(added)], + }) + + expect(result).toEqual({ reconcile: false }) + expect(await countRows(workflowBlocks)).toBe(MAX_WORKFLOW_BLOCKS) + }) + + check('loop and parallel configs land only for a stored or added block', async () => { + const loopId = generateId() + const orphan = await persist({ + blocks: [], + loops: { [generateId()]: { nodes: [] } }, + parallels: { [generateId()]: { nodes: [] } }, + }) + expect(orphan).toEqual({ reconcile: true }) + expect(await countRows(workflowSubflows)).toBe(0) + + const added = await persist({ + blocks: [{ ...payloadBlock(loopId), type: 'loop' }], + loops: { [loopId]: { nodes: [], iterations: 4, loopType: 'for' } }, + }) + expect(added).toEqual({ reconcile: false }) + expect(await countRows(workflowSubflows)).toBe(1) + + const existing = await persist({ blocks: [], loops: { [existingIds[0]]: { nodes: [] } } }) + expect(existing).toEqual({ reconcile: false }) + expect(await countRows(workflowSubflows)).toBe(2) + }) +}) diff --git a/apps/realtime/src/database/operations.ts b/apps/realtime/src/database/operations.ts index 116e1d18c92..8579d2dbbe1 100644 --- a/apps/realtime/src/database/operations.ts +++ b/apps/realtime/src/database/operations.ts @@ -37,6 +37,7 @@ import { isWorkflowAnnotationOnlyBlockType, isWorkflowBlockAncestorLocked, isWorkflowBlockProtected, + MAX_WORKFLOW_BLOCKS, normalizeWorkflowEdgeSourceHandle, normalizeWorkflowEdgeTargetHandle, preserveProtectedWorkflowBlocks, @@ -983,12 +984,12 @@ async function handleBlocksOperationTx( // block or its loop/parallel config, nor places a block inside a locked container. let reconcile = false const rejectedBlockIds = new Set() + const landed: Record = { ...lockBlocks } if (blocks && blocks.length > 0) { const incoming = blocks as Array> // Added blocks land unlocked, so one is refused exactly when it is protected now or // would sit under a locked ancestor once the whole batch lands. - const landed: Record = { ...lockBlocks } for (const block of incoming) { const id = block.id as string if (!isProtected(id)) landed[id] = { id, locked: false, data: block.data } @@ -1010,6 +1011,21 @@ async function handleBlocksOperationTx( return reconcile } + // The workflow row lock taken in persistWorkflowOperation serializes this count with + // every other write, so repeated batches cannot grow a workflow past the shared cap. + const existingBlockCount = Object.keys(lockBlocks).length + const newBlockCount = allowedBlocks.filter( + (block) => !Object.hasOwn(lockBlocks, block.id as string) + ).length + if (existingBlockCount + newBlockCount > MAX_WORKFLOW_BLOCKS) { + logger.warn('Refusing batch add past the workflow block cap', { + existingBlockCount, + newBlockCount, + max: MAX_WORKFLOW_BLOCKS, + }) + return true + } + const blockValues = allowedBlocks.map((block: Record) => { const blockId = block.id as string const mergedSubBlocks = mergeSubBlockValues( @@ -1153,15 +1169,22 @@ async function handleBlocksOperationTx( config, })), ] + // A loop or parallel config belongs to its container block, so one for a block that is + // neither stored nor added here would only leave an orphan row behind. const subflowValues = subflowEntries - .filter((subflow) => !isProtected(subflow.id) && !rejectedBlockIds.has(subflow.id)) + .filter( + (subflow) => + Object.hasOwn(landed, subflow.id) && + !isProtected(subflow.id) && + !rejectedBlockIds.has(subflow.id) + ) .map((subflow) => ({ ...subflow, workflowId, config: subflow.config as Record, })) if (subflowValues.length < subflowEntries.length) { - logger.info('Skipping loop/parallel config of locked containers') + logger.info('Skipping loop/parallel config of locked or missing containers') reconcile = true } if (subflowValues.length > 0) { diff --git a/apps/realtime/src/handlers/operations.ts b/apps/realtime/src/handlers/operations.ts index 26d92c3126f..ad6e10b05db 100644 --- a/apps/realtime/src/handlers/operations.ts +++ b/apps/realtime/src/handlers/operations.ts @@ -23,9 +23,10 @@ import { type IRoomManager, type UserSession, workflowRoom as wf } from '@/rooms const logger = createLogger('OperationsHandlers') /** - * Relays a persisted operation to the room. When persistence kept lock-protected state over - * the payload, every client, the sender included, is told to reload the stored graph instead - * of applying a payload that no longer describes what was saved. + * Relays a persisted operation to the room. When persistence kept stored state over the payload + * (lock-protected blocks, or a batch add past the workflow block cap), every client, the sender + * included, is told to reload the stored graph instead of applying a payload that no longer + * describes what was saved. */ function relayPersistedOperation( socket: AuthenticatedSocket, @@ -37,7 +38,7 @@ function relayPersistedOperation( if (reconcile) { roomManager.emitToRoom(wf(workflowId), 'workflow-updated', { workflowId, - message: 'Locked blocks were kept as stored', + message: 'Stored state was kept over the refused change', timestamp: Date.now(), }) return diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/workflow.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/workflow.tsx index 2bf2e959105..6ec05cbe616 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/workflow.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/workflow.tsx @@ -971,13 +971,14 @@ const WorkflowContent = React.memo( ) } - collaborativeBatchAddBlocks( + const added = collaborativeBatchAddBlocks( [block], autoConnectEdge ? [autoConnectEdge] : [], {}, {}, subBlockValues ) + if (!added) return usePanelEditorStore.getState().setCurrentBlockId(id) if (type === 'note') usePanelStore.getState().setIsMobilePanelOpen(false) }, diff --git a/apps/sim/hooks/use-collaborative-workflow.ts b/apps/sim/hooks/use-collaborative-workflow.ts index 206ee5f20d9..ccedb5cfd11 100644 --- a/apps/sim/hooks/use-collaborative-workflow.ts +++ b/apps/sim/hooks/use-collaborative-workflow.ts @@ -17,6 +17,8 @@ import { filterAcyclicEdges, getWorkflowBlockNameConflict, isWorkflowBlockProtected, + MAX_WORKFLOW_BLOCKS, + MAX_WORKFLOW_EDGES, } from '@sim/workflow-types/workflow' import { useQueryClient } from '@tanstack/react-query' import type { Edge } from '@xyflow/react' @@ -2184,6 +2186,19 @@ export function useCollaborativeWorkflow() { const allBlocks = { ...existingBlocks, ...newBlocksMap } const validEdges = filterValidEdges(edges, allBlocks) + const newBlockCount = blocks.filter( + (block) => !Object.hasOwn(existingBlocks, block.id) + ).length + if ( + Object.keys(existingBlocks).length + newBlockCount > MAX_WORKFLOW_BLOCKS || + validEdges.length > MAX_WORKFLOW_EDGES + ) { + toast.error( + `A workflow can hold up to ${MAX_WORKFLOW_BLOCKS.toLocaleString()} blocks, and one paste up to ${MAX_WORKFLOW_EDGES.toLocaleString()} connections` + ) + return false + } + logger.info('Batch adding blocks collaboratively', { blockCount: blocks.length, edgeCount: validEdges.length, diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index b54c78ed4bb..0f041130394 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -4,6 +4,8 @@ import { BLOCK_RETRY_MAX_WAIT_MS, BLOCK_RETRY_MIN_TRIES, BLOCK_RETRY_MIN_WAIT_MS, + MAX_WORKFLOW_BLOCKS, + MAX_WORKFLOW_EDGES, } from '@sim/workflow-types/workflow' import { z } from 'zod' import { @@ -3352,8 +3354,8 @@ export const v2ImportWorkflowContract = defineRouteContract({ * ask the persistence layer to write an unbounded number of rows. Both sit an * order of magnitude above the largest workflow observed in production. */ -export const MAX_WORKFLOW_GRAPH_BLOCKS = 2000 -export const MAX_WORKFLOW_GRAPH_EDGES = 10_000 +export const MAX_WORKFLOW_GRAPH_BLOCKS = MAX_WORKFLOW_BLOCKS +export const MAX_WORKFLOW_GRAPH_EDGES = MAX_WORKFLOW_EDGES /** * Ceiling on one `POST /operations` batch: a bound on the request, the one transaction and the * report an atomic batch writes, not on a workflow's size. A larger edit splits into batches. diff --git a/bun.lock b/bun.lock index c55b3af2d91..04eaf22f040 100644 --- a/bun.lock +++ b/bun.lock @@ -714,6 +714,7 @@ "name": "@sim/realtime-protocol", "version": "0.1.0", "dependencies": { + "@sim/workflow-types": "workspace:*", "zod": "4.3.6", }, "devDependencies": { diff --git a/packages/realtime-protocol/package.json b/packages/realtime-protocol/package.json index 7d6f7028a4c..0f5dfd435a1 100644 --- a/packages/realtime-protocol/package.json +++ b/packages/realtime-protocol/package.json @@ -49,6 +49,7 @@ "format:check": "biome format ." }, "dependencies": { + "@sim/workflow-types": "workspace:*", "zod": "4.3.6" }, "devDependencies": { diff --git a/packages/realtime-protocol/src/schemas.ts b/packages/realtime-protocol/src/schemas.ts index 277bcc8813e..19dce0a58cf 100644 --- a/packages/realtime-protocol/src/schemas.ts +++ b/packages/realtime-protocol/src/schemas.ts @@ -1,3 +1,4 @@ +import { MAX_WORKFLOW_BLOCKS, MAX_WORKFLOW_EDGES } from '@sim/workflow-types/workflow' import { z } from 'zod' import { BLOCK_OPERATIONS, @@ -14,12 +15,12 @@ import { /** * 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 + * minutes. Blocks and edges are the shared workflow graph 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_BLOCKS = MAX_WORKFLOW_BLOCKS +const MAX_BATCH_EDGES = MAX_WORKFLOW_EDGES const MAX_BATCH_SUBBLOCK_UPDATES = 10_000 const PositionSchema = z.object({ @@ -203,15 +204,24 @@ const SubblockCanonicalModesUpdateSchema = z.object({ operationId: z.string().optional(), }) +/** A record keyed by block id, holding at most one entry per block a workflow may have. */ +function boundedRecord(value: T) { + return z + .record(z.string(), value) + .refine((record) => Object.keys(record).length <= MAX_BATCH_BLOCKS, { + message: `Too many entries (max ${MAX_BATCH_BLOCKS})`, + }) +} + 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())).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(), + loops: boundedRecord(z.any()).optional(), + parallels: boundedRecord(z.any()).optional(), + subBlockValues: boundedRecord(z.record(z.string(), z.any())).optional(), }), timestamp: z.number(), operationId: z.string().optional(), diff --git a/packages/workflow-code/src/limits.ts b/packages/workflow-code/src/limits.ts index 20697310094..9dea152c978 100644 --- a/packages/workflow-code/src/limits.ts +++ b/packages/workflow-code/src/limits.ts @@ -1,4 +1,5 @@ import { utf8ByteLength } from '@sim/utils/paste' +import { MAX_WORKFLOW_BLOCKS, MAX_WORKFLOW_EDGES } from '@sim/workflow-types/workflow' /** * The limits workflow source shares across reading and writing. A get refuses to print a workflow @@ -17,10 +18,10 @@ import { utf8ByteLength } from '@sim/utils/paste' * Client-safe: no parser or catalog imports, so contracts can read it. */ export const SOURCE_LIMITS = { - /** Blocks in one workflow. Mirrors the v2 graph cap (`MAX_WORKFLOW_GRAPH_BLOCKS`). */ - maxBlocks: 2_000, - /** Edges in one workflow. Mirrors the v2 graph cap (`MAX_WORKFLOW_GRAPH_EDGES`). */ - maxEdges: 10_000, + /** Blocks in one workflow. */ + maxBlocks: MAX_WORKFLOW_BLOCKS, + /** Edges in one workflow. */ + maxEdges: MAX_WORKFLOW_EDGES, /** Variables in one workflow, so a lock holds at most this many variable entries. */ maxVariables: 2_000, /** Files in one source: `workflow.ts` plus one code file per block. */ diff --git a/packages/workflow-types/src/workflow.ts b/packages/workflow-types/src/workflow.ts index 0d2b858a685..027c343a5df 100644 --- a/packages/workflow-types/src/workflow.ts +++ b/packages/workflow-types/src/workflow.ts @@ -64,6 +64,13 @@ export interface BlockLayoutState { measuredHeight?: number } +/** + * Ceilings on one workflow's graph, shared by every write path that bounds it: the v2 graph + * routes, workflows-as-code source and the realtime batch add. + */ +export const MAX_WORKFLOW_BLOCKS = 2_000 +export const MAX_WORKFLOW_EDGES = 10_000 + /** * Inclusive bounds for {@link BlockRetryConfig.maxTries}: a retrying block tries * at least twice, since one retry is the whole point, and at most five times.