Skip to content

fix(service-knowledge): record-change sync honours the source where; a restored record re-enters the index - #37075

Merged
objectstack-fleet[bot] merged 4 commits into
mainfrom
claude/issue-36991-knowledge-sync-where
Nov 24, 2026
Merged

objectstack-fleet[bot] merged 4 commits into
mainfrom
claude/issue-36991-knowledge-sync-where

Conversation

@objectstack-fleet

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

Copy link
Copy Markdown
Contributor

Fixes #36991

Clause-②: no
Metadata-protocol: none

维护者速读

  • 用户能看到什么变化:挂了知识检索的应用里,知识源只索引符合条件的记录(例如只索引现行版本);记录改成不符合后,旧内容从检索结果里消失;从回收站恢复的记录,符合条件就能重新被搜到。
  • 为什么做:知识检索平台化专题第一阶段的「结果要对」——此前记录变更时完全不看索引条件,草稿会进索引,失效内容一直搜得到。
  • 出错会怎样:只影响挂了知识检索服务的应用的检索结果,保存记录本身不受影响;改动可直接撤回,撤回后回到旧行为。
  • 要你做的:无。

What changes

KnowledgeService.handleRecordUpsert no longer builds the document from the event payload. With a data engine bound, each object source 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 no where):

The plugin's event bridge now routes data.record.restored (RECORD_RESTORED_EVENT from @objectstack/spec/data) through the same path; its comment and the enableEventSync option docs name all four per-record events. With no data engine: a source without where still builds from the payload; a source with where is skipped and reported once per source at warn. 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 with reindexSource (same spelling it already used). No adapter-contract member, no spec change, no queue.

content/docs/protocol/knowledge.mdx section 6 is rewritten to say this, including the measured ordering below; it also drops the claim that a bare record.* 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.created is published at packages/objectql/src/engine-insert.ts:1716, inside the engine body that insert wraps in its own unit when it opens one (engine-insert.ts:386, executeWithMiddleware(opCtx, inOwnUnit(...)), closing at :1805); data.record.updated at engine-update.ts:2445, inside inOwnUnit opened at engine-update.ts:529. So both fire before that unit, or a caller's engine.transaction(...), commits.
  • publishDataEvent awaits realtimeService.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 a reindexSource, 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.restored is published at recycle-bin/restore.ts:470, after writeBack (:451) has run and committed the restore's own unit (restore.ts:756).
  • Bulk data.records.* events stay uncovered; the existing warn and doc callout say so.

Tests

src/__tests__/event-sync-data-events.test.ts is rewritten (it asserted building from after): the bridge cases now cover data.record.restored, and the sync cases run the real plugin and service against an engine double whose find applies scalar equality and $and, refuses any other operator by throwing, and applies limit by 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); no where; payload missing a content field; restored and matching is searchable; restored but not matching is not indexed; no engine without where; no engine with where (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. In knowledge-service.test.ts the 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 with git diff HEAD empty); the test imports the source by relative path, so no dist/ leg:

Mutation Red
re-read where reduced to { id } 5 of 23 (query shape, not matching, stops matching, restored not matching, match-then-no-match race)
serialization removed from the upsert path 3 of 23 (all three races)
RECORD_RESTORED_EVENT dropped from the bridge 2 of 23 (restored routing, restored searchable); a first attempt with the anchor ending in a bare close-paren-brace was refused by the tool before any run (replacement count did not move), and was re-run with a unique anchor
document built from the payload instead of the re-read row 3 of 51 across both files (both withholding pins, missing-content-field)

Acceptance notes

  • Under contentFields: ['*'] the event-path document now carries every string field of the re-read row, exactly what reindexSource already sends for the same row; explicit lists send only the listed fields. Retiring '*' is the epic's row 3, not this card.
  • The per-document chain orders syncs in one process only; two processes publishing for one row are not ordered by it (the card scopes item 5 to in-process).
  • The sync stays inline with the write (as before): a write now also waits for one system-context read per bound source.

Verification

Two minutes: pnpm --filter @objectstack/service-knowledge exec vitest run src/__tests__/event-sync-data-events.test.ts should print Tests 23 passed (23).

Read first, by risk:

  1. packages/services/service-knowledge/src/knowledge-service.ts: syncRecord (the re-read and the miss-means-delete branch) and serializeRecordSync.
  2. packages/services/service-knowledge/src/knowledge-service-plugin.ts: the event-bridge branch now including RECORD_RESTORED_EVENT.
  3. content/docs/protocol/knowledge.mdx section 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 test VERDICT 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.
  • Dependency closure built first: pnpm --workspace-concurrency=2 --filter '@objectstack/service-knowledge^...' build, VERDICT command-exit 0.
Derived gate families (dispatch-gates --commands, 100)
  • 98 exit 0, among them 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.
  • 2 NOT MEASURED, exit 3 PREREQUISITE NOT MET (unbuilt packages outside this diff's closure): pnpm --filter @objectstack/spec run check:skill-examples (needs client-react dist), 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.
  • Repo-wide lint, test:repo and full dogfood are CI's (no !, no narrowing arm).

Generated by Claude Code

…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>
@github-actions github-actions Bot added size/l 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 14 documentable anchor(s).

4 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/automation/webhooks.mdx (via data.record.updated (literal, a string literal in start))
  • content/docs/protocol/kernel/realtime-protocol.mdx (via data.record.created (literal, a string literal in start), data.record.updated (literal, a string literal in start))
  • content/docs/protocol/knowledge.mdx (via KnowledgeService (symbol, a top-level class), reindexSource (symbol, a method of class KnowledgeService), data.record.created (literal, a string literal in start), data.record.updated (literal, a string literal in start))

⛔ 2 release-owned page(s) also name something this change touched. These are read-only:

  • content/docs/releases/v17/17-6.mdx (via data.record.created (literal, a string literal in start), data.record.updated (literal, a string literal in start))
  • content/docs/releases/v17/17-7.mdx (via data.record.created (literal, a string literal in start), data.record.updated (literal, a string literal in start))

content/docs/releases/ is RELEASE-OWNED (AGENTS.md "Documentation Guardrails"): release
notes are written centrally at release time, and a code PR that edits them is the exact PR
that guardrail exists to stop. They are still audited — read-only. If one of them is actually
wrong, file an issue or open a dedicated docs-only PR; do not edit it here.

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 ebb4713c06f06adbfe0390b5722c70e31948e3a1 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from c72661e2077f3b99c2d0273ccd25e6226697dde0 — the merge of head 46266e8a062ed1837bf429ca51cbd65eede07397 into base ebb4713c06f06adbfe0390b5722c70e31948e3a1, 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 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

⚠️ 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 ebb4713c06f06adbfe0390b5722c70e31948e3a1 → 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-24T19:03Z): 53f2e69c8bc0f59a9420fc52c4c944f45b77fb36 — check-runs on it: 40 success, 15 skipped, 0 failure, 0 pending; mergeable state clean. Area: a4-K.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ

席位核对 — REWORK · L1 · head 53f2e69c8bc0f59a9420fc52c4c944f45b77fb36 · 2026-11-24T19:14Z

Read against GitHub and the tree at this head: card #36991 and its 3 comments, epic #37000's binding rules, the zone's finalized-head note (7141528526), PR #36850's merged gates, and the full diff (6 files, +612/−150, merge-base 8aecf6d770).

D1 (should-fix) — Three new texts say the event-path document carries "only the fields the source lists": knowledge.mdx §6 ("The same field rules as a reindex apply: only the fields the source lists, and never a credential-class or internal field"), the changeset ("only the fields the source lists; credential-class and internal fields never") and the handleRecordUpsert JSDoc ("only the fields the source lists"). The PR body's first bullet says the same. recordToDocument (unchanged here, shared with reindexSource) also sets the document title from record.title whenever it is a string and not withheld, whether or not the source lists title. §5 of the same page already names it ("every contentFields member of its source, the record title and the source's metadataFields"). Reword all four places to match, for example "the fields the source lists and the record title, never a credential-class or internal field". The behaviour itself is unchanged and stays as it is.

D2 (should-fix) — The rollback sentence covers only one of its two outcomes. In knowledge.mdx §6, the handleRecordUpsert JSDoc and the changeset ("a rolled-back write leaves its document until …"), it says the document "stays built from a row that never committed". On the miss branch, the re-read inside the uncommitted unit finds no match and deletes the document. A rollback then leaves the committed, still-matching row out of the index until its next event or a reindexSource. That is a new rollback outcome of this PR's re-read, a missing document where the payload path left wrong text. It is not worse, but it needs its own sentence. Name both outcomes. The phase-4 card that the zone's note (7141528526) files at ACCEPT should carry both as well.

S1 (nit) — The per-document chain is awaited inline, so one request's write can wait on another request's in-flight sync of the same document. On a single-connection pool (SQLite), a sync whose re-read runs outside any transaction (a write with no unit of its own, or data.record.restored, published after commit) can sit waiting for the connection. Meanwhile a second request's transaction on the same row holds that connection and waits on the chain. The wait lasts until the pool's acquire timeout. The earlier sync then fails with a warn, and the later re-read still leaves the index correct. The window is narrow, the state ends consistent, and the phase-4 queue removes the inline wait. One sentence in §6 ("a write's sync can wait behind an earlier sync of the same document") or a line on that phase-4 card is enough. A code change is not asked for in this round.

Checklist readings

  • Shape and card: l1-face.mjs --pr 37075 is CLEAN at 53f2e69c8b (13 items). The PR is draft, based on main, with first line Fixes #36991, and no closing keyword binds any other card. Fixes is right because all six What items are delivered. Items 1 and 2: re-read by where ∧ id, limit: 1, system context; a hit builds via recordToDocument + schemaFor, a miss deletes. Item 3: RECORD_RESTORED_EVENT is in the bridge, and its comment and the enableEventSync docs now name all four events. Item 4: with no engine, a source without where builds from the payload; a source with where is skipped with one warn per source. Item 5: per-document chain. Item 6: ordering stated in the code comment and §6, and the bulk callout is kept. All eight Acceptance tests are present in event-sync-data-events.test.ts, the file is rewritten, and the container counts are in the PR body. Out of scope is held: no adapter-contract member, no organization ids, no queue.
  • Scope, changeset, declarations: all 6 files are within the claim's file surface. @objectstack/service-knowledge is at patch, which is right for a bug fix with no signature change. Clause-②: no and Metadata-protocol: none are on the body and the changeset, and they agree with the diff (no packages/spec/src/**, no authorable key). Nothing under content/docs/releases/. Skills-docs is not owed.
  • Contract-review face: none. record-recognisers.mjs --template --paths <6 files> reports that the paths decide no face, and it defers to the changeset's Clause-②: line. That line is no, with no (narrowing) arm. So no declaration face and no L2 at CONTRACT_REVIEW_TIER or TIER_DEFAULT is owed.
  • Gates: check-runs at 53f2e69c8b: 40 success, 15 expected skip, 0 failed, 0 pending. Lint & Repo Gates and TypeScript Type Check are success. mergeable_state is clean. Dogfood is not owed (no !, no narrowing).
  • Test evidence: real commands with output: 117/117 package tests (event-sync 23, knowledge-service 28), typecheck exit 0, dependency closure built first. Four ablations through ablation-replace.mjs, each with an anchor that hit 1 then 0 and a restore to HEAD: where→{ id } 5/23 red, serialisation removed 3/23, restored dropped 2/23, payload instead of the re-read row 3/51. The engine double refuses any operator it does not implement, so a query shape it cannot answer turns the suite red.
  • Serialisation: the map key is ${source.id}:${recordId} for both upsert and delete. Each sync runs after the previous one settles and re-reads on its own, so a later sync never acts on an earlier read. The catch keeps a rejected task from breaking the chain. The tail removes itself in finally only while it is still the stored tail, so the map holds only in-flight documents. whereUnenforceableReported is bounded by the source count. Ordering holds within one process only, as the docs and the PR body say. For the cross-request wait, see S1.
  • Tenant and organisation scope: the re-read uses systemContext(), the same isSystem context as the reindex walk, and carries no organisation scope. It is keyed by the event's own record id, so it reads only the row the event names. That is no wider than the payload it replaces or than reindexSource, and search still re-checks each hit as the caller.
  • PR fix(service-knowledge): knowledge search asks the object's API exposure and the caller's field-level read rules per source #36850 gates: recordToDocument withholding applies to the re-read row, pinned under '*' and under named fields in knowledge-service.test.ts. admitSources is search-time, and the event path does not reach or skip it.
  • Egress: the event path sends exactly what reindexSource sends for the same row. Under '*' that is every string field of the row, per the seat's routing (option A); retiring '*' is epic row 3. For the wording, see D1.
  • Rollback staleness: documented in the code comment and §6. Not worsened, but incompletely stated (D2).
  • Docs sentences checked against the code:
    • The data.record.* wording at :55.
    • The four-event vocabulary, and that a bare record.* is ignored. The bridge has no branch for it, and tests pin it.
    • The re-read query shape.
    • Hit builds from the re-read row and cannot be short.
    • Miss deletes. Deleting an absent document is a no-op in both in-repo adapters (knowledge-memory filters; knowledge-ragflow deletes what it finds).
    • Restored row takes the same path.
    • Both no-engine branches.
    • Delete by recordId.
    • Per-process serialisation.
    • Created/updated published inside the write after the after* hooks, and before the unit or caller transaction commits. Verified at engine-insert.ts, engine-update.ts and engine-realtime-publish.ts:484.
    • The in-memory realtime adapter awaits each subscriber (in-memory-realtime-adapter.ts:98).
    • Restored is published after the restore's own unit (restore.ts:470, :756).
    • The changeset's bullets were read the same way.
    • Exceptions: D1 and D2.

Rework

A patch round on the same claim, text only: D1 in four places (mdx §6, changeset, JSDoc, PR body) and D2 in three (mdx §6, JSDoc, changeset). S1 is optional. Re-run the package tests and post the new 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>
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpRrYuqSLCvbSk9zrL

Final head for delta L1 (2026-11-24T19:42Z): 4ab8a4ff2269b6ed0716c79b93f42607f131219d — check-runs on it: 42 success, 17 skipped, 0 failure, 0 pending. Area: a4-K.

  • Delta from 53f2e69c is text only (+30/−13, 3 files: the handleRecordUpsert JSDoc, knowledge.mdx §6, the changeset; plus the PR body): D1 (fields listed + record title), D2 (both rollback outcomes), S1 (a sync can wait behind an earlier sync of the same document) from REWORK 7141806791.
  • The docs-drift comment also names content/docs/ai/knowledge-rag.mdx; its event-sync sentence (:79, "records on indexed objects change … drive KnowledgeService.handleRecordUpsert/Delete automatically") stays true and is not changed here.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpEsWWE9Y5YtSsDgqZ

席位核对 — ACCEPT · L1 · head 4ab8a4ff2269b6ed0716c79b93f42607f131219d · 2026-11-24T19:45Z

Delta L1 for card #36991, requested by zone a4-K (7142475022), over the REWORK at 53f2e69c.

  • Delta shape. Prose only, 3 files +30/−13: the changeset, content/docs/protocol/knowledge.mdx, and doc comments in packages/services/service-knowledge/src/knowledge-service.ts. No code line moved.
  • D1: closed. Every place that said a document carries "only the fields the source lists" now says "the fields the source lists and the record title, never a credential-class or internal field" — the changeset, the protocol page and the handleRecordUpsert comment agree with recordToDocument.
  • D2: closed. The rollback consequence now names both outcomes: an uncommitted matching row leaves a document built from a row that never committed; an uncommitted non-matching row deleted the document, so a committed row that may still match is missing until the next event or reindexSource. Stated in all three places.
  • S1: closed. The serialisation note now says a write's sync can wait behind an earlier in-flight sync of the same document (up to the pool's acquire timeout on a single-connection pool), and that the index still ends consistent.
  • Kept, as the zone reported: knowledge-rag.mdx:79's event-sync sentence still holds at this head; not changed, not required.
  • Gates. Check-runs at this head: 42 success, 17 expected skip, 0 failed, 0 pending.
  • Landing K: 19 first-parent commits on main since the merge base — over the bound. Merge main first (a merge-only head move keeps this ACCEPT), then land when green.
  • No must-fix, no should-fix. The zone lands it.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#4 · os-justin · session_01QSeKYpRrYuqSLCvbSk9zrL

Landing — PR #37075 at head 46266e8a062ed1837bf429ca51cbd65eede07397 (2026-11-24T20:17Z), on ACCEPT 7142566131 (head 4ab8a4f; this head is a merge of main only, diff vs main unchanged: same 6 files, +629/−150). Area: a4-K.

Probe Reading
check-runs at this head 40 success, 15 skipped, 0 failure, 0 pending
check-governed-merges.mjs --pr 37075 NOT governed, 0 of 6 paths; 779 changed lines ≤ 3000
landing-k.mjs --pr 37075 K = 2 < 15; locale leg none; shared-budget leg: this PR touches no book

State: ready + auto-merge; #36991 closes on merge via Fixes. Follow-up already filed: #37110 (rollback outcomes, epic #37000 phase 4).

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 24, 2026 20:18
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 24, 2026
Merged via the queue into main with commit eec6fb3 Nov 24, 2026
56 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/issue-36991-knowledge-sync-where branch November 24, 2026 20:43
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…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>
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: record-change sync ignores the source where, and a restored record never re-enters the index

2 participants