import { describe, expect, test } from 'bun:test' import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { canonicalizeDefinitions, planDiff, table, textIndexFingerprint, toCreateSQL, type TableDefinition, type TextSkipIndex, } from '@chkit/core' import { canonicalizeSqlFragments } from '@chkit/clickhouse' import { renderSchemaFile } from '../../../plugin-pull/src/render-schema.js' import expressionPairs from '../../../../test/fixtures/text-index-expressions.json' import fixtures from '../../../../test/fixtures/text-index.json' import { collectTableSqlFragments, compareTableShape, type SqlCanonicalizer, } from '../commands/drift/compare.js' import { CORE_ENTRY, createJournalTableName, createLiveExecutor, createPrefix, formatTestDiagnostic, getLiveEnv, pollUntil, runCli, runCliWithRetry, waitForTable, } from './e2e-testkit.js' const env = getLiveEnv() const docs = (name: string, index: TextSkipIndex): TableDefinition => table({ database: env.clickhouseDatabase, name, engine: 'MergeTree()', columns: [ { name: 'id', type: 'UInt64' }, { name: 'body', type: 'String' }, ], primaryKey: ['id'], orderBy: ['id'], indexes: [index], }) const ROWS = `(1, 'alpha beta gamma'), (2, 'alpha beta gamma'), (3, 'alpha'), (4, 'é東京😀'), (5, 'a,b=c')` const ROW_COUNT = 5 async function loadPulled(definition: TableDefinition, dir: string): Promise { const path = join(dir, `${definition.name}.ts`) await writeFile( path, renderSchemaFile([definition]).replace("'@chkit/core'", JSON.stringify(CORE_ENTRY)), ) return (await import(path)).default[0] } describe('text index live round trips', () => { for (const { name: label, ...params } of fixtures) { test(label, async () => { const executor = createLiveExecutor(env) const name = `${createPrefix('text')}docs` const index: TextSkipIndex = { name: 'idx', expression: 'body', type: 'text', granularity: 1, ...params, } const definition = docs(name, index) const fullName = `${definition.database}.${name}` const cloneName = `${name}_clone` const dir = await mkdtemp(join(tmpdir(), 'chkit-text-pull-')) try { // Start from SQL exactly as a user wrote it, independently of our renderer. await executor.command( `CREATE TABLE ${fullName} (id UInt64, body String, INDEX idx (${index.expression}) TYPE text(tokenizer = ${index.tokenizer}${index.preprocessor ? `, preprocessor = ${index.preprocessor}` : ''}) GRANULARITY 1) ENGINE=MergeTree ORDER BY id`, ) await waitForTable(executor, definition.database, name) await executor.command(`INSERT INTO ${fullName} VALUES ${ROWS}`) const actual = await pollUntil( async () => (await executor.listTableDetails([definition.database])).find( (item) => item.name === name, ), (item) => item !== undefined, ) if (!actual) throw new Error('Missing test table') expect(compareTableShape(definition, actual)).toBeNull() expect(actual.indexes[0]?.granularity).toBe(100000000) const pulled = await loadPulled({ ...definition, indexes: actual.indexes }, dir) expect(planDiff([definition], [pulled]).operations).toEqual([]) await executor.command(toCreateSQL({ ...pulled, name: cloneName })) await waitForTable(executor, definition.database, cloneName) // Insert the rows directly rather than INSERT ... SELECT from the // original: on a multi-replica service the copy can run on a replica // that hasn't seen the original's rows yet and copy nothing. const cloneFullName = `${definition.database}.${cloneName}` await executor.command(`INSERT INTO ${cloneFullName} VALUES ${ROWS}`) // Read both tables in one query so both come from the same replica, and // re-read until that replica sees every row of both. const search = (target: string) => `(SELECT groupArray(id) FROM (SELECT id FROM ${target} WHERE hasAllTokens(${index.expression}, ['alpha']) ORDER BY id))` const observed = await pollUntil( async () => ( await executor.query<{ counts: string[]; original: string[]; clone: string[] }>( `SELECT [(SELECT count() FROM ${fullName}), (SELECT count() FROM ${cloneFullName})] AS counts, ${search(fullName)} AS original, ${search(cloneFullName)} AS clone`, ) )[0], // The text index can trail the rows it covers on a fresh replica, so // also wait for the clone's results to match; on timeout the last // observation is returned and a real mismatch fails below. (row) => (row?.counts.every((count) => Number(count) === ROW_COUNT) ?? false) && JSON.stringify(row?.clone) === JSON.stringify(row?.original), ) expect(observed?.counts.map(Number)).toEqual([ROW_COUNT, ROW_COUNT]) expect(observed?.clone).toEqual(observed?.original) if (label === 'two spaces') expect(observed?.original.map(Number)).toEqual([1, 3]) } finally { await executor.command(`DROP TABLE IF EXISTS ${fullName} SYNC`) await executor.command(`DROP TABLE IF EXISTS ${definition.database}.${cloneName} SYNC`) await executor.close() await rm(dir, { recursive: true, force: true }) } }, 60000) } test('generate, migrate, drift, change tokenizer, and migrate again', async () => { const executor = createLiveExecutor(env) const name = `${createPrefix('text_cli')}docs` const definition = docs(name, { name: 'idx', type: 'text', expression: 'body', tokenizer: "splitByString([' '])", granularity: 1, }) const dir = await mkdtemp(join(tmpdir(), 'chkit-text-cli-')) const schemaPath = join(dir, 'schema.ts') const configPath = join(dir, 'clickhouse.config.ts') const journal = createJournalTableName('text_index') const extraEnv = { CHKIT_JOURNAL_TABLE: journal } const command = (args: string[]) => { const result = runCli(dir, [...args, '--config', configPath, '--json'], extraEnv) if (result.exitCode !== 0) throw new Error(formatTestDiagnostic(args.join(' '), result)) return JSON.parse(result.stdout) } try { await writeFile( configPath, `export default ${JSON.stringify({ schema: schemaPath, outDir: join(dir, 'chkit'), migrationsDir: join(dir, 'chkit/migrations'), metaDir: join(dir, 'chkit/meta'), clickhouse: { url: env.clickhouseUrl, username: env.clickhouseUser, password: env.clickhousePassword, database: env.clickhouseDatabase } })}`, ) const writeSchema = async (value: TableDefinition) => writeFile( schemaPath, renderSchemaFile([value]).replace("'@chkit/core'", JSON.stringify(CORE_ENTRY)), ) const migrate = async () => { const result = await runCliWithRetry( dir, ['migrate', '--execute', '--config', configPath, '--json'], { extraEnv }, ) if (result.exitCode !== 0) throw new Error(formatTestDiagnostic('migrate', result)) } await writeSchema(definition) command(['generate']) await migrate() await waitForTable(executor, definition.database, name) expect(command(['drift', '--table', `${definition.database}.${name}`]).drifted).toBe(false) const changed = { ...definition, indexes: [ { ...definition.indexes?.[0], tokenizer: "splitByString([' '])", } as TextSkipIndex, ], } expect(planDiff([definition], [changed]).operations).toHaveLength(2) await writeSchema(changed) command(['generate']) await migrate() expect(command(['drift', '--table', `${definition.database}.${name}`]).drifted).toBe(false) const actual = (await executor.listTableDetails([definition.database])).find( (item) => item.name === name, ) if (!actual) throw new Error('Missing test table') expect(compareTableShape(definition, actual)?.reasonCodes).toContain('index_mismatch') expect(compareTableShape(changed, actual)).toBeNull() expect(canonicalizeDefinitions([changed])).not.toEqual(canonicalizeDefinitions([definition])) } finally { await executor.command(`DROP TABLE IF EXISTS ${definition.database}.${name} SYNC`) await executor.command(`DROP TABLE IF EXISTS ${definition.database}.${journal} SYNC`) await executor.close() await rm(dir, { recursive: true, force: true }) } }, 120000) }) test('text index tuning, newer options, and materializing existing rows', async () => { const executor = createLiveExecutor(env) const name = `${createPrefix('text_options')}docs` const [{ version }] = await executor.query<{ version: string }>('SELECT version() AS version') const [major, minor] = version.split('.').map(Number) const newerOptions = major > 26 || (major === 26 && minor >= 8) const index: TextSkipIndex = { name: 'idx', expression: 'body', type: 'text', tokenizer: 'splitByNonAlpha', dictionaryBlockSize: 512, dictionaryBlockFrontcodingCompression: false, postingListBlockSize: 1024, postingListCodec: 'bitpacking', ...(newerOptions ? { postprocessor: 'lower(body)', supportPhraseSearch: true } : {}), } const definition = { ...docs(name, index), ...(newerOptions ? { settings: { allow_experimental_text_index_phrase_search: 1 } } : {}), } const fullName = `${definition.database}.${name}` const dir = await mkdtemp(join(tmpdir(), 'chkit-text-options-')) try { await executor.command(toCreateSQL({ ...definition, indexes: [] })) await executor.command( `INSERT INTO ${fullName} VALUES (1, 'hello world'), (2, 'goodbye world')`, ) for (const op of planDiff([{ ...definition, indexes: [] }], [definition]).operations) await executor.command(op.sql) await executor.command( `ALTER TABLE ${fullName} MATERIALIZE INDEX idx SETTINGS mutations_sync = 2`, ) const actual = (await executor.listTableDetails([definition.database])).find( (item) => item.name === name, ) if (!actual) throw new Error('Missing test table') expect(compareTableShape(definition, actual)).toBeNull() const pulled = await loadPulled({ ...definition, indexes: actual.indexes }, dir) expect(planDiff([definition], [pulled]).operations).toEqual([]) const fn = newerOptions ? "hasPhrase(body, 'hello world')" : "hasAllTokens(body, ['hello'])" expect( (await executor.query<{ id: number }>(`SELECT id FROM ${fullName} WHERE ${fn}`)).map((row) => Number(row.id), ), ).toEqual([1]) } finally { await executor.command(`DROP TABLE IF EXISTS ${fullName} SYNC`) await executor.close() await rm(dir, { recursive: true, force: true }) } }, 60000) test('normalization preserves every printable ClickHouse string escape', async () => { const { normalizeTextIndexSQL } = await import('@chkit/core') const executor = createLiveExecutor(env) try { const escapeSql = (code: number) => `'\\${String.fromCharCode(code)}'` const checks: string[] = [] for (let code = 32; code < 127; code++) { const sql = escapeSql(code) if (code === 120) { expect(() => normalizeTextIndexSQL(sql)).toThrow('Invalid hexadecimal') continue } checks.push( `SELECT ${code} AS code, hex(${sql}) AS original, hex(${normalizeTextIndexSQL(sql)}) AS normalized`, ) } // One request instead of ~94 sequential round trips to a remote service. const rows = await executor.query<{ code: number; original: string; normalized: string }>( checks.join('\nUNION ALL\n'), ) expect(rows).toHaveLength(checks.length) for (const { code, original, normalized } of rows) { expect(normalized, `escape ${JSON.stringify(escapeSql(Number(code)))}`).toBe(original) } } finally { await executor.close() } }, 60000) test('quoted literal names remain distinct from constants in ClickHouse and planning', async () => { const executor = createLiveExecutor(env) try { const names = ['null', 'true', 'false', 'inf', 'infinity', 'nan'].flatMap((word) => [ word, word.toUpperCase(), word[0]?.toUpperCase() + word.slice(1), ]) const checks: string[] = [] for (const name of names) { const quoted = `toString(\`${name}\`)` const unquoted = `toString(${name})` checks.push( `SELECT '${name}' AS name, ${quoted} AS quoted_value, ${unquoted} AS literal_value FROM (SELECT 'sentinel' AS \`${name}\`)`, ) const index: TextSkipIndex = { name: 'idx', type: 'text', expression: quoted, tokenizer: 'splitByNonAlpha', } expect(textIndexFingerprint(index)).not.toBe( textIndexFingerprint({ ...index, expression: unquoted }), ) } // One request instead of a sequential round trip per name. const rows = await executor.query<{ name: string quoted_value: string literal_value: string | null }>(checks.join('\nUNION ALL\n')) expect(rows.map((row) => row.name).sort()).toEqual([...names].sort()) for (const row of rows) { expect(row.quoted_value, row.name).toBe('sentinel') expect(row.literal_value, row.name).not.toBe('sentinel') } } finally { await executor.close() } }, 60000) test('quoted NULL column round-trips and changing it to a literal migrates the index', async () => { const executor = createLiveExecutor(env) const name = `${createPrefix('text_keyword')}docs` const index: TextSkipIndex = { name: 'idx', type: 'text', tokenizer: 'splitByNonAlpha', expression: 'concat(body, ifNull("NULL", \'missing\'))', } const base = docs(name, index) const definition = { ...base, columns: [...base.columns, { name: 'NULL', type: 'String' }], } const changedIndex = { ...index, expression: "concat(body, ifNull(NULL, 'missing'))", } const changed = { ...definition, indexes: [changedIndex] } const fullName = `${definition.database}.${name}` const dir = await mkdtemp(join(tmpdir(), 'chkit-text-keyword-')) try { await executor.command(toCreateSQL(definition)) await executor.command(`INSERT INTO ${fullName} VALUES (1, 'doc ', 'alpha')`) const getActual = async () => { const actual = (await executor.listTableDetails([definition.database])).find( (item) => item.name === name, ) if (!actual) throw new Error('Missing test table') return actual } const actual = await getActual() expect(compareTableShape(definition, actual)).toBeNull() expect(compareTableShape(changed, actual)?.reasonCodes).toContain('index_mismatch') const pulled = await loadPulled({ ...definition, indexes: actual.indexes }, dir) expect(planDiff([definition], [pulled]).operations).toEqual([]) const search = (expression: string) => executor.query<{ id: number }>( `SELECT id FROM ${fullName} WHERE hasAllTokens(${expression}, ['alpha'])`, ) expect((await search(index.expression)).map((row) => Number(row.id))).toEqual([1]) const plan = planDiff([pulled], [changed]) expect(plan.operations.map((op) => op.type)).toEqual([ 'alter_table_drop_index', 'alter_table_add_index', ]) for (const op of plan.operations) await executor.command(op.sql) await executor.command( `ALTER TABLE ${fullName} MATERIALIZE INDEX idx SETTINGS mutations_sync = 2`, ) expect(compareTableShape(changed, await getActual())).toBeNull() expect(await search(changedIndex.expression)).toEqual([]) } finally { await executor.command(`DROP TABLE IF EXISTS ${fullName} SYNC`) await executor.close() await rm(dir, { recursive: true, force: true }) } }, 60000) // ClickHouse stores a text index expression the way its formatter prints it: // `NOT a AND b` comes back as `(NOT a) AND b`, BETWEEN as two comparisons. const expressionColumns = [ { name: 'id', type: 'UInt64' }, { name: 's', type: 'String' }, { name: 'x', type: 'String' }, { name: 'a', type: 'UInt8' }, { name: 'b', type: 'UInt8' }, { name: 'c', type: 'UInt8' }, { name: 'd', type: 'UInt8' }, ] test('text index expressions compare equal exactly when ClickHouse parses them the same', async () => { const executor = createLiveExecutor(env) try { const cases = expressionPairs.map(({ schema, server, equal }) => { const index = (expression: string): TextSkipIndex => ({ name: 'idx', type: 'text', expression, tokenizer: 'splitByNonAlpha', }) const expected = table({ database: 'app', name: 'docs', engine: 'MergeTree()', columns: expressionColumns, primaryKey: ['id'], orderBy: ['id'], indexes: [index(schema)], }) const actual = { engine: 'MergeTree()', primaryKey: '(id)', orderBy: '(id)', columns: expressionColumns, settings: {}, indexes: [{ ...index(server), granularity: 100000000 }], projections: [], } return { label: `${schema} vs ${server}`, expected, actual, equal } }) const formatted = await canonicalizeSqlFragments( executor, cases.flatMap(({ expected, actual }) => collectTableSqlFragments(expected, actual).expressions), { wrap: true }, ) const canonicalizer: SqlCanonicalizer = { expression: (fragment) => formatted.get(fragment) ?? null, query: () => null, } for (const { label, expected, actual, equal } of cases) { expect(compareTableShape(expected, actual, canonicalizer)?.indexDiffs ?? [], label).toEqual( equal ? [] : ['idx'], ) } } finally { await executor.close() } }, 60000) test('generate, migrate, and drift read clean when ClickHouse re-parenthesizes text index expressions', async () => { const executor = createLiveExecutor(env) const name = `${createPrefix('text_expr')}docs` const expressions = [ ...new Set(expressionPairs.filter(({ equal }) => equal).map(({ schema }) => schema)), ] // One table holds them all. ClickHouse allows one text index per expression // and several spellings in the fixture parse the same, so each is suffixed. const definition = table({ database: env.clickhouseDatabase, name, engine: 'MergeTree()', columns: expressionColumns, primaryKey: ['id'], orderBy: ['id'], indexes: expressions.map((expression, i) => ({ name: `idx${i}`, type: 'text' as const, expression: `concat(${expression}, '${i}')`, tokenizer: 'splitByNonAlpha', })), }) const dir = await mkdtemp(join(tmpdir(), 'chkit-text-expr-')) const schemaPath = join(dir, 'schema.ts') const configPath = join(dir, 'clickhouse.config.ts') const journal = createJournalTableName('text_expr') const extraEnv = { CHKIT_JOURNAL_TABLE: journal } const command = (args: string[]) => { const result = runCli(dir, [...args, '--config', configPath, '--json'], extraEnv) if (result.exitCode !== 0) throw new Error(formatTestDiagnostic(args.join(' '), result)) return JSON.parse(result.stdout) } try { await writeFile( configPath, `export default ${JSON.stringify({ schema: schemaPath, outDir: join(dir, 'chkit'), migrationsDir: join(dir, 'chkit/migrations'), metaDir: join(dir, 'chkit/meta'), clickhouse: { url: env.clickhouseUrl, username: env.clickhouseUser, password: env.clickhousePassword, database: env.clickhouseDatabase } })}`, ) await writeFile( schemaPath, renderSchemaFile([definition]).replace("'@chkit/core'", JSON.stringify(CORE_ENTRY)), ) command(['generate']) const migrate = await runCliWithRetry( dir, ['migrate', '--execute', '--config', configPath, '--json'], { extraEnv }, ) if (migrate.exitCode !== 0) throw new Error(formatTestDiagnostic('migrate', migrate)) await waitForTable(executor, definition.database, name) const drift = command(['drift', '--table', `${definition.database}.${name}`]) expect(drift.tableDrift).toEqual([]) expect(drift.drifted).toBe(false) } finally { await executor.command(`DROP TABLE IF EXISTS ${definition.database}.${name} SYNC`) await executor.command(`DROP TABLE IF EXISTS ${definition.database}.${journal} SYNC`) await executor.close() await rm(dir, { recursive: true, force: true }) } }, 120000)