ktx/packages/cli/test/context/scan/relationship-profiling.test.ts
Pintouch 2afab61417
feat(connectors): add MongoDB connector (#305) (#310)
* refactor(connectors): split KtxDialect into core and KtxSqlDialect

Separate the dialect contract into a driver-agnostic core (display/ref
formatting and type mapping) and a SQL-only extension (query generators).
The catalog and entity-details paths resolve the core dialect for any
snapshot driver, so it must stay free of SQL generation; this is the
prerequisite refactor for adding non-SQL primary sources.

- KtxDialect keeps type, formatDisplayRef, parseDisplayRef,
  columnDisplayTablePartCount, mapDataType, mapToDimensionType
- KtxSqlDialect extends it with quoteIdentifier, formatTableName, and the
  query/sample/statistics generators; the 7 SQL dialects implement it
- add getSqlDialectForDriver for SQL drivers; the 7 connectors and the
  relationship-benchmark harness consume it
- thread the relationship pipeline (profiling/validation/composite/
  discovery) as KtxSqlDialect | null so a non-SQL source skips coverage SQL
  and its candidates stay in review; local-enrichment builds the SQL
  dialect only when the connector advertises readOnlySql

Pure extraction: no behavior change for the existing 7 drivers.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(connectors): add MongoDB connector for issue #305

Add a read-only MongoDB connector that treats a database as a primary
context source: collections map to tables and inferred top-level fields to
columns. MongoDB is the first non-SQL source (readOnlySql: false), so
ktx sql and metric compilation do not apply, but its collections flow
through ingest, descriptions, and relationship discovery.

- schema-inference: infer a flat column schema from the most recent
  sample_size documents (by _id desc, or order_by for non-ObjectId keys).
  Union BSON types per field, mark multi-type fields mixed (string), keep
  sub-documents/arrays as a single opaque json column, derive nullability
  from presence, treat _id as the primary key
- connector: KtxMongoDbScanConnector behind an injectable client seam;
  strictly read-only (find/listCollections/estimatedDocumentCount only),
  no executeReadOnly; resolves env:/file: via resolveKtxConfigReference
- core-only KtxMongoDbDialect and a live-database introspection adapter
- wire the mongodb driver: driver union, dialect registry, driver
  registration (scopeConfigKey databases), mongodbConnectionSchema,
  connection-drivers, normalizeDriver, the live-database route, and the
  ktx setup picker. ktx sql is refused by the read-only SQL capability gate
- tests: schema inference, connector snapshot via a fake client, dialect,
  driver-schema parsing, and the ktx sql rejection

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(integrations): document the MongoDB primary source

Add a MongoDB section to the primary-sources reference: connection config
(url, databases, enabled_tables, sample_size, order_by), mongodb+srv/TLS/
Atlas notes, the schema-inference explainer, a features matrix, and the
non-SQL caveat. Update the frontmatter and connection field reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(connectors): address review blockers on the MongoDB connector

- introspect: skip estimatedDocumentCount for views. The count command is
  rejected on a MongoDB view (CommandNotSupportedOnView), so counting a view
  aborted introspect for the whole connection; compute estimatedRows only for
  real collections, as ClickHouse does.
- sl: refuse a semantic-layer query against a non-SQL connection instead of
  defaulting it to the Postgres dialect. compileLocalSlQuery (the shared CLI +
  MCP path) now rejects a driver with no SQL dialect via the new
  isSqlQueryableDriver authority, keeping MongoDB context-only per issue #305.
- tests: cover input.tableScope and the empty-scope skip for the Mongo
  connector (the scan layer does not post-filter), the view no-count path, and
  the ktx sl query refusal for a mongodb connection.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* polish(mongodb): compute sampled nullCount and document sampling caveats

Address the non-blocking review notes:

- sampleColumn now counts null/absent values over the sampled window instead of
  returning nullCount: null, since the documents are already in hand
- warn that a custom order_by must be indexed (an unindexed sort hits MongoDB's
  in-memory sort limit on large collections) in the connection schema and docs
- note that sampled values for nested fields are stringified, not faithfully
  serialized, so the json opacity is deliberate

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(examples): add a MongoDB connector example

A manual, container-backed example mirroring examples/postgres-historic:

- docker-compose.yml + init/seed.js seed a representative dataset (nested
  documents, arrays, a Decimal128, a mixed-type field, a nullable field, an
  ObjectId reference, and a view) on first container start
- scripts/smoke.sh + introspect-smoke.mjs assert the connector's inferred
  schema with no LLM credentials — the same introspection entry point ktx
  ingest's database-schema stage uses, including the view-no-count path
- README.md documents the smoke and a full keyless ktx ingest run
  (claude-code LLM + managed sentence-transformers embeddings)

Works with Docker Compose or podman compose. Verified end to end.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore: ignore examples/** in knip to fix dead-code false positives

The MongoDB connector example files (examples/mongodb/init/seed.js and
examples/mongodb/scripts/introspect-smoke.mjs) are used at runtime but were
flagged as unused by knip. Add examples/** to the ignore array, matching the
existing .context/** entry.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0114qQV8fJ5a5ME3XbMVRzbL

* fix(mongodb): refuse non-SQL connections before SQL analysis

`ktx sql` and the MCP sql_execution tool resolved a SQL-analysis dialect
(falling back to Postgres for a non-SQL driver) and ran read-only
validation before the connector capability gate refused the connection.
For a MongoDB connection that spun up the parser/daemon and produced
Postgres parser diagnostics instead of a clean non-SQL refusal.

Route both entry points through a shared assertSqlQueryableConnection
guard before dialect selection, mirroring compileLocalSlQuery. The
federated duckdb path has no driver and is exempted at each call site.
Add CLI and MCP regression tests asserting validation/connector work
never starts for a MongoDB connection.

* fix(mongodb): pass CI gates (dialect boundary, secrets, setup test)

Three latent failures in the connector surfaced once CI ran on the branch:

- connector.ts imported the concrete KtxMongoDbDialect, which the connector
  dialect-import boundary forbids. Route it through getDialectForDriver('mongodb')
  and widen inferKtxMongoCollectionColumns to the base KtxDialect (it only uses
  mapDataType/mapToDimensionType).
- detect-secrets flagged a test ObjectId hex and the mongodb+srv example URL;
  annotate both with allowlist pragmas.
- the "shows every supported database" setup test omitted the new MongoDB option.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Luca Martial <48870843+luca-martial@users.noreply.github.com>
Co-authored-by: Luca Martial <lucamrtl@gmail.com>
Co-authored-by: Andrey Avtomonov <andreybavt@gmail.com>
2026-06-29 15:17:56 +02:00

439 lines
14 KiB
TypeScript

import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import Database from 'better-sqlite3';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { getSqlDialectForDriver } from '../../../src/context/connections/dialects.js';
import type { KtxEnrichedColumn, KtxEnrichedSchema, KtxEnrichedTable } from '../../../src/context/scan/enrichment-types.js';
import { snapshotToKtxEnrichedSchema } from '../../../src/context/scan/local-enrichment.js';
import { loadKtxRelationshipBenchmarkFixture, maskKtxRelationshipBenchmarkSnapshot } from '../../../src/context/scan/relationship-benchmarks.js';
import { createKtxRelationshipProfileCache, profileKtxRelationshipSchema } from '../../../src/context/scan/relationship-profiling.js';
import type { KtxQueryResult, KtxReadOnlyQueryInput, KtxScanContext } from '../../../src/context/scan/types.js';
class InMemorySqliteExecutor {
readonly db = new Database(':memory:');
queryCount = 0;
executeReadOnly(input: KtxReadOnlyQueryInput, _ctx: KtxScanContext): Promise<KtxQueryResult> {
this.queryCount += 1;
const rows = this.db.prepare(input.sql).all() as Record<string, unknown>[];
const headers = Object.keys(rows[0] ?? {});
return Promise.resolve({
headers,
rows: rows.map((row) => headers.map((header) => row[header])),
totalRows: rows.length,
rowCount: rows.length,
});
}
close(): void {
this.db.close();
}
}
class FileSqliteExecutor {
readonly db: Database.Database;
queryCount = 0;
constructor(dataPath: string) {
this.db = new Database(dataPath, { readonly: true, fileMustExist: true });
}
executeReadOnly(input: KtxReadOnlyQueryInput, _ctx: KtxScanContext): Promise<KtxQueryResult> {
this.queryCount += 1;
const rows = this.db.prepare(input.sql).all() as Record<string, unknown>[];
const headers = Object.keys(rows[0] ?? {});
return Promise.resolve({
headers,
rows: rows.map((row) => headers.map((header) => row[header])),
totalRows: rows.length,
rowCount: rows.length,
});
}
close(): void {
this.db.close();
}
}
function column(tableId: string, name: string, overrides: Partial<KtxEnrichedColumn> = {}): KtxEnrichedColumn {
const tableRef = overrides.tableRef ?? { catalog: null, db: null, name: tableId };
return {
id: `${tableId}.${name}`,
tableId,
tableRef,
name,
nativeType: overrides.nativeType ?? 'INTEGER',
normalizedType: overrides.normalizedType ?? 'integer',
dimensionType: overrides.dimensionType ?? 'number',
nullable: overrides.nullable ?? true,
primaryKey: overrides.primaryKey ?? false,
parentColumnId: null,
descriptions: {},
embedding: null,
sampleValues: null,
cardinality: null,
...overrides,
};
}
function table(name: string, columns: KtxEnrichedColumn[]): KtxEnrichedTable {
const ref = { catalog: null, db: null, name };
return {
id: name,
ref,
enabled: true,
descriptions: {},
columns: columns.map((item) => ({ ...item, tableId: name, tableRef: ref })),
};
}
function schema(tables: KtxEnrichedTable[]): KtxEnrichedSchema {
return { connectionId: 'warehouse', tables, relationships: [] };
}
describe('relationship profiling', () => {
let executor: InMemorySqliteExecutor | null = null;
afterEach(() => {
executor?.close();
executor = null;
});
it('keeps profiling on the batched table path', async () => {
const source = await readFile(new URL('../../../src/context/scan/relationship-profiling.ts', import.meta.url), 'utf-8');
expect(source).not.toMatch(new RegExp('queryColumn' + 'Profile'));
expect(source).not.toMatch(/for \(const column of table\.columns\)[\s\S]*executeReadOnly/);
expect(source).toMatch(/queryTableProfile/);
expect(source).toMatch(/UNION ALL/);
});
it('profiles row count, null rate, uniqueness, sample values, and text lengths', async () => {
executor = new InMemorySqliteExecutor();
executor.db.exec(`
CREATE TABLE accounts (id INTEGER, code TEXT, parent_id INTEGER);
INSERT INTO accounts (id, code, parent_id) VALUES
(1, 'A-1', NULL),
(2, 'B-2', 1),
(3, 'C-3', 1),
(4, 'C-3', 2);
`);
const result = await profileKtxRelationshipSchema({
connectionId: 'warehouse',
driver: 'sqlite',
dialect: getSqlDialectForDriver('sqlite'),
schema: schema([
table('accounts', [
column('accounts', 'id', { primaryKey: false, nullable: false }),
column('accounts', 'code', { nativeType: 'TEXT', normalizedType: 'text', dimensionType: 'string' }),
column('accounts', 'parent_id'),
]),
]),
executor,
ctx: { runId: 'profile-test' },
sampleValuesPerColumn: 3,
});
expect(result.sqlAvailable).toBe(true);
expect(result.queryCount).toBe(1);
expect(executor.queryCount).toBe(1);
expect(result.tables).toHaveLength(1);
expect(result.tables[0]).toMatchObject({ table: { name: 'accounts' }, rowCount: 4 });
expect(result.columns['accounts.id']).toMatchObject({
table: { name: 'accounts' },
column: 'id',
rowCount: 4,
nullCount: 0,
distinctCount: 4,
uniquenessRatio: 1,
nullRate: 0,
minTextLength: 1,
maxTextLength: 1,
});
expect(result.columns['accounts.code']).toMatchObject({
distinctCount: 3,
uniquenessRatio: 0.75,
sampleValues: ['C-3', 'A-1', 'B-2'],
minTextLength: 3,
maxTextLength: 3,
});
expect(result.columns['accounts.parent_id']).toMatchObject({
nullCount: 1,
distinctCount: 2,
uniquenessRatio: 0.5,
nullRate: 0.25,
});
});
it('profiles each enabled table with one read-only SQL query', async () => {
executor = new InMemorySqliteExecutor();
executor.db.exec(`
CREATE TABLE accounts (id INTEGER, code TEXT, parent_id INTEGER);
CREATE TABLE users (id INTEGER, account_id INTEGER);
INSERT INTO accounts (id, code, parent_id) VALUES
(1, 'A-1', NULL),
(2, 'B-2', 1),
(3, 'C-3', 1),
(4, 'C-3', 2);
INSERT INTO users (id, account_id) VALUES
(10, 1),
(11, 1),
(12, 2);
`);
const result = await profileKtxRelationshipSchema({
connectionId: 'warehouse',
driver: 'sqlite',
dialect: getSqlDialectForDriver('sqlite'),
schema: schema([
table('accounts', [
column('accounts', 'id', { nullable: false }),
column('accounts', 'code', { nativeType: 'TEXT', normalizedType: 'text', dimensionType: 'string' }),
column('accounts', 'parent_id'),
]),
table('users', [column('users', 'id', { nullable: false }), column('users', 'account_id')]),
]),
executor,
ctx: { runId: 'profile-batched-query-count' },
sampleValuesPerColumn: 3,
});
expect(result.sqlAvailable).toBe(true);
expect(result.queryCount).toBe(2);
expect(executor.queryCount).toBe(2);
expect(result.tables).toEqual([
{ table: { catalog: null, db: null, name: 'accounts' }, rowCount: 4 },
{ table: { catalog: null, db: null, name: 'users' }, rowCount: 3 },
]);
expect(result.columns['accounts.code']).toMatchObject({
distinctCount: 3,
uniquenessRatio: 0.75,
sampleValues: ['C-3', 'A-1', 'B-2'],
});
expect(result.columns['users.account_id']).toMatchObject({
rowCount: 3,
nullCount: 0,
distinctCount: 2,
uniquenessRatio: 2 / 3,
});
});
it('bounds column profile statistics with profileSampleRows', async () => {
const executor = new InMemorySqliteExecutor();
executor.db.exec(`
CREATE TABLE accounts (id INTEGER NOT NULL, account_code TEXT NOT NULL);
INSERT INTO accounts VALUES (1, 'a1'), (2, 'a2'), (3, 'a3'), (4, 'a4');
`);
const profiles = await profileKtxRelationshipSchema({
connectionId: 'warehouse',
driver: 'sqlite',
dialect: getSqlDialectForDriver('sqlite'),
schema: schema([
table('accounts', [
column('accounts', 'id', { nullable: false }),
column('accounts', 'account_code', {
nativeType: 'TEXT',
normalizedType: 'text',
dimensionType: 'string',
nullable: false,
}),
]),
]),
executor,
ctx: { runId: 'profile-sample-rows' },
profileSampleRows: 2,
});
expect(profiles.queryCount).toBe(1);
expect(executor.queryCount).toBe(1);
expect(profiles.tables).toEqual([{ table: { catalog: null, db: null, name: 'accounts' }, rowCount: 4 }]);
expect(profiles.columns['accounts.id']).toMatchObject({
rowCount: 2,
distinctCount: 2,
uniquenessRatio: 1,
});
expect(profiles.columns['accounts.account_code']?.sampleValues).toEqual(['a1', 'a2']);
executor.close();
});
it('reuses a profile cache inside one scan run but re-queries with a fresh cache', async () => {
executor = new InMemorySqliteExecutor();
executor.db.exec(`
CREATE TABLE accounts (id INTEGER NOT NULL, account_code TEXT NOT NULL);
INSERT INTO accounts VALUES (1, 'a1'), (2, 'a2'), (3, 'a2');
`);
const relationshipSchema = schema([
table('accounts', [
column('accounts', 'id', { nullable: false }),
column('accounts', 'account_code', {
nativeType: 'TEXT',
normalizedType: 'text',
dimensionType: 'string',
nullable: false,
}),
]),
]);
const cache = createKtxRelationshipProfileCache();
const first = await profileKtxRelationshipSchema({
connectionId: 'warehouse',
driver: 'sqlite',
dialect: getSqlDialectForDriver('sqlite'),
schema: relationshipSchema,
executor,
ctx: { runId: 'profile-cache-run' },
cache,
});
const second = await profileKtxRelationshipSchema({
connectionId: 'warehouse',
driver: 'sqlite',
dialect: getSqlDialectForDriver('sqlite'),
schema: relationshipSchema,
executor,
ctx: { runId: 'profile-cache-run' },
cache,
});
const third = await profileKtxRelationshipSchema({
connectionId: 'warehouse',
driver: 'sqlite',
dialect: getSqlDialectForDriver('sqlite'),
schema: relationshipSchema,
executor,
ctx: { runId: 'profile-cache-fresh-run' },
cache: createKtxRelationshipProfileCache(),
});
expect(first.queryCount).toBe(1);
expect(second.queryCount).toBe(0);
expect(third.queryCount).toBe(1);
expect(executor.queryCount).toBe(2);
expect(second.tables).toEqual(first.tables);
expect(second.columns).toEqual(first.columns);
});
it('profiles the checked-in scale stress fixture with one query per table', async () => {
const fixtureRoot = new URL('../../fixtures/relationship-benchmarks', import.meta.url);
const fixture = await loadKtxRelationshipBenchmarkFixture(join(fixtureRoot.pathname, 'scale_stress_no_declared_constraints'));
if (!fixture.dataPath) {
throw new Error('scale_stress_no_declared_constraints is missing data.sqlite');
}
const maskedSnapshot = maskKtxRelationshipBenchmarkSnapshot(
fixture.snapshot,
'declared_pks_and_declared_fks_removed',
);
const scaleExecutor = new FileSqliteExecutor(fixture.dataPath);
try {
const result = await profileKtxRelationshipSchema({
connectionId: fixture.snapshot.connectionId,
driver: fixture.snapshot.driver,
dialect: getSqlDialectForDriver(fixture.snapshot.driver),
schema: snapshotToKtxEnrichedSchema(maskedSnapshot, new Map()),
executor: scaleExecutor,
ctx: { runId: 'scale-stress-profile-query-count' },
profileSampleRows: 3,
});
expect(fixture.snapshot.tables).toHaveLength(400);
expect(result.queryCount).toBe(400);
expect(result.queryCount).toBeLessThanOrEqual(2 * fixture.snapshot.tables.length);
expect(scaleExecutor.queryCount).toBe(400);
} finally {
scaleExecutor.close();
}
});
it('profiles tables concurrently up to profileConcurrency', async () => {
let inFlight = 0;
let maxInFlight = 0;
const executor = {
executeReadOnly: vi.fn(async (input: KtxReadOnlyQueryInput) => {
inFlight += 1;
maxInFlight = Math.max(maxInFlight, inFlight);
await new Promise((resolve) => setTimeout(resolve, 10));
inFlight -= 1;
return {
headers: [
'column_name',
'table_row_count',
'row_count',
'null_count',
'distinct_count',
'min_text_length',
'max_text_length',
'sample_values',
],
rows: [[input.sql.includes('accounts') ? 'id' : 'account_id', 2, 2, 0, 2, 1, 2, '1\u001f2']],
totalRows: 1,
rowCount: 1,
};
}),
};
await profileKtxRelationshipSchema({
connectionId: 'warehouse',
driver: 'sqlite',
dialect: getSqlDialectForDriver('sqlite'),
schema: schemaWithTables(['accounts', 'orders', 'payments', 'refunds']),
executor,
ctx: { runId: 'profile-concurrency' },
profileConcurrency: 4,
});
expect(maxInFlight).toBe(4);
});
it('keeps profiling other tables when one table profile fails', async () => {
const executor = {
executeReadOnly: vi.fn(async (input: KtxReadOnlyQueryInput) => {
if (input.sql.includes('"orders"')) {
throw new Error('orders unavailable');
}
return {
headers: [
'column_name',
'table_row_count',
'row_count',
'null_count',
'distinct_count',
'min_text_length',
'max_text_length',
'sample_values',
],
rows: [['id', 2, 2, 0, 2, 1, 2, '1\u001f2']],
totalRows: 1,
rowCount: 1,
};
}),
};
const result = await profileKtxRelationshipSchema({
connectionId: 'warehouse',
driver: 'sqlite',
dialect: getSqlDialectForDriver('sqlite'),
schema: schemaWithTables(['accounts', 'orders']),
executor,
ctx: { runId: 'profile-error-isolated' },
profileConcurrency: 2,
});
expect(result.warnings).toContain('profile_failed:orders:orders unavailable');
expect(result.tables).toHaveLength(2);
expect(Object.keys(result.columns)).toContain('accounts.id');
});
});
function schemaWithTables(names: string[]): KtxEnrichedSchema {
return schema(
names.map((name) =>
table(name, [
column(name, name === 'orders' ? 'account_id' : 'id', {
nullable: false,
primaryKey: name !== 'orders',
}),
]),
),
);
}