You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit d7f299c
Browse filesBrowse the repository at this point in the historyBrowse 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>
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`.
|`IKnowledgeAdapter` contract | ✅ | upsert / search / delete / healthCheck; optional `listDocuments` with a contract test suite (`@objectstack/service-knowledge/testing`)|
|**docHash**|`string`| optional | Service-computed hash of the assembled document (content, title, metadata); stored and returned as stored by the adapter |
0 commit comments