ktx/packages/cli/test/context/ingest/adapters/metricflow/semantic-models.test.ts
Andrey Avtomonov 56985b7e09
test: split cli tests from source tree (#216)
* feat(cli): define full warehouse dialect contract

* test(cli): keep dialect edge tests focused

* fix(cli): stabilize dialect contract foundation

* refactor(connectors): own read-only query preparation

* refactor(connectors): resolve dialects through registry

* refactor(connectors): keep concrete dialect classes internal

* chore(workspace): enforce dialect import boundary

* refactor(cli): resolve relationship dialect at scan boundary

* refactor(cli): use dialect display parsing for entity details

* refactor(cli): use dialect display parsing for warehouse catalog

* refactor(cli): use dialect SQL in relationship workflows

* test(cli): verify solid dialect scan workflow closure

* test: split cli tests from source tree

* refactor(cli): standardize BigQuery scope listing

* feat(sqlite): implement connector scope listing

* test(connectors): cover required table listing

* feat(cli): add warehouse driver registry

* refactor(setup): route scope discovery through driver registry

* refactor(cli): route local query execution through driver registry

* refactor(historic-sql): route dialect support through driver registry

* refactor(cli): test warehouse connections through driver registry

* fix(cli): close driver registry type export gaps

* Improve setup daemon diagnostics

* refactor(setup): centralize rail-prefixed diagnostics + query-history fallback

Extract errorMessage, writePrefixedLines, and flushPrefixedBufferedCommandOutput
into clack.ts so the setup wizard, managed daemons, and embedding/agent steps
share one rail-formatted writer. setup-databases.ts also adds a
"disable query history and retry" option when the schema-context build fails
and query history is the likely culprit, surfaced via a new
failed-query-history-unavailable status.

* fix(cli): carry catalog through the picker so BigQuery/Snowflake/SQL Server scope filters match

The setup picker's KtxTableListEntry was a 2-level { schema, name }, so
qualifiedTableId always wrote db.name into enabled_tables. When BigQuery,
Snowflake, or SQL Server later ran fast ingest, their introspect step filtered
the scope set with scopedTableNames(scope, { catalog: projectId|database, db })
— catalog was non-null on the introspect side but null in the scope refs, so
every entry was rejected, the live-database adapter staged zero table files,
and detect() failed with 'Adapter "live-database" did not recognize fetched
source output'.

Align the picker boundary with the canonical 3-level KtxTableRef:

- Add catalog: string | null to KtxTableListEntry.
- BigQuery/Snowflake/SQL Server listTables populate catalog from the
  resolved projectId / database; Postgres/MySQL/ClickHouse/SQLite set null.
- qualifiedTableId emits catalog.schema.name when catalog is non-null
  (resolveEnabledTables already accepts the 3-part shape) and
  schemasFromEnabledTables now goes through parseDottedTableEntry so it
  recovers the schema correctly from both 2-part and 3-part entries.
- Export parseDottedTableEntry from enabled-tables.ts (@internal) for picker
  reuse.

Update listTables expectations in all seven connector tests and the setup /
picker test fixtures. Add a picker regression test that covers the
catalog-bearing round-trip (save + refine).

* fix(cli): allow debug telemetry under opt-out env
2026-05-26 08:49:05 +02:00

259 lines
8.9 KiB
TypeScript

import { describe, expect, it } from 'vitest';
import { composeOverlay } from '../../../../../src/context/sl/semantic-layer.service.js';
import type { SemanticLayerSource } from '../../../../../src/context/sl/types.js';
import type { ParsedCrossModelMetric, ParsedMetricflowRelationship, ParsedSemanticModel } from '../../../../../src/context/ingest/adapters/metricflow/deep-parse.js';
import {
buildMetricflowColumns,
buildMetricflowJoinsForModel,
buildMetricflowSemanticModelSource,
countImportableMetricflowRelationships,
findMatchingMetricflowTable,
mapCrossModelMetricToSource,
mapSemanticModelToSource,
resolveMetricflowSemanticModelSourceName,
rewriteMetricflowManifestJoins,
toKebabCaseMetricflowName,
} from '../../../../../src/context/ingest/adapters/metricflow/semantic-models.js';
const ordersModel: ParsedSemanticModel = {
name: 'orders',
description: 'Order facts',
modelRef: 'fct_orders',
dimensions: [
{ name: 'status', column: 'status', type: 'string', label: 'Status', description: 'Order status' },
{ name: 'ordered_at', column: 'ordered_at', type: 'time', label: 'Ordered At' },
],
measures: [
{
type: 'simple',
name: 'total_revenue',
column: 'amount',
aggregation: 'sum',
label: 'Total Revenue',
description: 'Revenue',
filter: "status = 'completed'",
},
{
type: 'derived',
name: 'average_revenue',
expr: 'total_revenue / NULLIF(order_count, 0)',
dependsOn: ['total_revenue', 'order_count'],
},
],
entities: [],
defaultTimeDimension: 'ordered_at',
};
describe('metricflow semantic model mapping', () => {
it('normalizes source names the same way the server importer did', () => {
expect(toKebabCaseMetricflowName('Fct Orders!')).toBe('fct-orders');
});
it('maps a parsed semantic model to a SemanticLayerSource', () => {
expect(mapSemanticModelToSource(ordersModel, 'analytics.orders')).toEqual({
name: 'fct-orders',
table: 'analytics.orders',
grain: ['status', 'ordered_at'],
columns: [
{ name: 'status', type: 'string', description: 'Order status' },
{ name: 'ordered_at', type: 'time' },
],
measures: [
{
name: 'total_revenue',
expr: 'sum(amount)',
description: 'Revenue',
filter: "status = 'completed'",
},
{
name: 'average_revenue',
expr: 'total_revenue / NULLIF(order_count, 0)',
},
],
joins: [],
descriptions: { dbt: 'Order facts' },
});
});
it('maps a cross-model metric to a SQL standalone source', () => {
const metric: ParsedCrossModelMetric = {
name: 'roas',
label: 'ROAS',
description: 'Return on ad spend',
type: 'derived',
expr: 'revenue / spend',
dependsOn: [
{ metricName: 'orders', alias: 'revenue' },
{ metricName: 'campaigns', alias: 'spend' },
],
filter: "channel = 'paid'",
};
expect(mapCrossModelMetricToSource(metric)).toEqual({
name: 'roas',
sql: 'revenue / spend',
descriptions: { dbt: 'Return on ad spend' },
grain: [],
columns: [],
measures: [
{
name: 'roas',
expr: 'revenue / spend',
description: 'Return on ad spend',
filter: "channel = 'paid'",
},
],
joins: [],
});
});
it('finds matching tables using target schema, exact name, dotted suffix, and underscore suffix', () => {
const tables = [
{ id: '1', name: 'fct_orders', catalog: null, db: 'analytics', columns: [] },
{ id: '2', name: 'warehouse.marts.fct_orders', catalog: null, db: 'marts', columns: [] },
{ id: '3', name: 'warehouse_fct_customers', catalog: null, db: null, columns: [] },
];
expect(findMatchingMetricflowTable('fct_orders', tables, 'analytics')?.id).toBe('1');
expect(findMatchingMetricflowTable('fct_orders', [tables[1]], null)?.id).toBe('2');
expect(findMatchingMetricflowTable('fct_customers', [tables[2]], null)?.id).toBe('3');
expect(findMatchingMetricflowTable('missing', tables, null)).toBeUndefined();
});
it('counts only relationships whose tables and columns exist', () => {
const relationships: ParsedMetricflowRelationship[] = [
{ fromTable: 'orders', fromColumn: 'customer_id', toTable: 'customers', toColumn: 'id' },
{ fromTable: 'orders', fromColumn: 'missing', toTable: 'customers', toColumn: 'id' },
{ fromTable: 'orders', fromColumn: 'customer_id', toTable: 'missing_table', toColumn: 'id' },
];
const tables = [
{ id: '1', name: 'orders', catalog: null, db: null, columns: [{ id: 'c1', name: 'customer_id' }] },
{ id: '2', name: 'customers', catalog: null, db: null, columns: [{ id: 'c2', name: 'id' }] },
];
expect(countImportableMetricflowRelationships(relationships, tables)).toBe(1);
});
it('resolves semantic-model source names to lowercase snake_case identifiers', () => {
expect(
resolveMetricflowSemanticModelSourceName(ordersModel, {
id: '1',
name: 'ANALYTICS.Fct Orders',
catalog: null,
db: 'analytics',
columns: [],
}),
).toBe('fct_orders');
expect(resolveMetricflowSemanticModelSourceName({ ...ordersModel, modelRef: 'fallback_model' }, undefined)).toBe(
'fallback_model',
);
});
it('materializes entity join keys as hidden standalone columns', () => {
expect(
buildMetricflowColumns({
...ordersModel,
entities: [{ name: 'customer', type: 'foreign', expr: 'customer_id', description: 'FK to customers' }],
}),
).toContainEqual({ name: 'customer_id', type: 'string', visibility: 'hidden', description: 'FK to customers' });
});
it('builds standalone sources with semantic-model joins', () => {
const orders: ParsedSemanticModel = {
...ordersModel,
modelRef: 'orders',
entities: [{ name: 'customer', type: 'foreign', expr: 'customer_id' }],
};
const customers: ParsedSemanticModel = {
...ordersModel,
name: 'customers',
modelRef: 'customers',
dimensions: [{ name: 'id', column: 'id', type: 'string' }],
measures: [],
entities: [],
};
const sourceNameByModelRef = new Map([
[orders.modelRef, 'orders'],
[customers.modelRef, 'customers'],
]);
const joins = buildMetricflowJoinsForModel(
orders,
[{ fromTable: 'orders', fromColumn: 'customer_id', toTable: 'customers', toColumn: 'id' }],
sourceNameByModelRef,
);
expect(
buildMetricflowSemanticModelSource(
{
model: orders,
matchedTable: undefined,
sourceName: 'orders',
manifestSource: null,
},
joins,
new Map(),
),
).toMatchObject({
name: 'orders',
table: 'orders',
joins: [{ to: 'customers', on: 'orders.customer_id = customers.id', relationship: 'many_to_one' }],
});
});
it('builds overlays for exact manifest matches so scanned columns remain manifest-owned', () => {
const manifestSource: SemanticLayerSource = {
name: 'orders',
table: 'analytics.orders',
grain: ['id'],
columns: [
{ name: 'id', type: 'string' },
{ name: 'customer_id', type: 'string' },
],
joins: [],
measures: [],
descriptions: { db: 'Orders table from scan' },
};
const overlay = buildMetricflowSemanticModelSource(
{
model: { ...ordersModel, modelRef: 'orders', description: 'dbt-described orders' },
matchedTable: undefined,
sourceName: 'orders',
manifestSource,
},
[{ to: 'customers', on: 'orders.customer_id = customers.id', relationship: 'many_to_one' }],
new Map(),
);
expect(overlay).not.toHaveProperty('table');
expect(overlay).not.toHaveProperty('grain');
expect(overlay).not.toHaveProperty('columns');
expect(overlay).toMatchObject({
name: 'orders',
joins: [{ to: 'customers', on: 'orders.customer_id = customers.id', relationship: 'many_to_one' }],
descriptions: { dbt: 'dbt-described orders' },
});
const composed = composeOverlay(manifestSource, overlay);
expect(composed.columns.map((column) => column.name)).toEqual(['id', 'customer_id']);
expect(composed.joins).toHaveLength(1);
expect(composed.descriptions).toEqual({ db: 'Orders table from scan', dbt: 'dbt-described orders' });
});
it('rewrites preserved manifest joins to synced bare source names', () => {
expect(
rewriteMetricflowManifestJoins(
[
{
to: 'analytics.customers',
on: 'analytics.orders.customer_id = analytics.customers.id',
relationship: 'many_to_one',
},
],
new Map([
['analytics.orders', 'orders'],
['analytics.customers', 'customers'],
]),
),
).toEqual([{ to: 'customers', on: 'orders.customer_id = customers.id', relationship: 'many_to_one' }]);
});
});