mirror of
https://github.com/Kaelio/ktx.git
synced 2026-06-28 08:49:38 +02:00
fix: read semantic sources safely (#284)
* fix: read semantic sources safely
* test: retarget reindex per-scope error case to a broken manifest
Reading a broken standalone source was made non-fatal in de1f1a8d (it is
surfaced for repair instead of throwing), so the reindex per-scope error
test no longer captured an error. Point it at a corrupt manifest shard,
which is the remaining fatal read failure the per-scope catch must
isolate, and assert the captured error names the offending file.
* fix(sl): decouple semantic-layer file names from warehouse naming rules
The in-file `name:` field is now the sole source identity; the filename is
a derived label that never participates in identity. This removes the
"Unsafe semantic-layer source name" failure class entirely: any warehouse
identifier (Snowflake's uppercase SIGNED_UP, EVENT$LOG, dotted names) can
be read, overlaid, edited, and deleted.
- New `source-files.ts`: one total filename derivation (safe lowercase
names verbatim; otherwise slug + sha256-hash suffix, immune to
case-insensitive-filesystem collisions) and one by-name file resolver.
- Reads resolve by name everywhere; the path-from-name fast path and
`assertSafeSourceName` are gone.
- Writes resolve-then-write: rewrites land on the file that declares the
name (human renames survive); new sources get a derived filename; a
derived path occupied by a different source fails instead of clobbering.
- `readSourceFile` returns null for missing files instead of forcing every
caller to launder IO errors; `deleteSource` distinguishes manifest-backed
sources from not-found instead of silently succeeding.
- `sl_write_source` accepts verbatim warehouse identifiers (snake_case is
now a recommendation for new sources) and rejects sourceName/source.name
mismatches; `sl_edit_source` rejects name-changing edits.
- Ingest projection commits, gate-repair allowlists, and touched-source
derivation use resolved paths / in-file names instead of interpolating
`<connId>/<name>.yaml`.
- Collapsed the five parallel path derivations and duplicated path-token
helpers onto the shared module; dropped dead service methods.
* fix(sl): resolve sources by declared name end-to-end and gate warehouse SQL with the parser-backed validator
- Key broken/renamed semantic-layer files by their recoverable in-file
name (slSourceNameForFile) so mid-edit sources stay reachable under
their real identity in reads, listings, and search
- Derive finalization touched sources from composed-source diffs and
recover deleted files' declared names from the pre-change commit
instead of parsing hash-derived filenames
- Resolve revert/rollback paths against history (listFilesAtCommit) so
human-renamed files are restored where they lived at preHead
- Validate ingest sql_execution through the daemon's sqlglot
validateReadOnly in the connection's dialect, sharing one
driver-to-dialect map (sql-analysis/dialect.ts) across MCP and ingest
- Harden the local read-only SQL backstop: accept leading comments,
reject smuggled second statements, and strip trailing
semicolons/comments before row-limit wrapping
This commit is contained in:
parent
853f39a7c3
commit
f3f893bf01
51 changed files with 1797 additions and 476 deletions
|
|
@ -9,8 +9,8 @@ import {
|
|||
resolveLocalSlSource,
|
||||
searchLocalSlSources,
|
||||
validateLocalSlSource,
|
||||
writeLocalSlSource,
|
||||
} from '../../../src/context/sl/local-sl.js';
|
||||
import { seedSlSourceFile } from './sl-source-seeding.test-utils.js';
|
||||
|
||||
const ORDERS_YAML = [
|
||||
'name: orders',
|
||||
|
|
@ -60,7 +60,7 @@ describe('local semantic-layer helpers', () => {
|
|||
});
|
||||
|
||||
it('writes, reads, lists, and validates semantic-layer sources', async () => {
|
||||
const write = await writeLocalSlSource(project, {
|
||||
const write = await seedSlSourceFile(project, {
|
||||
connectionId: 'warehouse',
|
||||
sourceName: 'orders',
|
||||
yaml: ORDERS_YAML,
|
||||
|
|
@ -92,7 +92,7 @@ describe('local semantic-layer helpers', () => {
|
|||
});
|
||||
|
||||
it('resolves a scoped source by connection id', async () => {
|
||||
await writeLocalSlSource(project, {
|
||||
await seedSlSourceFile(project, {
|
||||
connectionId: 'warehouse',
|
||||
sourceName: 'orders',
|
||||
yaml: ORDERS_YAML,
|
||||
|
|
@ -115,7 +115,7 @@ describe('local semantic-layer helpers', () => {
|
|||
});
|
||||
|
||||
it('returns not-found for a missing scoped source', async () => {
|
||||
await writeLocalSlSource(project, {
|
||||
await seedSlSourceFile(project, {
|
||||
connectionId: 'warehouse',
|
||||
sourceName: 'orders',
|
||||
yaml: ORDERS_YAML,
|
||||
|
|
@ -130,12 +130,12 @@ describe('local semantic-layer helpers', () => {
|
|||
});
|
||||
|
||||
it('resolves a unique source name across all connections', async () => {
|
||||
await writeLocalSlSource(project, {
|
||||
await seedSlSourceFile(project, {
|
||||
connectionId: 'warehouse',
|
||||
sourceName: 'orders',
|
||||
yaml: ORDERS_YAML,
|
||||
});
|
||||
await writeLocalSlSource(project, {
|
||||
await seedSlSourceFile(project, {
|
||||
connectionId: 'analytics',
|
||||
sourceName: 'tickets',
|
||||
yaml: SUPPORT_YAML,
|
||||
|
|
@ -157,7 +157,7 @@ describe('local semantic-layer helpers', () => {
|
|||
});
|
||||
|
||||
it('returns not-found for a missing unscoped source', async () => {
|
||||
await writeLocalSlSource(project, {
|
||||
await seedSlSourceFile(project, {
|
||||
connectionId: 'warehouse',
|
||||
sourceName: 'orders',
|
||||
yaml: ORDERS_YAML,
|
||||
|
|
@ -169,12 +169,12 @@ describe('local semantic-layer helpers', () => {
|
|||
});
|
||||
|
||||
it('reports sorted ambiguous connection ids for duplicate source names', async () => {
|
||||
await writeLocalSlSource(project, {
|
||||
await seedSlSourceFile(project, {
|
||||
connectionId: 'warehouse',
|
||||
sourceName: 'orders',
|
||||
yaml: ORDERS_YAML,
|
||||
});
|
||||
await writeLocalSlSource(project, {
|
||||
await seedSlSourceFile(project, {
|
||||
connectionId: 'analytics',
|
||||
sourceName: 'orders',
|
||||
yaml: ORDERS_YAML,
|
||||
|
|
@ -261,6 +261,153 @@ describe('local semantic-layer helpers', () => {
|
|||
);
|
||||
});
|
||||
|
||||
it('reads manifest-backed scan sources whose warehouse identifiers are uppercase', async () => {
|
||||
await project.fileStore.writeFile(
|
||||
'semantic-layer/warehouse/_schema/PUBLIC.yaml',
|
||||
`tables:
|
||||
WIDGET_SALES:
|
||||
table: PUBLIC.WIDGET_SALES
|
||||
columns:
|
||||
- name: ID
|
||||
type: number
|
||||
pk: true
|
||||
- name: EMAIL
|
||||
type: string
|
||||
`,
|
||||
'ktx',
|
||||
'ktx@example.com',
|
||||
'Add uppercase manifest shard',
|
||||
);
|
||||
|
||||
await expect(readLocalSlSource(project, { connectionId: 'warehouse', sourceName: 'WIDGET_SALES' })).resolves.toEqual(
|
||||
expect.objectContaining({
|
||||
connectionId: 'warehouse',
|
||||
name: 'WIDGET_SALES',
|
||||
path: 'semantic-layer/warehouse/_schema/PUBLIC.yaml#WIDGET_SALES',
|
||||
yaml: expect.stringContaining('table: PUBLIC.WIDGET_SALES'),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('reads manifest-backed sources whose names are not filename-safe', async () => {
|
||||
// Snowflake and Postgres unquoted identifiers allow `$`; manifest keys
|
||||
// carry the warehouse name verbatim, so the lookup must accept it.
|
||||
await project.fileStore.writeFile(
|
||||
'semantic-layer/warehouse/_schema/PUBLIC.yaml',
|
||||
`tables:
|
||||
EVENT$LOG:
|
||||
table: PUBLIC.EVENT$LOG
|
||||
columns:
|
||||
- name: ID
|
||||
type: number
|
||||
pk: true
|
||||
`,
|
||||
'ktx',
|
||||
'ktx@example.com',
|
||||
'Add manifest shard with dollar-sign table name',
|
||||
);
|
||||
|
||||
await expect(readLocalSlSource(project, { connectionId: 'warehouse', sourceName: 'EVENT$LOG' })).resolves.toEqual(
|
||||
expect.objectContaining({
|
||||
connectionId: 'warehouse',
|
||||
name: 'EVENT$LOG',
|
||||
path: 'semantic-layer/warehouse/_schema/PUBLIC.yaml#EVENT$LOG',
|
||||
yaml: expect.stringContaining('table: PUBLIC.EVENT$LOG'),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('reads a manifest-backed source while a sibling standalone file has broken YAML', async () => {
|
||||
await project.fileStore.writeFile(
|
||||
'semantic-layer/warehouse/_schema/PUBLIC.yaml',
|
||||
`tables:
|
||||
WIDGET_SALES:
|
||||
table: PUBLIC.WIDGET_SALES
|
||||
columns:
|
||||
- name: ID
|
||||
type: number
|
||||
pk: true
|
||||
`,
|
||||
'ktx',
|
||||
'ktx@example.com',
|
||||
'Add manifest shard',
|
||||
);
|
||||
await project.fileStore.writeFile(
|
||||
'semantic-layer/warehouse/orders.yaml',
|
||||
'name: orders\nmeasures:\n - name: revenue\n expr: [unterminated\n',
|
||||
'ktx',
|
||||
'ktx@example.com',
|
||||
'seed a sibling source mid-edit with broken YAML',
|
||||
);
|
||||
|
||||
await expect(readLocalSlSource(project, { connectionId: 'warehouse', sourceName: 'WIDGET_SALES' })).resolves.toEqual(
|
||||
expect.objectContaining({
|
||||
name: 'WIDGET_SALES',
|
||||
yaml: expect.stringContaining('table: PUBLIC.WIDGET_SALES'),
|
||||
}),
|
||||
);
|
||||
|
||||
// The broken sibling stays visible in listings instead of hiding or
|
||||
// failing the whole connection.
|
||||
await expect(listLocalSlSources(project, { connectionId: 'warehouse' })).resolves.toEqual([
|
||||
expect.objectContaining({ name: 'orders', columnCount: 0 }),
|
||||
expect.objectContaining({ name: 'WIDGET_SALES', columnCount: 1 }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns the raw YAML of a standalone source whose content no longer parses', async () => {
|
||||
await project.fileStore.writeFile(
|
||||
'semantic-layer/warehouse/orders.yaml',
|
||||
'name: orders\nmeasures:\n - name: revenue\n expr: [unterminated\n',
|
||||
'ktx',
|
||||
'ktx@example.com',
|
||||
'seed a source mid-edit with broken YAML',
|
||||
);
|
||||
|
||||
await expect(readLocalSlSource(project, { connectionId: 'warehouse', sourceName: 'orders' })).resolves.toEqual(
|
||||
expect.objectContaining({
|
||||
connectionId: 'warehouse',
|
||||
name: 'orders',
|
||||
path: 'semantic-layer/warehouse/orders.yaml',
|
||||
yaml: expect.stringContaining('[unterminated'),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('reads a broken source by its declared name even when the filename differs', async () => {
|
||||
// Identity is the intact top-level `name:`, recovered via parseDocument even
|
||||
// when the YAML is broken below it — never the filename. A human-renamed or
|
||||
// hashed-filename source (e.g. an uppercase warehouse name) saved mid-edit
|
||||
// must stay reachable under the name it declares, matching the writer side
|
||||
// (resolveSlSourceFile). Keying it by the filename would make it invisible
|
||||
// under its real name.
|
||||
await project.fileStore.writeFile(
|
||||
'semantic-layer/warehouse/renamed-by-hand.yaml',
|
||||
'name: SIGNED_UP\nmeasures:\n - name: signups\n expr: [unterminated\n',
|
||||
'ktx',
|
||||
'ktx@example.com',
|
||||
'seed a human-renamed source mid-edit with broken YAML',
|
||||
);
|
||||
|
||||
await expect(readLocalSlSource(project, { connectionId: 'warehouse', sourceName: 'SIGNED_UP' })).resolves.toEqual(
|
||||
expect.objectContaining({
|
||||
connectionId: 'warehouse',
|
||||
name: 'SIGNED_UP',
|
||||
path: 'semantic-layer/warehouse/renamed-by-hand.yaml',
|
||||
yaml: expect.stringContaining('[unterminated'),
|
||||
}),
|
||||
);
|
||||
|
||||
// The filename is not the identity, so it does not resolve a source.
|
||||
await expect(
|
||||
readLocalSlSource(project, { connectionId: 'warehouse', sourceName: 'renamed-by-hand' }),
|
||||
).resolves.toBeNull();
|
||||
|
||||
await expect(listLocalSlSources(project, { connectionId: 'warehouse' })).resolves.toEqual([
|
||||
expect.objectContaining({ name: 'SIGNED_UP', columnCount: 0 }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('expands manifest-backed scan sources when listing all connections', async () => {
|
||||
await project.fileStore.writeFile(
|
||||
'semantic-layer/warehouse/_schema/public.yaml',
|
||||
|
|
@ -292,12 +439,12 @@ describe('local semantic-layer helpers', () => {
|
|||
});
|
||||
|
||||
it('searches local semantic-layer source text through SQLite FTS', async () => {
|
||||
await writeLocalSlSource(project, {
|
||||
await seedSlSourceFile(project, {
|
||||
connectionId: 'warehouse',
|
||||
sourceName: 'orders',
|
||||
yaml: ORDERS_YAML,
|
||||
});
|
||||
await writeLocalSlSource(project, {
|
||||
await seedSlSourceFile(project, {
|
||||
connectionId: 'warehouse',
|
||||
sourceName: 'tickets',
|
||||
yaml: SUPPORT_YAML,
|
||||
|
|
@ -365,12 +512,12 @@ describe('local semantic-layer helpers', () => {
|
|||
});
|
||||
|
||||
it('searches all connections with one global hybrid ranking pass', async () => {
|
||||
await writeLocalSlSource(project, {
|
||||
await seedSlSourceFile(project, {
|
||||
connectionId: 'warehouse',
|
||||
sourceName: 'orders',
|
||||
yaml: ORDERS_YAML,
|
||||
});
|
||||
await writeLocalSlSource(project, {
|
||||
await seedSlSourceFile(project, {
|
||||
connectionId: 'finance',
|
||||
sourceName: 'orders',
|
||||
yaml: [
|
||||
|
|
@ -403,7 +550,7 @@ describe('local semantic-layer helpers', () => {
|
|||
});
|
||||
|
||||
it('returns dictionary evidence when collected sample values explain a match', async () => {
|
||||
await writeLocalSlSource(project, {
|
||||
await seedSlSourceFile(project, {
|
||||
connectionId: 'warehouse',
|
||||
sourceName: 'orders',
|
||||
yaml: ORDERS_YAML,
|
||||
|
|
@ -456,7 +603,7 @@ describe('local semantic-layer helpers', () => {
|
|||
});
|
||||
|
||||
it('adds the token lane alongside lexical matches for normalized query terms', async () => {
|
||||
await writeLocalSlSource(project, {
|
||||
await seedSlSourceFile(project, {
|
||||
connectionId: 'warehouse',
|
||||
sourceName: 'orders',
|
||||
yaml: ORDERS_YAML,
|
||||
|
|
@ -471,21 +618,13 @@ describe('local semantic-layer helpers', () => {
|
|||
});
|
||||
});
|
||||
|
||||
it('reports schema validation errors without writing invalid YAML', async () => {
|
||||
it('reports schema validation errors for invalid YAML', async () => {
|
||||
const invalidYaml = ['name: broken', 'table: public.orders', 'columns: []', ''].join('\n');
|
||||
|
||||
await expect(validateLocalSlSource(invalidYaml)).resolves.toMatchObject({
|
||||
valid: false,
|
||||
errors: expect.arrayContaining([expect.stringContaining('grain')]),
|
||||
});
|
||||
|
||||
await expect(
|
||||
writeLocalSlSource(project, {
|
||||
connectionId: 'warehouse',
|
||||
sourceName: 'broken',
|
||||
yaml: invalidYaml,
|
||||
}),
|
||||
).rejects.toThrow('Invalid semantic-layer source');
|
||||
});
|
||||
|
||||
it('reports overlay columns that are not computed columns', async () => {
|
||||
|
|
@ -506,12 +645,40 @@ describe('local semantic-layer helpers', () => {
|
|||
});
|
||||
});
|
||||
|
||||
it('rejects unsafe source paths', async () => {
|
||||
it('never derives a file path from a traversal-style source name', async () => {
|
||||
// Reads match names against loaded records, so a traversal-style name is
|
||||
// simply not found; the writer-side guarantee (derived filenames contain
|
||||
// no separators) is covered by the source-files tests.
|
||||
await expect(
|
||||
readLocalSlSource(project, {
|
||||
connectionId: 'warehouse',
|
||||
sourceName: '../orders',
|
||||
}),
|
||||
).rejects.toThrow('Unsafe semantic-layer source name');
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('reads a source from a human-renamed file by its in-file name', async () => {
|
||||
// The filename is a derived label, not identity: a file renamed by a human
|
||||
// still resolves under the `name:` it declares.
|
||||
await project.fileStore.writeFile(
|
||||
'semantic-layer/warehouse/custom-file-name.yaml',
|
||||
ORDERS_YAML,
|
||||
'ktx',
|
||||
'ktx@example.com',
|
||||
'Seed source at a human-chosen filename',
|
||||
);
|
||||
|
||||
await expect(
|
||||
readLocalSlSource(project, { connectionId: 'warehouse', sourceName: 'orders' }),
|
||||
).resolves.toMatchObject({
|
||||
connectionId: 'warehouse',
|
||||
name: 'orders',
|
||||
path: 'semantic-layer/warehouse/custom-file-name.yaml',
|
||||
yaml: ORDERS_YAML,
|
||||
});
|
||||
|
||||
await expect(
|
||||
readLocalSlSource(project, { connectionId: 'warehouse', sourceName: 'custom-file-name' }),
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -5,8 +5,9 @@ import { join } from 'node:path';
|
|||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { initKtxProject, type KtxLocalProject } from '../../../src/context/project/project.js';
|
||||
import { assertSearchBackendConformanceCase } from '../search/backend-conformance.test-utils.js';
|
||||
import { searchLocalSlSources, writeLocalSlSource, type LocalSlSourceSearchResult } from '../../../src/context/sl/local-sl.js';
|
||||
import { searchLocalSlSources, type LocalSlSourceSearchResult } from '../../../src/context/sl/local-sl.js';
|
||||
import { searchLocalSlSourcesWithPglitePrototype } from '../../../src/context/sl/pglite-sl-search-prototype.js';
|
||||
import { seedSlSourceFile } from './sl-source-seeding.test-utils.js';
|
||||
|
||||
const ORDERS_YAML = [
|
||||
'name: orders',
|
||||
|
|
@ -107,9 +108,9 @@ function toConformanceResult(result: LocalSlSourceSearchResult) {
|
|||
}
|
||||
|
||||
async function seedSemanticLayerProject(project: KtxLocalProject): Promise<void> {
|
||||
await writeLocalSlSource(project, { connectionId: 'warehouse', sourceName: 'orders', yaml: ORDERS_YAML });
|
||||
await writeLocalSlSource(project, { connectionId: 'finance', sourceName: 'orders', yaml: FINANCE_ORDERS_YAML });
|
||||
await writeLocalSlSource(project, { connectionId: 'warehouse', sourceName: 'customers', yaml: CUSTOMERS_YAML });
|
||||
await seedSlSourceFile(project, { connectionId: 'warehouse', sourceName: 'orders', yaml: ORDERS_YAML });
|
||||
await seedSlSourceFile(project, { connectionId: 'finance', sourceName: 'orders', yaml: FINANCE_ORDERS_YAML });
|
||||
await seedSlSourceFile(project, { connectionId: 'warehouse', sourceName: 'customers', yaml: CUSTOMERS_YAML });
|
||||
|
||||
await project.fileStore.writeFile(
|
||||
'raw-sources/warehouse/live-database/sync-1/enrichment/relationship-profile.json',
|
||||
|
|
|
|||
|
|
@ -1,5 +1,9 @@
|
|||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import type { Mock } from 'vitest';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { initKtxProject, type KtxLocalProject } from '../../../src/context/project/project.js';
|
||||
|
||||
import {
|
||||
ColumnNameCollisionError,
|
||||
|
|
@ -71,6 +75,7 @@ describe('loadSource', () => {
|
|||
it('warns and returns null when an existing source file has invalid YAML', async () => {
|
||||
const logger = { log: vi.fn(), warn: vi.fn(), error: vi.fn() };
|
||||
const configService = {
|
||||
listFiles: vi.fn().mockResolvedValue({ files: ['semantic-layer/warehouse/orders.yaml'] }),
|
||||
readFile: vi.fn().mockResolvedValue({ content: 'name: [' }),
|
||||
};
|
||||
const service = new SemanticLayerService(configService as never, connectionCatalog(), pythonPort, logger as never);
|
||||
|
|
@ -79,9 +84,33 @@ describe('loadSource', () => {
|
|||
|
||||
expect(configService.readFile).toHaveBeenCalledWith('semantic-layer/warehouse/orders.yaml');
|
||||
expect(logger.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('[loadSource] warehouse/orders.yaml: YAML parse failed:'),
|
||||
expect.stringContaining('[loadSource] semantic-layer/warehouse/orders.yaml: YAML parse failed:'),
|
||||
);
|
||||
});
|
||||
|
||||
it('returns null when no file declares the source name', async () => {
|
||||
const configService = {
|
||||
listFiles: vi.fn().mockResolvedValue({ files: [] }),
|
||||
readFile: vi.fn(),
|
||||
};
|
||||
const service = new SemanticLayerService(configService as never, connectionCatalog(), pythonPort);
|
||||
|
||||
await expect(service.loadSource('warehouse', 'orders')).resolves.toBeNull();
|
||||
expect(configService.readFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('resolves a source by its in-file name when the filename differs', async () => {
|
||||
const configService = {
|
||||
listFiles: vi.fn().mockResolvedValue({ files: ['semantic-layer/warehouse/renamed.yaml'] }),
|
||||
readFile: vi.fn().mockResolvedValue({ content: 'name: SIGNED_UP\nmeasures: []\n' }),
|
||||
};
|
||||
const service = new SemanticLayerService(configService as never, connectionCatalog(), pythonPort);
|
||||
|
||||
await expect(service.loadSource('warehouse', 'SIGNED_UP')).resolves.toEqual({
|
||||
name: 'SIGNED_UP',
|
||||
measures: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('composeOverlay', () => {
|
||||
|
|
@ -1242,3 +1271,177 @@ describe('findDanglingSegmentRefs', () => {
|
|||
expect(findDanglingSegmentRefs({})).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('writeSource / deleteSource file naming', () => {
|
||||
let tempDir: string;
|
||||
let project: KtxLocalProject;
|
||||
let service: SemanticLayerService;
|
||||
|
||||
const author = 'T U';
|
||||
const authorEmail = 't@u.com';
|
||||
|
||||
beforeEach(async () => {
|
||||
tempDir = await mkdtemp(join(tmpdir(), 'ktx-sl-service-files-'));
|
||||
project = await initKtxProject({ projectDir: join(tempDir, 'project') });
|
||||
service = new SemanticLayerService(project.fileStore as never, connectionCatalog() as never, pythonPort as never);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const signedUp: SemanticLayerSource = {
|
||||
name: 'SIGNED_UP',
|
||||
table: 'PUBLIC.SIGNED_UP',
|
||||
grain: ['ID'],
|
||||
columns: [{ name: 'ID', type: 'number' }],
|
||||
joins: [],
|
||||
measures: [],
|
||||
};
|
||||
|
||||
it('writes a new uppercase source at a derived filename and reads it back by name', async () => {
|
||||
const result = await service.writeSource('warehouse', signedUp, author, authorEmail);
|
||||
|
||||
expect(result.path).toMatch(/^semantic-layer\/warehouse\/signed_up-[0-9a-f]{8}\.yaml$/);
|
||||
|
||||
const file = await service.readSourceFile('warehouse', 'SIGNED_UP');
|
||||
expect(file?.path).toBe(result.path);
|
||||
expect(file?.content).toContain('name: SIGNED_UP');
|
||||
|
||||
// Rewriting lands on the same file instead of deriving a second one.
|
||||
const rewrite = await service.writeSource('warehouse', signedUp, author, authorEmail);
|
||||
expect(rewrite.path).toBe(result.path);
|
||||
});
|
||||
|
||||
it('repairs a broken file occupying the derived path instead of refusing the write', async () => {
|
||||
const written = await service.writeSource('warehouse', signedUp, author, authorEmail);
|
||||
await project.fileStore.writeFile(
|
||||
written.path,
|
||||
'name: SIGNED_UP\nmeasures: [unterminated\n',
|
||||
author,
|
||||
authorEmail,
|
||||
'break the file',
|
||||
);
|
||||
|
||||
const repaired = await service.writeSource('warehouse', signedUp, author, authorEmail);
|
||||
|
||||
expect(repaired.path).toBe(written.path);
|
||||
const file = await service.readSourceFile('warehouse', 'SIGNED_UP');
|
||||
expect(file?.path).toBe(written.path);
|
||||
expect(file?.content).toContain('name: SIGNED_UP');
|
||||
});
|
||||
|
||||
it('rewrites a human-renamed file in place', async () => {
|
||||
await project.fileStore.writeFile(
|
||||
'semantic-layer/warehouse/custom.yaml',
|
||||
'name: orders\nmeasures: []\n',
|
||||
author,
|
||||
authorEmail,
|
||||
'seed renamed file',
|
||||
);
|
||||
|
||||
const result = await service.writeSource(
|
||||
'warehouse',
|
||||
{ name: 'orders', grain: [], columns: [], joins: [], measures: [] },
|
||||
author,
|
||||
authorEmail,
|
||||
);
|
||||
|
||||
expect(result.path).toBe('semantic-layer/warehouse/custom.yaml');
|
||||
const listed = await project.fileStore.listFiles('semantic-layer/warehouse');
|
||||
expect(listed.files).toEqual(['semantic-layer/warehouse/custom.yaml']);
|
||||
});
|
||||
|
||||
it('repairs a human-renamed broken file in place instead of deriving a second one', async () => {
|
||||
// Renamed (filename ≠ name) AND mid-edit broken: identity must survive the
|
||||
// syntax error so the rewrite lands on the original file rather than creating
|
||||
// a duplicate at the derived path that later trips the by-name resolver.
|
||||
await project.fileStore.writeFile(
|
||||
'semantic-layer/warehouse/custom.yaml',
|
||||
'name: SIGNED_UP\nmeasures: [unterminated\n',
|
||||
author,
|
||||
authorEmail,
|
||||
'seed broken renamed file',
|
||||
);
|
||||
|
||||
const repaired = await service.writeSource('warehouse', signedUp, author, authorEmail);
|
||||
|
||||
expect(repaired.path).toBe('semantic-layer/warehouse/custom.yaml');
|
||||
const listed = await project.fileStore.listFiles('semantic-layer/warehouse');
|
||||
expect(listed.files).toEqual(['semantic-layer/warehouse/custom.yaml']);
|
||||
const file = await service.readSourceFile('warehouse', 'SIGNED_UP');
|
||||
expect(file?.path).toBe('semantic-layer/warehouse/custom.yaml');
|
||||
expect(file?.content).toContain('name: SIGNED_UP');
|
||||
});
|
||||
|
||||
it('keeps a .yml-renamed file visible to the loader and the by-name resolver alike', async () => {
|
||||
await project.fileStore.writeFile(
|
||||
'semantic-layer/warehouse/custom.yml',
|
||||
'name: orders\ntable: public.orders\ngrain: [id]\ncolumns:\n - name: id\n type: number\nmeasures: []\n',
|
||||
author,
|
||||
authorEmail,
|
||||
'seed .yml file',
|
||||
);
|
||||
|
||||
const { sources, loadErrors } = await service.loadAllSources('warehouse');
|
||||
expect(loadErrors).toEqual([]);
|
||||
expect(sources.map((source) => source.name)).toEqual(['orders']);
|
||||
|
||||
const file = await service.readSourceFile('warehouse', 'orders');
|
||||
expect(file?.path).toBe('semantic-layer/warehouse/custom.yml');
|
||||
});
|
||||
|
||||
it('refuses to clobber a derived path occupied by a different source', async () => {
|
||||
await project.fileStore.writeFile(
|
||||
'semantic-layer/warehouse/orders.yaml',
|
||||
'name: other_source\nmeasures: []\n',
|
||||
author,
|
||||
authorEmail,
|
||||
'seed conflicting file',
|
||||
);
|
||||
|
||||
await expect(
|
||||
service.writeSource(
|
||||
'warehouse',
|
||||
{ name: 'orders', grain: [], columns: [], joins: [], measures: [] },
|
||||
author,
|
||||
authorEmail,
|
||||
),
|
||||
).rejects.toThrow("already defines source 'other_source'");
|
||||
});
|
||||
|
||||
it('deletes the file resolved by name, wherever it lives', async () => {
|
||||
await project.fileStore.writeFile(
|
||||
'semantic-layer/warehouse/custom.yaml',
|
||||
'name: orders\nmeasures: []\n',
|
||||
author,
|
||||
authorEmail,
|
||||
'seed renamed file',
|
||||
);
|
||||
|
||||
await service.deleteSource('warehouse', 'orders', author, authorEmail);
|
||||
|
||||
const listed = await project.fileStore.listFiles('semantic-layer/warehouse');
|
||||
expect(listed.files).toEqual([]);
|
||||
});
|
||||
|
||||
it('explains manifest-backed deletes instead of silently succeeding', async () => {
|
||||
await project.fileStore.writeFile(
|
||||
'semantic-layer/warehouse/_schema/public.yaml',
|
||||
'tables:\n payments:\n table: public.payments\n columns:\n - name: id\n type: number\n',
|
||||
author,
|
||||
authorEmail,
|
||||
'seed manifest shard',
|
||||
);
|
||||
|
||||
await expect(service.deleteSource('warehouse', 'payments', author, authorEmail)).rejects.toThrow(
|
||||
/scan manifest/,
|
||||
);
|
||||
});
|
||||
|
||||
it('throws a plain not-found error for unknown sources', async () => {
|
||||
await expect(service.deleteSource('warehouse', 'missing', author, authorEmail)).rejects.toThrow(
|
||||
'Semantic-layer source not found: warehouse/missing',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
22
packages/cli/test/context/sl/sl-source-seeding.test-utils.ts
Normal file
22
packages/cli/test/context/sl/sl-source-seeding.test-utils.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import type { KtxFileWriteResult } from '../../../src/context/core/file-store.js';
|
||||
import type { KtxLocalProject } from '../../../src/context/project/project.js';
|
||||
import { slSourceFilePath } from '../../../src/context/sl/source-files.js';
|
||||
|
||||
/**
|
||||
* Seed a standalone/overlay semantic-layer file at the writer-derived path,
|
||||
* bypassing tool-level validation. Production writes go through
|
||||
* `SemanticLayerService.writeSource`; tests that only need a file on disk use
|
||||
* this instead.
|
||||
*/
|
||||
export async function seedSlSourceFile(
|
||||
project: KtxLocalProject,
|
||||
input: { connectionId: string; sourceName: string; yaml: string },
|
||||
): Promise<KtxFileWriteResult> {
|
||||
return project.fileStore.writeFile(
|
||||
slSourceFilePath(input.connectionId, input.sourceName),
|
||||
input.yaml,
|
||||
'ktx',
|
||||
'ktx@example.com',
|
||||
`Seed semantic-layer source: ${input.connectionId}/${input.sourceName}`,
|
||||
);
|
||||
}
|
||||
154
packages/cli/test/context/sl/source-files.test.ts
Normal file
154
packages/cli/test/context/sl/source-files.test.ts
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { initKtxProject, type KtxLocalProject } from '../../../src/context/project/project.js';
|
||||
import {
|
||||
resolveSlSourceFile,
|
||||
slSourceFileName,
|
||||
slSourceFilePath,
|
||||
slSourceNameForFile,
|
||||
} from '../../../src/context/sl/source-files.js';
|
||||
|
||||
describe('slSourceFileName', () => {
|
||||
it('keeps safe lowercase snake_case names verbatim', () => {
|
||||
expect(slSourceFileName('orders')).toBe('orders.yaml');
|
||||
expect(slSourceFileName('mart_account_segments')).toBe('mart_account_segments.yaml');
|
||||
expect(slSourceFileName('orders2')).toBe('orders2.yaml');
|
||||
});
|
||||
|
||||
it('derives a slug-hash filename for any other name and never throws', () => {
|
||||
expect(slSourceFileName('SIGNED_UP')).toMatch(/^signed_up-[0-9a-f]{8}\.yaml$/);
|
||||
expect(slSourceFileName('EVENT$LOG')).toMatch(/^event_log-[0-9a-f]{8}\.yaml$/);
|
||||
expect(slSourceFileName('my.dotted.name')).toMatch(/^my_dotted_name-[0-9a-f]{8}\.yaml$/);
|
||||
expect(slSourceFileName('汉字')).toMatch(/^src-[0-9a-f]{8}\.yaml$/);
|
||||
expect(slSourceFileName(' ')).toMatch(/^src-[0-9a-f]{8}\.yaml$/);
|
||||
});
|
||||
|
||||
it('is deterministic', () => {
|
||||
expect(slSourceFileName('EVENT$LOG')).toBe(slSourceFileName('EVENT$LOG'));
|
||||
});
|
||||
|
||||
it('never emits path separators or traversal segments', () => {
|
||||
for (const name of ['../orders', 'a/b', 'a\\b', '..', './x']) {
|
||||
const fileName = slSourceFileName(name);
|
||||
expect(fileName).not.toContain('/');
|
||||
expect(fileName).not.toContain('\\');
|
||||
expect(fileName).not.toContain('..');
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps case-differing names disjoint on case-insensitive filesystems', () => {
|
||||
// Safe-branch filenames contain no `-`; hash-branch filenames always end
|
||||
// in `-<8 hex>` with a hash of the raw name, so `events` vs `EVENTS`
|
||||
// cannot collide even when the filesystem folds case (macOS, Windows).
|
||||
const lower = slSourceFileName('events');
|
||||
const upper = slSourceFileName('EVENTS');
|
||||
expect(lower).toBe('events.yaml');
|
||||
expect(upper).toMatch(/^events-[0-9a-f]{8}\.yaml$/);
|
||||
expect(upper.toLowerCase()).not.toBe(lower.toLowerCase());
|
||||
expect(lower).not.toContain('-');
|
||||
});
|
||||
|
||||
it('routes Windows reserved device basenames through the hash branch', () => {
|
||||
expect(slSourceFileName('con')).toMatch(/^con-[0-9a-f]{8}\.yaml$/);
|
||||
expect(slSourceFileName('lpt1')).toMatch(/^lpt1-[0-9a-f]{8}\.yaml$/);
|
||||
});
|
||||
|
||||
it('caps overlong names', () => {
|
||||
const longName = `a${'b'.repeat(300)}`;
|
||||
const fileName = slSourceFileName(longName);
|
||||
expect(fileName.length).toBeLessThanOrEqual(64 + '-12345678.yaml'.length);
|
||||
expect(fileName).toMatch(/^ab+-[0-9a-f]{8}\.yaml$/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('slSourceFilePath', () => {
|
||||
it('rejects unsafe connection ids but accepts any source name', () => {
|
||||
expect(slSourceFilePath('warehouse', 'EVENT$LOG')).toMatch(
|
||||
/^semantic-layer\/warehouse\/event_log-[0-9a-f]{8}\.yaml$/,
|
||||
);
|
||||
expect(() => slSourceFilePath('../warehouse', 'orders')).toThrow('Unsafe connection id');
|
||||
});
|
||||
});
|
||||
|
||||
describe('slSourceNameForFile', () => {
|
||||
it('prefers the in-file name and falls back to the filename', () => {
|
||||
expect(slSourceNameForFile('semantic-layer/warehouse/custom.yaml', 'name: SIGNED_UP\n')).toBe('SIGNED_UP');
|
||||
expect(slSourceNameForFile('semantic-layer/warehouse/orders.yaml', 'measures: []\n')).toBe('orders');
|
||||
expect(slSourceNameForFile('semantic-layer/warehouse/orders.yaml', 'measures: [unterminated\n')).toBe('orders');
|
||||
});
|
||||
|
||||
it('recovers the declared name when the file is broken below the name: line', () => {
|
||||
// A human-renamed file left mid-edit keeps its identity: the syntax error is
|
||||
// under `measures:`, so the top-level `name:` is still recoverable and must
|
||||
// win over the (unrelated) filename.
|
||||
expect(slSourceNameForFile('semantic-layer/warehouse/renamed-by-hand.yaml', 'name: SIGNED_UP\nmeasures: [oops\n')).toBe(
|
||||
'SIGNED_UP',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveSlSourceFile', () => {
|
||||
let tempDir: string;
|
||||
let project: KtxLocalProject;
|
||||
|
||||
beforeEach(async () => {
|
||||
tempDir = await mkdtemp(join(tmpdir(), 'ktx-sl-source-files-'));
|
||||
project = await initKtxProject({ projectDir: join(tempDir, 'project') });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function seed(path: string, content: string): Promise<void> {
|
||||
await project.fileStore.writeFile(path, content, 'ktx', 'ktx@example.com', `seed ${path}`);
|
||||
}
|
||||
|
||||
it('matches by in-file name regardless of the filename', async () => {
|
||||
await seed('semantic-layer/warehouse/renamed-by-hand.yaml', 'name: SIGNED_UP\nmeasures: []\n');
|
||||
|
||||
await expect(resolveSlSourceFile(project.fileStore, 'warehouse', 'SIGNED_UP')).resolves.toEqual({
|
||||
path: 'semantic-layer/warehouse/renamed-by-hand.yaml',
|
||||
content: 'name: SIGNED_UP\nmeasures: []\n',
|
||||
});
|
||||
});
|
||||
|
||||
it('returns null when no file declares the name and ignores manifest shards', async () => {
|
||||
await seed('semantic-layer/warehouse/_schema/public.yaml', 'tables:\n orders:\n table: public.orders\n');
|
||||
|
||||
await expect(resolveSlSourceFile(project.fileStore, 'warehouse', 'orders')).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('falls back to the filename for broken YAML', async () => {
|
||||
const broken = 'name: orders\nmeasures: [unterminated\n';
|
||||
await seed('semantic-layer/warehouse/orders.yaml', broken);
|
||||
|
||||
await expect(resolveSlSourceFile(project.fileStore, 'warehouse', 'orders')).resolves.toEqual({
|
||||
path: 'semantic-layer/warehouse/orders.yaml',
|
||||
content: broken,
|
||||
});
|
||||
});
|
||||
|
||||
it('matches a human-renamed broken file by its still-recoverable name', async () => {
|
||||
// Filename ≠ name, so the filename fallback cannot find it; resolution must
|
||||
// come from the intact top-level `name:` even though the YAML is broken.
|
||||
const broken = 'name: SIGNED_UP\nmeasures: [unterminated\n';
|
||||
await seed('semantic-layer/warehouse/renamed-by-hand.yaml', broken);
|
||||
|
||||
await expect(resolveSlSourceFile(project.fileStore, 'warehouse', 'SIGNED_UP')).resolves.toEqual({
|
||||
path: 'semantic-layer/warehouse/renamed-by-hand.yaml',
|
||||
content: broken,
|
||||
});
|
||||
});
|
||||
|
||||
it('throws when two files declare the same source name', async () => {
|
||||
await seed('semantic-layer/warehouse/orders.yaml', 'name: orders\nmeasures: []\n');
|
||||
await seed('semantic-layer/warehouse/orders_copy.yaml', 'name: orders\nmeasures: []\n');
|
||||
|
||||
await expect(resolveSlSourceFile(project.fileStore, 'warehouse', 'orders')).rejects.toThrow(
|
||||
'Multiple semantic-layer files declare source "orders"',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -188,7 +188,7 @@ describe('SlEditSourceTool — manifest-backed source without overlay', () => {
|
|||
it('returns a directed hint pointing at sl_write_source + overlay shape', async () => {
|
||||
const { tool, semanticLayerService } = makeTool({
|
||||
semanticLayerService: {
|
||||
readSourceFile: vi.fn().mockRejectedValue(new Error('ENOENT')),
|
||||
readSourceFile: vi.fn().mockResolvedValue(null),
|
||||
isManifestBacked: vi.fn().mockResolvedValue(true),
|
||||
},
|
||||
});
|
||||
|
|
@ -222,7 +222,7 @@ describe('SlEditSourceTool — manifest-backed source without overlay', () => {
|
|||
it('still returns the plain "Source not found" error for truly-missing names', async () => {
|
||||
const { tool, semanticLayerService } = makeTool({
|
||||
semanticLayerService: {
|
||||
readSourceFile: vi.fn().mockRejectedValue(new Error('ENOENT')),
|
||||
readSourceFile: vi.fn().mockResolvedValue(null),
|
||||
isManifestBacked: vi.fn().mockResolvedValue(false),
|
||||
},
|
||||
});
|
||||
|
|
@ -241,3 +241,20 @@ describe('SlEditSourceTool — manifest-backed source without overlay', () => {
|
|||
expect(semanticLayerService.writeSource).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('SlEditSourceTool — name edits', () => {
|
||||
it('rejects edits that change the in-file name', async () => {
|
||||
const { tool, semanticLayerService } = makeTool();
|
||||
const result = await tool.call(
|
||||
{
|
||||
connectionId: '11111111-1111-1111-1111-111111111111',
|
||||
sourceName: 'orders',
|
||||
yaml_edits: [{ oldText: 'name: orders', newText: 'name: renamed_orders' }],
|
||||
} as any,
|
||||
baseContext,
|
||||
);
|
||||
expect(result.structured.success).toBe(false);
|
||||
expect(result.markdown).toMatch(/renaming is not supported/i);
|
||||
expect(semanticLayerService.writeSource).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -16,8 +16,15 @@ function makeSession(overrides: Partial<ToolSession> = {}): ToolSession {
|
|||
configService: {
|
||||
writeFile: vi.fn().mockResolvedValue(undefined),
|
||||
deleteFile: vi.fn().mockResolvedValue(undefined),
|
||||
// No live file for `orders` — revert recovers the preHead path from history.
|
||||
listFiles: vi.fn().mockResolvedValue({ files: [] }),
|
||||
readFile: vi.fn().mockRejectedValue(new Error('ENOENT')),
|
||||
} as any,
|
||||
gitService: {
|
||||
// The source lived at its derived filename at preHead.
|
||||
listFilesAtCommit: vi.fn().mockResolvedValue(['semantic-layer/conn-1/orders.yaml']),
|
||||
getFileAtCommit: vi.fn().mockResolvedValue('name: orders\nmeasures: []\n'),
|
||||
} as any,
|
||||
gitService: { getFileAtCommit: vi.fn().mockResolvedValue('pre: content') } as any,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
|
@ -65,4 +72,33 @@ describe('SlRollbackTool', () => {
|
|||
expect(hasTouchedSlSource(session.touchedSlSources, 'conn-1', 'orders')).toBe(false);
|
||||
expect(session.actions).toEqual([]);
|
||||
});
|
||||
|
||||
it('restores a deleted human-renamed source at the path it occupied at preHead', async () => {
|
||||
// The source lived at a custom filename (≠ the writer-derived `orders.yaml`)
|
||||
// and the session deleted it. Revert must recover the custom path from the
|
||||
// preHead commit and restore there, not write/no-op against the derived path.
|
||||
const slSourcesRepository = { deleteByConnectionAndName: vi.fn().mockResolvedValue(undefined) };
|
||||
const tool = new SlRollbackTool(slSourcesRepository as never, connections as never, 1);
|
||||
const renamedContent = 'name: orders\ntable: public.orders\nmeasures: []\n';
|
||||
const session = makeSession({
|
||||
gitService: {
|
||||
listFilesAtCommit: vi.fn().mockResolvedValue(['semantic-layer/conn-1/custom.yaml']),
|
||||
getFileAtCommit: vi.fn().mockResolvedValue(renamedContent),
|
||||
} as any,
|
||||
});
|
||||
const context: ToolContext = { sourceId: 's', messageId: 'm', userId: 'u', session };
|
||||
|
||||
const result = await tool.call({ sourceName: 'orders' } as any, context);
|
||||
|
||||
expect(result.structured.success).toBe(true);
|
||||
expect((session.configService as any).writeFile).toHaveBeenCalledWith(
|
||||
'semantic-layer/conn-1/custom.yaml',
|
||||
renamedContent,
|
||||
expect.anything(),
|
||||
expect.anything(),
|
||||
expect.anything(),
|
||||
expect.anything(),
|
||||
);
|
||||
expect((session.configService as any).deleteFile).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ function makeTool(overrides: Partial<Record<string, any>> = {}) {
|
|||
validateWithProposedSource: vi.fn().mockResolvedValue({ errors: [], warnings: [] }),
|
||||
writeSource: vi.fn().mockResolvedValue({ commitHash: 'c1' }),
|
||||
deleteSource: vi.fn().mockResolvedValue(undefined),
|
||||
readSourceFile: vi.fn().mockRejectedValue(new Error('not found')),
|
||||
readSourceFile: vi.fn().mockResolvedValue(null),
|
||||
...overrides.semanticLayerService,
|
||||
};
|
||||
const slSearchService = {
|
||||
|
|
@ -66,7 +66,7 @@ describe('SlWriteSourceTool — session gating', () => {
|
|||
deleteSource: vi.fn().mockResolvedValue(undefined),
|
||||
listManifestSourceNames: vi.fn().mockResolvedValue([]),
|
||||
isManifestBacked: vi.fn().mockResolvedValue(false),
|
||||
readSourceFile: vi.fn().mockRejectedValue(new Error('not found')),
|
||||
readSourceFile: vi.fn().mockResolvedValue(null),
|
||||
findManifestEntryByTableRef: vi.fn().mockResolvedValue(null),
|
||||
} as any,
|
||||
wikiService: {} as any,
|
||||
|
|
@ -248,7 +248,7 @@ describe('SlWriteSourceTool — session gating', () => {
|
|||
deleteSource: vi.fn().mockResolvedValue(undefined),
|
||||
listManifestSourceNames: vi.fn().mockResolvedValue(['mart_account_segments']),
|
||||
isManifestBacked: vi.fn().mockResolvedValue(false),
|
||||
readSourceFile: vi.fn().mockRejectedValue(new Error('not found')),
|
||||
readSourceFile: vi.fn().mockResolvedValue(null),
|
||||
findManifestEntryByTableRef: vi.fn().mockResolvedValue(null),
|
||||
} as any,
|
||||
});
|
||||
|
|
@ -377,3 +377,36 @@ describe('SlWriteSourceTool — standalone shadow guard', () => {
|
|||
expect(result.markdown).toMatch(/shadows an existing manifest entry|already exists/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SlWriteSourceTool — source name identity', () => {
|
||||
it('accepts verbatim warehouse identifiers as sourceName', () => {
|
||||
const { tool } = makeTool();
|
||||
const base = { connectionId: '11111111-1111-1111-1111-111111111111' };
|
||||
expect(tool.inputSchema.safeParse({ ...base, sourceName: 'SIGNED_UP' }).success).toBe(true);
|
||||
expect(tool.inputSchema.safeParse({ ...base, sourceName: 'EVENT$LOG' }).success).toBe(true);
|
||||
expect(tool.inputSchema.safeParse({ ...base, sourceName: 'orders' }).success).toBe(true);
|
||||
expect(tool.inputSchema.safeParse({ ...base, sourceName: '' }).success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a source whose name does not match sourceName', async () => {
|
||||
const { tool, semanticLayerService } = makeTool();
|
||||
const result = await tool.call(
|
||||
{
|
||||
connectionId: '11111111-1111-1111-1111-111111111111',
|
||||
sourceName: 'orders',
|
||||
source: {
|
||||
name: 'other_orders',
|
||||
sql: 'select 1 as id',
|
||||
grain: ['id'],
|
||||
columns: [{ name: 'id', type: 'string' }],
|
||||
measures: [],
|
||||
joins: [],
|
||||
} as any,
|
||||
} as any,
|
||||
baseContext,
|
||||
);
|
||||
expect(result.structured.success).toBe(false);
|
||||
expect(result.markdown).toMatch(/does not match sourceName/);
|
||||
expect(semanticLayerService.writeSource).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue