import process from 'node:process' import { createStatelessClickHouseExecutor, type ClickHouseExecutor } from '@chkit/clickhouse' import { createPluginRunner, defineFlags, withFactoryDefaults, type ChxInlinePluginRegistration, type ResolvedChxConfig, } from '@chkit/core' import { loadDefinitionModules } from '@chkit/core/schema-loader' import { z } from 'zod' import { BATCH_ID_COLUMN, createClickHouseDestination, INGESTED_AT_COLUMN, RUN_ID_COLUMN } from './destination.js' import { MAX_DURATION_MS, runIngestion, type BackfillRequest } from './executor.js' import { createClickHouseJournal, DEFAULT_JOURNAL_TABLE, emptyCheckpoint, isMissingJournalError } from './journal.js' import { assertRunnable, collectPipelines, selectStreams, type SelectedStream } from './registry.js' import { doctorJournal, repairJournal } from './recovery.js' import type { PipelineDefinition, StreamResult } from './types.js' const REQUIRED_COLUMNS = [BATCH_ID_COLUMN, RUN_ID_COLUMN, INGESTED_AT_COLUMN] /** The budget arms a timer, whose delay cannot exceed a signed 32-bit millisecond count. */ const MAX_DURATION_SECONDS = Math.floor(MAX_DURATION_MS / 1000) const IngestOptionsSchema = z.object({ journalTable: z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/, 'must be a table name of letters, digits and underscores').default(DEFAULT_JOURNAL_TABLE), /** Host-default execution budget in seconds. */ maxDurationSeconds: z.number().positive().max(MAX_DURATION_SECONDS).default(3600), prefetchBatches: z.number().int().positive().default(1), }) type IngestOptions = z.infer export type IngestPluginOptions = Partial const SELECTION_FLAGS = defineFlags([ { name: '--tag', type: 'string[]', description: 'Exact tag every selected stream must carry (repeatable, AND)', placeholder: '' }, ] as const) const RUN_FLAGS = defineFlags([ ...SELECTION_FLAGS, { name: '--backfill', type: 'string', description: 'Stable backfill id; uses an isolated checkpoint namespace', placeholder: '' }, { name: '--from', type: 'string', description: 'Backfill range lower bound (ISO timestamp)', placeholder: '' }, { name: '--to', type: 'string', description: 'Backfill range upper bound (ISO timestamp)', placeholder: '' }, { name: '--max-duration', type: 'string', description: 'Execution budget in seconds', placeholder: '' }, ] as const) const RECOVERY_FLAGS = defineFlags([ ...SELECTION_FLAGS, { name: '--backfill', type: 'string', description: 'Inspect an isolated backfill checkpoint namespace', placeholder: '' }, ] as const) const REPAIR_FLAGS = defineFlags([ ...RECOVERY_FLAGS, { name: '--apply', type: 'string', description: 'Materialize the reviewed fingerprint with writers stopped (select one stream)', placeholder: '' }, ] as const) interface IngestPluginCommandContext { args: string[] flags: Record jsonMode: boolean options: IngestOptions config: ResolvedChxConfig configPath: string print: (value: unknown) => void pluginContext?: { executor: ClickHouseExecutor; hasExecutor: boolean } } class IngestConfigError extends Error { constructor(message: string, options?: ErrorOptions) { super(message, options) this.name = 'IngestConfigError' } } const runCommand = createPluginRunner({ configErrorClass: IngestConfigError }) export function createIngestPlugin(options: IngestPluginOptions = {}) { const optionsSchema = withFactoryDefaults(IngestOptionsSchema, options) return { manifest: { name: 'ingest' as const, apiVersion: 1 as const }, optionsSchema, commands: [ { name: 'run', description: 'Execute the selected ingestion streams from their journaled checkpoints', takesArgs: false, flags: RUN_FLAGS, optionsSchema, run: runCommand({ command: 'run', label: 'Ingest run', fn: async (context) => { const selected = await loadSelection(context) const backfill = parseBackfill(context.flags) const maxDurationSeconds = parseMaxDuration(context.flags['--max-duration']) ?? context.options.maxDurationSeconds const target = openTarget(context) const abort = new AbortController() const onSignal = () => abort.abort(new DOMException('Interrupted', 'AbortError')) process.once('SIGINT', onSignal) process.once('SIGTERM', onSignal) try { const result = await runIngestion( { selected, backfill }, { journal: createClickHouseJournal({ executor: target.executor, database: target.database, targetId: target.targetId, table: context.options.journalTable, cluster: target.cluster, }), destination: createClickHouseDestination(target.executor), signal: abort.signal, maxDurationMs: maxDurationSeconds * 1000, prefetchBatches: context.options.prefetchBatches, log: context.jsonMode ? undefined : (message) => context.print(message), } ) if (context.jsonMode) { context.print({ command: 'run', ...result }) } else { const rows = result.streams.reduce((sum, stream) => sum + stream.rows, 0) context.print(`Ingest run ${result.runId}: ${result.ok ? 'ok' : 'incomplete'} (${result.streams.length} streams, ${rows} rows)`) for (const line of formatStreamErrors(result.streams)) context.print(line) } return result.ok ? 0 : 1 } finally { process.off('SIGINT', onSignal) process.off('SIGTERM', onSignal) await target.close() } }, }), }, { name: 'list', description: 'List the ingestion streams in the loaded definition graph', takesArgs: false, flags: SELECTION_FLAGS, optionsSchema, run: runCommand({ command: 'list', label: 'Ingest list', fn: async (context) => { const selected = await loadSelection(context) const streams = selected.map(describeStream) if (context.jsonMode) { context.print({ ok: true, command: 'list', streams }) } else { for (const stream of streams) { context.print(`${stream.streamId} -> ${stream.destination} [${stream.tags.join(', ')}]`) } } return 0 }, }), }, { name: 'doctor', description: 'Validate journal evidence and diagnose uncertain run histories', takesArgs: false, flags: RECOVERY_FLAGS, optionsSchema, run: runCommand({ command: 'doctor', label: 'Ingest doctor', fn: async (context) => { const selected = await loadSelection(context) const backfill = parseBackfill(context.flags) const target = openTarget(context) try { const streams = await Promise.all(selected.map(async (entry) => { const namespaceId = backfill ? `${entry.stream.id}#backfill:${backfill.id}` : entry.stream.id const report = await doctorJournal(namespaceId, { executor: target.executor, database: target.database, targetId: target.targetId, table: context.options.journalTable, }) return { ...describeStream(entry), report } })) const ok = streams.every((stream) => stream.report.healthy) if (context.jsonMode) { context.print({ ok, command: 'doctor', targetId: target.targetId, streams }) } else { for (const { report } of streams) { context.print(`${report.namespaceId}: ${report.healthy ? 'healthy' : report.problems.join('; ')} (${report.runs} runs, selected checkpoint v${report.checkpoint.version}, ${report.selectedEvidenceRows} stream evidence rows)`) } } return ok ? 0 : 1 } finally { await target.close() } }, }), }, { name: 'repair', description: 'Review recovery; --apply materializes a verified journal for explicit configuration activation', takesArgs: false, flags: REPAIR_FLAGS, optionsSchema, run: runCommand({ command: 'repair', label: 'Ingest repair', fn: async (context) => { const selected = await loadSelection(context) const backfill = parseBackfill(context.flags) const apply = context.flags['--apply'] if (typeof apply === 'string' && selected.length !== 1) { throw new IngestConfigError('--apply requires exactly one selected stream; use --tag to narrow the selection.') } const target = openTarget(context) try { const streams = [] for (const entry of selected) { const namespaceId = backfill ? `${entry.stream.id}#backfill:${backfill.id}` : entry.stream.id const result = await repairJournal(namespaceId, typeof apply === 'string' ? apply : undefined, { executor: target.executor, database: target.database, targetId: target.targetId, table: context.options.journalTable, }) streams.push({ ...describeStream(entry), ...result }) } if (context.jsonMode) { context.print({ ok: true, command: 'repair', targetId: target.targetId, streams }) } else { for (const { applied, plan } of streams) { if (plan.healthy) { context.print(`${plan.namespaceId}: healthy; ${plan.runs} runs, selected checkpoint v${plan.checkpoint.version}.`) continue } context.print(`${plan.namespaceId}: ${applied ? 'repair materialized; configuration activation required' : 'repair plan'}; retain ${plan.retainedFacts} facts, selected checkpoint v${plan.checkpoint.version}.`) for (const problem of plan.problems) context.print(problem) context.print(`Evidence: ${plan.evidenceRows} rows ${applied ? 'preserved in' : 'will be archived to'} ${applied ? plan.archiveTable : `${plan.archiveTable}_`}; original table retained.`) context.print(plan.replayWarning) context.print(plan.activation) if (!applied && !plan.healthy && plan.repairable) context.print(`Review this plan, then run ingest repair --tag stream:${plan.namespaceId.split('#backfill:')[0]}${backfill ? ` --backfill ${backfill.id}` : ''} --apply ${plan.fingerprint}`) } } return 0 } finally { await target.close() } }, }), }, { name: 'status', description: 'Show the committed checkpoint of each selected stream', takesArgs: false, flags: SELECTION_FLAGS, optionsSchema, run: runCommand({ command: 'status', label: 'Ingest status', fn: async (context) => { const selected = await loadSelection(context) const target = openTarget(context) try { const journal = createClickHouseJournal({ executor: target.executor, database: target.database, targetId: target.targetId, table: context.options.journalTable, }) // Read-only: a missing journal means nothing has run yet (#414). const streams = await Promise.all( selected.map(async (entry) => { const checkpoint = await journal.readCheckpoint(entry.stream.id).catch((error: unknown) => { if (isMissingJournalError(error)) return emptyCheckpoint() throw error }) return { ...describeStream(entry), checkpointVersion: checkpoint.version, checkpoint: checkpoint.envelope ?? null } }) ) if (context.jsonMode) { context.print({ ok: true, command: 'status', targetId: target.targetId, streams }) } else { for (const stream of streams) { context.print(`${stream.streamId}: v${stream.checkpointVersion} ${stream.checkpoint ? JSON.stringify(stream.checkpoint.state) : '(no checkpoint)'}`) } } return 0 } finally { await target.close() } }, }), }, ], hooks: { async onCheck(context: { config: ResolvedChxConfig }) { const findings = checkGraph(await loadGraph(context.config)) return { plugin: 'ingest', evaluated: true, ok: findings.every((finding) => finding.severity !== 'error'), findings, } }, }, } } export type IngestPlugin = ReturnType export function ingest(options: IngestPluginOptions = {}): ChxInlinePluginRegistration { return { plugin: createIngestPlugin(options), name: 'ingest', enabled: true, options } } export function formatStreamErrors(streams: readonly StreamResult[]): string[] { const groups = new Map() for (const { outcome, error, namespaceId } of streams) { if (error === undefined) continue const key = JSON.stringify([outcome, error]) const group = groups.get(key) ?? { outcome, error, namespaces: [] } group.namespaces.push(namespaceId) groups.set(key, group) } return [...groups.values()].flatMap(({ outcome, error, namespaces }) => namespaces.length === 1 ? [`${namespaces.join('')} ${outcome}: ${error}`] : [`${namespaces.length} streams ${outcome}: ${error}`, ` ${namespaces.join(', ')}`]) } /** Local, zero-network graph checks: they hold in `--offline` mode too. */ export function checkGraph(pipelines: readonly PipelineDefinition[]) { const findings: Array<{ code: string; message: string; severity: 'info' | 'warn' | 'error' }> = [] if (pipelines.length === 0) { findings.push({ code: 'ingest_no_pipelines', message: 'No ingestion pipeline is exported by the project entry.', severity: 'warn' }) } for (const pipeline of pipelines) { try { assertRunnable(pipeline) } catch (error) { findings.push({ code: 'ingest_invalid_pipeline', message: error instanceof Error ? error.message : String(error), severity: 'error' }) continue } for (const stream of pipeline.streams) { const columns = new Set(stream.destination.columns.map((column) => column.name)) const missing = REQUIRED_COLUMNS.filter((name) => !columns.has(name)) if (missing.length > 0) { findings.push({ code: 'ingest_missing_metadata_columns', message: `Stream "${stream.id}" destination ${stream.destination.database}.${stream.destination.name} is missing ${missing.join(', ')}. Spread ingestionColumns into its columns.`, severity: 'error', }) } } } return findings } // Discover values exported from the configured entry (or legacy schema files). async function loadGraph(config: ResolvedChxConfig): Promise { if (config.schema.length === 0) return [] return collectPipelines(await loadDefinitionModules(config.schema, { cwd: process.cwd() })) } async function loadSelection(context: IngestPluginCommandContext): Promise { try { const pipelines = await loadGraph(context.config) if (pipelines.length === 0) { throw new IngestConfigError('No ingestion pipeline is exported. Export a definePipeline(...) value from the module configured as "entry".') } const tags = context.flags['--tag'] return selectStreams(pipelines, Array.isArray(tags) ? tags : typeof tags === 'string' ? [tags] : []) } catch (error) { throw error instanceof IngestConfigError ? error : new IngestConfigError(error instanceof Error ? error.message : String(error), { cause: error }) } } function openTarget(context: IngestPluginCommandContext) { const clickhouse = context.config.clickhouse // Ingestion requires JSONEachRow and per-insert deduplication settings. // The host executor contract does not guarantee either capability. // Streams fetch, load and journal concurrently, so the executor must not be // bound to one ClickHouse HTTP session (a session allows one in-flight query). if (clickhouse) { const executor = createStatelessClickHouseExecutor(clickhouse) return { executor, database: clickhouse.database, cluster: clickhouse.cluster, targetId: targetIdOf(clickhouse.url, clickhouse.database), close: () => executor.close() } } throw new IngestConfigError('Ingestion requires a direct ClickHouse connection for JSON rows and deduplication settings. Configure clickhouse in your clickhouse.config.ts; a host-provided executor is not supported.') } function targetIdOf(url: string, database: string): string { try { return `${new URL(url).host}/${database}` } catch { return `${url}/${database}` } } function parseBackfill(flags: IngestPluginCommandContext['flags']): BackfillRequest | undefined { const id = flags['--backfill'] const from = parseTimestamp(flags['--from'], '--from') const to = parseTimestamp(flags['--to'], '--to') if (typeof id !== 'string') { if (from || to) throw new IngestConfigError('--from and --to require --backfill : explicit ranges never touch the scheduled checkpoint.') return undefined } if (!/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(id)) throw new IngestConfigError(`Invalid --backfill id "${id}".`) return { id, from, to } } function parseTimestamp(raw: string | string[] | boolean | undefined, flag: string): Date | undefined { if (typeof raw !== 'string') return undefined const date = new Date(raw) if (Number.isNaN(date.getTime())) throw new IngestConfigError(`Invalid timestamp for ${flag}: ${raw}`) return date } function parseMaxDuration(raw: string | string[] | boolean | undefined): number | undefined { if (typeof raw !== 'string') return undefined const seconds = Number(raw) if (!Number.isFinite(seconds) || seconds <= 0 || seconds > MAX_DURATION_SECONDS) { throw new IngestConfigError(`Invalid value for --max-duration: ${raw}. Use a number of seconds between 0 and ${MAX_DURATION_SECONDS}.`) } return seconds } function describeStream(entry: SelectedStream) { return { streamId: entry.stream.id, pipelineId: entry.pipeline.id, destination: `${entry.stream.destination.database}.${entry.stream.destination.name}`, strategy: `${entry.stream.incremental.id}@${entry.stream.incremental.version}`, tags: [...entry.effectiveTags], } }