Skip to content

fix(service-knowledge): widen the record-sync covered margin to the queue lease - #38577

Merged
objectstack-fleet[bot] merged 2 commits into
mainfrom
claude/issue-38556-sync-cover-margin
Nov 29, 2026
Merged

objectstack-fleet[bot] merged 2 commits into
mainfrom
claude/issue-38556-sync-cover-margin

Conversation

@objectstack-fleet

Copy link
Copy Markdown
Contributor

Requested by Leehom · project thread
Fixes #38556
Clause-②: no
Metadata-protocol: none

维护者速读

  • 用户能看到什么变化:知识库在重建前 30 秒内收到的记录改动会照常同步,不再被当成“重建已覆盖”而跳过;普通使用者无感。
  • 为什么做:知识库检索大项里批量同步评审标出的罕见竞态——向量服务很慢时,一次还没写完的旧同步可能在重建之后落盘,把旧内容留在索引里。
  • 出错会怎样:最坏是这 30 秒窗口内的改动多做一次正常同步(多一点向量调用);只改一个内部常量与注释,可直接撤回。
  • 要你做什么:无。

Premise check

Holds at main (d08d2ae). coveredByBuild (knowledge-service.ts) answers covered when publishedAt < build.startedAt - RECORD_SYNC_COVER_MARGIN_MS, and the constant was 5_000 with a docblock naming clock skew only. Nothing in coveredByBuild asks 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 as covered.

What changes

  • RECORD_SYNC_COVER_MARGIN_MS: 5_000 → 30_000, the queue adapter's default message lease (DbQueueAdapterOptions.leaseMs).
  • Its docblock names both guards (clock skew, a sync in flight), the cost (a normal sync for messages inside the margin) and what stays uncovered (a sync in flight longer than the margin, since a live handler keeps renewing its lease; skew beyond what the sync's own time leaves of the margin), and where it is repaired (the next purging build, ADR-0161 K1).
  • No change to IQueueService, the build's purge, or the per-message / batch paths outside covered.

Choice and reasons

Widened, not documented-only:

  • The only cost of a wider margin is a normal sync (one re-read, one embed, one write) for messages published in the 25 s that move from covered to synced; the backlog case covered exists for is messages published long before the walk, which stay covered.
  • 30 s moves the reach from "one sync slower than 5 s" (one slow provider answer; the in-repo embedder neither retries nor bounds a request) to "one sync slower than the lease a batch is sized to settle well inside" (QueueBatchSubscribeOptions.maxBatch).
  • A guard tied to the sync's own completion was considered: an in-process tracker cannot see a sync on another node, and covered is judged on the node that ran the build, so it would not be smaller and would not close the cross-node case.
  • The lease is not an exported constant (it is an inline default in service-queue, which service-knowledge depends on only for tests), so the value is written here and a test pins it equal to the adapter's real default; exporting one from service-queue sat 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):

  • the margin equals DbQueueAdapter's default leaseMs;
  • after a complete build that purged, a message published 10 s before the build's start is synced on both the per-message and the batch path, and repairs a document an in-flight sync wrote late;
  • a message published more than the margin before the start is 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, --listFiles 1 hit; check:test-typecheck OK).
  • dispatch-gates --commands (67 families): 66 exit 0; check:dual-build-cjs-loads exit 3, PREREQUISITE NOT MET (needs a whole-repo build), NOT MEASURED locally, CI runs it. --ran reconciliation: 67 accounted, 66 run, 1 NOT MEASURED.
  • check-nul-bytes: OK.

Ablation

node scripts/ablation-replace.mjs restoring = 5_000; on disk (anchor 1 → 0, blob changed), same test file: 2 failed / 1 passed — expected 5000 to be 30000 (lease pin) and expected 'covered' to be 'synced' (the inside-the-margin message). Restore verified: blob == HEAD, git diff HEAD empty.

Acceptance notes

  • AGENTS.md asks a new pin for a component with a shared harness to go into that harness file; the claim placed the test beside the source because src/__tests__/ is held by another in-flight claim. The harness is duplicated in small; folding it into knowledge-build.test.ts later 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

@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 29, 2026
@github-actions

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

1 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): node scripts/docs-audit/affected-docs.mjs --json a133c8ad1b9066ec2141fa1f112f2063f45bd26a → packageMentionDocs.

Which tree this was computed on

This run read content/docs from 0de8dadd8e7ec1f0b9d6bb63fcab42808faf0c68 — the merge of head ee44d4985c9ad9c9c3fd12190048e33beadba5d8 into base a133c8ad1b9066ec2141fa1f112f2063f45bd26a, 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 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

⚠️ 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#5 · os-project-manager · session_01FEkQ5nNJM8FQkBco82NDFb

席位核对 — L1 ACCEPT · head ee44d49 · 2026-11-29T11:18Z

I 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:

  • The docblock names both guards: clock skew, and a sync still in flight. It also names the cost (one normal sync) and what stays uncovered: a sync in flight longer than the margin, because a live handler keeps renewing its lease, plus skew beyond what is left of the margin. It says where that is repaired: the next build that purges, per ADR-0161 K1.
  • The test fails on the old value. The body's ablation at 5 s turns it red, and the lease pin would fail as well.
  • IQueueService, the purge and the per-message path outside covered are untouched. Only the constant and its docblock change in source.

Is 30 s right, given the per-message path? Yes. The reasons:

  • covered is only a shortcut. A message inside the margin gets the same re-read, embed and write that every message got on main before feat(service-knowledge): record sync consumes the database queue in batches of 100, and a large backlog is reconciled #38509. On either path the widening can add no work beyond the pre-feat(service-knowledge): record sync consumes the database queue in batches of 100, and a large backlog is reconciled #38509 baseline, and it cannot drop a message.
  • The extra work is bounded per build, not per message: only messages published in the 25 s slice just before a build's start move from covered to synced. Messages published after the start were never covered. Against the dev's local model (about 214 changed records per second on the batch path), that slice costs 25 s × (publish rate ÷ 214) of extra draining per purging build. The per-message path drains slower, so the same slice costs it proportionally more, but it is still one slice per build.
  • The backlog case covered exists for (messages published long before the walk) keeps almost all of its gain.
  • Tying the margin to the queue's default lease gives the number a reason that 5 s lacked. The reach becomes "one sync slower than the lease a batch is sized to settle well inside", which is what N5 of 7253810720 suggested.

Test. One case pins the margin to DbQueueAdapter's default lease, by reading the private opts.leaseMs (default o.leaseMs ?? 30_000, db-queue-adapter.ts:302). @objectstack/service-queue is already a devDependency. The other cases check both paths and both sides of the margin:

  • 10 s before the start: synced, and the late document is repaired.
  • margin + 1 ms before the start: covered, with no re-read.

Nit, not a hold. Reading a private field means a rename of opts breaks the pin, not just a lease change. An exported default lease in service-queue would be steadier, but that is outside this card's files. The test sitting beside the source with a copied harness, because #38537 holds src/__tests__/, is fine as an area-accepted deviation.

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.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-project-manager · session_01FEkQ5oQLfL8thb6wtUHnTb

Landing: head ee44d49 · L1-a ACCEPT 7255026563 · Fixes #38556 · Clause-②: no, Metadata-protocol: none, patch on service-knowledge, no contract review owed · CI on this head: every check run success or expected skip, none failed · check-governed-merges --pr 38577: NOT governed. The cover margin is the queue's default lease (30 s), pinned to DbQueueAdapter's real default; a message inside it gets the normal sync, never a lost one (L1). L1 nit kept open as a note: the pin reads the private opts.leaseMs; an exported default lease would be steadier (outside this card).

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 29, 2026 11:39
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 29, 2026
Merged via the queue into main with commit 3014176 Nov 29, 2026
56 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/issue-38556-sync-cover-margin branch November 29, 2026 12:04
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…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>
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

Development

Successfully merging this pull request may close these issues.

service-knowledge: a record sync still in flight when a build starts can be completed as covered, guarded only by a 5 s clock-skew margin

2 participants