Skip to content

fix(service-knowledge): reindexSource pages an object source by id, one walk per source at a time - #37129

Merged
objectstack-fleet[bot] merged 5 commits into
mainfrom
claude/issue-36992-reindex-paging
Nov 24, 2026
Merged

objectstack-fleet[bot] merged 5 commits into
mainfrom
claude/issue-36992-reindex-paging

Conversation

@objectstack-fleet

@objectstack-fleet objectstack-fleet Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #36992

Clause-②: no
Metadata-protocol: none

维护者速读

  • 用户能看到什么变化:挂了知识检索的应用,管理员手动重建某个知识源时,系统改为每次读 100 条、写 100 条,大表不再一次全读进内存;同一知识源的两次重建会排队依次执行;文档和告警不再声称重建能清掉已删除记录的检索内容。
  • 为什么做:知识检索平台化专题第一阶段的「数据多了也不能崩」——原来重建一次把整张表读进内存再一次性交给索引服务,数据量大时会撑爆内存或超时。
  • 出错会怎样:只影响挂了知识检索服务的应用的手动重建;某一页失败时重建停在那一页并在结果里说明是哪一页,之前写入的不回退;已删除记录的旧内容仍要等「索引清理」那张卡落地才会被清掉;改动可直接撤回。
  • 要你做的:无。

What changes

KnowledgeService.reindexSource (packages/services/service-knowledge/src/knowledge-service.ts) for an object source, per card items 1-5:

  • Keyset paging by id (item 1). The walk reads at most REINDEX_PAGE_SIZE = 100 rows per find(object, { where, orderBy: [{ field: 'id', order: 'asc' }], limit }, { context: system }). Page 1 sends the source's where alone. Every later page sends { $and: [where, { id: { $gt: cursor } }] } (or just the cursor condition when the source has no where), where the cursor is the previous page's last id, kept in its own type. Each page is upserted in its own adapter.upsert(docs, { source, reason: 'reindex' }) before the next read. Every find carries a limit, and no upsert holds more than one page. Each row goes through the same recordToDocument(source, objSource, row, this.schemaFor(object)) gate the event sync uses; no second builder was added. The system context now travels in the trailing options argument (the IDataEngine contract's position) and no longer inside the query behind an as never cast.
  • Only an empty page ends the walk. A page that comes back short of its limit is followed by the next read: find does not promise min(limit, remaining) rows, because an afterFind hook may drop rows from a page (packages/objectql/src/engine-find.ts). So a 101-row object takes three reads, the last one empty.
  • Failure ends the run with ok: false and names the page (item 1). A read, a document build or an upsert that throws returns { ok: false, object, discovered, indexed, message }. The message reads reindex of source 'S' stopped at page N (after id 'X'): ... with the cause (an Error's message, any other thrown value via String(...)), and the counts cover the pages done before it. Those pages stay in the index. Two further stops prevent an endless walk: a page whose last row has no id, and a last id that did not move past the cursor (an engine that ignored the id condition). Each returns ok: false and names its page. Before this change, a failure threw out of reindexSource.
  • What is serialized, and what is not (item 1). The record sync's per-document promise chain from fix(service-knowledge): record-change sync honours the source where; a restored record re-enters the index #37075 is now one module-level helper, chainAfter(tails, key, task), which returns the task's own outcome while the chain itself never rejects. serializeRecordSync delegates to it unchanged in meaning, and reindexSource chains on a separate reindexTails map keyed by source id. So a second reindex of the same source waits for the first and their pages never interleave; different sources still run concurrently. Record events do NOT wait for a walk. A row updated or deleted between a page's read and that page's upsert is written back from the older read, and a deleted row's document then stays as a ghost until the index purge (service-knowledge: adapters list their documents; a complete reindex skips unchanged documents and purges the ones its source no longer has; one contract test suite #37096). That race predates this PR, and paging narrows its window from the whole object to one page. The jsdoc and the changeset say exactly this.
  • limit / dryRun (item 2). opts.limit keeps its total-cap meaning: each read asks for min(100, limit - discovered), and the walk stops at the cap without an extra read. A fractional limit is floored. A negative or non-finite one (-1, NaN, Infinity) is refused with ok: false and nothing is read; before this change such a value went straight to find. dryRun calls count(object, { where }, { context }), reads no rows, and reports min(count, limit).
  • Page size (item 3), my reading. Item 3 said to match the embedder's per-request cap until the embedder-openai sibling landed, then follow it. That sibling (embedder-openai: embed() sends every input in one request; providers with a per-request cap reject a reindex #36995) landed as fix(embedder-openai): batch embed() input at the provider's per-request cap #37037, and OpenAIEmbedder now splits a larger input set into requests of its own cap. So the page size is no longer an embedder-correctness bound; it bounds memory and the size of one adapter call. I kept 100 as a module constant and did not add an option: KnowledgeReindexOptions is a spec contract, and KnowledgeServiceOptions is not forwarded from any config a host writes. REINDEX_PAGE_SIZE is exported from the module for the tests only and is not re-exported from index.ts, so the published dist/index.d.ts export list is unchanged.
  • Result shape (item 4). { indexed, discovered, object?, ok, message? } is unchanged. No fields were added, so no published type widens.
  • No purge (item 5). A reindex still removes no documents, and no adapter-contract member was added. The knowledge-platform ADR (ADR: knowledge platform boundary — the platform owns document assembly, sync and reconcile, structural split and record-level return; knowledge_source becomes a governed type #37001 / docs(adr): ADR-0161 — the knowledge platform boundary; knowledge_source becomes a governed metadata type #37119) is not merged.
  • No surface claims a reindex removes documents any more. These sites are reworded; behaviour is unchanged. Each now says a reindex refreshes the rows that still exist and match, and that the documents of deleted (or no-longer-matching) rows wait for the index purge (service-knowledge: adapters list their documents; a complete reindex skips unchanged documents and purges the ones its source no longer has; one contract test suite #37096):
    • content/docs/protocol/knowledge.mdx: the predicate-write callout ("Repair such an index with an explicit reindexSource") and the rolled-back-write passage (a document built from an insert that rolled back has no row left to repair it from).
    • The same rolled-back-write passage in handleRecordUpsert's jsdoc.
    • The bulk-write warning in knowledge-service-plugin.ts. As a runtime string it names the purge in words, with no tracker number. Its existing pins in event-sync-data-events.test.ts still hold.

Tests

src/__tests__/knowledge-service.test.ts adds a new top-level describe('KnowledgeService — the reindex walk pages by id') (25 cases) in the existing harness file. Its engine double throws on any find without a positive limit, without orderBy id asc, or without the system context, and on any operator it does not implement. It orders numbers numerically and everything else by string. Rows are inserted in shuffled order, so the walk sees only the engine's ordering.

  • Boundaries:
    • 0 rows: one read, no upsert.
    • Exactly 100 rows: one upsert of 100, then a page-2 read of { id: { $gt: 'r099' } } that comes back empty.
    • 101 rows: upserts of 100 then 1, each row exactly once, in id order, then a third, empty read of { id: { $gt: 'r100' } }. Every read is limited to 100, every upsert holds at most 100, and the reason is reindex.
  • A short page is not the end: the first full page comes back with 99 of its 100 rows (the drop an afterFind hook can make), and every later row is still upserted (pages 99/100/50, 249 rows, 4 reads).
  • Numeric ids 1..150: the cursor keeps the number ({ id: { $gt: 100 } }, then { id: { $gt: 150 } }), and the pages follow numeric order.
  • The source's where is ANDed with the cursor (the exact page-2 where is asserted).
  • limit:
    • 150 / 100 / 30 / 0 read [100,50] / [100] / [30] / nothing.
    • A limit above the row count reads to the end.
    • 150.7 is floored to 150.
    • -1, NaN and Infinity are refused with ok: false (plain and dryRun), with no find, no count and no upsert.
  • dryRun uses count under the where, capped by limit, with zero find calls.
  • Failures, each ok: false with the counts of the pages done before it:
    • A failed read on page 2 and a failed upsert on page 2: the message names page 2 and after id 'r099', the counts are 100/100, and the next walk after a failure runs (the lock is released).
    • A document build that throws on page 2.
    • A thrown non-Error is reported by its text, never as undefined.
  • An engine that ignores the cursor ends the walk at page 2 instead of looping. A last row with no id ends the walk after page 1.
  • A concurrent second reindex of the same source makes no read while the first one's read is held, and the upsert order is r000+100, r100+50, r000+100, r100+50. Walks of different sources do not wait for each other.

The two older reindex tests were updated for the new call shape. The context is read from the trailing argument. dryRun asserts that count is called and find is not. Their doubles now answer an empty next page, as a cursor-honouring engine does: they used to return the same rows for every read, which this walk now correctly reports as a cursor that did not advance.

Acceptance notes

  • Cursor order on a SQL driver, checked once. The zone confirmed that a single check is enough. service-knowledge cannot reach a SQL driver: its dependencies are core, objectql, platform-objects, service-settings and spec. A committed test would need @objectstack/driver-sql as a devDependency plus a pnpm-lock.yaml importer entry, and the lockfile is outside this PR's file surface. So the check is a scratch measurement against this branch's source, re-run on the current head (readings under Verification).
  • KnowledgeReindexResult.ok's jsdoc in packages/spec ("an adapter / source check prevented the run") now also covers a failed page and a refused limit. That is outside this PR's file surface, and the wording is still broadly true.
  • dryRun's count is not wrapped: a failing count still rejects, as the old dryRun read did. The card's ok: false rule is about pages.

Verification

Read first (risk order):

  1. knowledge-service.ts walkObjectSource: the loop's exits (empty page, cap, and the two non-advance stops) and the cursor where composition.
  2. knowledge-service.ts chainAfter and serializeRecordSync: the event-sync chain now goes through the shared helper.
  3. knowledge-service.test.ts pagedEngine: the double's refusals are what make "every find has a limit" fail loudly.

Two-minute check: run pnpm --filter @objectstack/service-knowledge exec vitest run src/__tests__/knowledge-service.test.ts. Expect 53 passing tests, 25 of them under the reindex walk pages by id.

Every reading below was taken at head 9e24b96c, the final commit.

Package tests and typecheck
pnpm --filter @objectstack/service-knowledge test
 Test Files  8 passed (8)
      Tests  142 passed (142)
pnpm --filter @objectstack/service-knowledge typecheck
check:test-typecheck: OK — 0 file(s) / 0 error(s) / 0 pinned signature(s)
Ablations (source-resolved subject: the test imports ../knowledge-service.js, so no dist is on the path; each mutation made by scripts/ablation-replace.mjs; each restore proven by blob == HEAD and an empty git diff HEAD)
A4 (9e24b96c) restore `if (rows.length < want) break;` after the page upsert
   -> 3 failed (one page + 1, the short-page pin, numeric ids), 50 passed
   (a first attempt was refused by the tool before any test ran: its replacement contained the anchor, so the anchor count could not drop)
A1-A3 (99518e66, before this round; the code they mutate is unchanged)
A1 delete `limit: want,` from the page read   -> 12 failed (the double refuses an unbounded find)
A2 bypass chainAfter on reindexTails          -> 1 failed  (the never-interleave pin)
A3 drop the `id > cursor` condition           -> 7 failed; the walk still terminated (the non-advance stop held)
SQL driver: one scratch run of ObjectQL + SqlDriver (better-sqlite3, :memory:) against this branch's source at 9e24b96

The run used 250 rows of a kb_note object, inserted in shuffled order: 16 explicit ids chosen to stress ordering (a A b B r9 r10 r100 Z z 0 9 10 _x -y r_1 r-1) plus 234 engine-generated ids. 191 rows have status = 'open'. The fourth read is the empty one that ends the walk.

rows 250 result {"ok":true,"object":"kb_note","discovered":250,"indexed":250}
pages 100,100,50 finds 4 maxPage 100 pageSize 100
each row once true
walk order == engine id order true
every find limited true
page2 query {"where":{"id":{"$gt":"MutQpGXcbru5V4DJ"}},"orderBy":[{"field":"id","order":"asc"}],"limit":100}
open: rows 191 result {"ok":true,"object":"kb_note","discovered":191,"indexed":191} once true page2 query {"where":{"$and":[{"status":"open"},{"id":{"$gt":"XhVtf05MZ_zLLW3V"}}]},"orderBy":[{"field":"id","order":"asc"}],"limit":100}
limit 150 {"ok":true,"object":"kb_note","discovered":150,"indexed":150} reads 100,50
dryRun {"ok":true,"object":"kb_note","discovered":191,"indexed":0,"message":"dryRun=true; no documents pushed."}
Local gate subset (dispatch-gates --commands, derived from merge base eec6fb3, 5 paths): 100 derived, 98 exit 0, 2 NOT MEASURED
dispatch-gates --ran: 100 derived famil(ies) accounted for — 98 run, 2 NOT-MEASURED (2 DERIVED from a recorded exit 3)
NOT MEASURED: pnpm check:dual-build-cjs-loads, reason: PREREQUISITE NOT MET (64 packages have no dist/; reads the whole monorepo's built output)
NOT MEASURED: pnpm --filter @objectstack/spec run check:skill-examples, reason: PREREQUISITE NOT MET (client / client-react have no dist/; selected by the docs page)
doc authoring guard: 23493 customer-facing string(s) ... clean — no internal issue-id references
check-nul-bytes: OK (no raw ASCII control bytes)
eslint --no-inline-config on the three changed source files: exit 0

CI runs both NOT MEASURED families on a full build.


Generated by Claude Code

@github-actions github-actions Bot added size/m documentation Improvements or additions to documentation tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Nov 24, 2026
@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 1 package(s): @objectstack/service-knowledge, touching 8 documentable anchor(s).

2 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:

  • content/docs/ai/knowledge-rag.mdx (via KnowledgeService (symbol, a top-level class))
  • content/docs/protocol/knowledge.mdx (via KnowledgeService (symbol, a top-level class), reindexSource (symbol, a method of class KnowledgeService))
What this run could not see
  • 1 name(s) were too generic to anchor anything (single lowercase words)
  • the SDK route bridge reached 69 of 252 client-bound route-ledger rows — the other 183 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 183: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 124 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 4 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json 517e4153c6e8e68cd194c3a2321476da9bb9b332 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from 0240378548e98d5fe7b276005a1c411963f38033 — the merge of head 9e24b96c22ad3f8ea1707543939338489f7af2a5 into base 517e4153c6e8e68cd194c3a2321476da9bb9b332, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# while this PR is open — GitHub drops the merge commit once it closes
git fetch origin 0240378548e98d5fe7b276005a1c411963f38033 && git checkout 0240378548e98d5fe7b276005a1c411963f38033
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 517e4153c6e8e68cd194c3a2321476da9bb9b332 9e24b96c22ad3f8ea1707543939338489f7af2a5 && git checkout -B drift-repro 517e4153c6e8e68cd194c3a2321476da9bb9b332 && git merge --no-ff 9e24b96c22ad3f8ea1707543939338489f7af2a5

node scripts/docs-audit/affected-docs.mjs --json 517e4153c6e8e68cd194c3a2321476da9bb9b332

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

Advisory only, and a precision-first one (#9192): a page is listed because it names a
symbol, wire route or SDK method this diff touched — not because it mentions a changed
package. Each row says which anchor put it there, so a wrong row is reportable rather than
merely annoying. To re-verify, run the docs-accuracy-audit workflow scoped to these files:
node scripts/docs-audit/affected-docs.mjs 517e4153c6e8e68cd194c3a2321476da9bb9b332 → pass the list as
args.docs, on the commit named under Which tree this was computed on.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpRrYuqSLCvbSk9zrL

Final head for L1 (2026-11-24T22:00Z): 99518e665ef655150b07d968de1a8f97975abba7 — check-runs on it: 36 success, 16 skipped, 0 failure, 0 pending. Area: a4-K.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ

席位核对 — REWORK · L1 · head 99518e665ef655150b07d968de1a8f97975abba7 · 2026-11-24T22:08Z

Requested by zone a4-K (7145688334) for card #36992.

Delivered and correct: every card item is in (knowledge-service.ts); the sort is explicit (orderBy id asc on every page) and the test double refuses its absence; the cursor keeps the id's own type and the no-advance guard checks equality only, never a JS comparison that could disagree with a database collation; where composes with $and exactly as the #36991 sync does; the system context goes in the contract's trailing argument; the two promise chains are separate maps, so no deadlock; where, orderBy, limit and count all push down to the engine (Prime Directive 5); a limit of 150 reads 100 then 50 with no extra read; no result field and no adapter contract member added. The three ablations re-derive as stated. patch, Clause-②: no, Metadata-protocol: none: right. Check-runs: 36 success, 16 expected skip, 0 failed. K: 6.

M1 (must-fix) — if (rows.length < want) break; (knowledge-service.ts ~311) ends the walk with ok:true whenever a page comes back short. find does not promise min(limit, remaining) rows: an afterFind handler may replace the result (packages/objectql/src/engine-find.ts ~654-673; pinned in engine-find-hook-result-shape.test.ts), so one dropped row silently leaves every later row out of the index — a regression from the single unbounded read this replaces. Fix: end only on an empty page or at the cap; pin a page that returns 99 of a full 100 with every later row still upserted; ablate by restoring the break; the 101-row test then expects three reads.
S1 (should-fix) — the lock claim (knowledge-service.ts ~199-203 and the changeset's "One reindex per source" bullet: "pages never interleave (the same promise chain as the record sync)") overstates it: walks share chainAfter, not the record-sync chain, and record events never wait for a walk, so a row deleted or updated between a page's read and its upsert is written back from the older read (a deleted row becomes a ghost document until the purge, #37096). The race predates this PR and paging narrows it. Reword to what is enforced: same-source walks wait for each other; record events do not wait; name #37096.
S2 (should-fix) — the "reindex repairs bulk deletes" drift is carried on the wrong card and has three sites: content/docs/protocol/knowledge.mdx ~411, the rolled-back-insert passage ~386-392, and the runtime warning in knowledge-service-plugin.ts ~282. The purge is #37096 (epic row 2), not the ADR #37001. Either trim ~411 here (inside the claimed surface) or record all three sites on #37096 — not on #37001.

Nits: N1 the new describe has 17 cases, not 16 (body and report); N2 recordToDocument runs outside the page's try, and (err as Error).message reads undefined for a thrown non-Error — bring both under the ok:false path; N3 normalise limit (floor, clamp; a negative or NaN now returns a silent ok:true, 0); N4 one case with numeric ids 1..150.

The zone's two questions: (a) "checked once" for the SQL cursor order is enough — no follow-up card; add one line on #37100 asking for a reindex-over-a-real-driver case (PostgreSQL non-C collation is where it can differ). (b) see S2.

Delta L1 on the new head.

…imit normalised; docs no longer claim a reindex removes documents

Claude-Session: https://claude.ai/code/session_01QSeKYpRrYuqSLCvbSk9zrL
Co-authored-by: Claude <noreply@anthropic.com>
@github-actions github-actions Bot added size/l and removed size/m labels Nov 24, 2026
…age; changeset states what is serialized

Claude-Session: https://claude.ai/code/session_01QSeKYpRrYuqSLCvbSk9zrL
Co-authored-by: Claude <noreply@anthropic.com>
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpRrYuqSLCvbSk9zrL

Final head for delta L1 (2026-11-24T22:47Z): 9e24b96c22ad3f8ea1707543939338489f7af2a5 — check-runs on it: 40 success, 15 skipped, 0 failure, 0 pending. Area: a4-K. PR body updated to this head.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ

席位核对 — ACCEPT · L1 · head 9e24b96c22ad3f8ea1707543939338489f7af2a5 · 2026-11-24T22:48Z

Delta L1 for card #36992 over the REWORK at 99518e665e (7145865808), requested by zone a4-K (7146650869).

  • M1: closed. Only an empty page ends the walk (the short-page break is gone, with a comment naming why: an afterFind hook may drop rows); a walk now ends on an empty page or the cap. Pinned: a page that lost a row to a hook does not stop the walk; the ablation restoring the break turns 3 cases red.
  • S1: closed. The doc comment says what is enforced: same-source walks wait for each other (a per-source chainAfter chain), record events do not wait for a walk, and a row changed between a page's read and its upsert is written back from the older read — a deleted row's document stays as a ghost until the purge, service-knowledge: adapters list their documents; a complete reindex skips unchanged documents and purges the ones its source no longer has; one contract test suite #37096.
  • S2: closed. No sentence says a reindex removes documents: content/docs/protocol/knowledge.mdx (the predicate-write passage and the rollback passage) and the runtime warning in knowledge-service-plugin.ts now say a reindex refreshes rows that still exist and match and removes none; the rest waits for service-knowledge: adapters list their documents; a complete reindex skips unchanged documents and purges the ones its source no longer has; one contract test suite #37096.
  • N1–N4: done. The case count is corrected; recordToDocument runs under the page's ok:false path and a thrown non-Error is reported by its text (errorText), both pinned; limit is floored when fractional and refused with ok:false when negative or non-finite (pinned); numeric ids 1..150 page in numeric order.
  • The previous head's three reds (6ffdf21e): Test Core 9/10 was this PR's (the legacy reindex doubles returned the same rows each page, now answering an empty next page); the other two were aggregates cancelled by the new push.
  • Gates. Check-runs at this head: 41 success, 17 expected skip, 0 failed, 1 pending — the PR-body check re-triggered by the body edit; the zone confirms it green before landing. Landing K: 10.
  • No must-fix, no should-fix. The zone lands it once that check is green.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpRrYuqSLCvbSk9zrL

Landing — PR #37129 at head 9e24b96c22ad3f8ea1707543939338489f7af2a5 (2026-11-24T22:49Z), on delta ACCEPT 7146681480. Area: a4-K.

Probe Reading
check-runs at this head 42 success, 17 skipped, 0 failure, 0 pending (the re-triggered PR-body check now green)
check-governed-merges.mjs --pr 37129 NOT governed, 0 of 5 paths; 626 changed lines ≤ 3000
landing-k.mjs --pr 37129 K = 5 < 15; locale leg none; shared-budget leg none

State: ready + auto-merge; #36992 closes on merge via Fixes.

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 24, 2026 22:50
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 24, 2026
Merged via the queue into main with commit bee9b68 Nov 24, 2026
60 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/issue-36992-reindex-paging branch November 24, 2026 23:22
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…index skips unchanged documents and purges stale ones; adapter contract suite (objectstack-ai#37164)

Fixes objectstack-ai#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 objectstack-ai#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
(objectstack-ai#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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/l tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

service-knowledge: reindexSource reads the whole object in one unbounded find and upserts it in one call

2 participants