From 3034d99bc4eea0dfd17b65e6578b5a3faff65295 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 05:05:25 +0000 Subject: [PATCH 01/19] fix(knowledge-turso): a scoped search reads its passage table once a statement; a request past its bound answers TIMEOUT A search with a record scope or a metadata filter read its WHERE row by row in the vector leg, the keyword candidates and the keyword count, and the keyword candidates were computed twice in one statement. Each was a pass over the passage table; on a remote libSQL database a scoped statement went past the 10 s request bound. The WHERE is now read once a statement into a materialized scope set that every other read looks up by chunk id, and the keyword candidates are materialized. A request past requestTimeoutMs answers TIMEOUT (504), "did not answer in time", instead of SERVICE_UNAVAILABLE "is not ready". Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbaAVoqUQiPmxMVpLst --- .changeset/38675-scoped-search-one-pass.md | 14 ++ packages/plugins/knowledge-turso/README.md | 4 +- .../src/__tests__/acceptance.test.ts | 4 +- .../src/__tests__/scope-plan.test.ts | 194 ++++++++++++++++++ .../plugins/knowledge-turso/src/plugin.ts | 2 +- .../knowledge-turso/src/turso-adapter.ts | 72 ++++--- 6 files changed, 261 insertions(+), 29 deletions(-) create mode 100644 .changeset/38675-scoped-search-one-pass.md create mode 100644 packages/plugins/knowledge-turso/src/__tests__/scope-plan.test.ts diff --git a/.changeset/38675-scoped-search-one-pass.md b/.changeset/38675-scoped-search-one-pass.md new file mode 100644 index 00000000000..bd859462237 --- /dev/null +++ b/.changeset/38675-scoped-search-one-pass.md @@ -0,0 +1,14 @@ +--- +'@objectstack/knowledge-turso': patch +--- + +fix(knowledge-turso): a scoped search reads its passage table once a statement, and a request past its bound answers TIMEOUT, not "not ready" + +Clause-②: no +Metadata-protocol: none + +Before, a search with a record scope or a metadata filter ran its `WHERE` row by row in every part of the statement: the vector leg, the keyword leg's candidates, and the count of passages in scope behind the keyword weights. A metadata scope term reads each passage's JSON, so each of those was a pass over the whole passage table. The keyword leg's candidates were also computed twice in one statement, once for the weights and once for the ranks. On 59,621 one-passage records of 1,024 dimensions, a statement scoped to 3 policies took about 1.0 s locally, and a scoped search ran two or three such statements. On a remote libSQL (Turso) database each pass reads the table's pages over the network, and one statement went past the 10 s request bound. + +Now a scoped or filtered statement reads its `WHERE` once, into the set of the passages in scope, and every other read of the passage table is a lookup by chunk id. The keyword leg's candidates are read once. The same measurement takes about 80 ms for 3 policies and 250 to 450 ms for a unit holding 10% of the passages, and an unscoped statement about 650 ms instead of 1.2 s. The hits are unchanged. + +A request that takes longer than `requestTimeoutMs` now answers `TIMEOUT` (504) with "The knowledge store (libSQL) did not answer in time: a request to its database took longer than N ms." Before, it answered `SERVICE_UNAVAILABLE` (503) with "The knowledge store (libSQL) is not ready", which told a caller the store was down when one statement was slow. The operator text in `remedy` still names `requestTimeoutMs`. diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index b7380be2aa8..47b83a4d3bb 100644 --- a/packages/plugins/knowledge-turso/README.md +++ b/packages/plugins/knowledge-turso/README.md @@ -26,7 +26,7 @@ A source is usually a `knowledge_source` metadata item (a `*.knowledge-source.ts | `authToken` | — | The token of a `libsql://` URL. | | `client` | — | A libSQL client to use as it is (not configured, not closed by the plugin). | | `busyTimeoutMs` | `5000` | How long a write waits for another process's lock on a `file:` store. | -| `requestTimeoutMs` | `10000` for a remote URL | The longest one request to a remote database may take (each statement, each document's batch of a write, each commit) before the call answers `SERVICE_UNAVAILABLE`. A write stopped before its commit is rolled back, never committed. None for a file or `:memory:`; for a `client` given as it is, only when set. | +| `requestTimeoutMs` | `10000` for a remote URL | The longest one request to a remote database may take (each statement, each document's batch of a write, each commit) before the call answers `TIMEOUT` (504): "did not answer in time", never "not ready", since the database may be up and one statement slow. A write stopped before its commit is rolled back, never committed. None for a file or `:memory:`; for a `client` given as it is, only when set. | | `projectRoot` | `process.cwd()` | The directory the default file is under. | | `queryPrefix` | `''` | Text put before every query before it is embedded. Passages are embedded as they are. | | `embedder` | the kernel's `embedder` service | The embedder to call, read at each call. | @@ -55,7 +55,7 @@ Two legs, merged by reciprocal rank fusion (RRF, `k` = 60) before the knowledge - **Keyword index.** Each passage table `knowledge__g` has one beside it: a map table `…-kw`, a contentless FTS5 table `…-fts` (`tokenize='trigram'`) and three triggers that keep both in step with every insert, rewrite and removal of a passage, inside the statement that writes it. It is made with the table and dropped with it. A table made by a release without one gets it at its first search, built from the rows it holds in one transaction; until then nothing else changes. Its names hold a hyphen, which no source, generation or object name can, and an object under one of them that the store did not make is never dropped or used: the generation is refused `SERVICE_UNAVAILABLE`, naming it. - **Vector leg.** Passages ranked by the cosine distance of their stored vector (`vector_distance_cos`); a passage whose cosine similarity is not positive is not ranked by it. Its ranks 1…`topK` feed the fusion, whichever of the two ways below found the passages. -The organization filter, the record scope (a passage's record, or a metadata value equal to an id as text, a list matching by any element) and the metadata `filter` (JSON equality per key) are one `WHERE`, run in both legs. +The organization filter, the record scope (a passage's record, or a metadata value equal to an id as text, a list matching by any element) and the metadata `filter` (JSON equality per key) are one `WHERE`, run in both legs. A search with a record scope or a metadata `filter` reads that `WHERE` once per statement, into a set of the passages in scope, and both legs and the keyword leg's counts read the passages in scope from that set by their key: a metadata term reads each passage's JSON, a pass over the table, which would otherwise be paid once by each leg and once more by the keyword counts. Measured on 59,621 one-passage records of 1,024 dimensions (one organization, `topK` 40, a Chinese question of 16 terms): a search scoped to 3 policies' clauses (90 passages) took about 1.0 s a statement before and 80 ms after, one scoped to a unit holding 10% of them 1.0 to 1.4 s before and 250 to 450 ms after. The keyword leg's candidates are read once a statement, not once for its counts and once for its ranks. - **Exact scan.** The vector leg reads every row in scope. Measured on Linux x64 with 1,536-wide vectors: 1,000 passages take 8.3 MB and a search about 5 ms; 10,000 passages take 82 MB and a search about 50 ms. - **Approximate index, for a large source.** When a complete build of a source completes (`os knowledge rebuild`, a fingerprint change, the boot build or the daily reconcile — they all end in `completeBuild`) on a generation of `vectorIndexThreshold` passages or more (default 20,000), the store makes that generation's approximate index: every passage's vector quantized to one bit a dimension, in a side table a 32nd the size of the vectors. The vector leg then ranks the side table by its one-bit vectors, takes the nearest `topK × vectorIndexOverfetch` (default 40 a hit) as candidates, runs the same `WHERE` over them, and ranks those in scope by their stored float32 vector. The candidates are ranked before the filter, so a leg the filter leaves with fewer than 8 × `topK` candidates in scope, or short of `topK` hits, is run again as the exact scan. The float32 re-rank of a thin pool misses the neighbours the one-bit ranking put past the cut: measured at 200,000 passages, a pool of `topK` gave a recall@10 of 0.88 with 3% of the passages in scope, and a pool of 4 × `topK` still left a query at 0.7 with 10% in scope. Before that exact scan, a leg whose scope is not of record terms alone (no scope, or a parent term) tries one more pass over 10 times the candidates, under the same floor, when its first pool says that can clear it: measured at 200,000 passages under a parent scope keeping 10% to 20% of them, about 0.35 s at p95 instead of about 0.9 s for the exact scan, at the same recall. A scope of record terms alone has no second pass, since the record index lets the exact scan read only the rows in scope, and when it keeps too few passages for the first pass to be expected to keep 1.25 × that floor (with the default over-fetch, under 25% of the source's passages, estimated from the passages of at most 256 of its ids), it skips the first pass too and goes straight to the exact scan: measured at 200,000 passages with 5%, 10% and 20% of them in scope, p95 74, 143 and 289 ms instead of 219, 321 and 418 ms (the exact scan alone: 81, 154 and 291 ms). So a search whose scope keeps a small share of a source's passages is answered by the exact scan, and the index speeds up the broad ones. And a search never answers fewer hits than the exact scan would, since the knowledge service reads "fewer than asked" as "no more there". diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index d8a3fe2d029..e6d5546dde8 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -737,7 +737,7 @@ describe('knowledge-turso with a request bound (a remote database)', () => { store.closeAll(); }); - it('a request that stalls inside a write answers SERVICE_UNAVAILABLE naming requestTimeoutMs, and nothing of the write lands', async () => { + it('a request that stalls inside a write answers TIMEOUT naming requestTimeoutMs, and nothing of the write lands', async () => { const store = storeOf('file'); const real = store.client(); const s = source('stall'); @@ -763,7 +763,7 @@ describe('knowledge-turso with a request bound (a remote database)', () => { }) as Client; const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: hanging, embedder: new FakeEmbedder(), requestTimeoutMs: 80 }); const err = await refusal(adapter.upsert([doc(s, 'a', 'otter pup'), doc(s, 'b', 'otter den')], ctx(s))); - expect(err).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503, remedy: expect.stringContaining('requestTimeoutMs') }); + expect(err).toMatchObject({ code: 'TIMEOUT', status: 504, remedy: expect.stringContaining('requestTimeoutMs') }); await new Promise((r) => setTimeout(r, 100)); expect((await plain.listDocuments(ctx(s), { limit: 10 })).documents.map((d) => d.documentId)).toEqual([`${s.name}:seed`]); // The next write goes through. diff --git a/packages/plugins/knowledge-turso/src/__tests__/scope-plan.test.ts b/packages/plugins/knowledge-turso/src/__tests__/scope-plan.test.ts new file mode 100644 index 00000000000..e2ff4fbab88 --- /dev/null +++ b/packages/plugins/knowledge-turso/src/__tests__/scope-plan.test.ts @@ -0,0 +1,194 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * How a scoped search reads its passage table, pinned by the query plan, not + * by a clock: on a remote database each pass over the table costs its rows' + * pages over the network, and the statement is bounded (`requestTimeoutMs`). + * A record scope or a metadata filter is read once a statement, into the set + * of the passages in scope, and every other read of the passage table is a + * lookup by its key; the keyword leg's candidates are read once, not once for + * its counts and once for its ranks. And a request past its bound answers + * `TIMEOUT` (504), never "the store is not ready". + */ + +import { afterAll, describe, expect, it } from 'vitest'; +import type { Client, InArgs } from '@libsql/client'; +import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai'; +import type { AdapterContext, AdapterSearchOptions } from '@objectstack/spec/contracts'; +import { TursoKnowledgeAdapter } from '../index.js'; +import { FakeEmbedder, storeOf } from './turso.testkit.js'; + +const source = (name: string): KnowledgeSource => + ({ name, label: name, adapter: 'under_test', source: { kind: 'object', object: 'clause', content: ['body'] } }) as KnowledgeSource; + +const FP = { fingerprint: 'fp-test:scope', recipeHash: 'rh-test:1' }; +const ctx = (s: KnowledgeSource): AdapterContext => ({ source: s, reason: 'manual', index: FP }); + +/** Clause `i` of policy `i % 6`, in unit `i % 3`, in organization `org_a`; the text shares words across clauses. */ +function clauses(s: KnowledgeSource, n: number): KnowledgeDocument[] { + return Array.from({ length: n }, (_, i) => { + const id = `${s.name}:${String(i).padStart(3, '0')}`; + const content = `差旅 住宿标准 年假 ${i % 2 === 0 ? '出差 报销' : '涉密 岗位'} clause w${i % 9}x w${(i * 7) % 11}x`; + return { + id, + sourceId: s.name, + sourceRecordId: `r${i}`, + organizationId: 'org_a', + content, + title: `Policy ${i % 6}`, + metadata: { policy: `pol_${i % 6}`, units: ['root', `unit_${i % 3}`], status: i % 4 === 0 ? 'draft' : 'published' }, + chunks: [{ id: `${id}#0`, documentId: id, index: 0, content }], + }; + }); +} + +/** A client that records every statement it runs, beside the raw client the plans are read on. */ +function recording(raw: Client) { + const statements: Array<{ sql: string; args: InArgs }> = []; + const client = new Proxy(raw, { + get(t, key) { + const value = Reflect.get(t, key, t) as unknown; + if (typeof value !== 'function') return value; + const fn = (value as (...a: unknown[]) => unknown).bind(t); + if (key !== 'execute') return fn; + return (st: string | { sql: string; args?: InArgs }) => { + statements.push(typeof st === 'string' ? { sql: st, args: [] } : { sql: st.sql, args: st.args ?? [] }); + return fn(st); + }; + }, + }) as Client; + return { client, statements }; +} + +interface PlanRow { + id: number; + parent: number; + detail: string; +} + +/** + * The reads of `table` (the passage table itself, never its `-kw`, `-fts`, + * `-vec` or `-org` objects' own rows) a plan makes other than a lookup by its + * key, each with the plan steps above it. + */ +function passesOver(plan: PlanRow[], table: string): Array<{ detail: string; under: string[] }> { + const byId = new Map(plan.map((r) => [r.id, r])); + const own = new RegExp(`^(SCAN|SEARCH) ${table}(?![-_\\w])`); + const byKey = new RegExp(`USING (COVERING )?INDEX sqlite_autoindex_${table}_1 \\(chunk_id=\\?\\)$`); + return plan + .filter((r) => own.test(r.detail) && !byKey.test(r.detail)) + .map((r) => { + const under: string[] = []; + for (let p = byId.get(r.parent); p; p = byId.get(p.parent)) under.push(p.detail); + return { detail: r.detail, under }; + }); +} + +describe('knowledge-turso: a scoped search reads its passage table once a statement', () => { + const store = storeOf('file'); + afterAll(() => store.closeAll()); + + async function built(name: string, vectorIndexThreshold: number) { + const raw = store.client(); + const watched = recording(raw); + const s = source(name); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: watched.client, embedder: new FakeEmbedder(), vectorIndexThreshold }); + await adapter.beginBuild(ctx(s)); + await adapter.upsert(clauses(s, 48), ctx(s)); + await adapter.completeBuild(ctx(s)); + return { raw, adapter, s, table: `knowledge_${name}_g1`, statements: watched.statements }; + } + + /** The search statements (`WITH …`) one search ran, each with its plan. */ + async function plansOf(at: Awaited>, opts: Partial, query = '我在集团干了几年 年假 住宿标准 w1x') { + const from = at.statements.length; + const hits = await at.adapter.search(query, { source: at.s, topK: 4, index: { fingerprint: FP.fingerprint }, ...opts }); + const searches = at.statements.slice(from).filter((st) => /^\s*WITH\b/.test(st.sql)); + expect(searches.length).toBeGreaterThan(0); + const plans: PlanRow[][] = []; + for (const st of searches) { + const plan = await at.raw.execute({ sql: `EXPLAIN QUERY PLAN ${st.sql}`, args: st.args }); + plans.push(plan.rows.map((r) => ({ id: Number(r.id), parent: Number(r.parent), detail: String(r.detail) }))); + } + return { hits, plans }; + } + + const scopes: Array<[string, Partial]> = [ + ['a metadata (parent) scope term', { organizationIds: ['org_a'], scope: [{ kind: 'metadata', field: 'units', ids: ['unit_1'] }] }], + ['a record scope term', { scope: [{ kind: 'record', ids: ['r1', 'r4', 'r7'] }] }], + ['a parent and a record term', { scope: [{ kind: 'metadata', field: 'policy', ids: ['pol_2'] }, { kind: 'record', ids: ['r5'] }] }], + ['a metadata filter', { filter: { status: 'published' } }], + ]; + + for (const index of [{ name: 'exact', threshold: Infinity }, { name: 'approximate', threshold: 1 }]) { + for (const [what, opts] of scopes) { + it(`${what}, ${index.name} vector leg: the scope is read once, into one set; every other read of the table is by key`, async () => { + const at = await built(`plan_${index.name}_${scopes.findIndex(([w]) => w === what)}`, index.threshold); + const { hits, plans } = await plansOf(at, opts); + expect(hits.length).toBeGreaterThan(0); + for (const plan of plans) { + const passes = passesOver(plan, at.table); + // One pass, the one that fills the scope set; the vector leg, the keyword candidates, the + // keyword counts and the rows answered read the passages in scope by their key. + expect(passes, JSON.stringify(passes)).toHaveLength(1); + expect(passes[0].under).toContain('MATERIALIZE scope'); + // The keyword candidates are read once, for the counts and the ranks both. + expect(plan.filter((r) => r.detail === 'MATERIALIZE cand')).toHaveLength(1); + } + }); + } + } + + it('the scope set holds what the scope held before: the same hits as the terms read row by row', async () => { + const at = await built('plan_same', Infinity); + const docs = clauses(at.s, 48); + const ids = (hits: Array<{ documentId: string }>) => hits.map((h) => h.documentId).sort(); + const inUnit1 = docs.filter((d) => (d.metadata!.units as string[]).includes('unit_1')).map((d) => d.id); + const hits = await at.adapter.search('年假 clause', { source: at.s, topK: 48, scope: [{ kind: 'metadata', field: 'units', ids: ['unit_1'] }] }); + expect(ids(hits)).toEqual([...inUnit1].sort()); + const both = await at.adapter.search('年假 clause', { + source: at.s, + topK: 48, + scope: [{ kind: 'metadata', field: 'policy', ids: ['pol_2'] }], + filter: { status: 'published' }, + }); + expect(ids(both)).toEqual( + docs.filter((d) => d.metadata!.policy === 'pol_2' && d.metadata!.status === 'published').map((d) => d.id).sort(), + ); + }); + + it('a search without a scope or a filter makes no scope set', async () => { + const at = await built('plan_unscoped', Infinity); + const { plans } = await plansOf(at, { organizationIds: ['org_a'] }); + for (const plan of plans) expect(plan.some((r) => r.detail === 'MATERIALIZE scope')).toBe(false); + }); +}); + +describe('knowledge-turso: a request past its bound', () => { + it('answers TIMEOUT (504), "did not answer in time", never "not ready", for a search statement', async () => { + const store = storeOf('memory'); + const real = store.client(); + const s = source('timed'); + await new TursoKnowledgeAdapter({ id: 'under_test', client: real, embedder: new FakeEmbedder() }).upsert(clauses(s, 4), ctx(s)); + // The search statement hangs, as a slow statement on a remote database does. + const hanging = new Proxy(real, { + get(t, key) { + const value = Reflect.get(t, key, t) as unknown; + if (typeof value !== 'function') return value; + const fn = (value as (...a: unknown[]) => unknown).bind(t); + if (key !== 'execute') return fn; + return (st: string | { sql: string }) => + /^\s*WITH\b/.test(typeof st === 'string' ? st : st.sql) ? new Promise(() => undefined) : fn(st); + }, + }) as Client; + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: hanging, embedder: new FakeEmbedder(), requestTimeoutMs: 60 }); + const err = await adapter.search('年假', { source: s, topK: 4, index: { fingerprint: FP.fingerprint } }).then( + () => undefined, + (e: unknown) => e as Error & Record, + ); + expect(err).toMatchObject({ code: 'TIMEOUT', status: 504, remedy: expect.stringContaining('requestTimeoutMs') }); + expect(err!.message).toBe('The knowledge store (libSQL) did not answer in time: a request to its database took longer than 60 ms.'); + expect(err!.message).not.toMatch(/not ready/); + store.closeAll(); + }); +}); diff --git a/packages/plugins/knowledge-turso/src/plugin.ts b/packages/plugins/knowledge-turso/src/plugin.ts index f9567e99e88..26b15fddbd5 100644 --- a/packages/plugins/knowledge-turso/src/plugin.ts +++ b/packages/plugins/knowledge-turso/src/plugin.ts @@ -50,7 +50,7 @@ export interface KnowledgeTursoPluginOptions { /** * The longest one request to the database (a statement, a document's batch, * a commit) may take before the call answers - * `SERVICE_UNAVAILABLE`, for a remote database (`libsql://`, `https://`, + * `TIMEOUT` (504), for a remote database (`libsql://`, `https://`, * `wss://`), whose requests have no bound of their own. Applies to a * `client` given as it is only when set. * @default 10000 for a remote URL; none for a file or `:memory:` diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index ff1f06686bd..1a41a93d37e 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -264,28 +264,15 @@ function boundedClient(client: Client, ms: number): Client { } /** - * `work`, or `SERVICE_UNAVAILABLE` when it has not settled within `ms`. A - * statement that times out inside a transaction is followed by a rollback, - * never a commit, so nothing it began lands; only a COMMIT that times out - * (`commit`) may still land, and its refusal says so. + * `work`, or `TIMEOUT` (504) when it has not settled within `ms`. A statement + * that times out inside a transaction is followed by a rollback, never a + * commit, so nothing it began lands; only a COMMIT that times out (`commit`) + * may still land, and its refusal says so. */ function withTimeout(work: Promise, ms: number, commit = false): Promise { let timer: ReturnType | undefined; const late = new Promise((_, reject) => { - timer = setTimeout( - () => - reject( - notReady( - 'its database did not answer in time', - `A request to the libSQL database took longer than ${ms} ms (the store's \`requestTimeoutMs\`); check that ` + - 'the database is reachable, or raise the bound.' + - (commit - ? ' It was the commit of a write: that write may still be applied. Writes are idempotent, so retry it.' - : ''), - ), - ), - ms, - ); + timer = setTimeout(() => reject(timedOut(ms, commit)), ms); }); // The stalled request settles on its own later; nothing waits for it. work.catch(() => undefined); @@ -345,6 +332,10 @@ function withTimeout(work: Promise, ms: number, commit = false): Promise 0; + const rowsInScope = narrowed ? 'chunk_id IN (SELECT chunk_id FROM scope)' : inScope; args.push(topK); const limit = `?${args.length}`; const tableName = generationTable(opts.source.name, active.generation); const table = quoted(tableName); + const scopeCte = `scope AS MATERIALIZED (SELECT chunk_id FROM ${table} WHERE ${inScope})`; const vectorIndex = vectorIndexNames(tableName); const legs: string[] = []; @@ -778,10 +779,10 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { // The candidate count is bound for the approximate statement alone, after every other value. const candidates = `?${args.length + 1}`; const pool = approximate - ? `SELECT chunk_id, vector_distance_cos(embedding, vector32(?1)) AS distance FROM ${table} WHERE ${inScope} + ? `SELECT chunk_id, vector_distance_cos(embedding, vector32(?1)) AS distance FROM ${table} WHERE ${rowsInScope} AND chunk_id IN (SELECT chunk_id FROM ${quoted(vectorIndex.side)} ORDER BY vector_distance_cos(embedding, vector1bit(?1)) LIMIT ${candidates})` - : `SELECT chunk_id, vector_distance_cos(embedding, vector32(?1)) AS distance FROM ${table} WHERE ${inScope}`; + : `SELECT chunk_id, vector_distance_cos(embedding, vector32(?1)) AS distance FROM ${table} WHERE ${rowsInScope}`; const ranked = (from: string) => `vec AS ( SELECT chunk_id, row_number() OVER (ORDER BY distance, chunk_id) AS pos FROM ${from} WHERE distance < 1 ORDER BY distance, chunk_id LIMIT ${limit})`; @@ -807,10 +808,12 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { // Passages of equal keyword score are ranked by cosine distance, so the // keyword leg never reorders by chunk id what the vector leg ranks. const distance = vectorLeg ? 'vector_distance_cos(embedding, vector32(?1))' : '0'; + // The candidates are read once (MATERIALIZED): `stats` and `kw` both + // read them, and as a subquery each would match every term again. ctes.push( - `cand AS (SELECT chunk_id, ${distance} AS distance, ${matches.map((m, i) => `${m} AS h${i}`).join(', ')} - FROM ${table} WHERE ${inScope} AND (${matches.join(' OR ')}))`, - `stats AS (SELECT (SELECT count(*) FROM ${table} WHERE ${inScope}) AS n, + `cand AS MATERIALIZED (SELECT chunk_id, ${distance} AS distance, ${matches.map((m, i) => `${m} AS h${i}`).join(', ')} + FROM ${table} WHERE ${rowsInScope} AND (${matches.join(' OR ')}))`, + `stats AS (SELECT ${narrowed ? '(SELECT count(*) FROM scope)' : `(SELECT count(*) FROM ${table} WHERE ${inScope})`} AS n, ${matches.map((_, i) => `coalesce(sum(h${i}), 0) AS d${i}`).join(', ')} FROM cand)`, `kw AS ( SELECT chunk_id, row_number() OVER (ORDER BY score DESC, distance, chunk_id) AS pos FROM ( @@ -821,7 +824,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { } // `candidates`: the approximate statement over that many one-bit candidates; absent, the exact one. const statement = (candidates?: number): InStatement => ({ - sql: `WITH ${[...(vectorLeg ? vectorCtes(candidates !== undefined) : []), ...ctes].join(',\n')} + sql: `WITH ${[...(narrowed ? [scopeCte] : []), ...(vectorLeg ? vectorCtes(candidates !== undefined) : []), ...ctes].join(',\n')} SELECT p.chunk_id, p.document_id, p.source_record_id, p.content, p.title, p.metadata, p.doc_hash, p.heading_path, u.vpos, u.kpos${candidates !== undefined ? ', (SELECT count(*) FROM pool) AS pool' : ''} FROM (SELECT chunk_id, min(vpos) AS vpos, min(kpos) AS kpos FROM (${legs.join(' UNION ALL ')}) @@ -1732,6 +1735,27 @@ function vectorIndexNotOurs(table: string, sourceId: string, generation: number) ); } +/** + * A request to the store's database that took longer than its bound: `TIMEOUT` + * (504, ADR-0112), never "not ready" — the database may be up and one + * statement slow, so the caller reads that this request timed out, not that + * the store is down. The message is one sentence with no database detail; + * the remedy is operator text. + */ +function timedOut(ms: number, commit: boolean): Error { + return Object.assign( + new Error(`The knowledge store (libSQL) did not answer in time: a request to its database took longer than ${ms} ms.`), + { + code: 'TIMEOUT', + status: 504, + remedy: + `A request to the libSQL database took longer than ${ms} ms (the store's \`requestTimeoutMs\`); check that ` + + 'the database is reachable and answers its statements within the bound, or raise the bound.' + + (commit ? ' It was the commit of a write: that write may still be applied. Writes are idempotent, so retry it.' : ''), + }, + ); +} + /** * The store is not ready. The message is one sentence with no database * detail, as a search caller may read it; what went wrong and what to do are From d3c750a86e0e50b389bab5fb4a782217c44da965 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 05:14:56 +0000 Subject: [PATCH 02/19] chore(changeset): say that writes past the request bound answer TIMEOUT too Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbaAVoqUQiPmxMVpLst --- .changeset/38675-scoped-search-one-pass.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/38675-scoped-search-one-pass.md b/.changeset/38675-scoped-search-one-pass.md index bd859462237..3f6e7d3452c 100644 --- a/.changeset/38675-scoped-search-one-pass.md +++ b/.changeset/38675-scoped-search-one-pass.md @@ -11,4 +11,4 @@ Before, a search with a record scope or a metadata filter ran its `WHERE` row by Now a scoped or filtered statement reads its `WHERE` once, into the set of the passages in scope, and every other read of the passage table is a lookup by chunk id. The keyword leg's candidates are read once. The same measurement takes about 80 ms for 3 policies and 250 to 450 ms for a unit holding 10% of the passages, and an unscoped statement about 650 ms instead of 1.2 s. The hits are unchanged. -A request that takes longer than `requestTimeoutMs` now answers `TIMEOUT` (504) with "The knowledge store (libSQL) did not answer in time: a request to its database took longer than N ms." Before, it answered `SERVICE_UNAVAILABLE` (503) with "The knowledge store (libSQL) is not ready", which told a caller the store was down when one statement was slow. The operator text in `remedy` still names `requestTimeoutMs`. +Any request that takes longer than `requestTimeoutMs` now answers `TIMEOUT` (504): a search, and also a write, a listing, a build step or a commit. Its message is "The knowledge store (libSQL) did not answer in time: a request to its database took longer than N ms." Before, it answered `SERVICE_UNAVAILABLE` (503) with "The knowledge store (libSQL) is not ready", which told a caller the store was down when one statement was slow. The operator text in `remedy` still names `requestTimeoutMs`. From 40596897a680c5eec337ae581e10f48d979ede8f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 05:24:15 +0000 Subject: [PATCH 03/19] perf(knowledge-turso): compute the keyword leg once a search; send a scope too narrow for the approximate pass straight to the exact scan The first statement of a search computes the keyword leg; a wider approximate pass or the exact scan after it binds the ranks it answered. A scope with a parent term or a metadata filter has its share estimated from 256 rows read by rowid and, under the record scope's cut, goes straight to the exact scan. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01JQwxbaAVoqUQiPmxMVpLst --- .changeset/38676-keyword-once-narrow-exact.md | 14 +++ packages/plugins/knowledge-turso/README.md | 4 +- .../src/__tests__/acceptance.test.ts | 91 ++++++++++------- .../src/__tests__/scope-plan.test.ts | 9 +- packages/plugins/knowledge-turso/src/sql.ts | 18 ++++ .../knowledge-turso/src/turso-adapter.ts | 98 +++++++++++++++---- 6 files changed, 175 insertions(+), 59 deletions(-) create mode 100644 .changeset/38676-keyword-once-narrow-exact.md diff --git a/.changeset/38676-keyword-once-narrow-exact.md b/.changeset/38676-keyword-once-narrow-exact.md new file mode 100644 index 00000000000..eea6bd5e98a --- /dev/null +++ b/.changeset/38676-keyword-once-narrow-exact.md @@ -0,0 +1,14 @@ +--- +'@objectstack/knowledge-turso': patch +--- + +perf(knowledge-turso): the keyword leg is computed once a search, and a scope too narrow for the approximate pass goes straight to the exact scan + +Clause-②: no +Metadata-protocol: none + +Before, every vector statement of one search carried the keyword leg. When the approximate pass fell short and a wider pass or the exact scan followed, the keyword terms (up to 16, the two-character ones matched by `LIKE` over every row in scope) were matched again in each statement. Only a scope of record ids alone was checked for being too narrow for the approximate pass. A scope with a parent (metadata) term or a metadata filter always took the one-bit pass first, then often a pass over 10 times the candidates, then the exact scan. + +Now the first statement of a search computes the keyword leg, and a statement after it binds the ranks the first one answered. A scope with a parent term, or a metadata filter, has its share of the passages estimated from 256 rows of the table, read by rowid (no pass over the table). Under the same cut as a record scope (25% of the passages at the default over-fetch), it goes straight to the exact scan. On 59,621 one-passage records of 1,024 dimensions (`topK` 40, a 16-term Chinese question), a search scoped to 3 policies took about 80 ms instead of 190 ms, one scoped to a unit holding 1.7% of the passages about 150 ms instead of 310 to 680 ms, and one holding 10% about 240 ms instead of 570 to 700 ms. The hits are those of the exact scan, as before. + +The question is still embedded once per call to the adapter. The knowledge service's second round makes a second call, so it embeds the question again. diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index 47b83a4d3bb..0bf9eb8ed3d 100644 --- a/packages/plugins/knowledge-turso/README.md +++ b/packages/plugins/knowledge-turso/README.md @@ -55,10 +55,10 @@ Two legs, merged by reciprocal rank fusion (RRF, `k` = 60) before the knowledge - **Keyword index.** Each passage table `knowledge__g` has one beside it: a map table `…-kw`, a contentless FTS5 table `…-fts` (`tokenize='trigram'`) and three triggers that keep both in step with every insert, rewrite and removal of a passage, inside the statement that writes it. It is made with the table and dropped with it. A table made by a release without one gets it at its first search, built from the rows it holds in one transaction; until then nothing else changes. Its names hold a hyphen, which no source, generation or object name can, and an object under one of them that the store did not make is never dropped or used: the generation is refused `SERVICE_UNAVAILABLE`, naming it. - **Vector leg.** Passages ranked by the cosine distance of their stored vector (`vector_distance_cos`); a passage whose cosine similarity is not positive is not ranked by it. Its ranks 1…`topK` feed the fusion, whichever of the two ways below found the passages. -The organization filter, the record scope (a passage's record, or a metadata value equal to an id as text, a list matching by any element) and the metadata `filter` (JSON equality per key) are one `WHERE`, run in both legs. A search with a record scope or a metadata `filter` reads that `WHERE` once per statement, into a set of the passages in scope, and both legs and the keyword leg's counts read the passages in scope from that set by their key: a metadata term reads each passage's JSON, a pass over the table, which would otherwise be paid once by each leg and once more by the keyword counts. Measured on 59,621 one-passage records of 1,024 dimensions (one organization, `topK` 40, a Chinese question of 16 terms): a search scoped to 3 policies' clauses (90 passages) took about 1.0 s a statement before and 80 ms after, one scoped to a unit holding 10% of them 1.0 to 1.4 s before and 250 to 450 ms after. The keyword leg's candidates are read once a statement, not once for its counts and once for its ranks. +The organization filter, the record scope (a passage's record, or a metadata value equal to an id as text, a list matching by any element) and the metadata `filter` (JSON equality per key) are one `WHERE`, run in both legs. A search with a record scope or a metadata `filter` reads that `WHERE` once per statement, into a set of the passages in scope, and both legs and the keyword leg's counts read the passages in scope from that set by their key: a metadata term reads each passage's JSON, a pass over the table, which would otherwise be paid once by each leg and once more by the keyword counts. Measured on 59,621 one-passage records of 1,024 dimensions (one organization, `topK` 40, a Chinese question of 16 terms): a search scoped to 3 policies' clauses (90 passages) took about 1.0 s a statement before and 80 ms after, one scoped to a unit holding 10% of them 1.0 to 1.4 s before and 250 to 450 ms after. The keyword leg's candidates are read once a statement, not once for its counts and once for its ranks. And the keyword leg is computed once a search: when the approximate pass falls short and a wider pass or the exact scan follows, that statement binds the keyword ranks the first one answered. - **Exact scan.** The vector leg reads every row in scope. Measured on Linux x64 with 1,536-wide vectors: 1,000 passages take 8.3 MB and a search about 5 ms; 10,000 passages take 82 MB and a search about 50 ms. -- **Approximate index, for a large source.** When a complete build of a source completes (`os knowledge rebuild`, a fingerprint change, the boot build or the daily reconcile — they all end in `completeBuild`) on a generation of `vectorIndexThreshold` passages or more (default 20,000), the store makes that generation's approximate index: every passage's vector quantized to one bit a dimension, in a side table a 32nd the size of the vectors. The vector leg then ranks the side table by its one-bit vectors, takes the nearest `topK × vectorIndexOverfetch` (default 40 a hit) as candidates, runs the same `WHERE` over them, and ranks those in scope by their stored float32 vector. The candidates are ranked before the filter, so a leg the filter leaves with fewer than 8 × `topK` candidates in scope, or short of `topK` hits, is run again as the exact scan. The float32 re-rank of a thin pool misses the neighbours the one-bit ranking put past the cut: measured at 200,000 passages, a pool of `topK` gave a recall@10 of 0.88 with 3% of the passages in scope, and a pool of 4 × `topK` still left a query at 0.7 with 10% in scope. Before that exact scan, a leg whose scope is not of record terms alone (no scope, or a parent term) tries one more pass over 10 times the candidates, under the same floor, when its first pool says that can clear it: measured at 200,000 passages under a parent scope keeping 10% to 20% of them, about 0.35 s at p95 instead of about 0.9 s for the exact scan, at the same recall. A scope of record terms alone has no second pass, since the record index lets the exact scan read only the rows in scope, and when it keeps too few passages for the first pass to be expected to keep 1.25 × that floor (with the default over-fetch, under 25% of the source's passages, estimated from the passages of at most 256 of its ids), it skips the first pass too and goes straight to the exact scan: measured at 200,000 passages with 5%, 10% and 20% of them in scope, p95 74, 143 and 289 ms instead of 219, 321 and 418 ms (the exact scan alone: 81, 154 and 291 ms). So a search whose scope keeps a small share of a source's passages is answered by the exact scan, and the index speeds up the broad ones. And a search never answers fewer hits than the exact scan would, since the knowledge service reads "fewer than asked" as "no more there". +- **Approximate index, for a large source.** When a complete build of a source completes (`os knowledge rebuild`, a fingerprint change, the boot build or the daily reconcile — they all end in `completeBuild`) on a generation of `vectorIndexThreshold` passages or more (default 20,000), the store makes that generation's approximate index: every passage's vector quantized to one bit a dimension, in a side table a 32nd the size of the vectors. The vector leg then ranks the side table by its one-bit vectors, takes the nearest `topK × vectorIndexOverfetch` (default 40 a hit) as candidates, runs the same `WHERE` over them, and ranks those in scope by their stored float32 vector. The candidates are ranked before the filter, so a leg the filter leaves with fewer than 8 × `topK` candidates in scope, or short of `topK` hits, is run again as the exact scan. The float32 re-rank of a thin pool misses the neighbours the one-bit ranking put past the cut: measured at 200,000 passages, a pool of `topK` gave a recall@10 of 0.88 with 3% of the passages in scope, and a pool of 4 × `topK` still left a query at 0.7 with 10% in scope. Before that exact scan, a leg whose scope is not of record terms alone (no scope, or a parent term) tries one more pass over 10 times the candidates, under the same floor, when its first pool says that can clear it: measured at 200,000 passages under a parent scope keeping 10% to 20% of them, about 0.35 s at p95 instead of about 0.9 s for the exact scan, at the same recall. A scope of record terms alone has no second pass, since the record index lets the exact scan read only the rows in scope. Any scope, or a metadata `filter`, that keeps too few passages for the first pass to be expected to keep 1.25 × that floor (with the default over-fetch, under 25% of the source's passages) skips the first pass too and goes straight to the exact scan. A scope of record terms alone is estimated from the passages of at most 256 of its ids, counted through the record index; any other is estimated from 256 rows of the table at evenly spread rowids, read by key: measured at 200,000 passages with 5%, 10% and 20% of them in scope, p95 74, 143 and 289 ms instead of 219, 321 and 418 ms (the exact scan alone: 81, 154 and 291 ms). So a search whose scope keeps a small share of a source's passages is answered by the exact scan, and the index speeds up the broad ones. And a search never answers fewer hits than the exact scan would, since the knowledge service reads "fewer than asked" as "no more there". - **Measured** on Linux x64 at 200,000 passages of 1,536 dimensions (clustered synthetic vectors, one organization, `topK` 10, on a shared machine): a search whose keyword leg matches nothing took 66 ms at the median and 81 ms at p95 (the exact scan: 958 ms and 1,054 ms), with a recall@10 against the exact scan of 0.998 over 100 queries; a hybrid search took 550 ms and 666 ms (exact: 1,416 ms and 1,544 ms), recall@10 1.000 — the keyword leg, unchanged, is most of that, and a term under three characters (`LIKE` over every row in scope) alone costs about 600 ms there. - **When it is built.** At the end of a complete build, never on a search: the side table is made empty in one transaction, then the passage table's rows are copied in, 2,048 to a transaction, before the generation is switched to (or, for a build inside the active generation, while it keeps answering by the exact scan); 200,000 passages took 3 s and 54 MB. Every write after that also writes the passage's one-bit vector. A source that grows past the threshold between builds keeps the exact scan until its next complete build — at the latest the next daily reconcile. A database that refuses the one-bit vectors or the index's DDL (a host whose libSQL lacks them) gets no index: the build completes, the source keeps the exact scan, and the adapter's health check (the plugin's boot line, the knowledge health endpoint) names the source and the reason until a later build makes the index. A copy batch the database refuses ends the copy the same way: the side table, short of its passage table, is never searched, and the next complete build resumes it. The health check's record of a refusal is kept by the process that ran the build, until it restarts. - **What a search reads to choose.** A process reads the store's catalog (two reads) the first time it searches a generation, and remembers whether that generation's index is complete. The memory is keyed per generation instance: its number and the time its row was made. A build remembers what it found for its own process, so a source under the threshold costs no catalog read there, and two reads once in any other process. With `vectorIndexThreshold: Infinity` a search never reads the catalog for an index, so an index made earlier under a finite threshold stays in place and is not searched. An index another process completes inside the active generation is used here after this process's next complete build of the source, or a restart. A search that takes the index also reads the organization index (three seeks). diff --git a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts index e6d5546dde8..3354b1920e7 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts @@ -12,7 +12,7 @@ */ import { afterAll, describe, expect, it } from 'vitest'; -import type { Client } from '@libsql/client'; +import type { Client, InArgs } from '@libsql/client'; import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai'; import type { AdapterContext, IDataEngine, IEmbedder } from '@objectstack/spec/contracts'; import type { ExecutionContext } from '@objectstack/spec/kernel'; @@ -1327,12 +1327,13 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { ]; // Eight candidates a hit, so the candidates are not every row of this small table. const { adapter, sql } = await built(s, docs, { vectorIndexOverfetch: 8 }); - // A filter only the far passages pass: none is among the candidates, so the exact scan answers. + // A filter only the far passages pass: 4 of 60, estimated from a sample of the rows as under the cut, + // so the exact scan answers without a one-bit pass none of whose candidates it keeps. let from = sql.length; const drafts = await adapter.search(QUERY, { source: s, topK: 3, filter: { status: 'draft' } }); expect(drafts).toHaveLength(3); for (const hit of drafts) expect(hit.metadata).toMatchObject({ status: 'draft' }); - expect(vectorLegs(sql, from)).toEqual({ approximate: 1, exact: 1 }); + expect(vectorLegs(sql, from)).toEqual({ approximate: 0, exact: 1 }); const t = source('ann_overfetch'); const tiers = [ ...['best_1', 'best_2'].map((n) => doc(t, n, QUERY)), @@ -1357,23 +1358,25 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { expect(vectorLegs(over.sql, from)).toEqual({ approximate: 0, exact: 1 }); }); - it('a leg under 8 × topK in scope tries 10 × the candidates once before the exact scan, unless its pool is too thin or its scope is of records alone', async () => { + it('a leg under 8 × topK in scope tries 10 × the candidates once before the exact scan, unless its pool is too thin, its scope too narrow or of records alone; the keyword leg is computed once', async () => { const QUERY = 'w1x w2x w3x w4x'; - // Two best passages, 30 next to them and 368 further away, each with a list of tags a parent - // (metadata) scope term matches: 'wide' holds the two best and half the far ones, 'short' the two - // best and 3 next ones, 'thin' one far passage. + // Two best passages, 100 next to them and 298 further away, each with a list of tags a parent + // (metadata) term matches: 'wide' holds the two best and half the far ones (151, 38%), 'thin' the + // other half of the far ones (149, 37%), 'short' the two best and 3 next ones (5, 1%). const corpus = (s: KnowledgeSource) => [ ...['best_1', 'best_2'].map((n) => doc(s, n, QUERY, { metadata: { tags: ['wide', 'short'] } })), - ...Array.from({ length: 30 }, (_, i) => - doc(s, `mid_${String(i).padStart(2, '0')}`, `${QUERY} w${(i % 20) + 5}x w${(i % 7) + 30}x`, { metadata: { tags: [i < 3 ? 'short' : 'out'] } }), + ...Array.from({ length: 100 }, (_, i) => + doc(s, `mid_${String(i).padStart(3, '0')}`, `${QUERY} w${(i % 20) + 5}x w${(i % 7) + 30}x`, { metadata: { tags: [i < 3 ? 'short' : 'out'] } }), ), - ...wordsOf(368, 23).map((text, i) => - doc(s, `rest_${String(i).padStart(3, '0')}`, `w1x ${text}`, { metadata: { tags: i % 2 === 0 ? ['wide'] : i === 1 ? ['out', 'thin'] : ['out'] } }), + ...wordsOf(298, 23).map((text, i) => + doc(s, `rest_${String(i).padStart(3, '0')}`, `w1x ${text}`, { metadata: { tags: i % 2 === 0 ? ['wide'] : ['thin'] } }), ), ]; const s = source('ann_retry'); - // topK 2 and 8 candidates a hit: 16 candidates, a floor of 16, and 160 for the second pass. - const { adapter, sql, args } = await built(s, corpus(s), { vectorIndexOverfetch: 8 }); + // topK 2 and the default 40 candidates a hit: 80 candidates, a floor of 16, and 800 for the second + // pass. A parent term is estimated from a sample of the rows; under 25% of them goes straight to + // the exact scan. + const { adapter, sql, args, client: adapterClient } = await built(s, corpus(s)); const t = source('ann_retry_exact'); const exact = await built(t, corpus(t), { vectorIndexThreshold: Infinity }); const ids = (hits: Array<{ sourceRecordId?: string }>) => hits.map((h) => h.sourceRecordId); @@ -1384,35 +1387,53 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { expect(ids(hits), JSON.stringify(scope).slice(0, 60)).toEqual(ids(await exact.adapter.search(QUERY, { source: t, topK: 2, scope }))); return { hits, from }; }; + // The vector statements since `from` that compute the keyword leg, and those that bind its ranks. + const keywordLeg = (from: number) => { + const legs = sql.slice(from).filter((q) => q.includes('vec AS (')); + return { computed: legs.filter((q) => q.includes('cand AS')).length, bound: legs.filter((q) => q.includes('kw AS (SELECT json_extract(')).length }; + }; - // 'wide': the first pass keeps the 2 best of its 16 candidates; 10 × a pool of 2 can reach 16, and the - // second pass keeps far more than 16 of its 160, so it answers, as the exact scan would, without it. + // 'wide': the first pass keeps the 2 best of its 80 candidates (the next 78 are the near passages + // out of scope); 10 × a pool of 2 can reach 16, and the second pass keeps far more than 16 of its + // 800, so it answers, as the exact scan would, without it. let { hits, from } = await search(tagged('wide')); expect(ids(hits)).toEqual(['best_1', 'best_2']); expect(vectorLegs(sql, from)).toEqual({ approximate: 2, exact: 0 }); - expect(sql.flatMap((q, i) => (i >= from && q.includes('vector1bit(') ? [args[i][args[i].length - 1]] : []))).toEqual([16, 160]); + expect(sql.flatMap((q, i) => (i >= from && q.includes('vector1bit(') ? [args[i][args[i].length - 1]] : []))).toEqual([80, 800]); + // The second pass binds the keyword ranks the first answered, never computes them again. + expect(keywordLeg(from)).toEqual({ computed: 1, bound: 1 }); // Each pass binds exactly the values it reads, its candidate count last. for (const st of vectorStatements({ sql, args }, from)) expect(st).toMatchObject({ reads: st.bound }); - // 'short': five passages in scope, so both passes keep at most 5, and the exact scan answers after both. - ({ from } = await search(tagged('short'))); - expect(vectorLegs(sql, from)).toEqual({ approximate: 2, exact: 1 }); - - // 'thin': one far passage, no candidate of the first pass; 10 × 0 cannot reach 16, so there is no - // second pass. - ({ hits, from } = await search(tagged('thin'))); - expect(ids(hits)).toEqual(['rest_001']); + // 'thin': no candidate of the first pass is in scope; 10 × 0 cannot reach 16, so there is no + // second pass, and the exact scan binds the first pass's keyword ranks. + ({ from } = await search(tagged('thin'))); expect(vectorLegs(sql, from)).toEqual({ approximate: 1, exact: 1 }); + expect(keywordLeg(from)).toEqual({ computed: 1, bound: 1 }); + for (const st of vectorStatements({ sql, args }, from)) expect(st).toMatchObject({ reads: st.bound }); - // The 'wide' passages as a scope of records alone: the record index serves the exact scan from the - // rows in scope, so there is no second pass, and at 8 candidates a hit no first one either: no share - // of the passages lets the 16 candidates be expected to keep 1.25 × the floor of 16. + // 'short': five passages in scope, estimated under the cut from the sample: the exact scan alone. + ({ hits, from } = await search(tagged('short'))); + expect(ids(hits)).toEqual(['best_1', 'best_2']); + expect(vectorLegs(sql, from)).toEqual({ approximate: 0, exact: 1 }); + // The sample reads its rows by rowid, never a pass over the table. + const at = sql.findIndex((q, i) => i >= from && /^\s*WITH RECURSIVE\b/.test(q)); + expect(at).toBeGreaterThanOrEqual(from); + const plan = await adapterClient.execute({ sql: `EXPLAIN QUERY PLAN ${sql[at]}`, args: args[at] as InArgs }); + const reads = plan.rows.map((r) => String(r.detail)).filter((d) => new RegExp(`^(SCAN|SEARCH) knowledge_${s.name}_g1(?![-_\\w])`).test(d)); + expect(reads.length).toBeGreaterThan(0); + // Seeks only: the bounds (min and max rowid) and the sampled rows by rowid; never a SCAN. + for (const read of reads) expect(read).toMatch(/^SEARCH /); + + // The 'wide' passages as a scope of records alone: 151 of 400 passages, over the cut, take the first + // pass; its pool of 2 is short, and the record index serves the exact scan from the rows in scope, + // so there is no second pass. const records = corpus(s) .filter((d) => (d.metadata?.tags as string[] | undefined)?.includes('wide')) .flatMap((d) => d.sourceRecordId ?? []); ({ hits, from } = await search([{ kind: 'record', ids: records }])); expect(ids(hits)).toEqual(['best_1', 'best_2']); - expect(vectorLegs(sql, from)).toEqual({ approximate: 0, exact: 1 }); + expect(vectorLegs(sql, from)).toEqual({ approximate: 1, exact: 1 }); // Two builds of 400 passages on each store kind: past vitest's 5 s default on a loaded CI box. }, 30_000); @@ -1456,9 +1477,11 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { // spread over the 340, as about 40 passages, so the exact scan alone. const absent = Array.from({ length: 300 }, (_, i) => `gone_${i}`); expect(await search([{ kind: 'record', ids: [...absent, ...records(200, 240)] }])).toEqual({ approximate: 0, exact: 1 }); - // The narrow records beside a parent (metadata) term: the record index does not serve that scan, so - // the approximate pass runs as before, here answering from its first pool. - expect(await search([{ kind: 'record', ids: records(190, 240) }, { kind: 'metadata', field: 'status', ids: ['none'] }])).toEqual({ approximate: 1, exact: 0 }); + // The narrow records beside a parent (metadata) term: the record index cannot count that scope, so its + // share is estimated from a sample of the rows, 50 of 400 passages, under the cut: the exact scan alone. + expect(await search([{ kind: 'record', ids: records(190, 240) }, { kind: 'metadata', field: 'status', ids: ['none'] }])).toEqual({ approximate: 0, exact: 1 }); + // A wider one, 250 of 400 (records 090…239 and the 50 passages of records 030…039), takes the first pass. + expect((await search([{ kind: 'record', ids: [...records(30, 40), ...records(90, 240)] }, { kind: 'metadata', field: 'status', ids: ['none'] }])).approximate).toBe(1); // The count of the passages in scope binds the scope's ids alone, term by term. const counts = sql.flatMap((q, i) => (!q.includes('vec AS (') && q.includes('source_record_id IN (SELECT value FROM json_each(?1))') ? [args[i]] : [])); expect(counts.map((bound) => bound.length)).toEqual([1, 1, 1, 1, 1]); @@ -1595,15 +1618,15 @@ for (const kind of ['memory', 'file'] as StoreKind[]) { await adapter.completeBuild(ctx(s)); expect(keywordTerms('?! …')).toEqual([]); const from = watched.sql.length; - // Answered through the index; then a scope of its two records beside a parent term, under the - // floor, runs both approximate passes and the exact scan, and the two records alone the exact scan. + // Answered through the index; then a scope of its two records beside a parent term, and the two + // records alone, each estimated under the cut (the first from a sample of the rows), the exact scan. const hits = await adapter.search('?! …', { source: s, topK: 2 }); expect(hits).toHaveLength(2); const ids = hits.flatMap((h) => h.sourceRecordId ?? []); expect(await adapter.search('?! …', { source: s, topK: 2, scope: [{ kind: 'record', ids }, { kind: 'metadata', field: 'status', ids: ['none'] }] })).toHaveLength(2); expect(await adapter.search('?! …', { source: s, topK: 2, scope: [{ kind: 'record', ids }] })).toHaveLength(2); const statements = vectorStatements(watched, from); - expect(statements.map((st) => st.approximate)).toEqual([true, true, true, false, false]); + expect(statements.map((st) => st.approximate)).toEqual([true, false, false]); for (const st of statements) expect(st).toMatchObject({ reads: st.bound }); }); diff --git a/packages/plugins/knowledge-turso/src/__tests__/scope-plan.test.ts b/packages/plugins/knowledge-turso/src/__tests__/scope-plan.test.ts index e2ff4fbab88..b07a536836a 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/scope-plan.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/scope-plan.test.ts @@ -103,7 +103,8 @@ describe('knowledge-turso: a scoped search reads its passage table once a statem async function plansOf(at: Awaited>, opts: Partial, query = '我在集团干了几年 年假 住宿标准 w1x') { const from = at.statements.length; const hits = await at.adapter.search(query, { source: at.s, topK: 4, index: { fingerprint: FP.fingerprint }, ...opts }); - const searches = at.statements.slice(from).filter((st) => /^\s*WITH\b/.test(st.sql)); + // The search statements, not the estimate of a scope's share (`WITH RECURSIVE`, a sample of rows by rowid). + const searches = at.statements.slice(from).filter((st) => /^\s*WITH\b/.test(st.sql) && !/^\s*WITH RECURSIVE\b/.test(st.sql)); expect(searches.length).toBeGreaterThan(0); const plans: PlanRow[][] = []; for (const st of searches) { @@ -132,9 +133,11 @@ describe('knowledge-turso: a scoped search reads its passage table once a statem // keyword counts and the rows answered read the passages in scope by their key. expect(passes, JSON.stringify(passes)).toHaveLength(1); expect(passes[0].under).toContain('MATERIALIZE scope'); - // The keyword candidates are read once, for the counts and the ranks both. - expect(plan.filter((r) => r.detail === 'MATERIALIZE cand')).toHaveLength(1); } + // The keyword candidates are read once a search, for the counts and the ranks both: by the + // first statement, and never again by a vector statement after it. + expect(plans.flat().filter((r) => r.detail === 'MATERIALIZE cand')).toHaveLength(1); + expect(plans[0].some((r) => r.detail === 'MATERIALIZE cand')).toBe(true); }); } } diff --git a/packages/plugins/knowledge-turso/src/sql.ts b/packages/plugins/knowledge-turso/src/sql.ts index bd18494e4b7..7c16cd5b83b 100644 --- a/packages/plugins/knowledge-turso/src/sql.ts +++ b/packages/plugins/knowledge-turso/src/sql.ts @@ -495,3 +495,21 @@ export const METADATA_VALUE_JSON = `CASE type * matches the id `'7'`. Booleans, null and objects match no id. */ export const SCOPE_SCALAR_TYPES = `('text', 'integer', 'real')`; + +/** + * The statement that estimates the share of the passages of `table` a + * `WHERE` (`inScope`, over the table's own columns) keeps, from `size` rows + * at evenly spread rowids between the least and the greatest: `seen`, the + * sampled rowids that hold a row (a removed row leaves a gap; none for an + * empty table), and `hit`, those in scope. Two seeks for the bounds (each + * bound a scalar subquery of its own, which SQLite answers from the end of + * the table's b-tree) and `size` key lookups, never a pass over the table. + */ +export function scopeSampleSql(table: string, inScope: string, size: number): string { + if (!Number.isInteger(size) || size < 2) throw new RangeError(`knowledge-turso: a scope sample holds 2 rows or more, got ${String(size)}`); + const t = quoted(table); + return `WITH RECURSIVE k(i) AS (SELECT 0 UNION ALL SELECT i + 1 FROM k WHERE i < ${size - 1}), + b AS (SELECT (SELECT min(rowid) FROM ${t}) AS lo, (SELECT max(rowid) FROM ${t}) AS hi) + SELECT count(*) AS seen, coalesce(sum(CASE WHEN ${inScope} THEN 1 ELSE 0 END), 0) AS hit + FROM ${t} WHERE rowid IN (SELECT b.lo + ((b.hi - b.lo) * k.i) / ${size - 1} FROM k, b)`; +} diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index 1a41a93d37e..93aa4111847 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -35,6 +35,7 @@ import { legacyTable, passageTableDdl, quoted, + scopeSampleSql, dropVectorIndexDdl, organizationIndexDdl, vectorBackfillSql, @@ -150,8 +151,8 @@ const VECTOR_RETRY_POOL = 10; /** * How many times the floor ({@link VECTOR_MIN_POOL} × topK) the first - * approximate pass must be expected to keep in scope for a scope of record - * terms alone to take it: its `topK × vectorIndexOverfetch` candidates times + * approximate pass must be expected to keep in scope for a scope (of record + * terms, of parent terms, or a metadata filter) to take it: its `topK × vectorIndexOverfetch` candidates times * the share of the passages in scope. A narrower scope goes straight to the * exact scan, which the record index serves from the rows in scope; the * one-bit pass reads every row of the table, and under such a scope it often @@ -168,6 +169,13 @@ const VECTOR_RECORD_SCOPE_POOL = 1.25; /** At most how many of a record scope's ids the estimate of its passages counts ({@link VECTOR_RECORD_SCOPE_POOL}). */ const VECTOR_SCOPE_SAMPLE = 256; +/** + * How many rows of a passage table the estimate of a parent-term or filtered + * scope's share reads ({@link VECTOR_RECORD_SCOPE_POOL}): at the cut of 25%, + * a standard error of about 2.7 points. + */ +const VECTOR_SCOPE_ROW_SAMPLE = 256; + /** How many passages one batch of a vector index's copy writes: each batch is a transaction of its own, so a search waits at most one batch. */ const VECTOR_BACKFILL_BATCH = 2048; @@ -316,9 +324,13 @@ function withTimeout(work: Promise, ms: number, commit = false): Promise { - // The candidate count is bound for the approximate statement alone, after every other value. - const candidates = `?${args.length + 1}`; + const vectorCtes = (approximate: boolean, candidates: string): string[] => { const pool = approximate ? `SELECT chunk_id, vector_distance_cos(embedding, vector32(?1)) AS distance FROM ${table} WHERE ${rowsInScope} AND chunk_id IN (SELECT chunk_id FROM ${quoted(vectorIndex.side)} @@ -822,16 +836,36 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { ); legs.push('SELECT chunk_id, NULL AS vpos, pos AS kpos FROM kw'); } - // `candidates`: the approximate statement over that many one-bit candidates; absent, the exact one. - const statement = (candidates?: number): InStatement => ({ - sql: `WITH ${[...(narrowed ? [scopeCte] : []), ...(vectorLeg ? vectorCtes(candidates !== undefined) : []), ...ctes].join(',\n')} + // `candidates`: the approximate statement over that many one-bit + // candidates; absent, the exact one. `keyword`: the keyword leg's ranks + // an earlier statement of this search answered, bound as JSON and read + // as they are, so the leg is computed once a search however many vector + // statements follow; absent, the statement computes the leg itself. + const statement = (candidates?: number, keyword?: ReadonlyArray): InStatement => { + const bound: unknown[] = keyword === undefined ? [...args] : [...args.slice(0, shared), JSON.stringify(keyword)]; + const keywordCtes = + keyword === undefined + ? ctes + : [`kw AS (SELECT json_extract(value, '$[0]') AS chunk_id, json_extract(value, '$[1]') AS pos FROM json_each(?${bound.length}))`]; + // The candidate count is bound for the approximate statement alone, after every other value. + if (candidates !== undefined) bound.push(candidates); + const sql = `WITH ${[ + ...(narrowed ? [scopeCte] : []), + ...(vectorLeg ? vectorCtes(candidates !== undefined, `?${bound.length}`) : []), + ...keywordCtes, + ].join(',\n')} SELECT p.chunk_id, p.document_id, p.source_record_id, p.content, p.title, p.metadata, p.doc_hash, p.heading_path, u.vpos, u.kpos${candidates !== undefined ? ', (SELECT count(*) FROM pool) AS pool' : ''} FROM (SELECT chunk_id, min(vpos) AS vpos, min(kpos) AS kpos FROM (${legs.join(' UNION ALL ')}) GROUP BY chunk_id) u - JOIN ${table} p ON p.chunk_id = u.chunk_id`, - args: (candidates !== undefined ? [...args, candidates] : args) as InArgs, - }); + JOIN ${table} p ON p.chunk_id = u.chunk_id`; + return { sql, args: bound as InArgs }; + }; + // The keyword leg's ranks a statement answered, to bind into the next one. + const keywordRanks = (answered: ResultSet): Array<[string, number]> | undefined => + terms.length === 0 + ? undefined + : answered.rows.flatMap((r) => (r.kpos === null ? [] : [[String(r.chunk_id), Number(r.kpos)] as [string, number]])); const result = await this.queued(client, async () => { // The generation may have been switched while the query was embedded. const now = await this.generations(opts.source.name); @@ -840,14 +874,18 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { const instance = now.active.createdAt; if (vectorLeg && (await this.approximateSearchable(tableName, instance))) { const candidates = topK * this.vectorIndexOverfetch; - // A scope of record terms alone that the first pass is not expected - // to answer goes straight to the exact scan, which the record index - // serves from the rows in scope. + // A scope the first pass is not expected to answer goes straight to + // the exact scan, which reads the passages in scope by their key: a + // scope of record terms alone counted through the record index, any + // other scope or filter estimated from a sample of the table's rows. if (recordScope && (await this.recordScopeUnderCut(client, tableName, recordTerms))) return client.execute(statement()); + if (narrowed && !recordScope && (await this.scopeUnderCut(client, tableName, inScope, args.slice(0, shared - 1)))) { + return client.execute(statement()); + } // A failed approximate statement (its index gone under this process's // memory of it) forgets that memory and is answered by the exact scan. - const approximate = (candidates: number) => - client.execute(statement(candidates)).catch(() => { + const approximate = (candidates: number, keyword?: ReadonlyArray) => + client.execute(statement(candidates, keyword)).catch(() => { this.vectorIndexKnown.delete(vectorIndexKey(tableName, instance)); return undefined; }); @@ -862,15 +900,18 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { const near = await approximate(candidates); if (near === undefined) return client.execute(statement()); if (stands(near)) return near; + // The statements after the first bind its keyword ranks, never compute them again. + const keyword = keywordRanks(near); // Such a leg tries VECTOR_RETRY_POOL times the candidates once, under // the same floor, when the first pool says the wider one can reach it; // otherwise, or short again, the exact scan answers. Not under a scope // of record terms alone: the record index serves that exact scan from // the rows in scope, which costs less than the wider pass. if (!recordScope && poolOf(near) * VECTOR_RETRY_POOL >= VECTOR_MIN_POOL * topK) { - const wide = await approximate(candidates * VECTOR_RETRY_POOL); + const wide = await approximate(candidates * VECTOR_RETRY_POOL, keyword); if (wide !== undefined && stands(wide)) return wide; } + return client.execute(statement(undefined, keyword)); } return client.execute(statement()); }); @@ -1312,6 +1353,23 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { return inScope * this.vectorIndexOverfetch < VECTOR_RECORD_SCOPE_POOL * VECTOR_MIN_POOL * n; } + /** + * Whether a scope with a parent (metadata) term, or a metadata filter, of + * the `WHERE` `inScope` (whose values `args` binds from `?1`), keeps fewer + * of the passages of `table` than the first approximate pass needs, by the + * cut {@link recordScopeUnderCut} applies. Such a scope has no index, so its + * share is estimated on {@link VECTOR_SCOPE_ROW_SAMPLE} rows of the table at + * evenly spread rowids ({@link scopeSampleSql}): that many key lookups, + * never a pass over the table. Runs inside the client's queue. + */ + private async scopeUnderCut(db: Pick, table: string, inScope: string, args: unknown[]): Promise { + const counted = await db.execute({ sql: scopeSampleSql(table, inScope, VECTOR_SCOPE_ROW_SAMPLE), args: args as InArgs }); + const { seen, hit } = counted.rows[0]; + if (Number(seen) === 0) return true; + const share = Number(hit) / Number(seen); + return share * this.vectorIndexOverfetch < VECTOR_RECORD_SCOPE_POOL * VECTOR_MIN_POOL; + } + /** Forgets what this process knew of the approximate vector index of every instance of the passage table `table`. */ private forgetVectorIndex(table: string): void { const prefix = vectorIndexKey(table, ''); From 1ff58575674eb31c246ca3f6a40858c596158ceb Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:32:22 +0000 Subject: [PATCH 04/19] feat(spec): source.retrieval.mode, AdapterCapabilities.retrieval and AdapterSearchOptions.retrieval (wip) --- .../src/__tests__/index-fingerprint.test.ts | 14 +++ .../services/service-knowledge/src/testing.ts | 91 +++++++++++++++++++ packages/spec/liveness/knowledge_source.json | 12 +++ .../src/ai/knowledge-source.metadata-form.ts | 20 ++++ packages/spec/src/ai/knowledge-source.test.ts | 43 +++++++++ packages/spec/src/ai/knowledge-source.zod.ts | 68 ++++++++++++++ .../spec/src/contracts/knowledge-adapter.ts | 49 +++++++++- 7 files changed, 294 insertions(+), 3 deletions(-) diff --git a/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts b/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts index 9061a06536f..2168abc0b70 100644 --- a/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts +++ b/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts @@ -170,3 +170,17 @@ describe('recipe hash (ADR-0161 K7)', () => { expect(computeRecipeHash({ source: source({ content: ['body'] }), schema })).toBe(computeRecipeHash({ source: source(), schema })); }); }); + +// `source.retrieval` is read on every search and by no build (ADR-0161, the +// dated note on retrieval modes): neither hash moves with it, so changing a +// source's retrieval mode rebuilds nothing. +describe('retrieval mode (ADR-0161, the dated note on retrieval modes)', () => { + it('changes neither the index fingerprint nor the recipe hash', () => { + const fingerprint = computeIndexFingerprint({ source: source(), embedding, split }); + const recipe = computeRecipeHash({ source: source() }); + for (const retrieval of [{}, { mode: 'vector' }, { mode: 'keyword' }, { mode: 'hybrid' }]) { + expect(computeIndexFingerprint({ source: source({ retrieval }), embedding, split })).toBe(fingerprint); + expect(computeRecipeHash({ source: source({ retrieval }) })).toBe(recipe); + } + }); +}); diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 036bf9be61c..ba240142225 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -74,6 +74,11 @@ * whose figure and exception words one passage holds, among passages that * hold the question's characters one by one and none of its words: the * passage is ranked. + * + * An adapter that declares `retrieval` reports its modes and default + * (`capabilities.retrieval`), and the same fixture is searched under each + * mode it lists: `vector` leaves that passage out, `keyword` answers it + * alone, and the default handed explicitly answers what no mode answers. */ import { describe, expect, it, vi } from 'vitest'; @@ -86,6 +91,7 @@ import type { AdapterSearchOptions, } from '@objectstack/spec/contracts'; import type { KnowledgeDocument, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import { KNOWLEDGE_RETRIEVAL_MODES } from '@objectstack/spec/ai'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import type { TenancyPosture } from '@objectstack/spec/security'; import { KnowledgeService, type KnowledgeLogger } from './knowledge-service.js'; @@ -148,6 +154,17 @@ export interface KnowledgeAdapterContractOptions { * behaviour. Absent: `false`. */ keywordLeg?: boolean; + /** + * `capabilities.retrieval` (ADR-0161, the dated note on retrieval modes): + * the adapter reports the modes it runs and its default, and its search + * honours `AdapterSearchOptions.retrieval`. The report is checked against + * the three modes, and each listed mode is asserted by behaviour: `vector` + * leaves out the passage only the keyword leg ranks, `keyword` ranks by + * the query's words alone, `hybrid` answers what the default answers when + * it is the default. A `vector` or `keyword` case needs `keywordLeg`. + * Absent: `false`. + */ + retrieval?: boolean; }; } @@ -510,6 +527,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption expect(typeof adapter.beginBuild === 'function').toBe(opts.implements.builds); expect(typeof adapter.completeBuild === 'function').toBe(opts.implements.builds); expect(typeof adapter.dropSource === 'function').toBe(opts.implements.dropSource); + expect(adapter.capabilities?.retrieval !== undefined).toBe(opts.implements.retrieval === true); if (opts.implements.generations) { expect(opts.implements.builds && opts.implements.refusesOtherFingerprint).toBe(true); } @@ -568,6 +586,79 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption }); } + if (opts.implements.retrieval === true) { + describe('retrieval modes (ADR-0161, the dated note on retrieval modes)', () => { + it('reports the modes it runs, each once and each one of the three, and a default it lists', async () => { + const adapter: IKnowledgeAdapter = await make(); + const report = adapter.capabilities?.retrieval; + expect(report).toBeDefined(); + if (report === undefined) return; + expect(report.modes.length).toBeGreaterThan(0); + expect(new Set(report.modes).size).toBe(report.modes.length); + for (const mode of report.modes) expect(KNOWLEDGE_RETRIEVAL_MODES).toContain(mode); + expect(report.modes).toContain(report.default); + }); + + /** + * The keyword-leg fixture: five passages hold the question's + * characters one by one (a bag-of-words embedder ranks them first by + * vector) and none of its words; one passage holds its figure and + * words, which the vector leg alone ranks below `topK`. + */ + const QUESTION = '出差住宿费超标的话2000元以下除外的情况还要部门经理审批吗'; + async function seeded(): Promise<{ adapter: IKnowledgeAdapter; a: KnowledgeSource; listed: readonly string[]; byDefault: string }> { + const adapter: IKnowledgeAdapter = await make(); + const a = objectSource('retrieval_modes'); + const spread = ['a', 'b', 'c', 'd', 'e'].map((n) => + doc(a, `spread_${n}`, `出 差 住 宿 费 超 标 部 门 经 理 审 批 情 况 ${n}`), + ); + await adapter.upsert([...spread, doc(a, 'clause', '采购单笔金额2000元以下除外,其余一律公开招标')], ctxOf(a)); + const report = adapter.capabilities?.retrieval; + return { adapter, a, listed: report?.modes ?? [], byDefault: report?.default ?? '' }; + } + const nonIncreasing = (hits: Array<{ score: number }>) => { + for (let i = 1; i < hits.length; i++) expect(hits[i - 1].score).toBeGreaterThanOrEqual(hits[i].score); + }; + + it('`vector` runs the vector leg alone: the passage only the keyword leg ranks is not answered', async () => { + const { adapter, a, listed } = await seeded(); + if (!listed.includes('vector')) return; + expect(opts.implements.keywordLeg, 'the vector case reads the keyword-leg fixture').toBe(true); + const hits = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: { mode: 'vector' } }); + expect(hits.length).toBeGreaterThan(0); + expect(hits.map((h) => h.documentId)).not.toContain(`${a.name}:clause`); + nonIncreasing(hits); + }); + + it('`keyword` runs the keyword leg alone: only the passage holding the question\'s words is answered', async () => { + const { adapter, a, listed } = await seeded(); + if (!listed.includes('keyword')) return; + expect(opts.implements.keywordLeg, 'the keyword case reads the keyword-leg fixture').toBe(true); + const hits = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: { mode: 'keyword' } }); + expect(hits.map((h) => h.documentId)).toEqual([`${a.name}:clause`]); + // A query with no word any passage holds answers nothing under keyword alone. + expect(await adapter.search('zzqx', { source: a, topK: 3, retrieval: { mode: 'keyword' } })).toEqual([]); + }); + + it('`hybrid` ranks both legs; as the default it answers exactly what a search without the member answers', async () => { + const { adapter, a, listed, byDefault } = await seeded(); + if (!listed.includes('hybrid')) return; + const hybrid = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: { mode: 'hybrid' } }); + nonIncreasing(hybrid); + if (opts.implements.keywordLeg) expect(hybrid.map((h) => h.documentId)).toContain(`${a.name}:clause`); + if (byDefault === 'hybrid') { + expect(hybrid).toEqual(await adapter.search(QUESTION, { source: a, topK: 3 })); + } + }); + + it('the default mode, handed explicitly, answers exactly what a search without the member answers', async () => { + const { adapter, a, byDefault } = await seeded(); + const explicit = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: { mode: byDefault as 'vector' } }); + expect(explicit).toEqual(await adapter.search(QUESTION, { source: a, topK: 3 })); + }); + }); + } + if (opts.implements.organizationIds) { describe('organizationIds (ADR-0161 K8, item 9)', () => { /** B's document outranks A's; a third document carries no organization. */ diff --git a/packages/spec/liveness/knowledge_source.json b/packages/spec/liveness/knowledge_source.json index e44ed13b954..56fbab6004f 100644 --- a/packages/spec/liveness/knowledge_source.json +++ b/packages/spec/liveness/knowledge_source.json @@ -121,6 +121,18 @@ } } }, + "retrieval": { + "status": "planned", + "verifiedAt": "2026-11-30", + "note": "PLANNED RECORD (ruling 7270218011 on #38692, phase 1a; ADR-0161, the dated note on retrieval modes): `retrieval: { mode }`, how a source is searched. CARRIED today: it parses at every door (strict, `retrieval: {}` allowed) and is kept by the parse. ACTED ON by nothing yet: the knowledge service resolves the effective mode (the source's declaration, else the adapter's `capabilities.retrieval.default`), refuses a mode the adapter does not list at the four points the ruling names, and hands it to the adapter as `AdapterSearchOptions.retrieval`; knowledge-turso and knowledge-pgvector run one leg or both. Those are the phase-1a PRs that follow this one. Flip to `live` on the commit that lands the service's reader, citing it. Enters neither the index fingerprint nor the recipe hash.", + "children": { + "mode": { + "status": "planned", + "verifiedAt": "2026-11-30", + "note": "Planned with its container `retrieval` (see that row): `vector`, `keyword` or `hybrid`; omitted means the adapter's default." + } + } + }, "where": { "status": "live", "verifiedAt": "2026-11-26", diff --git a/packages/spec/src/ai/knowledge-source.metadata-form.ts b/packages/spec/src/ai/knowledge-source.metadata-form.ts index d84610e3be3..1215e5f31b2 100644 --- a/packages/spec/src/ai/knowledge-source.metadata-form.ts +++ b/packages/spec/src/ai/knowledge-source.metadata-form.ts @@ -25,6 +25,8 @@ import { defineMetadataForm } from '../ui/view.zod'; * - `source.affinity` is the JSON editor too: a list of `{ field, caller, * mode, places? }` entries whose cross-key rules (a `field` listed in * `metadataFields`, `places` on a `boost` alone) no list widget states. + * - `source.retrieval.mode` is a select of the three modes, blank for the + * store's default; which modes the store runs is judged at save. * * ADR-0161 K5 and K10 rule 5: embedding is egress, so `content` offers named * fields only, and its help says beside it what a build sends and to whom. @@ -77,6 +79,24 @@ export const knowledgeSourceForm = defineMetadataForm({ { field: 'metadataFields', label: 'Filter fields', widget: 'field-multi', dependsOn: 'object', helpText: 'Fields kept beside each passage, so a search can filter on them (for example a status or an owner). Each one must be a field you may query.' }, { field: 'documentBy', label: 'Document unit', widget: 'field-ref', dependsOn: 'object', helpText: 'Optional. The field that links each record to the parent record it is a part of (a clause to its policy): a lookup or master-detail field, single-valued, also listed in Filter fields. A record-level search then answers one hit per parent instead of one per record; a record with no parent is its own hit. Setting it rebuilds nothing; adding the field to Filter fields does.' }, { field: 'affinity', label: 'Order for the asker', widget: 'json', helpText: 'Optional. Lists entries that move hits related to the person asking up the answer, for example [{"field": "business_unit", "caller": "business_unit", "mode": "nearest"}] puts their own unit first, then its parent units, then the rest, and [{"field": "owner", "caller": "user", "mode": "boost", "places": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing.' }, + { + field: 'retrieval', + label: 'Search', + type: 'composite', + helpText: 'How a search of this source finds passages. Leave it blank for the store\'s default. Changing it rebuilds nothing.', + fields: [ + { + field: 'mode', + label: 'Retrieval mode', + options: [ + { label: 'Vector only (by meaning)', value: 'vector' }, + { label: 'Keyword only (by words)', value: 'keyword' }, + { label: 'Hybrid (both)', value: 'hybrid' }, + ], + helpText: 'Blank: the store\'s default (hybrid on turso and pgvector). Vector ranks passages by meaning; keyword by the words they hold, with no call to the embedding provider, which suits document or clause numbers; hybrid merges both. A mode the store does not run is refused at save.', + }, + ], + }, { field: 'where', label: 'Records to index', widget: 'json', helpText: 'An ObjectQL filter on the object, for example {"status": {"$ne": "done"}}. Only the records it matches are indexed. Blank: every record.' }, { field: 'split', diff --git a/packages/spec/src/ai/knowledge-source.test.ts b/packages/spec/src/ai/knowledge-source.test.ts index cf5c5b01ae0..663ecd5d07f 100644 --- a/packages/spec/src/ai/knowledge-source.test.ts +++ b/packages/spec/src/ai/knowledge-source.test.ts @@ -28,6 +28,7 @@ import { getMetadataTypeSchema } from '../kernel/metadata-type-schemas'; import { ObjectStackDefinitionSchema } from '../stack.zod'; import { KNOWLEDGE_AFFINITY_MAX_PLACES, + KNOWLEDGE_RETRIEVAL_MODES, KnowledgeSourceSchema, type KnowledgeSource, type KnowledgeSourceParsed, @@ -415,3 +416,45 @@ describe('KnowledgeSourceSchema — `source.affinity`, the order for the caller expect(issues.map(([code, path]) => [code, path])).toEqual([['unrecognized_keys', 'source.affinity.0']]); }); }); + +describe('KnowledgeSourceSchema — `source.retrieval`, how a source is searched (ADR-0161, the dated note on retrieval modes)', () => { + const withRetrieval = (retrieval: unknown): unknown => ({ ...SOURCE, source: { ...SOURCE.source, retrieval } }); + + it('positive control: each of the three modes parses and is kept as written; absent stays absent', () => { + expect(KNOWLEDGE_RETRIEVAL_MODES).toEqual(['vector', 'keyword', 'hybrid']); + for (const mode of KNOWLEDGE_RETRIEVAL_MODES) { + const r = KnowledgeSourceSchema.safeParse(withRetrieval({ mode })); + expect(r.success, mode).toBe(true); + if (r.success) expect(r.data.source.retrieval).toEqual({ mode }); + } + expect('retrieval' in KnowledgeSourceSchema.parse(SOURCE).source).toBe(false); + }); + + it('accepts `retrieval: {}`, which declares nothing and adds no default', () => { + const r = KnowledgeSourceSchema.safeParse(withRetrieval({})); + expect(r.success).toBe(true); + if (r.success) expect(r.data.source.retrieval).toEqual({}); + }); + + it('refuses a mode outside the three, naming the three', () => { + const issues = issuesOf(withRetrieval({ mode: 'semantic' })); + expect(issues.map(([code, path]) => [code, path])).toEqual([['invalid_value', 'source.retrieval.mode']]); + expect(issues[0]![2]).toMatch(/^`knowledge_source.source.retrieval.mode` is 'vector', 'keyword' or 'hybrid', got 'semantic'/); + }); + + it('refuses an unknown key under `retrieval` — `vectorWeight` included, which this version does not carry — never drops it', () => { + for (const key of ['vectorWeight', 'keywordWeight', 'fusion']) { + const issues = issuesOf(withRetrieval({ mode: 'hybrid', [key]: 0.5 })); + expect(issues.map(([code, path]) => [code, path]), key).toEqual([['unrecognized_keys', 'source.retrieval']]); + } + }); + + it('is published by the type\'s JSON Schema, so a document validated against it is not refused a release later', () => { + const json = z.toJSONSchema(KnowledgeSourceSchema, { io: 'input', unrepresentable: 'any' }) as { + properties: { source: { properties: Record; additionalProperties?: unknown }> } }; + }; + const retrieval = json.properties.source.properties.retrieval; + expect(retrieval?.properties?.mode?.enum).toEqual(['vector', 'keyword', 'hybrid']); + expect(retrieval?.additionalProperties).toBe(false); + }); +}); diff --git a/packages/spec/src/ai/knowledge-source.zod.ts b/packages/spec/src/ai/knowledge-source.zod.ts index 50af210a137..64e6ef189c6 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -128,6 +128,60 @@ export const KnowledgeSplitSchema = lazySchema(() => strictObject( }, )); +/** + * The retrieval modes a knowledge source may declare (ADR-0161, the dated note + * on retrieval modes; ruling 7270218011 on #38692): + * + * - `vector`: only the vector leg runs, ranking passages by meaning. + * - `keyword`: only the keyword leg runs, ranking passages by the words they + * hold. The embedder is not called and no query vector is made; passages of + * equal keyword score are ranked by passage id, so the answer is + * deterministic, and a question with no words to match answers nothing. It + * suits exact lookups: a document number, a clause number, a name. + * - `hybrid`: both legs run, merged by the store's fusion. + * + * Which modes a store runs is the store's report (`AdapterCapabilities.retrieval`), + * never configuration; a source that declares a mode its store does not run is + * refused, never silently searched another way. + */ +export const KNOWLEDGE_RETRIEVAL_MODES = ['vector', 'keyword', 'hybrid'] as const; + +/** One of {@link KNOWLEDGE_RETRIEVAL_MODES}. */ +export const KnowledgeRetrievalModeSchema = lazySchema(() => z.enum(KNOWLEDGE_RETRIEVAL_MODES, { + error: (issue) => (typeof issue.input === 'string' + ? `\`knowledge_source.source.retrieval.mode\` is 'vector', 'keyword' or 'hybrid', got '${issue.input}'. ` + + 'Write `mode: \'vector\'` to rank by meaning alone, `mode: \'keyword\'` to rank by the words a passage holds ' + + '(no embedding call), or `mode: \'hybrid\'` for both; leave `mode` out for the store\'s default.' + : undefined), +})); + +/** + * How a source is searched (ADR-0161, the dated note on retrieval modes): + * which legs the store runs. A declaration of the source, read on every search + * and never by a build, so it enters neither the index fingerprint nor the + * recipe hash: changing it rebuilds nothing. `retrieval: {}` declares nothing + * and reads as the key left out. + */ +export const KnowledgeRetrievalSchema = lazySchema(() => strictObject( + { + surface: 'this source\'s `retrieval`', + history: 'This shape is strict from birth — `retrieval` had no earlier spelling, so an unknown key here was never accepted.', + }, + { + /** + * Which legs run: `vector`, `keyword` or `hybrid` + * ({@link KNOWLEDGE_RETRIEVAL_MODES}). Omitted: the store's default + * (`AdapterCapabilities.retrieval.default`; `hybrid` on turso and + * pgvector), today's behaviour. A store that does not list the mode + * refuses the source at save, at registration when its store already + * resolves, once after boot, and on every search (the source is listed as + * refused); a store that reports no modes accepts only the key left out. + */ + mode: KnowledgeRetrievalModeSchema.optional() + .describe('Which legs a search runs: vector, keyword or hybrid; omitted means the store\'s default'), + }, +)); + /** * `source.documentBy` must be one of `source.metadataFields`: a record-level * search groups each hit by the value the index stores beside its passage, @@ -449,6 +503,17 @@ export const ObjectKnowledgeSourceSchema = lazySchema(() => strictObject( */ affinity: z.array(KnowledgeAffinityEntrySchema).optional() .describe('How this source\'s hits are ordered for the caller: boost (by places) or nearest (own business unit first), by position, never by score'), + /** + * [ADR-0161, the dated note on retrieval modes] How this source is + * searched: `retrieval.mode` names the legs the store runs + * ({@link KnowledgeRetrievalSchema}). Beside {@link affinity} and before + * it: the mode decides which passages the store ranks and their scores, + * then affinity re-orders them for the caller. Omitted: the store's + * default, as before this key. It enters neither the index fingerprint + * nor the recipe hash, so changing it rebuilds nothing. + */ + retrieval: KnowledgeRetrievalSchema.optional() + .describe('How this source is searched: mode vector, keyword or hybrid; omitted means the store\'s default, and changing it rebuilds nothing'), }, ).superRefine(refineObjectSource)); @@ -583,3 +648,6 @@ export type KnowledgeAffinityMode = z.input; export type KnowledgeAffinityModeParsed = z.infer; export type KnowledgeAffinityEntry = z.input; export type KnowledgeAffinityEntryParsed = z.infer; +export type KnowledgeRetrievalMode = z.input; +export type KnowledgeRetrieval = z.input; +export type KnowledgeRetrievalParsed = z.infer; diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index 4728cd8b136..4d729a55900 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -4,7 +4,7 @@ import type { KnowledgeDocument, KnowledgeHit, } from '../ai/knowledge-document.zod'; -import type { KnowledgeSource } from '../ai/knowledge-source.zod'; +import type { KnowledgeRetrievalMode, KnowledgeSource } from '../ai/knowledge-source.zod'; /** * `IKnowledgeAdapter` — plugin-side contract. @@ -176,6 +176,26 @@ export interface AdapterSearchOptions { * answers it from that generation. Absent: no check. */ index?: { fingerprint: string }; + /** + * The retrieval mode this search runs (ADR-0161, the dated note on + * retrieval modes): the EFFECTIVE mode, which the knowledge service resolves + * from the source's `source.retrieval.mode`, else the adapter's + * {@link AdapterCapabilities.retrieval} `default`. A per-request parameter, + * as `topK` and `scope` are — not configuration (ADR-0161 K8, rule 4). + * + * - `vector`: run only the vector leg. + * - `keyword`: run only the keyword leg. Do not call the embedder and make + * no query vector; rank passages of equal keyword score by passage id. + * A query with no terms to match answers no hits. + * - `hybrid`: run both legs and fuse them, as the adapter's default does. + * + * The service hands only a mode the adapter lists in + * `capabilities.retrieval.modes`, and never hands this member to an adapter + * that reports no `capabilities.retrieval`. Absent: the adapter's default. + * Scores need only not increase with rank within one source's answer; under + * a one-leg mode they reflect rank alone. + */ + retrieval?: { mode: KnowledgeRetrievalMode }; /** Trace id for correlation. */ traceId?: string; } @@ -244,6 +264,28 @@ export interface AdapterCapabilities { * `chunks`, and splits them itself. */ chunks?: boolean; + /** + * The retrieval modes the adapter runs, and which one it runs when a + * source declares none (ADR-0161, the dated note on retrieval modes). A + * report, not configuration: `default` is one of `modes`, and an adapter + * that lists `hybrid` honours the source's vector share when that arrives. + * + * The knowledge service refuses a source that declares a mode outside + * `modes` — at save, at registration when the adapter already resolves, + * once after boot, and on every search, where the source is listed as + * refused — and never searches it another way. Absent: the adapter reports + * no modes, and only a source that declares none is searched by it; the + * service is never told which legs it runs. + */ + retrieval?: AdapterRetrievalCapability; +} + +/** {@link AdapterCapabilities.retrieval}: the modes an adapter runs, and its default. */ +export interface AdapterRetrievalCapability { + /** The modes the adapter runs; not empty, no mode twice. */ + readonly modes: readonly KnowledgeRetrievalMode[]; + /** The mode it runs for a source that declares none; one of {@link modes}. */ + readonly default: KnowledgeRetrievalMode; } /** @@ -308,8 +350,9 @@ export interface IKnowledgeAdapter { readonly id: string; /** - * What the adapter accepts beyond whole documents (ADR-0161 K8, item 5). - * Absent: whole documents only. + * What the adapter accepts beyond whole documents (ADR-0161 K8, item 5), + * and the retrieval modes it runs. Absent: whole documents only, and no + * modes reported. */ readonly capabilities?: AdapterCapabilities; From 8dc9af75d4ff3f1c849ddefcd6e58ce8fae6da00 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:39:49 +0000 Subject: [PATCH 05/19] chore(spec): regenerate the generated artifacts for source.retrieval --- content/docs/protocol/knowledge.mdx | 10 +++++- .../docs/references/ai/knowledge-source.mdx | 34 +++++++++++++++++-- content/docs/references/index.mdx | 10 +++--- .../ai.md | 2 +- packages/spec/api-surface/ai.json | 6 ++++ packages/spec/api-surface/contracts.json | 1 + packages/spec/authorable-surface/ai.json | 2 ++ packages/spec/declaration-map/ai.json | 4 +++ packages/spec/export-origins/ai.json | 6 ++++ packages/spec/export-origins/contracts.json | 1 + packages/spec/json-schema.manifest/ai.json | 2 ++ .../liveness/state-counts/knowledge_source.md | 2 +- packages/spec/src/ai/knowledge-source.test.ts | 2 +- 13 files changed, 71 insertions(+), 11 deletions(-) diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 105eb543109..9b4c0e338d0 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -483,7 +483,10 @@ and [3.5 The split](#35-the-split). ```ts interface IKnowledgeAdapter { readonly id: string; - readonly capabilities?: { chunks?: boolean }; // takes the service's passages + readonly capabilities?: { + chunks?: boolean; // takes the service's passages + retrieval?: { modes: readonly ('vector' | 'keyword' | 'hybrid')[]; default: 'vector' | 'keyword' | 'hybrid' }; + }; // the retrieval modes it runs, and its default readonly embedding?: { // what its embedder is maxInputTokens?: number; // longest input it accepts model?: string; dimensions?: number; variant?: string; // what its vectors are @@ -523,6 +526,11 @@ caller's organizations; an adapter that reads it ranks only those organizations' documents, filtering before it ranks — see [Organization scope](#organization-scope). `AdapterSearchOptions.scope` holds a search to chosen records the same way — see [Record scope](#record-scope). +`capabilities.retrieval` reports the retrieval modes an adapter runs +(`vector`, `keyword`, `hybrid`) and the one it runs by default; it is a +report, not configuration. `AdapterSearchOptions.retrieval` carries the mode +a search runs, a per-request parameter like `topK`, and only ever a mode the +adapter lists. `listDocuments` lists the documents the adapter holds for a source, a page of at most `limit` entries at a time, each with the `docHash` it was stored with; `nextCursor` is absent once the diff --git a/content/docs/references/ai/knowledge-source.mdx b/content/docs/references/ai/knowledge-source.mdx index 423e186a7ad..2e11a10f60a 100644 --- a/content/docs/references/ai/knowledge-source.mdx +++ b/content/docs/references/ai/knowledge-source.mdx @@ -23,8 +23,8 @@ See `content/docs/protocol/knowledge.mdx` for the design. ## TypeScript Usage ```typescript -import { KnowledgeAffinityCallerSchema, KnowledgeAffinityEntrySchema, KnowledgeAffinityModeSchema, KnowledgeRefreshPolicySchema, KnowledgeSourceSchema, KnowledgeSplitSchema, KnowledgeSplitStrategySchema, ObjectKnowledgeSourceSchema } from '@objectstack/spec/ai'; -import type { KnowledgeAffinityCaller, KnowledgeAffinityEntry, KnowledgeAffinityMode, KnowledgeRefreshPolicy, KnowledgeSource, KnowledgeSplit, KnowledgeSplitStrategy, ObjectKnowledgeSource } from '@objectstack/spec/ai'; +import { KnowledgeAffinityCallerSchema, KnowledgeAffinityEntrySchema, KnowledgeAffinityModeSchema, KnowledgeRefreshPolicySchema, KnowledgeRetrievalSchema, KnowledgeRetrievalModeSchema, KnowledgeSourceSchema, KnowledgeSplitSchema, KnowledgeSplitStrategySchema, ObjectKnowledgeSourceSchema } from '@objectstack/spec/ai'; +import type { KnowledgeAffinityCaller, KnowledgeAffinityEntry, KnowledgeAffinityMode, KnowledgeRefreshPolicy, KnowledgeRetrieval, KnowledgeRetrievalMode, KnowledgeSource, KnowledgeSplit, KnowledgeSplitStrategy, ObjectKnowledgeSource } from '@objectstack/spec/ai'; // Validate data const result = KnowledgeAffinityCallerSchema.parse(data); @@ -76,6 +76,28 @@ const result = KnowledgeAffinityCallerSchema.parse(data); | **cron** | `never` | optional | [REMOVED] `knowledge_source.refresh.cron` was removed in @objectstack/spec 19.0.0 (ADR-0161 K6) — it was parsed and reached no engine: nothing ever scheduled a reindex from it. Delete the key. To rebuild on a schedule, call `reindexSource` from a flow or a job; keeping the index correct between events is the service's reconcile pass. A source registered in code (`KnowledgeServicePlugin({ sources })`, `registerSource`) is in no stack collection, so `os migrate meta` lists no edit for it: make this edit in the registration itself. Run `os migrate meta --from 18` to list the mechanical edits for existing sources; `--write` applies the ones it can prove, and you apply the rest by hand. | +--- + +## KnowledgeRetrieval + +### Properties + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **mode** | `Enum<'vector' \| 'keyword' \| 'hybrid'>` | optional | Which legs a search runs: vector, keyword or hybrid; omitted means the store's default | + + +--- + +## KnowledgeRetrievalMode + +### Allowed Values + +* `vector` +* `keyword` +* `hybrid` + + --- ## KnowledgeSource @@ -116,6 +138,7 @@ const result = KnowledgeAffinityCallerSchema.parse(data); | **where** | `Record` | optional | | | **split** | `{ strategy: Enum<'whole' \| 'recursive' \| 'markdown'>; maxChars?: integer; minChars?: integer }` | optional | How the service cuts this object's documents into passages; omitted means recursive | | **affinity** | `{ field: string; caller: Enum<'user' \| 'business_unit'>; mode: Enum<'boost' \| 'nearest'>; places?: integer }[]` | optional | How this source's hits are ordered for the caller: boost (by places) or nearest (own business unit first), by position, never by score | +| **retrieval** | `{ mode?: Enum<'vector' \| 'keyword' \| 'hybrid'> }` | optional | How this source is searched: mode vector, keyword or hybrid; omitted means the store's default, and changing it rebuilds nothing | ### Nested Shape: `KnowledgeSource.refresh` @@ -166,6 +189,7 @@ const result = KnowledgeAffinityCallerSchema.parse(data); | **where** | `Record` | optional | | | **split** | `{ strategy: Enum<'whole' \| 'recursive' \| 'markdown'>; maxChars?: integer; minChars?: integer }` | optional | How the service cuts this object's documents into passages; omitted means recursive | | **affinity** | `{ field: string; caller: Enum<'user' \| 'business_unit'>; mode: Enum<'boost' \| 'nearest'>; places?: integer }[]` | optional | How this source's hits are ordered for the caller: boost (by places) or nearest (own business unit first), by position, never by score | +| **retrieval** | `{ mode?: Enum<'vector' \| 'keyword' \| 'hybrid'> }` | optional | How this source is searched: mode vector, keyword or hybrid; omitted means the store's default, and changing it rebuilds nothing | ### Nested Shape: `ObjectKnowledgeSource.split` @@ -184,6 +208,12 @@ const result = KnowledgeAffinityCallerSchema.parse(data); | **mode** | `Enum<'boost' \| 'nearest'>` | ✅ | boost lifts a match by places; nearest puts the caller's own unit first, then its parents | | **places** | `integer` | optional | boost only: how many non-matching hits a match may pass, 1 to 20 | +### Nested Shape: `ObjectKnowledgeSource.retrieval` + +| Property | Type | Required | Description | +| :--- | :--- | :--- | :--- | +| **mode** | `Enum<'vector' \| 'keyword' \| 'hybrid'>` | optional | Which legs a search runs: vector, keyword or hybrid; omitted means the store's default | + --- diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 920f1a62496..03b540df209 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1745 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1747 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -22,7 +22,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | -| [AI Protocol](/docs/references/ai) | 17 | 105 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | +| [AI Protocol](/docs/references/ai) | 17 | 107 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 37 | 528 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 197 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | @@ -36,13 +36,13 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 17 | 187 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **223** | **1745** | 14 protocol modules | +| **Total** | **223** | **1747** | 14 protocol modules | --- ## AI Protocol -**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **17 pages, 105 schemas** +**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **17 pages, 107 schemas** Agents, tools, skills, RAG and knowledge sources, model registry, conversations. @@ -55,7 +55,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | [`dataset-tools.zod.ts`](/docs/references/ai/dataset-tools) | `DatasetNextStep`, `DatasetNextStepDecision`, `DatasetProvenance`, `DatasetTermCandidate`, `DatasetTermMatch`, `DatasetTermMatchedOn`, `DatasetToolCatalogDimension`, `DatasetToolCatalogEntry`, `DatasetToolCatalogMeasure`, `ListDatasetsInput`, `ListDatasetsOutput`, `QueryDatasetInput`, `QueryDatasetOutput` | | [`draft-review.zod.ts`](/docs/references/ai/draft-review) | `DraftReviewItem`, `DraftReviewLinks`, `DraftReviewList`, `DraftReviewVerdict`, `DraftReviewVerdictRefusal` | | [`knowledge-document.zod.ts`](/docs/references/ai/knowledge-document) | `KnowledgeChunk`, `KnowledgeDocument`, `KnowledgeHit` | -| [`knowledge-source.zod.ts`](/docs/references/ai/knowledge-source) | `KnowledgeAffinityCaller`, `KnowledgeAffinityEntry`, `KnowledgeAffinityMode`, `KnowledgeRefreshPolicy`, `KnowledgeSource`, `KnowledgeSplit`, `KnowledgeSplitStrategy`, `ObjectKnowledgeSource` | +| [`knowledge-source.zod.ts`](/docs/references/ai/knowledge-source) | `KnowledgeAffinityCaller`, `KnowledgeAffinityEntry`, `KnowledgeAffinityMode`, `KnowledgeRefreshPolicy`, `KnowledgeRetrieval`, `KnowledgeRetrievalMode`, `KnowledgeSource`, `KnowledgeSplit`, `KnowledgeSplitStrategy`, `ObjectKnowledgeSource` | | [`mcp.zod.ts`](/docs/references/ai/mcp) | `MCPApprovalPolicy`, `MCPServerRef`, `MCPToolBinding`, `MCPTransport`, `McpActionNamespace`, `McpListedActionAddress` | | [`model-registry.zod.ts`](/docs/references/ai/model-registry) | `ModelCapability`, `ModelConfig`, `ModelLimits`, `ModelPricing`, `ModelProvider`, `ModelRegistry`, `ModelRegistryEntry`, `ModelSelectionCriteria`, `PromptTemplate`, `PromptVariable` | | [`object-query-source.zod.ts`](/docs/references/ai/object-query-source) | `ObjectQuerySource` | diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md index 5f25e0c458c..050f8f7f1d7 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `ai/` | 121 | +| `ai/` | 122 | diff --git a/packages/spec/api-surface/ai.json b/packages/spec/api-surface/ai.json index b5f1388e297..0bfeb1ab566 100644 --- a/packages/spec/api-surface/ai.json +++ b/packages/spec/api-surface/ai.json @@ -132,6 +132,7 @@ "GetRecordContextOutputSchema (const)", "ImageContentSchema (const)", "KNOWLEDGE_AFFINITY_MAX_PLACES (const)", + "KNOWLEDGE_RETRIEVAL_MODES (const)", "KnowledgeAffinityCaller (type)", "KnowledgeAffinityCallerParsed (type)", "KnowledgeAffinityCallerSchema (const)", @@ -150,6 +151,11 @@ "KnowledgeRefreshPolicy (type)", "KnowledgeRefreshPolicyParsed (type)", "KnowledgeRefreshPolicySchema (const)", + "KnowledgeRetrieval (type)", + "KnowledgeRetrievalMode (type)", + "KnowledgeRetrievalModeSchema (const)", + "KnowledgeRetrievalParsed (type)", + "KnowledgeRetrievalSchema (const)", "KnowledgeSource (type)", "KnowledgeSourceParsed (type)", "KnowledgeSourceSchema (const)", diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index f012c7992d5..dd0891c1994 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -44,6 +44,7 @@ "AdapterListDocumentsOptions (interface)", "AdapterListDocumentsPage (interface)", "AdapterListedDocument (interface)", + "AdapterRetrievalCapability (interface)", "AdapterScopeTerm (type)", "AdapterSearchOptions (interface)", "AnalyticsDriverCapabilities (interface)", diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index 0ee44069dda..529db46b843 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -292,6 +292,7 @@ "ai/KnowledgeHit:title", "ai/KnowledgeRefreshPolicy:cron [RETIRED]", "ai/KnowledgeRefreshPolicy:onRecordChange", + "ai/KnowledgeRetrieval:mode", "ai/KnowledgeSource:_lock", "ai/KnowledgeSource:_lockDocsUrl", "ai/KnowledgeSource:_lockReason", @@ -391,6 +392,7 @@ "ai/ObjectKnowledgeSource:kind", "ai/ObjectKnowledgeSource:metadataFields", "ai/ObjectKnowledgeSource:object", + "ai/ObjectKnowledgeSource:retrieval", "ai/ObjectKnowledgeSource:split", "ai/ObjectKnowledgeSource:where", "ai/ObjectQuerySource:aggregations", diff --git a/packages/spec/declaration-map/ai.json b/packages/spec/declaration-map/ai.json index 8a975cdd035..70474f71dfe 100644 --- a/packages/spec/declaration-map/ai.json +++ b/packages/spec/declaration-map/ai.json @@ -101,6 +101,10 @@ "KnowledgeHitSchema": "ai/KnowledgeHit", "KnowledgeRefreshPolicy": "ai/KnowledgeRefreshPolicy", "KnowledgeRefreshPolicySchema": "ai/KnowledgeRefreshPolicy", + "KnowledgeRetrieval": "ai/KnowledgeRetrieval", + "KnowledgeRetrievalMode": "ai/KnowledgeRetrievalMode", + "KnowledgeRetrievalModeSchema": "ai/KnowledgeRetrievalMode", + "KnowledgeRetrievalSchema": "ai/KnowledgeRetrieval", "KnowledgeSource": "ai/KnowledgeSource", "KnowledgeSourceSchema": "ai/KnowledgeSource", "KnowledgeSplit": "ai/KnowledgeSplit", diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index e7d955f2f85..2114847e360 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -130,6 +130,7 @@ "GetRecordContextOutputSchema": "src/ai/record-context-tools.zod.ts#GetRecordContextOutputSchema (const)", "ImageContentSchema": "src/ai/conversation.zod.ts#ImageContentSchema (const)", "KNOWLEDGE_AFFINITY_MAX_PLACES": "src/ai/knowledge-source.zod.ts#KNOWLEDGE_AFFINITY_MAX_PLACES (const)", + "KNOWLEDGE_RETRIEVAL_MODES": "src/ai/knowledge-source.zod.ts#KNOWLEDGE_RETRIEVAL_MODES (const)", "KnowledgeAffinityCaller": "src/ai/knowledge-source.zod.ts#KnowledgeAffinityCaller (type)", "KnowledgeAffinityCallerParsed": "src/ai/knowledge-source.zod.ts#KnowledgeAffinityCallerParsed (type)", "KnowledgeAffinityCallerSchema": "src/ai/knowledge-source.zod.ts#KnowledgeAffinityCallerSchema (const)", @@ -148,6 +149,11 @@ "KnowledgeRefreshPolicy": "src/ai/knowledge-source.zod.ts#KnowledgeRefreshPolicy (type)", "KnowledgeRefreshPolicyParsed": "src/ai/knowledge-source.zod.ts#KnowledgeRefreshPolicyParsed (type)", "KnowledgeRefreshPolicySchema": "src/ai/knowledge-source.zod.ts#KnowledgeRefreshPolicySchema (const)", + "KnowledgeRetrieval": "src/ai/knowledge-source.zod.ts#KnowledgeRetrieval (type)", + "KnowledgeRetrievalMode": "src/ai/knowledge-source.zod.ts#KnowledgeRetrievalMode (type)", + "KnowledgeRetrievalModeSchema": "src/ai/knowledge-source.zod.ts#KnowledgeRetrievalModeSchema (const)", + "KnowledgeRetrievalParsed": "src/ai/knowledge-source.zod.ts#KnowledgeRetrievalParsed (type)", + "KnowledgeRetrievalSchema": "src/ai/knowledge-source.zod.ts#KnowledgeRetrievalSchema (const)", "KnowledgeSource": "src/ai/knowledge-source.zod.ts#KnowledgeSource (type)", "KnowledgeSourceParsed": "src/ai/knowledge-source.zod.ts#KnowledgeSourceParsed (type)", "KnowledgeSourceSchema": "src/ai/knowledge-source.zod.ts#KnowledgeSourceSchema (const)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index 4d03a5d5c49..e2d26712da4 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -44,6 +44,7 @@ "AdapterListDocumentsOptions": "src/contracts/knowledge-adapter.ts#AdapterListDocumentsOptions (interface)", "AdapterListDocumentsPage": "src/contracts/knowledge-adapter.ts#AdapterListDocumentsPage (interface)", "AdapterListedDocument": "src/contracts/knowledge-adapter.ts#AdapterListedDocument (interface)", + "AdapterRetrievalCapability": "src/contracts/knowledge-adapter.ts#AdapterRetrievalCapability (interface)", "AdapterScopeTerm": "src/contracts/knowledge-adapter.ts#AdapterScopeTerm (type)", "AdapterSearchOptions": "src/contracts/knowledge-adapter.ts#AdapterSearchOptions (interface)", "AnalyticsDriverCapabilities": "src/contracts/analytics-service.ts#AnalyticsDriverCapabilities (interface)", diff --git a/packages/spec/json-schema.manifest/ai.json b/packages/spec/json-schema.manifest/ai.json index 4bc2c8920db..3f17e4320fe 100644 --- a/packages/spec/json-schema.manifest/ai.json +++ b/packages/spec/json-schema.manifest/ai.json @@ -54,6 +54,8 @@ "ai/KnowledgeDocument", "ai/KnowledgeHit", "ai/KnowledgeRefreshPolicy", + "ai/KnowledgeRetrieval", + "ai/KnowledgeRetrievalMode", "ai/KnowledgeSource", "ai/KnowledgeSplit", "ai/KnowledgeSplitStrategy", diff --git a/packages/spec/liveness/state-counts/knowledge_source.md b/packages/spec/liveness/state-counts/knowledge_source.md index a575042db63..1fcc479c9f3 100644 --- a/packages/spec/liveness/state-counts/knowledge_source.md +++ b/packages/spec/liveness/state-counts/knowledge_source.md @@ -12,4 +12,4 @@ committed anywhere: `check:liveness` sums the shards when it reads them. | Type | live | exp | elsewhere | dead | planned | classified | |---|---|---|---|---|---|---| -| `knowledge_source` | 26 | 0 | 0 | 6 | 0 | 32 | +| `knowledge_source` | 26 | 0 | 0 | 6 | 1 | 33 | diff --git a/packages/spec/src/ai/knowledge-source.test.ts b/packages/spec/src/ai/knowledge-source.test.ts index 663ecd5d07f..af044bd5816 100644 --- a/packages/spec/src/ai/knowledge-source.test.ts +++ b/packages/spec/src/ai/knowledge-source.test.ts @@ -450,7 +450,7 @@ describe('KnowledgeSourceSchema — `source.retrieval`, how a source is searched }); it('is published by the type\'s JSON Schema, so a document validated against it is not refused a release later', () => { - const json = z.toJSONSchema(KnowledgeSourceSchema, { io: 'input', unrepresentable: 'any' }) as { + const json = z.toJSONSchema(KnowledgeSourceSchema, { io: 'input', unrepresentable: 'any' }) as unknown as { properties: { source: { properties: Record; additionalProperties?: unknown }> } }; }; const retrieval = json.properties.source.properties.retrieval; From e582d5e89f67baebf3e2801116837abdb6abf872 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:45:45 +0000 Subject: [PATCH 06/19] chore(changeset): source.retrieval.mode and the adapter's retrieval report --- .../38692-knowledge-retrieval-mode-spec.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .changeset/38692-knowledge-retrieval-mode-spec.md diff --git a/.changeset/38692-knowledge-retrieval-mode-spec.md b/.changeset/38692-knowledge-retrieval-mode-spec.md new file mode 100644 index 00000000000..c48981f369f --- /dev/null +++ b/.changeset/38692-knowledge-retrieval-mode-spec.md @@ -0,0 +1,17 @@ +--- +'@objectstack/spec': minor +'@objectstack/service-knowledge': minor +--- + +feat(spec): a knowledge source may declare its retrieval mode, `source.retrieval.mode` (`vector`, `keyword` or `hybrid`), and a knowledge adapter reports the modes it runs + +Clause-②: yes (widening) +Metadata-protocol: added + +A `knowledge_source` may now declare how it is searched: `source: { …, retrieval: { mode: 'vector' } }`. `vector` runs only the vector leg (ranking passages by meaning), `keyword` only the keyword leg (ranking passages by the words they hold, with no call to the embedder), and `hybrid` both, merged by the store's fusion. Leaving `mode` out, or writing `retrieval: {}`, keeps the store's default, which is today's behaviour. The key is read on every search and by no build, so it enters neither the index fingerprint nor the recipe hash: changing it rebuilds nothing. The parse refuses a mode outside the three, and any other key under `retrieval`, each with the fix. Studio's knowledge source form offers the key as a "Retrieval mode" select under "Search". + +`IKnowledgeAdapter` gains two optional members. `capabilities.retrieval: { modes, default }` is the adapter's report of the modes it runs and the one it runs when a source declares none; it is a report, not configuration. `AdapterSearchOptions.retrieval: { mode }` carries the mode a search runs, a per-request parameter like `topK`. An adapter that reports no modes keeps working unchanged; a source that names it may only leave `mode` out. + +The adapter contract suite (`@objectstack/service-knowledge/testing`) takes a new optional declaration, `implements.retrieval`: it checks the adapter's report (each mode one of the three, none twice, the default listed), searches a fixed set of passages under each listed mode (`vector` leaves out the passage only the keyword leg ranks, `keyword` answers that passage alone and nothing for a query with no word any passage holds), and checks that the default mode handed explicitly answers exactly what a search without the member answers. An adapter that does not declare it is checked to report no modes. + +The knowledge service's reading of the mode (and its refusal of a mode the source's store does not run) and the turso and pgvector stores' support for it ship as separate changes. From 9e576393c79ea0d5fedea54217b52e842cdaf15b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:50:00 +0000 Subject: [PATCH 07/19] test(service-knowledge): the vector-mode contract case reads the vector leg by a passage's own text --- packages/services/service-knowledge/src/testing.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index ba240142225..1eb8060fa13 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -625,9 +625,12 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption if (!listed.includes('vector')) return; expect(opts.implements.keywordLeg, 'the vector case reads the keyword-leg fixture').toBe(true); const hits = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: { mode: 'vector' } }); - expect(hits.length).toBeGreaterThan(0); expect(hits.map((h) => h.documentId)).not.toContain(`${a.name}:clause`); nonIncreasing(hits); + // The vector leg still runs: a passage's own text ranks that passage first. + const own = await adapter.search('出 差 住 宿 费 超 标 部 门 经 理 审 批 情 况 c', { source: a, topK: 3, retrieval: { mode: 'vector' } }); + expect(own[0]?.documentId).toBe(`${a.name}:spread_c`); + nonIncreasing(own); }); it('`keyword` runs the keyword leg alone: only the passage holding the question\'s words is answered', async () => { From adc756c22659bfc1d82919594de676648346d413 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:52:38 +0000 Subject: [PATCH 08/19] feat(knowledge-turso): run one leg or both by the search's retrieval mode; report the three modes, hybrid by default --- .../src/__tests__/contract.test.ts | 1 + .../src/__tests__/retrieval-modes.test.ts | 156 ++++++++++++++++++ .../knowledge-turso/src/turso-adapter.ts | 69 +++++--- 3 files changed, 207 insertions(+), 19 deletions(-) create mode 100644 packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts diff --git a/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts b/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts index 903aba6ac35..0862fcbce35 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/contract.test.ts @@ -28,6 +28,7 @@ for (const kind of ['memory', 'file'] as const) { scope: true, dropSource: true, keywordLeg: true, + retrieval: true, }, }); }); diff --git a/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts b/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts new file mode 100644 index 00000000000..2fd7351bbad --- /dev/null +++ b/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts @@ -0,0 +1,156 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The retrieval modes (ADR-0161, the dated note on retrieval modes) on + * libSQL: the capability report, the legs each mode writes into the ranking + * statement, that `keyword` never calls the embedder nor reads the + * approximate index, and the fusion's scores — `hybrid` bit-identical to the + * fusion before modes existed, one leg `61 / (60 + rank)`. What each mode + * answers is also the contract suite's (`contract.test.ts`). + */ + +import { afterAll, describe, expect, it } from 'vitest'; +import type { Client } from '@libsql/client'; +import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai'; +import type { AdapterContext } from '@objectstack/spec/contracts'; +import { TursoKnowledgeAdapter } from '../index.js'; +import { RETRIEVAL, RRF_K, fuse } from '../turso-adapter.js'; +import { FakeEmbedder, storeOf } from './turso.testkit.js'; + +const source = (id: string): KnowledgeSource => + ({ name: id, label: id, adapter: 'under_test', source: { kind: 'object', object: 'article', content: ['body'] } }) as KnowledgeSource; +const FP = { fingerprint: 'fp-test:modes', recipeHash: 'rh-test:1' }; +const ctx = (s: KnowledgeSource): AdapterContext => ({ source: s, reason: 'manual', index: FP }); +const doc = (s: KnowledgeSource, n: string, content: string): KnowledgeDocument => { + const id = `${s.name}:${n}`; + return { id, sourceId: s.name, sourceRecordId: n, content, metadata: {}, chunks: [{ id: `${id}#0`, documentId: id, index: 0, content }] }; +}; + +/** A client whose every executed statement's SQL is recorded. */ +function recording(client: Client): { client: Client; sql: string[] } { + const sql: string[] = []; + const watched = new Proxy(client, { + get(t, key) { + const value = Reflect.get(t, key, t) as unknown; + if (typeof value !== 'function') return value; + const fn = (value as (...a: unknown[]) => unknown).bind(t); + if (key === 'execute') { + return (statement: unknown, ...rest: unknown[]) => { + sql.push(typeof statement === 'string' ? statement : String((statement as { sql: unknown }).sql)); + return fn(statement, ...rest); + }; + } + return fn; + }, + }); + return { client: watched, sql }; +} + +/** The ranking statements recorded since `from`: those that merge the legs. */ +const rankings = (sql: string[], from: number) => sql.slice(from).filter((s) => s.includes('GROUP BY chunk_id')); + +describe('knowledge-turso retrieval modes', () => { + const store = storeOf('memory'); + afterAll(() => store.closeAll()); + + async function seeded(opts: { vectorIndexThreshold?: number } = {}) { + const s = source(`modes_${Math.random().toString(36).slice(2, 8)}`); + const watched = recording(store.client()); + const embedder = new FakeEmbedder(); + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: watched.client, embedder, ...opts }); + const docs = Array.from({ length: 50 }, (_, i) => doc(s, String(i).padStart(3, '0'), `granite quarry stone ${i} w${i % 7}x`)); + await adapter.beginBuild(ctx(s)); + await adapter.upsert(docs, ctx(s)); + await adapter.completeBuild(ctx(s)); + return { s, adapter, embedder, sql: watched.sql }; + } + + it('reports all three modes, hybrid by default', () => { + const adapter = store.adapter(); + expect(adapter.capabilities.retrieval).toBe(RETRIEVAL); + expect(RETRIEVAL).toEqual({ modes: ['vector', 'keyword', 'hybrid'], default: 'hybrid' }); + }); + + it('hybrid writes both legs, and answers exactly what no mode answers', async () => { + const { s, adapter, embedder, sql } = await seeded(); + const from = sql.length; + const calls = embedder.calls; + const hybrid = await adapter.search('granite w3x', { source: s, topK: 5, retrieval: { mode: 'hybrid' }, index: FP }); + const ranked = rankings(sql, from); + expect(ranked).toHaveLength(1); + expect(ranked[0]).toContain('vec AS ('); + expect(ranked[0]).toContain('kw AS'); + expect(embedder.calls).toBe(calls + 1); + expect(hybrid).toEqual(await adapter.search('granite w3x', { source: s, topK: 5, index: FP })); + }); + + it('vector writes the vector leg alone; the first hit scores 1', async () => { + const { s, adapter, sql } = await seeded(); + const from = sql.length; + const hits = await adapter.search('granite w3x', { source: s, topK: 5, retrieval: { mode: 'vector' }, index: FP }); + const ranked = rankings(sql, from); + expect(ranked).toHaveLength(1); + expect(ranked[0]).toContain('vec AS ('); + expect(ranked[0]).not.toContain('kw AS'); + expect(hits[0]?.score).toBe(1); + }); + + it('keyword writes the keyword leg alone, never calls the embedder, and ranks equal scores by chunk id', async () => { + const { s, adapter, embedder, sql } = await seeded(); + const from = sql.length; + const calls = embedder.calls; + const hits = await adapter.search('granite', { source: s, topK: 5, retrieval: { mode: 'keyword' }, index: FP }); + const ranked = rankings(sql, from); + expect(ranked).toHaveLength(1); + expect(ranked[0]).not.toContain('vec AS ('); + expect(ranked[0]).toContain('kw AS'); + expect(embedder.calls).toBe(calls); + // Every passage holds the one term equally: chunk id order, first scoring 1. + expect(hits.map((h) => h.chunkId)).toEqual([...hits.map((h) => h.chunkId)].sort()); + expect(hits[0]?.score).toBe(1); + // No term to match: nothing, and no passage read. + const at = sql.length; + expect(await adapter.search(' ', { source: s, topK: 5, retrieval: { mode: 'keyword' }, index: FP })).toEqual([]); + expect(rankings(sql, at)).toHaveLength(0); + }); + + it('keyword never reads the approximate index of a generation that has one', async () => { + const { s, adapter, sql } = await seeded({ vectorIndexThreshold: 40 }); + const from = sql.length; + await adapter.search('granite', { source: s, topK: 5, retrieval: { mode: 'keyword' }, index: FP }); + expect(sql.slice(from).some((q) => q.includes('vector1bit('))).toBe(false); + const at = sql.length; + await adapter.search('granite', { source: s, topK: 5, retrieval: { mode: 'vector' }, index: FP }); + expect(sql.slice(at).some((q) => q.includes('vector1bit('))).toBe(true); + }); +}); + +describe('knowledge-turso fusion under the retrieval modes', () => { + type Row = { chunk_id: string; vpos: number | null; kpos: number | null }; + + /** The fusion's score as it stood before retrieval modes existed: the hybrid pin's reference. */ + const before = (row: Row): number => { + const best = 2 / (RRF_K + 1); + const leg = (pos: unknown) => (pos === null || pos === undefined ? 0 : 1 / (RRF_K + Number(pos))); + return (leg(row.vpos) + leg(row.kpos)) / best; + }; + + it('hybrid is bit-identical to the fusion before modes, for every pair of ranks up to 200', () => { + const ranks: Array = [null, ...Array.from({ length: 200 }, (_, i) => i + 1)]; + const rows: Row[] = []; + for (const vpos of ranks) for (const kpos of ranks) if (vpos !== null || kpos !== null) rows.push({ chunk_id: `${vpos}:${kpos}`, vpos, kpos }); + const fused = fuse(rows, rows.length, 2); + expect(fused).toHaveLength(rows.length); + let differing = 0; + for (const { row, score } of fused) if (!Object.is(score, before(row))) differing += 1; + expect(differing).toBe(0); + }); + + it('one leg scores 61 / (60 + rank): the first is 1, and scores fall with rank', () => { + const rows: Row[] = Array.from({ length: 50 }, (_, i) => ({ chunk_id: `c${String(i + 1).padStart(3, '0')}`, vpos: null, kpos: i + 1 })); + const fused = fuse(rows, 50, 1); + expect(fused[0]?.score).toBe(1); + for (const { row, score } of fused) expect(score).toBeCloseTo(61 / (60 + Number(row.kpos)), 12); + for (let i = 1; i < fused.length; i++) expect(fused[i - 1]!.score).toBeGreaterThan(fused[i]!.score); + }); +}); diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index 93aa4111847..3330f900f3a 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -197,6 +197,17 @@ const LOCK_CONFLICT = 'LOCK_CONFLICT'; /** The `k` of reciprocal rank fusion: a passage at rank `r` of a leg adds `1 / (k + r)` to its score. */ export const RRF_K = 60; +/** + * The retrieval modes this adapter runs, and its default (ADR-0161, the dated + * note on retrieval modes): all three, `hybrid` when a source declares none. + * A report, not configuration; the default does not move with whether a + * generation has an approximate index. + */ +export const RETRIEVAL = Object.freeze({ + modes: Object.freeze(['vector', 'keyword', 'hybrid'] as const), + default: 'hybrid' as const, +}); + /** A generation row: one index of one source under one fingerprint. */ interface GenerationRow { generation: number; @@ -310,8 +321,16 @@ function withTimeout(work: Promise, ms: number, commit = false): Promise(work: Promise, ms: number, commit = false): Promise x === 0); - const terms = keywordTerms(query); + const vectorLeg = mode !== 'keyword' && !vector.every((x) => x === 0); + const terms = mode === 'vector' ? [] : keywordTerms(query); if (!vectorLeg && terms.length === 0) return []; // One WHERE for both legs: the organization filter, the record scope and // the metadata filter, each bound as values. ?1 is the query vector. - const args: unknown[] = [vectorLiteral(vector)]; + // Under `keyword` there is no query vector and no statement reads ?1; it is bound as NULL. + const args: unknown[] = [mode === 'keyword' ? null : vectorLiteral(vector)]; const where: string[] = []; // Whether the record index can serve the exact scan: a scope of record terms alone. let recordScope = false; @@ -925,7 +953,7 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { } return this.searchAttempt(query, opts, attempt + 1); } - return fuse(result.rows, topK).map(({ row: r, score }) => { + return fuse(result.rows, topK, mode === 'hybrid' ? 2 : 1).map(({ row: r, score }) => { const headingPath = parseJson(r.heading_path); return { chunkId: String(r.chunk_id), @@ -1684,16 +1712,19 @@ async function oneBitVectorsWork(db: Pick): Promise } /** - * Reciprocal rank fusion of the two legs' rows (`vpos`, `kpos`: a row's rank - * in each leg, or null): best first, at most `topK`; a tie goes to the better + * Reciprocal rank fusion of the legs' rows (`vpos`, `kpos`: a row's rank in + * each leg, or null): best first, at most `topK`; a tie goes to the better * vector rank, then to the chunk id. The score is the fused sum divided by - * that of a row first in both legs. + * that of a row first in each of the `legs` the search's mode runs: under + * `hybrid` (two) exactly as before modes existed, under one leg + * `61 / (60 + rank)`. Exported for its pin test, not from the package entry. */ -function fuse>( +export function fuse>( rows: readonly R[], topK: number, + legs: 1 | 2, ): Array<{ row: R; score: number }> { - const best = 2 / (RRF_K + 1); + const best = legs / (RRF_K + 1); const leg = (pos: unknown) => (pos === null || pos === undefined ? 0 : 1 / (RRF_K + Number(pos))); const vectorRank = (row: R) => (row.vpos === null || row.vpos === undefined ? Infinity : Number(row.vpos)); return rows From 041525490277bfcb0102443b0566fcc90da8c7b5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 06:53:04 +0000 Subject: [PATCH 09/19] docs(knowledge-turso): the retrieval modes in the README, the protocol page and a changeset --- .changeset/38692-knowledge-turso-retrieval-modes.md | 10 ++++++++++ content/docs/protocol/knowledge.mdx | 5 ++++- packages/plugins/knowledge-turso/README.md | 2 ++ 3 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 .changeset/38692-knowledge-turso-retrieval-modes.md diff --git a/.changeset/38692-knowledge-turso-retrieval-modes.md b/.changeset/38692-knowledge-turso-retrieval-modes.md new file mode 100644 index 00000000000..f57daa1da42 --- /dev/null +++ b/.changeset/38692-knowledge-turso-retrieval-modes.md @@ -0,0 +1,10 @@ +--- +'@objectstack/knowledge-turso': patch +--- + +feat(knowledge-turso): the store runs the vector leg alone, the keyword leg alone, or both, as a source's retrieval mode says + +Clause-②: no +Metadata-protocol: none + +`knowledge-turso` now reports the retrieval modes it runs (`capabilities.retrieval`: `vector`, `keyword` and `hybrid`, with `hybrid` by default) and honours the mode the knowledge service hands it on each search (`AdapterSearchOptions.retrieval`). `hybrid`, and a search that carries no mode, run exactly as before: both legs, merged by reciprocal rank fusion, with every score unchanged to the last bit. `vector` runs the vector leg alone (the exact scan, or the approximate index as before) and `keyword` the keyword match alone; the other leg is not written into any statement, and a hit's score is `61 / (60 + rank)`, so the first is 1. `keyword` does not embed the question or read the approximate index, ranks passages of equal keyword score by chunk id, and answers nothing for a question with no term to match. The keyword index is kept whatever the mode, so changing a source's mode rebuilds nothing. diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 9b4c0e338d0..7fa4fb9243a 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -849,7 +849,10 @@ large source of one organization, through an approximate index. the [record scope](#record-scope) and the metadata `filter` (JSON equality per key) are one `WHERE`, run in both legs. Without the approximate index the vector leg reads every row in scope: 1,000 passages of 1,536 dimensions take 8.3 MB and a search about - 5 ms; 10,000 take 82 MB and about 50 ms. + 5 ms; 10,000 take 82 MB and about 50 ms. It runs all three retrieval + modes, `hybrid` by default: `vector` or `keyword` leaves the other leg out + of every statement and scores a hit `61 / (60 + rank)`, and `keyword` does + not embed the question or read the approximate index. - **Approximate index.** A complete build that completes on a generation of `vectorIndexThreshold` passages or more (default 20,000), all of one organization, makes its approximate index: each passage's vector quantized diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index 0bf9eb8ed3d..dacae08c6e6 100644 --- a/packages/plugins/knowledge-turso/README.md +++ b/packages/plugins/knowledge-turso/README.md @@ -51,6 +51,8 @@ On a file the store sets WAL and a busy timeout: without them a second process w Two legs, merged by reciprocal rank fusion (RRF, `k` = 60) before the knowledge service re-checks each hit as the caller. Each leg ranks at most `topK` passages; a hit's `score` is the sum of `1 / (60 + rank)` over the legs that rank it, divided by that of a passage first in both, so it lies in `(0, 1]`: 1 for first in both legs, 0.5 for first in one alone. +**Retrieval modes.** The store reports all three modes (`capabilities.retrieval`: `vector`, `keyword`, `hybrid`), `hybrid` by default, and a source chooses with `source.retrieval.mode`. `hybrid` runs both legs as above. `vector` runs the vector leg alone and `keyword` the keyword leg alone: the other leg is not written into any statement, and a hit's `score` is `61 / (60 + rank)`, 1 for the first. `keyword` does not embed the question or read the approximate index, ranks passages of equal keyword score by chunk id, and answers nothing for a question with no term to match. The keyword index is kept whatever the mode, so changing the mode rebuilds nothing. + - **Keyword leg.** The query is split into terms at white space and punctuation; a hyphen, dot, slash, underscore, `#`, `@` or `+` inside a term keeps it whole, so `X-200` and `v1.2` are one term each (at most 16 terms). A run of Han, kana or Hangul inside a term is cut into overlapping pieces of three characters and of two (a run of two is one piece, a run of one is dropped), so a question written without spaces is still matched word by word; a figure or a code next to a run (`2000`, `X-200`) stays one term. Under the cap the figures, codes and words come first, then the pieces of three characters, then those of two. A term of three characters or more is matched as one quoted FTS5 phrase in the passage table's trigram index — so `X-200` is text, never FTS5 syntax, and 「住宿标准」 matches inside 「员工出差住宿标准」. A shorter term, which a trigram index cannot match (「出差」), is matched by `content LIKE '%…%'` over the rows in scope. A passage's keyword score sums, over the terms it holds, the term's BM25 inverse document frequency among the rows in scope, so a word most passages hold weighs little. There is no dictionary segmentation: the pieces find a code, a name or a phrase as written, and the vector leg answers the question's meaning. - **Keyword index.** Each passage table `knowledge__g` has one beside it: a map table `…-kw`, a contentless FTS5 table `…-fts` (`tokenize='trigram'`) and three triggers that keep both in step with every insert, rewrite and removal of a passage, inside the statement that writes it. It is made with the table and dropped with it. A table made by a release without one gets it at its first search, built from the rows it holds in one transaction; until then nothing else changes. Its names hold a hyphen, which no source, generation or object name can, and an object under one of them that the store did not make is never dropped or used: the generation is refused `SERVICE_UNAVAILABLE`, naming it. - **Vector leg.** Passages ranked by the cosine distance of their stored vector (`vector_distance_cos`); a passage whose cosine similarity is not positive is not ranked by it. Its ranks 1…`topK` feed the fusion, whichever of the two ways below found the passages. From e8053716659c3d779cafe585328098641c1658bc Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 07:25:08 +0000 Subject: [PATCH 10/19] test(spec): pin KnowledgeRetrievalModeSchema as isomorphic (ADR-0122) Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- packages/spec/src/type-alias-convention.pin.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/spec/src/type-alias-convention.pin.test.ts b/packages/spec/src/type-alias-convention.pin.test.ts index 79d059e5ed7..0cfb59e9f2d 100644 --- a/packages/spec/src/type-alias-convention.pin.test.ts +++ b/packages/spec/src/type-alias-convention.pin.test.ts @@ -393,6 +393,7 @@ export type Iso_ai_knowledgeDocument__KnowledgeDocumentSchema = Assert, z.infer< typeof M3.KnowledgeHitSchema > >>; // ai/knowledge-source.zod.ts +export type Iso_ai_knowledgeSource__KnowledgeRetrievalModeSchema = Assert, z.infer< typeof M4.KnowledgeRetrievalModeSchema > >>; export type Iso_ai_knowledgeSource__ObjectKnowledgeSourceSchema = Assert, z.infer< typeof M4.ObjectKnowledgeSourceSchema > >>; // ai/mcp.zod.ts From 14b8b7a4ae831f7a73d91ac2289bfa5be1152321 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 07:35:41 +0000 Subject: [PATCH 11/19] docs(knowledge): the adapter contract carries the retrieval mode; name its per-search refusal code ADR-0161's K2 row on the adapter surface no longer says "no hybrid toggle": the contract carries the modes an adapter runs and the mode a search runs in, which a source declares. Protocol doc 7.1 says the same. The contract doc of AdapterSearchOptions.retrieval names the refusal of a mode the adapter does not list: SERVICE_UNAVAILABLE in a search's refused, VALIDATION_ERROR at save and registration. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- content/docs/protocol/knowledge.mdx | 4 +++- ...plit-record-return-knowledge-source-is-a-governed-type.md | 2 +- packages/spec/src/contracts/knowledge-adapter.ts | 5 +++++ 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 9b4c0e338d0..685004cae35 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -1504,7 +1504,9 @@ followed (§4.1, §4.2) are the adapters to run in production. ### 7.1 Non-goals for Phase 1 -- Reranker hooks, hybrid retrieval toggles, MMR — adapter-private. +- Reranker hooks, MMR — adapter-private. Which legs a search runs is not: + a source declares it (`source.retrieval.mode`, §3.1); how the legs are + weighted is not authorable yet. - Field-level masking inside a passage. A source serving a field the caller may not query is not searched for that caller at all (§5, source admission); a passage is never re-projected or redacted per caller. diff --git a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md index e8612d48a02..0f771225031 100644 --- a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md +++ b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md @@ -147,7 +147,7 @@ Each text below states the old position. The left column quotes it as it reads a | Same file, §1: "We have nothing distinctive to add to those layers." and "The protocol scopes the framework's responsibility to (1)–(4) and delegates the rest to plugins." | The framework's list grows by the four of K1; what is delegated is the adapter's four. | #37096 | | Same file, §3.1: a source "is stored as metadata (versioned, environment-scoped) just like a view or a flow", against the schema note on `packages/spec/src/ai/knowledge-source.zod.ts#KnowledgeSourceSchema`: "the shape of a **runtime registration**, ⛔ not a governed metadata type". | The two agree: a source is a `knowledge_source` item (K4). Until row 3 lands, the schema note is the true one. | row 3 | | Same file, §3.2: "The framework does **not** chunk; adapters do." | The framework splits; adapters index the passages. | #37098 (row 6) | -| Same file, §3.4, and the note on `packages/spec/src/contracts/knowledge-adapter.ts#IKnowledgeAdapter`: "The surface is **deliberately minimal**: no chunk strategy, no embedding configuration, no rerank toggles." | The contract grows by K8's list. It carries what an adapter reports about its embedder and still no configuration, no rerank and no hybrid toggle. | #37096, then each card that adds a member | +| Same file, §3.4, and the note on `packages/spec/src/contracts/knowledge-adapter.ts#IKnowledgeAdapter`: "The surface is **deliberately minimal**: no chunk strategy, no embedding configuration, no rerank toggles." | The contract grows by K8's list. It carries what an adapter reports about its embedder and the retrieval modes it runs (`capabilities.retrieval`), and the mode a search runs in (`AdapterSearchOptions.retrieval`), which a source declares; still no configuration and no rerank. | #37096, then each card that adds a member (#38692 phase 1a: the retrieval mode) | | Same file, §6: "that surface stays unbuilt until a real `object` source calls for it." | The enumeration surface is built (K8, item 1); reconcile covers application-level predicate writes. | #37096 and row 15 | | Same file, §7 and §8: `knowledge-pgvector` as "Phase 3", and "a `KnowledgeSource.embedding` field". | `knowledge-pgvector` is an open adapter of this repository (cloud ADR-0119 D5); `embedding` is removed (K6). | #37100, row 3 | | `packages/spec/src/ai/embedding.zod.ts`, file note: "NOT in scope (these belong to application code, not the platform): Chunking strategies (fixed/semantic/recursive/markdown)." and "These were removed in v1 because they describe one specific way to build a RAG application". | Structural splitting is a platform capability of the knowledge service. It does not return as the pipeline vocabulary that was removed. Retrieval pipelines, document loaders and end-to-end orchestration stay out of scope. | #37098 | diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index 4d729a55900..0790d351e29 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -192,6 +192,11 @@ export interface AdapterSearchOptions { * The service hands only a mode the adapter lists in * `capabilities.retrieval.modes`, and never hands this member to an adapter * that reports no `capabilities.retrieval`. Absent: the adapter's default. + * A source declaring a mode its adapter does not list is never searched + * another way: the knowledge service lists it in a search's `refused` with + * `SERVICE_UNAVAILABLE` (503, the ADR-0112 standard code a source whose + * adapter is not mounted is refused with there), and refuses it at its save + * and registration with `VALIDATION_ERROR` (400). * Scores need only not increase with rank within one source's answer; under * a one-leg mode they reflect rank alone. */ From 08788c6156c1e92d49d4dbe5c5cbfe571b829675 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 08:32:14 +0000 Subject: [PATCH 12/19] fix(platform-objects): name the retrieval-mode choices in every locale; count the new isomorphic pin The knowledge source form's Search group and its Retrieval mode select get their translation bundle entries, translated in the ten locales, and the ADR-0122 pin count moves 880 -> 881 for KnowledgeRetrievalModeSchema. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- .../translations/ar.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/de.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/en.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/es-ES.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/fr.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/ja-JP.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/ko.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/pt-BR.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/ru.metadata-forms.generated.ts | 13 +++++++++++++ .../translations/zh-CN.metadata-forms.generated.ts | 13 +++++++++++++ .../zh-Hant.metadata-forms.generated.ts | 13 +++++++++++++ packages/spec/src/type-alias-convention.pin.test.ts | 10 +++++++--- 12 files changed, 150 insertions(+), 3 deletions(-) diff --git a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts index 122b54abb87..077577dcfa0 100644 --- a/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const arMetadataForms: NonNullable = { label: "Order for the asker", helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "البحث", + helpText: "كيف يعثر البحث في هذا المصدر على المقاطع. اتركه فارغًا لاستخدام الوضع الافتراضي للمخزن. تغييره لا يعيد بناء أي شيء." + }, + "source.retrieval.mode": { + label: "وضع الاسترجاع", + helpText: "فارغ: الوضع الافتراضي للمخزن (هجين في turso وpgvector). المتجه يرتّب المقاطع حسب المعنى؛ والكلمات المفتاحية حسب الكلمات التي تحتويها، دون استدعاء مزوّد التضمين، وهو ما يناسب أرقام المستندات أو البنود؛ والهجين يدمج الاثنين. يُرفض عند الحفظ أي وضع لا يشغّله المخزن.", + options: { + vector: "المتجه فقط (حسب المعنى)", + keyword: "الكلمات المفتاحية فقط (حسب الكلمات)", + hybrid: "هجين (كلاهما)" + } + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts index fa9fe31de92..31d44962244 100644 --- a/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const deMetadataForms: NonNullable = { label: "Order for the asker", helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "Suche", + helpText: "Wie eine Suche in dieser Quelle Passagen findet. Leer lassen für den Standard des Speichers. Eine Änderung löst keinen Neuaufbau aus." + }, + "source.retrieval.mode": { + label: "Abrufmodus", + helpText: "Leer: der Standard des Speichers (hybrid bei turso und pgvector). Vektor ordnet Passagen nach Bedeutung; Stichwort nach den enthaltenen Wörtern, ohne Aufruf des Embedding-Anbieters, was zu Dokument- oder Klauselnummern passt; hybrid führt beides zusammen. Ein Modus, den der Speicher nicht ausführt, wird beim Speichern abgelehnt.", + options: { + vector: "Nur Vektor (nach Bedeutung)", + keyword: "Nur Stichwort (nach Wörtern)", + hybrid: "Hybrid (beides)" + } + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index b857c9545f3..f6607bfb55f 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const enMetadataForms: NonNullable = { label: "Order for the asker", helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "Search", + helpText: "How a search of this source finds passages. Leave it blank for the store's default. Changing it rebuilds nothing." + }, + "source.retrieval.mode": { + label: "Retrieval mode", + helpText: "Blank: the store's default (hybrid on turso and pgvector). Vector ranks passages by meaning; keyword by the words they hold, with no call to the embedding provider, which suits document or clause numbers; hybrid merges both. A mode the store does not run is refused at save.", + options: { + vector: "Vector only (by meaning)", + keyword: "Keyword only (by words)", + hybrid: "Hybrid (both)" + } + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts index 9bea909628d..b859ff778ee 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const esESMetadataForms: NonNullable = label: "Orden según quien pregunta", helpText: "Opcional. Enumera entradas que suben en la respuesta los resultados relacionados con quien pregunta; por ejemplo, [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] pone primero su propia unidad, luego sus unidades superiores y después el resto, y [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] deja que un resultado suyo adelante hasta 3 otros (de 1 a 20). Cada campo debe figurar en los campos de filtro y apuntar a usuarios (caller user) o a unidades de negocio (caller business_unit); como máximo un nearest. No se descarta ningún resultado ni cambia su puntuación, y configurarlo no reconstruye nada.\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "Búsqueda", + helpText: "Cómo una búsqueda en esta fuente encuentra pasajes. Déjalo vacío para usar el modo predeterminado del almacén. Cambiarlo no reconstruye nada." + }, + "source.retrieval.mode": { + label: "Modo de recuperación", + helpText: "Vacío: el modo predeterminado del almacén (híbrido en turso y pgvector). Vectorial ordena los pasajes por su significado; palabra clave por las palabras que contienen, sin llamar al proveedor de embeddings, lo que sirve para números de documento o de cláusula; híbrido combina ambos. Un modo que el almacén no ejecuta se rechaza al guardar.", + options: { + vector: "Solo vectorial (por significado)", + keyword: "Solo palabra clave (por palabras)", + hybrid: "Híbrido (ambos)" + } + }, "source.where": { label: "Registros que indexar", helpText: "Un filtro ObjectQL sobre el objeto, por ejemplo {\"status\": {\"$ne\": \"done\"}}. Solo se indexan los registros que coinciden. En blanco: todos los registros." diff --git a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts index d5b376fbe0b..1d5e5fa33f4 100644 --- a/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const frMetadataForms: NonNullable = { label: "Order for the asker", helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "Recherche", + helpText: "Comment une recherche dans cette source trouve les passages. Laissez vide pour le mode par défaut du magasin. Le modifier ne reconstruit rien." + }, + "source.retrieval.mode": { + label: "Mode de recherche", + helpText: "Vide : le mode par défaut du magasin (hybride sur turso et pgvector). Vectoriel classe les passages par leur sens ; mot-clé par les mots qu'ils contiennent, sans appel au fournisseur d'embeddings, ce qui convient aux numéros de document ou de clause ; hybride fusionne les deux. Un mode que le magasin n'exécute pas est refusé à l'enregistrement.", + options: { + vector: "Vectoriel seul (par le sens)", + keyword: "Mot-clé seul (par les mots)", + hybrid: "Hybride (les deux)" + } + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts index fd74ec8dbac..199f97863e3 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const jaJPMetadataForms: NonNullable = label: "質問者に合わせた並び順", helpText: "任意。質問者に関係するヒットを上位に移すエントリを並べます。例:[{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] は質問者自身の部門を先頭に、次に上位部門を順に、最後にその他を並べ、[{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] は質問者が所有するヒットを最大 3 件分上に移します(1〜20)。各フィールドはフィルターフィールドに含まれ、ユーザー(caller が user)またはビジネスユニット(caller が business_unit)を指す必要があります。nearest は 1 つまでです。ヒットを除外することもスコアを変えることもなく、設定しても再構築は行われません。\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "検索", + helpText: "このソースを検索するときのパッセージの探し方。空欄にするとストアの既定になります。変更しても再構築は行われません。" + }, + "source.retrieval.mode": { + label: "検索モード", + helpText: "空欄:ストアの既定(turso と pgvector ではハイブリッド)。ベクトルは意味でパッセージを順位付けし、キーワードは含まれる語句で順位付けします(埋め込みプロバイダーは呼び出さないため、文書番号や条項番号に向いています)。ハイブリッドは両方を統合します。ストアが実行しないモードは保存時に拒否されます。", + options: { + vector: "ベクトルのみ(意味で)", + keyword: "キーワードのみ(語句で)", + hybrid: "ハイブリッド(両方)" + } + }, "source.where": { label: "インデックス化するレコード", helpText: "オブジェクトに対する ObjectQL フィルター。例:{\"status\": {\"$ne\": \"done\"}}。一致するレコードだけがインデックス化されます。空欄:すべてのレコード。" diff --git a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts index 2b5de15d92f..92f3c7326ff 100644 --- a/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const koMetadataForms: NonNullable = { label: "Order for the asker", helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "검색", + helpText: "이 소스를 검색할 때 구절을 찾는 방식입니다. 비워 두면 저장소의 기본값을 사용합니다. 변경해도 다시 빌드하지 않습니다." + }, + "source.retrieval.mode": { + label: "검색 방식", + helpText: "비워 두면 저장소의 기본값(turso와 pgvector에서는 하이브리드)을 사용합니다. 벡터는 의미로 구절의 순위를 매기고, 키워드는 구절에 담긴 단어로 순위를 매기며 임베딩 제공자를 호출하지 않아 문서 번호나 조항 번호에 적합합니다. 하이브리드는 둘을 합칩니다. 저장소가 실행하지 않는 방식은 저장 시 거부됩니다.", + options: { + vector: "벡터만(의미 기준)", + keyword: "키워드만(단어 기준)", + hybrid: "하이브리드(둘 다)" + } + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts index f359904d89f..63d3a209749 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const ptBRMetadataForms: NonNullable = label: "Order for the asker", helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "Busca", + helpText: "Como uma busca nesta fonte encontra trechos. Deixe em branco para usar o padrão do armazenamento. Alterar não reconstrói nada." + }, + "source.retrieval.mode": { + label: "Modo de recuperação", + helpText: "Em branco: o padrão do armazenamento (híbrido no turso e no pgvector). Vetorial ordena os trechos pelo significado; palavra-chave pelas palavras que contêm, sem chamar o provedor de embeddings, o que serve para números de documento ou de cláusula; híbrido combina os dois. Um modo que o armazenamento não executa é recusado ao salvar.", + options: { + vector: "Somente vetorial (pelo significado)", + keyword: "Somente palavra-chave (pelas palavras)", + hybrid: "Híbrido (ambos)" + } + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts index 88ff3a6b1bf..0937d28506d 100644 --- a/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const ruMetadataForms: NonNullable = { label: "Order for the asker", helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "Поиск", + helpText: "Как поиск по этому источнику находит фрагменты. Оставьте пустым, чтобы использовать режим хранилища по умолчанию. Изменение ничего не перестраивает." + }, + "source.retrieval.mode": { + label: "Режим поиска", + helpText: "Пусто: режим хранилища по умолчанию (гибридный в turso и pgvector). Векторный упорядочивает фрагменты по смыслу; по ключевым словам — по содержащимся в них словам, без обращения к провайдеру эмбеддингов, что подходит для номеров документов или пунктов; гибридный объединяет оба. Режим, который хранилище не выполняет, отклоняется при сохранении.", + options: { + vector: "Только векторный (по смыслу)", + keyword: "Только ключевые слова (по словам)", + hybrid: "Гибридный (оба)" + } + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts index 83afaf885ea..d527bd0cc50 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const zhCNMetadataForms: NonNullable = label: "按提问人排序", helpText: "可选。列出把与提问人相关的命中往前排的条目,例如 [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] 先排提问人本单位,再按上级单位逐级,最后其余;[{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] 让提问人负责的命中最多越过 3 条其他命中(1 到 20)。每个字段须列在筛选字段中,并指向用户(caller 为 user)或业务单位(caller 为 business_unit);nearest 最多一条。不会丢弃命中,也不改分数,设置它不会触发重建。\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "检索", + helpText: "检索此来源时如何查找段落。留空则使用存储的默认方式。修改它不会触发重建。" + }, + "source.retrieval.mode": { + label: "检索方式", + helpText: "留空:使用存储的默认方式(turso 和 pgvector 为混合)。向量按含义对段落排序;关键词按段落包含的词语排序,不调用嵌入服务,适合文件编号或条款编号;混合则合并两者。存储不支持的方式在保存时会被拒绝。", + options: { + vector: "仅向量(按含义)", + keyword: "仅关键词(按词语)", + hybrid: "混合(两者)" + } + }, "source.where": { label: "要索引的记录", helpText: "对该对象的 ObjectQL 筛选条件,例如 {\"status\": {\"$ne\": \"done\"}}。只有匹配的记录会被索引。留空:所有记录。" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts index cd7cc6e30cf..25d84eaf09e 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.metadata-forms.generated.ts @@ -3565,6 +3565,19 @@ export const zhHantMetadataForms: NonNullable label: "Order for the asker", helpText: "Optional. Lists entries that move hits related to the person asking up the answer, for example [{\"field\": \"business_unit\", \"caller\": \"business_unit\", \"mode\": \"nearest\"}] puts their own unit first, then its parent units, then the rest, and [{\"field\": \"owner\", \"caller\": \"user\", \"mode\": \"boost\", \"places\": 3}] lets a hit they own pass up to 3 others (1 to 20). Each field must be in Filter fields and point at users (caller user) or business units (caller business_unit); at most one nearest. Nothing is dropped or scored differently, and setting it rebuilds nothing." }, + "source.retrieval": { + label: "檢索", + helpText: "檢索此來源時如何查找段落。留空則使用儲存的預設方式。修改它不會觸發重建。" + }, + "source.retrieval.mode": { + label: "檢索方式", + helpText: "留空:使用儲存的預設方式(turso 和 pgvector 為混合)。向量依含義排序段落;關鍵字依段落包含的詞語排序,不呼叫嵌入服務,適合文件編號或條款編號;混合則合併兩者。儲存不支援的方式在儲存時會被拒絕。", + options: { + vector: "僅向量(依含義)", + keyword: "僅關鍵字(依詞語)", + hybrid: "混合(兩者)" + } + }, "source.where": { label: "Records to index", helpText: "An ObjectQL filter on the object, for example {\"status\": {\"$ne\": \"done\"}}. Only the records it matches are indexed. Blank: every record." diff --git a/packages/spec/src/type-alias-convention.pin.test.ts b/packages/spec/src/type-alias-convention.pin.test.ts index 0cfb59e9f2d..5b46eddeb02 100644 --- a/packages/spec/src/type-alias-convention.pin.test.ts +++ b/packages/spec/src/type-alias-convention.pin.test.ts @@ -305,7 +305,7 @@ import type * as M205 from './ai/object-query-source.zod.js'; import type * as M207 from './api/ai-answer.zod.js'; // --------------------------------------------------------------------------- -// 880 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. +// 881 isomorphic aliases: `z.input` === `z.infer`, so no `XParsed` is declared. // // That number is machine-checked, not hand-kept. The runtime companion at the // bottom of this file recomputes the pin count from the source and asserts that @@ -1848,7 +1848,7 @@ describe('ADR-0122 type-alias convention', () => { // this title and the section header above the pin list — are now asserted // against the recomputed count below, so neither can go stale without a red // test naming it. - it('still declares all 880 isomorphic pins', () => { + it('still declares all 881 isomorphic pins', () => { // The truth of each pin is proved by tsc, not here — an `Assert>` // that stops holding is a compile error with the alias named. What tsc // cannot notice is a pin that was DELETED: removing the assertion removes @@ -2988,7 +2988,11 @@ describe('ADR-0122 type-alias convention', () => { // `RecordQuickActionsLocationSchema` (`ui/action.zod.ts`), the shared // location enum less `record`, with no default or transform // (Iso_ui_action__RecordQuickActionsLocationSchema). +1 added. - expect(pins).toHaveLength(880); + // 880 -> 881 is #38692: the mode a knowledge source's searches run in, + // `KnowledgeRetrievalModeSchema` (`ai/knowledge-source.zod.ts`), a plain + // enum with no default or transform + // (Iso_ai_knowledgeSource__KnowledgeRetrievalModeSchema). +1 added. + expect(pins).toHaveLength(881); // The count is stated in PROSE twice as well — this case's title and the // section header above the pin list — and until commit c6b05c76a nothing read either From 7436d4f2e31fad5d3a79154b0a591dfa0bfad198 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 08:52:18 +0000 Subject: [PATCH 13/19] test(platform-objects): count the retrieval-mode rows in the translated metadata-form catalog Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- .../object-lifecycle-panel-echo-decisions.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts index 9058db36f9c..68ffe3980d7 100644 --- a/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts +++ b/packages/platform-objects/src/apps/translations/object-lifecycle-panel-echo-decisions.test.ts @@ -1361,7 +1361,10 @@ describe('#19403 round 10 — the verdicts, on the live bundles', () => { // authored in all three locales. // 869 since #37792: the object form's `pinOverview` row (the record // page layout switch) — one row label, authored in all three locales. - expect(translated.length, `${locale} positive control`).toBe(869); + // 871 since #38692: the `knowledge_source` form's `source.retrieval` + // group and its `mode` row (the retrieval mode) — two row labels, + // authored in every locale. + expect(translated.length, `${locale} positive control`).toBe(871); } // ⭐ DARK — the blindness, executable. On a synthetic two-locale catalog the // all-three predicate returns 0 while the per-locale one returns 1, so the From 53a6f991bce1c26c282e6838ec71526ea741b45b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 09:01:26 +0000 Subject: [PATCH 14/19] test(knowledge-turso): a vector-mode search writes no keyword condition at all Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- .../src/__tests__/retrieval-modes.test.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts b/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts index 2fd7351bbad..718ce4ecda0 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts @@ -80,6 +80,8 @@ describe('knowledge-turso retrieval modes', () => { expect(ranked).toHaveLength(1); expect(ranked[0]).toContain('vec AS ('); expect(ranked[0]).toContain('kw AS'); + // The control for the vector case below: hybrid does write the keyword terms. + expect(ranked[0]).toMatch(/\bMATCH\b/); expect(embedder.calls).toBe(calls + 1); expect(hybrid).toEqual(await adapter.search('granite w3x', { source: s, topK: 5, index: FP })); }); @@ -92,6 +94,15 @@ describe('knowledge-turso retrieval modes', () => { expect(ranked).toHaveLength(1); expect(ranked[0]).toContain('vec AS ('); expect(ranked[0]).not.toContain('kw AS'); + // No keyword condition is written at all, not just left out of the fusion: on a + // large table the keyword terms (LIKE, or the FTS5 match) are most of a search's cost. + const written = sql.slice(from); + expect(written.length).toBeGreaterThan(0); + for (const q of written) { + expect(q).not.toMatch(/\bLIKE\b/i); + expect(q).not.toMatch(/\bMATCH\b/); + expect(q).not.toContain('-fts'); + } expect(hits[0]?.score).toBe(1); }); From b15ac8df9799f66e3993ca40c44e6388c2884953 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 09:42:19 +0000 Subject: [PATCH 15/19] docs(spec): cite the ADR-0161 note of 2026-11-30 under K8 by its place; regenerate the spec artifacts after the merge of main The merge of main had left the ai shards of the generated spec artifacts without main's TurnEnd rows; check:generated --fix rewrites them from a fresh build. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- content/docs/references/index.mdx | 9 +++++---- .../2026-07-unknown-key-strictness-ledger.counts/ai.md | 2 +- .../src/__tests__/index-fingerprint.test.ts | 4 ++-- packages/services/service-knowledge/src/testing.ts | 4 ++-- packages/spec/api-surface/ai.json | 4 ++++ packages/spec/authorable-surface/ai.json | 7 ++++++- packages/spec/declaration-map/ai.json | 4 +++- packages/spec/export-origins/ai.json | 4 ++++ packages/spec/json-schema.manifest/ai.json | 3 ++- packages/spec/liveness/knowledge_source.json | 2 +- packages/spec/src/ai/knowledge-source.test.ts | 2 +- packages/spec/src/ai/knowledge-source.zod.ts | 6 +++--- packages/spec/src/contracts/knowledge-adapter.ts | 6 +++--- 13 files changed, 37 insertions(+), 20 deletions(-) diff --git a/content/docs/references/index.mdx b/content/docs/references/index.mdx index 03b540df209..40f494a7901 100644 --- a/content/docs/references/index.mdx +++ b/content/docs/references/index.mdx @@ -1,7 +1,7 @@ --- title: Protocol reference — every schema by module navTitle: Protocol Reference -description: Every schema published by @objectstack/spec — 1747 schemas across 14 protocol modules +description: Every schema published by @objectstack/spec — 1748 schemas across 14 protocol modules --- {/* ⚠️ AUTO-GENERATED — DO NOT EDIT. Run build-docs.ts to regenerate. Hand-written docs live in the module folders under content/docs/. */} @@ -22,7 +22,7 @@ counts are sums of the rows they head. Regenerate with | Module | Pages | Schemas | Description | | :--- | ---: | ---: | :--- | -| [AI Protocol](/docs/references/ai) | 17 | 107 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | +| [AI Protocol](/docs/references/ai) | 18 | 108 | Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | | [API Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/api) | 37 | 528 | REST contracts, endpoints, routing, realtime, batch, discovery. | | [Automation Protocol](/docs/references/automation) | 16 | 82 | Flows and their nodes, approvals, ETL pipelines, webhooks, state machines, execution records. | | [Data Protocol](/docs/references/data) | 35 | 197 | Objects, fields, queries, filters, datasources and drivers — the ObjectQL layer. | @@ -36,13 +36,13 @@ counts are sums of the rows they head. Regenerate with | [Studio Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/studio) | 3 | 35 | Studio designer metadata — the authoring surfaces for the protocols above. | | [System Protocol](https://github.com/objectstack-ai/objectstack/tree/main/packages/spec/docs/references/system) | 40 | 298 | The runtime environment — logging, jobs, cache, metrics, notifications, i18n and compliance. | | [UI Protocol](/docs/references/ui) | 17 | 187 | Apps, pages, views, dashboards, reports, actions and themes — the ObjectUI layer. | -| **Total** | **223** | **1747** | 14 protocol modules | +| **Total** | **224** | **1748** | 14 protocol modules | --- ## AI Protocol -**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **17 pages, 107 schemas** +**Source:** `packages/spec/src/ai/` · **Import:** `@objectstack/spec/ai` · **18 pages, 108 schemas** Agents, tools, skills, RAG and knowledge sources, model registry, conversations. @@ -64,6 +64,7 @@ Agents, tools, skills, RAG and knowledge sources, model registry, conversations. | [`skill.zod.ts`](/docs/references/ai/skill) | `Skill`, `SkillTriggerCondition` | | [`solution-blueprint.zod.ts`](/docs/references/ai/solution-blueprint) | `BlueprintApp`, `BlueprintCondition`, `BlueprintDashboard`, `BlueprintField`, `BlueprintNavItem`, `BlueprintObject`, `BlueprintSeed`, `BlueprintSummaryOperations`, `BlueprintView`, `BlueprintWidgetCondition`, `SolutionBlueprint`, `SolutionBlueprintStrict` | | [`tool.zod.ts`](/docs/references/ai/tool) | `Tool` | +| [`turn-end.zod.ts`](/docs/references/ai/turn-end) | `TurnEnd` | | [`usage.zod.ts`](/docs/references/ai/usage) | `AIUsageRecord`, `TokenUsage` | --- diff --git a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md index 050f8f7f1d7..3ecff028bbc 100644 --- a/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md +++ b/docs/audits/2026-07-unknown-key-strictness-ledger.counts/ai.md @@ -19,4 +19,4 @@ hand-patch a number here** — fix the code or the verdict and regenerate. | Dir | Sites | |---|---| -| `ai/` | 122 | +| `ai/` | 123 | diff --git a/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts b/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts index 2168abc0b70..5ea16f03535 100644 --- a/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts +++ b/packages/services/service-knowledge/src/__tests__/index-fingerprint.test.ts @@ -172,9 +172,9 @@ describe('recipe hash (ADR-0161 K7)', () => { }); // `source.retrieval` is read on every search and by no build (ADR-0161, the -// dated note on retrieval modes): neither hash moves with it, so changing a +// dated note of 2026-11-30 under K8): neither hash moves with it, so changing a // source's retrieval mode rebuilds nothing. -describe('retrieval mode (ADR-0161, the dated note on retrieval modes)', () => { +describe('retrieval mode (ADR-0161, the dated note of 2026-11-30 under K8)', () => { it('changes neither the index fingerprint nor the recipe hash', () => { const fingerprint = computeIndexFingerprint({ source: source(), embedding, split }); const recipe = computeRecipeHash({ source: source() }); diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 1eb8060fa13..78f526856b2 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -155,7 +155,7 @@ export interface KnowledgeAdapterContractOptions { */ keywordLeg?: boolean; /** - * `capabilities.retrieval` (ADR-0161, the dated note on retrieval modes): + * `capabilities.retrieval` (ADR-0161, the dated note of 2026-11-30 under K8): * the adapter reports the modes it runs and its default, and its search * honours `AdapterSearchOptions.retrieval`. The report is checked against * the three modes, and each listed mode is asserted by behaviour: `vector` @@ -587,7 +587,7 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption } if (opts.implements.retrieval === true) { - describe('retrieval modes (ADR-0161, the dated note on retrieval modes)', () => { + describe('retrieval modes (ADR-0161, the dated note of 2026-11-30 under K8)', () => { it('reports the modes it runs, each once and each one of the three, and a default it lists', async () => { const adapter: IKnowledgeAdapter = await make(); const report = adapter.capabilities?.retrieval; diff --git a/packages/spec/api-surface/ai.json b/packages/spec/api-surface/ai.json index 0bfeb1ab566..c9ffbb4d6d6 100644 --- a/packages/spec/api-surface/ai.json +++ b/packages/spec/api-surface/ai.json @@ -296,6 +296,7 @@ "StructuredOutputConfigSchema (const)", "StructuredOutputFormat (type)", "StructuredOutputFormatSchema (const)", + "TURN_END_PART_TYPE (const)", "TextContent (type)", "TextContentSchema (const)", "TokenBudgetConfig (type)", @@ -315,6 +316,9 @@ "ToolSchema (const)", "TransformPipelineStep (type)", "TransformPipelineStepSchema (const)", + "TurnEnd (type)", + "TurnEndParsed (type)", + "TurnEndSchema (const)", "agentForm (const)", "aiContextForm (const)", "aiContextWhereFields (function)", diff --git a/packages/spec/authorable-surface/ai.json b/packages/spec/authorable-surface/ai.json index 529db46b843..ab5bb1bb688 100644 --- a/packages/spec/authorable-surface/ai.json +++ b/packages/spec/authorable-surface/ai.json @@ -577,6 +577,11 @@ "ai/Tool:protection", "ai/ToolCall:function", "ai/ToolCall:id", - "ai/ToolCall:type" + "ai/ToolCall:type", + "ai/TurnEnd:reason", + "ai/TurnEnd:resumable", + "ai/TurnEnd:resumesLeft", + "ai/TurnEnd:turnId", + "ai/TurnEnd:wrapUp" ] } diff --git a/packages/spec/declaration-map/ai.json b/packages/spec/declaration-map/ai.json index 70474f71dfe..0d874a661cb 100644 --- a/packages/spec/declaration-map/ai.json +++ b/packages/spec/declaration-map/ai.json @@ -209,7 +209,9 @@ "ToolCallSchema": "ai/ToolCall", "ToolSchema": "ai/Tool", "TransformPipelineStep": "ai/TransformPipelineStep", - "TransformPipelineStepSchema": "ai/TransformPipelineStep" + "TransformPipelineStepSchema": "ai/TransformPipelineStep", + "TurnEnd": "ai/TurnEnd", + "TurnEndSchema": "ai/TurnEnd" }, "collisions": [] } diff --git a/packages/spec/export-origins/ai.json b/packages/spec/export-origins/ai.json index 2114847e360..610779dc917 100644 --- a/packages/spec/export-origins/ai.json +++ b/packages/spec/export-origins/ai.json @@ -293,6 +293,7 @@ "StructuredOutputConfigSchema": "src/ai/agent.zod.ts#StructuredOutputConfigSchema (const)", "StructuredOutputFormat": "src/ai/agent.zod.ts#StructuredOutputFormat (type)", "StructuredOutputFormatSchema": "src/ai/agent.zod.ts#StructuredOutputFormatSchema (const)", + "TURN_END_PART_TYPE": "src/ai/turn-end.zod.ts#TURN_END_PART_TYPE (const)", "TextContent": "src/ai/conversation.zod.ts#TextContent (type)", "TextContentSchema": "src/ai/conversation.zod.ts#TextContentSchema (const)", "TokenBudgetConfig": "src/ai/conversation.zod.ts#TokenBudgetConfig (type)", @@ -312,6 +313,9 @@ "ToolSchema": "src/ai/tool.zod.ts#ToolSchema (const)", "TransformPipelineStep": "src/ai/agent.zod.ts#TransformPipelineStep (type)", "TransformPipelineStepSchema": "src/ai/agent.zod.ts#TransformPipelineStepSchema (const)", + "TurnEnd": "src/ai/turn-end.zod.ts#TurnEnd (type)", + "TurnEndParsed": "src/ai/turn-end.zod.ts#TurnEndParsed (type)", + "TurnEndSchema": "src/ai/turn-end.zod.ts#TurnEndSchema (const)", "agentForm": "src/ai/agent.metadata-form.ts#agentForm (const)", "aiContextForm": "src/ai/ai-context.metadata-form.ts#aiContextForm (const)", "aiContextWhereFields": "src/ai/ai-context.zod.ts#aiContextWhereFields (function)", diff --git a/packages/spec/json-schema.manifest/ai.json b/packages/spec/json-schema.manifest/ai.json index 3f17e4320fe..56fd5331ef4 100644 --- a/packages/spec/json-schema.manifest/ai.json +++ b/packages/spec/json-schema.manifest/ai.json @@ -108,6 +108,7 @@ "ai/TokenUsageStats", "ai/Tool", "ai/ToolCall", - "ai/TransformPipelineStep" + "ai/TransformPipelineStep", + "ai/TurnEnd" ] } diff --git a/packages/spec/liveness/knowledge_source.json b/packages/spec/liveness/knowledge_source.json index ca269505e36..672e1a0b0e8 100644 --- a/packages/spec/liveness/knowledge_source.json +++ b/packages/spec/liveness/knowledge_source.json @@ -124,7 +124,7 @@ "retrieval": { "status": "planned", "verifiedAt": "2026-11-30", - "note": "PLANNED RECORD (ruling 7270218011 on #38692, phase 1a; ADR-0161, the dated note on retrieval modes): `retrieval: { mode }`, how a source is searched. CARRIED today: it parses at every door (strict, `retrieval: {}` allowed) and is kept by the parse. ACTED ON by nothing yet: the knowledge service resolves the effective mode (the source's declaration, else the adapter's `capabilities.retrieval.default`), refuses a mode the adapter does not list at the four points the ruling names, and hands it to the adapter as `AdapterSearchOptions.retrieval`; knowledge-turso and knowledge-pgvector run one leg or both. Those are the phase-1a PRs that follow this one. Flip to `live` on the commit that lands the service's reader, citing it. Enters neither the index fingerprint nor the recipe hash.", + "note": "PLANNED RECORD (ruling 7270218011 on #38692, phase 1a; ADR-0161, the dated note of 2026-11-30 under K8): `retrieval: { mode }`, how a source is searched. CARRIED today: it parses at every door (strict, `retrieval: {}` allowed) and is kept by the parse. ACTED ON by nothing yet: the knowledge service resolves the effective mode (the source's declaration, else the adapter's `capabilities.retrieval.default`), refuses a mode the adapter does not list at the four points the ruling names, and hands it to the adapter as `AdapterSearchOptions.retrieval`; knowledge-turso and knowledge-pgvector run one leg or both. Those are the phase-1a PRs that follow this one. Flip to `live` on the commit that lands the service's reader, citing it. Enters neither the index fingerprint nor the recipe hash.", "children": { "mode": { "status": "planned", diff --git a/packages/spec/src/ai/knowledge-source.test.ts b/packages/spec/src/ai/knowledge-source.test.ts index af044bd5816..1be90217149 100644 --- a/packages/spec/src/ai/knowledge-source.test.ts +++ b/packages/spec/src/ai/knowledge-source.test.ts @@ -417,7 +417,7 @@ describe('KnowledgeSourceSchema — `source.affinity`, the order for the caller }); }); -describe('KnowledgeSourceSchema — `source.retrieval`, how a source is searched (ADR-0161, the dated note on retrieval modes)', () => { +describe('KnowledgeSourceSchema — `source.retrieval`, how a source is searched (ADR-0161, the dated note of 2026-11-30 under K8)', () => { const withRetrieval = (retrieval: unknown): unknown => ({ ...SOURCE, source: { ...SOURCE.source, retrieval } }); it('positive control: each of the three modes parses and is kept as written; absent stays absent', () => { diff --git a/packages/spec/src/ai/knowledge-source.zod.ts b/packages/spec/src/ai/knowledge-source.zod.ts index 64e6ef189c6..a07a538429c 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -130,7 +130,7 @@ export const KnowledgeSplitSchema = lazySchema(() => strictObject( /** * The retrieval modes a knowledge source may declare (ADR-0161, the dated note - * on retrieval modes; ruling 7270218011 on #38692): + * of 2026-11-30 under K8; ruling 7270218011 on #38692): * * - `vector`: only the vector leg runs, ranking passages by meaning. * - `keyword`: only the keyword leg runs, ranking passages by the words they @@ -156,7 +156,7 @@ export const KnowledgeRetrievalModeSchema = lazySchema(() => z.enum(KNOWLEDGE_RE })); /** - * How a source is searched (ADR-0161, the dated note on retrieval modes): + * How a source is searched (ADR-0161, the dated note of 2026-11-30 under K8): * which legs the store runs. A declaration of the source, read on every search * and never by a build, so it enters neither the index fingerprint nor the * recipe hash: changing it rebuilds nothing. `retrieval: {}` declares nothing @@ -504,7 +504,7 @@ export const ObjectKnowledgeSourceSchema = lazySchema(() => strictObject( affinity: z.array(KnowledgeAffinityEntrySchema).optional() .describe('How this source\'s hits are ordered for the caller: boost (by places) or nearest (own business unit first), by position, never by score'), /** - * [ADR-0161, the dated note on retrieval modes] How this source is + * [ADR-0161, the dated note of 2026-11-30 under K8] How this source is * searched: `retrieval.mode` names the legs the store runs * ({@link KnowledgeRetrievalSchema}). Beside {@link affinity} and before * it: the mode decides which passages the store ranks and their scores, diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index 0790d351e29..b1e074cb4d7 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -177,8 +177,8 @@ export interface AdapterSearchOptions { */ index?: { fingerprint: string }; /** - * The retrieval mode this search runs (ADR-0161, the dated note on - * retrieval modes): the EFFECTIVE mode, which the knowledge service resolves + * The retrieval mode this search runs (ADR-0161, the dated note of + * 2026-11-30 under K8): the EFFECTIVE mode, which the knowledge service resolves * from the source's `source.retrieval.mode`, else the adapter's * {@link AdapterCapabilities.retrieval} `default`. A per-request parameter, * as `topK` and `scope` are — not configuration (ADR-0161 K8, rule 4). @@ -271,7 +271,7 @@ export interface AdapterCapabilities { chunks?: boolean; /** * The retrieval modes the adapter runs, and which one it runs when a - * source declares none (ADR-0161, the dated note on retrieval modes). A + * source declares none (ADR-0161, the dated note of 2026-11-30 under K8). A * report, not configuration: `default` is one of `modes`, and an adapter * that lists `hybrid` honours the source's vector share when that arrives. * From a76dc2eb6c79427ed4e60684f2900faa94bd095a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 10:14:50 +0000 Subject: [PATCH 16/19] chore(changeset): the platform-objects translations of the retrieval-mode form ship as a patch Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- .changeset/38692-knowledge-retrieval-mode-spec.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.changeset/38692-knowledge-retrieval-mode-spec.md b/.changeset/38692-knowledge-retrieval-mode-spec.md index c48981f369f..754d85822e2 100644 --- a/.changeset/38692-knowledge-retrieval-mode-spec.md +++ b/.changeset/38692-knowledge-retrieval-mode-spec.md @@ -1,6 +1,7 @@ --- '@objectstack/spec': minor '@objectstack/service-knowledge': minor +'@objectstack/platform-objects': patch --- feat(spec): a knowledge source may declare its retrieval mode, `source.retrieval.mode` (`vector`, `keyword` or `hybrid`), and a knowledge adapter reports the modes it runs @@ -14,4 +15,6 @@ A `knowledge_source` may now declare how it is searched: `source: { …, retriev The adapter contract suite (`@objectstack/service-knowledge/testing`) takes a new optional declaration, `implements.retrieval`: it checks the adapter's report (each mode one of the three, none twice, the default listed), searches a fixed set of passages under each listed mode (`vector` leaves out the passage only the keyword leg ranks, `keyword` answers that passage alone and nothing for a query with no word any passage holds), and checks that the default mode handed explicitly answers exactly what a search without the member answers. An adapter that does not declare it is checked to report no modes. +The Studio metadata-form translations (`@objectstack/platform-objects`) name the "Search" group and the "Retrieval mode" select and its three choices in every locale. + The knowledge service's reading of the mode (and its refusal of a mode the source's store does not run) and the turso and pgvector stores' support for it ship as separate changes. From 75d7437697965789272958e77ee83334a65a8459 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 11:03:57 +0000 Subject: [PATCH 17/19] fix(spec): the retrieval key warns until the service reads it; the contract leaves the per-search code to the service The planned liveness row of source.retrieval warns an author (authorWarn and authorHint) until the knowledge service reads it. The texts that state the refusals name the knowledge service as the refuser; the contract's jsdoc no longer names the per-search refusal code. The shared suite's vector case no longer needs a keyword leg, so a vector-only store attests. The ADR K2 row says the member carries the effective mode, and the protocol doc's section 3.1 names the key. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- content/docs/protocol/knowledge.mdx | 8 ++++++++ ...rd-return-knowledge-source-is-a-governed-type.md | 2 +- .../translations/en.metadata-forms.generated.ts | 2 +- packages/services/service-knowledge/src/testing.ts | 5 +++-- packages/spec/liveness/knowledge_source.json | 4 +++- .../spec/src/ai/knowledge-source.metadata-form.ts | 2 +- packages/spec/src/ai/knowledge-source.zod.ts | 13 +++++++------ packages/spec/src/contracts/knowledge-adapter.ts | 6 ++---- 8 files changed, 26 insertions(+), 16 deletions(-) diff --git a/content/docs/protocol/knowledge.mdx b/content/docs/protocol/knowledge.mdx index 685004cae35..0a84154c23f 100644 --- a/content/docs/protocol/knowledge.mdx +++ b/content/docs/protocol/knowledge.mdx @@ -181,6 +181,14 @@ that name (ADR-0161 K4): `VALIDATION_ERROR` (400), naming them. The adapter is placed where it is used, so a source registered before its store started finds it. +**How a source is searched: `source.retrieval.mode`** (ADR-0161, the dated +note of 2026-11-30 under K8). `'vector'` ranks by meaning alone, `'keyword'` +by the question's words alone (the embedder is never called), `'hybrid'` runs +both and merges them; omitted (or `retrieval: {}`), the adapter's default +(`capabilities.retrieval.default`, `'hybrid'` on `turso` and `pgvector`). The +mode is read by search alone: it enters neither the index fingerprint nor the +recipe hash, so changing it rebuilds nothing. + **What mounts the service.** A stack that ships a `knowledge_source` — any item in its `knowledgeSources`, at the top level or in a package — is served the knowledge service and the deployment's store, exactly as diff --git a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md index 91e0d334663..c2348262641 100644 --- a/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md +++ b/docs/adr/0161-knowledge-platform-boundary-platform-owns-assembly-sync-split-record-return-knowledge-source-is-a-governed-type.md @@ -150,7 +150,7 @@ Each text below states the old position. The left column quotes it as it reads a | Same file, §1: "We have nothing distinctive to add to those layers." and "The protocol scopes the framework's responsibility to (1)–(4) and delegates the rest to plugins." | The framework's list grows by the four of K1; what is delegated is the adapter's four. | #37096 | | Same file, §3.1: a source "is stored as metadata (versioned, environment-scoped) just like a view or a flow", against the schema note on `packages/spec/src/ai/knowledge-source.zod.ts#KnowledgeSourceSchema`: "the shape of a **runtime registration**, ⛔ not a governed metadata type". | The two agree: a source is a `knowledge_source` item (K4). Until row 3 lands, the schema note is the true one. | row 3 | | Same file, §3.2: "The framework does **not** chunk; adapters do." | The framework splits; adapters index the passages. | #37098 (row 6) | -| Same file, §3.4, and the note on `packages/spec/src/contracts/knowledge-adapter.ts#IKnowledgeAdapter`: "The surface is **deliberately minimal**: no chunk strategy, no embedding configuration, no rerank toggles." | The contract grows by K8's list. It carries what an adapter reports about its embedder and the retrieval modes it runs (`capabilities.retrieval`), and the mode a search runs in (`AdapterSearchOptions.retrieval`), which a source declares; still no configuration and no rerank. | #37096, then each card that adds a member (#38692 phase 1a: the retrieval mode) | +| Same file, §3.4, and the note on `packages/spec/src/contracts/knowledge-adapter.ts#IKnowledgeAdapter`: "The surface is **deliberately minimal**: no chunk strategy, no embedding configuration, no rerank toggles." | The contract grows by K8's list. It carries what an adapter reports about its embedder and the retrieval modes it runs (`capabilities.retrieval`), and the mode a search runs in (`AdapterSearchOptions.retrieval`): the source's declaration, else the adapter's default; still no configuration and no rerank. | #37096, then each card that adds a member (#38692 phase 1a: the retrieval mode) | | Same file, §6: "that surface stays unbuilt until a real `object` source calls for it." | The enumeration surface is built (K8, item 1); reconcile covers application-level predicate writes. | #37096 and row 15 | | Same file, §7 and §8: `knowledge-pgvector` as "Phase 3", and "a `KnowledgeSource.embedding` field". | `knowledge-pgvector` is an open adapter of this repository (cloud ADR-0119 D5); `embedding` is removed (K6). | #37100, row 3 | | `packages/spec/src/ai/embedding.zod.ts`, file note: "NOT in scope (these belong to application code, not the platform): Chunking strategies (fixed/semantic/recursive/markdown)." and "These were removed in v1 because they describe one specific way to build a RAG application". | Structural splitting is a platform capability of the knowledge service. It does not return as the pipeline vocabulary that was removed. Retrieval pipelines, document loaders and end-to-end orchestration stay out of scope. | #37098 | diff --git a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts index f6607bfb55f..a888b4925f7 100644 --- a/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.metadata-forms.generated.ts @@ -3571,7 +3571,7 @@ export const enMetadataForms: NonNullable = { }, "source.retrieval.mode": { label: "Retrieval mode", - helpText: "Blank: the store's default (hybrid on turso and pgvector). Vector ranks passages by meaning; keyword by the words they hold, with no call to the embedding provider, which suits document or clause numbers; hybrid merges both. A mode the store does not run is refused at save.", + helpText: "Blank: the store's default (hybrid on turso and pgvector). Vector ranks passages by meaning; keyword by the words they hold, with no call to the embedding provider, which suits document or clause numbers; hybrid merges both. The knowledge service refuses a mode the store does not run when the source is saved.", options: { vector: "Vector only (by meaning)", keyword: "Keyword only (by words)", diff --git a/packages/services/service-knowledge/src/testing.ts b/packages/services/service-knowledge/src/testing.ts index 78f526856b2..f4e41c3d050 100644 --- a/packages/services/service-knowledge/src/testing.ts +++ b/packages/services/service-knowledge/src/testing.ts @@ -161,7 +161,9 @@ export interface KnowledgeAdapterContractOptions { * the three modes, and each listed mode is asserted by behaviour: `vector` * leaves out the passage only the keyword leg ranks, `keyword` ranks by * the query's words alone, `hybrid` answers what the default answers when - * it is the default. A `vector` or `keyword` case needs `keywordLeg`. + * it is the default. The `keyword` case needs `keywordLeg`; the `vector` + * case holds for a store with no keyword leg too, so a vector-only store + * (`modes: ['vector']`) attests. * Absent: `false`. */ retrieval?: boolean; @@ -623,7 +625,6 @@ export function runKnowledgeAdapterContract(opts: KnowledgeAdapterContractOption it('`vector` runs the vector leg alone: the passage only the keyword leg ranks is not answered', async () => { const { adapter, a, listed } = await seeded(); if (!listed.includes('vector')) return; - expect(opts.implements.keywordLeg, 'the vector case reads the keyword-leg fixture').toBe(true); const hits = await adapter.search(QUESTION, { source: a, topK: 3, retrieval: { mode: 'vector' } }); expect(hits.map((h) => h.documentId)).not.toContain(`${a.name}:clause`); nonIncreasing(hits); diff --git a/packages/spec/liveness/knowledge_source.json b/packages/spec/liveness/knowledge_source.json index 672e1a0b0e8..f50d75d32b5 100644 --- a/packages/spec/liveness/knowledge_source.json +++ b/packages/spec/liveness/knowledge_source.json @@ -124,7 +124,9 @@ "retrieval": { "status": "planned", "verifiedAt": "2026-11-30", - "note": "PLANNED RECORD (ruling 7270218011 on #38692, phase 1a; ADR-0161, the dated note of 2026-11-30 under K8): `retrieval: { mode }`, how a source is searched. CARRIED today: it parses at every door (strict, `retrieval: {}` allowed) and is kept by the parse. ACTED ON by nothing yet: the knowledge service resolves the effective mode (the source's declaration, else the adapter's `capabilities.retrieval.default`), refuses a mode the adapter does not list at the four points the ruling names, and hands it to the adapter as `AdapterSearchOptions.retrieval`; knowledge-turso and knowledge-pgvector run one leg or both. Those are the phase-1a PRs that follow this one. Flip to `live` on the commit that lands the service's reader, citing it. Enters neither the index fingerprint nor the recipe hash.", + "authorWarn": true, + "authorHint": "Keep it, but nothing reads it yet: until the knowledge service reads it, a source is searched in its store's default mode whatever it declares, and a mode the store does not run is not refused.", + "note": "PLANNED RECORD (ruling 7270218011 on #38692, phase 1a; ADR-0161, the dated note of 2026-11-30 under K8): `retrieval: { mode }`, how a source is searched. CARRIED today: it parses at every door (strict, `retrieval: {}` allowed) and is kept by the parse. ACTED ON by nothing yet: the knowledge service resolves the effective mode (the source's declaration, else the adapter's `capabilities.retrieval.default`), refuses a mode the adapter does not list at the four points the ruling names, and hands it to the adapter as `AdapterSearchOptions.retrieval`; knowledge-turso and knowledge-pgvector run one leg or both. Those are the phase-1a PRs that follow this one. Flip to `live` on the commit that lands the service's reader, citing it, and drop `authorWarn` / `authorHint` in that same edit (a warned `live` row reds this gate). Enters neither the index fingerprint nor the recipe hash.", "children": { "mode": { "status": "planned", diff --git a/packages/spec/src/ai/knowledge-source.metadata-form.ts b/packages/spec/src/ai/knowledge-source.metadata-form.ts index 1215e5f31b2..75a86d7d7df 100644 --- a/packages/spec/src/ai/knowledge-source.metadata-form.ts +++ b/packages/spec/src/ai/knowledge-source.metadata-form.ts @@ -93,7 +93,7 @@ export const knowledgeSourceForm = defineMetadataForm({ { label: 'Keyword only (by words)', value: 'keyword' }, { label: 'Hybrid (both)', value: 'hybrid' }, ], - helpText: 'Blank: the store\'s default (hybrid on turso and pgvector). Vector ranks passages by meaning; keyword by the words they hold, with no call to the embedding provider, which suits document or clause numbers; hybrid merges both. A mode the store does not run is refused at save.', + helpText: 'Blank: the store\'s default (hybrid on turso and pgvector). Vector ranks passages by meaning; keyword by the words they hold, with no call to the embedding provider, which suits document or clause numbers; hybrid merges both. The knowledge service refuses a mode the store does not run when the source is saved.', }, ], }, diff --git a/packages/spec/src/ai/knowledge-source.zod.ts b/packages/spec/src/ai/knowledge-source.zod.ts index a07a538429c..8f61e67cdb2 100644 --- a/packages/spec/src/ai/knowledge-source.zod.ts +++ b/packages/spec/src/ai/knowledge-source.zod.ts @@ -141,8 +141,8 @@ export const KnowledgeSplitSchema = lazySchema(() => strictObject( * - `hybrid`: both legs run, merged by the store's fusion. * * Which modes a store runs is the store's report (`AdapterCapabilities.retrieval`), - * never configuration; a source that declares a mode its store does not run is - * refused, never silently searched another way. + * never configuration. A source that declares a mode its store does not run is + * refused by the knowledge service, never silently searched another way. */ export const KNOWLEDGE_RETRIEVAL_MODES = ['vector', 'keyword', 'hybrid'] as const; @@ -172,10 +172,11 @@ export const KnowledgeRetrievalSchema = lazySchema(() => strictObject( * Which legs run: `vector`, `keyword` or `hybrid` * ({@link KNOWLEDGE_RETRIEVAL_MODES}). Omitted: the store's default * (`AdapterCapabilities.retrieval.default`; `hybrid` on turso and - * pgvector), today's behaviour. A store that does not list the mode - * refuses the source at save, at registration when its store already - * resolves, once after boot, and on every search (the source is listed as - * refused); a store that reports no modes accepts only the key left out. + * pgvector), today's behaviour. The knowledge service refuses a source + * whose store does not list the mode: at save, at registration when its + * store already resolves, once after boot, and on every search (the source + * is listed as refused). A store that reports no modes takes only a source + * that leaves the key out. */ mode: KnowledgeRetrievalModeSchema.optional() .describe('Which legs a search runs: vector, keyword or hybrid; omitted means the store\'s default'), diff --git a/packages/spec/src/contracts/knowledge-adapter.ts b/packages/spec/src/contracts/knowledge-adapter.ts index b1e074cb4d7..b62c7af7d17 100644 --- a/packages/spec/src/contracts/knowledge-adapter.ts +++ b/packages/spec/src/contracts/knowledge-adapter.ts @@ -193,10 +193,8 @@ export interface AdapterSearchOptions { * `capabilities.retrieval.modes`, and never hands this member to an adapter * that reports no `capabilities.retrieval`. Absent: the adapter's default. * A source declaring a mode its adapter does not list is never searched - * another way: the knowledge service lists it in a search's `refused` with - * `SERVICE_UNAVAILABLE` (503, the ADR-0112 standard code a source whose - * adapter is not mounted is refused with there), and refuses it at its save - * and registration with `VALIDATION_ERROR` (400). + * another way: the knowledge service refuses it, at its save and its + * registration, and lists it in a search's `refused` with its code. * Scores need only not increase with rank within one source's answer; under * a one-leg mode they reflect rank alone. */ From a99c90a367af707b6704d66d3a3a97c29daefe40 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 12:16:29 +0000 Subject: [PATCH 18/19] Cite the retrieval-mode note by its date in the turso test Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- .../knowledge-turso/src/__tests__/retrieval-modes.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts b/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts index 718ce4ecda0..47577591b14 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts @@ -1,7 +1,7 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * The retrieval modes (ADR-0161, the dated note on retrieval modes) on + * The retrieval modes (ADR-0161, the dated note of 2026-11-30 under K8) on * libSQL: the capability report, the legs each mode writes into the ranking * statement, that `keyword` never calls the embedder nor reads the * approximate index, and the fusion's scores — `hybrid` bit-identical to the From 2496e519e7ae7bc0c7d143635c402ffea5fbeb76 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 14:04:23 +0000 Subject: [PATCH 19/19] Refuse a retrieval mode the store does not list; declare the widening MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A mode outside the store's list ran both legs on the one-leg scale; it is now refused (400 VALIDATION_ERROR) before anything is embedded or read. The exported adapter's capabilities grow a member, so the changeset says Clause-② yes (widening). The README's keyword-index sentence says a vector search does not build a missing index. Claude-Session: https://claude.ai/code/session_01JQwxbaASqBozmmj1n5tbUf Co-authored-by: Claude --- .../38692-knowledge-turso-retrieval-modes.md | 4 ++-- packages/plugins/knowledge-turso/README.md | 2 +- .../src/__tests__/retrieval-modes.test.ts | 13 +++++++++++++ .../plugins/knowledge-turso/src/turso-adapter.ts | 16 +++++++++++++--- 4 files changed, 29 insertions(+), 6 deletions(-) diff --git a/.changeset/38692-knowledge-turso-retrieval-modes.md b/.changeset/38692-knowledge-turso-retrieval-modes.md index f57daa1da42..65e0c8f627e 100644 --- a/.changeset/38692-knowledge-turso-retrieval-modes.md +++ b/.changeset/38692-knowledge-turso-retrieval-modes.md @@ -4,7 +4,7 @@ feat(knowledge-turso): the store runs the vector leg alone, the keyword leg alone, or both, as a source's retrieval mode says -Clause-②: no +Clause-②: yes (widening) Metadata-protocol: none -`knowledge-turso` now reports the retrieval modes it runs (`capabilities.retrieval`: `vector`, `keyword` and `hybrid`, with `hybrid` by default) and honours the mode the knowledge service hands it on each search (`AdapterSearchOptions.retrieval`). `hybrid`, and a search that carries no mode, run exactly as before: both legs, merged by reciprocal rank fusion, with every score unchanged to the last bit. `vector` runs the vector leg alone (the exact scan, or the approximate index as before) and `keyword` the keyword match alone; the other leg is not written into any statement, and a hit's score is `61 / (60 + rank)`, so the first is 1. `keyword` does not embed the question or read the approximate index, ranks passages of equal keyword score by chunk id, and answers nothing for a question with no term to match. The keyword index is kept whatever the mode, so changing a source's mode rebuilds nothing. +`knowledge-turso` now reports the retrieval modes it runs (`capabilities.retrieval`: `vector`, `keyword` and `hybrid`, with `hybrid` by default) and honours the mode the knowledge service hands it on each search (`AdapterSearchOptions.retrieval`). `hybrid`, and a search that carries no mode, run exactly as before: both legs, merged by reciprocal rank fusion, with every score unchanged to the last bit. `vector` runs the vector leg alone (the exact scan, or the approximate index as before) and `keyword` the keyword match alone; the other leg is not written into any statement, and a hit's score is `61 / (60 + rank)`, so the first is 1. `keyword` does not embed the question or read the approximate index, ranks passages of equal keyword score by chunk id, and answers nothing for a question with no term to match. A mode it does not list is refused (`400 VALIDATION_ERROR`), never run. The keyword index is kept whatever the mode, so changing a source's mode rebuilds nothing. diff --git a/packages/plugins/knowledge-turso/README.md b/packages/plugins/knowledge-turso/README.md index dacae08c6e6..b4ad4260c1b 100644 --- a/packages/plugins/knowledge-turso/README.md +++ b/packages/plugins/knowledge-turso/README.md @@ -54,7 +54,7 @@ Two legs, merged by reciprocal rank fusion (RRF, `k` = 60) before the knowledge **Retrieval modes.** The store reports all three modes (`capabilities.retrieval`: `vector`, `keyword`, `hybrid`), `hybrid` by default, and a source chooses with `source.retrieval.mode`. `hybrid` runs both legs as above. `vector` runs the vector leg alone and `keyword` the keyword leg alone: the other leg is not written into any statement, and a hit's `score` is `61 / (60 + rank)`, 1 for the first. `keyword` does not embed the question or read the approximate index, ranks passages of equal keyword score by chunk id, and answers nothing for a question with no term to match. The keyword index is kept whatever the mode, so changing the mode rebuilds nothing. - **Keyword leg.** The query is split into terms at white space and punctuation; a hyphen, dot, slash, underscore, `#`, `@` or `+` inside a term keeps it whole, so `X-200` and `v1.2` are one term each (at most 16 terms). A run of Han, kana or Hangul inside a term is cut into overlapping pieces of three characters and of two (a run of two is one piece, a run of one is dropped), so a question written without spaces is still matched word by word; a figure or a code next to a run (`2000`, `X-200`) stays one term. Under the cap the figures, codes and words come first, then the pieces of three characters, then those of two. A term of three characters or more is matched as one quoted FTS5 phrase in the passage table's trigram index — so `X-200` is text, never FTS5 syntax, and 「住宿标准」 matches inside 「员工出差住宿标准」. A shorter term, which a trigram index cannot match (「出差」), is matched by `content LIKE '%…%'` over the rows in scope. A passage's keyword score sums, over the terms it holds, the term's BM25 inverse document frequency among the rows in scope, so a word most passages hold weighs little. There is no dictionary segmentation: the pieces find a code, a name or a phrase as written, and the vector leg answers the question's meaning. -- **Keyword index.** Each passage table `knowledge__g` has one beside it: a map table `…-kw`, a contentless FTS5 table `…-fts` (`tokenize='trigram'`) and three triggers that keep both in step with every insert, rewrite and removal of a passage, inside the statement that writes it. It is made with the table and dropped with it. A table made by a release without one gets it at its first search, built from the rows it holds in one transaction; until then nothing else changes. Its names hold a hyphen, which no source, generation or object name can, and an object under one of them that the store did not make is never dropped or used: the generation is refused `SERVICE_UNAVAILABLE`, naming it. +- **Keyword index.** Each passage table `knowledge__g` has one beside it: a map table `…-kw`, a contentless FTS5 table `…-fts` (`tokenize='trigram'`) and three triggers that keep both in step with every insert, rewrite and removal of a passage, inside the statement that writes it. It is made with the table and dropped with it. A table made by a release without one gets it at its first search that has keyword terms (never under `vector`), built from the rows it holds in one transaction; until then nothing else changes. Its names hold a hyphen, which no source, generation or object name can, and an object under one of them that the store did not make is never dropped or used: the generation is refused `SERVICE_UNAVAILABLE`, naming it. - **Vector leg.** Passages ranked by the cosine distance of their stored vector (`vector_distance_cos`); a passage whose cosine similarity is not positive is not ranked by it. Its ranks 1…`topK` feed the fusion, whichever of the two ways below found the passages. The organization filter, the record scope (a passage's record, or a metadata value equal to an id as text, a list matching by any element) and the metadata `filter` (JSON equality per key) are one `WHERE`, run in both legs. A search with a record scope or a metadata `filter` reads that `WHERE` once per statement, into a set of the passages in scope, and both legs and the keyword leg's counts read the passages in scope from that set by their key: a metadata term reads each passage's JSON, a pass over the table, which would otherwise be paid once by each leg and once more by the keyword counts. Measured on 59,621 one-passage records of 1,024 dimensions (one organization, `topK` 40, a Chinese question of 16 terms): a search scoped to 3 policies' clauses (90 passages) took about 1.0 s a statement before and 80 ms after, one scoped to a unit holding 10% of them 1.0 to 1.4 s before and 250 to 450 ms after. The keyword leg's candidates are read once a statement, not once for its counts and once for its ranks. And the keyword leg is computed once a search: when the approximate pass falls short and a wider pass or the exact scan follows, that statement binds the keyword ranks the first one answered. diff --git a/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts b/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts index 47577591b14..ceddeea0b42 100644 --- a/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts +++ b/packages/plugins/knowledge-turso/src/__tests__/retrieval-modes.test.ts @@ -125,6 +125,19 @@ describe('knowledge-turso retrieval modes', () => { expect(rankings(sql, at)).toHaveLength(0); }); + it('a mode it does not list is refused before anything is read or embedded', async () => { + const { s, adapter, embedder, sql } = await seeded(); + const from = sql.length; + const calls = embedder.calls; + const refused = await adapter + .search('granite w3x', { source: s, topK: 5, retrieval: { mode: 'rerank' as never }, index: FP }) + .catch((e: unknown) => e); + expect(refused).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 }); + expect(String((refused as Error).message)).toContain("does not run the retrieval mode 'rerank'"); + expect(embedder.calls).toBe(calls); + expect(rankings(sql, from)).toEqual([]); + }); + it('keyword never reads the approximate index of a generation that has one', async () => { const { s, adapter, sql } = await seeded({ vectorIndexThreshold: 40 }); const from = sql.length; diff --git a/packages/plugins/knowledge-turso/src/turso-adapter.ts b/packages/plugins/knowledge-turso/src/turso-adapter.ts index 3330f900f3a..248f40bf932 100644 --- a/packages/plugins/knowledge-turso/src/turso-adapter.ts +++ b/packages/plugins/knowledge-turso/src/turso-adapter.ts @@ -199,7 +199,7 @@ export const RRF_K = 60; /** * The retrieval modes this adapter runs, and its default (ADR-0161, the dated - * note on retrieval modes): all three, `hybrid` when a source declares none. + * note of 2026-11-30 under K8): all three, `hybrid` when a source declares none. * A report, not configuration; the default does not move with whether a * generation has an approximate index. */ @@ -721,9 +721,19 @@ export class TursoKnowledgeAdapter implements IKnowledgeAdapter { const topK = Math.max(0, Math.floor(opts.topK)); if (topK === 0) return []; - // The legs the search's mode runs (ADR-0161, the dated note on retrieval - // modes); the service hands only a mode this adapter lists. + // The legs the search's mode runs (ADR-0161, the dated note of 2026-11-30 + // under K8); the service hands only a mode this adapter lists, and any + // other is refused, never run on a scale it was not built for. const mode = opts.retrieval?.mode ?? RETRIEVAL.default; + if (!(RETRIEVAL.modes as readonly string[]).includes(mode)) { + throw Object.assign( + new Error( + `knowledge-turso does not run the retrieval mode '${String(mode)}': it runs ` + + `${RETRIEVAL.modes.map((m) => `'${m}'`).join(', ')}.`, + ), + { code: 'VALIDATION_ERROR', status: 400 }, + ); + } // The query is embedded before the database is read — never under // `keyword`, which makes no query vector. let vector: number[] = [];