From 037c400ef4e61c9b9b030fb56cccc9a34664e470 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benoi=CC=82t=20Rouleau?= Date: Mon, 2 Nov 2026 22:37:26 -0500 Subject: [PATCH 1/2] fix(transactional stream): recover from a reorg inside a watermark's range Reconnect from an earlier watermark instead of failing with PartialReorgError. Co-Authored-By: Claude Opus 5.5 --- packages/amp/src/transactional-stream.ts | 3 +- .../src/transactional-stream/algorithms.ts | 35 ++++- .../amp/src/transactional-stream/errors.ts | 6 +- .../src/transactional-stream/state-actor.ts | 43 +++++- .../amp/src/transactional-stream/stream.ts | 25 ++- .../transactional-stream/algorithms.test.ts | 38 +++++ .../transactional-stream/state-actor.test.ts | 56 +++++++ .../test/transactional-stream/stream.test.ts | 146 ++++++++++++++++++ 8 files changed, 340 insertions(+), 12 deletions(-) create mode 100644 packages/amp/test/transactional-stream/stream.test.ts diff --git a/packages/amp/src/transactional-stream.ts b/packages/amp/src/transactional-stream.ts index 9e0ba4a..230f3d7 100644 --- a/packages/amp/src/transactional-stream.ts +++ b/packages/amp/src/transactional-stream.ts @@ -135,5 +135,6 @@ export { checkPartialReorg, compressCommits, findPruningPoint, - findRecoveryPoint + findRecoveryPoint, + findResumePoint } from "./transactional-stream/algorithms.ts" diff --git a/packages/amp/src/transactional-stream/algorithms.ts b/packages/amp/src/transactional-stream/algorithms.ts index 62ac400..19f1121 100644 --- a/packages/amp/src/transactional-stream/algorithms.ts +++ b/packages/amp/src/transactional-stream/algorithms.ts @@ -103,6 +103,36 @@ export const findRecoveryPoint = ( return undefined } +/** + * Find the watermark to reconnect from after a partial reorg. + * + * Amp re-sends everything after the watermark it's resumed from, so this has to be + * a watermark whose ranges all end before the reorg point on their network. + * + * @param buffer - Watermark buffer (oldest to newest) + * @param invalidation - Invalidation ranges from the reorg + * @returns Last watermark entirely before the reorg [id, ranges], or undefined if there is none + */ +export const findResumePoint = ( + buffer: ReadonlyArray]>, + invalidation: ReadonlyArray +): readonly [TransactionId, ReadonlyArray] | undefined => { + for (let i = buffer.length - 1; i >= 0; i--) { + const entry = buffer[i]! + + const beforeReorg = entry[1].every((range) => { + const inv = invalidation.find(({ network }) => network === range.network) + return inv === undefined || range.numbers.end < inv.start + }) + + if (beforeReorg) { + return entry + } + } + + return undefined +} + // ============================================================================= // Pruning Point Algorithm // ============================================================================= @@ -197,14 +227,15 @@ export const findPruningPoint = ( // ============================================================================= /** - * Check if a reorg is partial (unrecoverable). + * Check if a reorg is partial. * * A partial reorg occurs when the recovery point watermark has a range * that partially overlaps with the invalidation - meaning the reorg point * falls within a watermark's range, not at its boundary. * * If we were to ignore this, we would end up with a data gap because we're - * telling the consumer to invalidate data that won't be replayed. + * telling the consumer to invalidate data that won't be replayed. Recovering + * takes a reconnect from an earlier watermark (see {@link findResumePoint}). * * @param recoveryRanges - Block ranges from the recovery point watermark * @param invalidation - Invalidation ranges from the reorg diff --git a/packages/amp/src/transactional-stream/errors.ts b/packages/amp/src/transactional-stream/errors.ts index 81d7436..24ef43b 100644 --- a/packages/amp/src/transactional-stream/errors.ts +++ b/packages/amp/src/transactional-stream/errors.ts @@ -5,6 +5,7 @@ */ import * as Schema from "effect/Schema" import type { ProtocolStreamError } from "../protocol-stream/errors.ts" +import { InvalidationRange } from "../protocol-stream/messages.ts" // ============================================================================= // StateStore Errors @@ -40,13 +41,14 @@ export class UnrecoverableReorgError extends Schema.TaggedError( "Amp/TransactionalStream/PartialReorgError" )("PartialReorgError", { reason: Schema.String, - network: Schema.String + network: Schema.String, + invalidation: Schema.Array(InvalidationRange) }) {} // ============================================================================= diff --git a/packages/amp/src/transactional-stream/state-actor.ts b/packages/amp/src/transactional-stream/state-actor.ts index 49c1e17..bf27018 100644 --- a/packages/amp/src/transactional-stream/state-actor.ts +++ b/packages/amp/src/transactional-stream/state-actor.ts @@ -10,12 +10,13 @@ import * as Effect from "effect/Effect" import * as Ref from "effect/Ref" import type { BlockRange } from "../core/domain.ts" -import type { ProtocolMessage } from "../protocol-stream/messages.ts" +import type { InvalidationRange, ProtocolMessage } from "../protocol-stream/messages.ts" import { checkPartialReorg, compressCommits, findPruningPoint, findRecoveryPoint, + findResumePoint, type PendingCommit } from "./algorithms.ts" import { type CommitHandle, makeCommitHandle } from "./commit-handle.ts" @@ -51,7 +52,10 @@ interface StateContainer { /** * Action union for execute(). */ -export type Action = { readonly _tag: "Message"; readonly message: ProtocolMessage } | { readonly _tag: "Rewind" } +export type Action = + | { readonly _tag: "Message"; readonly message: ProtocolMessage } + | { readonly _tag: "Rewind" } + | { readonly _tag: "PartialReorg"; readonly invalidation: ReadonlyArray } /** * StateActor interface - manages transactional stream state. @@ -143,6 +147,9 @@ export const makeStateActor = Effect.fnUntraced(function* ( case "Message": return executeMessage(id, action.message, containerRef, store, retention) + + case "PartialReorg": + return executePartialReorg(id, action.invalidation, containerRef, store) } })() @@ -323,13 +330,43 @@ const executeReorg = Effect.fnUntraced(function* ( if (partialNetwork !== undefined) { return yield* new PartialReorgError({ reason: "Recovery point doesn't align with reorg boundary", - network: partialNetwork + network: partialNetwork, + invalidation }) } anchor = recoveryId } + return yield* undoReorg(id, anchor, invalidation, containerRef, store) +}) + +/** + * Execute a PartialReorg action: undo back to the last watermark before the reorg, + * or everything if there is none. The stream then reconnects from that watermark. + */ +const executePartialReorg = Effect.fnUntraced(function* ( + id: TransactionId, + invalidation: ReadonlyArray, + containerRef: Ref.Ref, + store: StateStoreService +): Effect.fn.Return { + const state = yield* Ref.get(containerRef) + const anchor = findResumePoint(state.buffer, invalidation)?.[0] + + return yield* undoReorg(id, anchor, invalidation, containerRef, store) +}) + +/** + * Undo everything after the anchor because of a reorg. + */ +const undoReorg = Effect.fnUntraced(function* ( + id: TransactionId, + anchor: TransactionId | undefined, + invalidation: ReadonlyArray, + containerRef: Ref.Ref, + store: StateStoreService +): Effect.fn.Return { // 4. Compute invalidation range and truncate both in-memory and store const range = computeInvalidationRange(anchor, id) diff --git a/packages/amp/src/transactional-stream/stream.ts b/packages/amp/src/transactional-stream/stream.ts index 752d921..16038e6 100644 --- a/packages/amp/src/transactional-stream/stream.ts +++ b/packages/amp/src/transactional-stream/stream.ts @@ -203,9 +203,26 @@ const make = Effect.gen(function* () { const shouldRewind = needsRewind(nextId, lastWatermarkId) // 5. Get protocol stream with resume cursor - const protocolOptions: ProtocolStreamOptions = - resumeWatermark !== undefined ? { schema: options?.schema, resumeWatermark } : { schema: options?.schema } - const protocolStream = protocolStreamService.stream(sql, protocolOptions) + const connect = ( + from: ReadonlyArray | undefined + ): Stream.Stream< + readonly [TransactionEvent, CommitHandle], + ProtocolStreamError | StateStoreError | UnrecoverableReorgError | PartialReorgError + > => { + const protocolOptions: ProtocolStreamOptions = + from !== undefined ? { schema: options?.schema, resumeWatermark: from } : { schema: options?.schema } + + return protocolStreamService.stream(sql, protocolOptions).pipe( + Stream.mapEffect((message) => actor.execute({ _tag: "Message", message } as Action)), + // Amp only re-sends from the reorg point here, not from the start of the watermark it falls in. + // Undo back to an earlier watermark and reconnect from it, so everything undone gets re-sent. + Stream.catchTag("PartialReorgError", ({ invalidation }) => + Stream.fromEffect(actor.execute({ _tag: "PartialReorg", invalidation })).pipe( + Stream.concat(Stream.unwrap(Effect.map(actor.watermark, (last) => connect(last?.[1])))) + ) + ) + ) + } // 6. Build transactional stream // First emit Rewind if needed, then map protocol messages through actor @@ -217,7 +234,7 @@ const make = Effect.gen(function* () { const messageStream: Stream.Stream< readonly [TransactionEvent, CommitHandle], ProtocolStreamError | StateStoreError | UnrecoverableReorgError | PartialReorgError - > = protocolStream.pipe(Stream.mapEffect((message) => actor.execute({ _tag: "Message", message } as Action))) + > = connect(resumeWatermark) return Stream.concat(rewindStream, messageStream) }) diff --git a/packages/amp/test/transactional-stream/algorithms.test.ts b/packages/amp/test/transactional-stream/algorithms.test.ts index ff0f181..509e0f0 100644 --- a/packages/amp/test/transactional-stream/algorithms.test.ts +++ b/packages/amp/test/transactional-stream/algorithms.test.ts @@ -10,6 +10,7 @@ import { compressCommits, findPruningPoint, findRecoveryPoint, + findResumePoint, type TransactionId } from "@edgeandnode/amp/transactional-stream" import { describe, expect, it } from "vitest" @@ -118,6 +119,43 @@ describe("findRecoveryPoint", () => { }) }) +// ============================================================================= +// findResumePoint Tests +// ============================================================================= + +describe("findResumePoint", () => { + it("returns the last watermark that ends before the reorg", () => { + const buffer = [makeWatermark(1, [makeBlockRange("eth", 0, 34)]), makeWatermark(3, [makeBlockRange("eth", 35, 37)])] + const result = findResumePoint(buffer, [makeInvalidation("eth", 36, 38)]) + expect(result?.[0]).toBe(1) + }) + + it("returns undefined when no watermark ends before the reorg", () => { + const buffer = [makeWatermark(1, [makeBlockRange("eth", 0, 37)])] + const result = findResumePoint(buffer, [makeInvalidation("eth", 36, 38)]) + expect(result).toBeUndefined() + }) + + it("walks back until every invalidated network ends before the reorg", () => { + const buffer = [ + makeWatermark(1, [makeBlockRange("eth", 0, 29), makeBlockRange("polygon", 0, 94)]), + makeWatermark(3, [makeBlockRange("eth", 30, 34), makeBlockRange("polygon", 95, 99)]), + makeWatermark(5, [makeBlockRange("eth", 35, 37), makeBlockRange("polygon", 100, 102)]) + ] + const result = findResumePoint(buffer, [makeInvalidation("eth", 36, 38), makeInvalidation("polygon", 97, 103)]) + expect(result?.[0]).toBe(1) + }) + + it("ignores networks that aren't invalidated", () => { + const buffer = [ + makeWatermark(1, [makeBlockRange("eth", 0, 34), makeBlockRange("polygon", 0, 99)]), + makeWatermark(3, [makeBlockRange("eth", 35, 37), makeBlockRange("polygon", 100, 102)]) + ] + const result = findResumePoint(buffer, [makeInvalidation("eth", 36, 38)]) + expect(result?.[0]).toBe(1) + }) +}) + // ============================================================================= // findPruningPoint Tests // ============================================================================= diff --git a/packages/amp/test/transactional-stream/state-actor.test.ts b/packages/amp/test/transactional-stream/state-actor.test.ts index 90d84ca..941fbd0 100644 --- a/packages/amp/test/transactional-stream/state-actor.test.ts +++ b/packages/amp/test/transactional-stream/state-actor.test.ts @@ -463,6 +463,62 @@ describe("StateActor.execute - Reorg", () => { ) }) +describe("StateActor.execute - PartialReorg", () => { + const invalidation = [{ network: "eth", start: 36, end: 38 }].map((i) => ({ + network: i.network as Network, + start: i.start as BlockNumber, + end: i.end as BlockNumber + })) + + it.effect("undoes back to the last watermark before the reorg", () => + Effect.gen(function* () { + const store = yield* StateStore + const actor = yield* makeStateActor(store, 128) + const [event] = yield* actor.execute({ _tag: "PartialReorg", invalidation }) + + expect(event._tag).toBe("Undo") + if (event._tag === "Undo") { + expect(event.cause._tag).toBe("Reorg") + expect(event.invalidate).toEqual({ start: 2, end: 3 }) + } + const watermark = yield* actor.watermark + expect(watermark?.[0]).toBe(1) + const snapshot = yield* store.load + expect(snapshot.buffer.map(([id]) => id)).toEqual([1]) + }).pipe( + Effect.provide( + InMemoryStateStore.layerWithState({ + buffer: [ + [1 as TransactionId, [makeBlockRange("eth", 0, 34)]], + [3 as TransactionId, [makeBlockRange("eth", 35, 37)]] + ], + next: 4 as TransactionId + }) + ) + ) + ) + + it.effect("undoes everything when no watermark ends before the reorg", () => + Effect.gen(function* () { + const store = yield* StateStore + const actor = yield* makeStateActor(store, 128) + const [event] = yield* actor.execute({ _tag: "PartialReorg", invalidation }) + + expect(event._tag === "Undo" && event.invalidate).toEqual({ start: 0, end: 1 }) + expect(yield* actor.watermark).toBeUndefined() + const snapshot = yield* store.load + expect(snapshot.buffer).toEqual([]) + }).pipe( + Effect.provide( + InMemoryStateStore.layerWithState({ + buffer: [[1 as TransactionId, [makeBlockRange("eth", 0, 37)]]], + next: 2 as TransactionId + }) + ) + ) + ) +}) + // ============================================================================= // Commit Tests // ============================================================================= diff --git a/packages/amp/test/transactional-stream/stream.test.ts b/packages/amp/test/transactional-stream/stream.test.ts new file mode 100644 index 0000000..18559ae --- /dev/null +++ b/packages/amp/test/transactional-stream/stream.test.ts @@ -0,0 +1,146 @@ +/** + * Tests for TransactionalStream - reconnecting after a partial reorg. + * + * @module + */ +import type { BlockNumber, BlockRange, Network } from "@edgeandnode/amp/core" +import { makeInvalidationRange, ProtocolStream, type ProtocolMessage } from "@edgeandnode/amp/protocol-stream" +import { + InMemoryStateStore, + layer as transactionalStreamLayer, + type StateSnapshot, + TransactionalStream, + type TransactionId +} from "@edgeandnode/amp/transactional-stream" +import { describe, expect, it } from "@effect/vitest" +import * as Effect from "effect/Effect" +import * as Layer from "effect/Layer" +import * as Stream from "effect/Stream" + +// ============================================================================= +// Test Helpers +// ============================================================================= + +const makeBlockRange = (start: number, end: number): BlockRange => + ({ + network: "eth" as Network, + numbers: { start: start as BlockNumber, end: end as BlockNumber }, + hash: "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef", + prevHash: undefined + }) as BlockRange + +const data = (start: number, end: number): ProtocolMessage => ({ + _tag: "Data", + data: [{ start, end }], + ranges: [makeBlockRange(start, end)] +}) + +const watermark = (start: number, end: number): ProtocolMessage => ({ + _tag: "Watermark", + ranges: [makeBlockRange(start, end)] +}) + +const reorg = (start: number, end: number): ProtocolMessage => ({ + _tag: "Reorg", + previous: [], + incoming: [makeBlockRange(start, end)], + invalidation: [makeInvalidationRange("eth", start, end)] +}) + +/** + * Runs a transactional stream over a mock ProtocolStream that serves one list of messages per connection, + * and reports what each connection resumed from and when it closed. + */ +const run = (snapshot: StateSnapshot, connections: ReadonlyArray>) => { + const log: Array = [] + let connection = 0 + + const layer = transactionalStreamLayer.pipe( + Layer.provide(InMemoryStateStore.layerWithState(snapshot)), + Layer.provide( + Layer.succeed(ProtocolStream, { + stream: (_sql, options) => { + const id = connection++ + const resume = options?.resumeWatermark?.[0]?.numbers + log.push(`open ${id} from ${resume === undefined ? "start" : `${resume.start}-${resume.end}`}`) + return Stream.fromIterable(connections[id] ?? []).pipe( + Stream.ensuring(Effect.sync(() => log.push(`close ${id}`))) + ) + } + } as ProtocolStream["Service"]) + ) + ) + + return Effect.gen(function* () { + const transactionalStream = yield* TransactionalStream + const events = yield* transactionalStream.streamTransactional("SELECT * FROM eth.logs").pipe(Stream.runCollect) + return { events: events.map(([event]) => event), log } + }).pipe(Effect.provide(layer)) +} + +// ============================================================================= +// Tests +// ============================================================================= + +describe("TransactionalStream.streamTransactional", () => { + it.effect("reconnects from an earlier watermark when a reorg starts inside the last one", () => + Effect.gen(function* () { + const { events, log } = yield* run( + { + buffer: [ + [1 as TransactionId, [makeBlockRange(0, 34)]], + [3 as TransactionId, [makeBlockRange(35, 37)]] + ], + next: 4 as TransactionId + }, + [ + // The batch that reveals the reorg only covers blocks from the reorg point on + [reorg(36, 38), data(36, 38), watermark(36, 38)], + [data(35, 38), watermark(35, 38)] + ] + ) + + expect(log).toEqual(["open 0 from 35-37", "close 0", "open 1 from 0-34", "close 1"]) + expect(events.map((event) => event._tag)).toEqual(["Undo", "Data", "Watermark"]) + const undo = events[0]! + expect(undo._tag === "Undo" && undo.invalidate).toEqual({ start: 2, end: 4 }) + const replacement = events[1]! + expect(replacement._tag === "Data" && replacement.ranges).toEqual([makeBlockRange(35, 38)]) + }) + ) + + it.effect("starts over when a reorg starts inside the only watermark", () => + Effect.gen(function* () { + const { events, log } = yield* run( + { + buffer: [[1 as TransactionId, [makeBlockRange(0, 37)]]], + next: 2 as TransactionId + }, + [[reorg(36, 38), data(36, 38)], [data(0, 38)]] + ) + + expect(log).toEqual(["open 0 from 0-37", "close 0", "open 1 from start", "close 1"]) + expect(events.map((event) => event._tag)).toEqual(["Undo", "Data"]) + const undo = events[0]! + expect(undo._tag === "Undo" && undo.invalidate).toEqual({ start: 0, end: 2 }) + }) + ) + + it.effect("stays connected when a reorg starts at a watermark's first block", () => + Effect.gen(function* () { + const { events, log } = yield* run( + { + buffer: [ + [1 as TransactionId, [makeBlockRange(0, 34)]], + [3 as TransactionId, [makeBlockRange(35, 37)]] + ], + next: 4 as TransactionId + }, + [[reorg(35, 38), data(35, 38), watermark(35, 38)]] + ) + + expect(log).toEqual(["open 0 from 35-37", "close 0"]) + expect(events.map((event) => event._tag)).toEqual(["Undo", "Data", "Watermark"]) + }) + ) +}) From 5fcd5deb3074eb38c95acdf21ab66e3e912fb293 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benoi=CC=82t=20Rouleau?= Date: Mon, 2 Nov 2026 23:08:19 -0500 Subject: [PATCH 2/2] fix(transactional stream): fail on a partial reorg with no earlier watermark Starting over isn't safe: older watermarks may have been pruned, so consumers can't undo the pruned data a full replay would send again, and CDC consumers end up with duplicates. Fail with PartialReorgError instead, leaving the state as it is. Co-Authored-By: Claude Opus 5.5 --- .../amp/src/transactional-stream/errors.ts | 2 + .../src/transactional-stream/state-actor.ts | 27 ++-- .../amp/src/transactional-stream/stream.ts | 4 +- packages/amp/test/cdc-stream/stream.test.ts | 127 ++++++++++++++++++ .../transactional-stream/state-actor.test.ts | 21 ++- .../test/transactional-stream/stream.test.ts | 21 +-- 6 files changed, 177 insertions(+), 25 deletions(-) diff --git a/packages/amp/src/transactional-stream/errors.ts b/packages/amp/src/transactional-stream/errors.ts index 24ef43b..a8426ec 100644 --- a/packages/amp/src/transactional-stream/errors.ts +++ b/packages/amp/src/transactional-stream/errors.ts @@ -42,6 +42,8 @@ export class UnrecoverableReorgError extends Schema.TaggedError( "Amp/TransactionalStream/PartialReorgError" diff --git a/packages/amp/src/transactional-stream/state-actor.ts b/packages/amp/src/transactional-stream/state-actor.ts index bf27018..4217607 100644 --- a/packages/amp/src/transactional-stream/state-actor.ts +++ b/packages/amp/src/transactional-stream/state-actor.ts @@ -55,7 +55,7 @@ interface StateContainer { export type Action = | { readonly _tag: "Message"; readonly message: ProtocolMessage } | { readonly _tag: "Rewind" } - | { readonly _tag: "PartialReorg"; readonly invalidation: ReadonlyArray } + | { readonly _tag: "PartialReorg"; readonly error: PartialReorgError } /** * StateActor interface - manages transactional stream state. @@ -149,7 +149,7 @@ export const makeStateActor = Effect.fnUntraced(function* ( return executeMessage(id, action.message, containerRef, store, retention) case "PartialReorg": - return executePartialReorg(id, action.invalidation, containerRef, store) + return executePartialReorg(id, action.error, containerRef, store) } })() @@ -342,19 +342,30 @@ const executeReorg = Effect.fnUntraced(function* ( }) /** - * Execute a PartialReorg action: undo back to the last watermark before the reorg, - * or everything if there is none. The stream then reconnects from that watermark. + * Execute a PartialReorg action: undo back to the last watermark before the reorg. + * The stream then reconnects from that watermark. + * + * Without one, this fails rather than start over: older watermarks may have been pruned, + * and consumers can't undo the pruned data that a full replay would send again. */ const executePartialReorg = Effect.fnUntraced(function* ( id: TransactionId, - invalidation: ReadonlyArray, + error: PartialReorgError, containerRef: Ref.Ref, store: StateStoreService -): Effect.fn.Return { +): Effect.fn.Return { const state = yield* Ref.get(containerRef) - const anchor = findResumePoint(state.buffer, invalidation)?.[0] + const resumePoint = findResumePoint(state.buffer, error.invalidation) + + if (resumePoint === undefined) { + return yield* new PartialReorgError({ + reason: "No buffered watermark ends before the reorg to reconnect from", + network: error.network, + invalidation: error.invalidation + }) + } - return yield* undoReorg(id, anchor, invalidation, containerRef, store) + return yield* undoReorg(id, resumePoint[0], error.invalidation, containerRef, store) }) /** diff --git a/packages/amp/src/transactional-stream/stream.ts b/packages/amp/src/transactional-stream/stream.ts index 16038e6..5df4a57 100644 --- a/packages/amp/src/transactional-stream/stream.ts +++ b/packages/amp/src/transactional-stream/stream.ts @@ -216,8 +216,8 @@ const make = Effect.gen(function* () { Stream.mapEffect((message) => actor.execute({ _tag: "Message", message } as Action)), // Amp only re-sends from the reorg point here, not from the start of the watermark it falls in. // Undo back to an earlier watermark and reconnect from it, so everything undone gets re-sent. - Stream.catchTag("PartialReorgError", ({ invalidation }) => - Stream.fromEffect(actor.execute({ _tag: "PartialReorg", invalidation })).pipe( + Stream.catchTag("PartialReorgError", (error) => + Stream.fromEffect(actor.execute({ _tag: "PartialReorg", error })).pipe( Stream.concat(Stream.unwrap(Effect.map(actor.watermark, (last) => connect(last?.[1])))) ) ) diff --git a/packages/amp/test/cdc-stream/stream.test.ts b/packages/amp/test/cdc-stream/stream.test.ts index a64eb9b..ab6a092 100644 --- a/packages/amp/test/cdc-stream/stream.test.ts +++ b/packages/amp/test/cdc-stream/stream.test.ts @@ -5,9 +5,12 @@ */ import { BatchStore, CdcStream, InMemoryBatchStore, layer as cdcStreamLayer } from "@edgeandnode/amp/cdc-stream" import type { BlockRange } from "@edgeandnode/amp/core" +import { makeInvalidationRange, ProtocolStream, type ProtocolMessage } from "@edgeandnode/amp/protocol-stream" import { type CommitHandle, dataEvent, + InMemoryStateStore, + layer as transactionalStreamLayer, rewindCause, TransactionalStream, type TransactionalStreamService, @@ -18,6 +21,7 @@ import { } from "@edgeandnode/amp/transactional-stream" import { describe, expect, it } from "@effect/vitest" import * as Effect from "effect/Effect" +import { identity } from "effect/Function" import * as Layer from "effect/Layer" import * as Ref from "effect/Ref" import * as Stream from "effect/Stream" @@ -395,3 +399,126 @@ describe("CdcStream.forEach", () => { }) ) }) + +// ============================================================================= +// Partial Reorg Tests +// ============================================================================= + +describe("CdcStream - partial reorg", () => { + const batch = (start: number, end: number): Array => [ + { + _tag: "Data", + data: Array.from({ length: end - start + 1 }, (_, i) => ({ block: start + i })), + ranges: [makeBlockRange("eth", start, end)] + }, + { _tag: "Watermark", ranges: [makeBlockRange("eth", start, end)] } + ] + + const reorg = (start: number, end: number): Array => [ + { + _tag: "Reorg", + previous: [], + incoming: [makeBlockRange("eth", start, end)], + invalidation: [makeInvalidationRange("eth", start, end)] + } + ] + + /** + * Streams the first connection's messages through the real transactional and CDC layers, then resumes with the + * state it committed, serving the remaining connections. Returns the blocks a consumer that applies each Insert + * and Delete ends up with, how the resumed session ended, and how many connections it opened. + */ + const run = (retention: number, connections: ReadonlyArray>) => { + let connection = 0 + const layer = cdcStreamLayer.pipe( + Layer.provide(InMemoryBatchStore.layer), + Layer.provide(transactionalStreamLayer), + Layer.provide(InMemoryStateStore.layer), + Layer.provide( + Layer.succeed(ProtocolStream, { + stream: () => Stream.fromIterable(connections[connection++] ?? []) + } as ProtocolStream["Service"]) + ) + ) + + return Effect.gen(function* () { + const cdc = yield* CdcStream + const rows = new Map>>() + const consume = cdc.forEach("SELECT * FROM eth.blocks", { retention }, (event) => + Effect.gen(function* () { + if (event._tag === "Insert") { + rows.set(event.id, event.data) + return + } + let next = yield* event.batches.next + while (next !== undefined) { + rows.delete(next[0]) + next = yield* event.batches.next + } + }) + ) + + yield* consume + const error = yield* consume.pipe(Effect.match({ onFailure: identity, onSuccess: () => undefined })) + + return { + blocks: [...rows.values()] + .flat() + .map((row) => row.block as number) + .sort((a, b) => a - b), + connections: connection, + error + } + }).pipe(Effect.provide(layer)) + } + + const blocks = (start: number, end: number) => Array.from({ length: end - start + 1 }, (_, i) => start + i) + + it.effect("fails instead of replaying pruned batches when retention is zero", () => + Effect.gen(function* () { + const result = yield* run(0, [[...batch(0, 34), ...batch(35, 37)], reorg(36, 38), batch(0, 38)]) + + expect(result.error?._tag).toBe("PartialReorgError") + expect(result.connections).toBe(2) + expect(result.blocks).toEqual(blocks(0, 37)) + }) + ) + + it.effect("fails instead of replaying pruned batches when the watermark before the reorg was pruned", () => + Effect.gen(function* () { + const result = yield* run(128, [ + [...batch(0, 99), ...batch(100, 199), ...batch(200, 299), ...batch(300, 399)], + reorg(150, 400), + batch(0, 400) + ]) + + expect(result.error?._tag).toBe("PartialReorgError") + expect(result.connections).toBe(2) + expect(result.blocks).toEqual(blocks(0, 399)) + }) + ) + + it.effect("recovers from a retained watermark", () => + Effect.gen(function* () { + const result = yield* run(128, [[...batch(0, 34), ...batch(35, 37)], reorg(36, 38), batch(35, 38)]) + + expect(result.error).toBeUndefined() + expect(result.connections).toBe(3) + expect(result.blocks).toEqual(blocks(0, 38)) + }) + ) + + it.effect("recovers from a retained watermark after older ones were pruned", () => + Effect.gen(function* () { + const result = yield* run(128, [ + [...batch(0, 99), ...batch(100, 199), ...batch(200, 299), ...batch(300, 399)], + reorg(350, 400), + batch(300, 400) + ]) + + expect(result.error).toBeUndefined() + expect(result.connections).toBe(3) + expect(result.blocks).toEqual(blocks(0, 400)) + }) + ) +}) diff --git a/packages/amp/test/transactional-stream/state-actor.test.ts b/packages/amp/test/transactional-stream/state-actor.test.ts index 941fbd0..df61424 100644 --- a/packages/amp/test/transactional-stream/state-actor.test.ts +++ b/packages/amp/test/transactional-stream/state-actor.test.ts @@ -5,7 +5,12 @@ */ import type { BlockNumber, BlockRange, Network } from "@edgeandnode/amp/core" import type { ProtocolMessage } from "@edgeandnode/amp/protocol-stream" -import { InMemoryStateStore, StateStore, type TransactionId } from "@edgeandnode/amp/transactional-stream" +import { + InMemoryStateStore, + PartialReorgError, + StateStore, + type TransactionId +} from "@edgeandnode/amp/transactional-stream" import { makeStateActor } from "@edgeandnode/amp/transactional-stream/state-actor" import { describe, expect, it } from "@effect/vitest" import * as Effect from "effect/Effect" @@ -469,12 +474,13 @@ describe("StateActor.execute - PartialReorg", () => { start: i.start as BlockNumber, end: i.end as BlockNumber })) + const error = new PartialReorgError({ reason: "partial", network: "eth", invalidation }) it.effect("undoes back to the last watermark before the reorg", () => Effect.gen(function* () { const store = yield* StateStore const actor = yield* makeStateActor(store, 128) - const [event] = yield* actor.execute({ _tag: "PartialReorg", invalidation }) + const [event] = yield* actor.execute({ _tag: "PartialReorg", error }) expect(event._tag).toBe("Undo") if (event._tag === "Undo") { @@ -498,16 +504,17 @@ describe("StateActor.execute - PartialReorg", () => { ) ) - it.effect("undoes everything when no watermark ends before the reorg", () => + it.effect("fails and keeps its watermarks when none ends before the reorg", () => Effect.gen(function* () { const store = yield* StateStore const actor = yield* makeStateActor(store, 128) - const [event] = yield* actor.execute({ _tag: "PartialReorg", invalidation }) + const failure = yield* Effect.flip(actor.execute({ _tag: "PartialReorg", error })) - expect(event._tag === "Undo" && event.invalidate).toEqual({ start: 0, end: 1 }) - expect(yield* actor.watermark).toBeUndefined() + expect(failure._tag).toBe("PartialReorgError") + expect(failure._tag === "PartialReorgError" && failure.invalidation).toEqual(invalidation) + expect((yield* actor.watermark)?.[0]).toBe(1) const snapshot = yield* store.load - expect(snapshot.buffer).toEqual([]) + expect(snapshot.buffer.map(([id]) => id)).toEqual([1]) }).pipe( Effect.provide( InMemoryStateStore.layerWithState({ diff --git a/packages/amp/test/transactional-stream/stream.test.ts b/packages/amp/test/transactional-stream/stream.test.ts index 18559ae..c9d5e04 100644 --- a/packages/amp/test/transactional-stream/stream.test.ts +++ b/packages/amp/test/transactional-stream/stream.test.ts @@ -10,10 +10,12 @@ import { layer as transactionalStreamLayer, type StateSnapshot, TransactionalStream, + type TransactionEvent, type TransactionId } from "@edgeandnode/amp/transactional-stream" import { describe, expect, it } from "@effect/vitest" import * as Effect from "effect/Effect" +import { identity } from "effect/Function" import * as Layer from "effect/Layer" import * as Stream from "effect/Stream" @@ -73,8 +75,12 @@ const run = (snapshot: StateSnapshot, connections: ReadonlyArray event), log } + const events: Array = [] + const error = yield* transactionalStream.streamTransactional("SELECT * FROM eth.logs").pipe( + Stream.runForEach(([event]) => Effect.sync(() => events.push(event))), + Effect.match({ onFailure: identity, onSuccess: () => undefined }) + ) + return { error, events, log } }).pipe(Effect.provide(layer)) } @@ -109,9 +115,9 @@ describe("TransactionalStream.streamTransactional", () => { }) ) - it.effect("starts over when a reorg starts inside the only watermark", () => + it.effect("fails without reconnecting when no watermark ends before the reorg", () => Effect.gen(function* () { - const { events, log } = yield* run( + const { error, events, log } = yield* run( { buffer: [[1 as TransactionId, [makeBlockRange(0, 37)]]], next: 2 as TransactionId @@ -119,10 +125,9 @@ describe("TransactionalStream.streamTransactional", () => { [[reorg(36, 38), data(36, 38)], [data(0, 38)]] ) - expect(log).toEqual(["open 0 from 0-37", "close 0", "open 1 from start", "close 1"]) - expect(events.map((event) => event._tag)).toEqual(["Undo", "Data"]) - const undo = events[0]! - expect(undo._tag === "Undo" && undo.invalidate).toEqual({ start: 0, end: 2 }) + expect(error?._tag).toBe("PartialReorgError") + expect(log).toEqual(["open 0 from 0-37", "close 0"]) + expect(events).toEqual([]) }) )