Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 12 additions & 9 deletions packages/amp/src/protocol-stream/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -208,23 +209,25 @@ 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<ProtocolMessage> = []

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 = {
previous: incoming,
initialized: true
}

return [newState, [message]] as const
return [newState, messages] as const
})
),
Stream.withSpan("ProtocolStream.stream")
Expand Down
6 changes: 4 additions & 2 deletions packages/amp/src/transactional-stream/memory-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,11 @@ const makeServiceFromRef = (stateRef: Ref.Ref<StateSnapshot>): 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 }
Expand Down
92 changes: 91 additions & 1 deletion packages/amp/test/protocol-stream/reorg.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<QueryResult<Record<string, unknown>>>) =>
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 } }
])
)
)
)
})
16 changes: 16 additions & 0 deletions packages/amp/test/transactional-stream/memory-store.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading