|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * How a scoped search reads its passage table, pinned by the query plan, not |
| 5 | + * by a clock: on a remote database each pass over the table costs its rows' |
| 6 | + * pages over the network, and the statement is bounded (`requestTimeoutMs`). |
| 7 | + * A record scope or a metadata filter is read once a statement, into the set |
| 8 | + * of the passages in scope, and every other read of the passage table is a |
| 9 | + * lookup by its key; the keyword leg's candidates are read once, not once for |
| 10 | + * its counts and once for its ranks. And a request past its bound answers |
| 11 | + * `TIMEOUT` (504), never "the store is not ready". |
| 12 | + */ |
| 13 | + |
| 14 | +import { afterAll, describe, expect, it } from 'vitest'; |
| 15 | +import type { Client, InArgs } from '@libsql/client'; |
| 16 | +import type { KnowledgeDocument, KnowledgeSource } from '@objectstack/spec/ai'; |
| 17 | +import type { AdapterContext, AdapterSearchOptions } from '@objectstack/spec/contracts'; |
| 18 | +import { TursoKnowledgeAdapter } from '../index.js'; |
| 19 | +import { FakeEmbedder, storeOf } from './turso.testkit.js'; |
| 20 | + |
| 21 | +const source = (name: string): KnowledgeSource => |
| 22 | + ({ name, label: name, adapter: 'under_test', source: { kind: 'object', object: 'clause', content: ['body'] } }) as KnowledgeSource; |
| 23 | + |
| 24 | +const FP = { fingerprint: 'fp-test:scope', recipeHash: 'rh-test:1' }; |
| 25 | +const ctx = (s: KnowledgeSource): AdapterContext => ({ source: s, reason: 'manual', index: FP }); |
| 26 | + |
| 27 | +/** Clause `i` of policy `i % 6`, in unit `i % 3`, in organization `org_a`; the text shares words across clauses. */ |
| 28 | +function clauses(s: KnowledgeSource, n: number): KnowledgeDocument[] { |
| 29 | + return Array.from({ length: n }, (_, i) => { |
| 30 | + const id = `${s.name}:${String(i).padStart(3, '0')}`; |
| 31 | + const content = `差旅 住宿标准 年假 ${i % 2 === 0 ? '出差 报销' : '涉密 岗位'} clause w${i % 9}x w${(i * 7) % 11}x`; |
| 32 | + return { |
| 33 | + id, |
| 34 | + sourceId: s.name, |
| 35 | + sourceRecordId: `r${i}`, |
| 36 | + organizationId: 'org_a', |
| 37 | + content, |
| 38 | + title: `Policy ${i % 6}`, |
| 39 | + metadata: { policy: `pol_${i % 6}`, units: ['root', `unit_${i % 3}`], status: i % 4 === 0 ? 'draft' : 'published' }, |
| 40 | + chunks: [{ id: `${id}#0`, documentId: id, index: 0, content }], |
| 41 | + }; |
| 42 | + }); |
| 43 | +} |
| 44 | + |
| 45 | +/** A client that records every statement it runs, beside the raw client the plans are read on. */ |
| 46 | +function recording(raw: Client) { |
| 47 | + const statements: Array<{ sql: string; args: InArgs }> = []; |
| 48 | + const client = new Proxy(raw, { |
| 49 | + get(t, key) { |
| 50 | + const value = Reflect.get(t, key, t) as unknown; |
| 51 | + if (typeof value !== 'function') return value; |
| 52 | + const fn = (value as (...a: unknown[]) => unknown).bind(t); |
| 53 | + if (key !== 'execute') return fn; |
| 54 | + return (st: string | { sql: string; args?: InArgs }) => { |
| 55 | + statements.push(typeof st === 'string' ? { sql: st, args: [] } : { sql: st.sql, args: st.args ?? [] }); |
| 56 | + return fn(st); |
| 57 | + }; |
| 58 | + }, |
| 59 | + }) as Client; |
| 60 | + return { client, statements }; |
| 61 | +} |
| 62 | + |
| 63 | +interface PlanRow { |
| 64 | + id: number; |
| 65 | + parent: number; |
| 66 | + detail: string; |
| 67 | +} |
| 68 | + |
| 69 | +/** |
| 70 | + * The reads of `table` (the passage table itself, never its `-kw`, `-fts`, |
| 71 | + * `-vec` or `-org` objects' own rows) a plan makes other than a lookup by its |
| 72 | + * key, each with the plan steps above it. |
| 73 | + */ |
| 74 | +function passesOver(plan: PlanRow[], table: string): Array<{ detail: string; under: string[] }> { |
| 75 | + const byId = new Map(plan.map((r) => [r.id, r])); |
| 76 | + const own = new RegExp(`^(SCAN|SEARCH) ${table}(?![-_\\w])`); |
| 77 | + const byKey = new RegExp(`USING (COVERING )?INDEX sqlite_autoindex_${table}_1 \\(chunk_id=\\?\\)$`); |
| 78 | + return plan |
| 79 | + .filter((r) => own.test(r.detail) && !byKey.test(r.detail)) |
| 80 | + .map((r) => { |
| 81 | + const under: string[] = []; |
| 82 | + for (let p = byId.get(r.parent); p; p = byId.get(p.parent)) under.push(p.detail); |
| 83 | + return { detail: r.detail, under }; |
| 84 | + }); |
| 85 | +} |
| 86 | + |
| 87 | +describe('knowledge-turso: a scoped search reads its passage table once a statement', () => { |
| 88 | + const store = storeOf('file'); |
| 89 | + afterAll(() => store.closeAll()); |
| 90 | + |
| 91 | + async function built(name: string, vectorIndexThreshold: number) { |
| 92 | + const raw = store.client(); |
| 93 | + const watched = recording(raw); |
| 94 | + const s = source(name); |
| 95 | + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: watched.client, embedder: new FakeEmbedder(), vectorIndexThreshold }); |
| 96 | + await adapter.beginBuild(ctx(s)); |
| 97 | + await adapter.upsert(clauses(s, 48), ctx(s)); |
| 98 | + await adapter.completeBuild(ctx(s)); |
| 99 | + return { raw, adapter, s, table: `knowledge_${name}_g1`, statements: watched.statements }; |
| 100 | + } |
| 101 | + |
| 102 | + /** The search statements (`WITH …`) one search ran, each with its plan. */ |
| 103 | + async function plansOf(at: Awaited<ReturnType<typeof built>>, opts: Partial<AdapterSearchOptions>, query = '我在集团干了几年 年假 住宿标准 w1x') { |
| 104 | + const from = at.statements.length; |
| 105 | + const hits = await at.adapter.search(query, { source: at.s, topK: 4, index: { fingerprint: FP.fingerprint }, ...opts }); |
| 106 | + const searches = at.statements.slice(from).filter((st) => /^\s*WITH\b/.test(st.sql)); |
| 107 | + expect(searches.length).toBeGreaterThan(0); |
| 108 | + const plans: PlanRow[][] = []; |
| 109 | + for (const st of searches) { |
| 110 | + const plan = await at.raw.execute({ sql: `EXPLAIN QUERY PLAN ${st.sql}`, args: st.args }); |
| 111 | + plans.push(plan.rows.map((r) => ({ id: Number(r.id), parent: Number(r.parent), detail: String(r.detail) }))); |
| 112 | + } |
| 113 | + return { hits, plans }; |
| 114 | + } |
| 115 | + |
| 116 | + const scopes: Array<[string, Partial<AdapterSearchOptions>]> = [ |
| 117 | + ['a metadata (parent) scope term', { organizationIds: ['org_a'], scope: [{ kind: 'metadata', field: 'units', ids: ['unit_1'] }] }], |
| 118 | + ['a record scope term', { scope: [{ kind: 'record', ids: ['r1', 'r4', 'r7'] }] }], |
| 119 | + ['a parent and a record term', { scope: [{ kind: 'metadata', field: 'policy', ids: ['pol_2'] }, { kind: 'record', ids: ['r5'] }] }], |
| 120 | + ['a metadata filter', { filter: { status: 'published' } }], |
| 121 | + ]; |
| 122 | + |
| 123 | + for (const index of [{ name: 'exact', threshold: Infinity }, { name: 'approximate', threshold: 1 }]) { |
| 124 | + for (const [what, opts] of scopes) { |
| 125 | + it(`${what}, ${index.name} vector leg: the scope is read once, into one set; every other read of the table is by key`, async () => { |
| 126 | + const at = await built(`plan_${index.name}_${scopes.findIndex(([w]) => w === what)}`, index.threshold); |
| 127 | + const { hits, plans } = await plansOf(at, opts); |
| 128 | + expect(hits.length).toBeGreaterThan(0); |
| 129 | + for (const plan of plans) { |
| 130 | + const passes = passesOver(plan, at.table); |
| 131 | + // One pass, the one that fills the scope set; the vector leg, the keyword candidates, the |
| 132 | + // keyword counts and the rows answered read the passages in scope by their key. |
| 133 | + expect(passes, JSON.stringify(passes)).toHaveLength(1); |
| 134 | + expect(passes[0].under).toContain('MATERIALIZE scope'); |
| 135 | + // The keyword candidates are read once, for the counts and the ranks both. |
| 136 | + expect(plan.filter((r) => r.detail === 'MATERIALIZE cand')).toHaveLength(1); |
| 137 | + } |
| 138 | + }); |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + it('the scope set holds what the scope held before: the same hits as the terms read row by row', async () => { |
| 143 | + const at = await built('plan_same', Infinity); |
| 144 | + const docs = clauses(at.s, 48); |
| 145 | + const ids = (hits: Array<{ documentId: string }>) => hits.map((h) => h.documentId).sort(); |
| 146 | + const inUnit1 = docs.filter((d) => (d.metadata!.units as string[]).includes('unit_1')).map((d) => d.id); |
| 147 | + const hits = await at.adapter.search('年假 clause', { source: at.s, topK: 48, scope: [{ kind: 'metadata', field: 'units', ids: ['unit_1'] }] }); |
| 148 | + expect(ids(hits)).toEqual([...inUnit1].sort()); |
| 149 | + const both = await at.adapter.search('年假 clause', { |
| 150 | + source: at.s, |
| 151 | + topK: 48, |
| 152 | + scope: [{ kind: 'metadata', field: 'policy', ids: ['pol_2'] }], |
| 153 | + filter: { status: 'published' }, |
| 154 | + }); |
| 155 | + expect(ids(both)).toEqual( |
| 156 | + docs.filter((d) => d.metadata!.policy === 'pol_2' && d.metadata!.status === 'published').map((d) => d.id).sort(), |
| 157 | + ); |
| 158 | + }); |
| 159 | + |
| 160 | + it('a search without a scope or a filter makes no scope set', async () => { |
| 161 | + const at = await built('plan_unscoped', Infinity); |
| 162 | + const { plans } = await plansOf(at, { organizationIds: ['org_a'] }); |
| 163 | + for (const plan of plans) expect(plan.some((r) => r.detail === 'MATERIALIZE scope')).toBe(false); |
| 164 | + }); |
| 165 | +}); |
| 166 | + |
| 167 | +describe('knowledge-turso: a request past its bound', () => { |
| 168 | + it('answers TIMEOUT (504), "did not answer in time", never "not ready", for a search statement', async () => { |
| 169 | + const store = storeOf('memory'); |
| 170 | + const real = store.client(); |
| 171 | + const s = source('timed'); |
| 172 | + await new TursoKnowledgeAdapter({ id: 'under_test', client: real, embedder: new FakeEmbedder() }).upsert(clauses(s, 4), ctx(s)); |
| 173 | + // The search statement hangs, as a slow statement on a remote database does. |
| 174 | + const hanging = new Proxy(real, { |
| 175 | + get(t, key) { |
| 176 | + const value = Reflect.get(t, key, t) as unknown; |
| 177 | + if (typeof value !== 'function') return value; |
| 178 | + const fn = (value as (...a: unknown[]) => unknown).bind(t); |
| 179 | + if (key !== 'execute') return fn; |
| 180 | + return (st: string | { sql: string }) => |
| 181 | + /^\s*WITH\b/.test(typeof st === 'string' ? st : st.sql) ? new Promise(() => undefined) : fn(st); |
| 182 | + }, |
| 183 | + }) as Client; |
| 184 | + const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: hanging, embedder: new FakeEmbedder(), requestTimeoutMs: 60 }); |
| 185 | + const err = await adapter.search('年假', { source: s, topK: 4, index: { fingerprint: FP.fingerprint } }).then( |
| 186 | + () => undefined, |
| 187 | + (e: unknown) => e as Error & Record<string, unknown>, |
| 188 | + ); |
| 189 | + expect(err).toMatchObject({ code: 'TIMEOUT', status: 504, remedy: expect.stringContaining('requestTimeoutMs') }); |
| 190 | + expect(err!.message).toBe('The knowledge store (libSQL) did not answer in time: a request to its database took longer than 60 ms.'); |
| 191 | + expect(err!.message).not.toMatch(/not ready/); |
| 192 | + store.closeAll(); |
| 193 | + }); |
| 194 | +}); |
0 commit comments