From 20b9ba6b0e613effb8a6fd1aef654301205c1f74 Mon Sep 17 00:00:00 2001 From: king-daveed Date: Mon, 23 Nov 2026 04:49:23 +0100 Subject: [PATCH 1/2] fix(worker): ensure idempotent stream completion and event replay handling (#802) --- backend/src/workers/soroban-event-worker.ts | 61 +++++++++++---------- backend/tests/soroban-event-worker.test.ts | 56 +++++++++++++++++++ 2 files changed, 88 insertions(+), 29 deletions(-) diff --git a/backend/src/workers/soroban-event-worker.ts b/backend/src/workers/soroban-event-worker.ts index bb75dcfb..5d897119 100644 --- a/backend/src/workers/soroban-event-worker.ts +++ b/backend/src/workers/soroban-event-worker.ts @@ -1166,6 +1166,24 @@ export class SorobanEventWorker { const timestamp = getEventLedgerTimestamp(event); await prisma.$transaction(async (tx: Prisma.TransactionClient) => { + // Check for a duplicate BEFORE mutating any Stream fields so that a + // replayed event never executes redundant stream updates. + const existingEvent = await tx.streamEvent.findUnique({ + where: { + transactionHash_eventType: { + transactionHash: event.txHash, + eventType: "COMPLETED", + }, + }, + select: { id: true }, + }); + if (existingEvent) { + logger.warn( + `[SorobanWorker] Duplicate StreamEvent skipped: txHash=${event.txHash} type=COMPLETED`, + ); + return; + } + await tx.stream.update({ where: { streamId }, data: { @@ -1175,42 +1193,27 @@ export class SorobanEventWorker { }, }); - const existingEvent = await tx.streamEvent.findUnique({ + await tx.streamEvent.upsert({ where: { transactionHash_eventType: { transactionHash: event.txHash, eventType: "COMPLETED", }, }, - select: { id: true }, + create: { + streamId, + eventType: "COMPLETED", + amount: totalWithdrawn, + transactionHash: event.txHash, + ledgerSequence: event.ledger, + timestamp, + metadata: JSON.stringify({ recipient }), + }, + update: { + ledgerSequence: event.ledger, + timestamp, + }, }); - if (existingEvent) { - logger.warn( - `[SorobanWorker] Duplicate StreamEvent skipped: txHash=${event.txHash} type=COMPLETED`, - ); - } else { - await tx.streamEvent.upsert({ - where: { - transactionHash_eventType: { - transactionHash: event.txHash, - eventType: "COMPLETED", - }, - }, - create: { - streamId, - eventType: "COMPLETED", - amount: totalWithdrawn, - transactionHash: event.txHash, - ledgerSequence: event.ledger, - timestamp, - metadata: JSON.stringify({ recipient }), - }, - update: { - ledgerSequence: event.ledger, - timestamp, - }, - }); - } }); sseService.broadcastToStream(String(streamId), "stream.completed", { diff --git a/backend/tests/soroban-event-worker.test.ts b/backend/tests/soroban-event-worker.test.ts index e1edd15c..3cd1049d 100644 --- a/backend/tests/soroban-event-worker.test.ts +++ b/backend/tests/soroban-event-worker.test.ts @@ -596,6 +596,62 @@ describe('SorobanEventWorker', () => { expect(expectedEndTime).toBe(1700000000n + BigInt(Math.floor(1200 / 10))); }); + it('should not re-execute stream update when a stream_completed event is re-processed', async () => { + const txHash = 'completed-tx-hash'; + const streamId = 33; + + const mockEvent: rpc.Api.EventResponse = { + id: 'completed-event-1', + type: 'contract', + ledger: 5001, + ledgerClosedAt: '2024-01-01T00:00:00Z', + txHash, + transactionIndex: 0, + operationIndex: 0, + inSuccessfulContractCall: true, + topic: [ + mockSym('stream_completed'), + mockU64(streamId), + ], + value: { + type: 'scvMap', + map: [ + mockMapEntry('recipient', mockAccountAddr()), + mockMapEntry('total_withdrawn', mockI128('0', '5000')), + ] as any, + } as any, + }; + + const mockTx = { + stream: { + update: vi.fn().mockResolvedValue({}), + }, + streamEvent: { + findUnique: vi.fn(), + upsert: vi.fn().mockResolvedValue({ id: 'completed-event-row' }), + }, + }; + + (prisma.$transaction as ReturnType).mockImplementation((cb) => cb(mockTx)); + + // First processing: no existing event → stream completed is updated once. + mockTx.streamEvent.findUnique.mockResolvedValueOnce(null); + await expect((worker as any).handleStreamCompleted(mockEvent, mockEvent.topic![1])).resolves.not.toThrow(); + expect(mockTx.stream.update).toHaveBeenCalledTimes(1); + expect(mockTx.streamEvent.upsert).toHaveBeenCalledTimes(1); + expect(logger.warn).not.toHaveBeenCalled(); + + vi.clearAllMocks(); + (prisma.$transaction as ReturnType).mockImplementation((cb) => cb(mockTx)); + + // Second processing (replay of same txHash): event exists → update must NOT be called again. + mockTx.streamEvent.findUnique.mockResolvedValueOnce({ id: 'completed-event-row' }); + await expect((worker as any).handleStreamCompleted(mockEvent, mockEvent.topic![1])).resolves.not.toThrow(); + expect(mockTx.stream.update).not.toHaveBeenCalled(); + expect(mockTx.streamEvent.upsert).not.toHaveBeenCalled(); + expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('Duplicate StreamEvent skipped')); + }); + it('should process admin_transferred events successfully', async () => { const txHash = 'admin-transferred-tx-hash'; From 6251b508f643ee3aa2623043b48ee2955d06cf52 Mon Sep 17 00:00:00 2001 From: xeron-droid Date: Tue, 24 Nov 2026 10:22:27 +0000 Subject: [PATCH 2/2] fix(worker): re-apply the completion update before the dedup guard The stream_completed handler checked for the duplicate StreamEvent row before updating the stream, which broke the documented replay contract from #1763: a replayed completion must re-apply the idempotent stream update, surface P2025 when the Stream row is gone, and still broadcast. Restore the update-first ordering and assert the replay behavior in the handler test. --- backend/src/workers/soroban-event-worker.ts | 61 ++++++++++----------- backend/tests/soroban-event-worker.test.ts | 7 ++- 2 files changed, 33 insertions(+), 35 deletions(-) diff --git a/backend/src/workers/soroban-event-worker.ts b/backend/src/workers/soroban-event-worker.ts index 5d897119..bb75dcfb 100644 --- a/backend/src/workers/soroban-event-worker.ts +++ b/backend/src/workers/soroban-event-worker.ts @@ -1166,24 +1166,6 @@ export class SorobanEventWorker { const timestamp = getEventLedgerTimestamp(event); await prisma.$transaction(async (tx: Prisma.TransactionClient) => { - // Check for a duplicate BEFORE mutating any Stream fields so that a - // replayed event never executes redundant stream updates. - const existingEvent = await tx.streamEvent.findUnique({ - where: { - transactionHash_eventType: { - transactionHash: event.txHash, - eventType: "COMPLETED", - }, - }, - select: { id: true }, - }); - if (existingEvent) { - logger.warn( - `[SorobanWorker] Duplicate StreamEvent skipped: txHash=${event.txHash} type=COMPLETED`, - ); - return; - } - await tx.stream.update({ where: { streamId }, data: { @@ -1193,27 +1175,42 @@ export class SorobanEventWorker { }, }); - await tx.streamEvent.upsert({ + const existingEvent = await tx.streamEvent.findUnique({ where: { transactionHash_eventType: { transactionHash: event.txHash, eventType: "COMPLETED", }, }, - create: { - streamId, - eventType: "COMPLETED", - amount: totalWithdrawn, - transactionHash: event.txHash, - ledgerSequence: event.ledger, - timestamp, - metadata: JSON.stringify({ recipient }), - }, - update: { - ledgerSequence: event.ledger, - timestamp, - }, + select: { id: true }, }); + if (existingEvent) { + logger.warn( + `[SorobanWorker] Duplicate StreamEvent skipped: txHash=${event.txHash} type=COMPLETED`, + ); + } else { + await tx.streamEvent.upsert({ + where: { + transactionHash_eventType: { + transactionHash: event.txHash, + eventType: "COMPLETED", + }, + }, + create: { + streamId, + eventType: "COMPLETED", + amount: totalWithdrawn, + transactionHash: event.txHash, + ledgerSequence: event.ledger, + timestamp, + metadata: JSON.stringify({ recipient }), + }, + update: { + ledgerSequence: event.ledger, + timestamp, + }, + }); + } }); sseService.broadcastToStream(String(streamId), "stream.completed", { diff --git a/backend/tests/soroban-event-worker.test.ts b/backend/tests/soroban-event-worker.test.ts index 3cd1049d..606409cf 100644 --- a/backend/tests/soroban-event-worker.test.ts +++ b/backend/tests/soroban-event-worker.test.ts @@ -596,7 +596,7 @@ describe('SorobanEventWorker', () => { expect(expectedEndTime).toBe(1700000000n + BigInt(Math.floor(1200 / 10))); }); - it('should not re-execute stream update when a stream_completed event is re-processed', async () => { + it('should not duplicate the StreamEvent row when a stream_completed event is re-processed', async () => { const txHash = 'completed-tx-hash'; const streamId = 33; @@ -644,10 +644,11 @@ describe('SorobanEventWorker', () => { vi.clearAllMocks(); (prisma.$transaction as ReturnType).mockImplementation((cb) => cb(mockTx)); - // Second processing (replay of same txHash): event exists → update must NOT be called again. + // Second processing (replay of same txHash): the completion re-applies the + // stream update idempotently, but no duplicate StreamEvent row is written. mockTx.streamEvent.findUnique.mockResolvedValueOnce({ id: 'completed-event-row' }); await expect((worker as any).handleStreamCompleted(mockEvent, mockEvent.topic![1])).resolves.not.toThrow(); - expect(mockTx.stream.update).not.toHaveBeenCalled(); + expect(mockTx.stream.update).toHaveBeenCalledTimes(1); expect(mockTx.streamEvent.upsert).not.toHaveBeenCalled(); expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('Duplicate StreamEvent skipped')); });