import { afterAll, beforeAll, describe, expect, test } from 'bun:test' import { table, toCreateSQL } from '@chkit/core' import type { ClickHouseExecutor } from '@chkit/clickhouse' import { createPrefix, createStatelessLiveExecutor, getLiveEnv, quoteIdent, waitForTable } from '@chkit/clickhouse/e2e-testkit' import { createClickHouseDestination, ingestionColumns, rawRows, rawTable } from './destination.js' import { runIngestion } from './executor.js' import { cursorState } from './incremental.js' import { createClickHouseJournal } from './journal.js' import { definePipeline, defineStream, selectStreams } from './registry.js' import type { DestinationAdapter } from './types.js' describe('@chkit/plugin-sync live env e2e', () => { const liveEnv = getLiveEnv() const prefix = createPrefix('ingest') const database = liveEnv.clickhouseDatabase const journalTable = `${prefix}journal` const destinationTable = table({ database, name: `${prefix}items`, columns: [{ name: 'id', type: 'UInt64' }, { name: 'label', type: 'String' }, ...ingestionColumns], engine: 'MergeTree()', primaryKey: ['id'], orderBy: ['id'], settings: { non_replicated_deduplication_window: '100' }, }) const landing = { ...rawTable({ database, name: `${prefix}raw` }), settings: { non_replicated_deduplication_window: '100' }, } const integers = table({ database, name: `${prefix}integers`, columns: [ { name: 'id', type: 'UInt64' }, { name: 'signed', type: 'Int64' }, { name: 'values', type: 'Array(UInt64)' }, ...ingestionColumns, ], engine: 'MergeTree()', orderBy: ['id'], }) const ephemeral = table({ database, name: `${prefix}ephemeral`, columns: [ { name: 'id', type: 'UInt64' }, { name: 'raw', type: 'String', defaultKind: 'EPHEMERAL' }, { name: 'raw length', type: 'UInt64', default: 'fn:length(raw)' }, { name: 'shout', type: 'String', defaultKind: 'MATERIALIZED', default: 'fn:upper(raw)' }, { name: 'items', type: 'Nested(sku String, qty UInt32)' }, ...ingestionColumns, ], engine: 'MergeTree()', orderBy: ['id'], }) let executor: ClickHouseExecutor beforeAll(async () => { // Ingestion fetches, loads and journals concurrently, so it needs a stateless executor. executor = createStatelessLiveExecutor(liveEnv) await executor.command(toCreateSQL(destinationTable)) await waitForTable(executor, database, destinationTable.name) await executor.command(toCreateSQL(landing)) await waitForTable(executor, database, landing.name) await executor.command(toCreateSQL(integers)) await waitForTable(executor, database, integers.name) await executor.command(toCreateSQL(ephemeral)) await waitForTable(executor, database, ephemeral.name) // Create the journal through the product path during setup, like every // other table here, instead of racing its propagation inside the first run. await createClickHouseJournal({ executor, database, targetId: `e2e/${prefix}`, table: journalTable }).ensure() }, 60_000) afterAll(async () => { await executor.command(`DROP TABLE IF EXISTS ${quoteIdent(database)}.${quoteIdent(destinationTable.name)}`) await executor.command(`DROP TABLE IF EXISTS ${quoteIdent(database)}.${quoteIdent(landing.name)}`) await executor.command(`DROP TABLE IF EXISTS ${quoteIdent(database)}.${quoteIdent(integers.name)}`) await executor.command(`DROP TABLE IF EXISTS ${quoteIdent(database)}.${quoteIdent(ephemeral.name)}`) await executor.command(`DROP TABLE IF EXISTS ${quoteIdent(database)}.${quoteIdent(journalTable)}`) await executor.close() }, 60_000) test('invalid checkpoint identities fail only when their streams run and never reach the reader', async () => { let invalidReads = 0 const invalid = [ { id: '', version: 1 }, { id: 1n as unknown as string, version: 1 }, { id: 'e2e.cursor', version: 0 }, { id: 'e2e.cursor', version: 1.5 }, { id: 'e2e.cursor', version: Number.MAX_SAFE_INTEGER + 1 }, ].map((identity, index) => defineStream({ id: `${prefix}invalid_${index}`, destination: destinationTable, incremental: cursorState({ ...identity, parse: Number }), async *read() { invalidReads += 1; yield { rows: [], state: 1 } }, })) const valid = defineStream({ id: `${prefix}valid_identity`, destination: destinationTable, incremental: cursorState({ id: 'e2e.cursor', version: 1, parse: Number }), async *read({ selection }) { yield { rows: [], state: (selection ?? 0) + 1 } }, }) const pipeline = definePipeline({ id: `${prefix}identity`, streams: [...invalid, valid] }) const journal = () => createClickHouseJournal({ executor, database, targetId: `e2e/${prefix}`, table: journalTable }) const destination = createClickHouseDestination(executor) const selected = selectStreams([pipeline], [`stream:${valid.id}`]) expect((await runIngestion({ selected, backfill: undefined }, { journal: journal(), destination })).ok).toBe(true) const result = await runIngestion({ selected: selectStreams([pipeline], []), backfill: undefined }, { journal: journal(), destination }) expect(result.ok).toBe(false) for (const stream of invalid) { expect(result.streams.find((entry) => entry.streamId === stream.id)).toMatchObject({ outcome: 'failed', error: expect.stringContaining('incremental strategy must have a non-empty id and a safe integer version of at least 1') }) const checkpoint = await journal().readCheckpoint(stream.id) expect(checkpoint.version).toBe(0) expect(checkpoint.envelope).toBeUndefined() } expect(invalidReads).toBe(0) expect(result.streams.find((entry) => entry.streamId === valid.id)?.outcome).toBe('succeeded') expect((await journal().readCheckpoint(valid.id)).envelope?.state).toBe(2) }, 120_000) test('a lost acknowledgement replays from the journaled checkpoint without skipping or duplicating rows', async () => { const source = Array.from({ length: 3 }, (_, page) => [0, 1].map((offset) => ({ id: page * 2 + offset, label: `row-${page * 2 + offset}` }))) const stream = defineStream({ id: `${prefix}items`, destination: destinationTable, batchSize: 2, incremental: cursorState({ id: 'e2e.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: `${prefix}pipeline`, streams: [stream] }) const journal = () => createClickHouseJournal({ executor, database, targetId: `e2e/${prefix}`, table: journalTable }) const destination = createClickHouseDestination(executor) let acknowledgementLost = false const lossy: DestinationAdapter = { insert: async (input) => { // Target the second batch, not the second call: the live destination // can itself need retries before the first batch is acknowledged. if (input.rows[0]?.id === 2) { if (acknowledgementLost) throw new Error('target unavailable') await destination.insert(input) acknowledgementLost = true throw new Error('acknowledgement lost') } await destination.insert(input) }, } const first = await runIngestion({ selected: selectStreams([pipeline], []), backfill: undefined }, { journal: journal(), destination: lossy }) expect(first.ok).toBe(false) expect(first.streams[0]).toMatchObject({ outcome: 'failed', rows: 2, batches: 1, error: 'target unavailable' }) expect((await journal().readCheckpoint(stream.id)).envelope?.state).toBe(1) // A fresh executor process reconstructs everything from the journal. const second = await runIngestion({ selected: selectStreams([pipeline], []), backfill: undefined }, { journal: journal(), destination }) expect(second.streams[0]).toMatchObject({ outcome: 'succeeded', error: undefined }) expect(second.ok).toBe(true) const checkpoint = await journal().readCheckpoint(stream.id) expect(checkpoint.envelope).toEqual({ strategy: 'e2e.page', version: 1, state: 3 }) expect(checkpoint.version).toBe(3) const rows = await executor.query<{ id: string; run_ids: string }>( `SELECT id, uniqExact(_chkit_run_id) AS run_ids FROM ${quoteIdent(database)}.${quoteIdent(destinationTable.name)} GROUP BY id ORDER BY id`, { select_sequential_consistency: '1' } ) expect(rows.map((row) => Number(row.id))).toEqual([0, 1, 2, 3, 4, 5]) const physical = await executor.query<{ rows: string }>( `SELECT count() AS rows FROM ${quoteIdent(database)}.${quoteIdent(destinationTable.name)}`, { select_sequential_consistency: '1' } ) expect(Number(physical[0]?.rows)).toBe(6) }, 120_000) test('successful full syncs land A → B → A instead of suppressing the last update', async () => { let value = 'A' const stream = defineStream({ id: `${prefix}raw`, destination: landing, async *read() { yield { rows: rawRows([{ id: '1', value }], (item) => item.id) } }, }) const selected = selectStreams([definePipeline({ id: `${prefix}raw_pipeline`, streams: [stream] })], []) let lastSuccessId = '' for (const next of ['A', 'B', 'A']) { value = next const journal = createClickHouseJournal({ executor, database, targetId: `e2e/${prefix}`, table: journalTable }) const result = await runIngestion({ selected, backfill: undefined }, { journal, destination: createClickHouseDestination(executor), }) expect(result.streams[0]).toMatchObject({ outcome: 'succeeded', error: undefined }) expect(result.ok).toBe(true) const checkpoint = await journal.readCheckpoint(stream.id) expect(checkpoint.successId).not.toBe(lastSuccessId) expect(checkpoint.successId).not.toBe('') lastSuccessId = checkpoint.successId const rows = await executor.query<{ raw: { value: string } }>( `SELECT raw FROM ${quoteIdent(database)}.${quoteIdent(landing.name)} FINAL`, { select_sequential_consistency: '1' } ) expect(rows.map((row) => row.raw.value)).toEqual([next]) } }, 120_000) test('BigInt rows round-trip through content hashing and JSONEachRow without losing precision', async () => { const row = { id: 18446744073709551615n, signed: -9223372036854775808n, values: [9007199254740993n, 18446744073709551615n] } const stream = defineStream({ id: `${prefix}integers`, destination: integers, async *read() { yield { rows: [row] } }, }) const result = await runIngestion({ selected: selectStreams([definePipeline({ id: `${prefix}integers_pipeline`, streams: [stream] })], []), backfill: undefined, }, { journal: createClickHouseJournal({ executor, database, targetId: `e2e/${prefix}`, table: journalTable }), destination: createClickHouseDestination(executor), }) expect(result.streams[0]).toMatchObject({ outcome: 'succeeded', rows: 1, error: undefined }) const rows = await executor.query<{ id: string; signed: string; values: string[] }>( `SELECT id, signed, values FROM ${quoteIdent(database)}.${quoteIdent(integers.name)}`, { select_sequential_consistency: '1', output_format_json_quote_64bit_integers: '1' } ) expect(rows).toEqual([{ id: row.id.toString(), signed: row.signed.toString(), values: row.values.map(String) }]) expect(typeof row.id).toBe('bigint') }, 120_000) test('EPHEMERAL inputs and flattened Nested fields reach the expressions of the destination', async () => { const stream = defineStream({ id: `${prefix}ephemeral`, destination: ephemeral, async *read() { yield { rows: [{ id: 1, raw: 'abcd', 'items.sku': ['a'], 'items.qty': [2] }, { id: 2, raw: 'hello', 'raw length': 9 }] } }, }) const result = await runIngestion({ selected: selectStreams([definePipeline({ id: `${prefix}ephemeral_pipeline`, streams: [stream] })], []), backfill: undefined, }, { journal: createClickHouseJournal({ executor, database, targetId: `e2e/${prefix}`, table: journalTable }), destination: createClickHouseDestination(executor), }) expect(result.streams[0]).toMatchObject({ outcome: 'succeeded', rows: 2, error: undefined }) const rows = await executor.query<{ id: string; raw_length: string; shout: string; skus: string[] }>( `SELECT id, \`raw length\` AS raw_length, shout, items.sku AS skus FROM ${quoteIdent(database)}.${quoteIdent(ephemeral.name)} ORDER BY id`, { select_sequential_consistency: '1', output_format_json_quote_64bit_integers: '1' } ) expect(rows).toEqual([ { id: '1', raw_length: '4', shout: 'ABCD', skus: ['a'] }, { id: '2', raw_length: '9', shout: 'HELLO', skus: [] }, ]) }, 120_000) })