Skip to content

Commit 43eaf5e

Browse files
fix(knowledge-turso): a scoped search reads its passage table once a statement; a request past its bound answers TIMEOUT (#38693)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8Es8AjkqFCZ7RyXPBkdgAD3)_ Fixes #38675 ## What changes `packages/plugins/knowledge-turso` only. 1. **A scoped search reads its passage table once a statement.** When a search carries a record scope or a metadata `filter`, the statement now opens with `scope AS MATERIALIZED (SELECT chunk_id FROM <table> WHERE <the same WHERE>)`. The vector leg (exact and approximate), the keyword candidates and the keyword count of passages in scope read from that set by `chunk_id`, a primary-key lookup. Before, each of those three ran the `WHERE` row by row over the whole table, and a metadata scope term parses each row's JSON (`json_each(metadata)`). A search with only the organization filter is unchanged (no scope set). 2. **The keyword candidates are read once.** `cand` becomes `cand AS MATERIALIZED`. Both `stats` and `kw` read it, and SQLite inlined it into each, so every term was matched twice per statement. The fix applies to scoped and unscoped searches. 3. **A request past `requestTimeoutMs` answers `TIMEOUT` (504).** The message is "The knowledge store (libSQL) did not answer in time: a request to its database took longer than N ms." Before, the refusal was `SERVICE_UNAVAILABLE` (503) with "The knowledge store (libSQL) is not ready: its database did not answer in time." That told the model and the employee the store was down when one statement was slow. `remedy` (operator text) still names `requestTimeoutMs` and keeps the commit warning. `TIMEOUT`/504 is the ADR-0112 code for an operation that timed out. Nothing in `service-knowledge` branches on the old code; it passes any coded refusal through (`codedRefusalOf`). Docs: the README `requestTimeoutMs` row and the Search section, the `requestTimeoutMs` option doc in `plugin.ts`, and the adapter's class comment. ## Why The premise, read on `main` at 5ac1ee0 and measured. - **Why a scoped statement is slower than an unscoped one.** In the plan of a scoped statement, the passage table is read in full three times: by the vector leg, by the keyword candidates (twice, since `cand` is inlined into `stats` and `kw`) and by the count in `stats`. Each read evaluates the metadata scope term per row. An unscoped statement reads it twice: the count in `stats` is a covering-index count, and `cand` is still inlined twice. A narrow scope also fails the approximate leg's pool floor, so a scoped search runs two or three such statements (approximate, maybe wide, then exact). An unscoped search runs one. - **Reproduced locally** (no remote Turso here). A `file:` libSQL store was built through the adapter: 59,621 one-passage records, 1,024 dimensions, clustered vectors, one organization, Chinese clause text, metadata `{business_unit: [root, division, leaf], policy, clause_hash}`, approximate index built (`completeBuild`, threshold 20,000). The search was `topK` 40 (the service's first round) with the card's question 「我在集团干了12年了,一年有几天年假?」 (16 terms). Times are per statement, before → after: | Search | Before | After | |---|---|---| | No scope (organization filter) | 1 statement, 1.14–1.32 s | 1 statement, 0.63–0.69 s | | 3 policies (90 passages) | 0.88–0.91 s + 1.03–1.05 s | 0.13 s + 0.08 s | | One leaf unit (~1.7%) | 0.97–0.99 s + 1.13–1.22 s | 0.19 s + 0.15 s | | One division (~10%) | 0.99–1.18 s + 1.18–1.23 s | 0.25 s + 0.31 s | | Group root (100%) | 1 statement, 1.26–1.28 s | 1 statement, 0.85–0.97 s | The card's hosted timings (25.6 s for an unscoped search, a scoped statement over 10 s) are about 8 to 10 times these local ones. On that ratio, a scoped statement now lands well under the bound. That is an inference from the ratio, not a remote measurement: the remote store was not reachable from here. - **Responsibility.** The cause is in this plugin's search SQL (`turso-adapter.ts`), not in `service-knowledge`. The approximate index (the card's second suspicion) is not the cause in the reproduction: the slow statements are slow with the index built and used. Whether the hosted table has its index was not readable from here. Out of scope, left to the cards the seat named: the keyword leg recomputed across the approximate → wide → exact statements, the approximate pass under a narrow scope, and the query embedded twice per refill (#38676); the keyword leg's ranking quality (#38671). ## Verification - `src/__tests__/scope-plan.test.ts` (new) pins the plan, not a clock. For a metadata scope term, a record scope term, both terms together, and a metadata filter, each on the exact and the approximate vector leg, every search statement's `EXPLAIN QUERY PLAN` reads the passage table once outside a chunk-id lookup, under `MATERIALIZE scope`, and holds one `MATERIALIZE cand`. A search with no scope makes no scope set. Scoped hits equal the terms' row-by-row meaning. A stalled search statement answers `TIMEOUT`/504 with the new sentence and no "not ready". With the adapter change stashed, 9 of the 11 cases fail: the 8 plan pins and the timeout pin. The 2 behaviour-equivalence cases pass on both. - `acceptance.test.ts`: the stalled-write case now expects `TIMEOUT`/504. - `pnpm --filter @objectstack/knowledge-turso test`: 5 files, 301 tests pass. `pnpm typecheck` passes for the package. eslint on the changed files is clean. - Local gates from `dispatch-gates.mjs` that pass: `check:issue-citations`, `check:doc-authoring`, `check:keyed-text-bounds`, `check:closed-ceremony-text`, `check:objectql-double-limit`, `check:where-matcher`, `check:duration-unit-keys`, `check:changeset-fixed` and `check:empty-changeset`. Clause-②: no Metadata-protocol: none ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (not touched) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran. eslint is clean on the changed files; the repo-wide `pnpm lint` was not run locally. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: not touched. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [ ] The *Before Submitting* list in CONTRIBUTING.md is done. The full repo-wide suite was not run; CI runs it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01JQwxbaAVoqUQiPmxMVpLst --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c02f972 commit 43eaf5e

6 files changed

Lines changed: 261 additions & 29 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/knowledge-turso': patch
3+
---
4+
5+
fix(knowledge-turso): a scoped search reads its passage table once a statement, and a request past its bound answers TIMEOUT, not "not ready"
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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.
11+
12+
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.
13+
14+
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`.

‎packages/plugins/knowledge-turso/README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ A source is usually a `knowledge_source` metadata item (a `*.knowledge-source.ts
2626
| `authToken` | — | The token of a `libsql://` URL. |
2727
| `client` | — | A libSQL client to use as it is (not configured, not closed by the plugin). |
2828
| `busyTimeoutMs` | `5000` | How long a write waits for another process's lock on a `file:` store. |
29-
| `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. |
29+
| `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. |
3030
| `projectRoot` | `process.cwd()` | The directory the default file is under. |
3131
| `queryPrefix` | `''` | Text put before every query before it is embedded. Passages are embedded as they are. |
3232
| `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
5555
- **Keyword index.** Each passage table `knowledge_<source>_g<n>` 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.
5656
- **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.
5757

58-
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.
58+
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.
5959

6060
- **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.
6161
- **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".

‎packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -737,7 +737,7 @@ describe('knowledge-turso with a request bound (a remote database)', () => {
737737
store.closeAll();
738738
});
739739

740-
it('a request that stalls inside a write answers SERVICE_UNAVAILABLE naming requestTimeoutMs, and nothing of the write lands', async () => {
740+
it('a request that stalls inside a write answers TIMEOUT naming requestTimeoutMs, and nothing of the write lands', async () => {
741741
const store = storeOf('file');
742742
const real = store.client();
743743
const s = source('stall');
@@ -763,7 +763,7 @@ describe('knowledge-turso with a request bound (a remote database)', () => {
763763
}) as Client;
764764
const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: hanging, embedder: new FakeEmbedder(), requestTimeoutMs: 80 });
765765
const err = await refusal(adapter.upsert([doc(s, 'a', 'otter pup'), doc(s, 'b', 'otter den')], ctx(s)));
766-
expect(err).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503, remedy: expect.stringContaining('requestTimeoutMs') });
766+
expect(err).toMatchObject({ code: 'TIMEOUT', status: 504, remedy: expect.stringContaining('requestTimeoutMs') });
767767
await new Promise((r) => setTimeout(r, 100));
768768
expect((await plain.listDocuments(ctx(s), { limit: 10 })).documents.map((d) => d.documentId)).toEqual([`${s.name}:seed`]);
769769
// The next write goes through.
Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
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+
});

‎packages/plugins/knowledge-turso/src/plugin.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ export interface KnowledgeTursoPluginOptions {
5050
/**
5151
* The longest one request to the database (a statement, a document's batch,
5252
* a commit) may take before the call answers
53-
* `SERVICE_UNAVAILABLE`, for a remote database (`libsql://`, `https://`,
53+
* `TIMEOUT` (504), for a remote database (`libsql://`, `https://`,
5454
* `wss://`), whose requests have no bound of their own. Applies to a
5555
* `client` given as it is only when set.
5656
* @default 10000 for a remote URL; none for a file or `:memory:`

0 commit comments

Comments
 (0)