Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/turso-drop-during-build.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@objectstack/knowledge-turso': patch
---

fix(knowledge-turso): a build that keeps going after `dropSource` cannot bring the dropped source back

Clause-②: no
Metadata-protocol: none

`IKnowledgeAdapter.dropSource` removes every generation of a source, "the one under construction included", and afterwards a source registered again under the same key is built from nothing. On the turso store a build of the source that was under way when it was dropped, in another process or in the same one, broke that: its next page found no generation and opened a new active one, and the rest of the walk landed there, so the store served the dropped source again.

A build's writes, listing and completion now go only to the generation that build began. When that generation is gone, because the source was dropped or another build under another fingerprint replaced it, the call is refused `LOCK_CONFLICT` (409), the same code and status the pgvector store answers, and the build ends; nothing is opened. A completion of such a build is refused the same way (before, it threw an error with no code). The build knows its generation by its number, the time its row was made and its fingerprint, so a later generation that takes the same number after a drop is never taken for it.

A build that begins after the drop builds the source from nothing, as before. Writes outside a build (event sync) are not fenced. Nothing to migrate.
4 changes: 2 additions & 2 deletions packages/plugins/knowledge-turso/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ On a file the store sets WAL and a busy timeout: without them a second process w

## Tables

- `knowledge_generation` — one row per source and generation: the index fingerprint it was built under, the recipe hash, the vector width, the model, and whether it is active or being built. At most one of each per source, by a unique index. It does not refuse a second builder: a second build under the same fingerprint joins the one under way, and one under another fingerprint replaces it, after which the first builder's writes are refused `KNOWLEDGE_REBUILD_REQUIRED`. No generation mixes two fingerprints.
- `knowledge_generation` — one row per source and generation: the index fingerprint it was built under, the recipe hash, the vector width, the model, and whether it is active or being built. At most one of each per source, by a unique index. It does not refuse a second builder: a second build under the same fingerprint joins the one under way, and one under another fingerprint replaces it, after which the first build's writes, listing and completion are refused `LOCK_CONFLICT` (409) and that build ends; a write outside a build under the replaced fingerprint is refused `KNOWLEDGE_REBUILD_REQUIRED`. No generation mixes two fingerprints.
- `knowledge_<source>_g<n>` — the passages of one generation of one source, with an `F32_BLOB(<width>)` vector column sized for that generation.

`<source>` is the source's index key: its name, or for a source a package ships, the knowledge service's spelling of that package and name (so two packages' sources of one name are two tables). When a source stops being served (its metadata item was removed, or a package now holds its name), the knowledge service calls `dropSource`: the source's generation tables and rows are dropped in one transaction. A table the store did not make under one of those names (an object's table, in a database shared with object tables) is never dropped: the call is refused `SERVICE_UNAVAILABLE`, naming the table, and nothing of the source is removed.
`<source>` is the source's index key: its name, or for a source a package ships, the knowledge service's spelling of that package and name (so two packages' sources of one name are two tables). When a source stops being served (its metadata item was removed, or a package now holds its name), the knowledge service calls `dropSource`: the source's generation tables and rows are dropped in one transaction. A table the store did not make under one of those names (an object's table, in a database shared with object tables) is never dropped: the call is refused `SERVICE_UNAVAILABLE`, naming the table, and nothing of the source is removed. A build of the source under way when it is dropped, in this process or another, is ended: its next write, listing or completion is refused `LOCK_CONFLICT` (409) and opens nothing, so the build never brings the source back. A build that begins after the drop builds the source from nothing.

## Search

Expand Down
165 changes: 165 additions & 0 deletions packages/plugins/knowledge-turso/src/__tests__/acceptance.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,171 @@ for (const kind of ['memory', 'file'] as StoreKind[]) {
});
}

/** A build's context: the walk's calls carry `reason: 'reindex'`. */
const buildCtx = (s: KnowledgeSource, index = FP_A): AdapterContext => ({ source: s, reason: 'reindex', index });

/** What the store holds for a source: its generation rows (`n:fingerprint:state`) and its passage tables. */
async function heldFor(client: Client, s: KnowledgeSource): Promise<{ generations: string[]; tables: string[] }> {
const rows = await client.execute({
sql: 'SELECT generation, fingerprint, state FROM knowledge_generation WHERE source_id = ? ORDER BY generation',
args: [s.name],
});
return {
generations: rows.rows.map((r) => `${Number(r.generation)}:${String(r.fingerprint)}:${String(r.state)}`),
tables: await tables(client, `knowledge_${s.name}_g%`),
};
}

const NOTHING = { generations: [], tables: [] };

for (const kind of ['memory', 'file'] as StoreKind[]) {
describe(`knowledge-turso: a build whose source is dropped while it runs, on ${kind === 'memory' ? ':memory:' : 'a file: URL'}`, () => {
const store = storeOf(kind);
afterAll(() => store.closeAll());

/**
* Two adapters over one store, standing for two processes: each keeps its
* own builds; on a file, each has its own connection to the database.
*/
function twoProcesses(embedder: IEmbedder = new FakeEmbedder()) {
const at = store.url();
const first = store.client(at);
const second = kind === 'file' ? store.client(at) : first;
return {
client: first,
a: new TursoKnowledgeAdapter({ id: 'under_test', client: first, embedder }),
b: new TursoKnowledgeAdapter({ id: 'under_test', client: second, embedder: new FakeEmbedder() }),
};
}

const FP_B = { fingerprint: 'fp-test:b', recipeHash: 'rh-test:1' };
const FP_C = { fingerprint: 'fp-test:c', recipeHash: 'rh-test:1' };

const begins = [
['beside the active generation', FP_B, true],
['inside the active generation', FP_A, true],
['of a source that held nothing', FP_A, false],
] as const;
const calls = {
write: (a: TursoKnowledgeAdapter, c: AdapterContext) => a.upsert([doc(c.source as KnowledgeSource, '2', 'granite quarry')], c),
list: (a: TursoKnowledgeAdapter, c: AdapterContext) => a.listDocuments(c, { limit: 10 }),
complete: (a: TursoKnowledgeAdapter, c: AdapterContext) => a.completeBuild(c),
} as const;

for (const [shape, index, seeded] of begins) {
for (const [call, run] of Object.entries(calls)) {
it(`a build ${shape}, then a drop in another process: the build's ${call} is refused LOCK_CONFLICT, nothing is held, and the source builds again from nothing`, async () => {
const { client, a, b } = twoProcesses();
const s = source(`drop_${seeded ? (index === FP_A ? 'inside' : 'beside') : 'empty'}_${call}`);
if (seeded) await a.upsert([doc(s, '1', 'granite quarry')], ctx(s));
await a.beginBuild(buildCtx(s, index));
await b.dropSource(ctx(s));

expect(await refusal(run(a, buildCtx(s, index)))).toMatchObject({ code: 'LOCK_CONFLICT', status: 409 });
expect(await heldFor(client, s)).toEqual(NOTHING);
expect(await b.indexStatus(ctx(s))).toEqual({});

// The build ended: one that begins after the drop builds the source from nothing.
await a.beginBuild(buildCtx(s, index));
await a.upsert([doc(s, '3', 'basalt columns')], buildCtx(s, index));
await a.completeBuild(buildCtx(s, index));
expect(await heldFor(client, s)).toEqual({ generations: [`1:${index.fingerprint}:active`], tables: [`knowledge_${s.name}_g1`] });
const hits = await b.search('basalt', { source: s, topK: 5, index: { fingerprint: index.fingerprint } });
expect(hits.map((h) => h.documentId)).toEqual([`${s.name}:3`]);
});
}
}

it("a drop in the build's own process ends the build the same way", async () => {
const { client, a } = twoProcesses();
const s = source('drop_same_process');
await a.upsert([doc(s, '1', 'granite quarry')], ctx(s));
await a.beginBuild(buildCtx(s, FP_B));
await a.dropSource(ctx(s));
expect(await refusal(a.upsert([doc(s, '2', 'marble')], buildCtx(s, FP_B)))).toMatchObject({ code: 'LOCK_CONFLICT', status: 409 });
expect(await heldFor(client, s)).toEqual(NOTHING);
});

it('a page whose embedding was under way when the drop committed is written nowhere', async () => {
let drop: (() => Promise<void>) | undefined;
const embedder = new (class extends FakeEmbedder {
override async embed(texts: string[]): Promise<number[][]> {
const now = drop;
drop = undefined;
if (now) await now();
return super.embed(texts);
}
})();
const { client, a, b } = twoProcesses(embedder);
const s = source('drop_while_embedding');
await a.upsert([doc(s, '1', 'granite quarry')], ctx(s));
await a.beginBuild(buildCtx(s, FP_B));
drop = () => b.dropSource(ctx(s));
expect(await refusal(a.upsert([doc(s, '2', 'marble')], buildCtx(s, FP_B)))).toMatchObject({ code: 'LOCK_CONFLICT', status: 409 });
expect(drop).toBeUndefined();
expect(await heldFor(client, s)).toEqual(NOTHING);
});

it('a build another process replaced under another fingerprint is ended the same way; the replacing build goes on', async () => {
const { client, a, b } = twoProcesses();
const s = source('replaced_build');
await a.upsert([doc(s, '1', 'granite quarry')], ctx(s));
await a.beginBuild(buildCtx(s, FP_B));
await b.beginBuild(buildCtx(s, FP_C));
// The replacing build's generation took the number of the one it replaced.
expect((await heldFor(client, s)).generations).toEqual([`1:${FP_A.fingerprint}:active`, `2:${FP_C.fingerprint}:building`]);
expect(await refusal(a.upsert([doc(s, '2', 'marble')], buildCtx(s, FP_B)))).toMatchObject({ code: 'LOCK_CONFLICT', status: 409 });
await b.upsert([doc(s, '3', 'basalt columns')], buildCtx(s, FP_C));
await b.completeBuild(buildCtx(s, FP_C));
expect(await b.indexStatus(ctx(s))).toEqual({ fingerprint: FP_C.fingerprint, recipeHash: FP_C.recipeHash });
expect((await b.search('basalt marble', { source: s, topK: 5, index: FP_C })).map((h) => h.documentId)).toEqual([`${s.name}:3`]);
});

for (const [label, next, pause] of [
['under another fingerprint', FP_C, 0],
['under the same fingerprint, made later', FP_A, 10],
] as const) {
it(`a generation that takes a dropped build's number ${label} is never that build's`, async () => {
const { client, a, b } = twoProcesses();
const s = source(`reused_${next === FP_A ? 'same' : 'other'}`);
await a.beginBuild(buildCtx(s, FP_A));
await b.dropSource(ctx(s));
if (pause > 0) await new Promise((resolve) => setTimeout(resolve, pause));
await b.beginBuild(buildCtx(s, next));
expect((await heldFor(client, s)).generations).toEqual([`1:${next.fingerprint}:active`]);
expect(await refusal(a.upsert([doc(s, '1', 'marble')], buildCtx(s, FP_A)))).toMatchObject({ code: 'LOCK_CONFLICT', status: 409 });
expect(await b.listDocuments(buildCtx(s, next), { limit: 10 })).toEqual({ documents: [] });
});
}

it('through KnowledgeService: a walk whose source another process drops after its first page stops, and leaves nothing', async () => {
const { client, a, b } = twoProcesses();
const s = source('drop_mid_walk');
const rows = Array.from({ length: 250 }, (_, i) => ({ id: `r${String(i + 1).padStart(4, '0')}`, body: `granite ${i + 1}`, status: 'published' }));
const svc = new KnowledgeService({ dataEngine: rowsEngine(rows) });
const upsert = a.upsert.bind(a);
let pages = 0;
a.upsert = async (batch, c) => {
await upsert(batch, c);
pages += 1;
if (pages === 1) await b.dropSource(ctx(s));
};
svc.registerAdapter('under_test', a);
svc.registerSource(s);

expect(await svc.reindexSource(s.name)).toMatchObject({ ok: false, indexed: 100 });
expect(pages).toBe(1);
expect(await heldFor(client, s)).toEqual(NOTHING);
expect(await b.indexStatus(ctx(s))).toEqual({});

// Drop-then-build: the next walk builds the source from nothing.
a.upsert = upsert;
expect(await svc.reindexSource(s.name)).toMatchObject({ ok: true, indexed: 250 });
expect((await heldFor(client, s)).tables).toEqual([`knowledge_${s.name}_g1`]);
});
});
}

describe('knowledge-turso without a database or an embedder', () => {
it('answers every call SERVICE_UNAVAILABLE in one sentence; the reason is operator text in remedy and healthCheck', async () => {
const adapter = new TursoKnowledgeAdapter({ embedder: new FakeEmbedder(), unavailable: 'no native build for win32-arm64' });
Expand Down
Loading
Loading