Repository navigation
fix(service-knowledge): widen the record-sync covered margin to the queue lease - #38577
Conversation
…ueue lease Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb
📓 Docs Drift Check1 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
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 0de8dadd8e7ec1f0b9d6bb63fcab42808faf0c68 && git checkout 0de8dadd8e7ec1f0b9d6bb63fcab42808faf0c68
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin a133c8ad1b9066ec2141fa1f112f2063f45bd26a ee44d4985c9ad9c9c3fd12190048e33beadba5d8 && git checkout -B drift-repro a133c8ad1b9066ec2141fa1f112f2063f45bd26a && git merge --no-ff ee44d4985c9ad9c9c3fd12190048e33beadba5d8
node scripts/docs-audit/affected-docs.mjs --json a133c8ad1b9066ec2141fa1f112f2063f45bd26a |
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5nNJM8FQkBco82NDFb 席位核对 — L1 ACCEPT · head ee44d49 · 2026-11-29T11:18ZI read the diff at ee44d49 (3 files, +186/−5) against the L1 checklist and card #38556. At the time of reading the checks on this head were 10 success, 16 skipped, 14 pending and 0 failed, so this verdict is on the diff. Landing waits for green. Fixes #38556 holds. The card's acceptance asks for three things, and all three are delivered:
Is 30 s right, given the per-message path? Yes. The reasons:
Test. One case pins the margin to
Nit, not a hold. Reading a private field means a rename of I did not run the suite locally: KnowledgeService needs a built objectql dist that this container lacks. I rely on CI and the body's ablation. ACCEPT once the pending checks finish green. Not governed, so the area lands it. |
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5oQLfL8thb6wtUHnTb Landing: head ee44d49 · L1-a ACCEPT 7255026563 · |
…bulk import until its record syncs drain (objectstack-ai#38767) <!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9DAwBxBGNv4CexdUyBYJXSw)_ Fixes objectstack-ai#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: - **Estimate no larger than the source's rows** (a bulk import or bulk update: about one message per record). The walk is **deferred until the backlog has drained** (new `backlogDrained`): the queue's waiting count is read afresh every `RECORD_SYNC_BACKLOG_READ_INTERVAL_MS`, and the walk starts once that count times the source's share of the scheduling batch is under one message. The drain embeds and writes each imported record once; the walk then skips every document the drain wrote (unchanged hash) and writes only the rows no message reached. A queue that never drains (other sources keep it busy) starts the walk after `RECORD_SYNC_BACKLOG_RETRY_MAX_MS` (60 min), so it is never held off for good. Builds stopped, the service held, or the source gone or no longer walked while it waits: nothing is walked, and a later backlog may ask again. - **Estimate larger than the source's rows** (repeated saves of the same records, rows deleted or moved out of `where`). Walked beside the drain, exactly as before: one walk costs at most one embed per row and covers the messages. This is objectstack-ai#38413's case, pinned by the `knowledge-build.test.ts` objectstack-ai#38413 suite, which is unchanged and green. 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 (objectstack-ai#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 objectstack-ai#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 objectstack-ai#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 (objectstack-ai#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. <details><summary>Harness (scratchpad only, not committed)</summary> 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`. </details> ## 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. <details><summary>Readings at 785fede</summary> - `pnpm --filter @objectstack/service-knowledge test`: Test Files 26 passed (26), Tests 840 passed (840). This includes the unchanged `knowledge-build.test.ts` objectstack-ai#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`. </details> ## 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 objectstack-ai#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 objectstack-ai#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](https://claude.ai/code/session_01ADHkmPDtfMCw4FJfyFfQ7v)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmPDtfMCw4FJfyFfQ7v <!-- signed: repo:objectstack#3 · os-steve · session_01ADHkmPDtfMCw4FJfyFfQ7v --> Co-authored-by: Claude <noreply@anthropic.com>
Requested by Leehom · project thread
Fixes #38556
Clause-②: no
Metadata-protocol: none
维护者速读
Premise check
Holds at
main(d08d2ae).coveredByBuild(knowledge-service.ts) answerscoveredwhenpublishedAt < build.startedAt - RECORD_SYNC_COVER_MARGIN_MS, and the constant was5_000with a docblock naming clock skew only. Nothing incoveredByBuildasks whether a sync of the record is still in flight (and a sync on another node is invisible to it), so a sync that re-read a record before a later write and whose store write lands after the walk leaves the older document, and the later write's message (published more than 5 s before the build began) completes ascovered.What changes
RECORD_SYNC_COVER_MARGIN_MS:5_000→30_000, the queue adapter's default message lease (DbQueueAdapterOptions.leaseMs).IQueueService, the build's purge, or the per-message / batch paths outsidecovered.Choice and reasons
Widened, not documented-only:
coveredto synced; the backlog casecoveredexists for is messages published long before the walk, which stay covered.QueueBatchSubscribeOptions.maxBatch).coveredis judged on the node that ran the build, so it would not be smaller and would not close the cross-node case.service-queue, whichservice-knowledgedepends on only for tests), so the value is written here and a test pins it equal to the adapter's real default; exporting one fromservice-queuesat outside this card's file surface.Tests
New
src/knowledge-record-sync-cover-margin.test.ts(beside the source, by the claim's file surface):DbQueueAdapter's defaultleaseMs;syncedon both the per-message and the batch path, and repairs a document an in-flight sync wrote late;covered, with no re-read.Readings at ee44d49
pnpm --filter @objectstack/service-knowledge test: Test Files 23 passed (23), Tests 784 passed (784).pnpm --filter @objectstack/service-knowledge typecheck: exit 0 (tsc covers the new file,--listFiles1 hit;check:test-typecheckOK).dispatch-gates --commands(67 families): 66 exit 0;check:dual-build-cjs-loadsexit 3, PREREQUISITE NOT MET (needs a whole-repo build), NOT MEASURED locally, CI runs it.--ranreconciliation: 67 accounted, 66 run, 1 NOT MEASURED.check-nul-bytes: OK.Ablation
node scripts/ablation-replace.mjsrestoring= 5_000;on disk (anchor 1 → 0, blob changed), same test file: 2 failed / 1 passed —expected 5000 to be 30000(lease pin) andexpected 'covered' to be 'synced'(the inside-the-margin message). Restore verified: blob == HEAD,git diff HEADempty.Acceptance notes
src/__tests__/is held by another in-flight claim. The harness is duplicated in small; folding it intoknowledge-build.test.tslater is a follow-up for whoever holds that directory.Verification (two minutes)
pnpm --filter @objectstack/service-knowledge exec vitest run --maxWorkers=2 src/knowledge-record-sync-cover-margin.test.ts— expect 3 passed.🤖 Generated with Claude Code
https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb