Skip to content

fix(service-knowledge): defer a backlog reconcile asked for during a bulk import until its record syncs drain - #38767

Merged
objectstack-fleet[bot] merged 1 commit into
mainfrom
claude/issue-38591-reconcile-skips-pending-sync
Nov 30, 2026
Merged

objectstack-fleet[bot] merged 1 commit into
mainfrom
claude/issue-38591-reconcile-skips-pending-sync

Conversation

@objectstack-fleet

Copy link
Copy Markdown
Contributor

Requested by Steve · project thread
Fixes #38591
Clause-②: no
Metadata-protocol: none

repo:objectstack#3 · os-steve · session_01ADHkmPDtfMCw4FJfyFfQ7v

维护者速读

  • 用户能看到什么变化:往知识库来源批量导入记录时,向量化请求和向量写入从约两倍降到与整体重建持平;代价是导入后检索追上的时间回到只走批量同步时的水平(真实向量服务上约为重建的 1.36 倍,本容器未实测)。
  • 为什么做:知识库检索大项里,上一轮真实服务实测发现导入时“积压对账”和批量同步把每条记录都向量化、写入了两遍,每次导入花两倍的钱。
  • 出错会怎样:导入期间的对账推迟到同步排空后才跑;判断失误时最坏是对账晚启动(至多一小时)或多做一遍同步;只改一个内部函数,可直接撤回。
  • 要你做什么:无。

What changes

considerBacklogReconcile (knowledge-service-record-sync.ts) still decides, as before, that a source's backlog is large enough for a reconcile (estimate at least RECORD_SYNC_BACKLOG_THRESHOLD and at least RECORD_SYNC_BACKLOG_ROW_SHARE of its rows). What it does next now depends on one comparison:

An import cannot reach the second branch: each message is published after its row commits, and the rows are counted after the waiting count is read, so an import's estimate never exceeds its rows.

No change to coveredByBuild, the cover margin, the batch path, IQueueService, any option, setting, error code or export. knowledge-record-sync-queue.ts is untouched.

Choice: (b), and why not (a)

  • (a) the walk skips a record whose message is queued or claimed needs the walk to know which records have such a message. IQueueService exposes a count (getQueueSize, pending only) and the dead letters (listFailed), and no read of pending or claimed messages by source or record. Adding one is a contract change in packages/spec (a needs_decision), and the walk lives in knowledge-service-indexing.ts, outside this card's file surface. An in-process tracker would not see messages published on another node.
  • (b) defer the walk until the backlog drains is buildable inside the record-sync facet, and measured below: the import drain lands at 501 requests and 50,000 writes, against the rebuild's 500 and 50,000.

The margin's own case (#38556) stays closed

coveredByBuild and RECORD_SYNC_COVER_MARGIN_MS are untouched, so a message published inside the margin of a build's start is still synced. knowledge-record-sync-cover-margin.test.ts is unchanged and green.

Premise check (origin/main acf3b33)

  • considerBacklogReconcile is at knowledge-service-record-sync.ts:645, called from the batch path at :516; it schedules the reconcile with void this.enqueueReconcile(...) beside the batch.
  • coveredByBuild (:480) covers a message only when publishedAt < startedAt - RECORD_SYNC_COVER_MARGIN_MS, and only after the build ended done with a purge; a build running now covers nothing.
  • The walk (walkObjectSource) lists the adapter's documents once, before its first page, and skips only documents whose hash it listed. During an import those documents do not exist yet, so the walk embeds every row, and the drain syncs every message it takes meanwhile.
  • The measurement commit 30141766 IS fix(service-knowledge): widen the record-sync covered margin to the queue lease #38577's merge (margin 30_000 there), so the margin change does not retire the card. Even at the old 5 s margin, a reconcile that starts 6 s into a 34 s import covers almost none of it.
  • Reproduced on the base before the fix: table below, 0 messages covered.

Measurement (counts)

A real kernel: ObjectQLPlugin over SqlDriver (better-sqlite3, a file), QueueServicePlugin({ adapter: 'db' }) with default options, KnowledgeServicePlugin with one object source, buildAtBoot: false. The store is a counting double that lists its documents: one upsert call is one embedding request, each document one write, with 100 ms per request. As in #38529: a complete build over the empty table first, then ql.insert of 50,000 records in arrays of 500, timed from the first insert until no record-sync message is pending or running and any reconcile has ended. The rebuild runs over the drained data file with a fresh store. The harness is not in the diff; it is a snippet in the details below.

run (50,000 records) embedding requests texts document writes outcomes reconcile
before: acf3b33e, reconcile beside the drain 1,001 99,976 99,976 50,000 synced, 0 covered walked beside: 50,000 read, 49,976 written
after: this branch 501 50,000 50,000 50,000 synced, 0 covered after the drain: 50,000 read, 0 written, 50,000 unchanged
rebuild of the same records 500 50,000 50,000 n/a n/a
  • After against the rebuild: requests +0.2 %, writes 0 %; the acceptance asks for within 10 %. Before against the rebuild: 2.00x and 2.00x (service-knowledge: measure a 50,000-record bulk-import drain with a real embedding provider, against a rebuild of the same records #38529 measured 985 against 503, and 99,551 against 50,012, with a real provider).
  • Wall time on this shared box, with the fake embedder: import 36.5 s / 34.4 s; drain 108.6 s before, 105.5 s after; the deferred reconcile ended 21 s after the drain (126.8 s); rebuild 52.0 s / 51.8 s. These are shared-box seconds, not idle-box figures.
  • Real-embedder timing: NOT MEASURED (no AI gateway key in this container). The counts carry the acceptance.
Harness (scratchpad only, not committed)

The harness boots the kernel above with a counting store (upsert increments a request count and adds the batch length to writes, then waits REQ_MS), wraps processRecordSyncBatch to tally outcomes, inserts the records, waits until sys_job_queue holds no pending or running row of knowledge-record-sync and any reconcile has ended, then boots a second kernel over the same file with a fresh store and runs rebuildSource('kb', { trigger: 'operator' }). Run with M38591_N=50000 M38591_REQ_MS=100: 180 s before, 196 s after, under os-verify-lock.

Tests

New src/__tests__/reconcile-during-import-38591.test.ts (an engine double and a store double that records each written document with its call's reason, fake timers):

  • a reconcile started during a pending import (6,000 messages for 6,000 rows) embeds no record that has a pending message, checked after every batch; once drained it walks, and every imported document was written exactly once, by its own sync;
  • a record with no sync message is still reconciled once the import has drained: the walk writes exactly that one document;
  • a queue that does not drain holds the walk off for RECORD_SYNC_BACKLOG_RETRY_MAX_MS, then it walks;
  • builds stopped while the walk waits: nothing is walked.
Readings at 785fede
  • pnpm --filter @objectstack/service-knowledge test: Test Files 26 passed (26), Tests 840 passed (840). This includes the unchanged knowledge-build.test.ts service-knowledge: a bulk import syncs one record per queue message, read, embedded and written alone, so the index trails the data for hours #38413 suite and knowledge-record-sync-cover-margin.test.ts.
  • pnpm --filter @objectstack/service-knowledge typecheck: exit 0; tsc --listFiles names the new test once in tsconfig.json and once in tsconfig.test.json; check:test-typecheck OK.
  • Dependency closure pnpm --filter '@objectstack/service-knowledge^...' build: exit 0.
  • dispatch-gates --commands --repo objectstack-ai/objectstack at 785fede derives 68 families. 67 exit 0. check:dual-build-cjs-loads exits 3, PREREQUISITE NOT MET (it needs a whole-repo build): NOT MEASURED locally, and CI runs it. --ran reconciliation: 68 derived, 67 run, 1 NOT-MEASURED, 0 UNRUN. check-plugin-teardown-shape --self-test first exited 3 because this shallow checkout could not reach its pinned fixture commit; after a --depth=1 fetch of that commit it exited 0. check:query-options-erasure (392 s) and check:type-check-debt (234 s) ran past a 150 s and a 300 s per-command timeout on this shared box, and both exited 0 when re-run with a longer one. check:nul-bytes exit 0. overlap-check.mjs before the push: origin/main: merges cleanly, VERDICT clean exit 0.

Ablation

node scripts/ablation-replace.mjs turned const deferred = estimate <= rows; into const deferred = false; on disk (anchor 1 → 0, blob 8cdba5dc3e67 → 8ae94f8819d7; the test imports the source directly, so no dist/ is involved). Result: the new file goes 4 failed / 4. The card's pin fails with expected [ 'kb:imp00100', …(5899) ] to deeply equal []: the walk wrote 5,900 records whose messages were still waiting. Restored: the blob equals HEAD and git diff HEAD is empty.

Acceptance notes

  • Wall time moves to the batch path's rate. In service-knowledge: measure a 50,000-record bulk-import drain with a real embedding provider, against a rebuild of the same records #38529 the default drain (568.6 s) beat the batch path alone (805.7 s) only because two embedding streams ran at once, paying twice. With this change an import drains at the batch-only rate, 1.36x the rebuild on that provider, which is inside service-knowledge: a bulk import syncs one record per queue message, read, embedded and written alone, so the index trails the data for hours #38413's "small multiple". Not re-measured here.
  • Drained is judged on the pending count. getQueueSize counts pending messages, not claimed ones, so the walk can begin while the last batch (at most RECORD_SYNC_BATCH_SIZE records) is still syncing; at most one batch is written twice. The 30 s read interval makes this rare.
  • A row count cached from an earlier backlog (RECORD_SYNC_SOURCE_ROWS_TTL_MS, 10 min) can be lower than the table's rows after a later import, which could send that import down the walk-beside branch. It is reached only by a second large backlog of the same source within 10 minutes of a failed reconcile (the 5 min retry); noted, not changed.
  • The 60 min bound reuses RECORD_SYNC_BACKLOG_RETRY_MAX_MS; no new constant.
  • AGENTS.md asks a new pin for a component with a shared harness file to go into that file (knowledge-build.test.ts). The claim's file surface names a new file, so the harness is duplicated in small; folding it in is a follow-up for whoever holds that file.
  • Not in scope, per the card: the cover margin's value, the batch size, a remote libSQL store.

Verification (two minutes)

pnpm --filter @objectstack/service-knowledge exec vitest run --maxWorkers=2 src/__tests__/reconcile-during-import-38591.test.ts — expect 4 passed.

Read first, by risk:

  1. knowledge-service-record-sync.ts considerBacklogReconcile: the deferred branch and the rewritten completion chain (a dropped deferral must not count as a failed reconcile).
  2. knowledge-service-record-sync.ts backlogDrained: the drained test, the 60 min bound and the stop conditions.
  3. The new test's first case, the card's pin.

Generated by Claude Code

🤖 Generated with Claude Code

https://claude.ai/code/session_01ADHkmPDtfMCw4FJfyFfQ7v

…bulk import until its record syncs drain

A backlog no larger than the source's rows is about one message per record:
the drain embeds each record once, and a walk beside it could cover only the
messages published RECORD_SYNC_COVER_MARGIN_MS before it began, so it
embedded and wrote every imported record a second time. The walk now waits
until the backlog has drained (bounded by RECORD_SYNC_BACKLOG_RETRY_MAX_MS)
and then writes only the rows no message reached. A backlog that outnumbers
the rows is walked beside the drain, as before.

Claude-Session: https://claude.ai/code/session_01ADHkmPDtfMCw4FJfyFfQ7v
Co-authored-by: Claude <noreply@anthropic.com>
@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 30, 2026
@github-actions

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

7 anchor(s) derived from 1 changed package(s); no hand-written page names any of them, so this run has nothing to list — not a clean bill of health. This check sees only pages that NAME a derived anchor: one that documents this change in prose, or enumerates it in an authoring dialect, names none and stays invisible to it on every run.

What this run could not see
  • 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 — 5 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 111ad632d02cff93cc2786657925370a9c16c521 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from 810eaaddedc67f1c8b8042a2014d65f6b333b0d7 — the merge of head 785feded899206fa0e829b8190e0c0b25ed75d50 into base 111ad632d02cff93cc2786657925370a9c16c521, 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 810eaaddedc67f1c8b8042a2014d65f6b333b0d7 && git checkout 810eaaddedc67f1c8b8042a2014d65f6b333b0d7
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 111ad632d02cff93cc2786657925370a9c16c521 785feded899206fa0e829b8190e0c0b25ed75d50 && git checkout -B drift-repro 111ad632d02cff93cc2786657925370a9c16c521 && git merge --no-ff 785feded899206fa0e829b8190e0c0b25ed75d50

node scripts/docs-audit/affected-docs.mjs --json 111ad632d02cff93cc2786657925370a9c16c521

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

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#3 · os-steve · session_01ADHkmPDtfMCw4FJfyFfQ7v

Final head for review — zone o3-K · 2026-11-30T13:37Z
Head-sha: 785feded899206fa0e829b8190e0c0b25ed75d50
CI: every check-run on this head is success or an expected skip (39 success, 18 skipped, 0 failed, 0 running).
Hold: the draft-hold on new knowledge work was lifted by the maintainer at 2026-11-30T13:34Z (seat zone order, 13:37Z appendix). Next: L1 (L1-b).

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#3 · os-steve · session_01ADHkmT9HTWLMN33WUVxVWB
L1-b, the seat's L1 thread · 2026-11-30T13:42Z · first review

席位核对

ACCEPT @ 785fede (card #38591, Fixes; 3 files, one package)

  • Relation. Fixes #38591 delivers the card. Before this change, an import paid the embedding cost about twice (1,001 requests and 99,976 writes for 50,000 records). After it, the import lands at the rebuild's cost (501 and 50,000, against 500 and 50,000), inside the card's 10 %. The body's choice of (b) over (a) is argued from the contract: IQueueService has no read of pending messages by record, and adding one is a packages/spec change outside the card. The body states that the real-embedder timing is NOT MEASURED. No closing keyword binds any other card.
  • The rule, read on the code. considerBacklogReconcile keeps its threshold and row-share tests, then splits on estimate <= rows.
    • Deferred (an import or bulk update): backlogDrained re-reads the pending count every RECORD_SYNC_BACKLOG_READ_INTERVAL_MS. It walks once waiting * share < 1, or after RECORD_SYNC_BACKLOG_RETRY_MAX_MS (60 min). It returns false, and does not walk, when builds are stopped, the service is held, or the source is gone or excluded.
    • Not deferred (estimate > rows, service-knowledge: a bulk import syncs one record per queue message, read, embedded and written alone, so the index trails the data for hours #38413's case): the walk runs beside the drain, unchanged.
    • The completion chain. A dropped deferral sets running = false and notBefore = now, and does not count as a failure. A walk that ran keeps the old success and back-off logic, now after await. The timer is unref'd.
  • Declarations. Clause-②: no and Metadata-protocol: none match: no option, setting, error code or export moves. The changeset is patch for service-knowledge, and I read it sentence by sentence; each sentence is true to the code, including "a queue that does not drain within an hour starts the walk anyway". Dogfood and L2 are not owed.
  • Acceptance notes, weighed.
    • Drained is judged on the pending count, so up to one batch can be written twice. That is documented.
    • The 10-minute cached row count is documented and not changed.
    • The new test file duplicates a small harness instead of folding into knowledge-build.test.ts, as AGENTS.md asks. The claim names a new file, so this is a recorded deviation and does not block.
  • My runs at this head (fresh worktree, offline install, @objectstack/service-knowledge^... built):
    • reconcile-during-import-38591.test.ts with knowledge-build.test.ts (the service-knowledge: a bulk import syncs one record per queue message, read, embedded and written alone, so the index trails the data for hours #38413 suite): 53/53 passed.
    • Ablation A, never defer (estimate <= rows && rows < 0): all 4 new cases red, including the card's pin. This matches the dev's leg.
    • Ablation B, the drained test never true (only the 60-minute bound left): 2 red, the card's pin and "still reconciled once drained". The other two cases, the bound and stop-while-waiting, stay green, as they should. So the drain test itself is pinned.
    • Both files were restored, and git status is clean.
    • I did not run src/knowledge-record-sync-cover-margin.test.ts, because my path was wrong, or the whole package (840 per the body). That part is NOT MEASURED by me.

Checks at this head (read before writing): 39 success, 18 skipped, 0 failure. mergeable_state is clean. The opt-in Dogfood battery skips are expected.
L2: not owed. Not governed; the zone lands it.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#3 · os-steve · session_01ADHkmPDtfMCw4FJfyFfQ7v

Landing — zone o3-K · 2026-11-30T13:44Z

Probe Reading on head 785feded899206fa0e829b8190e0c0b25ed75d50
check-governed-merges --pr 38767 NOT governed; 401 changed lines (+377 / -24), under the human-merge threshold; no merge=os-regen path in the file list, so no generated drift to re-measure
CI check-runs 39 success, 18 skipped, 0 failed, 0 running; mergeable_state clean

L1 ACCEPT 7280239039 (L1-b) on this head; no L2 owed (not governed, Clause-②: no). State change: draft → ready, auto-merge armed; the card closes on merge via Fixes #38591.

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 30, 2026 13:45
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 30, 2026
Merged via the queue into main with commit 95a49ad Nov 30, 2026
58 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/issue-38591-reconcile-skips-pending-sync branch November 30, 2026 14:10
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/m tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

2 participants