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
3 changes: 2 additions & 1 deletion packages/amp/src/transactional-stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,5 +135,6 @@ export {
checkPartialReorg,
compressCommits,
findPruningPoint,
findRecoveryPoint
findRecoveryPoint,
findResumePoint
} from "./transactional-stream/algorithms.ts"
35 changes: 33 additions & 2 deletions packages/amp/src/transactional-stream/algorithms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<readonly [TransactionId, ReadonlyArray<BlockRange>]>,
invalidation: ReadonlyArray<InvalidationRange>
): readonly [TransactionId, ReadonlyArray<BlockRange>] | 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
// =============================================================================
Expand Down Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions packages/amp/src/transactional-stream/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -40,13 +41,16 @@ export class UnrecoverableReorgError extends Schema.TaggedError<UnrecoverableReo
/**
* Partial reorg - recovery point doesn't align with invalidation boundary.
* This occurs when a reorg point falls in the middle of a watermark's block range.
* The stream must be restarted with fresh state.
* TransactionalStream recovers from it by undoing back to an earlier watermark and reconnecting from there.
* It only reaches consumers when no buffered watermark ends before the reorg. The stream must then be restarted
* with fresh state.
*/
export class PartialReorgError extends Schema.TaggedError<PartialReorgError>(
"Amp/TransactionalStream/PartialReorgError"
)("PartialReorgError", {
reason: Schema.String,
network: Schema.String
network: Schema.String,
invalidation: Schema.Array(InvalidationRange)
}) {}

// =============================================================================
Expand Down
54 changes: 51 additions & 3 deletions packages/amp/src/transactional-stream/state-actor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 error: PartialReorgError }

/**
* StateActor interface - manages transactional stream state.
Expand Down Expand Up @@ -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.error, containerRef, store)
}
})()

Expand Down Expand Up @@ -323,13 +330,54 @@ 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.
* 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,
error: PartialReorgError,
containerRef: Ref.Ref<StateContainer>,
store: StateStoreService
): Effect.fn.Return<TransactionEvent, StateStoreError | PartialReorgError> {
const state = yield* Ref.get(containerRef)
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, resumePoint[0], error.invalidation, containerRef, store)
})

/**
* Undo everything after the anchor because of a reorg.
*/
const undoReorg = Effect.fnUntraced(function* (
id: TransactionId,
anchor: TransactionId | undefined,
invalidation: ReadonlyArray<InvalidationRange>,
containerRef: Ref.Ref<StateContainer>,
store: StateStoreService
): Effect.fn.Return<TransactionEvent, StateStoreError> {
// 4. Compute invalidation range and truncate both in-memory and store
const range = computeInvalidationRange(anchor, id)

Expand Down
25 changes: 21 additions & 4 deletions packages/amp/src/transactional-stream/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<BlockRange> | 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", (error) =>
Stream.fromEffect(actor.execute({ _tag: "PartialReorg", error })).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
Expand All @@ -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)
})
Expand Down
127 changes: 127 additions & 0 deletions packages/amp/test/cdc-stream/stream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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"
Expand Down Expand Up @@ -395,3 +399,126 @@ describe("CdcStream.forEach", () => {
})
)
})

// =============================================================================
// Partial Reorg Tests
// =============================================================================

describe("CdcStream - partial reorg", () => {
const batch = (start: number, end: number): Array<ProtocolMessage> => [
{
_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<ProtocolMessage> => [
{
_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<ReadonlyArray<ProtocolMessage>>) => {
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<TransactionId, ReadonlyArray<Record<string, unknown>>>()
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))
})
)
})
Loading
Loading