From d6bc1d7b6962580c1f0eb88f48eddcd0ac34b0ea Mon Sep 17 00:00:00 2001 From: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com> Date: Sat, 6 Jun 2026 13:07:32 -0400 Subject: [PATCH] fix(parts-batcher): defer operations when target message is missing from cache (#262) * fix(parts-batcher): defer operations when target message is missing from cache * fix(parts-batcher): add TTL for deferred operations to prevent repeated invalidations --- frontend/src/hooks/useSSE.test.tsx | 12 +-- frontend/src/lib/partsBatcher.test.ts | 111 ++++++++++++++++++----- frontend/src/lib/partsBatcher.ts | 126 +++++++++++++++++++++----- 3 files changed, 196 insertions(+), 53 deletions(-) diff --git a/frontend/src/hooks/useSSE.test.tsx b/frontend/src/hooks/useSSE.test.tsx index e1c9795c..3ab6fbd1 100644 --- a/frontend/src/hooks/useSSE.test.tsx +++ b/frontend/src/hooks/useSSE.test.tsx @@ -4,7 +4,8 @@ import type { ReactNode } from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { useSSE } from './useSSE' import { useSessionStatus } from '../stores/sessionStatusStore' -import type { Part, MessageWithParts } from '@/api/types' +import type { MessageWithParts } from '@/api/types' +import { createTextPart } from '@/lib/partsBatcher' const mocks = vi.hoisted(() => ({ getSessionStatuses: vi.fn(), @@ -293,14 +294,14 @@ describe('useSSE', () => { ['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo-a'], [{ ...assistantMessage('session-1', 'message-1'), - parts: [textPart('session-1', 'message-1', 'part-1', 'A')], + parts: [createTextPart('session-1', 'message-1', 'part-1', 'A')], }], ) queryClient.setQueryData( ['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo-b'], [{ ...assistantMessage('session-1', 'message-1'), - parts: [textPart('session-1', 'message-1', 'part-1', 'B')], + parts: [createTextPart('session-1', 'message-1', 'part-1', 'B')], }], ) @@ -377,7 +378,7 @@ describe('useSSE', () => { ['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo'], [{ ...assistantMessage('session-1', 'message-1'), - parts: [textPart('session-1', 'message-1', 'part-1', '')], + parts: [createTextPart('session-1', 'message-1', 'part-1', '')], }], ) @@ -450,6 +451,3 @@ function assistantMessage(sessionID: string, messageID: string): MessageWithPart } } -function textPart(sessionID: string, messageID: string, partID: string, text: string): Part { - return { id: partID, sessionID, messageID, type: 'text', text } as Part -} diff --git a/frontend/src/lib/partsBatcher.test.ts b/frontend/src/lib/partsBatcher.test.ts index 6663c788..3ec6c068 100644 --- a/frontend/src/lib/partsBatcher.test.ts +++ b/frontend/src/lib/partsBatcher.test.ts @@ -1,7 +1,7 @@ import { QueryClient } from '@tanstack/react-query' -import { describe, it, expect, vi } from 'vitest' -import { createPartsBatcher } from './partsBatcher' -import type { Part, MessageWithParts } from '@/api/types' +import { describe, it, expect, vi, afterEach } from 'vitest' +import { createPartsBatcher, createTextPart, DEFERRED_OPERATION_TTL_MS } from './partsBatcher' +import type { MessageWithParts } from '@/api/types' function assistantMessage(sessionID: string, messageID: string): MessageWithParts { return { @@ -23,21 +23,21 @@ function assistantMessage(sessionID: string, messageID: string): MessageWithPart } } -function textPart(sessionID: string, messageID: string, partID: string, text: string): Part { - return { id: partID, sessionID, messageID, type: 'text', text } as Part -} - function createManyCachedMessages(count: number, sessionID: string): MessageWithParts[] { const messages: MessageWithParts[] = [] for (let i = 0; i < count; i++) { const msg = assistantMessage(sessionID, `msg-${i}`) - msg.parts = [textPart(sessionID, `msg-${i}`, `part-${i}`, `base text ${i}`)] + msg.parts = [createTextPart(sessionID, `msg-${i}`, `part-${i}`, `base text ${i}`)] messages.push(msg) } return messages } describe('createPartsBatcher', () => { + afterEach(() => { + vi.useRealTimers() + }) + it('invalidates when part deltas arrive before message cache exists and applies a later authoritative upsert', () => { const queryClient = new QueryClient() const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries') @@ -59,7 +59,7 @@ describe('createPartsBatcher', () => { [assistantMessage('session-1', 'message-1')], ) - batcher.queuePartUpdate('session-1', textPart('session-1', 'message-1', 'part-1', 'Hello world'), '/repo') + batcher.queuePartUpdate('session-1', createTextPart('session-1', 'message-1', 'part-1', 'Hello world'), '/repo') batcher.flush() const data = queryClient.getQueryData([ @@ -82,7 +82,7 @@ describe('createPartsBatcher', () => { [assistantMessage('session-1', 'message-1')], ) - batcher.queuePartUpdate('session-1', textPart('session-1', 'message-1', 'part-1', 'authoritative text'), '/repo') + batcher.queuePartUpdate('session-1', createTextPart('session-1', 'message-1', 'part-1', 'authoritative text'), '/repo') batcher.flush() const data = queryClient.getQueryData([ @@ -100,7 +100,6 @@ describe('createPartsBatcher', () => { it('does not replay unapplied deltas onto refetched authoritative data', () => { const queryClient = new QueryClient() - const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries') const batcher = createPartsBatcher(queryClient, 'http://localhost:5551') queryClient.setQueryData( @@ -111,21 +110,91 @@ describe('createPartsBatcher', () => { batcher.queuePartDelta('session-1', 'message-1', 'part-1', 'text', ' stale', '/repo') batcher.flush() + let data = queryClient.getQueryData([ + 'opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo', + ]) + expect(data![0].parts[0]).toHaveProperty('text', ' stale') + + queryClient.setQueryData( + ['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo'], + [{ ...assistantMessage('session-1', 'message-1'), parts: [createTextPart('session-1', 'message-1', 'part-1', 'fresh')] }], + ) + + batcher.flush() + + data = queryClient.getQueryData([ + 'opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo', + ]) + expect(data![0].parts[0]).toHaveProperty('text', 'fresh') + }) + + it('keeps text deltas pending until a later message update creates the assistant message', () => { + const queryClient = new QueryClient() + const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries') + const batcher = createPartsBatcher(queryClient, 'http://localhost:5551') + + queryClient.setQueryData( + ['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo'], + [assistantMessage('session-1', 'message-old')], + ) + + batcher.queuePartDelta('session-1', 'message-new', 'part-1', 'text', 'streamed', '/repo') + batcher.flush() + expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo'], }) queryClient.setQueryData( ['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo'], - [{ ...assistantMessage('session-1', 'message-1'), parts: [textPart('session-1', 'message-1', 'part-1', 'fresh')] }], + [assistantMessage('session-1', 'message-old'), assistantMessage('session-1', 'message-new')], ) - batcher.flush() + batcher.flush({ sessionID: 'session-1', directory: '/repo' }) const data = queryClient.getQueryData([ 'opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo', ]) - expect(data![0].parts[0]).toHaveProperty('text', 'fresh') + expect(data![1].parts).toHaveLength(1) + expect(data![1].parts[0]).toMatchObject({ + id: 'part-1', + sessionID: 'session-1', + messageID: 'message-new', + type: 'text', + text: 'streamed', + }) + }) + + it('invalidates once while deferring, then drops the operation after the TTL elapses for a never-arriving message', () => { + vi.useFakeTimers() + const queryClient = new QueryClient() + const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries') + const batcher = createPartsBatcher(queryClient, 'http://localhost:5551') + + queryClient.setQueryData( + ['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo'], + [assistantMessage('session-1', 'message-old')], + ) + + batcher.queuePartDelta('session-1', 'message-missing', 'part-1', 'text', 'streamed', '/repo') + batcher.flush() + expect(invalidateSpy).toHaveBeenCalledTimes(1) + + batcher.flush() + batcher.flush() + expect(invalidateSpy).toHaveBeenCalledTimes(1) + + vi.advanceTimersByTime(DEFERRED_OPERATION_TTL_MS + 1) + batcher.flush() + batcher.flush() + expect(invalidateSpy).toHaveBeenCalledTimes(1) + + const data = queryClient.getQueryData([ + 'opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo', + ]) + expect(data).toHaveLength(1) + expect(data![0].info.id).toBe('message-old') + expect(data![0].parts).toHaveLength(0) }) it('applies deltas queued after an authoritative upsert in the same batch', () => { @@ -137,7 +206,7 @@ describe('createPartsBatcher', () => { [assistantMessage('session-1', 'message-1')], ) - batcher.queuePartUpdate('session-1', textPart('session-1', 'message-1', 'part-1', 'snapshot'), '/repo') + batcher.queuePartUpdate('session-1', createTextPart('session-1', 'message-1', 'part-1', 'snapshot'), '/repo') batcher.queuePartDelta('session-1', 'message-1', 'part-1', 'text', ' later', '/repo') batcher.flush() @@ -202,8 +271,8 @@ describe('createPartsBatcher', () => { [{ ...assistantMessage('session-1', 'message-1'), parts: [ - textPart('session-1', 'message-1', 'part-1', 'first'), - textPart('session-1', 'message-1', 'part-2', 'second'), + createTextPart('session-1', 'message-1', 'part-1', 'first'), + createTextPart('session-1', 'message-1', 'part-2', 'second'), ], }], ) @@ -227,11 +296,11 @@ describe('createPartsBatcher', () => { queryClient.setQueryData( ['opencode', 'messages', 'http://localhost:5551', 'session-a', '/repo-a'], - [{ ...assistantMessage('session-a', 'msg-1'), parts: [textPart('session-a', 'msg-1', 'part-1', 'A1')] }], + [{ ...assistantMessage('session-a', 'msg-1'), parts: [createTextPart('session-a', 'msg-1', 'part-1', 'A1')] }], ) queryClient.setQueryData( ['opencode', 'messages', 'http://localhost:5551', 'session-b', '/repo-b'], - [{ ...assistantMessage('session-b', 'msg-2'), parts: [textPart('session-b', 'msg-2', 'part-2', 'B1')] }], + [{ ...assistantMessage('session-b', 'msg-2'), parts: [createTextPart('session-b', 'msg-2', 'part-2', 'B1')] }], ) batcher.queuePartDelta('session-a', 'msg-1', 'part-1', 'text', ' delta A', '/repo-a') @@ -264,7 +333,7 @@ describe('createPartsBatcher', () => { queryClient.setQueryData( ['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo'], - [{ ...assistantMessage('session-1', 'msg-1'), parts: [textPart('session-1', 'msg-1', 'part-1', 'text')] }], + [{ ...assistantMessage('session-1', 'msg-1'), parts: [createTextPart('session-1', 'msg-1', 'part-1', 'text')] }], ) batcher.queuePartDelta('session-1', 'msg-1', 'part-1', 'text', ' updated', '/repo') @@ -286,7 +355,7 @@ describe('createPartsBatcher', () => { ) queryClient.setQueryData( ['opencode', 'messages', 'http://localhost:5551', 'session-1', '/repo-b'], - [{ ...assistantMessage('session-1', 'message-1'), parts: [textPart('session-1', 'message-1', 'part-1', 'B')] }], + [{ ...assistantMessage('session-1', 'message-1'), parts: [createTextPart('session-1', 'message-1', 'part-1', 'B')] }], ) batcher.queuePartDelta('session-1', 'message-1', 'part-1', 'text', ' + chunk', '/repo-b') diff --git a/frontend/src/lib/partsBatcher.ts b/frontend/src/lib/partsBatcher.ts index ac6d5289..2c4df8e3 100644 --- a/frontend/src/lib/partsBatcher.ts +++ b/frontend/src/lib/partsBatcher.ts @@ -11,20 +11,54 @@ interface PartsBatcher { } type PartOperation = - | { type: 'upsert'; part: Part } - | { type: 'delta'; messageID: string; partID: string; field: string; delta: string } + | { type: 'upsert'; part: Part; deferred?: boolean } + | { type: 'delta'; messageID: string; partID: string; field: string; delta: string; deferred?: boolean } | { type: 'remove'; messageID: string; partID: string } type OperationGroup = { sessionID: string directory?: string operations: PartOperation[] + firstDeferredAt?: number } +export const DEFERRED_OPERATION_TTL_MS = 3000 + function groupKey(sessionID: string, directory?: string): string { return `${directory ?? ''}\0${sessionID}` } +function deferOperation(operation: PartOperation): PartOperation | undefined { + if (operation.type === 'remove') return undefined + return { ...operation, deferred: true } +} + +function isGroupExpired(group: OperationGroup, now: number): boolean { + return group.firstDeferredAt !== undefined && now - group.firstDeferredAt >= DEFERRED_OPERATION_TTL_MS +} + +function stampDeferred(group: OperationGroup, now: number): void { + if (group.firstDeferredAt === undefined) group.firstDeferredAt = now +} + +export function createTextPart(sessionID: string, messageID: string, partID: string, text: string): Part { + return { id: partID, sessionID, messageID, type: 'text', text } as Part +} + +function appendPart( + updatedData: MessageWithParts[], + msgIdx: number, + msg: MessageWithParts, + part: Part, + pIdx: Map, + supersededPartIDs: Set, +): void { + const nextParts = [...msg.parts, part] + updatedData[msgIdx] = { ...msg, parts: nextParts } + pIdx.set(part.id, nextParts.length - 1) + supersededPartIDs.add(part.id) +} + export function createPartsBatcher( queryClient: QueryClient, opcodeUrl: string, @@ -43,8 +77,8 @@ export function createPartsBatcher( const flush = (target?: { sessionID?: string; directory?: string }) => { if (pendingOperations.size === 0) return + const now = Date.now() const groupsToDelete: string[] = [] - const invalidatedGroupKeys = new Set() for (const [key, group] of pendingOperations.entries()) { if (target) { @@ -62,11 +96,18 @@ export function createPartsBatcher( const currentData = queryClient.getQueryData(queryKey) if (!currentData) { - if (!invalidatedGroupKeys.has(key)) { - invalidatedGroupKeys.add(key) + if (group.firstDeferredAt === undefined) { queryClient.invalidateQueries({ queryKey }) } - groupsToDelete.push(key) + const deferred = group.operations + .map(deferOperation) + .filter((operation): operation is PartOperation => Boolean(operation)) + if (deferred.length > 0 && !isGroupExpired(group, now)) { + stampDeferred(group, now) + group.operations = deferred + } else { + groupsToDelete.push(key) + } continue } @@ -74,6 +115,7 @@ export function createPartsBatcher( let dataMutated = false const unapplied: PartOperation[] = [] const supersededPartIDs = new Set() + const removedPartIDs = new Set() const messageIdxById = new Map() for (let i = 0; i < currentData.length; i++) { @@ -98,7 +140,8 @@ export function createPartsBatcher( if (operation.type === 'upsert') { const msgIdx = messageIdxById.get(operation.part.messageID) if (msgIdx === undefined) { - unapplied.push(operation) + const deferred = deferOperation(operation) + if (deferred) unapplied.push(deferred) continue } if (!dataMutated) { @@ -108,16 +151,18 @@ export function createPartsBatcher( const msg = updatedData[msgIdx] const pIdx = ensurePartIdx(msgIdx, msg.parts) const existingPartIdx = pIdx.get(operation.part.id) - let nextParts: Part[] - if (existingPartIdx !== undefined) { - nextParts = [...msg.parts] - nextParts[existingPartIdx] = operation.part - } else { - nextParts = [...msg.parts, operation.part] - pIdx.set(operation.part.id, nextParts.length - 1) + if (operation.deferred && existingPartIdx !== undefined) { + supersededPartIDs.add(operation.part.id) + continue + } + if (existingPartIdx !== undefined) { + const nextParts = [...msg.parts] + nextParts[existingPartIdx] = operation.part + updatedData[msgIdx] = { ...msg, parts: nextParts } + supersededPartIDs.add(operation.part.id) + } else { + appendPart(updatedData, msgIdx, msg, operation.part, pIdx, supersededPartIDs) } - updatedData[msgIdx] = { ...msg, parts: nextParts } - supersededPartIDs.add(operation.part.id) continue } @@ -140,13 +185,15 @@ export function createPartsBatcher( const nextParts = msg.parts.filter((part) => part.id !== operation.partID) updatedData[msgIdx] = { ...msg, parts: nextParts } partIdxCache.delete(msgIdx) + removedPartIDs.add(operation.partID) supersededPartIDs.add(operation.partID) continue } const msgIdx = messageIdxById.get(operation.messageID) if (msgIdx === undefined) { - unapplied.push(operation) + const deferred = deferOperation(operation) + if (deferred) unapplied.push(deferred) continue } if (!dataMutated) { @@ -155,9 +202,28 @@ export function createPartsBatcher( } const msg = updatedData[msgIdx] const pIdx = ensurePartIdx(msgIdx, msg.parts) + if (removedPartIDs.has(operation.partID)) { + continue + } const pIdxResult = pIdx.get(operation.partID) if (pIdxResult === undefined) { - unapplied.push(operation) + if (operation.field === 'text') { + appendPart( + updatedData, + msgIdx, + msg, + createTextPart(sessionID, operation.messageID, operation.partID, operation.delta), + pIdx, + supersededPartIDs, + ) + } else { + const deferred = deferOperation(operation) + if (deferred) unapplied.push(deferred) + } + continue + } + if (operation.deferred) { + supersededPartIDs.add(operation.partID) continue } const targetPart = msg.parts[pIdxResult] @@ -176,18 +242,28 @@ export function createPartsBatcher( queryClient.setQueryData(queryKey, updatedData) } - const filteredUnapplied = unapplied.filter((op) => { - if (op.type === 'delta' || op.type === 'remove') { + const retainedUnapplied = unapplied.filter((op) => { + if (op.type === 'remove') return false + if (op.type === 'delta') { return !supersededPartIDs.has(op.partID) } + if (op.type === 'upsert') { + return !supersededPartIDs.has(op.part.id) + } return true }) - if (filteredUnapplied.length > 0) { - if (!invalidatedGroupKeys.has(key)) { - invalidatedGroupKeys.add(key) - queryClient.invalidateQueries({ queryKey }) - } + const needsInvalidate = retainedUnapplied.length > 0 || unapplied.some((op) => op.type === 'remove') + const willRetain = retainedUnapplied.length > 0 && !isGroupExpired(group, now) + + if (needsInvalidate && group.firstDeferredAt === undefined) { + queryClient.invalidateQueries({ queryKey }) + } + + if (willRetain) { + stampDeferred(group, now) + group.operations = retainedUnapplied + continue } groupsToDelete.push(key)