Repository navigation
fix(service-knowledge): record-change sync honours the source where; a restored record re-enters the index - #37075
Conversation
…where; restored rows re-enter Claude-Session: https://claude.ai/code/session_01QSeKYpRrYuqSLCvbSk9zrL Co-authored-by: Claude <noreply@anthropic.com>
… transaction ordering; changeset Claude-Session: https://claude.ai/code/session_01QSeKYpRrYuqSLCvbSk9zrL Co-authored-by: Claude <noreply@anthropic.com>
📓 Docs Drift CheckThis PR changes 1 package(s): 4 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:
⛔ 2 release-owned page(s) also name something this change touched. These are read-only:
What this run could not see
Coarse fallback — 4 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): Which tree this was computed onThis run read A worktree cut from an older # while this PR is open — GitHub drops the merge commit once it closes
git fetch origin c72661e2077f3b99c2d0273ccd25e6226697dde0 && git checkout c72661e2077f3b99c2d0273ccd25e6226697dde0
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin ebb4713c06f06adbfe0390b5722c70e31948e3a1 46266e8a062ed1837bf429ca51cbd65eede07397 && git checkout -B drift-repro ebb4713c06f06adbfe0390b5722c70e31948e3a1 && git merge --no-ff 46266e8a062ed1837bf429ca51cbd65eede07397
node scripts/docs-audit/affected-docs.mjs --json ebb4713c06f06adbfe0390b5722c70e31948e3a1
|
|
repo:objectstack#4 · os-justin · session_01QSeKYpRrYuqSLCvbSk9zrL Final head for L1 (2026-11-24T19:03Z):
|
|
repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ 席位核对 — REWORK · L1 · head
|
…ields, both rollback outcomes and the inline sync wait Claude-Session: https://claude.ai/code/session_01QSeKYpRrYuqSLCvbSk9zrL Co-authored-by: Claude <noreply@anthropic.com>
|
repo:objectstack#4 · os-justin · session_01QSeKYpRrYuqSLCvbSk9zrL Final head for delta L1 (2026-11-24T19:42Z):
|
|
repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ 席位核对 — ACCEPT · L1 · head
|
…owledge-sync-where
|
repo:objectstack#4 · os-justin · session_01QSeKYpRrYuqSLCvbSk9zrL Landing — PR #37075 at head
State: ready + auto-merge; #36991 closes on merge via |
…ne walk per source at a time (objectstack-ai#37129) Fixes objectstack-ai#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 objectstack-ai#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 (objectstack-ai#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 (objectstack-ai#36995) landed as objectstack-ai#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 (objectstack-ai#37001 / objectstack-ai#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 (objectstack-ai#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. <details><summary>Package tests and typecheck</summary> ``` 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) ``` </details> <details><summary>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)</summary> ``` A4 (9e24b96) 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 (99518e6, 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) ``` </details> <details><summary>SQL driver: one scratch run of ObjectQL + SqlDriver (better-sqlite3, :memory:) against this branch's source at 9e24b96</summary> 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."} ``` </details> <details><summary>Local gate subset (dispatch-gates --commands, derived from merge base eec6fb3, 5 paths): 100 derived, 98 exit 0, 2 NOT MEASURED</summary> ``` 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. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYpRrYuqSLCvbSk9zrL)_ <!-- signed: repo:objectstack#4 · os-justin · session_01QSeKYpRrYuqSLCvbSk9zrL --> --------- Co-authored-by: Claude <noreply@anthropic.com>
Fixes #36991
Clause-②: no
Metadata-protocol: none
维护者速读
What changes
KnowledgeService.handleRecordUpsertno longer builds the document from the event payload. With a data engine bound, eachobjectsource bound to the object re-reads the row under the system context,find(object, { where: { $and: [where, { id }] }, limit: 1 }, { context: system })({ id }alone when the source has nowhere):recordToDocument(source, objSource, row, this.schemaFor(object))gate as the reindex walk, so the credential-class /internalwithholding landed by fix(service-knowledge): knowledge search asks the object's API exposure and the caller's field-level read rules per source #36850 holds on this path too, and the document carries the fields the source lists and the recordtitle, never a credential-class orinternalfield;The plugin's event bridge now routes
data.record.restored(RECORD_RESTORED_EVENTfrom@objectstack/spec/data) through the same path; its comment and theenableEventSyncoption docs name all four per-record events. With no data engine: a source withoutwherestill builds from the payload; a source withwhereis skipped and reported once per source atwarn. Syncs of one document (${source.id}:${recordId}, upserts and deletes alike) run through an in-process promise chain, dropped when idle, so two opposite events cannot interleave. The system context is one helper now shared withreindexSource(same spelling it already used). No adapter-contract member, no spec change, no queue.content/docs/protocol/knowledge.mdxsection 6 is rewritten to say this, including the measured ordering below; it also drops the claim that a barerecord.*event is still accepted (the bridge has had no branch for it).Item 6: where the event fires relative to the write's transaction (measured on origin/main 8aecf6d)
data.record.createdis published atpackages/objectql/src/engine-insert.ts:1716, inside the engine body thatinsertwraps in its own unit when it opens one (engine-insert.ts:386,executeWithMiddleware(opCtx, inOwnUnit(...)), closing at :1805);data.record.updatedatengine-update.ts:2445, insideinOwnUnitopened atengine-update.ts:529. So both fire before that unit, or a caller'sengine.transaction(...), commits.publishDataEventawaitsrealtimeService.publish(engine-realtime-publish.ts:484), and the in-process adapter awaits each subscriber (packages/services/service-realtime/src/in-memory-realtime-adapter.ts:98), so the knowledge handler runs inside the write's async context. A read with no explicit transaction takes the ambient one (engine-driver-options.ts:304-306), so the re-read sees the row the write just made. A rolled-back unit leaves the index wrong until the row's next event or areindexSource, in one of two ways: if the uncommitted row matched, the document stays built from a row that never committed (as the payload path did); if it did not match, the document was deleted, so the committed row, which may still match, is missing from the index (new with the re-read). Because the sync is inline, a write's sync can also wait behind an earlier in-flight sync of the same document (on a single-connection pool, up to the acquire timeout); the index still ends consistent.data.record.restoredis published atrecycle-bin/restore.ts:470, afterwriteBack(:451) has run and committed the restore's own unit (restore.ts:756).data.records.*events stay uncovered; the existing warn and doc callout say so.Tests
src/__tests__/event-sync-data-events.test.tsis rewritten (it asserted building fromafter): the bridge cases now coverdata.record.restored, and the sync cases run the real plugin and service against an engine double whosefindapplies scalar equality and$and, refuses any other operator by throwing, and applieslimitby presence after the filter. One test per acceptance item: enter on match; does not enter when not matching; exit when a record stops matching (and search no longer finds it); nowhere; payload missing a content field; restored and matching is searchable; restored but not matching is not indexed; no engine withoutwhere; no engine withwhere(skipped, one warn across two events); and three two-event races (match then no match, no match then match, update then delete) each ending consistent with the database. Inknowledge-service.test.tsthe event-path withholding pin now feeds a payload carrying only the id and a re-read row carrying the credential and internal fields, under'*'and named explicitly.Ablations, each through
scripts/ablation-replace.mjs(anchor hit 1 to 0, blob changed, restored to HEAD withgit diff HEADempty); the test imports the source by relative path, so nodist/leg:wherereduced to{ id }RECORD_RESTORED_EVENTdropped from the bridgeAcceptance notes
contentFields: ['*']the event-path document now carries every string field of the re-read row, exactly whatreindexSourcealready sends for the same row; explicit lists send only the listed fields. Retiring'*'is the epic's row 3, not this card.Verification
Two minutes:
pnpm --filter @objectstack/service-knowledge exec vitest run src/__tests__/event-sync-data-events.test.tsshould printTests 23 passed (23).Read first, by risk:
packages/services/service-knowledge/src/knowledge-service.ts:syncRecord(the re-read and the miss-means-delete branch) andserializeRecordSync.packages/services/service-knowledge/src/knowledge-service-plugin.ts: the event-bridge branch now includingRECORD_RESTORED_EVENT.content/docs/protocol/knowledge.mdxsection 6: the ordering statement.Container run (head 53f2e69, this worktree; re-run at 4ab8a4f after the text-only patch round:
pnpm --filter @objectstack/service-knowledge testVERDICT command-exit 0,Test Files 8 passed (8),Tests 117 passed (117)):Package tests and typecheck
pnpm --filter @objectstack/service-knowledge test: VERDICT command-exit 0,Test Files 8 passed (8),Tests 117 passed (117)(event-sync file 23, knowledge-service file 28).pnpm --filter @objectstack/service-knowledge typecheck: VERDICT command-exit 0;check:test-typecheck: OK, 0 files / 0 errors.pnpm --workspace-concurrency=2 --filter '@objectstack/service-knowledge^...' build, VERDICT command-exit 0.Derived gate families (dispatch-gates --commands, 100)
check:system-context-census,check:query-options-erasure,check:where-matcher,check:objectql-double-limit,check:engine-double-contract,check:doc-authoring,check:issue-citations,check:nul-bytes.pnpm --filter @objectstack/spec run check:skill-examples(needsclient-reactdist),pnpm check:dual-build-cjs-loads(needs every package's dist). Declared to CI.dispatch-gates --ran: 100 derived, 98 run, 2 NOT-MEASURED (derived from the recorded exit 3), 0 UNRUN.test:repoand full dogfood are CI's (no!, no narrowing arm).Generated by Claude Code