diff --git a/packages/amp/src/protocol-stream/service.ts b/packages/amp/src/protocol-stream/service.ts index 14d1827..6968b5c 100644 --- a/packages/amp/src/protocol-stream/service.ts +++ b/packages/amp/src/protocol-stream/service.ts @@ -181,9 +181,10 @@ const make = Effect.gen(function* () { resumeWatermark: options?.resumeWatermark }) + // Start from the resume watermark so reorgs that happened while stopped are detected const initialState: ProtocolStreamState = { - previous: [], - initialized: false + previous: options?.resumeWatermark ?? [], + initialized: options?.resumeWatermark !== undefined } return rawStream.pipe( @@ -208,15 +209,17 @@ const make = Effect.gen(function* () { // Detect reorgs const invalidations = state.initialized ? detectReorgs(state.previous, incoming) : [] - // Determine message type - let message: ProtocolMessage + // Determine message types: a reorg is followed by the batch that revealed it + const messages: Array = [] if (invalidations.length > 0) { - message = protocolReorg(state.previous, incoming, invalidations) - } else if (metadata.rangesComplete && batchData.length === 0) { - message = protocolWatermark(incoming) + messages.push(protocolReorg(state.previous, incoming, invalidations)) + } + + if (metadata.rangesComplete && batchData.length === 0) { + messages.push(protocolWatermark(incoming)) } else { - message = protocolData(batchData, incoming) + messages.push(protocolData(batchData, incoming)) } const newState: ProtocolStreamState = { @@ -224,7 +227,7 @@ const make = Effect.gen(function* () { initialized: true } - return [newState, [message]] as const + return [newState, messages] as const }) ), Stream.withSpan("ProtocolStream.stream") diff --git a/packages/amp/src/transactional-stream/memory-store.ts b/packages/amp/src/transactional-stream/memory-store.ts index 83e6042..dde89b9 100644 --- a/packages/amp/src/transactional-stream/memory-store.ts +++ b/packages/amp/src/transactional-stream/memory-store.ts @@ -35,9 +35,11 @@ const makeServiceFromRef = (stateRef: Ref.Ref): StateStoreService buffer = buffer.filter(([id]) => id > commitData.prune!) } - // Add new watermarks + // Add new watermarks, skipping ones already committed (commit must be idempotent) for (const entry of commitData.insert) { - buffer.push(entry) + if (!buffer.some(([id]) => id === entry[0])) { + buffer.push(entry) + } } return { ...state, buffer } diff --git a/packages/amp/test/protocol-stream/reorg.test.ts b/packages/amp/test/protocol-stream/reorg.test.ts index aedeae2..a9b03fe 100644 --- a/packages/amp/test/protocol-stream/reorg.test.ts +++ b/packages/amp/test/protocol-stream/reorg.test.ts @@ -15,10 +15,21 @@ * - Multi-network partial reorg detection * - Watermark and data message generation */ +import { ArrowFlight, type QueryResult } from "@edgeandnode/amp/arrow-flight" import type { BlockHash, BlockNumber, BlockRange, Network } from "@edgeandnode/amp/core" -import { data, invalidates, makeInvalidationRange, reorg, watermark } from "@edgeandnode/amp/protocol-stream" +import { + data, + invalidates, + layer as protocolStreamLayer, + makeInvalidationRange, + ProtocolStream, + reorg, + watermark +} from "@edgeandnode/amp/protocol-stream" import { describe, it } from "@effect/vitest" import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import * as Stream from "effect/Stream" // ============================================================================= // Test Helpers - Ported from Rust utils/response.rs @@ -489,3 +500,82 @@ describe("edge cases", () => { }) ) }) + +// ============================================================================= +// ProtocolStream Service Tests +// ============================================================================= + +/** + * Creates a ProtocolStream layer over a mock ArrowFlight that streams the given batches. + */ +const makeProtocolStreamLayer = (batches: ReadonlyArray>>) => + protocolStreamLayer.pipe( + Layer.provide( + Layer.succeed(ArrowFlight, { + streamQuery: () => Stream.fromIterable(batches) + } as unknown as ArrowFlight["Service"]) + ) + ) + +describe("ProtocolStream.stream", () => { + it.effect("emits the data of the batch that reveals a reorg", ({ expect }) => + Effect.gen(function* () { + const protocolStream = yield* ProtocolStream + const messages = yield* protocolStream.stream("SELECT * FROM eth.logs").pipe(Stream.runCollect) + + expect(messages.map((message) => message._tag)).toEqual(["Data", "Watermark", "Reorg", "Data"]) + const replacement = messages[3]! + expect(replacement._tag === "Data" && replacement.data).toEqual([{ block: 5 }, { block: 12 }]) + }).pipe( + Effect.provide( + makeProtocolStreamLayer([ + { data: [{ block: 0 }], metadata: { ranges: [makeBlockRange("eth", 0, 10, 0)], rangesComplete: false } }, + { data: [], metadata: { ranges: [makeBlockRange("eth", 0, 10, 0)], rangesComplete: true } }, + { + data: [{ block: 5 }, { block: 12 }], + metadata: { ranges: [makeBlockRangeWithReorg("eth", 5, 12, 1, 1)], rangesComplete: false } + } + ]) + ) + ) + ) + + it.effect("detects a reorg against the resume watermark", ({ expect }) => + Effect.gen(function* () { + const protocolStream = yield* ProtocolStream + const messages = yield* protocolStream + .stream("SELECT * FROM eth.logs", { resumeWatermark: [makeBlockRange("eth", 0, 10, 0)] }) + .pipe(Stream.runCollect) + + expect(messages.map((message) => message._tag)).toEqual(["Reorg", "Data"]) + const reorgMessage = messages[0]! + expect(reorgMessage._tag === "Reorg" && reorgMessage.invalidation).toEqual([makeInvalidationRange("eth", 7, 12)]) + }).pipe( + Effect.provide( + makeProtocolStreamLayer([ + { + data: [{ block: 7 }], + metadata: { ranges: [makeBlockRangeWithReorg("eth", 7, 12, 1, 1)], rangesComplete: false } + } + ]) + ) + ) + ) + + it.effect("resumes without a reorg when the chain continues from the resume watermark", ({ expect }) => + Effect.gen(function* () { + const protocolStream = yield* ProtocolStream + const messages = yield* protocolStream + .stream("SELECT * FROM eth.logs", { resumeWatermark: [makeBlockRange("eth", 0, 10, 0)] }) + .pipe(Stream.runCollect) + + expect(messages.map((message) => message._tag)).toEqual(["Data"]) + }).pipe( + Effect.provide( + makeProtocolStreamLayer([ + { data: [{ block: 11 }], metadata: { ranges: [makeBlockRange("eth", 11, 20, 0)], rangesComplete: false } } + ]) + ) + ) + ) +}) diff --git a/packages/amp/test/transactional-stream/memory-store.test.ts b/packages/amp/test/transactional-stream/memory-store.test.ts index 1ca0fbb..766de45 100644 --- a/packages/amp/test/transactional-stream/memory-store.test.ts +++ b/packages/amp/test/transactional-stream/memory-store.test.ts @@ -140,6 +140,22 @@ describe("StateStore.commit", () => { ) ) + it.effect("is idempotent when the same commit is applied twice", () => + Effect.gen(function* () { + const store = yield* StateStore + const commit = { + insert: [[1 as TransactionId, [makeBlockRange("eth", 0, 10)]] as const], + prune: undefined + } + + yield* store.commit(commit) + yield* store.commit(commit) + + const snapshot = yield* store.load + expect(snapshot.buffer.map(([id]) => id)).toEqual([1]) + }).pipe(Effect.provide(InMemoryStateStore.layer)) + ) + it.effect("can insert and prune atomically", () => Effect.gen(function* () { const store = yield* StateStore