Skip to content

Commit d7f299c

Browse files
feat(service-knowledge): adapters list their documents; a complete reindex skips unchanged documents and purges stale ones; adapter contract suite (#37164)
Fixes #37096 Clause-②: yes Metadata-protocol: added Skills-docs: none — no skill under `skills/**` teaches `KnowledgeDocument`, the adapter contract or reindex; `skills/objectstack-ai/SKILL.md` teaches `KnowledgeSource` authoring only. `content/docs/protocol/knowledge.mdx` gains the members, the skip and the purge in this change. ## 维护者速读 - 用户能看到什么变化:知识检索全量重建时,只有实现了“列出已存文档”能力的存储才会跳过没变的内容、清掉源数据里已删除或不再符合筛选条件的内容;本仓库里目前只有开发测试用的内存存储实现了它,RAGFlow 存储的重建和以前完全一样。 - 为什么做:知识检索平台化专题的第二阶段(让向量存储能列出自己存了什么,并有一套所有存储都要跑的契约测试)。 - 出错会怎样:最坏是重建时误删一条仍有效的内容,或漏删一条失效内容;每条删除前都会按源条件重读一次确认,读不出结果就停下不删,清理中途失败时重建结果会报失败;下次重建或记录变更即可恢复,可直接撤回。 - 要你做什么:无。 ## What changes ADR-0161 K8 items 1 and 2, each landing with its reader (ADR-0049): - **Contract (`@objectstack/spec`).** `IKnowledgeAdapter.listDocuments?(ctx, { cursor?, limit })` → `{ documents: { documentId, docHash? }[], nextCursor? }` (new exported interfaces `AdapterListDocumentsOptions`, `AdapterListedDocument`, `AdapterListDocumentsPage`), and `KnowledgeDocument.docHash?`. Both optional; shapes exactly as K8's table. - **`docHash` (service).** `computeDocHash` = `v1:` + SHA-256 over `{ content, title, metadata }` serialized with every plain object's keys sorted. Stamped by `recordToDocument` (walk and event sync) and by `indexDocument`, which refuses a caller-supplied `docHash` (it throws, naming `docHash` and that the service computes it) instead of replacing it. - **Skip (its reader).** `reindexSource` lists the adapter's documents before the walk (paged, `LIST_DOCUMENTS_PAGE_SIZE` = 500, a repeated cursor refused); a document whose computed hash equals the listed one is not upserted (`skipped`). A listed entry with no hash reads as changed. - **Purge.** One function, `purgeDocuments`, exported from the service module for row 15's reconcile in this package (not re-exported from the package entry). It runs only after a complete walk (no `limit`, no `dryRun`, no failed page), never for `refresh.onRecordChange: false`, never without `listDocuments`. Candidates = listed before the walk − seen in it. Each candidate is confirmed by the event sync's own re-read — extracted unchanged into one helper, `rereadRow` (`where` AND id, `limit: 1`, system context), now called by both — and runs on the per-document record-sync chain, so an event sync of the same row cannot interleave between the re-read and the delete. A listed id the source does not derive (`SOURCE:RECORD`) is kept and counted in `message`. A walk page or a re-read that answers no list of rows is a failure, never "empty" or "no row": the walk stops (`purged: null`) or the purge stops (`ok: false`). The event sync shares `rereadRow`, so on a non-list answer it now warns and keeps the document where it used to delete it (pinned). The re-read asks by the id text only; see the numeric-id limit in Acceptance notes. - **Result.** `skipped` and `purged` on every return of `reindexSource`; `purged: null` = no purge ran. A failed listing: everything written, nothing purged, `message` says why, still `ok: true`. A failed purge step: `ok: false`, `purged` = deletions before it. - **`knowledge-memory`** implements `listDocuments` (id order, cursor = last id of the page before; `docHash` stored as given) — the reference implementation. - **Contract suite.** `@objectstack/service-knowledge/testing` → `runKnowledgeAdapterContract({ name, makeAdapter, implements: { listDocuments } })`: upsert / search / delete; `listDocuments` at 0, one page, one page + 1, `docHash` as stored, source scoping; skip, purge, and no purge under `limit`/`dryRun` through a real `KnowledgeService` over an engine double. `implements` is asserted against the adapter, and an adapter without `listDocuments` runs the `purged: null` case instead. Entry follows the `service-cluster` / `metadata-core` precedent: own `tsup.config.ts`, ESM-only `./testing` export (no `require`), `vitest` external, not reachable from `.`. `knowledge-memory` runs it. - **Docs.** `content/docs/protocol/knowledge.mdx` (§3.2, §3.3, §3.4 with the suite, a new "Reindex: skip and purge" section, the stale-index callout and the predicate-write paragraph); the plugin's predicate-write warning text says the same. Regenerated: `api-surface/contracts.json`, `export-origins/contracts.json`, `authorable-surface/ai.json`, `content/docs/references/ai/knowledge-document.mdx`. - **`KnowledgeReindexResult` (`@objectstack/spec`)** gains optional `skipped?: number` and `purged?: number | null` (fields only added; `null` = no purge ran). - **`knowledge-ragflow` test config** gains the one anchored `@objectstack/service-knowledge/testing` alias ahead of its bare entry, as `check:test-source-alias` prescribes; nothing else in that package. ### Deviations - File surface extended by the dispatching zone (card What 4; check:test-source-alias): `packages/spec/src/contracts/knowledge-service.ts` and `packages/plugins/knowledge-ragflow/vitest.config.ts`, granted by the dispatching zone after the first report; both edits are exactly the two described above. - The full-workspace `pnpm test` before opening was scoped to the three touched packages' builds, typechecks and suites plus the 131 derived gate families (below). ## Tests <details><summary>build, typecheck and vitest (head 48ed4f1)</summary> ``` build (closure of knowledge-memory + knowledge-ragflow) exit 0 typecheck service-knowledge, knowledge-memory, knowledge-ragflow (tsc --noEmit + check:test-typecheck) exit 0 @objectstack/service-knowledge Test Files 8 passed (8) Tests 170 passed (170) @objectstack/knowledge-memory Test Files 2 passed (2) Tests 20 passed (20) @objectstack/knowledge-ragflow Test Files 1 passed (1) Tests 10 passed (10) dist: testing.js / testing.d.ts emitted ESM-only; no file reachable from index.js imports vitest ``` </details> <details><summary>Ablations (committed first; ablation-replace, restored to the HEAD blob each time)</summary> - Purge confirm removed (`rereadRow` line deleted): 3 red — "purges … each confirmed by a re-read", "a document written by the event sync during the walk survives the purge", "a purge whose re-read fails stops…". Restored: blob == HEAD, `git diff HEAD` empty. - Skip removed (every document treated as changed): 5 red in `knowledge-service.test.ts`; 1 red in the contract suite on `knowledge-memory` ("a second complete reindex skips every unchanged document…"). Restored both times. </details> New cases: `computeDocHash` (prefix, key-order stability at depth, sensitivity to content / title / metadata / array order), skip (all unchanged; only the changed row; entry without hash), listing paged to its end, purge of a deleted row and of a row that left `where` with the exact re-read `where`s, no purge under `limit` / `limit: 0` / `dryRun` / failed page, event-sync-created and restored documents survive, `onRecordChange: false`, failed listing, repeated cursor, failed re-read, foreign ids. Thirteen existing exact-result assertions gained `skipped: 0, purged: null` (stub adapters without `listDocuments`; otherwise unchanged). ## Acceptance notes - **Known limit — numeric record ids** (contract review 7152394541 S1; follow-up card #37221). The purge re-reads by the record id text recovered from the document id. On driver-mongodb and driver-memory a row stored under a caller-supplied numeric id is not found by that re-read, so if it was restored, or came back into `where`, after the walk read past it, its document is deleted; the row is untouched and its document returns at its next event or the next complete reindex. A second re-read by the number was tried and removed: on driver-sql it binds a number against the text `id` column, which MySQL compares numerically (`'05'` matches `5`) and SQL Server and Oracle reject, and no object schema types its `id`, so the service cannot tell which objects have numeric ids. Stated in `purgeDocuments`' TSDoc, the protocol doc and the changeset, and pinned by "the purge re-reads by the id text only". - `docHash` and the metadata protocol: `KnowledgeDocument` is referenced by no metadata-type schema, only by the adapter and service contracts, so no metadata author writes it; it shows on the `authorable-surface` shard because that shard records the keys of every exported `ai/` schema (`KnowledgeHit`, equally runtime-only, is there too), and `Check Changeset` reads any shard move as a protocol change, hence `Metadata-protocol: added` and spec at `minor`. The key has its producer (the service) and its readers (the adapter stores and lists it; the reindex compares it), so it is not declared-but-unenforced. - `knowledge-memory` stores no chunk for a document with empty content, so such a document is never listed: it is re-written on every reindex and never purged (the safe direction). ## Verification Read first (risk order): `packages/services/service-knowledge/src/knowledge-service.ts` (`walkObjectSource` end, `purgeDocuments`, `rereadRow`); `packages/services/service-knowledge/src/testing.ts`; `packages/services/service-knowledge/package.json` + `tsup.config.ts`. Two minutes: `pnpm --filter @objectstack/knowledge-memory exec vitest run src/__tests__/contract.test.ts` — expect 12 passed, the suite named "IKnowledgeAdapter contract — knowledge-memory". <details><summary>Local gates (head cf8b70a)</summary> `node scripts/pm/dispatch-gates.mjs --repo objectstack-ai/objectstack --ran` at cf8b70a: 131 derived, 126 run, 5 NOT-MEASURED, 0 UNRUN (exit codes recorded before any pipe; the derived list is unchanged from c6e78ea). NOT MEASURED: - `check-plugin-teardown-shape --self-test` :: exit 3 — its pinned fixture commit is not in this shallow clone. - `spec check:skill-examples`, `check:dual-build-cjs-loads`, `check:published-readme-exports` :: exit 3 — they read built output of packages this worktree did not build. - `check:dts-closure` :: exit 1 — each run names the next package this worktree never built (`service-cluster-redis`, then `service-i18n`); the three touched packages' declarations are present and not listed. Everything else exit 0, including `check:test-source-alias`, `spec check:generated` (all 14 up to date), `check:tenant-audit-census`, `check:type-check-debt`, `check:query-options-erasure`, `check:slot-lookup` and `check-comment-mask-corpus` (the last four rerun with a longer local time cap after the first sweep's cap fired), `check:engine-double-contract`, `check:nul-bytes`, `check:doc-authoring`. Local-only: `check:skill-frame-freshness` exit 0. Patch round at eddd9a6 (changeset only: `@objectstack/spec` to `minor`, `Metadata-protocol: added`, `Skills-docs:` line): `check-changeset-no-major --base MERGE_BASE` against this body as the PR event exit 0 (level axis ✓); `check-empty-changeset` (self-test and base) exit 0; `check-adr-0087-registration` (self-test and base) exit 0; `check:changeset-gate-self-tests` exit 0; spec `check:generated` after a spec build exit 0, all 14 up to date. Round at 58478ca (`indexDocument` refuses a caller-supplied `docHash`; TSDoc and changeset wording to match): typecheck service-knowledge and knowledge-memory exit 0; service-knowledge 8/8 files 165/165 tests, knowledge-memory 2/2 files 20/20; ablation (refusal disabled through ablation-replace): 1 failed, exactly "indexDocument refuses a caller-supplied docHash, naming it, and writes nothing", 75 passed, restored to the HEAD blob (a first attempt was void: the suite could not load before the closure was built in the fresh worktree); spec `check:generated` exit 0; `check-changeset-no-major` against this body exit 0; `check-empty-changeset`, `check-adr-0087-registration`, `check:nul-bytes` exit 0; overlap-check clean. Round at ffc6bff (L1 REWORK 7151268664 S1–S4 and N1–N4; contract review 7151166003 S1–S2, N1–N3): - Code: a walk page that answers no list goes through `stopped(...)`; `rereadRow` throws on a non-list answer; the purge asks for a canonical-integer id again by the number. - Tests: four new — "a walk page that answers no list stops the walk", "a purge re-read that answers no list stops the purge", "the purge's re-read and delete run on the document's sync chain" (holds the purge between its re-read and its delete while a restore's event sync arrives), "a numeric record id restored during the walk is found by its number and kept; a gone one is purged". - Ablations via ablation-replace, each restored to the HEAD blob with `git diff HEAD` empty: page guard made `break` → 1 failed | 79 passed (the page test); re-read guard made `return undefined` → 1 failed (the re-read test); `serialize` made a direct call → 1 failed (the chain test); numeric re-ask deleted → 1 failed (the numeric test). - Build of spec, service-knowledge, knowledge-memory, knowledge-ragflow exit 0; typecheck of the three packages exit 0; vitest service-knowledge 8/8 files 169/169, knowledge-memory 2/2 files 20/20, knowledge-ragflow 1/1 files 10/10; spec `check:generated` exit 0 (all 14 up to date). - `dispatch-gates --ran` at ffc6bff: 131 derived, 127 run, 4 NOT-MEASURED (exit 3: `check-plugin-teardown-shape --self-test`, pinned fixture not in this shallow clone; `spec check:skill-examples`, `check:dual-build-cjs-loads`, `check:published-readme-exports`, built output of packages this worktree did not build), 0 UNRUN; `check:dts-closure` exit 0; four commands that hit the local 100 s cap reran green with a longer one. Changeset gates against this body: `check-changeset-no-major` exit 0, `check-empty-changeset` exit 0, `check-adr-0087-registration` exit 0. - Docs: `content/docs/protocol/knowledge.mdx` now says `indexDocument` refuses a carried `docHash`, and that a non-list answer stops the walk or the purge. Changeset reworded in plain terms; `purged` TSDoc lists every `null` case and what an absent key means. Round at 48ed4f1 (L1 ACCEPT 7152441226 N1–N2; contract review 7152394541 S1 and N1–N2): - S1: the numeric re-ask is removed (option b — no object schema types its `id`, so the service cannot restrict it to numeric-id objects without new spec surface); the limit is stated in `purgeDocuments`' TSDoc, `knowledge.mdx` and the changeset, and pinned by "the purge re-reads by the id text only: a numeric id restored mid-walk is not found (the stated limit)". - L1 N1 / L2 N1: the event sync's new keep on a non-list re-read is stated here, in `knowledge.mdx` and in the changeset, and pinned by "a re-read that answers no list leaves the document and warns once; it does not delete". - L2 N2: the three waits on `setTimeout(5)` in this PR's tests are gone. Two wait on the held `find` being entered (`holdNextFind().reached`). The chain case waits one `setImmediate` turn, which lets every pending promise run with no clock involved. The remaining `setTimeout(5)` is in the pre-existing "a second reindex of the same source waits" case (#37129), which this PR does not touch. - Tests: service-knowledge 8/8 files 170/170, knowledge-memory 2/2 files 20/20, knowledge-ragflow 1/1 files 10/10; typecheck of the three exit 0; build exit 0; spec `check:generated` exit 0. - Ablations via ablation-replace, each restored to the HEAD blob with `git diff HEAD` empty. Re-read guard made `return undefined`: 2 failed | 79 (the purge re-read case and the event-sync case). `serialize` made a direct call: 1 failed | 80 (the chain case, with the clock-free wait). Numeric re-ask re-added: 1 failed | 80 (the limit pin). A first numeric attempt was void because the replacement kept the anchor text; the tool refused it and restored the file. - `dispatch-gates --ran` at 48ed4f1: 131 derived, 127 run, 4 NOT-MEASURED, 0 UNRUN. The same four exit-3 prerequisites as before. Three commands that hit the 100 s local cap reran exit 0. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYmGV9ehU2Bfmw95h7E)_ <!-- signed: repo:objectstack#4 · os-justin · session_01QSeKYmGV9ehU2Bfmw95h7E --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6211ddf commit d7f299c

19 files changed

Lines changed: 1391 additions & 64 deletions

File tree

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/service-knowledge': patch
4+
'@objectstack/knowledge-memory': patch
5+
---
6+
7+
feat(service-knowledge): adapters list their documents; a complete reindex skips unchanged documents and purges the ones its source no longer has; one adapter contract test suite
8+
9+
Clause-②: yes
10+
Metadata-protocol: added
11+
Skills-docs: none — no skill under `skills/**` teaches `KnowledgeDocument`, the adapter contract or reindex; `skills/objectstack-ai/SKILL.md` teaches `KnowledgeSource` authoring only, which this change does not touch. `content/docs/protocol/knowledge.mdx` gains the members, the skip and the purge in this change.
12+
13+
Knowledge adapters can now list the documents they hold, and a full reindex uses that list to skip unchanged documents and to remove documents whose record is gone.
14+
15+
New, all optional, in `@objectstack/spec`:
16+
17+
- `IKnowledgeAdapter.listDocuments?(ctx, { cursor?, limit })` returns `{ documents, nextCursor? }`, each entry `{ documentId, docHash? }`: the documents the adapter holds for a source, one page at a time. New exported types in `@objectstack/spec/contracts`: `AdapterListDocumentsOptions`, `AdapterListedDocument`, `AdapterListDocumentsPage`.
18+
- `KnowledgeDocument.docHash?`: a hash of the document's content, title and metadata, prefixed `v1:`. The knowledge service sets it on every document it hands an adapter; the adapter stores it and returns it unchanged. `indexDocument` refuses a document that already carries a `docHash` (it throws, naming the field).
19+
- `KnowledgeReindexResult.skipped?` and `purged?`.
20+
21+
`KnowledgeService.reindexSource` for an `object` source, when the source's adapter implements `listDocuments`:
22+
23+
- does not send a document to the adapter again when its hash is unchanged, and counts it in `skipped`;
24+
- after a full run (no `limit`, no `dryRun`, every page read), deletes each listed document whose record no longer exists or no longer matches the source's `where`. Before each deletion it reads the record again; a record that exists at that moment keeps its document. A deletion never overlaps a sync of the same record. `purged` counts the deletions. Known limit: on driver-mongodb and driver-memory, a record stored under a caller-supplied numeric id is not found by that re-read, so if it was restored during the run its document is deleted until the record's next change or the next full reindex.
25+
26+
`purged` is `null` when nothing was deleted because no removal ran: the adapter has no `listDocuments`, the run had a `limit` or `dryRun`, a page failed or answered no list of rows, the source sets `refresh.onRecordChange: false`, or the adapter's listing failed (the `message` says why). If a re-read or a deletion fails, the result is `ok: false` and `purged` counts the deletions made before it.
27+
28+
The record sync (on record create, update and restore) now leaves a document in place and logs a warning when the data engine answers its re-read with something other than a list of rows; it used to delete the document.
29+
30+
`@objectstack/service-knowledge/testing` (new, test-only, ESM only; it imports `vitest`) exports `runKnowledgeAdapterContract({ name, makeAdapter, implements: { listDocuments } })`, a test suite any adapter package runs with its own factory: upsert, search and delete; `listDocuments` paging and `docHash` round-trips; and the skip and the removal through a real `KnowledgeService`. `@objectstack/knowledge-memory` implements `listDocuments` and runs the suite.
31+
32+
What to do: nothing. An adapter without `listDocuments` keeps working; its reindex sends every document, as before, and reports `purged: null`. An adapter package adds `listDocuments` (storing `docHash` as given) to get the skip and the removal, and runs the suite from `@objectstack/service-knowledge/testing` with its own factory. A caller of `indexDocument` stops setting `docHash`.

‎content/docs/protocol/knowledge.mdx‎

Lines changed: 92 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,12 @@ registers itself with that name. Adapter config (endpoint, dataset id,
158158
Canonical shapes shared by every adapter:
159159

160160
- `KnowledgeDocument` — one logical document (`id`, `sourceId`,
161-
`sourceRecordId?`, `content`, `metadata`, `permissions?`).
161+
`sourceRecordId?`, `content`, `metadata`, `permissions?`, `docHash?`).
162+
`docHash` is a hash of the assembled document — content, title and
163+
metadata, in a stable key order, behind a version prefix (`v1:`). The
164+
service computes it on every document it hands an adapter, and
165+
`indexDocument` refuses a document that already carries one; the adapter
166+
stores it and returns it as stored, and never computes or alters it.
162167
- `KnowledgeChunk` — adapter-produced chunk of a document. The framework
163168
does **not** chunk; adapters do.
164169
- `KnowledgeHit` — a search result (`chunkId`, `documentId`, `score`,
@@ -200,7 +205,8 @@ interface IKnowledgeService {
200205
the all-important `executionContext` (from the permission-aware tool
201206
execution work — see `actions-as-tools.mdx`). `KnowledgeReindexOptions`
202207
accepts `dryRun` and `limit`; `reindexSource` returns a
203-
`KnowledgeReindexResult` (`indexed`, `discovered`, `ok`, …).
208+
`KnowledgeReindexResult` (`indexed`, `discovered`, `skipped`, `purged`,
209+
`ok`, …) — see [Reindex: skip and purge](#reindex-skip-and-purge).
204210

205211
### 3.4 `IKnowledgeAdapter` (implemented by plugins)
206212

@@ -210,6 +216,10 @@ interface IKnowledgeAdapter {
210216
upsert(docs: KnowledgeDocument[], ctx: AdapterContext): Promise<void>;
211217
search(query: string, opts: AdapterSearchOptions): Promise<KnowledgeHit[]>;
212218
delete(documentIds: string[], ctx: AdapterContext): Promise<void>;
219+
listDocuments?(
220+
ctx: AdapterContext,
221+
opts: { cursor?: string; limit: number },
222+
): Promise<{ documents: { documentId: string; docHash?: string }[]; nextCursor?: string }>;
213223
healthCheck?(): Promise<{ ok: boolean; message?: string }>;
214224
}
215225
```
@@ -219,6 +229,34 @@ management, no chunk strategy, no rerank toggles. Those are the
219229
adapter's private concerns. Adapters that need extra knobs expose them
220230
in their plugin options.
221231

232+
Every member past `upsert` / `search` / `delete` is optional (ADR-0161
233+
K8): an adapter that lacks one keeps working, and the service does what it
234+
did before that member existed. `listDocuments` lists the documents the
235+
adapter holds for a source, a page of at most `limit` entries at a time, each
236+
with the `docHash` it was stored with; `nextCursor` is absent once the
237+
listing is complete. A document written while a listing runs may be missing
238+
from it — the safe direction, since a missing entry is never purged.
239+
240+
**The contract test suite.** Every adapter package runs the same suite
241+
against its own factory:
242+
243+
```ts
244+
import { runKnowledgeAdapterContract } from '@objectstack/service-knowledge/testing';
245+
246+
runKnowledgeAdapterContract({
247+
name: 'my-adapter',
248+
makeAdapter: () => new MyAdapter(/* a fresh, empty store */),
249+
implements: { listDocuments: true },
250+
});
251+
```
252+
253+
It covers upsert / search / delete, `listDocuments` page boundaries and
254+
`docHash` round-trips, and — through a real `KnowledgeService` — the skip and
255+
the purge below. `implements` declares the optional members, and the suite
256+
checks the declaration against the adapter. `./testing` is a test-only,
257+
ESM-only entry that imports `vitest`; nothing in the runtime entry reaches it.
258+
`knowledge-memory` runs it as the reference implementation.
259+
222260
---
223261

224262
## 4. Plugin model
@@ -392,8 +430,7 @@ then rolls back, the index is wrong in one of two ways:
392430

393431
The row's next event or a `reindexSource` repairs a row that still exists. A
394432
document built from an **insert** that rolled back has no row left to repair it
395-
from, and a reindex removes no documents, so it stays until the index purge
396-
([#37096](https://github.com/objectstack-ai/objectstack/issues/37096)) lands.
433+
from; it stays until a complete reindex purges it (below).
397434

398435
`data.record.restored` is
399436
published after the restore's own unit has committed.
@@ -412,12 +449,54 @@ published after the restore's own unit has committed.
412449
than per-record events. A knowledge index is a per-record projection and
413450
`matched: 40` names no record, so there is no upsert or delete to derive —
414451
the service logs a warning naming the object and count instead of failing
415-
silently. An explicit `reindexSource` refreshes the documents of rows that
416-
still exist and match; it removes no documents, so those of deleted rows (or
417-
of rows that stopped matching) stay until the index purge
418-
([#37096](https://github.com/objectstack-ai/objectstack/issues/37096)) lands.
452+
silently. A complete `reindexSource` refreshes the documents of rows that
453+
still exist and match, and — over an adapter that implements
454+
`listDocuments` — purges those of deleted rows and of rows that stopped
455+
matching. Over an adapter that does not, they stay in the index.
419456
</Callout>
420457

458+
### Reindex: skip and purge
459+
460+
A `reindexSource` of an `object` source over an adapter that implements
461+
`listDocuments` first lists what the adapter holds for the source (document
462+
id → stored `docHash`), then walks the object's rows page by page:
463+
464+
- **Skip.** A row whose document's computed `docHash` equals the listed one is
465+
not written again; the result counts it in `skipped`. Every other document
466+
is written (`indexed`). A listed entry without a `docHash` reads as changed.
467+
- **Purge.** After a **complete** walk — no `limit`, no `dryRun`, no failed
468+
page — every document listed before the walk that the walk did not see is a
469+
candidate. Each candidate is confirmed by the same re-read the event sync
470+
makes (the source's `where` AND the record id, under the system context) and
471+
deleted only when that finds no row. A row created or restored during the
472+
walk keeps its document: if it was listed, the re-read finds it; if it was
473+
not, it was never a candidate. The purge of a document waits for any
474+
in-flight event sync of the same document. `purged` counts the deletions.
475+
- **Known limit: numeric record ids.** The purge reads the record id back from
476+
the document id as text and re-reads by that text. On driver-mongodb and
477+
driver-memory, which do not equate `'5'` with `5`, a row stored under a
478+
caller-supplied numeric id is not found by that re-read; if such a row was
479+
restored (or came back into `where`) after the walk read past it, its
480+
document is deleted. The row itself is untouched, and its document returns at
481+
the row's next event or the next complete reindex. Platform-minted ids are
482+
text on every driver, so this needs a caller-supplied numeric id.
483+
- **`purged: null`** means no purge ran: a walk with a `limit` or a `dryRun`,
484+
a failed walk, a source with `refresh.onRecordChange: false` (an external
485+
indexer owns its index), or an adapter without `listDocuments` — which also
486+
skips nothing, the walk otherwise unchanged. A listing that fails skips and
487+
purges nothing either, and the result's `message` says why.
488+
- A listed document whose id is not one the source derives from a record
489+
(`<sourceId>:<recordId>`) is never purged, since no row can confirm it; the
490+
result's `message` counts such documents.
491+
492+
A re-read or delete that fails stops the purge — a re-read that answers no
493+
list of rows counts as failed, never as "no row" — and the result is
494+
`ok: false`, `purged` counts the deletions made before it, and the `message`
495+
names the document. A walk page that answers no list of rows stops the walk
496+
the same way, with `purged: null`, rather than ending it as if the source were
497+
empty. The event sync shares that re-read: when it answers no list of rows, the
498+
sync leaves the document in place and logs a warning, rather than deleting it.
499+
421500
### Retention deletes are covered by a reap guard
422501

423502
The platform's own predicate delete — `LifecycleService` reaping rows past
@@ -445,9 +524,10 @@ returns the ids it confirms. Rows it does not confirm stay put.
445524
external indexer owns is never a reason to hold up another package's
446525
retention.
447526

448-
Application-level predicate writes remain uncovered: de-indexing them needs an
449-
adapter-side enumeration capability that no adapter declares today, and that
450-
surface stays unbuilt until a real `object` source calls for it.
527+
Application-level predicate writes are not de-indexed as they happen. Their
528+
stale documents are removed by the next complete `reindexSource`, over an
529+
adapter that implements `listDocuments` ([Reindex: skip and
530+
purge](#reindex-skip-and-purge)); nothing runs that reindex on a schedule yet.
451531

452532
`file` / `http` sources rely on explicit `reindexSource` calls
453533
(typically triggered by a cron job, a Console button, or a webhook).
@@ -467,7 +547,7 @@ up.
467547
| `KnowledgeSourceSchema` | ✅ | object / file / http kinds |
468548
| `KnowledgeDocument` / `Chunk` / `Hit` | ✅ | Canonical shapes |
469549
| `IKnowledgeService` contract | ✅ | search / index / delete / reindex |
470-
| `IKnowledgeAdapter` contract | ✅ | upsert / search / delete / healthCheck |
550+
| `IKnowledgeAdapter` contract | ✅ | upsert / search / delete / healthCheck; optional `listDocuments` with a contract test suite (`@objectstack/service-knowledge/testing`) |
471551
| `service-knowledge` orchestrator | ✅ | Adapter routing, RLS wrapper, sync |
472552
| `knowledge-memory` | ✅ | In-process; deterministic fake embedder |
473553
| `knowledge-ragflow` | ✅ | Minimal REST adapter (datasets + chunks + retrieval) |

‎content/docs/references/ai/knowledge-document.mdx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ const result = KnowledgeChunkSchema.parse(data);
6060
| **title** | `string` | optional | |
6161
| **metadata** | `Record<string, any>` | optional (default: `{}`) | |
6262
| **permissions** | `string[]` | optional | |
63+
| **docHash** | `string` | optional | Service-computed hash of the assembled document (content, title, metadata); stored and returned as stored by the adapter |
6364

6465

6566
---
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
// The `IKnowledgeAdapter` contract suite (ADR-0161 K8, rule 1), run against the
4+
// reference adapter. Every adapter package runs the same suite with its own
5+
// factory; a fresh adapter per case keeps the cases independent.
6+
7+
import { runKnowledgeAdapterContract } from '@objectstack/service-knowledge/testing';
8+
import { KnowledgeMemoryAdapter } from '../index';
9+
10+
runKnowledgeAdapterContract({
11+
name: 'knowledge-memory',
12+
makeAdapter: () => new KnowledgeMemoryAdapter('under_test'),
13+
implements: { listDocuments: true },
14+
});

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import type {
44
IKnowledgeAdapter,
55
IKnowledgeService,
66
AdapterContext,
7+
AdapterListDocumentsOptions,
8+
AdapterListDocumentsPage,
79
AdapterSearchOptions,
810
} from '@objectstack/spec/contracts';
911
import type {
@@ -20,6 +22,11 @@ import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts';
2022
*
2123
* Deterministic — same input always produces the same hits — so it's
2224
* great for tests and reference implementations. **Don't use in prod.**
25+
*
26+
* The reference implementation of `listDocuments` (ADR-0161 K8, item 1): it
27+
* stores each document's `docHash` as given and lists it back as stored, in
28+
* document-id order, the cursor being the last id of the page before. It runs
29+
* the contract suite of `@objectstack/service-knowledge/testing`.
2330
*/
2431
export class KnowledgeMemoryAdapter implements IKnowledgeAdapter {
2532
readonly id: string;
@@ -55,6 +62,29 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter {
5562
);
5663
}
5764

65+
async listDocuments(ctx: AdapterContext, opts: AdapterListDocumentsOptions): Promise<AdapterListDocumentsPage> {
66+
if (!Number.isInteger(opts.limit) || opts.limit < 1) {
67+
throw new RangeError(`listDocuments: limit must be a positive integer, got ${String(opts.limit)}`);
68+
}
69+
// One entry per document, from its first chunk (every chunk carries the
70+
// document's hash), in id order so a cursor stays valid across writes.
71+
const byDoc = new Map<string, string | undefined>();
72+
for (const c of this.store.get(ctx.source.id) ?? []) {
73+
if (!byDoc.has(c.documentId)) byDoc.set(c.documentId, c.docHash);
74+
}
75+
const ids = [...byDoc.keys()]
76+
.filter((id) => opts.cursor === undefined || id > opts.cursor)
77+
.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
78+
const page = ids.slice(0, opts.limit);
79+
return {
80+
documents: page.map((documentId) => {
81+
const docHash = byDoc.get(documentId);
82+
return docHash === undefined ? { documentId } : { documentId, docHash };
83+
}),
84+
...(ids.length > page.length ? { nextCursor: page[page.length - 1] } : {}),
85+
};
86+
}
87+
5888
async search(query: string, opts: AdapterSearchOptions): Promise<KnowledgeHit[]> {
5989
const chunks = this.store.get(opts.source.id) ?? [];
6090
if (chunks.length === 0) return [];
@@ -94,6 +124,8 @@ interface ChunkRecord {
94124
chunkId: string;
95125
documentId: string;
96126
sourceRecordId?: string;
127+
/** The document's `docHash`, stored as given (ADR-0161 K8, item 2). */
128+
docHash?: string;
97129
content: string;
98130
title?: string;
99131
metadata: Record<string, unknown>;
@@ -134,6 +166,7 @@ function chunkAndEmbed(doc: KnowledgeDocument): ChunkRecord[] {
134166
chunkId: `${doc.id}#${idx}`,
135167
documentId: doc.id,
136168
sourceRecordId: doc.sourceRecordId,
169+
docHash: doc.docHash,
137170
content,
138171
title: doc.title,
139172
metadata: doc.metadata ?? {},

‎packages/plugins/knowledge-memory/vitest.config.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,15 @@ export default defineConfig({
2525
{ find: /^@objectstack\/core\/logger$/, replacement: path.resolve(__dirname, '../../core/src/logger.ts') },
2626
{ find: '@objectstack/core/egress', replacement: path.resolve(__dirname, '../../core/src/egress.ts') },
2727
{ find: '@objectstack/core', replacement: path.resolve(__dirname, '../../core/src/index.ts') },
28+
// `./testing` (the adapter contract suite) BEFORE the bare package, and both
29+
// anchored: a string `find` matches by PREFIX, so the bare entry would
30+
// resolve the subpath to `…/src/index.ts/testing` — ENOTDIR at run time.
2831
{
29-
find: '@objectstack/service-knowledge',
32+
find: /^@objectstack\/service-knowledge\/testing$/,
33+
replacement: path.resolve(__dirname, '../../services/service-knowledge/src/testing.ts'),
34+
},
35+
{
36+
find: /^@objectstack\/service-knowledge$/,
3037
replacement: path.resolve(__dirname, '../../services/service-knowledge/src/index.ts'),
3138
},
3239
// #9457: ONE anchored rule for every `@objectstack/spec` namespace, in place

‎packages/plugins/knowledge-ragflow/vitest.config.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@ export default defineConfig({
2525
{ find: /^@objectstack\/core\/logger$/, replacement: path.resolve(__dirname, '../../core/src/logger.ts') },
2626
{ find: '@objectstack/core/egress', replacement: path.resolve(__dirname, '../../core/src/egress.ts') },
2727
{ find: '@objectstack/core', replacement: path.resolve(__dirname, '../../core/src/index.ts') },
28+
// The published `./testing` subpath BEFORE the bare package, which is a
29+
// PREFIX match with a FILE replacement (ENOTDIR otherwise).
30+
{
31+
find: /^@objectstack\/service-knowledge\/testing$/,
32+
replacement: path.resolve(__dirname, '../../services/service-knowledge/src/testing.ts'),
33+
},
2834
{
2935
find: '@objectstack/service-knowledge',
3036
replacement: path.resolve(__dirname, '../../services/service-knowledge/src/index.ts'),

‎packages/services/service-knowledge/package.json‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,16 @@
1717
"types": "./dist/index.d.cts",
1818
"default": "./dist/index.cjs"
1919
}
20+
},
21+
"./testing": {
22+
"import": {
23+
"types": "./dist/testing.d.ts",
24+
"default": "./dist/testing.js"
25+
}
2026
}
2127
},
2228
"scripts": {
23-
"build": "tsup --config ../../../tsup.config.ts && node ../../../scripts/check-dts-emitted.mjs",
29+
"build": "rm -rf dist && tsup && node ../../../scripts/check-dts-emitted.mjs",
2430
"test": "vitest run",
2531
"typecheck": "tsc --noEmit && pnpm check:test-typecheck",
2632
"check:test-typecheck": "tsx ../../../scripts/check-test-typecheck.mts --self-test && tsx ../../../scripts/check-test-typecheck.mts --package packages/services/service-knowledge --project tsconfig.test.json"

0 commit comments

Comments
 (0)