Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
187 changes: 187 additions & 0 deletions apps/realtime/src/database/batch-add-cap.integration.ts
Original file line number Diff line number Diff line change
@@ -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<void>) {
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<string, unknown>) {
return {
operation: BLOCKS_OPERATIONS.BATCH_ADD_BLOCKS,
target: OPERATION_TARGETS.BLOCKS,
payload,
timestamp: Date.now(),
}
}

function persist(payload: Record<string, unknown>) {
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)
})
})
29 changes: 26 additions & 3 deletions apps/realtime/src/database/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import {
isWorkflowAnnotationOnlyBlockType,
isWorkflowBlockAncestorLocked,
isWorkflowBlockProtected,
MAX_WORKFLOW_BLOCKS,
normalizeWorkflowEdgeSourceHandle,
normalizeWorkflowEdgeTargetHandle,
preserveProtectedWorkflowBlocks,
Expand Down Expand Up @@ -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<string>()
const landed: Record<string, DbBlockRef> = { ...lockBlocks }

if (blocks && blocks.length > 0) {
const incoming = blocks as Array<Record<string, unknown>>
// 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<string, DbBlockRef> = { ...lockBlocks }
for (const block of incoming) {
const id = block.id as string
if (!isProtected(id)) landed[id] = { id, locked: false, data: block.data }
Expand All @@ -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<string, unknown>) => {
const blockId = block.id as string
const mergedSubBlocks = mergeSubBlockValues(
Expand Down Expand Up @@ -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<string, unknown>,
}))
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) {
Expand Down
9 changes: 5 additions & 4 deletions apps/realtime/src/handlers/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -37,7 +38,7 @@ function relayPersistedOperation(
if (reconcile) {
roomManager.emitToRoom<WorkflowUpdatedBroadcast>(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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
},
Expand Down
15 changes: 15 additions & 0 deletions apps/sim/hooks/use-collaborative-workflow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
}

logger.info('Batch adding blocks collaboratively', {
blockCount: blocks.length,
edgeCount: validEdges.length,
Expand Down
6 changes: 4 additions & 2 deletions apps/sim/lib/api/contracts/v2/workflows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/realtime-protocol/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"format:check": "biome format ."
},
"dependencies": {
"@sim/workflow-types": "workspace:*",
"zod": "4.3.6"
},
"devDependencies": {
Expand Down
Loading
Loading