From 8ab05f1363bf0b43d7b9b3e6a3cf0c635ae436df Mon Sep 17 00:00:00 2001 From: kowshikdev Date: Thu, 3 Dec 2026 19:44:35 +0530 Subject: [PATCH] fix(realtime): answer each field edit only once its own flush settles A subblock or variable edit that arrived while an earlier flush of the same field was being stored joined that flush's operations. The earlier flush then confirmed it before its value was written, so when its own write failed the client had already dropped the operation and the edit was lost. The earlier sender also stayed excluded from the later broadcast and kept a stale value, and the variable audit named the later editor for the earlier change. Each flush now takes the value, operations and actor it stores, flushes of a field run in order, and the pending entry is removed only when no newer edit is waiting, so an edit made during a flush is no longer dropped. Co-Authored-By: Claude Opus 5.5 --- .../src/handlers/field-update-flush.test.ts | 240 ++++++++++++++++++ apps/realtime/src/handlers/subblocks.ts | 76 +++--- apps/realtime/src/handlers/variables.ts | 83 +++--- 3 files changed, 323 insertions(+), 76 deletions(-) create mode 100644 apps/realtime/src/handlers/field-update-flush.test.ts diff --git a/apps/realtime/src/handlers/field-update-flush.test.ts b/apps/realtime/src/handlers/field-update-flush.test.ts new file mode 100644 index 00000000000..4938342d09d --- /dev/null +++ b/apps/realtime/src/handlers/field-update-flush.test.ts @@ -0,0 +1,240 @@ +/** + * Collaborators edit the same field while an earlier edit is still being stored. Drives the real + * `subblock-update` and `variable-update` handlers against in-memory sockets: each edit may be + * reported only once its own write has finished, because a client drops an operation it is told is + * confirmed and never retries it. + */ +import { createDeferred } from '@sim/testing/helpers/deferred' +import { auditMock, auditMockFns } from '@sim/testing/mocks/audit.mock' +import { + databaseMock, + dbChainMockFns, + queueTableRows, + resetDbChainMock, +} from '@sim/testing/mocks/database.mock' +import { schemaMock } from '@sim/testing/mocks/schema.mock' +import { workflowAuthzMock, workflowAuthzMockFns } from '@sim/testing/mocks/workflow-authz.mock' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('@sim/audit', () => auditMock) +vi.mock('@sim/db', () => databaseMock) +vi.mock('@sim/db/schema', () => schemaMock) +vi.mock('@sim/platform-authz/workflow', () => workflowAuthzMock) + +import { setupSubblocksHandlers } from '@/handlers/subblocks' +import { setupVariablesHandlers } from '@/handlers/variables' +import type { IRoomManager } from '@/rooms' + +const WORKFLOW_ID = 'workflow-1' +const TARGET_ID = 'target-1' +const DEBOUNCE_MS = 25 + +type Handler = (payload: unknown) => Promise + +/** A workflow room of in-memory clients, recording what each one is sent. */ +function openRoom(socketIds: string[]) { + const outcomes: Record = {} + const values: Record = {} + for (const id of socketIds) { + outcomes[id] = [] + values[id] = [] + } + const deliver = (recipients: string[]) => ({ + emit: (event: string, payload: { operationId?: string; value?: unknown }) => { + for (const id of recipients) { + if (payload.operationId) outcomes[id].push(`${event}:${payload.operationId}`) + else values[id].push(payload.value) + } + }, + }) + const roomManager = { + isReady: () => true, + getRoomForSocket: async () => ({ type: 'workflow', id: WORKFLOW_ID }), + getUserSession: async (id: string) => ({ userId: `user-${id}`, userName: id }), + hasRoom: async () => true, + getRoomUsers: async () => + socketIds.map((id) => ({ socketId: id, userId: `user-${id}`, role: 'write' })), + updateUserActivity: async () => {}, + io: { + to: (room: string) => ({ + ...deliver(room === WORKFLOW_ID ? socketIds : [room]), + except: (excluded: string[]) => deliver(socketIds.filter((id) => !excluded.includes(id))), + }), + }, + } as unknown as IRoomManager + + const handlers: Record> = {} + for (const id of socketIds) { + handlers[id] = {} + const socket = { + id, + on: (event: string, handler: Handler) => { + handlers[id][event] = handler + }, + emit: () => {}, + } as unknown as Parameters[0] + setupSubblocksHandlers(socket, roomManager) + setupVariablesHandlers(socket, roomManager) + } + return { handlers, outcomes, values } +} + +describe.each([ + { + event: 'subblock-update', + field: { blockId: TARGET_ID, subblockId: 'code' }, + auditedUsers: [], + }, + { + event: 'variable-update', + field: { variableId: TARGET_ID, field: 'value' }, + auditedUsers: ['user-alice', 'user-bob'], + }, +])('$event while an earlier one is being stored', ({ event, field, auditedUsers }) => { + beforeEach(() => { + vi.useFakeTimers() + resetDbChainMock() + workflowAuthzMockFns.mockAuthorizeWorkflowByWorkspacePermission.mockResolvedValue({ + allowed: true, + workspacePermission: 'write', + }) + for (let read = 0; read < 6; read++) { + queueTableRows(schemaMock.workflow, [ + { id: WORKFLOW_ID, variables: { [TARGET_ID]: { id: TARGET_ID, value: '' } } }, + ]) + } + for (let read = 0; read < 3; read++) { + queueTableRows(schemaMock.workflowBlocks, [ + { id: TARGET_ID, subBlocks: {}, locked: false, data: {} }, + ]) + } + dbChainMockFns.returning.mockResolvedValue([{ id: TARGET_ID }]) + }) + + afterEach(() => { + vi.useRealTimers() + }) + + /** Alice's edit is mid-write when Bob's arrives; `release` lets her write finish. */ + async function overlappingEdits() { + const room = openRoom(['alice', 'bob', 'carol']) + const write = createDeferred() + dbChainMockFns.transaction.mockImplementationOnce(async (run) => { + await write.promise + return run(databaseMock.db) + }) + const send = (socketId: string, value: string, operationId = `op-${socketId}`) => + room.handlers[socketId][event]({ + workflowId: WORKFLOW_ID, + ...field, + value, + timestamp: Date.now(), + operationId, + }) + + await send('alice', 'from alice') + await vi.advanceTimersByTimeAsync(DEBOUNCE_MS) + await send('bob', 'from bob') + return { + ...room, + send, + release: async () => { + write.resolve() + await vi.advanceTimersByTimeAsync(0) + }, + } + } + + it('reports the second edit as failed, never confirmed, when its own write fails', async () => { + const { outcomes, release } = await overlappingEdits() + await release() + expect(outcomes).toEqual({ alice: ['operation-confirmed:op-alice'], bob: [], carol: [] }) + + dbChainMockFns.transaction.mockRejectedValueOnce(new Error('connection lost')) + await vi.advanceTimersByTimeAsync(DEBOUNCE_MS) + expect(outcomes).toEqual({ + alice: ['operation-confirmed:op-alice'], + bob: ['operation-failed:op-bob'], + carol: [], + }) + }) + + it('sends the stored value to the first client and no superseded value to the second', async () => { + const { values, release } = await overlappingEdits() + await release() + await vi.advanceTimersByTimeAsync(DEBOUNCE_MS) + + expect(values).toEqual({ alice: ['from bob'], bob: [], carol: ['from alice', 'from bob'] }) + }) + + it('audits each edit as the user who made it', async () => { + const { release } = await overlappingEdits() + await release() + await vi.advanceTimersByTimeAsync(DEBOUNCE_MS) + + const actors = auditMockFns.mockRecordAudit.mock.calls.map(([entry]) => entry.actorId) + expect(actors).toEqual(auditedUsers) + }) + + it('stores and sends the edits in order when the second is due before the first is stored', async () => { + const { outcomes, values, release } = await overlappingEdits() + await vi.advanceTimersByTimeAsync(DEBOUNCE_MS) + expect(outcomes).toEqual({ alice: [], bob: [], carol: [] }) + await release() + + expect(values).toEqual({ alice: ['from bob'], bob: [], carol: ['from alice', 'from bob'] }) + }) + + it('does not echo an edit to its sender when it joined one already waiting its turn', async () => { + const { outcomes, values, send, release } = await overlappingEdits() + await vi.advanceTimersByTimeAsync(DEBOUNCE_MS) + await send('carol', 'from carol') + await vi.advanceTimersByTimeAsync(DEBOUNCE_MS) + await release() + + expect(outcomes.carol).toEqual(['operation-confirmed:op-carol']) + expect(values.carol).toEqual([]) + }) + + it('keeps an edit made after the first is stored behind the second still being stored', async () => { + const { outcomes, send, release } = await overlappingEdits() + await release() + const write = createDeferred() + dbChainMockFns.transaction.mockImplementationOnce(async (run) => { + await write.promise + return run(databaseMock.db) + }) + await vi.advanceTimersByTimeAsync(DEBOUNCE_MS) + await send('carol', 'from carol') + await vi.advanceTimersByTimeAsync(DEBOUNCE_MS) + expect(outcomes).toEqual({ alice: ['operation-confirmed:op-alice'], bob: [], carol: [] }) + + write.resolve() + await vi.advanceTimersByTimeAsync(0) + expect(outcomes).toEqual({ + alice: ['operation-confirmed:op-alice'], + bob: ['operation-confirmed:op-bob'], + carol: ['operation-confirmed:op-carol'], + }) + }) + + it('answers a third edit that arrives while the second is being stored', async () => { + const { outcomes, send, release } = await overlappingEdits() + await release() + const write = createDeferred() + dbChainMockFns.transaction.mockImplementationOnce(async (run) => { + await write.promise + return run(databaseMock.db) + }) + await vi.advanceTimersByTimeAsync(DEBOUNCE_MS) + await send('alice', 'from alice again', 'op-alice-2') + write.resolve() + await vi.advanceTimersByTimeAsync(DEBOUNCE_MS) + + expect(outcomes).toEqual({ + alice: ['operation-confirmed:op-alice', 'operation-confirmed:op-alice-2'], + bob: ['operation-confirmed:op-bob'], + carol: [], + }) + }) +}) diff --git a/apps/realtime/src/handlers/subblocks.ts b/apps/realtime/src/handlers/subblocks.ts index 3c84cea5dd5..7c94f1ffdad 100644 --- a/apps/realtime/src/handlers/subblocks.ts +++ b/apps/realtime/src/handlers/subblocks.ts @@ -17,9 +17,13 @@ const logger = createLogger('SubblocksHandlers') const DEBOUNCE_INTERVAL_MS = 25 type PendingSubblock = { - latest: { blockId: string; subblockId: string; value: any; timestamp: number } - timeout: NodeJS.Timeout - // Map operationId -> socketId to emit confirmations/failures to correct clients + /** Newest value, until a flush takes it. */ + latest?: { blockId: string; subblockId: string; value: any; timestamp: number } + timeout?: NodeJS.Timeout + /** Settles with the last flush due, so one field's flushes run one at a time, in order. */ + lastFlush: Promise + // Map operationId -> socketId to emit confirmations/failures to correct clients. + // Holds only operations no flush has taken yet. opToSocket: Map } @@ -188,31 +192,23 @@ export function setupSubblocksHandlers(socket: AuthenticatedSocket, roomManager: // Server-side debounce/coalesce by workflowId+blockId+subblockId const debouncedKey = `${workflowId}:${blockId}:${subblockId}` - const existing = pendingSubblockUpdates.get(debouncedKey) - if (existing) { - clearTimeout(existing.timeout) - existing.latest = { blockId, subblockId, value, timestamp } - if (operationId) existing.opToSocket.set(operationId, socket.id) - existing.timeout = setTimeout(async () => { - await flushSubblockUpdate(workflowId, existing, roomManager) - pendingSubblockUpdates.delete(debouncedKey) - }, DEBOUNCE_INTERVAL_MS) - } else { - const opToSocket = new Map() - if (operationId) opToSocket.set(operationId, socket.id) - const timeout = setTimeout(async () => { - const pending = pendingSubblockUpdates.get(debouncedKey) - if (pending) { - await flushSubblockUpdate(workflowId, pending, roomManager) - pendingSubblockUpdates.delete(debouncedKey) - } - }, DEBOUNCE_INTERVAL_MS) - pendingSubblockUpdates.set(debouncedKey, { - latest: { blockId, subblockId, value, timestamp }, - timeout, - opToSocket, - }) + const pending: PendingSubblock = pendingSubblockUpdates.get(debouncedKey) ?? { + opToSocket: new Map(), + lastFlush: Promise.resolve(), } + pendingSubblockUpdates.set(debouncedKey, pending) + pending.latest = { blockId, subblockId, value, timestamp } + if (operationId) pending.opToSocket.set(operationId, socket.id) + clearTimeout(pending.timeout) + const timeout = setTimeout(async () => { + pending.lastFlush = pending.lastFlush.then(() => + flushSubblockUpdate(workflowId, pending, roomManager) + ) + await pending.lastFlush + // A newer update has its own timer and still needs this entry. + if (pending.timeout === timeout) pendingSubblockUpdates.delete(debouncedKey) + }, DEBOUNCE_INTERVAL_MS) + pending.timeout = timeout } catch (error) { logger.error('Error handling subblock update:', error) @@ -241,7 +237,14 @@ async function flushSubblockUpdate( pending: PendingSubblock, roomManager: IRoomManager ) { - const { blockId, subblockId, value, timestamp } = pending.latest + // Take the value with its own operations: one that arrives while this is being stored belongs to + // the next flush, and must not be answered before its value is persisted. + const { latest, opToSocket: operations } = pending + if (!latest) return + pending.latest = undefined + pending.opToSocket = new Map() + + const { blockId, subblockId, value, timestamp } = latest const io = roomManager.io try { @@ -253,7 +256,7 @@ async function flushSubblockUpdate( .limit(1) if (workflowExists.length === 0) { - pending.opToSocket.forEach((socketId, opId) => { + operations.forEach((socketId, opId) => { io.to(socketId).emit('operation-failed', { operationId: opId, error: 'Workflow not found', @@ -267,7 +270,7 @@ async function flushSubblockUpdate( await assertWorkflowMutable(workflowId) } catch (error) { if (error instanceof WorkflowLockedError) { - pending.opToSocket.forEach((socketId, opId) => { + operations.forEach((socketId, opId) => { io.to(socketId).emit('operation-failed', { operationId: opId, error: error.message, @@ -342,8 +345,9 @@ async function flushSubblockUpdate( }) if (updateSuccessful) { - // Broadcast to room excluding all senders (works cross-pod via Redis adapter) - const senderSocketIds = [...pending.opToSocket.values()] + // Broadcast to room excluding all senders (works cross-pod via Redis adapter), and those whose + // newer value is waiting for the next flush, which would not send it back to them + const senderSocketIds = [...operations.values(), ...pending.opToSocket.values()] const broadcastPayload = { workflowId, blockId, @@ -358,21 +362,21 @@ async function flushSubblockUpdate( } // Confirm all coalesced operationIds (io.to(socketId) works cross-pod) - pending.opToSocket.forEach((socketId, opId) => { + operations.forEach((socketId, opId) => { io.to(socketId).emit('operation-confirmed', { operationId: opId, serverTimestamp: Date.now(), }) }) } else if (blockLocked) { - pending.opToSocket.forEach((socketId, opId) => { + operations.forEach((socketId, opId) => { io.to(socketId).emit('operation-confirmed', { operationId: opId, serverTimestamp: Date.now(), }) }) } else { - pending.opToSocket.forEach((socketId, opId) => { + operations.forEach((socketId, opId) => { io.to(socketId).emit('operation-failed', { operationId: opId, error: 'Block no longer exists', @@ -382,7 +386,7 @@ async function flushSubblockUpdate( } } catch (error) { logger.error('Error flushing subblock update:', error) - pending.opToSocket.forEach((socketId, opId) => { + operations.forEach((socketId, opId) => { io.to(socketId).emit('operation-failed', { operationId: opId, error: getErrorMessage(error, 'Unknown error'), diff --git a/apps/realtime/src/handlers/variables.ts b/apps/realtime/src/handlers/variables.ts index 31903ba00c8..31070948380 100644 --- a/apps/realtime/src/handlers/variables.ts +++ b/apps/realtime/src/handlers/variables.ts @@ -17,8 +17,12 @@ const logger = createLogger('VariablesHandlers') const DEBOUNCE_INTERVAL_MS = 25 type PendingVariable = { - latest: { variableId: string; field: string; value: any; timestamp: number } - timeout: NodeJS.Timeout + /** Newest value, until a flush takes it. */ + latest?: { variableId: string; field: string; value: any; timestamp: number } + timeout?: NodeJS.Timeout + /** Settles with the last flush due, so one field's flushes run one at a time, in order. */ + lastFlush: Promise + /** Operations no flush has taken yet, by the socket to answer. */ opToSocket: Map /** Most recent writer, used as the audit actor when the coalesced update is persisted. */ actorId: string @@ -179,35 +183,26 @@ export function setupVariablesHandlers(socket: AuthenticatedSocket, roomManager: await roomManager.updateUserActivity(wf(workflowId), socket.id, { lastActivity: Date.now() }) const debouncedKey = `${workflowId}:${variableId}:${field}` - const existing = pendingVariableUpdates.get(debouncedKey) - if (existing) { - clearTimeout(existing.timeout) - existing.latest = { variableId, field, value, timestamp } - existing.actorId = session.userId - existing.actorName = session.userName - if (operationId) existing.opToSocket.set(operationId, socket.id) - existing.timeout = setTimeout(async () => { - await flushVariableUpdate(workflowId, existing, roomManager) - pendingVariableUpdates.delete(debouncedKey) - }, DEBOUNCE_INTERVAL_MS) - } else { - const opToSocket = new Map() - if (operationId) opToSocket.set(operationId, socket.id) - const timeout = setTimeout(async () => { - const pending = pendingVariableUpdates.get(debouncedKey) - if (pending) { - await flushVariableUpdate(workflowId, pending, roomManager) - pendingVariableUpdates.delete(debouncedKey) - } - }, DEBOUNCE_INTERVAL_MS) - pendingVariableUpdates.set(debouncedKey, { - latest: { variableId, field, value, timestamp }, - timeout, - opToSocket, - actorId: session.userId, - actorName: session.userName, - }) + const pending: PendingVariable = pendingVariableUpdates.get(debouncedKey) ?? { + opToSocket: new Map(), + lastFlush: Promise.resolve(), + actorId: session.userId, } + pendingVariableUpdates.set(debouncedKey, pending) + pending.latest = { variableId, field, value, timestamp } + pending.actorId = session.userId + pending.actorName = session.userName + if (operationId) pending.opToSocket.set(operationId, socket.id) + clearTimeout(pending.timeout) + const timeout = setTimeout(async () => { + pending.lastFlush = pending.lastFlush.then(() => + flushVariableUpdate(workflowId, pending, roomManager) + ) + await pending.lastFlush + // A newer update has its own timer and still needs this entry. + if (pending.timeout === timeout) pendingVariableUpdates.delete(debouncedKey) + }, DEBOUNCE_INTERVAL_MS) + pending.timeout = timeout } catch (error) { logger.error('Error handling variable update:', error) @@ -236,7 +231,14 @@ async function flushVariableUpdate( pending: PendingVariable, roomManager: IRoomManager ) { - const { variableId, field, value, timestamp } = pending.latest + // Take the value with its own operations: one that arrives while this is being stored belongs to + // the next flush, and must not be answered before its value is persisted. + const { latest, opToSocket: operations, actorId, actorName } = pending + if (!latest) return + pending.latest = undefined + pending.opToSocket = new Map() + + const { variableId, field, value, timestamp } = latest const io = roomManager.io try { @@ -251,7 +253,7 @@ async function flushVariableUpdate( .limit(1) if (workflowExists.length === 0) { - pending.opToSocket.forEach((socketId, opId) => { + operations.forEach((socketId, opId) => { io.to(socketId).emit('operation-failed', { operationId: opId, error: 'Workflow not found', @@ -265,7 +267,7 @@ async function flushVariableUpdate( await assertWorkflowMutable(workflowId) } catch (error) { if (error instanceof WorkflowLockedError) { - pending.opToSocket.forEach((socketId, opId) => { + operations.forEach((socketId, opId) => { io.to(socketId).emit('operation-failed', { operationId: opId, error: error.message, @@ -315,8 +317,8 @@ async function flushVariableUpdate( const workflowRow = workflowExists[0] recordAudit({ workspaceId: workflowRow.workspaceId ?? null, - actorId: pending.actorId, - actorName: pending.actorName, + actorId, + actorName, action: AuditAction.WORKFLOW_VARIABLES_UPDATED, resourceType: AuditResourceType.WORKFLOW, resourceId: workflowId, @@ -325,8 +327,9 @@ async function flushVariableUpdate( metadata: { variableId, field }, }) - // Broadcast to room excluding all senders (works cross-pod via Redis adapter) - const senderSocketIds = [...pending.opToSocket.values()] + // Broadcast to room excluding all senders (works cross-pod via Redis adapter), and those whose + // newer value is waiting for the next flush, which would not send it back to them + const senderSocketIds = [...operations.values(), ...pending.opToSocket.values()] const broadcastPayload = { workflowId, variableId, @@ -341,7 +344,7 @@ async function flushVariableUpdate( } // Confirm all coalesced operationIds (io.to(socketId) works cross-pod) - pending.opToSocket.forEach((socketId, opId) => { + operations.forEach((socketId, opId) => { io.to(socketId).emit('operation-confirmed', { operationId: opId, serverTimestamp: Date.now(), @@ -350,7 +353,7 @@ async function flushVariableUpdate( logger.debug(`Flushed variable update ${workflowId}: ${variableId}.${field}`) } else { - pending.opToSocket.forEach((socketId, opId) => { + operations.forEach((socketId, opId) => { io.to(socketId).emit('operation-failed', { operationId: opId, error: 'Variable no longer exists', @@ -360,7 +363,7 @@ async function flushVariableUpdate( } } catch (error) { logger.error('Error flushing variable update:', error) - pending.opToSocket.forEach((socketId, opId) => { + operations.forEach((socketId, opId) => { io.to(socketId).emit('operation-failed', { operationId: opId, error: getErrorMessage(error, 'Unknown error'),