mirror of
https://github.com/Kaelio/ktx.git
synced 2026-07-13 11:22:11 +02:00
test: split cli tests from source tree (#216)
* feat(cli): define full warehouse dialect contract
* test(cli): keep dialect edge tests focused
* fix(cli): stabilize dialect contract foundation
* refactor(connectors): own read-only query preparation
* refactor(connectors): resolve dialects through registry
* refactor(connectors): keep concrete dialect classes internal
* chore(workspace): enforce dialect import boundary
* refactor(cli): resolve relationship dialect at scan boundary
* refactor(cli): use dialect display parsing for entity details
* refactor(cli): use dialect display parsing for warehouse catalog
* refactor(cli): use dialect SQL in relationship workflows
* test(cli): verify solid dialect scan workflow closure
* test: split cli tests from source tree
* refactor(cli): standardize BigQuery scope listing
* feat(sqlite): implement connector scope listing
* test(connectors): cover required table listing
* feat(cli): add warehouse driver registry
* refactor(setup): route scope discovery through driver registry
* refactor(cli): route local query execution through driver registry
* refactor(historic-sql): route dialect support through driver registry
* refactor(cli): test warehouse connections through driver registry
* fix(cli): close driver registry type export gaps
* Improve setup daemon diagnostics
* refactor(setup): centralize rail-prefixed diagnostics + query-history fallback
Extract errorMessage, writePrefixedLines, and flushPrefixedBufferedCommandOutput
into clack.ts so the setup wizard, managed daemons, and embedding/agent steps
share one rail-formatted writer. setup-databases.ts also adds a
"disable query history and retry" option when the schema-context build fails
and query history is the likely culprit, surfaced via a new
failed-query-history-unavailable status.
* fix(cli): carry catalog through the picker so BigQuery/Snowflake/SQL Server scope filters match
The setup picker's KtxTableListEntry was a 2-level { schema, name }, so
qualifiedTableId always wrote db.name into enabled_tables. When BigQuery,
Snowflake, or SQL Server later ran fast ingest, their introspect step filtered
the scope set with scopedTableNames(scope, { catalog: projectId|database, db })
— catalog was non-null on the introspect side but null in the scope refs, so
every entry was rejected, the live-database adapter staged zero table files,
and detect() failed with 'Adapter "live-database" did not recognize fetched
source output'.
Align the picker boundary with the canonical 3-level KtxTableRef:
- Add catalog: string | null to KtxTableListEntry.
- BigQuery/Snowflake/SQL Server listTables populate catalog from the
resolved projectId / database; Postgres/MySQL/ClickHouse/SQLite set null.
- qualifiedTableId emits catalog.schema.name when catalog is non-null
(resolveEnabledTables already accepts the 3-part shape) and
schemasFromEnabledTables now goes through parseDottedTableEntry so it
recovers the schema correctly from both 2-part and 3-part entries.
- Export parseDottedTableEntry from enabled-tables.ts (@internal) for picker
reuse.
Update listTables expectations in all seven connector tests and the setup /
picker test fixtures. Add a picker regression test that covers the
catalog-bearing round-trip (save + refine).
* fix(cli): allow debug telemetry under opt-out env
This commit is contained in:
parent
924868841d
commit
56985b7e09
548 changed files with 5048 additions and 2228 deletions
|
|
@ -0,0 +1,473 @@
|
|||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
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 { ContextEvidenceSearchResult } from '../../../src/context/tools/context-evidence-tool-store.js';
|
||||
import {
|
||||
type LocalKnowledgeSearchResult,
|
||||
searchLocalKnowledgePages,
|
||||
writeLocalKnowledgePage,
|
||||
} from '../../../src/context/wiki/local-knowledge.js';
|
||||
import {
|
||||
assertSearchBackendCapabilities,
|
||||
assertSearchBackendConformanceCase,
|
||||
type SearchBackendConformanceResult,
|
||||
} from './backend-conformance.test-utils.js';
|
||||
import type { SearchBackendCapabilities } from '../../../src/context/search/types.js';
|
||||
|
||||
const SQLITE_SEARCH_CAPABILITIES = {
|
||||
fts: true,
|
||||
vector: false,
|
||||
fuzzy: false,
|
||||
jsonSearch: true,
|
||||
arraySearch: false,
|
||||
} satisfies SearchBackendCapabilities;
|
||||
|
||||
const ORDERS_YAML = [
|
||||
'name: orders',
|
||||
'table: public.orders',
|
||||
'grain:',
|
||||
' - order_id',
|
||||
'columns:',
|
||||
' - name: order_id',
|
||||
' type: string',
|
||||
' - name: revenue',
|
||||
' type: number',
|
||||
'measures:',
|
||||
' - name: total_revenue',
|
||||
' expr: sum(revenue)',
|
||||
'',
|
||||
].join('\n');
|
||||
|
||||
const FINANCE_ORDERS_YAML = [
|
||||
'name: orders',
|
||||
'descriptions:',
|
||||
' user: Finance orders used for invoice reconciliation.',
|
||||
'table: finance.orders',
|
||||
'grain:',
|
||||
' - order_id',
|
||||
'columns:',
|
||||
' - name: order_id',
|
||||
' type: string',
|
||||
' - name: invoice_status',
|
||||
' type: string',
|
||||
'',
|
||||
].join('\n');
|
||||
|
||||
class FakeEmbeddingPort {
|
||||
readonly maxBatchSize = 16;
|
||||
|
||||
async computeEmbedding(text: string): Promise<number[]> {
|
||||
return text.toLowerCase().includes('semantic revenue') ? [1, 0] : [0, 1];
|
||||
}
|
||||
|
||||
async computeEmbeddingsBulk(texts: string[]): Promise<number[][]> {
|
||||
return Promise.all(texts.map((text) => this.computeEmbedding(text)));
|
||||
}
|
||||
}
|
||||
|
||||
function toSlConformanceResult(result: LocalSlSourceSearchResult): SearchBackendConformanceResult {
|
||||
return {
|
||||
id: `${result.connectionId}/${result.name}`,
|
||||
score: result.score ?? 0,
|
||||
matchReasons: result.matchReasons ?? [],
|
||||
lanes: result.lanes,
|
||||
dictionaryMatches: result.dictionaryMatches,
|
||||
};
|
||||
}
|
||||
|
||||
function toWikiConformanceResult(result: LocalKnowledgeSearchResult): SearchBackendConformanceResult {
|
||||
return {
|
||||
id: result.key,
|
||||
score: result.score,
|
||||
matchReasons: result.matchReasons,
|
||||
lanes: result.lanes,
|
||||
};
|
||||
}
|
||||
|
||||
function toContextConformanceResult(result: ContextEvidenceSearchResult): SearchBackendConformanceResult {
|
||||
return {
|
||||
id: `${result.externalId}:${result.stableCitationKey}`,
|
||||
score: result.score,
|
||||
matchReasons: result.matchReasons ?? [],
|
||||
lanes: result.lanes,
|
||||
};
|
||||
}
|
||||
|
||||
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 project.fileStore.writeFile(
|
||||
'raw-sources/warehouse/live-database/sync-1/enrichment/relationship-profile.json',
|
||||
`${JSON.stringify(
|
||||
{
|
||||
connectionId: 'warehouse',
|
||||
driver: 'postgres',
|
||||
sqlAvailable: true,
|
||||
queryCount: 2,
|
||||
tables: [],
|
||||
columns: {
|
||||
'orders.status': {
|
||||
table: { catalog: null, db: 'public', name: 'orders' },
|
||||
column: 'status',
|
||||
nativeType: 'text',
|
||||
normalizedType: 'string',
|
||||
rowCount: 10,
|
||||
nullCount: 0,
|
||||
distinctCount: 2,
|
||||
uniquenessRatio: 0.2,
|
||||
nullRate: 0,
|
||||
sampleValues: ['paid', 'refunded'],
|
||||
minTextLength: 4,
|
||||
maxTextLength: 8,
|
||||
},
|
||||
},
|
||||
warnings: [],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
'ktx',
|
||||
'ktx@example.com',
|
||||
'Seed dictionary profile',
|
||||
);
|
||||
}
|
||||
|
||||
async function seedWikiProject(project: KtxLocalProject): Promise<void> {
|
||||
await writeLocalKnowledgePage(project, {
|
||||
key: 'metrics-revenue',
|
||||
scope: 'GLOBAL',
|
||||
summary: 'Semantic revenue definition',
|
||||
content: 'Revenue is recognized when an order is paid.',
|
||||
tags: ['finance'],
|
||||
refs: ['semantic-layer/warehouse/orders.yaml'],
|
||||
slRefs: ['orders'],
|
||||
});
|
||||
await writeLocalKnowledgePage(project, {
|
||||
key: 'support-escalations',
|
||||
scope: 'GLOBAL',
|
||||
summary: 'Support escalation process',
|
||||
content: 'Escalations move urgent support tickets to the operations queue.',
|
||||
tags: ['operations'],
|
||||
});
|
||||
}
|
||||
|
||||
async function seedContextDocument(
|
||||
subject: SqliteContextEvidenceStore,
|
||||
input: {
|
||||
runId?: string;
|
||||
syncId?: string;
|
||||
externalId?: string;
|
||||
title?: string;
|
||||
rawPath?: string;
|
||||
metadata?: JsonValue;
|
||||
publishState?: 'pending' | 'published';
|
||||
embedding?: number[] | null;
|
||||
content?: string;
|
||||
searchText?: string;
|
||||
} = {},
|
||||
): Promise<{ documentId: string; chunkId: string }> {
|
||||
const runId = input.runId ?? 'run-1';
|
||||
const syncId = input.syncId ?? 'sync-1';
|
||||
const externalId = input.externalId ?? 'page-1';
|
||||
const title = input.title ?? 'Revenue Policy';
|
||||
const rawPath = input.rawPath ?? `pages/${externalId}/page.md`;
|
||||
const doc = await subject.upsertDocument({
|
||||
runId,
|
||||
connectionId: 'conn-1',
|
||||
sourceKey: 'notion',
|
||||
externalId,
|
||||
externalParentId: null,
|
||||
databaseId: null,
|
||||
dataSourceId: null,
|
||||
title,
|
||||
path: `Company Handbook / ${title}`,
|
||||
url: `https://notion.test/${externalId}`,
|
||||
objectType: 'page',
|
||||
lastEditedAt: new Date('2026-04-30T10:00:00.000Z'),
|
||||
lastEditedBy: 'user-1',
|
||||
rawPath,
|
||||
syncId,
|
||||
contentHash: `hash-${externalId}`,
|
||||
publishState: input.publishState ?? 'published',
|
||||
metadata: input.metadata ?? {},
|
||||
});
|
||||
await subject.replaceChunks(doc.id, [
|
||||
{
|
||||
chunkKey: 'intro',
|
||||
headingPath: ['Policy'],
|
||||
ordinal: 0,
|
||||
content: input.content ?? `${title} requires approval from the accountable owner.`,
|
||||
searchText: input.searchText ?? `${title} approval accountable owner`,
|
||||
embedding: input.embedding ?? [1, 0, 0],
|
||||
tokenCount: 8,
|
||||
citation: {
|
||||
source: 'notion',
|
||||
pageId: externalId,
|
||||
title,
|
||||
syncId,
|
||||
rawPath,
|
||||
},
|
||||
stableCitationKey: `notion:${externalId}:intro`,
|
||||
syncId,
|
||||
contentHash: `chunk-${externalId}`,
|
||||
},
|
||||
]);
|
||||
|
||||
const read = await subject.readDocumentByExternalId('conn-1', 'notion', externalId, runId);
|
||||
if (!read) {
|
||||
throw new Error(`seeded document ${externalId} was not readable`);
|
||||
}
|
||||
|
||||
return { documentId: doc.id, chunkId: read.chunks[0].id };
|
||||
}
|
||||
|
||||
describe('SQLite hybrid search backend conformance', () => {
|
||||
let tempDir: string;
|
||||
let project: KtxLocalProject;
|
||||
let dbPath: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
tempDir = await mkdtemp(join(tmpdir(), 'ktx-search-conformance-'));
|
||||
project = await initKtxProject({ projectDir: join(tempDir, 'project') });
|
||||
dbPath = join(tempDir, '.ktx', 'db.sqlite');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('documents SQLite search backend capabilities', () => {
|
||||
assertSearchBackendCapabilities({
|
||||
backendName: 'sqlite',
|
||||
capabilities: SQLITE_SEARCH_CAPABILITIES,
|
||||
expected: {
|
||||
fts: true,
|
||||
vector: false,
|
||||
fuzzy: false,
|
||||
jsonSearch: true,
|
||||
arraySearch: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps semantic-layer global ranking, dictionary evidence, and token fallback stable', async () => {
|
||||
await seedSemanticLayerProject(project);
|
||||
|
||||
const global = await searchLocalSlSources(project, { query: 'orders', limit: 5 });
|
||||
assertSearchBackendConformanceCase({
|
||||
backendName: 'sqlite',
|
||||
surface: 'semantic-layer',
|
||||
caseName: 'global source ranking',
|
||||
results: global.map(toSlConformanceResult),
|
||||
expectedTopIds: ['finance/orders', 'warehouse/orders'],
|
||||
expectedReasonsById: {
|
||||
'finance/orders': ['lexical'],
|
||||
'warehouse/orders': ['lexical'],
|
||||
},
|
||||
expectedLanes: {
|
||||
lexical: { status: 'available' },
|
||||
semantic: { status: 'skipped', reason: 'embedding_unconfigured' },
|
||||
},
|
||||
});
|
||||
|
||||
const dictionary = await searchLocalSlSources(project, {
|
||||
connectionId: 'warehouse',
|
||||
query: 'refunded',
|
||||
limit: 5,
|
||||
});
|
||||
assertSearchBackendConformanceCase({
|
||||
backendName: 'sqlite',
|
||||
surface: 'semantic-layer',
|
||||
caseName: 'dictionary source evidence',
|
||||
results: dictionary.map(toSlConformanceResult),
|
||||
expectedTopIds: ['warehouse/orders'],
|
||||
expectedReasonsById: {
|
||||
'warehouse/orders': ['dictionary'],
|
||||
},
|
||||
expectedLanes: {
|
||||
dictionary: { status: 'available' },
|
||||
semantic: { status: 'skipped', reason: 'embedding_unconfigured' },
|
||||
},
|
||||
expectedDictionaryMatchesById: {
|
||||
'warehouse/orders': [{ column: 'status', values: ['refunded'] }],
|
||||
},
|
||||
});
|
||||
|
||||
const token = await searchLocalSlSources(project, {
|
||||
connectionId: 'warehouse',
|
||||
query: 'orders---',
|
||||
limit: 5,
|
||||
});
|
||||
assertSearchBackendConformanceCase({
|
||||
backendName: 'sqlite',
|
||||
surface: 'semantic-layer',
|
||||
caseName: 'token fallback reason',
|
||||
results: token.map(toSlConformanceResult),
|
||||
expectedTopIds: ['warehouse/orders'],
|
||||
expectedReasonsById: {
|
||||
'warehouse/orders': ['token'],
|
||||
},
|
||||
expectedLanes: {
|
||||
token: { status: 'available' },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps wiki lexical, semantic, and token behavior stable', async () => {
|
||||
await seedWikiProject(project);
|
||||
|
||||
const lexical = await searchLocalKnowledgePages(project, {
|
||||
query: 'paid order',
|
||||
userId: 'local',
|
||||
limit: 5,
|
||||
});
|
||||
assertSearchBackendConformanceCase({
|
||||
backendName: 'sqlite',
|
||||
surface: 'wiki',
|
||||
caseName: 'lexical page ranking',
|
||||
results: lexical.map(toWikiConformanceResult),
|
||||
expectedTopIds: ['metrics-revenue'],
|
||||
expectedReasonsById: {
|
||||
'metrics-revenue': ['lexical'],
|
||||
},
|
||||
expectedLanes: {
|
||||
lexical: { status: 'available' },
|
||||
semantic: { status: 'skipped', reason: 'embedding_unconfigured' },
|
||||
},
|
||||
});
|
||||
|
||||
const semantic = await searchLocalKnowledgePages(project, {
|
||||
query: 'semantic revenue',
|
||||
userId: 'local',
|
||||
limit: 5,
|
||||
embeddingService: new FakeEmbeddingPort(),
|
||||
});
|
||||
assertSearchBackendConformanceCase({
|
||||
backendName: 'sqlite',
|
||||
surface: 'wiki',
|
||||
caseName: 'semantic page ranking',
|
||||
results: semantic.map(toWikiConformanceResult),
|
||||
expectedTopIds: ['metrics-revenue'],
|
||||
expectedReasonsById: {
|
||||
'metrics-revenue': ['semantic'],
|
||||
},
|
||||
expectedLanes: {
|
||||
semantic: { status: 'available' },
|
||||
},
|
||||
});
|
||||
|
||||
const token = await searchLocalKnowledgePages(project, {
|
||||
query: 'paid---',
|
||||
userId: 'local',
|
||||
limit: 5,
|
||||
});
|
||||
assertSearchBackendConformanceCase({
|
||||
backendName: 'sqlite',
|
||||
surface: 'wiki',
|
||||
caseName: 'token page fallback',
|
||||
results: token.map(toWikiConformanceResult),
|
||||
expectedTopIds: ['metrics-revenue'],
|
||||
expectedReasonsById: {
|
||||
'metrics-revenue': ['token'],
|
||||
},
|
||||
expectedLanes: {
|
||||
token: { status: 'available' },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps context-evidence lane fusion and token fallback stable', async () => {
|
||||
const subject = new SqliteContextEvidenceStore({ dbPath });
|
||||
await seedContextDocument(subject, {
|
||||
externalId: 'page-discount',
|
||||
title: 'Enterprise Discount Policy',
|
||||
content: 'Enterprise discounts require finance approval before quote approval.',
|
||||
searchText: 'enterprise discount finance approval quote',
|
||||
embedding: [1, 0, 0],
|
||||
});
|
||||
await seedContextDocument(subject, {
|
||||
externalId: 'page-owner',
|
||||
title: 'Accountable Owner Policy',
|
||||
content: 'Every policy has an accountable owner and review date.',
|
||||
searchText: 'accountable owner review date',
|
||||
embedding: [0.95, 0.05, 0],
|
||||
});
|
||||
await seedContextDocument(subject, {
|
||||
externalId: 'page-expense',
|
||||
title: 'Expense Policy',
|
||||
content: 'Expense reimbursement requires receipt review.',
|
||||
searchText: 'expense reimbursement receipt review',
|
||||
embedding: [0, 1, 0],
|
||||
});
|
||||
|
||||
const fused = await subject.searchRRF({
|
||||
connectionId: 'conn-1',
|
||||
sourceKey: 'notion',
|
||||
queryEmbedding: [1, 0, 0],
|
||||
queryText: 'enterprise discount approval',
|
||||
limit: 2,
|
||||
includeDeleted: false,
|
||||
});
|
||||
assertSearchBackendConformanceCase({
|
||||
backendName: 'sqlite',
|
||||
surface: 'context-evidence',
|
||||
caseName: 'chunk lane fusion',
|
||||
results: fused.map(toContextConformanceResult),
|
||||
expectedTopIds: ['page-discount:notion:page-discount:intro'],
|
||||
expectedReasonsById: {
|
||||
'page-discount:notion:page-discount:intro': ['lexical', 'semantic', 'token'],
|
||||
},
|
||||
expectedLanes: {
|
||||
lexical: { status: 'available' },
|
||||
semantic: { status: 'available' },
|
||||
token: { status: 'available' },
|
||||
},
|
||||
});
|
||||
|
||||
const tokenSubject = new SqliteContextEvidenceStore({ dbPath: join(tempDir, 'token.sqlite') });
|
||||
await seedContextDocument(tokenSubject, {
|
||||
externalId: 'page-cpp',
|
||||
title: 'C++ Warehouse Notes',
|
||||
content: 'C++ parser notes for warehouse extraction.',
|
||||
searchText: 'C++ parser warehouse extraction',
|
||||
embedding: null,
|
||||
});
|
||||
|
||||
const token = await tokenSubject.searchRRF({
|
||||
connectionId: 'conn-1',
|
||||
sourceKey: 'notion',
|
||||
queryEmbedding: null,
|
||||
queryText: '++',
|
||||
limit: 5,
|
||||
includeDeleted: false,
|
||||
});
|
||||
assertSearchBackendConformanceCase({
|
||||
backendName: 'sqlite',
|
||||
surface: 'context-evidence',
|
||||
caseName: 'fts-empty token fallback',
|
||||
results: token.map(toContextConformanceResult),
|
||||
expectedTopIds: ['page-cpp:notion:page-cpp:intro'],
|
||||
expectedReasonsById: {
|
||||
'page-cpp:notion:page-cpp:intro': ['token'],
|
||||
},
|
||||
expectedLanes: {
|
||||
lexical: { status: 'skipped', reason: 'fts_query_empty' },
|
||||
semantic: { status: 'skipped', reason: 'embedding_unconfigured' },
|
||||
token: { status: 'available' },
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,151 @@
|
|||
import type { SearchBackendCapabilities, SearchLaneStatus } from '../../../src/context/search/types.js';
|
||||
|
||||
export interface SearchBackendConformanceLane {
|
||||
lane: string;
|
||||
status: SearchLaneStatus;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export interface SearchBackendConformanceDictionaryMatch {
|
||||
column: string;
|
||||
values: readonly string[];
|
||||
overflowCount?: number;
|
||||
}
|
||||
|
||||
export interface SearchBackendConformanceResult {
|
||||
id: string;
|
||||
score: number;
|
||||
matchReasons: readonly string[];
|
||||
lanes?: readonly SearchBackendConformanceLane[];
|
||||
dictionaryMatches?: readonly SearchBackendConformanceDictionaryMatch[];
|
||||
}
|
||||
|
||||
export interface ExpectedSearchBackendConformanceLane {
|
||||
status: SearchLaneStatus;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export interface AssertSearchBackendConformanceCaseInput {
|
||||
backendName: string;
|
||||
surface: string;
|
||||
caseName: string;
|
||||
results: readonly SearchBackendConformanceResult[];
|
||||
expectedTopIds: readonly string[];
|
||||
expectedReasonsById?: Record<string, readonly string[]>;
|
||||
expectedLanes?: Record<string, ExpectedSearchBackendConformanceLane>;
|
||||
expectedDictionaryMatchesById?: Record<string, readonly SearchBackendConformanceDictionaryMatch[]>;
|
||||
}
|
||||
|
||||
export interface AssertSearchBackendCapabilitiesInput {
|
||||
backendName: string;
|
||||
capabilities: SearchBackendCapabilities;
|
||||
expected: Partial<SearchBackendCapabilities>;
|
||||
}
|
||||
|
||||
function caseLabel(
|
||||
input: Pick<AssertSearchBackendConformanceCaseInput, 'backendName' | 'surface' | 'caseName'>,
|
||||
): string {
|
||||
return `${input.backendName} ${input.surface} conformance case "${input.caseName}"`;
|
||||
}
|
||||
|
||||
function fail(label: string, failures: string[]): never {
|
||||
throw new Error([`${label} failed:`, ...failures.map((failure) => `- ${failure}`)].join('\n'));
|
||||
}
|
||||
|
||||
function dictionaryMatchKey(match: SearchBackendConformanceDictionaryMatch): string {
|
||||
const values = [...match.values].sort((left, right) => left.localeCompare(right)).join(',');
|
||||
return `${match.column}:${values}:${match.overflowCount ?? 0}`;
|
||||
}
|
||||
|
||||
function dictionaryMatchKeys(matches: readonly SearchBackendConformanceDictionaryMatch[] | undefined): string[] {
|
||||
return (matches ?? []).map(dictionaryMatchKey).sort((left, right) => left.localeCompare(right));
|
||||
}
|
||||
|
||||
export function assertSearchBackendConformanceCase(input: AssertSearchBackendConformanceCaseInput): void {
|
||||
const label = caseLabel(input);
|
||||
const failures: string[] = [];
|
||||
const topResults = input.results.slice(0, input.expectedTopIds.length);
|
||||
|
||||
input.expectedTopIds.forEach((expectedId, index) => {
|
||||
const actualId = topResults[index]?.id;
|
||||
if (actualId !== expectedId) {
|
||||
failures.push(`expected result ${index + 1} to be ${expectedId}, got ${actualId ?? '<missing>'}`);
|
||||
}
|
||||
});
|
||||
|
||||
const byId = new Map(input.results.map((result) => [result.id, result]));
|
||||
|
||||
for (const expectedId of input.expectedTopIds) {
|
||||
const result = byId.get(expectedId);
|
||||
if (!result) {
|
||||
continue;
|
||||
}
|
||||
if (!Number.isFinite(result.score) || result.score <= 0) {
|
||||
failures.push(`expected ${expectedId} to have a positive finite score, got ${result.score}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [id, expectedReasons] of Object.entries(input.expectedReasonsById ?? {})) {
|
||||
const result = byId.get(id);
|
||||
if (!result) {
|
||||
failures.push(`expected reasons for ${id}, but the result was missing`);
|
||||
continue;
|
||||
}
|
||||
for (const reason of expectedReasons) {
|
||||
if (!result.matchReasons.includes(reason)) {
|
||||
failures.push(`expected ${id} to include match reason ${reason}, got [${result.matchReasons.join(', ')}]`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const allLanes = input.results.flatMap((result) => result.lanes ?? []);
|
||||
for (const [lane, expected] of Object.entries(input.expectedLanes ?? {})) {
|
||||
const actual = allLanes.find((entry) => entry.lane === lane);
|
||||
if (!actual) {
|
||||
failures.push(`expected lane ${lane} to be reported`);
|
||||
continue;
|
||||
}
|
||||
if (actual.status !== expected.status) {
|
||||
failures.push(`expected lane ${lane} status ${expected.status}, got ${actual.status}`);
|
||||
}
|
||||
if (expected.reason !== undefined && actual.reason !== expected.reason) {
|
||||
failures.push(`expected lane ${lane} reason ${expected.reason}, got ${actual.reason ?? '<missing>'}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [id, expectedMatches] of Object.entries(input.expectedDictionaryMatchesById ?? {})) {
|
||||
const result = byId.get(id);
|
||||
if (!result) {
|
||||
failures.push(`expected dictionary matches for ${id}, but the result was missing`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const actualKeys = dictionaryMatchKeys(result.dictionaryMatches);
|
||||
for (const expectedKey of dictionaryMatchKeys(expectedMatches)) {
|
||||
if (!actualKeys.includes(expectedKey)) {
|
||||
failures.push(`expected ${id} dictionary evidence ${expectedKey}, got [${actualKeys.join(', ')}]`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (failures.length > 0) {
|
||||
fail(label, failures);
|
||||
}
|
||||
}
|
||||
|
||||
export function assertSearchBackendCapabilities(input: AssertSearchBackendCapabilitiesInput): void {
|
||||
const failures: string[] = [];
|
||||
|
||||
for (const [capability, expected] of Object.entries(input.expected) as Array<
|
||||
[keyof SearchBackendCapabilities, boolean]
|
||||
>) {
|
||||
const actual = input.capabilities[capability];
|
||||
if (actual !== expected) {
|
||||
failures.push(`expected ${capability}=${expected}, got ${actual}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (failures.length > 0) {
|
||||
fail(`${input.backendName} search backend capabilities`, failures);
|
||||
}
|
||||
}
|
||||
264
packages/cli/test/context/search/discover.test.ts
Normal file
264
packages/cli/test/context/search/discover.test.ts
Normal file
|
|
@ -0,0 +1,264 @@
|
|||
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 { writeLocalKnowledgePage } from '../../../src/context/wiki/local-knowledge.js';
|
||||
import { createKtxDiscoverDataService } from '../../../src/context/search/discover.js';
|
||||
|
||||
describe('createKtxDiscoverDataService', () => {
|
||||
let tempDir: string;
|
||||
let project: KtxLocalProject;
|
||||
|
||||
beforeEach(async () => {
|
||||
tempDir = await mkdtemp(join(tmpdir(), 'ktx-discover-data-'));
|
||||
project = await initKtxProject({ projectDir: join(tempDir, 'project') });
|
||||
project.config.connections.warehouse = { driver: 'postgres', url: 'env:DATABASE_URL' };
|
||||
project.config.connections.billing = { driver: 'postgres', url: 'env:BILLING_DATABASE_URL' };
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function seedWiki(): Promise<void> {
|
||||
await writeLocalKnowledgePage(project, {
|
||||
key: 'orders-playbook',
|
||||
scope: 'GLOBAL',
|
||||
summary: 'Paid order operations',
|
||||
content: 'Use paid orders and order_count to inspect monthly customer activity for Acme Corp.',
|
||||
tags: ['orders'],
|
||||
});
|
||||
}
|
||||
|
||||
async function seedSl(): Promise<void> {
|
||||
await project.fileStore.writeFile(
|
||||
'semantic-layer/warehouse/orders.yaml',
|
||||
[
|
||||
'name: orders',
|
||||
'descriptions:',
|
||||
' user: Paid order facts',
|
||||
'table: public.orders',
|
||||
'grain: [id]',
|
||||
'columns:',
|
||||
' - name: status',
|
||||
' type: string',
|
||||
' descriptions:',
|
||||
' user: Payment status for the order',
|
||||
' - name: ordered_at',
|
||||
' type: time',
|
||||
'measures:',
|
||||
' - name: order_count',
|
||||
' expr: count(*)',
|
||||
' description: Number of paid orders',
|
||||
'',
|
||||
].join('\n'),
|
||||
'ktx',
|
||||
'ktx@example.com',
|
||||
'seed sl source',
|
||||
);
|
||||
}
|
||||
|
||||
async function seedScan(input: {
|
||||
connectionId?: string;
|
||||
syncId: string;
|
||||
tableName?: string;
|
||||
comment?: string;
|
||||
sampleValues?: string[];
|
||||
}): Promise<void> {
|
||||
const connectionId = input.connectionId ?? 'warehouse';
|
||||
const root = `raw-sources/${connectionId}/live-database/${input.syncId}`;
|
||||
const tableName = input.tableName ?? 'orders';
|
||||
await project.fileStore.writeFile(
|
||||
`${root}/connection.json`,
|
||||
JSON.stringify(
|
||||
{
|
||||
connectionId,
|
||||
driver: 'postgres',
|
||||
extractedAt: `2026-05-14T09:00:00.000Z`,
|
||||
scope: { schemas: ['public'] },
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
'ktx',
|
||||
'ktx@example.com',
|
||||
'seed scan connection',
|
||||
);
|
||||
await project.fileStore.writeFile(
|
||||
`${root}/tables/public-${tableName}.json`,
|
||||
JSON.stringify(
|
||||
{
|
||||
catalog: null,
|
||||
db: 'public',
|
||||
name: tableName,
|
||||
kind: 'table',
|
||||
comment: input.comment ?? 'Orders table from warehouse',
|
||||
estimatedRows: 123,
|
||||
descriptions: { db: input.comment ?? 'Orders table from warehouse' },
|
||||
columns: [
|
||||
{
|
||||
name: 'id',
|
||||
nativeType: 'integer',
|
||||
normalizedType: 'integer',
|
||||
dimensionType: 'number',
|
||||
nullable: false,
|
||||
primaryKey: true,
|
||||
comment: 'Order id',
|
||||
},
|
||||
{
|
||||
name: 'status',
|
||||
nativeType: 'text',
|
||||
normalizedType: 'text',
|
||||
dimensionType: 'string',
|
||||
nullable: false,
|
||||
primaryKey: false,
|
||||
comment: 'Order status',
|
||||
sampleValues: input.sampleValues ?? ['paid', 'pending'],
|
||||
},
|
||||
],
|
||||
foreignKeys: [],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
'ktx',
|
||||
'ktx@example.com',
|
||||
'seed table',
|
||||
);
|
||||
await project.fileStore.writeFile(
|
||||
`${root}/scan-report.json`,
|
||||
JSON.stringify(
|
||||
{
|
||||
connectionId,
|
||||
driver: 'postgres',
|
||||
syncId: input.syncId,
|
||||
runId: `scan-${input.syncId}`,
|
||||
trigger: 'mcp',
|
||||
mode: 'enriched',
|
||||
dryRun: false,
|
||||
artifactPaths: {
|
||||
rawSourcesDir: root,
|
||||
reportPath: `${root}/scan-report.json`,
|
||||
manifestShards: [],
|
||||
enrichmentArtifacts: [],
|
||||
},
|
||||
diffSummary: {
|
||||
tablesAdded: 1,
|
||||
tablesModified: 0,
|
||||
tablesDeleted: 0,
|
||||
tablesUnchanged: 0,
|
||||
columnsAdded: 0,
|
||||
columnsModified: 0,
|
||||
columnsDeleted: 0,
|
||||
},
|
||||
manifestShardsWritten: 0,
|
||||
structuralSyncStats: {
|
||||
tablesCreated: 0,
|
||||
tablesUpdated: 0,
|
||||
tablesDeleted: 0,
|
||||
columnsCreated: 0,
|
||||
columnsUpdated: 0,
|
||||
columnsDeleted: 0,
|
||||
},
|
||||
enrichment: {
|
||||
dataDictionary: 'completed',
|
||||
tableDescriptions: 'completed',
|
||||
columnDescriptions: 'completed',
|
||||
embeddings: 'skipped',
|
||||
deterministicRelationships: 'skipped',
|
||||
llmRelationshipValidation: 'skipped',
|
||||
statisticalValidation: 'skipped',
|
||||
},
|
||||
capabilityGaps: [],
|
||||
warnings: [],
|
||||
relationships: { accepted: 0, review: 0, rejected: 0, skipped: 0 },
|
||||
enrichmentState: { resumedStages: [], completedStages: [], failedStages: [] },
|
||||
createdAt: '2026-05-14T09:00:00.000Z',
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
'ktx',
|
||||
'ktx@example.com',
|
||||
'seed scan report',
|
||||
);
|
||||
}
|
||||
|
||||
it('returns unified ranked refs across wiki, semantic-layer, and raw schema', async () => {
|
||||
await seedWiki();
|
||||
await seedSl();
|
||||
await seedScan({ syncId: 'sync-1', sampleValues: ['paid', 'refunded'] });
|
||||
const service = createKtxDiscoverDataService(project, { userId: 'local-user' });
|
||||
|
||||
const results = await service.search({ query: 'paid orders', connectionId: 'warehouse', limit: 10 });
|
||||
|
||||
expect(results.map((result) => result.kind)).toEqual(
|
||||
expect.arrayContaining(['wiki', 'sl_source', 'sl_measure', 'sl_dimension', 'table', 'column']),
|
||||
);
|
||||
expect(results.every((result) => result.score >= 0 && result.score <= 1)).toBe(true);
|
||||
expect(results.every((result) => result.snippet === null || result.snippet.length <= 200)).toBe(true);
|
||||
expect(results).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: 'table',
|
||||
id: 'public.orders',
|
||||
connectionId: 'warehouse',
|
||||
tableRef: { catalog: null, db: 'public', name: 'orders' },
|
||||
matchedOn: expect.stringMatching(/name|description|comment|display/),
|
||||
}),
|
||||
);
|
||||
expect(results).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: 'column',
|
||||
id: 'public.orders.status',
|
||||
connectionId: 'warehouse',
|
||||
columnName: 'status',
|
||||
matchedOn: expect.stringMatching(/name|comment|description|sample_value/),
|
||||
}),
|
||||
);
|
||||
expect(results).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: 'sl_measure',
|
||||
id: 'orders.order_count',
|
||||
connectionId: 'warehouse',
|
||||
summary: 'Number of paid orders',
|
||||
snippet: 'count(*)',
|
||||
matchedOn: expect.stringMatching(/name|description|expr/),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('honors kind filters and connection scope', async () => {
|
||||
await seedWiki();
|
||||
await seedSl();
|
||||
await seedScan({ syncId: 'sync-1', connectionId: 'warehouse', tableName: 'orders' });
|
||||
await seedScan({ syncId: 'sync-2', connectionId: 'billing', tableName: 'invoices', comment: 'Billing invoices' });
|
||||
const service = createKtxDiscoverDataService(project);
|
||||
|
||||
const results = await service.search({
|
||||
query: 'orders',
|
||||
connectionId: 'warehouse',
|
||||
kinds: ['table', 'column'],
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
expect(results.every((result) => result.kind === 'table' || result.kind === 'column')).toBe(true);
|
||||
expect(results.every((result) => result.connectionId === 'warehouse')).toBe(true);
|
||||
expect(results.some((result) => result.id.includes('invoices'))).toBe(false);
|
||||
expect(results.some((result) => result.kind === 'wiki')).toBe(false);
|
||||
});
|
||||
|
||||
it('re-reads the latest scan artifacts on each call', async () => {
|
||||
await seedScan({ syncId: 'sync-1', tableName: 'orders', comment: 'Old orders table' });
|
||||
const service = createKtxDiscoverDataService(project);
|
||||
await expect(
|
||||
service.search({ query: 'orders', connectionId: 'warehouse', kinds: ['table'], limit: 10 }),
|
||||
).resolves.toEqual(expect.arrayContaining([expect.objectContaining({ id: 'public.orders' })]));
|
||||
|
||||
await seedScan({ syncId: 'sync-2', tableName: 'invoices', comment: 'Invoice facts' });
|
||||
const fresh = await service.search({ query: 'invoice', connectionId: 'warehouse', kinds: ['table'], limit: 10 });
|
||||
|
||||
expect(fresh).toEqual(expect.arrayContaining([expect.objectContaining({ id: 'public.invoices' })]));
|
||||
expect(fresh.some((result) => result.id === 'public.orders')).toBe(false);
|
||||
});
|
||||
});
|
||||
127
packages/cli/test/context/search/hybrid-search-core.test.ts
Normal file
127
packages/cli/test/context/search/hybrid-search-core.test.ts
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { HybridSearchCore } from '../../../src/context/search/hybrid-search-core.js';
|
||||
import type { SearchCandidateGenerator } from '../../../src/context/search/types.js';
|
||||
|
||||
function generator(
|
||||
lane: string,
|
||||
candidates: Array<{ id: string; rank: number; rawScore?: number; matchReason?: string; evidence?: unknown }>,
|
||||
weight?: number,
|
||||
): SearchCandidateGenerator {
|
||||
return {
|
||||
lane,
|
||||
weight,
|
||||
async generate() {
|
||||
return { candidates };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('HybridSearchCore', () => {
|
||||
it('runs lane generators with the shared pool size and applies final limit after RRF fusion', async () => {
|
||||
const calls: Array<{ lane: string; laneCandidatePoolLimit: number; finalLimit: number }> = [];
|
||||
const core = new HybridSearchCore();
|
||||
const result = await core.search({
|
||||
queryText: 'gross revenue',
|
||||
limit: 1,
|
||||
generators: [
|
||||
{
|
||||
lane: 'lexical',
|
||||
async generate(args) {
|
||||
calls.push({ lane: 'lexical', ...args });
|
||||
return {
|
||||
candidates: [
|
||||
{ id: 'orders', rank: 1, rawScore: 0.8 },
|
||||
{ id: 'customers', rank: 2, rawScore: 0.7 },
|
||||
],
|
||||
};
|
||||
},
|
||||
},
|
||||
{
|
||||
lane: 'semantic',
|
||||
async generate(args) {
|
||||
calls.push({ lane: 'semantic', ...args });
|
||||
return { candidates: [{ id: 'customers', rank: 1, rawScore: 0.91 }] };
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(calls).toEqual([
|
||||
expect.objectContaining({ lane: 'lexical', laneCandidatePoolLimit: 25, finalLimit: 1 }),
|
||||
expect.objectContaining({ lane: 'semantic', laneCandidatePoolLimit: 25, finalLimit: 1 }),
|
||||
]);
|
||||
expect(result.results.map((candidate) => candidate.id)).toEqual(['customers']);
|
||||
expect(result.results[0]).toMatchObject({
|
||||
matchReasons: ['lexical', 'semantic'],
|
||||
ranksByLane: { lexical: 2, semantic: 1 },
|
||||
rawScoresByLane: { lexical: 0.7, semantic: 0.91 },
|
||||
});
|
||||
expect(result.lanes).toEqual([
|
||||
expect.objectContaining({ lane: 'lexical', status: 'available', returnedCandidateCount: 2, weight: 1.5 }),
|
||||
expect.objectContaining({ lane: 'semantic', status: 'available', returnedCandidateCount: 1, weight: 2 }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps available lane results when another lane is skipped or fails', async () => {
|
||||
const core = new HybridSearchCore();
|
||||
const result = await core.search({
|
||||
queryText: 'paid',
|
||||
limit: 5,
|
||||
generators: [
|
||||
generator('lexical', [{ id: 'orders', rank: 1 }]),
|
||||
{
|
||||
lane: 'semantic',
|
||||
async generate() {
|
||||
return { status: 'skipped', candidates: [], reason: 'embedding_unconfigured' };
|
||||
},
|
||||
},
|
||||
{
|
||||
lane: 'dictionary',
|
||||
async generate() {
|
||||
throw new Error('dictionary index unavailable');
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(result.results.map((candidate) => candidate.id)).toEqual(['orders']);
|
||||
expect(result.lanes).toEqual([
|
||||
expect.objectContaining({ lane: 'lexical', status: 'available', reason: undefined }),
|
||||
expect.objectContaining({ lane: 'semantic', status: 'skipped', reason: 'embedding_unconfigured' }),
|
||||
expect.objectContaining({ lane: 'dictionary', status: 'failed', reason: 'dictionary index unavailable' }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('deduplicates one lane by best rank before fusion', async () => {
|
||||
const core = new HybridSearchCore();
|
||||
const result = await core.search({
|
||||
queryText: 'paid status',
|
||||
limit: 10,
|
||||
generators: [
|
||||
generator('dictionary', [
|
||||
{ id: 'orders', rank: 4, rawScore: 0.4, evidence: { column: 'state', values: ['paid'] } },
|
||||
{ id: 'orders', rank: 1, rawScore: 0.9, evidence: { column: 'status', values: ['paid'] } },
|
||||
]),
|
||||
],
|
||||
});
|
||||
|
||||
expect(result.results).toHaveLength(1);
|
||||
expect(result.results[0]).toMatchObject({
|
||||
id: 'orders',
|
||||
ranksByLane: { dictionary: 1 },
|
||||
rawScoresByLane: { dictionary: 0.9 },
|
||||
evidenceByLane: { dictionary: [{ column: 'status', values: ['paid'] }] },
|
||||
});
|
||||
});
|
||||
|
||||
it('uses deterministic id ordering when scores and lane counts tie', async () => {
|
||||
const core = new HybridSearchCore();
|
||||
const result = await core.search({
|
||||
queryText: 'revenue',
|
||||
limit: 10,
|
||||
generators: [generator('lexical', [{ id: 'zebra', rank: 1 }, { id: 'alpha', rank: 1 }])],
|
||||
});
|
||||
|
||||
expect(result.results.map((candidate) => candidate.id)).toEqual(['alpha', 'zebra']);
|
||||
});
|
||||
});
|
||||
317
packages/cli/test/context/search/pglite-owner-process.test.ts
Normal file
317
packages/cli/test/context/search/pglite-owner-process.test.ts
Normal file
|
|
@ -0,0 +1,317 @@
|
|||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { createServer } from 'node:net';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { Client } from 'pg';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { assertSearchBackendConformanceCase } from './backend-conformance.test-utils.js';
|
||||
import { KtxPGliteOwnerProcess } from '../../../src/context/search/pglite-owner-process.js';
|
||||
|
||||
async function allocatePort(): Promise<number> {
|
||||
const server = createServer();
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
const address = server.address();
|
||||
if (typeof address !== 'object' || address === null) {
|
||||
throw new Error('Expected TCP server address while allocating a PGlite owner-process port.');
|
||||
}
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
return address.port;
|
||||
}
|
||||
|
||||
async function createHybridSearchFixture(owner: KtxPGliteOwnerProcess): Promise<void> {
|
||||
await owner.query(`
|
||||
CREATE TABLE prototype_documents (
|
||||
id TEXT PRIMARY KEY,
|
||||
search_text TEXT NOT NULL,
|
||||
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
embedding vector(3) NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX prototype_documents_fts_idx
|
||||
ON prototype_documents
|
||||
USING GIN (to_tsvector('english', search_text));
|
||||
|
||||
CREATE INDEX prototype_documents_vector_idx
|
||||
ON prototype_documents
|
||||
USING ivfflat (embedding vector_cosine_ops)
|
||||
WITH (lists = 1);
|
||||
|
||||
CREATE TABLE prototype_dictionary_values (
|
||||
connection_id TEXT NOT NULL,
|
||||
source_name TEXT NOT NULL,
|
||||
column_name TEXT NOT NULL,
|
||||
value TEXT NOT NULL,
|
||||
PRIMARY KEY (connection_id, source_name, column_name, value)
|
||||
);
|
||||
|
||||
CREATE INDEX prototype_dictionary_values_trgm_idx
|
||||
ON prototype_dictionary_values
|
||||
USING GIN (value gin_trgm_ops);
|
||||
`);
|
||||
}
|
||||
|
||||
async function seedHybridSearchFixture(owner: KtxPGliteOwnerProcess): Promise<void> {
|
||||
await owner.query(
|
||||
`
|
||||
INSERT INTO prototype_documents (id, search_text, metadata, embedding)
|
||||
VALUES
|
||||
($1, $2, $3::jsonb, $4::vector),
|
||||
($5, $6, $7::jsonb, $8::vector),
|
||||
($9, $10, $11::jsonb, $12::vector)
|
||||
`,
|
||||
[
|
||||
'warehouse/orders',
|
||||
'orders paid revenue refund status customer',
|
||||
JSON.stringify({ connectionId: 'warehouse', sourceName: 'orders' }),
|
||||
JSON.stringify([1, 0, 0]),
|
||||
'finance/orders',
|
||||
'orders finance bookings gross margin',
|
||||
JSON.stringify({ connectionId: 'finance', sourceName: 'orders' }),
|
||||
JSON.stringify([0.72, 0.28, 0]),
|
||||
'warehouse/customers',
|
||||
'customers accounts lifecycle region',
|
||||
JSON.stringify({ connectionId: 'warehouse', sourceName: 'customers' }),
|
||||
JSON.stringify([0, 1, 0]),
|
||||
],
|
||||
);
|
||||
|
||||
await owner.query(`
|
||||
INSERT INTO prototype_dictionary_values (connection_id, source_name, column_name, value)
|
||||
VALUES
|
||||
('warehouse', 'orders', 'status', 'refunded'),
|
||||
('warehouse', 'orders', 'status', 'paid'),
|
||||
('warehouse', 'customers', 'region', 'emea')
|
||||
`);
|
||||
}
|
||||
|
||||
describe('KtxPGliteOwnerProcess', () => {
|
||||
let tempDir: string;
|
||||
let dataDir: string;
|
||||
let port: number;
|
||||
|
||||
beforeEach(async () => {
|
||||
tempDir = await mkdtemp(join(tmpdir(), 'ktx-pglite-owner-process-'));
|
||||
dataDir = join(tempDir, 'pgdata');
|
||||
port = await allocatePort();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('starts a socket owner process and serves PostgreSQL clients', async () => {
|
||||
const owner = await KtxPGliteOwnerProcess.start({
|
||||
dataDir,
|
||||
host: '127.0.0.1',
|
||||
port,
|
||||
});
|
||||
|
||||
try {
|
||||
await owner.query(`
|
||||
CREATE TABLE owner_process_smoke (
|
||||
id TEXT PRIMARY KEY,
|
||||
search_text TEXT NOT NULL,
|
||||
embedding vector(3) NOT NULL
|
||||
);
|
||||
|
||||
INSERT INTO owner_process_smoke (id, search_text, embedding)
|
||||
VALUES
|
||||
('orders', 'orders paid revenue', '[1,0,0]'::vector),
|
||||
('customers', 'customers region lifecycle', '[0,1,0]'::vector);
|
||||
`);
|
||||
|
||||
const client = new Client(owner.connectionConfig());
|
||||
await client.connect();
|
||||
|
||||
try {
|
||||
const result = await client.query<{ id: string }>(`
|
||||
SELECT id
|
||||
FROM owner_process_smoke
|
||||
ORDER BY embedding <=> '[1,0,0]'::vector, id ASC
|
||||
LIMIT 1
|
||||
`);
|
||||
|
||||
expect(result.rows).toEqual([{ id: 'orders' }]);
|
||||
} finally {
|
||||
await client.end();
|
||||
}
|
||||
} finally {
|
||||
await owner.stop();
|
||||
}
|
||||
});
|
||||
|
||||
it('runs lexical, semantic, and dictionary conformance probes through socket clients', async () => {
|
||||
const owner = await KtxPGliteOwnerProcess.start({
|
||||
dataDir,
|
||||
host: '127.0.0.1',
|
||||
port,
|
||||
});
|
||||
|
||||
try {
|
||||
await createHybridSearchFixture(owner);
|
||||
await seedHybridSearchFixture(owner);
|
||||
|
||||
const lexical = await owner.query<{ id: string; score: number }>(
|
||||
`
|
||||
SELECT
|
||||
id,
|
||||
ts_rank_cd(to_tsvector('english', search_text), websearch_to_tsquery('english', $1)) AS score
|
||||
FROM prototype_documents
|
||||
WHERE to_tsvector('english', search_text) @@ websearch_to_tsquery('english', $1)
|
||||
ORDER BY score DESC, id ASC
|
||||
LIMIT 2
|
||||
`,
|
||||
['paid orders'],
|
||||
);
|
||||
|
||||
assertSearchBackendConformanceCase({
|
||||
backendName: 'pglite-owner-process',
|
||||
surface: 'semantic-layer',
|
||||
caseName: 'socket postgres fts lexical ranking',
|
||||
results: lexical.rows.map((row) => ({
|
||||
id: row.id,
|
||||
score: row.score,
|
||||
matchReasons: ['lexical'],
|
||||
})),
|
||||
expectedTopIds: ['warehouse/orders'],
|
||||
expectedReasonsById: {
|
||||
'warehouse/orders': ['lexical'],
|
||||
},
|
||||
});
|
||||
|
||||
const semantic = await owner.query<{ id: string; similarity: number }>(
|
||||
`
|
||||
SELECT
|
||||
id,
|
||||
1 - (embedding <=> $1::vector) AS similarity
|
||||
FROM prototype_documents
|
||||
ORDER BY embedding <=> $1::vector, id ASC
|
||||
LIMIT 2
|
||||
`,
|
||||
[JSON.stringify([1, 0, 0])],
|
||||
);
|
||||
|
||||
assertSearchBackendConformanceCase({
|
||||
backendName: 'pglite-owner-process',
|
||||
surface: 'semantic-layer',
|
||||
caseName: 'socket pgvector semantic ranking',
|
||||
results: semantic.rows.map((row) => ({
|
||||
id: row.id,
|
||||
score: row.similarity,
|
||||
matchReasons: ['semantic'],
|
||||
})),
|
||||
expectedTopIds: ['warehouse/orders'],
|
||||
expectedReasonsById: {
|
||||
'warehouse/orders': ['semantic'],
|
||||
},
|
||||
});
|
||||
|
||||
const dictionary = await owner.query<{ id: string; value: string; score: number }>(
|
||||
`
|
||||
SELECT
|
||||
connection_id || '/' || source_name AS id,
|
||||
value,
|
||||
similarity(value, $1) AS score
|
||||
FROM prototype_dictionary_values
|
||||
WHERE similarity(value, $1) > 0
|
||||
ORDER BY score DESC, id ASC, value ASC
|
||||
LIMIT 2
|
||||
`,
|
||||
['refund'],
|
||||
);
|
||||
|
||||
assertSearchBackendConformanceCase({
|
||||
backendName: 'pglite-owner-process',
|
||||
surface: 'semantic-layer',
|
||||
caseName: 'socket pg_trgm dictionary ranking',
|
||||
results: dictionary.rows.map((row) => ({
|
||||
id: row.id,
|
||||
score: row.score,
|
||||
matchReasons: ['dictionary'],
|
||||
dictionaryMatches: [{ column: 'status', values: [row.value] }],
|
||||
})),
|
||||
expectedTopIds: ['warehouse/orders'],
|
||||
expectedReasonsById: {
|
||||
'warehouse/orders': ['dictionary'],
|
||||
},
|
||||
expectedDictionaryMatchesById: {
|
||||
'warehouse/orders': [{ column: 'status', values: ['refunded'] }],
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await owner.stop();
|
||||
}
|
||||
});
|
||||
|
||||
it('persists indexed rows after stopping and restarting the owner process', async () => {
|
||||
const firstOwner = await KtxPGliteOwnerProcess.start({
|
||||
dataDir,
|
||||
host: '127.0.0.1',
|
||||
port,
|
||||
});
|
||||
|
||||
try {
|
||||
await createHybridSearchFixture(firstOwner);
|
||||
await seedHybridSearchFixture(firstOwner);
|
||||
} finally {
|
||||
await firstOwner.stop();
|
||||
}
|
||||
|
||||
const secondOwner = await KtxPGliteOwnerProcess.start({
|
||||
dataDir,
|
||||
host: '127.0.0.1',
|
||||
port,
|
||||
});
|
||||
|
||||
try {
|
||||
const persisted = await secondOwner.query<{ count: number }>(
|
||||
"SELECT COUNT(*)::int AS count FROM prototype_documents WHERE metadata->>'connectionId' = $1",
|
||||
['warehouse'],
|
||||
);
|
||||
|
||||
expect(persisted.rows).toEqual([{ count: 2 }]);
|
||||
} finally {
|
||||
await secondOwner.stop();
|
||||
}
|
||||
});
|
||||
|
||||
it('serves concurrent PostgreSQL clients through one owner process', async () => {
|
||||
const owner = await KtxPGliteOwnerProcess.start({
|
||||
dataDir,
|
||||
host: '127.0.0.1',
|
||||
port,
|
||||
});
|
||||
|
||||
const clients: Client[] = [];
|
||||
|
||||
try {
|
||||
await createHybridSearchFixture(owner);
|
||||
await seedHybridSearchFixture(owner);
|
||||
|
||||
for (let index = 0; index < 4; index += 1) {
|
||||
const client = new Client(owner.connectionConfig());
|
||||
await client.connect();
|
||||
clients.push(client);
|
||||
}
|
||||
|
||||
const results = await Promise.all(
|
||||
clients.map((client) =>
|
||||
client.query<{ count: number }>('SELECT COUNT(*)::int AS count FROM prototype_documents'),
|
||||
),
|
||||
);
|
||||
|
||||
expect(results.map((result) => result.rows[0]?.count)).toEqual([3, 3, 3, 3]);
|
||||
} finally {
|
||||
await Promise.all(clients.map((client) => client.end().catch(() => undefined)));
|
||||
await owner.stop();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const ktxRoot = fileURLToPath(new URL('../../../../..', import.meta.url));
|
||||
|
||||
function readKtxFile(relativePath: string): string {
|
||||
return readFileSync(join(ktxRoot, relativePath), 'utf8');
|
||||
}
|
||||
|
||||
function readCliPackageJson(): {
|
||||
dependencies?: Record<string, string>;
|
||||
devDependencies?: Record<string, string>;
|
||||
exports?: Record<string, unknown>;
|
||||
files?: string[];
|
||||
} {
|
||||
return JSON.parse(readKtxFile('packages/cli/package.json'));
|
||||
}
|
||||
|
||||
describe('PGlite hybrid search runtime boundary', () => {
|
||||
it('keeps PGlite packages as dev-only prototype dependencies', () => {
|
||||
const pkg = readCliPackageJson();
|
||||
|
||||
expect(pkg.dependencies?.['@electric-sql/pglite']).toBeUndefined();
|
||||
expect(pkg.dependencies?.['@electric-sql/pglite-socket']).toBeUndefined();
|
||||
expect(pkg.devDependencies?.['@electric-sql/pglite']).toBeDefined();
|
||||
expect(pkg.devDependencies?.['@electric-sql/pglite-socket']).toBeDefined();
|
||||
expect(pkg.files).toEqual(['dist', 'assets']);
|
||||
});
|
||||
|
||||
it('keeps PGlite prototypes out of public exports and production routing', () => {
|
||||
const pkg = readCliPackageJson();
|
||||
const packageExportKeys = Object.keys(pkg.exports ?? {});
|
||||
|
||||
expect(packageExportKeys.filter((key) => key.toLowerCase().includes('pglite'))).toEqual([]);
|
||||
|
||||
const productionRoutingFiles = [
|
||||
'packages/cli/src/sl.ts',
|
||||
'packages/cli/src/knowledge.ts',
|
||||
'packages/cli/src/context/mcp/local-project-ports.ts',
|
||||
'packages/cli/src/context/wiki/local-knowledge.ts',
|
||||
'packages/cli/src/context/ingest/context-evidence/sqlite-context-evidence-store.ts',
|
||||
];
|
||||
|
||||
for (const relativePath of productionRoutingFiles) {
|
||||
expect(readKtxFile(relativePath), relativePath).not.toMatch(
|
||||
/pglite-owner-prototype|pglite-sl-search-prototype|@electric-sql\/pglite/i,
|
||||
);
|
||||
}
|
||||
|
||||
const localSlSource = readKtxFile('packages/cli/src/context/sl/local-sl.ts');
|
||||
expect(localSlSource).toContain("input.backend === 'pglite-owner-prototype'");
|
||||
expect(localSlSource).toContain('PGlite semantic-layer search prototype requires pglite owner-process options.');
|
||||
expect(localSlSource).toContain("await import('./pglite-sl-search-prototype.js')");
|
||||
});
|
||||
});
|
||||
299
packages/cli/test/context/search/pglite-spike.test.ts
Normal file
299
packages/cli/test/context/search/pglite-spike.test.ts
Normal file
|
|
@ -0,0 +1,299 @@
|
|||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { PGlite, type PGliteInterface } from '@electric-sql/pglite';
|
||||
import { pg_trgm } from '@electric-sql/pglite/contrib/pg_trgm';
|
||||
import { vector } from '@electric-sql/pglite/vector';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { assertSearchBackendCapabilities, assertSearchBackendConformanceCase } from './backend-conformance.test-utils.js';
|
||||
import type { SearchBackendCapabilities } from '../../../src/context/search/types.js';
|
||||
|
||||
type PGliteDb = PGliteInterface;
|
||||
|
||||
const PGLITE_SPIKE_CAPABILITIES = {
|
||||
fts: true,
|
||||
vector: true,
|
||||
fuzzy: true,
|
||||
jsonSearch: true,
|
||||
arraySearch: false,
|
||||
} satisfies SearchBackendCapabilities;
|
||||
|
||||
async function createSpikeDb(dataDir: string): Promise<PGliteDb> {
|
||||
const db = await PGlite.create({
|
||||
dataDir,
|
||||
extensions: {
|
||||
vector,
|
||||
pg_trgm,
|
||||
},
|
||||
});
|
||||
|
||||
await db.exec(`
|
||||
CREATE EXTENSION IF NOT EXISTS vector;
|
||||
CREATE EXTENSION IF NOT EXISTS pg_trgm;
|
||||
`);
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
async function createSchema(db: PGliteDb): Promise<void> {
|
||||
await db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS spike_documents (
|
||||
id TEXT PRIMARY KEY,
|
||||
search_text TEXT NOT NULL,
|
||||
metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
embedding vector(3) NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS spike_documents_fts_idx
|
||||
ON spike_documents
|
||||
USING GIN (to_tsvector('english', search_text));
|
||||
|
||||
CREATE INDEX IF NOT EXISTS spike_documents_vector_idx
|
||||
ON spike_documents
|
||||
USING ivfflat (embedding vector_cosine_ops)
|
||||
WITH (lists = 1);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS spike_dictionary_values (
|
||||
connection_id TEXT NOT NULL,
|
||||
source_name TEXT NOT NULL,
|
||||
column_name TEXT NOT NULL,
|
||||
value TEXT NOT NULL,
|
||||
PRIMARY KEY (connection_id, source_name, column_name, value)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS spike_dictionary_values_trgm_idx
|
||||
ON spike_dictionary_values
|
||||
USING GIN (value gin_trgm_ops);
|
||||
`);
|
||||
}
|
||||
|
||||
async function seedSearchFixture(db: PGliteDb): Promise<void> {
|
||||
await db.query(
|
||||
`
|
||||
INSERT INTO spike_documents (id, search_text, metadata, embedding)
|
||||
VALUES
|
||||
($1, $2, $3::jsonb, $4::vector),
|
||||
($5, $6, $7::jsonb, $8::vector),
|
||||
($9, $10, $11::jsonb, $12::vector)
|
||||
ON CONFLICT (id) DO UPDATE
|
||||
SET search_text = EXCLUDED.search_text,
|
||||
metadata = EXCLUDED.metadata,
|
||||
embedding = EXCLUDED.embedding
|
||||
`,
|
||||
[
|
||||
'warehouse/orders',
|
||||
'orders paid revenue refund status customer',
|
||||
JSON.stringify({ connectionId: 'warehouse', sourceName: 'orders' }),
|
||||
JSON.stringify([1, 0, 0]),
|
||||
'finance/orders',
|
||||
'orders finance bookings gross margin',
|
||||
JSON.stringify({ connectionId: 'finance', sourceName: 'orders' }),
|
||||
JSON.stringify([0.72, 0.28, 0]),
|
||||
'warehouse/customers',
|
||||
'customers accounts lifecycle region',
|
||||
JSON.stringify({ connectionId: 'warehouse', sourceName: 'customers' }),
|
||||
JSON.stringify([0, 1, 0]),
|
||||
],
|
||||
);
|
||||
|
||||
await db.query(
|
||||
`
|
||||
INSERT INTO spike_dictionary_values (connection_id, source_name, column_name, value)
|
||||
VALUES
|
||||
('warehouse', 'orders', 'status', 'refunded'),
|
||||
('warehouse', 'orders', 'status', 'paid'),
|
||||
('warehouse', 'customers', 'region', 'emea')
|
||||
ON CONFLICT DO NOTHING
|
||||
`,
|
||||
);
|
||||
}
|
||||
|
||||
async function closeDb(db: PGliteDb): Promise<void> {
|
||||
await db.close();
|
||||
}
|
||||
|
||||
describe('PGlite hybrid search spike', () => {
|
||||
let tempDir: string;
|
||||
let dataDir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
tempDir = await mkdtemp(join(tmpdir(), 'ktx-pglite-search-spike-'));
|
||||
dataDir = join(tempDir, 'pgdata');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('documents PGlite search backend capabilities', () => {
|
||||
assertSearchBackendCapabilities({
|
||||
backendName: 'pglite-spike',
|
||||
capabilities: PGLITE_SPIKE_CAPABILITIES,
|
||||
expected: {
|
||||
fts: true,
|
||||
vector: true,
|
||||
fuzzy: true,
|
||||
jsonSearch: true,
|
||||
arraySearch: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('supports FTS, pgvector ordering, and pg_trgm dictionary lookup', async () => {
|
||||
const db = await createSpikeDb(dataDir);
|
||||
|
||||
try {
|
||||
await createSchema(db);
|
||||
await seedSearchFixture(db);
|
||||
|
||||
const lexical = await db.query<{ id: string; score: number }>(
|
||||
`
|
||||
SELECT
|
||||
id,
|
||||
ts_rank_cd(to_tsvector('english', search_text), websearch_to_tsquery('english', $1)) AS score
|
||||
FROM spike_documents
|
||||
WHERE to_tsvector('english', search_text) @@ websearch_to_tsquery('english', $1)
|
||||
ORDER BY score DESC, id ASC
|
||||
LIMIT 2
|
||||
`,
|
||||
['paid orders'],
|
||||
);
|
||||
|
||||
assertSearchBackendConformanceCase({
|
||||
backendName: 'pglite-spike',
|
||||
surface: 'semantic-layer',
|
||||
caseName: 'postgres fts lexical ranking',
|
||||
results: lexical.rows.map((row) => ({
|
||||
id: row.id,
|
||||
score: row.score,
|
||||
matchReasons: ['lexical'],
|
||||
})),
|
||||
expectedTopIds: ['warehouse/orders'],
|
||||
expectedReasonsById: {
|
||||
'warehouse/orders': ['lexical'],
|
||||
},
|
||||
});
|
||||
|
||||
const semantic = await db.query<{ id: string; similarity: number }>(
|
||||
`
|
||||
SELECT
|
||||
id,
|
||||
1 - (embedding <=> $1::vector) AS similarity
|
||||
FROM spike_documents
|
||||
ORDER BY embedding <=> $1::vector, id ASC
|
||||
LIMIT 2
|
||||
`,
|
||||
[JSON.stringify([1, 0, 0])],
|
||||
);
|
||||
|
||||
assertSearchBackendConformanceCase({
|
||||
backendName: 'pglite-spike',
|
||||
surface: 'semantic-layer',
|
||||
caseName: 'pgvector cosine ranking',
|
||||
results: semantic.rows.map((row) => ({
|
||||
id: row.id,
|
||||
score: row.similarity,
|
||||
matchReasons: ['semantic'],
|
||||
})),
|
||||
expectedTopIds: ['warehouse/orders'],
|
||||
expectedReasonsById: {
|
||||
'warehouse/orders': ['semantic'],
|
||||
},
|
||||
});
|
||||
|
||||
const dictionary = await db.query<{ id: string; value: string; score: number }>(
|
||||
`
|
||||
SELECT
|
||||
connection_id || '/' || source_name AS id,
|
||||
value,
|
||||
similarity(value, $1) AS score
|
||||
FROM spike_dictionary_values
|
||||
WHERE similarity(value, $1) > 0
|
||||
ORDER BY score DESC, id ASC, value ASC
|
||||
LIMIT 2
|
||||
`,
|
||||
['refund'],
|
||||
);
|
||||
|
||||
assertSearchBackendConformanceCase({
|
||||
backendName: 'pglite-spike',
|
||||
surface: 'semantic-layer',
|
||||
caseName: 'pg_trgm dictionary ranking',
|
||||
results: dictionary.rows.map((row) => ({
|
||||
id: row.id,
|
||||
score: row.score,
|
||||
matchReasons: ['dictionary'],
|
||||
dictionaryMatches: [{ column: 'status', values: [row.value] }],
|
||||
})),
|
||||
expectedTopIds: ['warehouse/orders'],
|
||||
expectedReasonsById: {
|
||||
'warehouse/orders': ['dictionary'],
|
||||
},
|
||||
expectedDictionaryMatchesById: {
|
||||
'warehouse/orders': [{ column: 'status', values: ['refunded'] }],
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await closeDb(db);
|
||||
}
|
||||
});
|
||||
|
||||
it('persists indexed rows after reopening the filesystem database', async () => {
|
||||
const first = await createSpikeDb(dataDir);
|
||||
|
||||
try {
|
||||
await createSchema(first);
|
||||
await seedSearchFixture(first);
|
||||
} finally {
|
||||
await closeDb(first);
|
||||
}
|
||||
|
||||
const second = await createSpikeDb(dataDir);
|
||||
|
||||
try {
|
||||
const persisted = await second.query<{ count: number }>(
|
||||
"SELECT COUNT(*)::int AS count FROM spike_documents WHERE metadata->>'connectionId' = $1",
|
||||
['warehouse'],
|
||||
);
|
||||
|
||||
expect(persisted.rows[0]).toEqual({ count: 2 });
|
||||
} finally {
|
||||
await closeDb(second);
|
||||
}
|
||||
});
|
||||
|
||||
it('records direct concurrency behavior without assuming Postgres server parity', async () => {
|
||||
const db = await createSpikeDb(dataDir);
|
||||
|
||||
try {
|
||||
await createSchema(db);
|
||||
await seedSearchFixture(db);
|
||||
|
||||
const reads = await Promise.all(
|
||||
Array.from({ length: 4 }, () =>
|
||||
db.query<{ count: number }>('SELECT COUNT(*)::int AS count FROM spike_documents'),
|
||||
),
|
||||
);
|
||||
|
||||
expect(reads.map((result) => result.rows[0]?.count)).toEqual([3, 3, 3, 3]);
|
||||
|
||||
let secondOpenStatus: 'opened' | 'blocked' = 'opened';
|
||||
let second: PGliteDb | undefined;
|
||||
|
||||
try {
|
||||
second = await createSpikeDb(dataDir);
|
||||
await second.query('SELECT 1');
|
||||
} catch {
|
||||
secondOpenStatus = 'blocked';
|
||||
} finally {
|
||||
if (second) {
|
||||
await closeDb(second);
|
||||
}
|
||||
}
|
||||
|
||||
expect(['opened', 'blocked']).toContain(secondOpenStatus);
|
||||
} finally {
|
||||
await closeDb(db);
|
||||
}
|
||||
});
|
||||
});
|
||||
26
packages/cli/test/context/search/query.test.ts
Normal file
26
packages/cli/test/context/search/query.test.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { defaultLaneCandidatePoolLimit, normalizeSearchQuery } from '../../../src/context/search/query.js';
|
||||
|
||||
describe('search query helpers', () => {
|
||||
it('normalizes punctuation and duplicate terms into stable lowercase tokens', () => {
|
||||
expect(normalizeSearchQuery(' Gross-Revenue, gross_revenue! Paid orders ')).toEqual({
|
||||
raw: ' Gross-Revenue, gross_revenue! Paid orders ',
|
||||
normalized: 'gross revenue gross_revenue paid orders',
|
||||
terms: ['gross', 'revenue', 'gross_revenue', 'paid', 'orders'],
|
||||
});
|
||||
});
|
||||
|
||||
it('returns an empty normalized query for punctuation-only input', () => {
|
||||
expect(normalizeSearchQuery('--- ///')).toEqual({
|
||||
raw: '--- ///',
|
||||
normalized: '',
|
||||
terms: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('sizes per-lane candidate pools before final limiting', () => {
|
||||
expect(defaultLaneCandidatePoolLimit(1)).toBe(25);
|
||||
expect(defaultLaneCandidatePoolLimit(8)).toBe(25);
|
||||
expect(defaultLaneCandidatePoolLimit(10)).toBe(30);
|
||||
});
|
||||
});
|
||||
52
packages/cli/test/context/search/rrf.test.ts
Normal file
52
packages/cli/test/context/search/rrf.test.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { compareFusedSearchCandidates, DEFAULT_SEARCH_LANE_WEIGHTS, rrfContribution } from '../../../src/context/search/rrf.js';
|
||||
import type { FusedSearchCandidate } from '../../../src/context/search/types.js';
|
||||
|
||||
describe('RRF scoring', () => {
|
||||
it('uses the shared lane weights from the hybrid search spec', () => {
|
||||
expect(DEFAULT_SEARCH_LANE_WEIGHTS).toEqual({
|
||||
semantic: 2,
|
||||
dictionary: 2,
|
||||
lexical: 1.5,
|
||||
token: 0.75,
|
||||
});
|
||||
});
|
||||
|
||||
it('calculates a weighted RRF contribution with k=60 by default', () => {
|
||||
expect(rrfContribution(2, 1)).toBeCloseTo(2 / 61, 12);
|
||||
expect(rrfContribution(1.5, 2)).toBeCloseTo(1.5 / 62, 12);
|
||||
});
|
||||
|
||||
it('sorts fused candidates by score, lane count, and stable id', () => {
|
||||
const first: FusedSearchCandidate = {
|
||||
id: 'orders',
|
||||
score: 0.05,
|
||||
matchReasons: ['lexical'],
|
||||
ranksByLane: { lexical: 1 },
|
||||
rawScoresByLane: {},
|
||||
evidenceByLane: {},
|
||||
};
|
||||
const second: FusedSearchCandidate = {
|
||||
id: 'customers',
|
||||
score: 0.05,
|
||||
matchReasons: ['lexical', 'semantic'],
|
||||
ranksByLane: { lexical: 2, semantic: 1 },
|
||||
rawScoresByLane: {},
|
||||
evidenceByLane: {},
|
||||
};
|
||||
const third: FusedSearchCandidate = {
|
||||
id: 'accounts',
|
||||
score: 0.04,
|
||||
matchReasons: ['semantic'],
|
||||
ranksByLane: { semantic: 1 },
|
||||
rawScoresByLane: {},
|
||||
evidenceByLane: {},
|
||||
};
|
||||
|
||||
expect([first, second, third].sort(compareFusedSearchCandidates).map((candidate) => candidate.id)).toEqual([
|
||||
'customers',
|
||||
'orders',
|
||||
'accounts',
|
||||
]);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue