Skip to content

Commit cac9713

Browse files
committed
fix(realtime): cascade orphaned locked children and keep preserved edge ids
A replace that removes an unlocked container now removes its locked children too, matching a direct delete, instead of saving a dangling parentId. Preserved protected edges win by id, so a retargeted edge cannot duplicate one and abort the save. Skipped subflow updates re-sync the room like the other lock-reconciled writes.
1 parent 44dbf28 commit cac9713

4 files changed

Lines changed: 110 additions & 82 deletions

File tree

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

Lines changed: 25 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ const ids = {
3232
child: generateId(),
3333
free: generateId(),
3434
edgeIntoLocked: generateId(),
35+
unlockedParent: generateId(),
36+
lockedChild: generateId(),
3537
}
3638
const lockedLoopConfig = { id: ids.container, nodes: [ids.child], iterations: 3, loopType: 'for' }
3739
const checks: { name: string; status: 'passed' | 'failed'; durationMs: number; error?: string }[] =
@@ -132,14 +134,17 @@ describe('block locks against PostgreSQL', () => {
132134
beforeEach(async () => {
133135
await db.delete(workflowSubflows).where(eq(workflowSubflows.workflowId, workflowId))
134136
await db.delete(workflowBlocks).where(eq(workflowBlocks.workflowId, workflowId))
135-
await db
136-
.insert(workflowBlocks)
137-
.values([
138-
blockRow(ids.locked, 'Locked', { locked: true }),
139-
blockRow(ids.container, 'Locked loop', { type: 'loop', locked: true }),
140-
blockRow(ids.child, 'Child', { data: { parentId: ids.container, extent: 'parent' } }),
141-
blockRow(ids.free, 'Free'),
142-
])
137+
await db.insert(workflowBlocks).values([
138+
blockRow(ids.locked, 'Locked', { locked: true }),
139+
blockRow(ids.container, 'Locked loop', { type: 'loop', locked: true }),
140+
blockRow(ids.child, 'Child', { data: { parentId: ids.container, extent: 'parent' } }),
141+
blockRow(ids.free, 'Free'),
142+
blockRow(ids.unlockedParent, 'Unlocked loop', { type: 'loop' }),
143+
blockRow(ids.lockedChild, 'Locked child', {
144+
locked: true,
145+
data: { parentId: ids.unlockedParent, extent: 'parent' },
146+
}),
147+
])
143148
await db.insert(workflowEdges).values({
144149
id: ids.edgeIntoLocked,
145150
workflowId,
@@ -188,14 +193,15 @@ describe('block locks against PostgreSQL', () => {
188193
loops: { [ids.container]: { ...lockedLoopConfig, iterations: 99 } },
189194
parallels: {},
190195
})
191-
await persist(OPERATION_TARGETS.SUBFLOW, SUBFLOW_OPERATIONS.UPDATE, {
196+
const updated = await persist(OPERATION_TARGETS.SUBFLOW, SUBFLOW_OPERATIONS.UPDATE, {
192197
id: ids.container,
193198
type: 'loop',
194199
config: { iterations: 42 },
195200
})
196201

197202
expect(await readSubflows()).toEqual([{ id: ids.container, config: lockedLoopConfig }])
198203
expect(result).toEqual({ reconcile: true })
204+
expect(updated).toEqual({ reconcile: true })
199205
})
200206

201207
check('an add that touches no lock keeps collaborators on the payload', async () => {
@@ -231,7 +237,7 @@ describe('block locks against PostgreSQL', () => {
231237
)
232238

233239
check(
234-
'replace-state keeps protected blocks, their incoming edges and loop config as stored, and drops blocks nested into a lock',
240+
'replace-state keeps protected blocks, their incoming edges and loop config as stored, and drops what a lock or a removed parent no longer allows',
235241
async () => {
236242
const added = generateId()
237243
const nestedNew = generateId()
@@ -245,7 +251,11 @@ describe('block locks against PostgreSQL', () => {
245251
data: { parentId: ids.container, extent: 'parent' },
246252
}),
247253
},
248-
edges: [{ id: generateId(), source: ids.free, target: nestedNew }],
254+
edges: [
255+
{ id: generateId(), source: ids.free, target: nestedNew },
256+
// Retargets the protected edge under its own id.
257+
{ id: ids.edgeIntoLocked, source: ids.free, target: added },
258+
],
249259
loops: { [ids.container]: { ...lockedLoopConfig, iterations: 99 } },
250260
parallels: {},
251261
},
@@ -258,12 +268,14 @@ describe('block locks against PostgreSQL', () => {
258268
expect(blocks[ids.free]).toMatchObject({ locked: false, name: 'Free renamed' })
259269
expect(blocks[added]).toMatchObject({ locked: false })
260270
expect(blocks[nestedNew]).toBeUndefined()
271+
// The replacement removed its unlocked parent, so the locked child goes with it.
272+
expect(blocks[ids.lockedChild]).toBeUndefined()
261273

262274
const edges = await db
263-
.select()
275+
.select({ id: workflowEdges.id, target: workflowEdges.targetBlockId })
264276
.from(workflowEdges)
265277
.where(eq(workflowEdges.workflowId, workflowId))
266-
expect(edges.map((edge) => edge.id)).toEqual([ids.edgeIntoLocked])
278+
expect(edges).toEqual([{ id: ids.edgeIntoLocked, target: ids.locked }])
267279

268280
expect(await readSubflows()).toEqual([{ id: ids.container, config: lockedLoopConfig }])
269281
expect(result).toEqual({ reconcile: true })

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

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -482,7 +482,7 @@ export async function persistWorkflowOperation(
482482
await handleEdgesOperationTx(tx, workflowId, op, payload)
483483
break
484484
case OPERATION_TARGETS.SUBFLOW:
485-
await handleSubflowOperationTx(tx, workflowId, op, payload)
485+
reconcile = await handleSubflowOperationTx(tx, workflowId, op, payload)
486486
break
487487
case OPERATION_TARGETS.SUBBLOCK:
488488
await handleSubblockOperationTx(tx, workflowId, op, payload)
@@ -1828,7 +1828,7 @@ async function handleSubflowOperationTx(
18281828
workflowId: string,
18291829
operation: string,
18301830
payload: any
1831-
) {
1831+
): Promise<boolean> {
18321832
switch (operation) {
18331833
case SUBFLOW_OPERATIONS.UPDATE: {
18341834
if (!payload.id || !payload.config) {
@@ -1839,7 +1839,7 @@ async function handleSubflowOperationTx(
18391839
logger.info(
18401840
`Skipping update of subflow ${payload.id} - it is locked or in a locked container`
18411841
)
1842-
break
1842+
return true
18431843
}
18441844

18451845
logger.debug(`Updating subflow ${payload.id} with config:`, payload.config)
@@ -1953,7 +1953,7 @@ async function handleSubflowOperationTx(
19531953
.where(and(eq(workflowBlocks.id, payload.id), eq(workflowBlocks.workflowId, workflowId)))
19541954
}
19551955

1956-
break
1956+
return false
19571957
}
19581958

19591959
default:
@@ -2277,20 +2277,18 @@ async function handleWorkflowOperationTx(
22772277
incomingSubflows.filter(({ id }) => merged.blocks[id]).map((row) => [row.id, row])
22782278
),
22792279
...Object.fromEntries(
2280-
storedSubflows
2281-
.filter(({ id }) => merged.protectedBlockIds.has(id))
2282-
.map((row) => [row.id, row])
2280+
storedSubflows.filter(({ id }) => merged.keptBlockIds.has(id)).map((row) => [row.id, row])
22832281
),
22842282
})
22852283
if (subflowValues.length > 0) {
22862284
await tx.insert(workflowSubflows).values(subflowValues)
22872285
}
22882286

22892287
logger.info(`Successfully replaced workflow state for ${workflowId}`)
2290-
// A graph holding protected blocks may have been kept over the payload; comparing the
2288+
// A graph holding locked blocks may have been kept over the payload; comparing the
22912289
// stored rows against it field by field is not worth the precision, so re-sync.
22922290
return (
2293-
merged.protectedBlockIds.size > 0 ||
2291+
storedBlocks.some((row) => row.locked) ||
22942292
Object.values((blocks || {}) as Record<string, { locked?: unknown }>).some(
22952293
(block) => block.locked
22962294
)

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

Lines changed: 43 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,26 @@ import { type IRoomManager, type UserSession, workflowRoom as wf } from '@/rooms
2323
const logger = createLogger('OperationsHandlers')
2424

2525
/**
26-
* Tells every client in the room, the sender included, to reload the stored graph: persistence
27-
* kept lock-protected state over the payload they applied optimistically.
26+
* Relays a persisted operation to the room. When persistence kept lock-protected state over
27+
* the payload, every client, the sender included, is told to reload the stored graph instead
28+
* of applying a payload that no longer describes what was saved.
2829
*/
29-
function emitLockReconciliation(roomManager: IRoomManager, workflowId: string) {
30-
roomManager.emitToRoom<WorkflowUpdatedBroadcast>(wf(workflowId), 'workflow-updated', {
31-
workflowId,
32-
message: 'Locked blocks were kept as stored',
33-
timestamp: Date.now(),
34-
})
30+
function relayPersistedOperation(
31+
socket: AuthenticatedSocket,
32+
roomManager: IRoomManager,
33+
workflowId: string,
34+
reconcile: boolean,
35+
broadcast: object
36+
) {
37+
if (reconcile) {
38+
roomManager.emitToRoom<WorkflowUpdatedBroadcast>(wf(workflowId), 'workflow-updated', {
39+
workflowId,
40+
message: 'Locked blocks were kept as stored',
41+
timestamp: Date.now(),
42+
})
43+
return
44+
}
45+
socket.to(workflowId).emit('workflow-operation', broadcast)
3546
}
3647

3748
export function setupOperationsHandlers(socket: AuthenticatedSocket, roomManager: IRoomManager) {
@@ -337,20 +348,16 @@ export function setupOperationsHandlers(socket: AuthenticatedSocket, roomManager
337348

338349
await roomManager.updateRoomLastModified(wf(workflowId))
339350

340-
if (reconcile) {
341-
emitLockReconciliation(roomManager, workflowId)
342-
} else {
343-
socket.to(workflowId).emit('workflow-operation', {
344-
operation,
345-
target,
346-
payload,
347-
timestamp: operationTimestamp,
348-
senderId: socket.id,
349-
userId: session.userId,
350-
userName: session.userName,
351-
metadata: { workflowId, operationId: generateId() },
352-
})
353-
}
351+
relayPersistedOperation(socket, roomManager, workflowId, reconcile, {
352+
operation,
353+
target,
354+
payload,
355+
timestamp: operationTimestamp,
356+
senderId: socket.id,
357+
userId: session.userId,
358+
userName: session.userName,
359+
metadata: { workflowId, operationId: generateId() },
360+
})
354361

355362
if (operationId) {
356363
socket.emit('operation-confirmed', {
@@ -373,20 +380,16 @@ export function setupOperationsHandlers(socket: AuthenticatedSocket, roomManager
373380

374381
await roomManager.updateRoomLastModified(wf(workflowId))
375382

376-
if (reconcile) {
377-
emitLockReconciliation(roomManager, workflowId)
378-
} else {
379-
socket.to(workflowId).emit('workflow-operation', {
380-
operation,
381-
target,
382-
payload,
383-
timestamp: operationTimestamp,
384-
senderId: socket.id,
385-
userId: session.userId,
386-
userName: session.userName,
387-
metadata: { workflowId, operationId: generateId() },
388-
})
389-
}
383+
relayPersistedOperation(socket, roomManager, workflowId, reconcile, {
384+
operation,
385+
target,
386+
payload,
387+
timestamp: operationTimestamp,
388+
senderId: socket.id,
389+
userId: session.userId,
390+
userName: session.userName,
391+
metadata: { workflowId, operationId: generateId() },
392+
})
390393

391394
if (operationId) {
392395
socket.emit('operation-confirmed', { operationId, serverTimestamp: Date.now() })
@@ -582,7 +585,7 @@ export function setupOperationsHandlers(socket: AuthenticatedSocket, roomManager
582585
}
583586

584587
// For non-position operations, persist first then broadcast
585-
await persistWorkflowOperation(workflowId, {
588+
const { reconcile } = await persistWorkflowOperation(workflowId, {
586589
operation,
587590
target,
588591
payload,
@@ -592,21 +595,16 @@ export function setupOperationsHandlers(socket: AuthenticatedSocket, roomManager
592595

593596
await roomManager.updateRoomLastModified(wf(workflowId))
594597

595-
const broadcastData = {
598+
relayPersistedOperation(socket, roomManager, workflowId, reconcile, {
596599
operation,
597600
target,
598601
payload,
599602
timestamp: operationTimestamp,
600603
senderId: socket.id,
601604
userId: session.userId,
602605
userName: session.userName,
603-
metadata: {
604-
workflowId,
605-
operationId: generateId(),
606-
},
607-
}
608-
609-
socket.to(workflowId).emit('workflow-operation', broadcastData)
606+
metadata: { workflowId, operationId: generateId() },
607+
})
610608

611609
if (operationId) {
612610
socket.emit('operation-confirmed', {

‎packages/workflow-types/src/workflow.ts‎

Lines changed: 35 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -258,20 +258,22 @@ interface WorkflowLockGraph<B, E> {
258258
* - a block protected in `stored` (locked, or inside a locked container) is kept
259259
* exactly as stored, even when `incoming` changes or omits it, and so are the
260260
* edges into it, matching the edge rules that refuse adding or removing them;
261+
* - a protected block whose unlocked ancestor `incoming` removes goes with that
262+
* ancestor, as it does when the ancestor is deleted directly;
261263
* - every other block is written unlocked;
262264
* - an incoming block that would land inside a locked container is dropped,
263265
* together with the edges that touch it.
264266
*
265-
* Blocks are keyed by their own `id`, never the record key, because that is the
266-
* value persistence writes.
267+
* Blocks and edges are keyed by their own `id`, never the record key, because
268+
* that is the value persistence writes.
267269
*/
268270
export function preserveProtectedWorkflowBlocks<
269271
B extends WorkflowLockBlock & { id: string },
270-
E extends WorkflowEdgeEndpoints,
272+
E extends WorkflowEdgeEndpoints & { id: string },
271273
>(
272274
stored: WorkflowLockGraph<B, E>,
273275
incoming: WorkflowLockGraph<B, E>
274-
): WorkflowLockGraph<B, E> & { protectedBlockIds: Set<string> } {
276+
): WorkflowLockGraph<B, E> & { keptBlockIds: Set<string> } {
275277
const protectedBlockIds = new Set(
276278
Object.keys(stored.blocks).filter((id) => isWorkflowBlockProtected(id, stored.blocks))
277279
)
@@ -280,26 +282,44 @@ export function preserveProtectedWorkflowBlocks<
280282
for (const block of Object.values(incoming.blocks)) {
281283
if (!protectedBlockIds.has(block.id)) blocks[block.id] = { ...block, locked: false }
282284
}
283-
for (const id of protectedBlockIds) blocks[id] = stored.blocks[id]
284285

285-
const droppedBlockIds = new Set(
286-
Object.keys(blocks).filter(
287-
(id) => !protectedBlockIds.has(id) && isWorkflowBlockAncestorLocked(id, blocks)
288-
)
289-
)
290-
for (const id of droppedBlockIds) delete blocks[id]
286+
const hasRemovedAncestor = (id: string) => {
287+
const visited = new Set<string>()
288+
let parentId = getWorkflowBlockParentId(stored.blocks[id])
289+
while (parentId && !visited.has(parentId)) {
290+
visited.add(parentId)
291+
if (!protectedBlockIds.has(parentId) && !blocks[parentId]) return true
292+
parentId = getWorkflowBlockParentId(stored.blocks[parentId])
293+
}
294+
return false
295+
}
296+
const keptBlockIds = new Set([...protectedBlockIds].filter((id) => !hasRemovedAncestor(id)))
297+
for (const id of keptBlockIds) blocks[id] = stored.blocks[id]
291298

299+
const removedBlockIds = new Set([
300+
...[...protectedBlockIds].filter((id) => !keptBlockIds.has(id)),
301+
...Object.keys(blocks).filter(
302+
(id) => !keptBlockIds.has(id) && isWorkflowBlockAncestorLocked(id, blocks)
303+
),
304+
])
305+
for (const id of removedBlockIds) delete blocks[id]
306+
307+
const keptEdges = stored.edges.filter(
308+
(edge) => keptBlockIds.has(edge.target) && blocks[edge.source]
309+
)
310+
const keptEdgeIds = new Set(keptEdges.map((edge) => edge.id))
292311
const edges = [
293312
...incoming.edges.filter(
294313
(edge) =>
314+
!keptEdgeIds.has(edge.id) &&
295315
!protectedBlockIds.has(edge.target) &&
296-
!droppedBlockIds.has(edge.source) &&
297-
!droppedBlockIds.has(edge.target)
316+
!removedBlockIds.has(edge.source) &&
317+
!removedBlockIds.has(edge.target)
298318
),
299-
...stored.edges.filter((edge) => protectedBlockIds.has(edge.target) && blocks[edge.source]),
319+
...keptEdges,
300320
]
301321

302-
return { blocks, edges, protectedBlockIds }
322+
return { blocks, edges, keptBlockIds }
303323
}
304324

305325
export interface WorkflowEdgeEndpoints {

0 commit comments

Comments
 (0)