Skip to content

Commit 796b204

Browse files
committed
fix(knowledge-turso): review round 2 — the request bound per request, never per page; a write stopped is rolled back
- requestTimeoutMs bounds each request on its own (a statement, a batch, opening a transaction, a commit or rollback) through a bounded view of the client, no longer a whole queue turn; the queue stays keyed by the client as given. A write sends each document's statements as one batch, so a page of 100 documents is ~100 requests. A request that times out inside a write is followed by a rollback, never a commit; only a commit that times out may still land, and its remedy says so. The remedy names requestTimeoutMs. Pinned with a slow client (40 documents, 2 passages each) and a write whose second batch hangs (nothing of it lands). - search's retry count is a private method's, not a third public parameter. - A table the store did not make under a generation name answers SERVICE_UNAVAILABLE with the table in the remedy. - The platform-file refusal compares the file a link resolves to, and reads SQLite's -wal, -shm and -journal side files as their database. - Pinned: the vector-type half of the legacy shape, the VALIDATION_ERROR code (and a long source id accepted), the search retry bound, the remote default bound (requestBoundFor). Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JQwxbaMuehXzctoWq7iRsV
1 parent f073750 commit 796b204

7 files changed

Lines changed: 280 additions & 44 deletions

File tree

‎.changeset/37107-knowledge-turso.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ Metadata-protocol: none
1111

1212
ADR-0161 Execution row 7; cloud ADR-0119 D5 (#37107).
1313

14-
- **`@objectstack/knowledge-turso` now ships from this repository**, Apache-2.0 (its `LICENSE` file is the Apache-2.0 text). `KnowledgeTursoPlugin` registers a `TursoKnowledgeAdapter` (adapter id `turso`) that keeps passages and vectors in a libSQL database of its own with libSQL's native vectors: the `url` option (`file:`, `:memory:`, `libsql://`), else `knowledge.db` under the project's `.objectstack/data/` (`defaultStoreUrl`). A URL naming the platform's own database file (`objectstack.db`, `dev.db`, `standalone.db`, or the file `OS_DATABASE_URL` names) is refused: two engines writing one SQLite file lose rows. On a file the store sets WAL and a busy timeout (`busyTimeoutMs`, default 5000), and in one process every call of the store runs its database work one at a time. On a remote database (`libsql://`) one turn of that work is bounded (`requestTimeoutMs`, default 10000): past it the call answers `SERVICE_UNAVAILABLE` and the queue moves on.
14+
- **`@objectstack/knowledge-turso` now ships from this repository**, Apache-2.0 (its `LICENSE` file is the Apache-2.0 text). `KnowledgeTursoPlugin` registers a `TursoKnowledgeAdapter` (adapter id `turso`) that keeps passages and vectors in a libSQL database of its own with libSQL's native vectors: the `url` option (`file:`, `:memory:`, `libsql://`), else `knowledge.db` under the project's `.objectstack/data/` (`defaultStoreUrl`). A URL naming the platform's own database file (`objectstack.db`, `dev.db`, `standalone.db`, or the file `OS_DATABASE_URL` names) is refused: two engines writing one SQLite file lose rows. On a file the store sets WAL and a busy timeout (`busyTimeoutMs`, default 5000), and in one process every call of the store runs its database work one at a time. On a remote database (`libsql://`) each request is bounded (`requestTimeoutMs`, default 10000; a write sends one request per document): past it the call answers `SERVICE_UNAVAILABLE`, a write stopped before its commit is rolled back, and the queue moves on.
1515
- **The platform embedder and splitter.** The package's own OpenAI embedding provider, hash embedder and chunker are gone: it embeds with the kernel's `embedder` service, read at each call (or the `embedder` option), reports `embedding` (model, dimensions, input limit), and declares `capabilities.chunks`, indexing the service's passages as given. Removed exports of the cloud-repo releases: `HashEmbedder`, `HashEmbeddingProvider`, `EmbeddingProvider`, `TursoAdapterOptions` and the default export; removed options: `embedding` (now `embedder`), `chunkTarget`, `overFetch`, and `adapterConfig.tableName` / `dimensions` on a source.
1616
- **Generations under the index fingerprint (ADR-0161 K7; K8, item 8).** A generation table `knowledge_generation` and one passage table per source and generation, `knowledge_<source>_g<n>`. A write or a search under another fingerprint is refused `409 KNOWLEDGE_REBUILD_REQUIRED` (registered in the error-code ledger for this package). `beginBuild` under a new fingerprint opens a generation beside the active one, which keeps answering its own fingerprint; `completeBuild` switches to it, records the recipe hash and drops the old table; `indexStatus` answers the fingerprint, the recipe hash and whether a build is under way. The unique index keeps one generation under construction per source; it does not refuse a second builder: a second `beginBuild` under the same fingerprint joins the build, and one under another fingerprint replaces it, after which the first builder's writes are refused `KNOWLEDGE_REBUILD_REQUIRED`. Either way no generation mixes two fingerprints. A table of the cloud-repo releases (`knowledge_<source>` with exactly their columns) is never served: a search answers `KNOWLEDGE_REBUILD_REQUIRED`, and the table is dropped when the first complete reindex finishes.
1717
- **Listing, hashes, organizations.** `listDocuments` pages the generation the writes go to, each document's `docHash` as stored; hits carry `docHash` and the passage's `headingPath`; the organization filter, the record scope (`scope`, ADR-0161 K8 item 17) and the metadata `filter` run in SQL before ranking, by an exact cosine scan (no DiskANN index, which ranks before it filters). A passage whose text is unchanged is not embedded again.

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,14 @@ kernel.use(new KnowledgeTursoPlugin()); // .objectstack/data/knowledge.db
2424
| `authToken` | — | The token of a `libsql://` URL. |
2525
| `client` | — | A libSQL client to use as it is (not configured, not closed by the plugin). |
2626
| `busyTimeoutMs` | `5000` | How long a write waits for another process's lock on a `file:` store. |
27-
| `requestTimeoutMs` | `10000` for a remote URL | The longest one turn of database work may take on a remote database before the call answers `SERVICE_UNAVAILABLE`. None for a file or `:memory:`; for a `client` given as it is, only when set. |
27+
| `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. |
2828
| `projectRoot` | `process.cwd()` | The directory the default file is under. |
2929
| `queryPrefix` | `''` | Text put before every query before it is embedded. Passages are embedded as they are. |
3030
| `embedder` | the kernel's `embedder` service | The embedder to call, read at each call. |
3131

3232
## Its own file, never the platform's
3333

34-
The store opens a libSQL file of its own. Two engines writing one SQLite file in one process lose rows (measured: a row lost silently under WAL, a failed commit in delete mode), so a URL that names the platform's database — `objectstack.db`, `dev.db`, `standalone.db`, or the file `OS_DATABASE_URL` names — is refused: the plugin registers, warns, and every call answers `SERVICE_UNAVAILABLE`.
34+
The store opens a libSQL file of its own. Two engines writing one SQLite file in one process lose rows (measured: a row lost silently under WAL, a failed commit in delete mode), so a URL that names the platform's database — `objectstack.db`, `dev.db`, `standalone.db`, or the file `OS_DATABASE_URL` names, compared as the file a link resolves to and with SQLite's `-wal`, `-shm` and `-journal` side files read as their database — is refused: the plugin registers, warns, and every call answers `SERVICE_UNAVAILABLE`.
3535

3636
On a file the store sets WAL and a busy timeout: without them a second process writing the same file lost most of its writes in measurement. Within one process every call of the store runs its database work one at a time.
3737

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

Lines changed: 119 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,38 @@ for (const kind of ['memory', 'file'] as StoreKind[]) {
309309
expect((await adapter.search('amber', { source: s, topK: 5 })).map((h) => h.documentId)).toEqual([`${s.id}:r1`]);
310310
});
311311

312+
it('a table with the legacy columns but no F32_BLOB vector is not a legacy table', async () => {
313+
const client = store.client();
314+
const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder() });
315+
await client.execute(`CREATE TABLE knowledge_blobs (
316+
chunk_id TEXT PRIMARY KEY, document_id TEXT NOT NULL, source_record_id TEXT, content TEXT NOT NULL,
317+
title TEXT, metadata TEXT, embedding BLOB)`);
318+
const s = source('blobs');
319+
expect(await adapter.search('x', { source: s, topK: 5 })).toEqual([]);
320+
await adapter.upsert([doc(s, '1', 'flint')], ctx(s));
321+
await adapter.completeBuild(ctx(s));
322+
expect(await tables(client, 'knowledge_blobs%')).toEqual(['knowledge_blobs', 'knowledge_blobs_g1']);
323+
});
324+
325+
it('a search whose generation keeps being switched under it stops after three attempts, SERVICE_UNAVAILABLE', async () => {
326+
const client = store.client();
327+
const s = source('churn');
328+
const builder = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder() });
329+
await builder.upsert([doc(s, '1', 'spruce')], ctx(s));
330+
let n = 0;
331+
const churning = new (class extends FakeEmbedder {
332+
override async embed(texts: string[]): Promise<number[][]> {
333+
const next = { fingerprint: `fp-test:churn-${++n}`, recipeHash: 'rh-test:1' };
334+
await builder.beginBuild(ctx(s, next));
335+
await builder.completeBuild(ctx(s, next));
336+
return super.embed(texts);
337+
}
338+
})();
339+
const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: churning });
340+
expect(await refusal(adapter.search('spruce', { source: s, topK: 5 }))).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
341+
expect(n).toBe(3);
342+
});
343+
312344
it('a table the store did not make is never dropped, under a legacy name or a generation name', async () => {
313345
const client = store.client();
314346
const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder() });
@@ -325,7 +357,7 @@ for (const kind of ['memory', 'file'] as StoreKind[]) {
325357
// Under the name of a generation table it is refused, and left as it is.
326358
await client.execute('CREATE TABLE knowledge_notes_g1 (id TEXT PRIMARY KEY, body TEXT)');
327359
const notes = source('notes');
328-
await expect(adapter.upsert([doc(notes, '1', 'x')], ctx(notes))).rejects.toThrow(/did not make/);
360+
expect(await refusal(adapter.upsert([doc(notes, '1', 'x')], ctx(notes)))).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
329361
expect(await tables(client, 'knowledge_notes_g1')).toEqual(['knowledge_notes_g1']);
330362
});
331363

@@ -375,6 +407,11 @@ for (const kind of ['memory', 'file'] as StoreKind[]) {
375407
const adapter = store.adapter();
376408
const bad = source('x"; DROP TABLE knowledge_generation; --');
377409
await expect(adapter.upsert([doc(bad, '1', 'x')], ctx(bad))).rejects.toThrow(/cannot name a table/);
410+
expect(await refusal(adapter.listDocuments(ctx(bad), { limit: 1 }))).toMatchObject({ code: 'VALIDATION_ERROR', status: 400 });
411+
// The spec's own pattern, of any length.
412+
const long = source(`s_${'a'.repeat(80)}`);
413+
await adapter.upsert([doc(long, '1', 'long name')], ctx(long));
414+
expect((await adapter.search('long name', { source: long, topK: 1 })).length).toBe(1);
378415
await expect(adapter.search('x', { source: bad, topK: 1 })).rejects.toThrow(/cannot name a table/);
379416
});
380417
});
@@ -439,3 +476,84 @@ describe('knowledge-turso without a database or an embedder', () => {
439476
store.closeAll();
440477
});
441478
});
479+
480+
/** A client whose every request (and every request of its transactions) is delayed by `ms`; `stallAt` hangs the Nth. */
481+
function slowClient(real: Client, ms: number, stallAt?: (request: number) => boolean): Client {
482+
let request = 0;
483+
const delayed = <T extends object>(target: T, methods: string[], wrap?: (v: unknown) => unknown): T =>
484+
new Proxy(target, {
485+
get(t, key) {
486+
const value = Reflect.get(t, key, t) as unknown;
487+
if (typeof value !== 'function') return value;
488+
const fn = (value as (...a: unknown[]) => unknown).bind(t);
489+
if (typeof key !== 'string' || !methods.includes(key)) return fn;
490+
return async (...args: unknown[]) => {
491+
request += 1;
492+
if (stallAt?.(request)) return new Promise(() => undefined);
493+
await new Promise((r) => setTimeout(r, ms));
494+
const answered = await (fn(...args) as Promise<unknown>);
495+
return key === 'transaction' && wrap ? wrap(answered) : answered;
496+
};
497+
},
498+
});
499+
return delayed(real, ['execute', 'batch', 'transaction'], (tx) => delayed(tx as object, ['execute', 'batch', 'commit', 'rollback']));
500+
}
501+
502+
describe('knowledge-turso with a request bound (a remote database)', () => {
503+
it('bounds each request, not a page: a page of 40 documents on a slow database is written whole', async () => {
504+
const store = storeOf('file');
505+
const client = slowClient(store.client(), 15);
506+
const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client, embedder: new FakeEmbedder(), requestTimeoutMs: 120 });
507+
const s = source('slow');
508+
const docs = Array.from({ length: 40 }, (_, i) =>
509+
doc(s, String(i), `heron ${i}`, {
510+
chunks: [0, 1].map((index) => ({
511+
id: `${s.id}:${i}#${index}`,
512+
documentId: `${s.id}:${i}`,
513+
index,
514+
content: `heron ${i} ${index === 0 ? 'wading' : 'flying'}`,
515+
})),
516+
}),
517+
);
518+
await adapter.upsert(docs, ctx(s));
519+
// Again, unchanged: every passage is rewritten in place, still within the bound.
520+
await adapter.upsert(docs, ctx(s));
521+
expect((await adapter.listDocuments(ctx(s), { limit: 100 })).documents.length).toBe(40);
522+
store.closeAll();
523+
});
524+
525+
it('a request that stalls inside a write answers SERVICE_UNAVAILABLE naming requestTimeoutMs, and nothing of the write lands', async () => {
526+
const store = storeOf('file');
527+
const real = store.client();
528+
const s = source('stall');
529+
const plain = new TursoKnowledgeAdapter({ id: 'under_test', client: real, embedder: new FakeEmbedder() });
530+
await plain.upsert([doc(s, 'seed', 'otter')], ctx(s));
531+
let batches = 0;
532+
// The second batch inside a write transaction hangs, as a remote database can: the first document is written by then.
533+
const client = slowClient(real, 0, () => false);
534+
const hanging = new Proxy(client, {
535+
get(t, key) {
536+
if (key !== 'transaction') return Reflect.get(t, key, t);
537+
return async (...args: unknown[]) => {
538+
const tx = await (t.transaction as (...a: unknown[]) => Promise<object>).apply(t, args);
539+
return new Proxy(tx, {
540+
get(x, k) {
541+
const v = Reflect.get(x, k, x) as unknown;
542+
if (k === 'batch' && ++batches === 2) return () => new Promise(() => undefined);
543+
return typeof v === 'function' ? (v as (...a: unknown[]) => unknown).bind(x) : v;
544+
},
545+
});
546+
};
547+
},
548+
}) as Client;
549+
const adapter = new TursoKnowledgeAdapter({ id: 'under_test', client: hanging, embedder: new FakeEmbedder(), requestTimeoutMs: 80 });
550+
const err = await refusal(adapter.upsert([doc(s, 'a', 'otter pup'), doc(s, 'b', 'otter den')], ctx(s)));
551+
expect(err).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503, remedy: expect.stringContaining('requestTimeoutMs') });
552+
await new Promise((r) => setTimeout(r, 100));
553+
expect((await plain.listDocuments(ctx(s), { limit: 10 })).documents.map((d) => d.documentId)).toEqual([`${s.id}:seed`]);
554+
// The next write goes through.
555+
await adapter.upsert([doc(s, 'a', 'otter pup')], ctx(s));
556+
expect((await plain.listDocuments(ctx(s), { limit: 10 })).documents.length).toBe(2);
557+
store.closeAll();
558+
});
559+
});

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

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,14 @@
77
* never a failed boot.
88
*/
99

10-
import { mkdtempSync, rmSync } from 'node:fs';
10+
import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
1111
import { tmpdir } from 'node:os';
1212
import { join } from 'node:path';
1313
import { afterEach, describe, expect, it, vi } from 'vitest';
1414
import type { PluginContext } from '@objectstack/core';
1515
import type { IKnowledgeAdapter, IKnowledgeService } from '@objectstack/spec/contracts';
1616
import { EMBEDDER_SERVICE, KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts';
17-
import { KnowledgeTursoPlugin, defaultStoreUrl, resolveStoreUrl } from '../index.js';
17+
import { DEFAULT_REQUEST_TIMEOUT_MS, KnowledgeTursoPlugin, defaultStoreUrl, requestBoundFor, resolveStoreUrl } from '../index.js';
1818
import { FakeEmbedder } from './turso.testkit.js';
1919

2020
/** A plugin context with a knowledge service that records registrations, an embedder, and a logger that records. */
@@ -78,12 +78,41 @@ describe('resolveStoreUrl', () => {
7878
reason: expect.stringContaining("platform's own database file"),
7979
});
8080
expect(resolveStoreUrl({ url: 'file:/var/data/%zz.db', env: {} })).toMatchObject({ reason: expect.stringContaining('not a valid file: URL') });
81+
// SQLite's side files belong to their database.
82+
for (const url of ['file:/srv/app/objectstack.db-wal', 'file:/srv/app/dev.db-shm', 'file:/var/data/app.db-journal']) {
83+
expect(resolveStoreUrl({ url, env: { OS_DATABASE_URL: '/var/data/app.db' } })).toMatchObject({
84+
reason: expect.stringContaining("platform's own database file"),
85+
});
86+
}
8187
expect(resolveStoreUrl({ url: 'file:/var/data/knowledge.db', env: { OS_DATABASE_URL: 'file:/var/data/app.db' } })).toEqual({
8288
url: 'file:/var/data/knowledge.db',
8389
from: 'the plugin option `url`',
8490
});
8591
});
8692

93+
it("refuses a link to the platform's file: the file it resolves to is compared", () => {
94+
const dir = mkdtempSync(join(tmpdir(), 'knowledge-turso-link-'));
95+
try {
96+
writeFileSync(join(dir, 'app.db'), '');
97+
symlinkSync(join(dir, 'app.db'), join(dir, 'knowledge.db'));
98+
symlinkSync(dir, join(dir, 'alias'));
99+
const env = { OS_DATABASE_URL: `file:${join(dir, 'app.db')}` };
100+
expect(resolveStoreUrl({ url: `file:${join(dir, 'knowledge.db')}`, env })).toMatchObject({ reason: expect.stringContaining("platform's own database file") });
101+
expect(resolveStoreUrl({ url: `file:${join(dir, 'alias', 'app.db')}`, env })).toMatchObject({ reason: expect.stringContaining("platform's own database file") });
102+
expect(resolveStoreUrl({ url: `file:${join(dir, 'alias', 'other.db')}`, env })).toMatchObject({ url: `file:${join(dir, 'alias', 'other.db')}` });
103+
} finally {
104+
rmSync(dir, { recursive: true, force: true });
105+
}
106+
});
107+
108+
it('bounds requests by default on a remote URL only', () => {
109+
expect(requestBoundFor('libsql://db.example.turso.io')).toBe(DEFAULT_REQUEST_TIMEOUT_MS);
110+
expect(requestBoundFor('https://db.example.turso.io')).toBe(DEFAULT_REQUEST_TIMEOUT_MS);
111+
expect(requestBoundFor('file:/srv/app/.objectstack/data/knowledge.db')).toBeUndefined();
112+
expect(requestBoundFor(':memory:')).toBeUndefined();
113+
expect(requestBoundFor('file:/srv/k.db', 250)).toBe(250);
114+
});
115+
87116
it('accepts :memory: and libsql:// URLs, refuses anything else', () => {
88117
expect(resolveStoreUrl({ url: ':memory:', env: {} })).toMatchObject({ url: ':memory:' });
89118
expect(resolveStoreUrl({ url: 'libsql://db.example.turso.io', env: {} })).toMatchObject({ url: 'libsql://db.example.turso.io' });

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@ export {
77
} from './turso-adapter.js';
88
export {
99
DEFAULT_KNOWLEDGE_FILE,
10+
DEFAULT_REQUEST_TIMEOUT_MS,
1011
KnowledgeTursoPlugin,
1112
PLATFORM_DATABASE_FILES,
1213
defaultStoreUrl,
14+
requestBoundFor,
1315
resolveStoreUrl,
1416
type KnowledgeTursoPluginOptions,
1517
} from './plugin.js';

0 commit comments

Comments
 (0)