mirror of
https://github.com/Kaelio/ktx.git
synced 2026-06-22 08:38:08 +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
|
|
@ -1,5 +1,9 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { assertReadOnlySql, limitSqlForExecution } from '../../../src/context/connections/read-only-sql.js';
|
||||
import {
|
||||
assertReadOnlySql,
|
||||
limitSqlForExecution,
|
||||
stripTrailingSqlNoise,
|
||||
} from '../../../src/context/connections/read-only-sql.js';
|
||||
|
||||
describe('assertReadOnlySql', () => {
|
||||
it('allows select and with queries', () => {
|
||||
|
|
@ -15,6 +19,51 @@ describe('assertReadOnlySql', () => {
|
|||
'Only read-only SELECT/WITH queries can be executed locally',
|
||||
);
|
||||
});
|
||||
|
||||
it('accepts read-only queries that begin with leading comments', () => {
|
||||
expect(assertReadOnlySql('-- daily widget sales\nselect count(*) from public.widget_sales')).toBe(
|
||||
'select count(*) from public.widget_sales',
|
||||
);
|
||||
expect(assertReadOnlySql('/* block */\n with paid as (select 1) select * from paid')).toContain('with paid');
|
||||
});
|
||||
|
||||
it('still rejects mutating statements hidden behind leading comments', () => {
|
||||
expect(() => assertReadOnlySql('-- harmless\n delete from orders')).toThrow(
|
||||
'Only read-only SELECT/WITH queries can be executed locally',
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects a second statement smuggled after a semicolon', () => {
|
||||
expect(() => assertReadOnlySql('select 1; drop table orders')).toThrow(
|
||||
'Only one SQL statement can be executed.',
|
||||
);
|
||||
expect(() => assertReadOnlySql('select 1;\n-- pad\ndelete from orders')).toThrow(
|
||||
'Only one SQL statement can be executed.',
|
||||
);
|
||||
expect(() => assertReadOnlySql('select 1; /* pad */ truncate orders;')).toThrow(
|
||||
'Only one SQL statement can be executed.',
|
||||
);
|
||||
});
|
||||
|
||||
it('accepts trailing semicolons, including repeated ones followed by comments', () => {
|
||||
expect(assertReadOnlySql('select 1;')).toBe('select 1;');
|
||||
expect(assertReadOnlySql('select 1 ;; \n')).toBe('select 1 ;;');
|
||||
expect(assertReadOnlySql('select 1; -- done')).toBe('select 1; -- done');
|
||||
});
|
||||
|
||||
it('ignores semicolons inside string literals, quoted identifiers, and comments', () => {
|
||||
expect(assertReadOnlySql("select string_agg(name, '; ') from t")).toBe("select string_agg(name, '; ') from t");
|
||||
expect(assertReadOnlySql("select 'it''s; quoted' from t")).toBe("select 'it''s; quoted' from t");
|
||||
expect(assertReadOnlySql('select ";" from "t;u"')).toBe('select ";" from "t;u"');
|
||||
expect(assertReadOnlySql('select 1 -- tail; comment')).toBe('select 1 -- tail; comment');
|
||||
expect(assertReadOnlySql('select 1 /* a;b */ + 2')).toBe('select 1 /* a;b */ + 2');
|
||||
});
|
||||
|
||||
it('rejects statements smuggled after a string literal that closes a semicolon early', () => {
|
||||
expect(() => assertReadOnlySql("select 'a'; delete from orders")).toThrow(
|
||||
'Only one SQL statement can be executed.',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('limitSqlForExecution', () => {
|
||||
|
|
@ -27,4 +76,42 @@ describe('limitSqlForExecution', () => {
|
|||
it('returns the trimmed SQL when no maxRows value is provided', () => {
|
||||
expect(limitSqlForExecution('select * from orders; ', undefined)).toBe('select * from orders');
|
||||
});
|
||||
|
||||
it('strips leading comments before wrapping with a row limit', () => {
|
||||
expect(limitSqlForExecution('-- top customers\nselect * from public.orders', 25)).toBe(
|
||||
'select * from (select * from public.orders) as ktx_query_result limit 25',
|
||||
);
|
||||
});
|
||||
|
||||
it('drops a trailing semicolon followed by a comment so the subquery stays valid', () => {
|
||||
// The single-statement gate accepts `select 1; -- done`; without stripping
|
||||
// the terminator the wrapper would embed `select 1; -- done` and comment out
|
||||
// the closing paren and limit clause.
|
||||
expect(limitSqlForExecution('select 1; -- done', 5)).toBe(
|
||||
'select * from (select 1) as ktx_query_result limit 5',
|
||||
);
|
||||
expect(limitSqlForExecution('select 1; /* note */', 5)).toBe(
|
||||
'select * from (select 1) as ktx_query_result limit 5',
|
||||
);
|
||||
});
|
||||
|
||||
it('drops a trailing line comment with no semicolon before wrapping', () => {
|
||||
expect(limitSqlForExecution('select 1 -- done', 5)).toBe('select * from (select 1) as ktx_query_result limit 5');
|
||||
});
|
||||
});
|
||||
|
||||
describe('stripTrailingSqlNoise', () => {
|
||||
it('removes trailing semicolons, comments, and whitespace', () => {
|
||||
expect(stripTrailingSqlNoise('select 1;')).toBe('select 1');
|
||||
expect(stripTrailingSqlNoise('select 1 ;; ')).toBe('select 1');
|
||||
expect(stripTrailingSqlNoise('select 1; -- done')).toBe('select 1');
|
||||
expect(stripTrailingSqlNoise('select 1 -- done')).toBe('select 1');
|
||||
expect(stripTrailingSqlNoise('select 1; /* trailing */')).toBe('select 1');
|
||||
});
|
||||
|
||||
it('preserves semicolons and comment markers inside literals and mid-statement', () => {
|
||||
expect(stripTrailingSqlNoise("select 'a; -- b'")).toBe("select 'a; -- b'");
|
||||
expect(stripTrailingSqlNoise('select 1 /* a;b */ + 2')).toBe('select 1 /* a;b */ + 2');
|
||||
expect(stripTrailingSqlNoise('select ";" from "t;u"')).toBe('select ";" from "t;u"');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
|
||||
import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import type { KtxCoreConfig } from '../../../src/context/core/config.js';
|
||||
import { GitService } from '../../../src/context/core/git.service.js';
|
||||
|
|
@ -35,10 +35,29 @@ describe('GitService', () => {
|
|||
});
|
||||
|
||||
const writeAndCommit = async (filePath: string, content: string, message = 'msg') => {
|
||||
await mkdir(dirname(join(tempDir, filePath)), { recursive: true });
|
||||
await writeFile(join(tempDir, filePath), content, 'utf-8');
|
||||
return service.commitFile(filePath, message, 'Test', 'test@example.com');
|
||||
};
|
||||
|
||||
describe('listFilesAtCommit', () => {
|
||||
it('lists matching paths at a commit and recovers files deleted since', async () => {
|
||||
await writeAndCommit('semantic-layer/warehouse/custom.yaml', 'name: orders\n');
|
||||
const atSeed = await service.revParseHead();
|
||||
await service.deleteFile('semantic-layer/warehouse/custom.yaml', 'drop', 'Test', 'test@example.com');
|
||||
|
||||
// HEAD no longer has the file; the seed commit still does.
|
||||
await expect(service.listFilesAtCommit('semantic-layer/warehouse', 'HEAD')).resolves.toEqual([]);
|
||||
await expect(service.listFilesAtCommit('semantic-layer/warehouse', atSeed)).resolves.toEqual([
|
||||
'semantic-layer/warehouse/custom.yaml',
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns [] for a pathspec that matches nothing', async () => {
|
||||
await expect(service.listFilesAtCommit('does/not/exist', 'HEAD')).resolves.toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('cold-start bootstrap commit', () => {
|
||||
it('writes an empty commit on init so HEAD always resolves', async () => {
|
||||
// beforeEach already ran onModuleInit() against an empty temp dir.
|
||||
|
|
|
|||
|
|
@ -159,13 +159,16 @@ describe('reindexLocalIndexes', () => {
|
|||
'---\nsummary: Revenue\nusage_mode: auto\n---\n\nPaid orders.\n',
|
||||
'utf-8',
|
||||
);
|
||||
await mkdir(join(project.projectDir, 'semantic-layer/warehouse'), { recursive: true });
|
||||
await writeFile(join(project.projectDir, 'semantic-layer/warehouse/broken.yaml'), 'not: [valid', 'utf-8');
|
||||
// A broken standalone source is surfaced for repair rather than failing the
|
||||
// scope, so use a corrupt machine-generated manifest shard, which is the
|
||||
// remaining fatal read failure that the per-scope catch must isolate.
|
||||
await mkdir(join(project.projectDir, 'semantic-layer/warehouse/_schema'), { recursive: true });
|
||||
await writeFile(join(project.projectDir, 'semantic-layer/warehouse/_schema/broken.yaml'), 'not: [valid', 'utf-8');
|
||||
|
||||
const summary = await reindexLocalIndexes(project, { force: false, embeddingService: null });
|
||||
|
||||
expect(summary.scopes.find((scope) => scope.label === 'global')?.error).toBeUndefined();
|
||||
expect(summary.scopes.find((scope) => scope.label === 'warehouse')?.error).toContain('YAML');
|
||||
expect(summary.scopes.find((scope) => scope.label === 'warehouse')?.error).toContain('_schema/broken.yaml');
|
||||
});
|
||||
|
||||
it('marks a scope errored when configured embeddings fail', async () => {
|
||||
|
|
|
|||
|
|
@ -33,14 +33,14 @@ async function makeHarness() {
|
|||
}
|
||||
|
||||
describe('finalGateRepairPaths', () => {
|
||||
it('derives sorted wiki and semantic-layer file paths', () => {
|
||||
it('derives sorted, deduplicated wiki and semantic-layer file paths', () => {
|
||||
expect(
|
||||
finalGateRepairPaths({
|
||||
changedWikiPageKeys: ['account-segments', 'overview', 'account-segments'],
|
||||
touchedSlSources: [
|
||||
{ connectionId: 'warehouse', sourceName: 'mart_account_segments' },
|
||||
{ connectionId: 'warehouse', sourceName: 'orders' },
|
||||
{ connectionId: 'warehouse', sourceName: 'orders' },
|
||||
touchedSlSourcePaths: [
|
||||
'semantic-layer/warehouse/mart_account_segments.yaml',
|
||||
'semantic-layer/warehouse/orders.yaml',
|
||||
'semantic-layer/warehouse/orders.yaml',
|
||||
],
|
||||
}),
|
||||
).toEqual([
|
||||
|
|
|
|||
|
|
@ -18,19 +18,49 @@ describe('deriveFinalizationWikiPageKeys', () => {
|
|||
});
|
||||
|
||||
describe('deriveFinalizationTouchedSources', () => {
|
||||
it('maps standalone semantic-layer files directly', async () => {
|
||||
const result = await deriveFinalizationTouchedSources({
|
||||
it('resolves standalone files by the source diff, not the filename', () => {
|
||||
// The file carries a derived label (`signed_up-<hash>.yaml`); the source it
|
||||
// defines is the in-file `name:` (`SIGNED_UP`), visible only via the diff.
|
||||
const result = deriveFinalizationTouchedSources({
|
||||
changedPaths: ['semantic-layer/warehouse/signed_up-1a2b3c4d.yaml'],
|
||||
beforeSourcesByConnection: new Map([['warehouse', []]]),
|
||||
afterSourcesByConnection: new Map([
|
||||
['warehouse', [{ name: 'SIGNED_UP', grain: [], columns: [], joins: [], measures: [] }]],
|
||||
]),
|
||||
});
|
||||
expect(result).toEqual({
|
||||
touchedSources: [{ connectionId: 'warehouse', sourceName: 'SIGNED_UP' }],
|
||||
unresolvedPaths: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves deleted standalone files by the name that disappeared', () => {
|
||||
const result = deriveFinalizationTouchedSources({
|
||||
changedPaths: ['semantic-layer/warehouse/signed_up-1a2b3c4d.yaml'],
|
||||
beforeSourcesByConnection: new Map([
|
||||
['warehouse', [{ name: 'SIGNED_UP', grain: [], columns: [], joins: [], measures: [] }]],
|
||||
]),
|
||||
afterSourcesByConnection: new Map([['warehouse', []]]),
|
||||
});
|
||||
expect(result).toEqual({
|
||||
touchedSources: [{ connectionId: 'warehouse', sourceName: 'SIGNED_UP' }],
|
||||
unresolvedPaths: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('flags standalone changes that produce no source diff', () => {
|
||||
const result = deriveFinalizationTouchedSources({
|
||||
changedPaths: ['semantic-layer/warehouse/orders.yaml'],
|
||||
beforeSourcesByConnection: new Map(),
|
||||
afterSourcesByConnection: new Map(),
|
||||
});
|
||||
expect(result).toEqual({
|
||||
touchedSources: [{ connectionId: 'warehouse', sourceName: 'orders' }],
|
||||
unresolvedPaths: [],
|
||||
touchedSources: [],
|
||||
unresolvedPaths: ['semantic-layer/warehouse/orders.yaml'],
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves aggregate _schema changes by comparing loaded source snapshots', async () => {
|
||||
it('resolves aggregate _schema changes by comparing loaded source snapshots', () => {
|
||||
const beforeSourcesByConnection = new Map([
|
||||
[
|
||||
'warehouse',
|
||||
|
|
@ -72,7 +102,7 @@ describe('deriveFinalizationTouchedSources', () => {
|
|||
],
|
||||
]);
|
||||
|
||||
const result = await deriveFinalizationTouchedSources({
|
||||
const result = deriveFinalizationTouchedSources({
|
||||
changedPaths: ['semantic-layer/warehouse/_schema/public.yaml'],
|
||||
beforeSourcesByConnection,
|
||||
afterSourcesByConnection,
|
||||
|
|
@ -84,11 +114,11 @@ describe('deriveFinalizationTouchedSources', () => {
|
|||
});
|
||||
});
|
||||
|
||||
it('flags aggregate _schema changes that cannot be resolved to logical sources', async () => {
|
||||
it('flags aggregate _schema changes that cannot be resolved to logical sources', () => {
|
||||
const beforeSourcesByConnection = new Map([['warehouse', []]]);
|
||||
const afterSourcesByConnection = new Map([['warehouse', []]]);
|
||||
|
||||
const result = await deriveFinalizationTouchedSources({
|
||||
const result = deriveFinalizationTouchedSources({
|
||||
changedPaths: ['semantic-layer/warehouse/_schema/public.yaml'],
|
||||
beforeSourcesByConnection,
|
||||
afterSourcesByConnection,
|
||||
|
|
|
|||
|
|
@ -70,6 +70,15 @@ async function loadSourcesFromRoot(root: string) {
|
|||
};
|
||||
}
|
||||
|
||||
// Mirrors the production contract: resolve the standalone/overlay file for a
|
||||
// source, null when absent. Fixtures keep filename == name, so a direct read
|
||||
// is a faithful shortcut.
|
||||
async function readSourceFileFromRoot(root: string, connectionId: string, sourceName: string) {
|
||||
const relPath = `semantic-layer/${connectionId}/${sourceName}.yaml`;
|
||||
const content = await readFile(join(root, relPath), 'utf-8').catch(() => null);
|
||||
return content === null ? null : { content, path: relPath };
|
||||
}
|
||||
|
||||
async function listGlobalWikiPageKeys(root: string): Promise<string[]> {
|
||||
const dir = join(root, 'wiki/global');
|
||||
const entries = await readdir(dir).catch(() => []);
|
||||
|
|
@ -172,11 +181,17 @@ function makeDeps(
|
|||
const semanticLayerService: any = {
|
||||
loadAllSources: vi.fn(async () => loadSourcesFromRoot(runtime.configDir)),
|
||||
listFilesForConnection: vi.fn().mockResolvedValue(['mart_account_segments.yaml']),
|
||||
readSourceFile: vi.fn((connectionId: string, sourceName: string) =>
|
||||
readSourceFileFromRoot(runtime.configDir, connectionId, sourceName),
|
||||
),
|
||||
};
|
||||
semanticLayerService.forWorktree = vi.fn((workdir: string) => ({
|
||||
...semanticLayerService,
|
||||
loadAllSources: vi.fn(async () => loadSourcesFromRoot(workdir)),
|
||||
listFilesForConnection: vi.fn().mockResolvedValue(['mart_account_segments.yaml']),
|
||||
readSourceFile: vi.fn((connectionId: string, sourceName: string) =>
|
||||
readSourceFileFromRoot(workdir, connectionId, sourceName),
|
||||
),
|
||||
}));
|
||||
|
||||
const deps: IngestBundleRunnerDeps = {
|
||||
|
|
@ -2366,8 +2381,11 @@ describe('IngestBundleRunner isolated diff path', () => {
|
|||
join(runtime.configDir, '.ktx/ingest-traces/job-finalization-target-policy/trace.jsonl'),
|
||||
'utf-8',
|
||||
);
|
||||
expect(trace).toContain('finalization_committed');
|
||||
expect(trace).toContain('semantic_layer_target_policy');
|
||||
// The policy check runs inside finalization, before touched-source
|
||||
// derivation — an out-of-scope write fails the finalization stage
|
||||
// instead of reading as committed.
|
||||
expect(trace).not.toContain('finalization_committed');
|
||||
expect(trace).toContain('semantic_layer_target_policy_failed');
|
||||
expect(trace).toContain('ingest_failed');
|
||||
} finally {
|
||||
await rm(runtime.homeDir, { recursive: true, force: true });
|
||||
|
|
|
|||
|
|
@ -1776,12 +1776,24 @@ describe('IngestBundleRunner — Stages 1 → 7', () => {
|
|||
},
|
||||
],
|
||||
});
|
||||
deps.semanticLayerService.loadAllSources.mockImplementation((connectionId: string) =>
|
||||
Promise.resolve({ sources: [{ name: `${connectionId}_source` }], loadErrors: [] }),
|
||||
);
|
||||
let head = 'pre-finalization';
|
||||
// Touched-source derivation diffs composed sources before/after finalization
|
||||
// (the filename never carries identity), so the mock must reflect the write:
|
||||
// `orders` exists only once the finalization commit lands.
|
||||
deps.semanticLayerService.loadAllSources.mockImplementation((connectionId: string) =>
|
||||
Promise.resolve({
|
||||
sources:
|
||||
connectionId === 'warehouse-2' && head === 'post-finalization'
|
||||
? [{ name: `${connectionId}_source` }, { name: 'orders' }]
|
||||
: [{ name: `${connectionId}_source` }],
|
||||
loadErrors: [],
|
||||
}),
|
||||
);
|
||||
const git = {
|
||||
revParseHead: vi.fn(async () => head),
|
||||
// Touched-source derivation reads each changed file's `name:`; the worktree
|
||||
// is mocked (no files on disk), so serve the source content from history.
|
||||
getFileAtCommit: vi.fn(async () => 'name: orders\n'),
|
||||
commitFiles: vi.fn().mockImplementation(async (paths: string[]) => {
|
||||
if (paths.includes('semantic-layer/warehouse-2/orders.yaml')) {
|
||||
head = 'post-finalization';
|
||||
|
|
@ -1854,10 +1866,41 @@ describe('IngestBundleRunner — Stages 1 → 7', () => {
|
|||
}),
|
||||
);
|
||||
expect(deps.semanticLayerService.loadAllSources).toHaveBeenCalledWith('warehouse-2');
|
||||
expect(deps.slSearchService.indexSources).toHaveBeenCalledWith('warehouse-2', [{ name: 'warehouse-2_source' }]);
|
||||
expect(deps.slSearchService.indexSources).toHaveBeenCalledWith('warehouse-2', [
|
||||
{ name: 'warehouse-2_source' },
|
||||
{ name: 'orders' },
|
||||
]);
|
||||
expect(deps.sessionWorktreeService.cleanup).toHaveBeenCalledWith(expect.any(Object), 'success');
|
||||
});
|
||||
|
||||
it('recovers a deleted hash-named SL source by its in-file name, not its filename', async () => {
|
||||
const runner = buildRunner();
|
||||
// An uppercase warehouse source lives in a hash-derived filename, so parsing
|
||||
// the basename yields the phantom `widget_sales-1a2b3c4d`. The real name must
|
||||
// come from the file's `name:`, recovered from history once it was deleted.
|
||||
const deletedPath = 'semantic-layer/warehouse/widget_sales-1a2b3c4d.yaml';
|
||||
const getFileAtCommit = vi.fn(async () => 'name: WIDGET_SALES\ntable: WIDGET_SALES\n');
|
||||
const worktree = { workdir: join(tmpdir(), 'ktx-absent-worktree-recover'), git: { getFileAtCommit } };
|
||||
|
||||
const touched = await (runner as any).touchedSlSourcesFromPaths(worktree, [deletedPath], 'pre-change-sha');
|
||||
|
||||
expect(touched).toEqual([{ connectionId: 'warehouse', sourceName: 'WIDGET_SALES' }]);
|
||||
expect(getFileAtCommit).toHaveBeenCalledWith(deletedPath, 'pre-change-sha');
|
||||
});
|
||||
|
||||
it('falls back to the filename only when a deleted SL file is unrecoverable from history', async () => {
|
||||
const runner = buildRunner();
|
||||
const deletedPath = 'semantic-layer/warehouse/orders.yaml';
|
||||
const getFileAtCommit = vi.fn(async () => {
|
||||
throw new Error('path not present at commit');
|
||||
});
|
||||
const worktree = { workdir: join(tmpdir(), 'ktx-absent-worktree-fallback'), git: { getFileAtCommit } };
|
||||
|
||||
const touched = await (runner as any).touchedSlSourcesFromPaths(worktree, [deletedPath], 'pre-change-sha');
|
||||
|
||||
expect(touched).toEqual([{ connectionId: 'warehouse', sourceName: 'orders' }]);
|
||||
});
|
||||
|
||||
it('includes finalization actions in memory-flow saved counts', async () => {
|
||||
const deps = makeDeps();
|
||||
deps.adapter.source = 'historic-sql';
|
||||
|
|
|
|||
|
|
@ -1,13 +1,21 @@
|
|||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { SlConnectionCatalogPort } from '../../../../../src/context/sl/ports.js';
|
||||
import type { SqlAnalysisPort } from '../../../../../src/context/sql-analysis/ports.js';
|
||||
import type { ToolContext } from '../../../../../src/context/tools/base-tool.js';
|
||||
import { SqlExecutionTool } from '../../../../../src/context/ingest/tools/warehouse-verification/sql-execution.tool.js';
|
||||
|
||||
describe('SqlExecutionTool', () => {
|
||||
const connections = {
|
||||
executeQuery: vi.fn(),
|
||||
} as unknown as SlConnectionCatalogPort & { executeQuery: ReturnType<typeof vi.fn> };
|
||||
const tool = new SqlExecutionTool(connections);
|
||||
getConnectionById: vi.fn(async () => ({ id: 'warehouse', name: 'warehouse', connectionType: 'POSTGRESQL' })),
|
||||
} as unknown as SlConnectionCatalogPort & {
|
||||
executeQuery: ReturnType<typeof vi.fn>;
|
||||
getConnectionById: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
const sqlAnalysis = {
|
||||
validateReadOnly: vi.fn(async () => ({ ok: true, error: null })),
|
||||
} as unknown as SqlAnalysisPort & { validateReadOnly: ReturnType<typeof vi.fn> };
|
||||
const tool = new SqlExecutionTool(connections, sqlAnalysis);
|
||||
const context: ToolContext = {
|
||||
sourceId: 'ingest',
|
||||
messageId: 'm1',
|
||||
|
|
@ -15,7 +23,15 @@ describe('SqlExecutionTool', () => {
|
|||
session: { allowedConnectionNames: new Set(['warehouse']) } as any,
|
||||
};
|
||||
|
||||
it('wraps read-only SQL with a capped row limit', async () => {
|
||||
beforeEach(() => {
|
||||
connections.executeQuery.mockReset();
|
||||
connections.getConnectionById.mockReset();
|
||||
connections.getConnectionById.mockResolvedValue({ id: 'warehouse', name: 'warehouse', connectionType: 'POSTGRESQL' });
|
||||
sqlAnalysis.validateReadOnly.mockReset();
|
||||
sqlAnalysis.validateReadOnly.mockResolvedValue({ ok: true, error: null });
|
||||
});
|
||||
|
||||
it('validates with the parser-backed validator in the connection dialect, then wraps with a capped row limit', async () => {
|
||||
connections.executeQuery.mockResolvedValue({ headers: ['status'], rows: [['paid']], totalRows: 1 });
|
||||
|
||||
const result = await tool.call(
|
||||
|
|
@ -23,6 +39,7 @@ describe('SqlExecutionTool', () => {
|
|||
context,
|
||||
);
|
||||
|
||||
expect(sqlAnalysis.validateReadOnly).toHaveBeenCalledWith('select status from public.orders', 'postgres');
|
||||
expect(connections.executeQuery).toHaveBeenCalledWith(
|
||||
'warehouse',
|
||||
'select * from (select status from public.orders) as ktx_query_result limit 5',
|
||||
|
|
@ -31,15 +48,47 @@ describe('SqlExecutionTool', () => {
|
|||
expect(result.structured.wrappedSql).toContain('limit 5');
|
||||
});
|
||||
|
||||
it.each(['insert into x values (1)', 'drop table x', 'vacuum'])('rejects mutating SQL: %s', async (sql) => {
|
||||
connections.executeQuery.mockClear();
|
||||
it('maps connection types to sqlglot dialects', async () => {
|
||||
connections.getConnectionById.mockResolvedValue({ id: 'warehouse', name: 'warehouse', connectionType: 'SNOWFLAKE' });
|
||||
connections.executeQuery.mockResolvedValue({ headers: [], rows: [], totalRows: 0 });
|
||||
|
||||
const result = await tool.call({ connectionId: 'warehouse', sql }, context);
|
||||
await tool.call({ connectionId: 'warehouse', sql: 'select 1' }, context);
|
||||
|
||||
expect(result.markdown).toContain('Only read-only SELECT/WITH queries can be executed locally.');
|
||||
expect(sqlAnalysis.validateReadOnly).toHaveBeenCalledWith('select 1', 'snowflake');
|
||||
});
|
||||
|
||||
it('returns the validator error without executing when validation fails', async () => {
|
||||
sqlAnalysis.validateReadOnly.mockResolvedValue({ ok: false, error: 'SQL contains read/write operation: Insert' });
|
||||
|
||||
const result = await tool.call(
|
||||
{ connectionId: 'warehouse', sql: 'with x as (insert into t values (1) returning *) select * from x' },
|
||||
context,
|
||||
);
|
||||
|
||||
expect(result.markdown).toContain('SQL contains read/write operation: Insert');
|
||||
expect(result.structured.error).toContain('SQL contains read/write operation: Insert');
|
||||
expect(connections.executeQuery).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throws when no parser-backed validator is configured', async () => {
|
||||
const unvalidated = new SqlExecutionTool(connections);
|
||||
|
||||
await expect(unvalidated.call({ connectionId: 'warehouse', sql: 'select 1' }, context)).rejects.toThrow(
|
||||
'sql_execution requires parser-backed SQL validation.',
|
||||
);
|
||||
expect(connections.executeQuery).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(['insert into x values (1)', 'drop table x', 'vacuum'])(
|
||||
'keeps the local backstop even when the validator approves: %s',
|
||||
async (sql) => {
|
||||
const result = await tool.call({ connectionId: 'warehouse', sql }, context);
|
||||
|
||||
expect(result.markdown).toContain('Only read-only SELECT/WITH queries can be executed locally.');
|
||||
expect(connections.executeQuery).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('surfaces connector errors verbatim', async () => {
|
||||
connections.executeQuery.mockRejectedValue(new Error('relation "orbit_analytics.customer" does not exist'));
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|||
import { initKtxProject } from '../../../src/context/project/project.js';
|
||||
import { KtxQueryError } from '../../../src/errors.js';
|
||||
import { createKtxConnectorCapabilities, type KtxQueryResult, type KtxScanConnector, type KtxSchemaSnapshot } from '../../../src/context/scan/types.js';
|
||||
import { writeLocalSlSource } from '../../../src/context/sl/local-sl.js';
|
||||
import { SemanticLayerService } from '../../../src/context/sl/semantic-layer.service.js';
|
||||
import type { SemanticLayerSource } from '../../../src/context/sl/types.js';
|
||||
import { seedSlSourceFile } from '../sl/sl-source-seeding.test-utils.js';
|
||||
import { createLocalProjectMcpContextPorts } from '../../../src/context/mcp/local-project-ports.js';
|
||||
|
||||
describe('createLocalProjectMcpContextPorts', () => {
|
||||
|
|
@ -739,7 +741,7 @@ describe('createLocalProjectMcpContextPorts', () => {
|
|||
|
||||
it('reads seeded semantic-layer sources', async () => {
|
||||
const project = await initKtxProject({ projectDir: tempDir });
|
||||
await writeLocalSlSource(project, {
|
||||
await seedSlSourceFile(project, {
|
||||
connectionId: 'warehouse',
|
||||
sourceName: 'orders',
|
||||
yaml: [
|
||||
|
|
@ -763,7 +765,92 @@ describe('createLocalProjectMcpContextPorts', () => {
|
|||
});
|
||||
});
|
||||
|
||||
it('rejects path traversal keys before touching the project directory', async () => {
|
||||
it('reads manifest-backed sources with uppercase warehouse identifiers', async () => {
|
||||
const project = await initKtxProject({ projectDir: tempDir });
|
||||
await project.fileStore.writeFile(
|
||||
'semantic-layer/warehouse/_schema/PUBLIC.yaml',
|
||||
[
|
||||
'tables:',
|
||||
' WIDGET_SALES:',
|
||||
' table: PUBLIC.WIDGET_SALES',
|
||||
' columns:',
|
||||
' - name: ID',
|
||||
' type: number',
|
||||
' pk: true',
|
||||
'',
|
||||
].join('\n'),
|
||||
'ktx',
|
||||
'ktx@example.com',
|
||||
'seed uppercase manifest shard',
|
||||
);
|
||||
const ports = createLocalProjectMcpContextPorts(project, { embeddingService: null });
|
||||
|
||||
await expect(
|
||||
ports.semanticLayer?.readSource({ connectionId: 'warehouse', sourceName: 'WIDGET_SALES' }),
|
||||
).resolves.toMatchObject({
|
||||
sourceName: 'WIDGET_SALES',
|
||||
yaml: expect.stringContaining('table: PUBLIC.WIDGET_SALES'),
|
||||
});
|
||||
});
|
||||
|
||||
it('composes an overlay written for an uppercase manifest source at a derived filename', async () => {
|
||||
const project = await initKtxProject({ projectDir: tempDir });
|
||||
await project.fileStore.writeFile(
|
||||
'semantic-layer/warehouse/_schema/PUBLIC.yaml',
|
||||
[
|
||||
'tables:',
|
||||
' WIDGET_SALES:',
|
||||
' table: PUBLIC.WIDGET_SALES',
|
||||
' columns:',
|
||||
' - name: ID',
|
||||
' type: number',
|
||||
' pk: true',
|
||||
'',
|
||||
].join('\n'),
|
||||
'ktx',
|
||||
'ktx@example.com',
|
||||
'seed uppercase manifest shard',
|
||||
);
|
||||
|
||||
// The production write path: agents overlay manifest sources via
|
||||
// SemanticLayerService.writeSource using the verbatim warehouse name.
|
||||
const service = new SemanticLayerService(project.fileStore as never, {} as never, {} as never);
|
||||
const overlay = {
|
||||
name: 'WIDGET_SALES',
|
||||
measures: [{ name: 'widget_sales_count', expr: 'count(*)' }],
|
||||
} as SemanticLayerSource;
|
||||
const write = await service.writeSource('warehouse', overlay, 'ktx', 'ktx@example.com');
|
||||
expect(write.path).toMatch(/^semantic-layer\/warehouse\/widget_sales-[0-9a-f]{8}\.yaml$/);
|
||||
|
||||
const ports = createLocalProjectMcpContextPorts(project, { embeddingService: null });
|
||||
await expect(
|
||||
ports.semanticLayer?.readSource({ connectionId: 'warehouse', sourceName: 'WIDGET_SALES' }),
|
||||
).resolves.toMatchObject({
|
||||
sourceName: 'WIDGET_SALES',
|
||||
yaml: expect.stringContaining('widget_sales_count'),
|
||||
});
|
||||
});
|
||||
|
||||
it('returns a standalone source verbatim even when its YAML is currently broken', async () => {
|
||||
const project = await initKtxProject({ projectDir: tempDir });
|
||||
await project.fileStore.writeFile(
|
||||
'semantic-layer/warehouse/orders.yaml',
|
||||
'name: orders\nmeasures:\n - name: revenue\n expr: [unterminated\n',
|
||||
'ktx',
|
||||
'ktx@example.com',
|
||||
'seed broken source mid-edit',
|
||||
);
|
||||
const ports = createLocalProjectMcpContextPorts(project, { embeddingService: null });
|
||||
|
||||
await expect(
|
||||
ports.semanticLayer?.readSource({ connectionId: 'warehouse', sourceName: 'orders' }),
|
||||
).resolves.toMatchObject({
|
||||
sourceName: 'orders',
|
||||
yaml: expect.stringContaining('[unterminated'),
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps path-traversal keys away from the project directory', async () => {
|
||||
const project = await initKtxProject({ projectDir: tempDir });
|
||||
const ports = createLocalProjectMcpContextPorts(project, { embeddingService: null });
|
||||
|
||||
|
|
@ -774,12 +861,14 @@ describe('createLocalProjectMcpContextPorts', () => {
|
|||
}),
|
||||
).rejects.toThrow('Invalid wiki key "../outside". Wiki keys must be flat; use "outside".');
|
||||
|
||||
// Source reads never derive a file path from the name; a traversal-style
|
||||
// name simply matches no record.
|
||||
await expect(
|
||||
ports.semanticLayer?.readSource({
|
||||
connectionId: 'warehouse',
|
||||
sourceName: '../orders',
|
||||
}),
|
||||
).rejects.toThrow('Unsafe semantic-layer source name');
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('uses semantic compute for compile-only sl_query when supplied', async () => {
|
||||
|
|
@ -788,7 +877,7 @@ describe('createLocalProjectMcpContextPorts', () => {
|
|||
driver: 'postgres',
|
||||
url: 'env:DATABASE_URL',
|
||||
};
|
||||
await writeLocalSlSource(project, {
|
||||
await seedSlSourceFile(project, {
|
||||
connectionId: 'warehouse',
|
||||
sourceName: 'orders',
|
||||
yaml: [
|
||||
|
|
@ -850,7 +939,7 @@ describe('createLocalProjectMcpContextPorts', () => {
|
|||
driver: 'postgres',
|
||||
url: 'env:DATABASE_URL',
|
||||
};
|
||||
await writeLocalSlSource(project, {
|
||||
await seedSlSourceFile(project, {
|
||||
connectionId: 'warehouse',
|
||||
sourceName: 'orders',
|
||||
yaml: [
|
||||
|
|
|
|||
|
|
@ -357,6 +357,10 @@ describe('MemoryAgentService.gateRevertInvalidSources (J3)', () => {
|
|||
const configService = {
|
||||
writeFile: overrides.writeFile ?? vi.fn().mockResolvedValue({}),
|
||||
deleteFile: overrides.deleteFile ?? vi.fn().mockResolvedValue({}),
|
||||
// Revert resolves the live file by name; with no listing it falls back
|
||||
// to the writer-derived filename.
|
||||
listFiles: vi.fn().mockResolvedValue({ files: [] }),
|
||||
readFile: vi.fn().mockRejectedValue(new Error('ENOENT')),
|
||||
};
|
||||
const gitService = {
|
||||
getFileAtCommit: overrides.getFileAtCommit ?? vi.fn().mockRejectedValue(new Error('not present')),
|
||||
|
|
|
|||
|
|
@ -5,7 +5,8 @@ import { afterEach, beforeEach, describe, it } from 'vitest';
|
|||
import { SqliteContextEvidenceStore } from '../../../src/context/ingest/context-evidence/sqlite-context-evidence-store.js';
|
||||
import type { JsonValue } from '../../../src/context/ingest/ports.js';
|
||||
import { initKtxProject, type KtxLocalProject } from '../../../src/context/project/project.js';
|
||||
import { type LocalSlSourceSearchResult, searchLocalSlSources, writeLocalSlSource } from '../../../src/context/sl/local-sl.js';
|
||||
import { type LocalSlSourceSearchResult, searchLocalSlSources } from '../../../src/context/sl/local-sl.js';
|
||||
import { seedSlSourceFile } from '../sl/sl-source-seeding.test-utils.js';
|
||||
import type { ContextEvidenceSearchResult } from '../../../src/context/tools/context-evidence-tool-store.js';
|
||||
import {
|
||||
type LocalKnowledgeSearchResult,
|
||||
|
|
@ -99,12 +100,12 @@ function toContextConformanceResult(result: ContextEvidenceSearchResult): Search
|
|||
}
|
||||
|
||||
async function seedSemanticLayerProject(project: KtxLocalProject): Promise<void> {
|
||||
await writeLocalSlSource(project, {
|
||||
await seedSlSourceFile(project, {
|
||||
connectionId: 'warehouse',
|
||||
sourceName: 'orders',
|
||||
yaml: ORDERS_YAML,
|
||||
});
|
||||
await writeLocalSlSource(project, {
|
||||
await seedSlSourceFile(project, {
|
||||
connectionId: 'finance',
|
||||
sourceName: 'orders',
|
||||
yaml: FINANCE_ORDERS_YAML,
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
29
packages/cli/test/context/sql-analysis/dialect.test.ts
Normal file
29
packages/cli/test/context/sql-analysis/dialect.test.ts
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { sqlAnalysisDialectForDriver } from '../../../src/context/sql-analysis/dialect.js';
|
||||
|
||||
describe('sqlAnalysisDialectForDriver', () => {
|
||||
it('maps ktx.yaml driver names to sqlglot dialects', () => {
|
||||
expect(sqlAnalysisDialectForDriver('postgres')).toBe('postgres');
|
||||
expect(sqlAnalysisDialectForDriver('bigquery')).toBe('bigquery');
|
||||
expect(sqlAnalysisDialectForDriver('snowflake')).toBe('snowflake');
|
||||
expect(sqlAnalysisDialectForDriver('mysql')).toBe('mysql');
|
||||
expect(sqlAnalysisDialectForDriver('sqlserver')).toBe('tsql');
|
||||
expect(sqlAnalysisDialectForDriver('sqlite')).toBe('sqlite');
|
||||
expect(sqlAnalysisDialectForDriver('duckdb')).toBe('duckdb');
|
||||
expect(sqlAnalysisDialectForDriver('clickhouse')).toBe('clickhouse');
|
||||
expect(sqlAnalysisDialectForDriver('databricks')).toBe('databricks');
|
||||
});
|
||||
|
||||
it('maps local connection-type spellings to sqlglot dialects', () => {
|
||||
expect(sqlAnalysisDialectForDriver('POSTGRESQL')).toBe('postgres');
|
||||
expect(sqlAnalysisDialectForDriver('SQLSERVER')).toBe('tsql');
|
||||
expect(sqlAnalysisDialectForDriver('BIGQUERY')).toBe('bigquery');
|
||||
expect(sqlAnalysisDialectForDriver('SQLITE')).toBe('sqlite');
|
||||
});
|
||||
|
||||
it('defaults to postgres for unknown or missing drivers', () => {
|
||||
expect(sqlAnalysisDialectForDriver(undefined)).toBe('postgres');
|
||||
expect(sqlAnalysisDialectForDriver('')).toBe('postgres');
|
||||
expect(sqlAnalysisDialectForDriver('unknown')).toBe('postgres');
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue