import { describe, expect, test } from 'bun:test' import { setTimeout as sleep } from 'node:timers/promises' import { table } from '@chkit/core' import { ingestionColumns, rawRows, rawTable } from './destination.js' import { HttpError } from './errors.js' import { runIngestion } from './executor.js' import { cursorState, timestampWindow } from './incremental.js' import { paginate } from './paginate.js' import { definePipeline, defineStream, selectStreams } from './registry.js' import { createMemoryDestination, createMemoryJournal, createSourceContext } from './testing.js' import type { DestinationAdapter, SourceContext } from './types.js' const events = table({ database: 'app', name: 'events', columns: [ { name: 'id', type: 'UInt64' }, { name: 'label', type: 'String' }, { name: 'value', type: 'String' }, { name: 'nested', type: 'JSON' }, ...ingestionColumns, ], engine: 'MergeTree()', primaryKey: ['id'], orderBy: ['id'], }) const pages = (count: number, size: number) => Array.from({ length: count }, (_, page) => Array.from({ length: size }, (_, index) => ({ id: page * size + index }))) function httpError(status: number, headers: Record = {}) { return HttpError.fromResponse(new Response('nope', { status, headers })) } const connectionReset = (message: string) => Object.assign(new Error(message), { code: 'ECONNRESET' }) describe('runIngestion', () => { test('loads rows with runtime metadata and journals progress only after sink evidence', async () => { const journal = createMemoryJournal() const destination = createMemoryDestination() const order: string[] = [] const observed: DestinationAdapter = { insert: async (input) => { await destination.insert(input) order.push('insert') }, } const stream = defineStream({ id: 'app.events', destination: events, async *read() { yield { rows: [{ id: 1 }, { id: 2 }] } }, }) const pipeline = definePipeline({ id: 'app', streams: [stream] }) const append = journal.append.bind(journal) journal.append = async (appended) => { if (appended.some((event) => event.eventKind === 'batch_committed')) order.push('commit') await append(appended) } const result = await runIngestion({ selected: selectStreams([pipeline], []), backfill: undefined }, { journal, destination: observed }) expect(result.ok).toBe(true) expect(order).toEqual(['insert', 'commit']) const rows = destination.tables.get('app.events') ?? [] expect(rows.map((row) => row.id)).toEqual([1, 2]) expect(rows[0]?._chkit_run_id).toBe(result.runId) expect(typeof rows[0]?._chkit_batch_id).toBe('string') expect(rows[0]).not.toHaveProperty('_chkit_ingested_at') expect(journal.events.map((event) => event.eventKind)).toEqual([ 'run_started', 'work_planned', 'attempt_started', 'batch_committed', 'work_finished', 'run_finished', ]) }) test('a crash before sink evidence never advances the bookmark, and the restart neither skips nor duplicates rows', async () => { const journal = createMemoryJournal() const destination = createMemoryDestination() const source = pages(3, 2) const stream = defineStream({ id: 'app.cursor', destination: events, batchSize: 2, incremental: cursorState({ id: 'test.page', version: 1, parse: (raw) => Number(raw), }), async *read({ selection }) { for (let page = selection ?? 0; page < source.length; page += 1) { yield { rows: source[page] ?? [], state: page + 1 } } }, }) const pipeline = definePipeline({ id: 'app', streams: [stream] }) let firstWrite = true let acknowledgementLost = false const crashing: DestinationAdapter = { insert: async (input) => { // A transient error on the first batch must not shift the simulated // acknowledgement loss onto that batch's retry. if (firstWrite) { firstWrite = false throw new Error('temporary insert failure') } // Second batch: the write lands but the acknowledgement is lost. if (input.rows[0]?.id === 2) { if (acknowledgementLost) throw new Error('still down') await destination.insert(input) acknowledgementLost = true throw new Error('socket hang up') } await destination.insert(input) }, } const first = await runIngestion({ selected: selectStreams([pipeline], []), backfill: undefined }, { journal, destination: crashing }) expect(first.ok).toBe(false) expect(first.streams[0]).toMatchObject({ outcome: 'failed', rows: 2, batches: 1, error: 'still down' }) expect((await journal.readCheckpoint('app.cursor')).envelope?.state).toBe(1) const second = await runIngestion({ selected: selectStreams([pipeline], []), backfill: undefined }, { journal, destination }) expect(second.ok).toBe(true) expect((await journal.readCheckpoint('app.cursor')).envelope?.state).toBe(3) const ids = (destination.tables.get('app.events') ?? []).map((row) => row.id) expect(ids).toEqual([0, 1, 2, 3, 4, 5]) }, 10_000) test('timestampWindow commits the cutoff as watermark only after the whole window loaded', async () => { const journal = createMemoryJournal() const destination = createMemoryDestination() const selections: Array<{ from: string; to: string }> = [] const stream = defineStream({ id: 'app.window', destination: events, incremental: timestampWindow({ start: new Date('2026-01-01T00:00:00Z') }), async *read({ selection }) { selections.push({ from: selection.from.toISOString(), to: selection.to.toISOString() }) yield { rows: [{ id: selections.length }] } }, }) const pipeline = definePipeline({ id: 'app', streams: [stream] }) const times = [new Date('2026-02-01T00:00:00Z'), new Date('2026-03-01T00:00:00Z')] for (const time of times) { await runIngestion({ selected: selectStreams([pipeline], []), backfill: undefined }, { journal, destination, now: () => time }) } expect(selections).toEqual([ { from: '2026-01-01T00:00:00.000Z', to: '2026-02-01T00:00:00.000Z' }, { from: '2026-02-01T00:00:00.000Z', to: '2026-03-01T00:00:00.000Z' }, ]) expect((await journal.readCheckpoint('app.window')).envelope?.state).toEqual({ watermark: '2026-03-01T00:00:00.000Z' }) }) test('a failed window leaves the watermark untouched', async () => { const journal = createMemoryJournal() const stream = defineStream({ id: 'app.window', destination: events, incremental: timestampWindow({ start: new Date(0) }), async *read() { yield { rows: [{ id: 1 }] } throw new Error('provider exploded') }, }) const pipeline = definePipeline({ id: 'app', streams: [stream] }) const result = await runIngestion({ selected: selectStreams([pipeline], []), backfill: undefined }, { journal, destination: createMemoryDestination() }) expect(result.streams[0]?.outcome).toBe('failed') expect(result.streams[0]?.error).toContain('provider exploded') expect((await journal.readCheckpoint('app.window')).envelope).toBeUndefined() }) test('attempt retries rate limits and transient failures but not permanent ones', async () => { const journal = createMemoryJournal() const destination = createMemoryDestination() let calls = 0 const flaky = defineStream({ id: 'app.flaky', destination: events, async *read(context) { const rows = await context.attempt(async () => { calls += 1 if (calls === 1) throw await httpError(429, { 'retry-after': '0.02' }) if (calls === 2) throw await httpError(503) return [{ id: 1 }] }) yield { rows } }, }) const denied = defineStream({ id: 'app.denied', destination: events, async *read(context) { yield { rows: await context.attempt(async () => { throw await httpError(401) }) } }, }) const pipeline = definePipeline({ id: 'app', streams: [flaky, denied] }) const result = await runIngestion( { selected: selectStreams([pipeline], []), backfill: undefined }, { journal, destination, retry: { randomize: false, minTimeout: 10 } } ) expect(calls).toBe(3) // One failing stream does not stop its sibling. expect(result.streams.map((stream) => stream.outcome)).toEqual(['succeeded', 'failed']) expect(journal.events.filter((event) => event.eventKind === 'retry_scheduled').map((event) => event.errorClass)).toEqual(['rate_limited', 'transient']) }) test('refuses to reinterpret a checkpoint written by another strategy version', async () => { const journal = createMemoryJournal() const destination = createMemoryDestination() const build = (version: number) => { const stream = defineStream({ id: 'app.versioned', destination: events, incremental: cursorState({ id: 'test.cursor', version, parse: (raw) => String(raw) }), async *read() { yield { rows: [{ id: 1 }], state: 'c1' } }, }) return definePipeline({ id: 'app', streams: [stream] }) } await runIngestion({ selected: selectStreams([build(1)], []), backfill: undefined }, { journal, destination }) const result = await runIngestion({ selected: selectStreams([build(2)], []), backfill: undefined }, { journal, destination }) expect(result.streams[0]?.outcome).toBe('failed') expect(result.streams[0]?.error).toContain('never silently reinterprets') }) test('budget exhaustion is incomplete but preserves committed progress', async () => { const journal = createMemoryJournal() const destination = createMemoryDestination() const stream = defineStream({ id: 'app.budget', destination: events, batchSize: 1, budget: { maxChunks: 2 }, incremental: cursorState({ id: 'test.page', version: 1, parse: (raw) => Number(raw) }), async *read({ selection }) { for (let page = selection ?? 0; page < 5; page += 1) yield { rows: [{ id: page }], state: page + 1 } }, }) const pipeline = definePipeline({ id: 'app', streams: [stream] }) const result = await runIngestion({ selected: selectStreams([pipeline], []), backfill: undefined }, { journal, destination }) expect(result.ok).toBe(false) expect(result.streams[0]?.outcome).toBe('budget_exhausted') expect((await journal.readCheckpoint('app.budget')).envelope?.state).toBe(2) }) test('a backfill uses an isolated checkpoint namespace', async () => { const journal = createMemoryJournal() const destination = createMemoryDestination() const stream = defineStream({ id: 'app.window', destination: events, incremental: timestampWindow({ start: new Date(0) }), async *read() { yield { rows: [{ id: 1 }] } }, }) const pipeline = definePipeline({ id: 'app', streams: [stream] }) await runIngestion( { selected: selectStreams([pipeline], []), backfill: { id: 'jan', from: new Date('2026-01-01'), to: new Date('2026-02-01') } }, { journal, destination } ) expect((await journal.readCheckpoint('app.window')).envelope).toBeUndefined() expect((await journal.readCheckpoint('app.window#backfill:jan')).envelope?.state).toEqual({ watermark: '2026-02-01T00:00:00.000Z' }) }) }) describe('runtime contracts', () => { const run = (pipeline: ReturnType, env: Parameters[1]) => runIngestion({ selected: selectStreams([pipeline], []), backfill: undefined }, env) test('content-based batch identity supports BigInt rows and stays stable on replay', async () => { const journal = createMemoryJournal() const destination = createMemoryDestination() const row = { id: 9007199254740993n, nested: { values: [-9223372036854775808n] } } const tokens: string[] = [] let loseAcknowledgement = true const stream = defineStream({ id: 'app.bigint', destination: events, async *read() { yield { rows: [row] } }, }) const pipeline = definePipeline({ id: 'app', streams: [stream] }) const observed: DestinationAdapter = { async insert(input) { tokens.push(input.token) // Custom destinations continue receiving the original values. expect(input.rows[0]?.id).toBe(row.id) await destination.insert(input) if (loseAcknowledgement) throw new TypeError('acknowledgement lost') } } expect((await run(pipeline, { journal, destination: observed })).streams[0]?.error).toBe('acknowledgement lost') loseAcknowledgement = false expect((await run(pipeline, { journal, destination: observed })).ok).toBe(true) expect(tokens).toHaveLength(2) expect(tokens[0]).toBe(tokens[1]) expect(destination.tables.get('app.events')).toHaveLength(1) }) test.each(['source', 'sink'] as const)('a request-local AbortError in the %s is retried without cancelling the run', async (boundary) => { const journal = createMemoryJournal() const destination = createMemoryDestination() let calls = 0 const operation = async () => { if (++calls === 1) throw new DOMException('request timed out', 'AbortError') return [{ id: 1 }] } const stream = defineStream({ id: 'app.local_abort', destination: events, async *read({ attempt }) { yield { rows: boundary === 'sink' ? [{ id: 1 }] : await attempt(operation) } }, }) const result = await run(definePipeline({ id: 'app', streams: [stream] }), { journal, retry: { retries: 1, minTimeout: 0 }, destination: boundary === 'sink' ? { async insert(input) { await operation(); await destination.insert(input) } } : destination, }) expect(result.streams[0]).toMatchObject({ outcome: 'succeeded', rows: 1, error: undefined }) expect(calls).toBe(2) }) test('exhausted request-local abort retries report failure, not budget exhaustion', async () => { let calls = 0 const stream = defineStream({ id: 'app.local_abort', destination: events, async *read({ attempt }) { yield { rows: await attempt(async () => { calls += 1; throw new DOMException('request timed out', 'AbortError') }) } }, }) const result = await run(definePipeline({ id: 'app', streams: [stream] }), { journal: createMemoryJournal(), destination: createMemoryDestination(), retry: { retries: 1, minTimeout: 0 }, }) expect(result.streams[0]).toMatchObject({ outcome: 'failed', error: 'request timed out' }) expect(calls).toBe(2) }) test('a sink failure at the chunk limit cannot recreate the reader or hide the failure', async () => { const journal = createMemoryJournal() let readers = 0 let pulled = 0 const stream = defineStream({ id: 'app.bounded', destination: events, batchSize: 1, budget: { maxChunks: 1 }, incremental: timestampWindow({ start: new Date(0) }), async *read() { readers += 1 for (let id = 0; id < 3; id += 1) { pulled += 1; yield { rows: [{ id }] } } }, }) const result = await run(definePipeline({ id: 'app', streams: [stream] }), { journal, destination: { async insert() { throw new TypeError('sink serialization failed') } }, }) expect(result.streams[0]).toMatchObject({ outcome: 'failed', chunks: 1, error: 'sink serialization failed' }) expect(readers).toBe(1) expect(pulled).toBe(1) expect((await journal.readCheckpoint(stream.id)).envelope).toBeUndefined() expect(journal.events.filter((event) => event.eventKind === 'retry_scheduled')).toHaveLength(0) }) test('a transient failure outside a request fails the stream and keeps committed progress', async () => { const journal = createMemoryJournal() const append = journal.append.bind(journal) let committed: () => void = () => undefined const saved = new Promise((resolve) => { committed = resolve }) journal.append = async (appended) => { await append(appended) if (appended.some((event) => event.eventKind === 'batch_committed')) committed() } let readers = 0 const stream = defineStream({ id: 'app.disconnects', destination: events, batchSize: 1, incremental: cursorState({ id: 'page', version: 1, parse: (raw) => Number(raw) }), async *read({ selection }) { readers += 1 yield { rows: [{ id: selection ?? 0 }], state: (selection ?? 0) + 1 } if (selection === undefined) { await saved throw connectionReset('reader disconnected') } }, }) const pipeline = definePipeline({ id: 'app', streams: [stream] }) expect((await run(pipeline, { journal, destination: createMemoryDestination() })).streams[0]).toMatchObject({ outcome: 'failed', error: 'reader disconnected' }) expect(readers).toBe(1) expect((await journal.readCheckpoint(stream.id)).envelope?.state).toBe(1) expect((await run(pipeline, { journal, destination: createMemoryDestination() })).ok).toBe(true) expect((await journal.readCheckpoint(stream.id)).envelope?.state).toBe(2) }) test.each([false, true])('new full syncs preserve changes while failed syncs reuse tokens (declared id: %s)', async (withId) => { const journal = createMemoryJournal() const destination = createMemoryDestination() let label = 'A' const stream = defineStream({ id: 'app.full', destination: events, async *read() { yield { rows: [{ id: 1, label }], ...(withId ? { id: 'page:1' } : {}) } }, }) const pipeline = definePipeline({ id: 'app', streams: [stream] }) expect((await run(pipeline, { journal, destination })).ok).toBe(true) const firstSuccess = (await journal.readCheckpoint(stream.id)).successId expect(firstSuccess).not.toBe('') label = 'B' const lossy: DestinationAdapter = { async insert(input) { await destination.insert(input) throw new Error('acknowledgement lost') } } expect((await run(pipeline, { journal, destination: lossy })).ok).toBe(false) expect((await journal.readCheckpoint(stream.id)).successId).toBe(firstSuccess) expect((await run(pipeline, { journal, destination })).ok).toBe(true) label = 'A' expect((await run(pipeline, { journal, destination })).ok).toBe(true) expect(destination.tables.get('app.events')?.map((row) => row.label)).toEqual(['A', 'B', 'A']) expect((await journal.readCheckpoint(stream.id)).envelope).toBeUndefined() }) test('full sync boundaries advance with a fixed clock while local sequences restart', async () => { const journal = createMemoryJournal() const destination = createMemoryDestination() const now = () => new Date('2026-10-09T00:00:00Z') let value = 'A' const stream = defineStream({ id: 'app.fixed_clock', destination: events, async *read() { yield { rows: [{ id: 1, value }], id: 'page:1' } }, }) const pipeline = definePipeline({ id: 'app', streams: [stream] }) const successes = new Set() for (const next of ['A', 'B', 'A']) { value = next const result = await run(pipeline, { journal, destination, now }) expect(result.ok).toBe(true) const checkpoint = await journal.readCheckpoint(stream.id) expect(checkpoint.successId).toBe(`${result.runId}:4`) expect(successes.has(checkpoint.successId)).toBe(false) successes.add(checkpoint.successId) expect(journal.events.filter((event) => event.namespaceId === stream.id && event.runId === result.runId).map((event) => event.eventSeq)).toEqual([1, 2, 3, 4]) } expect(destination.tables.get('app.events')?.map((row) => row.value)).toEqual(['A', 'B', 'A']) }) test('a checkpoint whose acknowledgement is always lost is resumed by the next run', async () => { const journal = createMemoryJournal() const destination = createMemoryDestination() const append = journal.append.bind(journal) const stream = defineStream({ id: 'app.lost_checkpoint', destination: events, batchSize: 1, incremental: cursorState({ id: 'test.cursor', version: 1, parse: (value) => Number(value) }), async *read({ state }) { for (let id = state ?? 0; id < 2; id += 1) yield { rows: [{ id }], state: id + 1 } }, }) const pipeline = definePipeline({ id: 'app', streams: [stream] }) let ambiguousAttempts = 0 journal.append = async (appended) => { await append(appended) if (appended.some((event) => event.eventKind === 'batch_committed')) { ambiguousAttempts += 1 throw new Error('checkpoint acknowledgement lost') } } const first = await run(pipeline, { journal, destination }) expect(first.ok).toBe(false) expect(ambiguousAttempts).toBe(4) expect((await journal.readCheckpoint(stream.id)).envelope?.state).toBe(1) journal.append = append const second = await run(pipeline, { journal, destination }) expect(second.ok).toBe(true) expect((await journal.readCheckpoint(stream.id)).envelope?.state).toBe(2) expect(destination.tables.get('app.events')?.map((row) => row.id)).toEqual([0, 1]) }, 10_000) test.each(['deadline', 'cancel'] as const)('a hung destination never reports success after %s', async (mode) => { const journal = createMemoryJournal() const controller = new AbortController() let finishWrite: () => void = () => undefined const destination: DestinationAdapter = { insert: () => new Promise((resolve) => { finishWrite = resolve }) } const stream = defineStream({ id: 'app.hung_load', destination: events, async *read() { yield { rows: [{ id: 1 }] } }, }) const timer = mode === 'cancel' ? setTimeout(() => controller.abort(), 20) : undefined try { const result = await run(definePipeline({ id: 'app', streams: [stream] }), { journal, destination, signal: controller.signal, maxDurationMs: mode === 'deadline' ? 20 : 60_000, }) expect(result.ok).toBe(false) expect(result.streams[0]?.outcome).toBe(mode === 'deadline' ? 'budget_exhausted' : 'cancelled') expect(result.streams[0]?.rows).toBe(0) finishWrite() await new Promise((resolve) => setTimeout(resolve, 0)) expect(journal.events.filter((event) => event.eventKind === 'batch_committed')).toEqual([]) } finally { clearTimeout(timer) finishWrite() } }, 10_000) test.each(['ensure', 'run_started', 'stream_read', 'work_planned', 'batch_committed'])( 'the execution deadline bounds a hung journal %s', async (stage) => { const journal = createMemoryJournal() const append = journal.append.bind(journal) const read = journal.readCheckpoint.bind(journal) const hung = () => new Promise(() => undefined) if (stage === 'ensure') journal.ensure = hung journal.readCheckpoint = (namespace) => ( stage === 'stream_read' && !namespace.startsWith('@run:') ? hung() : read(namespace) ) journal.append = (appended) => appended.some((event) => event.eventKind === stage) ? hung() : append(appended) const stream = defineStream({ id: 'app.journal', destination: events, async *read() { yield { rows: [{ id: 1 }] } } }) const execution = run(definePipeline({ id: 'app', streams: [stream] }), { journal, destination: createMemoryDestination(), maxDurationMs: 20, }) if (['ensure', 'run_started'].includes(stage)) { await expect(execution).rejects.toThrow('execution budget exhausted') } else { const result = await execution expect(result.ok).toBe(false) expect(result.streams[0]?.outcome).toBe('budget_exhausted') } }, 1000 ) test.each(['work_finished', 'run_finished'])('a hung terminal journal %s has bounded cleanup', async (stage) => { const journal = createMemoryJournal() const append = journal.append.bind(journal) journal.append = (appended) => appended.some((event) => event.eventKind === stage) ? new Promise(() => undefined) : append(appended) const stream = defineStream({ id: 'app.terminal', destination: events, async *read() { yield { rows: [{ id: 1 }] } } }) const execution = run(definePipeline({ id: 'app', streams: [stream] }), { journal, destination: createMemoryDestination(), maxDurationMs: 100, }) if (stage === 'run_finished') await expect(execution).rejects.toThrow() else expect((await execution).ok).toBe(false) }, 8000) test.each(['work_finished', 'run_finished'])('a slow terminal journal %s still lands while the run is live', async (stage) => { const journal = createMemoryJournal() const append = journal.append.bind(journal) journal.append = async (appended) => { if (appended.some((event) => event.eventKind === stage)) await sleep(5500) await append(appended) } const stream = defineStream({ id: 'app.slow_terminal', destination: events, async *read() { yield { rows: [{ id: 1 }] } } }) const result = await run(definePipeline({ id: 'app', streams: [stream] }), { journal, destination: createMemoryDestination() }) expect(result.ok).toBe(true) expect(journal.events.map((event) => event.eventKind)).toContain(stage) }, 10_000) test.each(['run_started', 'run_finished'])('a transient %s append failure retries the same run fact', async (stage) => { const journal = createMemoryJournal() const append = journal.append.bind(journal) let failures = 0 journal.append = async (appended) => { if (appended.some((event) => event.eventKind === stage) && failures === 0) { failures += 1 throw new Error('UNKNOWN_TABLE on a lagging replica') } await append(appended) } const stream = defineStream({ id: 'app.transient_run_fact', destination: events, async *read() { yield { rows: [{ id: 1 }] } } }) const result = await run(definePipeline({ id: 'app', streams: [stream] }), { journal, destination: createMemoryDestination() }) expect(result.ok).toBe(true) expect(failures).toBe(1) expect(journal.events.filter((event) => event.eventKind === stage)).toHaveLength(1) }) test('a throwing loader factory releases its permit for sibling streams', async () => { const failed = defineStream({ id: 'app.factory', destination: events, loader() { throw new Error('loader construction failed') }, async *read() { yield { rows: [{ id: 1 }] } }, }) const healthy = defineStream({ id: 'app.healthy', destination: events, async *read() { yield { rows: [{ id: 2 }] } } }) const destination = createMemoryDestination() const result = await run(definePipeline({ id: 'app', streams: [failed, healthy], maxLoads: 1 }), { journal: createMemoryJournal(), destination, maxDurationMs: 100, }) expect(result.streams.map((stream) => stream.outcome)).toEqual(['failed', 'succeeded']) expect(destination.tables.get('app.events')?.map((row) => row.id)).toEqual([2]) }) test('a declared interval id keeps batch identity stable when replayed rows changed', async () => { const build = (label: string, withId: boolean) => { const stream = defineStream({ id: 'app.mutable', destination: events, async *read() { yield { rows: [{ id: 1, label }], ...(withId ? { id: 'page:1' } : {}) } }, }) return definePipeline({ id: 'app', streams: [stream] }) } const declared = createMemoryDestination() await run(build('before', true), { journal: createMemoryJournal(), destination: declared }) await run(build('after', true), { journal: createMemoryJournal(), destination: declared }) expect(declared.tables.get('app.events')).toHaveLength(1) // Without a declared interval the content hash wins: a duplicate over a suppressed change. const undeclared = createMemoryDestination() await run(build('before', false), { journal: createMemoryJournal(), destination: undeclared }) await run(build('after', false), { journal: createMemoryJournal(), destination: undeclared }) expect(undeclared.tables.get('app.events')).toHaveLength(2) }) test('rejects host limits the runtime cannot honour instead of silently degrading them', async () => { const stream = defineStream({ id: 'app.limits', destination: events, async *read() { yield { rows: [{ id: 1 }] } } }) const selected = selectStreams([definePipeline({ id: 'app', streams: [stream] })], []) const env = () => ({ journal: createMemoryJournal(), destination: createMemoryDestination() }) for (const maxDurationMs of [Number.POSITIVE_INFINITY, Number.NaN, 0, -1, 2 ** 31]) { await expect(runIngestion({ selected, backfill: undefined }, { ...env(), maxDurationMs })).rejects.toThrow('maxDurationMs must be a positive number of milliseconds up to 2147483647') } for (const prefetchBatches of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) { await expect(runIngestion({ selected, backfill: undefined }, { ...env(), prefetchBatches })).rejects.toThrow('prefetchBatches must be a positive integer') } const result = await runIngestion({ selected, backfill: undefined }, { ...env(), maxDurationMs: 2 ** 31 - 1, prefetchBatches: 3 }) expect(result.streams[0]).toMatchObject({ outcome: 'succeeded', rows: 1 }) }) test('the execution budget interrupts a hung reader and preserves committed progress', async () => { const journal = createMemoryJournal() const stream = defineStream({ id: 'app.hung', destination: events, batchSize: 1, incremental: cursorState({ id: 'test.page', version: 1, parse: (raw) => Number(raw) }), async *read() { yield { rows: [{ id: 1 }], state: 1 } await new Promise(() => undefined) }, }) const pipeline = definePipeline({ id: 'app', streams: [stream] }) const result = await run(pipeline, { journal, destination: createMemoryDestination(), maxDurationMs: 50 }) expect(result.streams[0]?.outcome).toBe('budget_exhausted') expect((await journal.readCheckpoint('app.hung')).envelope?.state).toBe(1) expect(journal.events.at(-1)?.eventKind).toBe('run_finished') }) test('an oversized chunk fails the stream instead of being buffered', async () => { const stream = defineStream({ id: 'app.big', destination: events, budget: { maxChunkRows: 2 }, async *read() { yield { rows: [{ id: 1 }, { id: 2 }, { id: 3 }] } }, }) const result = await run(definePipeline({ id: 'app', streams: [stream] }), { journal: createMemoryJournal(), destination: createMemoryDestination() }) expect(result.streams[0]?.error).toContain('above the 2-row bound') }) test('a mapped row cannot supply the destination-owned publication time', async () => { const destination = createMemoryDestination() const stream = defineStream({ id: 'app.stamped', destination: events, async *read() { yield { rows: [{ id: 1, _chkit_ingested_at: '2000-01-01 00:00:00' }] } }, }) await run(definePipeline({ id: 'app', streams: [stream] }), { journal: createMemoryJournal(), destination }) expect(destination.tables.get('app.events')?.[0]).not.toHaveProperty('_chkit_ingested_at') }) test('an ambiguous journal append retries the same fact without consuming a sequence number', async () => { const journal = createMemoryJournal() const append = journal.append.bind(journal) let failures = 0 journal.append = async (appended) => { if (appended.some((event) => event.eventKind === 'batch_committed') && failures === 0) { failures += 1 throw new Error('acknowledgement lost') } await append(appended) } const stream = defineStream({ id: 'app.events', destination: events, async *read() { yield { rows: [{ id: 1 }] } } }) const result = await run(definePipeline({ id: 'app', streams: [stream] }), { journal, destination: createMemoryDestination() }) expect(result.ok).toBe(true) const sequences = journal.events.filter((event) => event.namespaceId === 'app.events').map((event) => event.eventSeq) expect(sequences).toEqual([1, 2, 3, 4]) }) test('a planned unit of work and its first attempt share one journal insert', async () => { const journal = createMemoryJournal() const append = journal.append.bind(journal) const inserts: string[][] = [] journal.append = async (appended) => { if (appended.every((event) => event.namespaceId === 'app.events')) inserts.push(appended.map((event) => event.eventKind)) await append(appended) } const stream = defineStream({ id: 'app.events', destination: events, async *read() { yield { rows: [{ id: 1 }] } } }) const result = await run(definePipeline({ id: 'app', streams: [stream] }), { journal, destination: createMemoryDestination() }) expect(result.ok).toBe(true) expect(inserts).toEqual([['work_planned', 'attempt_started'], ['batch_committed'], ['work_finished']]) const sequences = journal.events.filter((event) => event.namespaceId === 'app.events').map((event) => event.eventSeq) expect(sequences).toEqual([1, 2, 3, 4]) }) test.each([ ['completes', { outcome: 'succeeded', rows: 1, error: undefined }], ['fails', { outcome: 'failed', rows: 0, error: 'reader exploded' }], ] as const)('a custom iterator whose return() throws synchronously keeps the outcome of a reader that %s', async (mode, expected) => { const destination = createMemoryDestination() let returns = 0 const stream = defineStream({ id: 'app.custom_iterator', destination: events, read: () => ({ [Symbol.asyncIterator]() { let pulled = false return { async next() { if (pulled && mode === 'fails') throw new Error('reader exploded') if (pulled) return { value: undefined, done: true as const } pulled = true return { value: { rows: [{ id: 1 }] }, done: false as const } }, return(): Promise }>> { returns += 1 throw new Error('cleanup exploded') }, } }, }), }) const result = await run(definePipeline({ id: 'app', streams: [stream] }), { journal: createMemoryJournal(), destination }) expect(result.streams[0]).toMatchObject(expected) expect(returns).toBe(1) }) test('retained source services cannot make requests or append retry facts after completion', async () => { const captured = Promise.withResolvers() const journal = createMemoryJournal() let calls = 0 const stream = defineStream({ id: 'app.retained_attempt', destination: events, async *read(context) { captured.resolve(context) yield { rows: [{ id: 1 }] } }, }) const result = await run(definePipeline({ id: 'app', streams: [stream] }), { journal, destination: createMemoryDestination(), fetch: async () => { calls += 1; return Response.json({ id: 2 }) }, }) const context = await captured.promise const facts = journal.events.length expect(result.ok).toBe(true) await expect(context.attempt(async () => { calls += 1; throw new Error('late request') })).rejects.toThrow('Reader attempt has ended') await expect(context.fetch('https://api.example.com/items')).rejects.toThrow('Reader attempt has ended') expect(calls).toBe(0) expect(journal.events).toHaveLength(facts) }) test('an unawaited source operation cannot start nested requests or retry after its reader completes', async () => { const release = Promise.withResolvers() const started = Promise.withResolvers() const captured = Promise.withResolvers>() const journal = createMemoryJournal() let calls = 0 let nestedCalls = 0 const stream = defineStream({ id: 'app.unawaited_attempt', destination: events, async *read({ attempt }) { const operation = attempt(async () => { calls += 1 started.resolve() await release.promise return attempt(async () => { nestedCalls += 1 throw connectionReset('late failure') }) }) void operation.then( (value) => captured.resolve({ status: 'fulfilled', value }), (reason: unknown) => captured.resolve({ status: 'rejected', reason }) ) await started.promise yield { rows: [{ id: 1 }] } }, }) const result = await run(definePipeline({ id: 'app', streams: [stream] }), { journal, destination: createMemoryDestination(), retry: { retries: 1, minTimeout: 0 }, }) const facts = journal.events.length release.resolve() expect(result.ok).toBe(true) expect((await captured.promise).status).toBe('rejected') expect(calls).toBe(1) expect(nestedCalls).toBe(0) expect(journal.events).toHaveLength(facts) }) test('a failing loader cleanup does not mask the write failure or stop the retry', async () => { const destination = createMemoryDestination() let writes = 0 const stream = defineStream({ id: 'app.cleanup', destination: events, loader: (ctx) => ({ ctx, async write(batch) { writes += 1 if (writes === 1) throw new Error('write failed') await ctx.destination.insert({ table: ctx.table, rows: batch.rows, token: batch.batchId }) }, finalize: async () => ({ evidence: 'clickhouse_ack', rows: 1, writeUnits: 1 }), abort: async () => { throw new Error('cleanup failed') }, }), async *read() { yield { rows: [{ id: 1 }] } }, }) const result = await run(definePipeline({ id: 'app', streams: [stream] }), { journal: createMemoryJournal(), destination }) expect(result.ok).toBe(true) expect(writes).toBe(2) }) }) describe('source services', () => { const run = (pipeline: ReturnType, env: Partial[1]>) => runIngestion({ selected: selectStreams([pipeline], []), backfill: undefined }, { journal: createMemoryJournal(), destination: createMemoryDestination(), ...env }) test('context.fetch retries a transient response, fails any other at once, and returns the body', async () => { const statuses = [503, 200, 404] const calls: string[] = [] const rows: Array<{ id: number }> = [] const stream = defineStream({ id: 'app.fetch', destination: events, async *read(context) { const page = await context.fetch('https://api.example.com/items') rows.push(...(await page.json() as Array<{ id: number }>)) yield { rows } await context.fetch('https://api.example.com/missing') }, }) const result = await run(definePipeline({ id: 'app', streams: [stream] }), { retry: { retries: 2, minTimeout: 0 }, fetch: async (url) => { calls.push(new URL(url).pathname) const status = statuses.shift() ?? 500 return status === 200 ? Response.json([{ id: 1 }]) : new Response('nope', { status }) }, }) expect(rows).toEqual([{ id: 1 }]) expect(calls).toEqual(['/items', '/items', '/missing']) expect(result.streams[0]).toMatchObject({ outcome: 'failed', error: expect.stringContaining('HTTP 404') }) }) test('a rate-limited response pauses every request of its pipeline until Retry-After', async () => { const started = performance.now() const requested = new Map() let limited = false const stream = (name: string, delayMs: number) => defineStream({ id: `app.${name}`, destination: events, async *read(context) { await sleep(delayMs) yield { rows: await (await context.fetch(`https://api.example.com/${name}`)).json() as Array<{ id: number }> } }, }) const result = await run(definePipeline({ id: 'app', maxStreams: 2, maxFetches: 2, streams: [stream('first', 0), stream('second', 50)] }), { retry: { retries: 2, minTimeout: 0 }, fetch: async (url) => { const name = new URL(url).pathname if (name === '/first' && !limited) { limited = true return new Response('slow down', { status: 429, headers: { 'retry-after': '0.3' } }) } requested.set(name, performance.now() - started) return Response.json([{ id: name === '/first' ? 1 : 2 }]) }, }) expect(result.ok).toBe(true) expect(requested.get('/second')).toBeGreaterThanOrEqual(250) }) test('a Retry-After past the Date range waits out the budget like any long hint', async () => { const journal = createMemoryJournal() const stream = defineStream({ id: 'app.limited', destination: events, async *read(context) { yield { rows: await (await context.fetch('https://api.example.com/items')).json() as Array<{ id: number }> } }, }) const result = await run(definePipeline({ id: 'app', streams: [stream] }), { journal, maxDurationMs: 100, retry: { minTimeout: 0, maxRetryTime: Number.POSITIVE_INFINITY }, fetch: async () => new Response('slow down', { status: 429, headers: { 'retry-after': '1e13' } }), }) expect(result.streams[0]?.outcome).toBe('budget_exhausted') expect(journal.events.filter((event) => event.eventKind === 'retry_scheduled')).toMatchObject([{ errorClass: 'rate_limited', retryAt: undefined }]) }) test('the testing source context handles requests like the runtime', async () => { const context = createSourceContext({ fetch: async (url) => new URL(url).pathname === '/ok' ? Response.json({ id: 1 }) : new Response('gone', { status: 404 }), }) expect(await (await context.fetch('https://api.example.com/ok')).json()).toEqual({ id: 1 }) await expect(context.fetch('https://api.example.com/missing')).rejects.toMatchObject({ name: 'HttpError', status: 404 }) }) test('a request inside a paginated page shares its attempt, permit, and retries', async () => { let calls = 0 const stream = defineStream({ id: 'app.paged', destination: events, async *read(context) { for await (const page of paginate({ context, fetchPage: async () => ({ items: await (await context.fetch('https://api.example.com/items')).json() as Array<{ id: number }>, next: undefined }), })) yield { rows: page.items } }, }) const journal = createMemoryJournal() const result = await runIngestion({ selected: selectStreams([definePipeline({ id: 'app', maxFetches: 1, streams: [stream] })], []), backfill: undefined }, { journal, destination: createMemoryDestination(), retry: { retries: 1, minTimeout: 0 }, fetch: async () => { calls += 1 return calls === 1 ? new Response('busy', { status: 503 }) : Response.json([{ id: 1 }]) }, }) expect(result.streams[0]).toMatchObject({ outcome: 'succeeded', rows: 1 }) expect(calls).toBe(2) expect(journal.events.filter((event) => event.eventKind === 'retry_scheduled')).toHaveLength(1) }) }) describe('pipeline concurrency and retries', () => { const run = (pipeline: ReturnType, env: Parameters[1]) => runIngestion({ selected: selectStreams([pipeline], []), backfill: undefined }, env) test.each(['fetches', 'loads'] as const)('%s release capacity during backoff and never exceed the limit', async (mode) => { const order: number[] = [] let active = 0 let peak = 0 const operation = async (id: number) => { order.push(id) active += 1 peak = Math.max(peak, active) await sleep(5) active -= 1 if (order.length === 1) throw connectionReset('temporary failure') return [{ id }] } const streams = [1, 2].map((id) => defineStream({ id: `app.stream${id}`, destination: events, async *read({ attempt }) { yield { rows: mode === 'fetches' ? await attempt(() => operation(id)) : [{ id }] } }, })) const destination: DestinationAdapter = { async insert({ rows }) { if (mode === 'loads') await operation(Number(rows[0]?.id)) }, } const result = await run(definePipeline({ id: 'app', streams, maxStreams: 2, maxFetches: 1, maxLoads: 1, }), { journal: createMemoryJournal(), destination, retry: { retries: 1, minTimeout: 10, randomize: false } }) expect(result.ok).toBe(true) expect(order).toEqual([1, 2, 1]) expect(peak).toBe(1) }) test('stream limits serialize readers and cancellation prevents queued readers from starting', async () => { for (const cancel of [false, true]) { const controller = new AbortController() const order: string[] = [] const streams = [1, 2].map((id) => defineStream({ id: `app.stream${id}`, destination: events, async *read() { order.push(`start:${id}`) if (cancel) controller.abort() await sleep(5) order.push(`end:${id}`) yield { rows: [] } }, })) const result = await run(definePipeline({ id: 'app', streams, maxStreams: 1 }), { journal: createMemoryJournal(), destination: createMemoryDestination(), signal: controller.signal, }) if (cancel) { expect(result.streams.map((stream) => stream.outcome)).toEqual(['cancelled', 'cancelled']) expect(order).not.toContain('start:2') } else { expect(result.ok).toBe(true) expect(order).toEqual(['start:1', 'end:1', 'start:2', 'end:2']) } } }) test('an exhausted request fails the stream after its own retries', async () => { let sourceCalls = 0 let readers = 0 const exhausted = defineStream({ id: 'app.exhausted', destination: events, async *read({ attempt }) { readers += 1 await attempt(async () => { sourceCalls += 1; throw connectionReset('source unavailable') }) }, }) const result = await run(definePipeline({ id: 'app', streams: [exhausted] }), { journal: createMemoryJournal(), destination: createMemoryDestination(), retry: { retries: 1, minTimeout: 0 }, }) expect(result.streams[0]).toMatchObject({ outcome: 'failed', error: 'source unavailable' }) expect(readers).toBe(1) expect(sourceCalls).toBe(2) }) test.each(['reader', 'plan', 'checkpoint'] as const)('an unrecognised %s failure fails the stream once instead of recreating the reader', async (source) => { const journal = createMemoryJournal() const failure = new TypeError(`invalid ${source}`) let failing = source !== 'checkpoint' let readers = 0 const stream = defineStream({ id: 'app.deterministic', destination: events, incremental: { id: 'test.deterministic', version: 1, parseState: (raw: unknown) => { if (failing && source === 'checkpoint') throw failure; return raw }, plan: () => { if (failing && source === 'plan') throw failure; return undefined }, }, async *read() { readers += 1 if (failing && source === 'reader') throw failure yield { rows: [{ id: readers }], state: 'committed' } }, }) const pipeline = definePipeline({ id: 'app', streams: [stream] }) if (source === 'checkpoint') { expect((await run(pipeline, { journal, destination: createMemoryDestination() })).ok).toBe(true) failing = true readers = 0 } const result = await run(pipeline, { journal, destination: createMemoryDestination() }) expect(result.streams[0]).toMatchObject({ outcome: 'failed', error: `invalid ${source}` }) expect(readers).toBe(source === 'reader' ? 1 : 0) expect(journal.events.filter((event) => event.eventKind === 'retry_scheduled')).toHaveLength(0) }) test('a failed request is not replayed by the reader boundary, even when the reader wraps it', async () => { let readers = 0 let calls = 0 const stream = defineStream({ id: 'app.wrapped', destination: events, async *read({ attempt }) { readers += 1 const rows = await attempt(async () => { calls += 1; throw connectionReset('source unavailable') }) .catch((error: unknown) => { throw new Error('provider request failed', { cause: error }) }) yield { rows } }, }) const result = await run(definePipeline({ id: 'app', streams: [stream] }), { journal: createMemoryJournal(), destination: createMemoryDestination(), retry: { retries: 1, minTimeout: 0 }, }) expect(result.streams[0]).toMatchObject({ outcome: 'failed', error: 'provider request failed' }) expect(readers).toBe(1) expect(calls).toBe(2) }) test('an exhausted load fails the stream without recreating the reader', async () => { const journal = createMemoryJournal() let readers = 0 let inserts = 0 const stream = defineStream({ id: 'app.sink_down', destination: events, async *read() { readers += 1; yield { rows: [{ id: 1 }] } }, }) const result = await run(definePipeline({ id: 'app', streams: [stream] }), { journal, destination: { async insert() { inserts += 1; throw connectionReset('clickhouse unavailable') } }, }) expect(result.streams[0]).toMatchObject({ outcome: 'failed', error: 'clickhouse unavailable' }) expect(readers).toBe(1) expect(inserts).toBe(3) expect(journal.events.filter((event) => event.eventKind === 'retry_scheduled')).toHaveLength(0) }) }) describe('rawTable', () => { test('lands provider objects untouched next to a stable id', async () => { const destination = createMemoryDestination() const landing = rawTable({ database: 'app_raw', name: 'tickets' }) const ticket = { key: 'T-1', requester: { email: 'a@example.com' }, tags: [{ name: 'vip' }] } const stream = defineStream({ id: 'app.tickets', destination: landing, async *read() { yield { rows: rawRows([ticket], (item) => item.key) } }, }) await runIngestion({ selected: selectStreams([definePipeline({ id: 'app', streams: [stream] })], []), backfill: undefined }, { journal: createMemoryJournal(), destination }) expect(landing.columns.map((column) => `${column.name}:${column.type}`).slice(0, 2)).toEqual(['id:String', 'raw:JSON']) expect(destination.tables.get('app_raw.tickets')?.[0]).toMatchObject({ id: 'T-1', raw: ticket }) }) }) describe('selectStreams', () => { test('repeated tags use exact AND semantics and an explicit empty selection fails', () => { const hourly = defineStream({ id: 'crm.people', destination: events, tags: ['schedule:1h'], async *read() {} }) const daily = defineStream({ id: 'crm.deals', destination: events, tags: ['schedule:1d'], async *read() {} }) const pipeline = definePipeline({ id: 'crm', tags: ['crm'], streams: [hourly, daily] }) expect(selectStreams([pipeline], []).map((entry) => entry.stream.id)).toEqual(['crm.people', 'crm.deals']) expect(selectStreams([pipeline], ['crm', 'schedule:1h']).map((entry) => entry.stream.id)).toEqual(['crm.people']) expect(selectStreams([pipeline], ['stream:crm.deals']).map((entry) => entry.stream.id)).toEqual(['crm.deals']) expect(() => selectStreams([pipeline], ['schedule'])).toThrow('No stream matches every requested tag') }) test('stream ids are globally unique across pipelines', () => { const stream = defineStream({ id: 'crm.people', destination: events, async *read() {} }) const a = definePipeline({ id: 'a', streams: [stream] }) const b = definePipeline({ id: 'b', streams: [stream] }) expect(() => selectStreams([a, b], [])).toThrow('globally unique') }) }) describe('paginate', () => { test('rejects a repeated continuation instead of looping forever', async () => { const context = createSourceContext({ fetch: async () => Response.json([]) }) const iterate = async () => { for await (const _ of paginate({ context, fetchPage: async () => ({ items: [1], next: 'same' }) })) { // drain } } await expect(iterate()).rejects.toThrow('repeated continuation') }) test('a cyclic provider cursor fails permanently without replaying the reader under its retry policy', async () => { const cursors: Array = [] const stream = defineStream({ id: 'app.cyclic', destination: events, async *read(context) { for await (const page of paginate({ context, fetchPage: async (cursor: string | undefined) => { cursors.push(cursor) return { items: [], next: 'same' } }, })) yield { rows: page.items } }, }) const journal = createMemoryJournal() const result = await runIngestion({ selected: selectStreams([definePipeline({ id: 'app', streams: [stream] })], []), backfill: undefined }, { journal, destination: createMemoryDestination(), }) expect(result.ok).toBe(false) expect(result.streams[0]?.error).toContain('repeated continuation') expect(cursors).toEqual([undefined, 'same']) expect(journal.events.filter((event) => event.eventKind === 'retry_scheduled')).toHaveLength(0) expect((await journal.readCheckpoint('app.cyclic')).lastSuccessSeq).toBe(0) }) })