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
126 changes: 126 additions & 0 deletions apps/realtime/src/database/batch-writes.integration.ts
Original file line number Diff line number Diff line change
@@ -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' } })
})
})
40 changes: 23 additions & 17 deletions apps/realtime/src/database/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, { x: number; y: number }>()
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
}

Expand Down Expand Up @@ -2023,6 +2025,7 @@ async function handleSubblockOperationTx(
}

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

for (const update of updates) {
const { blockId, subblockId, value, expectedValue } = update
Expand All @@ -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}`)
Expand Down
112 changes: 112 additions & 0 deletions packages/realtime-protocol/src/schemas.test.ts
Original file line number Diff line number Diff line change
@@ -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 = <T>(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)
}
)
})
Loading
Loading