Skip to content

Commit 44dbf28

Browse files
committed
fix(realtime): guard locked loop config and re-sync clients when locks win
batch-add-blocks loops/parallels and subflow updates could rewrite a locked container's config. When persistence keeps lock-protected state over a payload, the room is told to reload instead of receiving the rejected payload.
1 parent b59f210 commit 44dbf28

6 files changed

Lines changed: 167 additions & 78 deletions

File tree

‎apps/realtime/src/database/block-lock.integration.ts‎

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
/** Real PostgreSQL coverage: realtime batch-add and replace-state never change what a block lock protects. */
1+
/** Real PostgreSQL coverage: realtime batch-add, subflow updates and replace-state never change what a block lock protects. */
22
import { mkdir, writeFile } from 'node:fs/promises'
33
import { dirname, resolve } from 'node:path'
44
import { db } from '@sim/db'
@@ -14,6 +14,7 @@ import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/
1414
import {
1515
BLOCKS_OPERATIONS,
1616
OPERATION_TARGETS,
17+
SUBFLOW_OPERATIONS,
1718
WORKFLOW_OPERATIONS,
1819
} from '@sim/realtime-protocol/constants'
1920
import { getErrorMessage } from '@sim/utils/errors'
@@ -93,6 +94,13 @@ async function readBlocks() {
9394
return Object.fromEntries(rows.map((row) => [row.id, row]))
9495
}
9596

97+
async function readSubflows() {
98+
return db
99+
.select({ id: workflowSubflows.id, config: workflowSubflows.config })
100+
.from(workflowSubflows)
101+
.where(eq(workflowSubflows.workflowId, workflowId))
102+
}
103+
96104
describe('block locks against PostgreSQL', () => {
97105
beforeAll(async () => {
98106
const now = new Date()
@@ -157,7 +165,7 @@ describe('block locks against PostgreSQL', () => {
157165
})
158166

159167
check('batch-add-blocks cannot unlock or overwrite a locked block', async () => {
160-
await persist(OPERATION_TARGETS.BLOCKS, BLOCKS_OPERATIONS.BATCH_ADD_BLOCKS, {
168+
const result = await persist(OPERATION_TARGETS.BLOCKS, BLOCKS_OPERATIONS.BATCH_ADD_BLOCKS, {
161169
blocks: [
162170
payloadBlock(ids.locked, 'Hijacked', { locked: false }),
163171
payloadBlock(ids.child, 'Hijacked child'),
@@ -170,6 +178,35 @@ describe('block locks against PostgreSQL', () => {
170178
const blocks = await readBlocks()
171179
expect(blocks[ids.locked]).toMatchObject({ locked: true, name: 'Locked' })
172180
expect(blocks[ids.child]).toMatchObject({ name: 'Child' })
181+
expect(result).toEqual({ reconcile: true })
182+
})
183+
184+
check('batch-add-blocks and subflow updates cannot rewrite a locked loop config', async () => {
185+
const result = await persist(OPERATION_TARGETS.BLOCKS, BLOCKS_OPERATIONS.BATCH_ADD_BLOCKS, {
186+
blocks: [payloadBlock(generateId(), 'Throwaway')],
187+
edges: [],
188+
loops: { [ids.container]: { ...lockedLoopConfig, iterations: 99 } },
189+
parallels: {},
190+
})
191+
await persist(OPERATION_TARGETS.SUBFLOW, SUBFLOW_OPERATIONS.UPDATE, {
192+
id: ids.container,
193+
type: 'loop',
194+
config: { iterations: 42 },
195+
})
196+
197+
expect(await readSubflows()).toEqual([{ id: ids.container, config: lockedLoopConfig }])
198+
expect(result).toEqual({ reconcile: true })
199+
})
200+
201+
check('an add that touches no lock keeps collaborators on the payload', async () => {
202+
const result = await persist(OPERATION_TARGETS.BLOCKS, BLOCKS_OPERATIONS.BATCH_ADD_BLOCKS, {
203+
blocks: [payloadBlock(generateId(), 'Plain')],
204+
edges: [],
205+
loops: {},
206+
parallels: {},
207+
})
208+
209+
expect(result).toEqual({ reconcile: false })
173210
})
174211

175212
check(
@@ -198,7 +235,7 @@ describe('block locks against PostgreSQL', () => {
198235
async () => {
199236
const added = generateId()
200237
const nestedNew = generateId()
201-
await persist(OPERATION_TARGETS.WORKFLOW, WORKFLOW_OPERATIONS.REPLACE_STATE, {
238+
const result = await persist(OPERATION_TARGETS.WORKFLOW, WORKFLOW_OPERATIONS.REPLACE_STATE, {
202239
state: {
203240
blocks: {
204241
[ids.locked]: payloadBlock(ids.locked, 'Hijacked', { locked: false }),
@@ -228,11 +265,8 @@ describe('block locks against PostgreSQL', () => {
228265
.where(eq(workflowEdges.workflowId, workflowId))
229266
expect(edges.map((edge) => edge.id)).toEqual([ids.edgeIntoLocked])
230267

231-
const subflows = await db
232-
.select({ id: workflowSubflows.id, config: workflowSubflows.config })
233-
.from(workflowSubflows)
234-
.where(eq(workflowSubflows.workflowId, workflowId))
235-
expect(subflows).toEqual([{ id: ids.container, config: lockedLoopConfig }])
268+
expect(await readSubflows()).toEqual([{ id: ids.container, config: lockedLoopConfig }])
269+
expect(result).toEqual({ reconcile: true })
236270
}
237271
)
238272
})

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ describe('search replacement persistence', () => {
8484
},
8585
]
8686

87-
await expect(replaceTools(stored)).resolves.toBeUndefined()
87+
await expect(replaceTools(stored)).resolves.toEqual({ reconcile: false })
8888
expect(mockSet).toHaveBeenLastCalledWith(
8989
expect.objectContaining({
9090
subBlocks: { tools: { id: 'tools', type: 'tool-input', value: replacement } },
@@ -138,7 +138,7 @@ describe('subblock update with canonical modes persistence', () => {
138138
}
139139

140140
it('writes the subblock value and replaces canonical modes in one block update', async () => {
141-
await expect(updateTools({})).resolves.toBeUndefined()
141+
await expect(updateTools({})).resolves.toEqual({ reconcile: false })
142142

143143
expect(mockSet).toHaveBeenCalledTimes(2)
144144
expect(mockSet).toHaveBeenLastCalledWith(

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

Lines changed: 73 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,15 @@ interface DbBlockRef {
298298
data: unknown
299299
}
300300

301+
/** Every block of the workflow with the fields the lock checks read, keyed by id. */
302+
async function loadLockBlocks(tx: DbOrTx, workflowId: string): Promise<Record<string, DbBlockRef>> {
303+
const rows = await tx
304+
.select({ id: workflowBlocks.id, locked: workflowBlocks.locked, data: workflowBlocks.data })
305+
.from(workflowBlocks)
306+
.where(eq(workflowBlocks.workflowId, workflowId))
307+
return Object.fromEntries(rows.map((row) => [row.id, row]))
308+
}
309+
301310
/**
302311
* Finds all descendant block IDs of a container (recursive).
303312
* Works with raw DB block arrays.
@@ -413,8 +422,21 @@ export async function getWorkflowState(workflowId: string) {
413422
}
414423
}
415424

416-
export async function persistWorkflowOperation(workflowId: string, operation: any) {
425+
/** What a persisted operation means for the clients that applied its payload optimistically. */
426+
export interface PersistedWorkflowOperation {
427+
/**
428+
* True when the stored graph kept lock-protected state the payload tried to change, so the
429+
* payload no longer describes what was saved and every client must re-sync from the server.
430+
*/
431+
reconcile: boolean
432+
}
433+
434+
export async function persistWorkflowOperation(
435+
workflowId: string,
436+
operation: any
437+
): Promise<PersistedWorkflowOperation> {
417438
const startTime = Date.now()
439+
let reconcile = false
418440
try {
419441
const { operation: op, target, payload, timestamp, userId } = operation
420442

@@ -451,7 +473,7 @@ export async function persistWorkflowOperation(workflowId: string, operation: an
451473
await handleBlockOperationTx(tx, workflowId, op, payload)
452474
break
453475
case OPERATION_TARGETS.BLOCKS:
454-
await handleBlocksOperationTx(tx, workflowId, op, payload)
476+
reconcile = (await handleBlocksOperationTx(tx, workflowId, op, payload)) === true
455477
break
456478
case OPERATION_TARGETS.EDGE:
457479
await handleEdgeOperationTx(tx, workflowId, op, payload)
@@ -469,7 +491,7 @@ export async function persistWorkflowOperation(workflowId: string, operation: an
469491
await handleVariableOperationTx(tx, workflowId, op, payload)
470492
break
471493
case OPERATION_TARGETS.WORKFLOW:
472-
await handleWorkflowOperationTx(tx, workflowId, op, payload)
494+
reconcile = await handleWorkflowOperationTx(tx, workflowId, op, payload)
473495
break
474496
default:
475497
throw new Error(`Unknown operation target: ${target}`)
@@ -495,6 +517,7 @@ export async function persistWorkflowOperation(workflowId: string, operation: an
495517
workflowId: `${workflowId.substring(0, 8)}...`,
496518
})
497519
}
520+
return { reconcile }
498521
} catch (error) {
499522
const duration = Date.now() - startTime
500523
logger.error(
@@ -949,36 +972,31 @@ async function handleBlocksOperationTx(
949972
parallelCount: Object.keys(parallels || {}).length,
950973
})
951974

952-
if (blocks && blocks.length > 0) {
953-
const existingBlocks: DbBlockRef[] = await tx
954-
.select({
955-
id: workflowBlocks.id,
956-
locked: workflowBlocks.locked,
957-
data: workflowBlocks.data,
958-
})
959-
.from(workflowBlocks)
960-
.where(eq(workflowBlocks.workflowId, workflowId))
961-
const blocksById = Object.fromEntries(existingBlocks.map((b) => [b.id, b]))
975+
const lockBlocks = await loadLockBlocks(tx, workflowId)
976+
const isProtected = (id: string) => isWorkflowBlockProtected(id, lockBlocks)
962977

963-
// Lock state is admin-only, so an add never overwrites a protected block
964-
// nor places one inside a locked container.
978+
// Lock state is admin-only, so an add never writes the lock flag, overwrites a protected
979+
// block or its loop/parallel config, nor places a block inside a locked container.
980+
let reconcile = false
981+
982+
if (blocks && blocks.length > 0) {
965983
const allowedBlocks = (blocks as Array<Record<string, unknown>>).filter((block) => {
966984
const parentId = (block.data as Record<string, unknown> | null)?.parentId as
967985
| string
968986
| undefined
969-
if (
970-
isWorkflowBlockProtected(block.id as string, blocksById) ||
971-
(parentId && isWorkflowBlockProtected(parentId, blocksById))
972-
) {
987+
if (isProtected(block.id as string) || (parentId && isProtected(parentId))) {
973988
logger.info(`Skipping block ${block.id} - it or its parent is locked`)
974989
return false
975990
}
976991
return true
977992
})
993+
reconcile =
994+
allowedBlocks.length < blocks.length ||
995+
(blocks as Array<Record<string, unknown>>).some((block) => block.locked)
978996

979997
if (allowedBlocks.length === 0) {
980998
logger.info('All blocks filtered out due to locks, skipping add')
981-
break
999+
return reconcile
9821000
}
9831001

9841002
const blockValues = allowedBlocks.map((block: Record<string, unknown>) => {
@@ -1115,36 +1133,37 @@ async function handleBlocksOperationTx(
11151133
}
11161134
}
11171135

1118-
if (loops && Object.keys(loops).length > 0) {
1119-
const loopValues = Object.entries(loops).map(([id, loop]) => ({
1136+
const subflowEntries = [
1137+
...Object.entries(loops || {}).map(([id, config]) => ({ id, type: 'loop', config })),
1138+
...Object.entries(parallels || {}).map(([id, config]) => ({
11201139
id,
1140+
type: 'parallel',
1141+
config,
1142+
})),
1143+
]
1144+
const subflowValues = subflowEntries
1145+
.filter((subflow) => !isProtected(subflow.id))
1146+
.map((subflow) => ({
1147+
...subflow,
11211148
workflowId,
1122-
type: 'loop',
1123-
config: loop as Record<string, unknown>,
1149+
config: subflow.config as Record<string, unknown>,
11241150
}))
1125-
1126-
await upsertWorkflowRows(tx, workflowSubflows, workflowId, loopValues, SUBFLOW_UPSERT_SET)
1151+
if (subflowValues.length < subflowEntries.length) {
1152+
logger.info('Skipping loop/parallel config of locked containers')
1153+
reconcile = true
11271154
}
1128-
1129-
if (parallels && Object.keys(parallels).length > 0) {
1130-
const parallelValues = Object.entries(parallels).map(([id, parallel]) => ({
1131-
id,
1132-
workflowId,
1133-
type: 'parallel',
1134-
config: parallel as Record<string, unknown>,
1135-
}))
1136-
1155+
if (subflowValues.length > 0) {
11371156
await upsertWorkflowRows(
11381157
tx,
11391158
workflowSubflows,
11401159
workflowId,
1141-
parallelValues,
1160+
subflowValues,
11421161
SUBFLOW_UPSERT_SET
11431162
)
11441163
}
11451164

11461165
logger.info(`Successfully batch added blocks to workflow ${workflowId}`)
1147-
break
1166+
return reconcile
11481167
}
11491168

11501169
case BLOCKS_OPERATIONS.BATCH_REMOVE_BLOCKS: {
@@ -1816,6 +1835,13 @@ async function handleSubflowOperationTx(
18161835
throw new Error('Missing required fields for update subflow operation')
18171836
}
18181837

1838+
if (isWorkflowBlockProtected(payload.id, await loadLockBlocks(tx, workflowId))) {
1839+
logger.info(
1840+
`Skipping update of subflow ${payload.id} - it is locked or in a locked container`
1841+
)
1842+
break
1843+
}
1844+
18191845
logger.debug(`Updating subflow ${payload.id} with config:`, payload.config)
18201846

18211847
// Read-modify-write merge so partial config payloads never wipe other fields
@@ -2128,13 +2154,13 @@ async function handleVariableOperationTx(
21282154
}
21292155
}
21302156

2131-
/** Replaces the complete workflow state. */
2157+
/** Replaces the complete workflow state; resolves whether clients must re-sync from the server. */
21322158
async function handleWorkflowOperationTx(
21332159
tx: any,
21342160
workflowId: string,
21352161
operation: string,
21362162
payload: any
2137-
) {
2163+
): Promise<boolean> {
21382164
switch (operation) {
21392165
case WORKFLOW_OPERATIONS.REPLACE_STATE: {
21402166
if (!payload.state) {
@@ -2261,7 +2287,14 @@ async function handleWorkflowOperationTx(
22612287
}
22622288

22632289
logger.info(`Successfully replaced workflow state for ${workflowId}`)
2264-
break
2290+
// A graph holding protected blocks may have been kept over the payload; comparing the
2291+
// stored rows against it field by field is not worth the precision, so re-sync.
2292+
return (
2293+
merged.protectedBlockIds.size > 0 ||
2294+
Object.values((blocks || {}) as Record<string, { locked?: unknown }>).some(
2295+
(block) => block.locked
2296+
)
2297+
)
22652298
}
22662299

22672300
default:

‎apps/realtime/src/handlers/operations.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ function setup(id: string, role: string) {
9393
describe('workflow operation ACL', () => {
9494
beforeEach(() => {
9595
mockAssertMutable.mockResolvedValue(undefined)
96-
mockPersist.mockResolvedValue(undefined)
96+
mockPersist.mockResolvedValue({ reconcile: false })
9797
})
9898

9999
describe('read-only member', () => {

0 commit comments

Comments
 (0)