Skip to content

feat(service-knowledge): record sync consumes the database queue in batches of 100, and a large backlog is reconciled - #38509

Merged
os-zhuang merged 9 commits into
mainfrom
claude/project-thread-caiyo5
Nov 29, 2026
Merged

os-zhuang merged 9 commits into
mainfrom
claude/project-thread-caiyo5

Conversation

@objectstack-fleet

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

Copy link
Copy Markdown
Contributor

Requested by Leehom · project thread

Part of #38413
Acceptance gap: acceptance 2 is not closed by this PR. The figures here come from a LOCAL MODEL: 50,000 records on a real SQLite/libSQL store, with a local embedder at 200 ms per request + 0.5 ms per input, where the drain takes about 1.7 times as long as a full rebuild. That model cannot show what a real provider does. With a real provider the ratio should move toward 1, because per-message queue costs matter less when every request is slower, but that is not measured. carrier: #38529 (a 50k drain with a real embedding provider, Blocked-by #38509).

Clause-②: yes (widening)
Metadata-protocol: none
Ask 3: split to #38489 (per-source backlog needs a stored counter); the global waiting count is exact here (getQueueSize through count).

维护者速读

  • 用户可见变化:批量导入或批量修改几万条记录后,知识库检索追上数据所需的时间大幅缩短(本地模型实测 5 万条约 4 分钟,原来约 2.9 小时);单条保存的体验不变。
  • 为什么做:属于知识库检索这条线,解决大批量数据进来后很长时间搜不到新内容的问题,按您的裁决实施(队列加一个可选的批量消费能力)。
  • 出错会怎样:只影响走数据库队列的知识同步;某条记录同步失败只会单独重试、进死信,不拖累同批其它记录;邮件发送等其它队列订阅不受影响;可整单撤回。
  • 要你做的:无。

What changes

Ruling A (7250307515): record-sync batching reaches the knowledge worker through an optional batch-consume member on IQueueService. The database queue adapter implements it, and the knowledge worker uses it when the composed queue has it.

  • Contract (packages/spec/src/contracts/queue-service.ts). A new optional member:
    subscribeBatch?(queue: string, handler: QueueBatchHandler, options: QueueBatchSubscribeOptions): Promise(void).
    The types it uses are QueueBatchHandler = (messages: QueueMessage[]) => Promise(QueueBatchOutcome[]), QueueBatchOutcome = { ok: true } | { ok: false; error: unknown } and QueueBatchSubscribeOptions = { maxBatch: number }. The handler answers one outcome per message. A queue takes either per-message handlers or one batch handler, and unsubscribe removes either. The member is optional: every existing implementation keeps compiling, and a consumer falls back to per-message subscribe. It is documented in content/docs/kernel/runtime-services/queue-service.mdx.

  • Database queue (packages/services/service-queue/src/db-queue-adapter.ts). A batch queue gets a dispatch loop of its own. Each tick it:

    • claims up to maxBatch due rows, marking each row in flight as it is claimed;
    • renews all their leases in ONE compare-and-set write every third of leaseMs while the handler runs;
    • settles each row by its own outcome, so a failure takes the per-message retry and dead-letter path alone, and one settling write that throws does not stop the others;
    • ticks again at once while a claim comes back full.

    A row the lease reclaim returns to a batch queue wakes that queue's loop. The main loop is unchanged: the mail send, mail attachment reclaim and API-flow subscriptions keep one message per call at batchSize per pollIntervalMs. getQueueSize now counts through engine.count.

  • Knowledge worker. It uses subscribeBatch with maxBatch 100 (RECORD_SYNC_BATCH_SIZE) when the queue has it, and per-message subscribe otherwise. For each source and object in a batch, processRecordSyncBatch does one re-read (where AND id $in), one planIndex (one fingerprint, ADR-0161 K7), one split, one adapter upsert and one delete. When a group with more than one record fails, its records are synced again one at a time. Messages stay identifiers only, and no IKnowledgeAdapter member is added (K8).

  • Batch against the lease: a 100-message batch takes about 0.47 s against the 30 s lease, and one renewal write every 10 s covers every row in it.

  • covered (review M1). A message completes without a read only when all of these hold:

    • the source's last build on this node ended done and its purge ran (result.purged is a number);
    • the reconcile walks the source (reconcileExclusion);
    • the build began more than 5 s after the message was published.

    A build that ended done without purging covers nothing, so a waiting delete or where-exit is still synced on both paths. This covers an adapter without listDocuments and a listing that failed.

  • Backlog (ask 2, review S1). The rule is now per source and never blocks. The worker estimates a source's backlog as the queue's waiting count times the source's share of the batch in hand. When that estimate reaches both RECORD_SYNC_BACKLOG_THRESHOLD (5,000) and RECORD_SYNC_BACKLOG_ROW_SHARE (5 % of the source's rows, counted once per 10 min), one reconcile of that source is scheduled beside the syncs and is not awaited. The batch and every other source keep draining, and unsubscribe does not wait for a walk. Once the reconcile ends done with its purge run, the waiting messages it covers complete as covered. After it ends, the next backlog reconcile of that source waits:

    • 10 min if it ended done, so a source under sustained writes is not re-walked back to back;
    • 5 min, doubling to 1 h per failure, if it did not.
  • Held service (ruling 7248214179, from feat(service-knowledge)!: a knowledge service the runtime mounts holds its sources without an embedder or its deployment store #38470). The held check sits in resolveRecordSync, straight after the message is read. Both paths therefore complete a not-enabled service's messages as not-synced.

Contract faces touched:

  • IQueueService.subscribeBatch (optional), plus the exported types QueueBatchHandler, QueueBatchOutcome and QueueBatchSubscribeOptions.
  • api-surface/contracts.json and export-origins/contracts.json regenerated (+3 lines each); signatures unchanged.
  • KnowledgeService.processRecordSync takes an optional publishedAt and can answer covered. KnowledgeService.processRecordSyncBatch is new.
  • KnowledgeRecordSyncBatchItem and KnowledgeRecordSyncBatchResult are now exported from @objectstack/service-knowledge.
  • No error code, authorable key or metadata protocol change.

Tests

  • 1,000 syncs (record-sync-queue.test.ts, real DbQueueAdapter, 100 drafts outside where): 10 adapter upserts and 10 deletes. 900 documents were embedded, each published document once and no draft; this counts documents handed to the embedder, not embedder requests. The index of 900 documents equals reindexSource (content and docHash).
  • Poisoned record: it dead-letters alone, its 7 neighbours are indexed, and exactly one dead-letter error line is logged.
  • Mixed batch: deletes, a row moved out of where, an edit, a new draft and a new row in one batch give the same index as the per-message path. A held service's batch path syncs nothing.
  • M1: a delete and a where-exit message against a done build with purged: null still remove their documents. This is tested on both paths, for both no-purge causes: no listDocuments, and a listing that failed.
  • S1 (knowledge-build.test.ts):
    • over the threshold, the batch answers while the reconcile is held mid-walk, and the next batch of older messages completes as covered with no re-read and no second reconcile (re-walk wait);
    • under the threshold, no reconcile runs;
    • a backlog small against the source's rows is drained;
    • one message of source B inside source A's backlog is synced while A is reconciled;
    • a reconcile that ended without a purge is not asked again before its 5 min backoff, and is asked again after it;
    • a store that lists no documents is never reconciled.
  • S2 / N2 (db-queue-adapter.test.ts):
    • a sole writer keeps the lease entry of every batch row claimed while a main-loop reclaim reads;
    • one settling write that throws leaves the other rows settled.
Suite and ablation readings (head 76742ab)
  • service-queue: Test Files 5 passed (5), Tests 102 passed (102); typecheck green.
  • service-knowledge: Test Files 22 passed (22), Tests 781 passed (781); typecheck green.
  • Ablation M1: the condition typeof build.result?.purged !== 'number' || build.result.ok === false was removed from coveredByBuild. Both listing-failed cases went red ("2 failed | 2 passed"); the rebuild-unlisted cases stayed green through reconcileExclusion. Restored to the HEAD blob.
  • Ablation S2: inFlight?.add(String(row.id)) was removed from claimBatch. The S2 case went red ("expected [ false, true, true ] to deeply equal [ true, true, true ]"). Restored to the HEAD blob.
  • Earlier ablations: the held check went red ("vi.fn() ... called 1 times"), and the group fallback went red ("expected 900 to be less than or equal to 10").

Measurement: 50,000 records, LOCAL MODEL

This is a labelled local model, not a production figure.

  • Store: SQLite through the SQL driver for both data and the queue, with the knowledge-turso libSQL file vector store.
  • Embedder: local, with a latency model of 200 ms per request plus 0.5 ms per input, at most 2,048 inputs per request, requests sent in series.
  • Setup: default queue options. Each run starts from a copy of the same database.
  • "All changed" means the index starts empty and all 50,000 messages wait. "None changed" means the index is current and the same 50,000 messages wait.
run time rate embed requests / inputs
this round, all changed, batch + scheduled reconcile 217,019 ms 230/s 990 / 50,214
this round, all changed, batch only (reconcile off) 233,169 ms 214/s 500 / 50,000
this round, none changed, batch + scheduled reconcile 91,113 ms 549/s 0 / 0
this round, none changed, batch only 105,653 ms 473/s 0 / 0
a reconcile walk over the 50,000 unchanged rows 1,418 ms n/a 0 / 0
full rebuild (previous round) 142,359 ms n/a 500 / 50,000
before, per-message, 600 s window (previous round) 2,883 drained in 600,446 ms 4.8/s 2,884 / 2,884
  • Ask 2 now pays. The scheduled reconcile cut the drain by 7 % with every record changed (217 s against 233 s) and by 14 % with none changed (91 s against 106 s). The previous round's awaited reconcile showed 1.3 %.
  • What the floor is. A covered message still costs its claim and settle writes, about 1.8 ms each in this model; this is N1 below.
  • Why 5,000 and 5 %. The worker drains about 214 changed records per second, so 5,000 messages are about 23 s of draining. A walk over 50,000 unchanged rows takes 1.4 s, and draining costs 2.1 ms per unchanged message and 4.7 ms per changed one. At 5 % of the rows, the walk's own reading is about a quarter of the drain it runs beside, or less.
  • Before. The before figure comes from a 600 s window, not a full drain. Projected over 50,000 records it is about 2.9 h, with an 83 min floor at the claim pace of 10 per second.

Acceptance notes

Verification

Read first, by risk:

  1. packages/services/service-knowledge/src/knowledge-service.ts: coveredByBuild, considerBacklogReconcile and processRecordSyncBatch.
  2. packages/services/service-queue/src/db-queue-adapter.ts: claimBatch and its in-flight mark, dispatchBatch with its per-row settle, and the reclaim wake.
  3. packages/services/service-knowledge/src/knowledge-record-sync-queue.ts: the backlog constants and the numbers they cite.

Two-minute check: run pnpm --filter @objectstack/service-knowledge exec vitest run src/__tests__/knowledge-build.test.ts -t "purged nothing". Expect 4 passed: a delete still syncs after a build that did not purge.

Local gates (head 76742ab)
  • Derived with dispatch-gates.mjs --commands --repo objectstack-ai/objectstack on head 76742ab: 120 commands, all run, each exiting 0 with the code captured before any pipe.
  • check-plugin-teardown-shape --self-test passed after the pinned fixture commit was fetched into the shallow clone.
  • check:skill-examples first exited 3 (PREREQUISITE NOT MET: client dist missing). It exited 0 after @objectstack/client and @objectstack/client-react were built: "352 prose examples type-check".
  • check:dual-build-cjs-loads: "126 published require entry point(s) across 74 package(s) load".
  • --ran reconciliation: "Run reconciliation — 120 derived, 120 run, 0 NOT-MEASURED, 0 UNRUN".
  • The derivation warned that its tree is 17 commits behind origin/main, with 16 derivation files changed there. No merge was done, since there is no conflict and no main-caused red; CI judges the merge ref.
  • overlap-check --branch=claude/project-thread-caiyo5: "origin/main: merges cleanly", VERDICT clean exit 0.

🤖 Generated with Claude Code

https://claude.ai/code/session_01FEkQ5mC8eA4qtKSweeF7wd

…mixed batch parity, backlog reconcile

Claude-Session: https://claude.ai/code/session_01FEkQ5mC8eA4qtKSweeF7wd
Co-Authored-By: Claude <noreply@anthropic.com>
… batch consume and the knowledge batch sync

Claude-Session: https://claude.ai/code/session_01FEkQ5mC8eA4qtKSweeF7wd
Co-Authored-By: Claude <noreply@anthropic.com>
The held check #38470 put in processRecordSync moves into resolveRecordSync,
right after the message is read, so the per-message and batch paths both
complete a held service's messages as not-synced without calling a store.
Adds the batch-path held test.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEkQ5mC8eA4qtKSweeF7wd
@github-actions github-actions Bot added size/xl 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

github-actions Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 3 package(s): @objectstack/service-knowledge, @objectstack/service-queue, @objectstack/spec, touching 57 documentable anchor(s). ⚠️ 3 changed file(s) yielded no anchor (packages/services/service-knowledge/src/index.ts, packages/spec/api-surface/contracts.json, packages/spec/export-origins/contracts.json), so the pages documenting them are NOT COVERED by this run — this is not a clean bill of health for those files.

6 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), KnowledgeServicePlugin (symbol, a top-level class))
  • content/docs/automation/webhooks.mdx (via DbQueueAdapter (symbol, a top-level class))
  • content/docs/kernel/contracts/metadata-service.mdx (via publishedAt (symbol, a field of interface KnowledgeRecordSyncBatchItem))
  • content/docs/kernel/runtime-services/audit-service.mdx (via locked_until (literal, a string literal in reclaimExpired))
  • content/docs/kernel/runtime-services/queue-service.mdx (via QueueBatchHandler (symbol, a top-level type), QueueBatchOutcome (symbol, a top-level type), QueueBatchSubscribeOptions (symbol, a top-level interface), subscribeBatch (symbol, a method of class DbQueueAdapter; a method of interface IQueueService))
  • content/docs/protocol/knowledge.mdx (via KnowledgeService (symbol, a top-level class), KnowledgeServicePlugin (symbol, a top-level class))

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

  • content/docs/releases/v17/17-5.mdx (via DbQueueAdapter (symbol, a top-level class))

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
  • 3 changed file(s) yielded no anchor (packages/services/service-knowledge/src/index.ts, packages/spec/api-surface/contracts.json, packages/spec/export-origins/contracts.json) — pages documenting those are invisible to this run
  • 1 cross-cutting symbol(s) contributed no route anchor: maxBatch (4 routes)
  • 11 name(s) were too generic to anchor anything (single lowercase words)
  • the SDK route bridge reached 69 of 253 client-bound route-ledger rows — the other 184 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 184: 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; 125 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 — 181 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 d1a06a3d83f97c4056ccca062a049715d205026b → packageMentionDocs.

Which tree this was computed on

This run read content/docs from 76b18d16725420b7f5161809de49f1f02ea4374f — the merge of head 76742ab087c2f56ffc73dab9d9a6cef50c7c173c into base d1a06a3d83f97c4056ccca062a049715d205026b, 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 76b18d16725420b7f5161809de49f1f02ea4374f && git checkout 76b18d16725420b7f5161809de49f1f02ea4374f
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin d1a06a3d83f97c4056ccca062a049715d205026b 76742ab087c2f56ffc73dab9d9a6cef50c7c173c && git checkout -B drift-repro d1a06a3d83f97c4056ccca062a049715d205026b && git merge --no-ff 76742ab087c2f56ffc73dab9d9a6cef50c7c173c

node scripts/docs-audit/affected-docs.mjs --json d1a06a3d83f97c4056ccca062a049715d205026b

⚠️ 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 d1a06a3d83f97c4056ccca062a049715d205026b → 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#5 · os-project-manager · session_01FEkQ5mC8eA4qtKSweeF7wd
CI red at head cf05bbcf: Test UI (8/16), judged not this PR's · 2026-11-29T06:55Z

  • Failure: job 141257697988 (run 46234099973), 1 of 5,943 tests: ui/packages/auth/src/__tests__/registerMismatchFieldError-25885.test.tsx:138, "RegisterForm — inline errors, all at once … a short password that also does not match shows both messages together, and sends nothing", AssertionError: expected 'Enter your name' to be null.
  • Why not this PR's: the diff touches only packages/spec/src/contracts/queue-service.ts and its API-surface outputs, packages/services/service-queue/src/**, packages/services/service-knowledge/src/** and changesets. No ui/** file and nothing @object-ui/auth imports. The same job is green on main at ea82c962 (the base this head merges cleanly into).
  • Action: one re-run of the failed jobs through the relay (rerun-failed.mjs) once run 46234099973 completes. A second failure on the re-run is read as real.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-project-manager · session_01FEkQ5mC8eA4qtKSweeF7wd
Contract-review-claim: session_01FEkQ5mC8eA4qtKSweeF7wd · head cf05bbc · 2026-11-29T07:18Z

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

Final green head declared for L1: cf05bbcf4f2b58d172cb39cc987879cc0d0dc979.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

Contract review

Served-tier: CONTRACT_REVIEW_TIER
Head-sha: cf05bbcf4f2b58d172cb39cc987879cc0d0dc979
Local-runs: none
Scope: packages/spec/src/contracts/queue-service.ts + packages/services/service-queue/src/db-queue-adapter.ts, packages/services/service-knowledge/src/knowledge-service-plugin.ts, packages/services/service-knowledge/src/knowledge-service.ts, packages/services/service-knowledge/src/knowledge-record-sync-queue.ts
Security-touching: no
Rule-change-verified: none

Round 1 on PR #38509 for card #38413. Read: the card body and its 10 comments (triage 7248383369, both claims, the four dev reports, the serial note 7250530624, analysis 7249459668, ruling 7250307515), the PR body and its 3 comments, the net diff of 12 files against merge base 91fc3980, and the check-runs on the head: 71 runs, 60 success, 11 skipped, none failed (Test UI (8/16) was red once on a ui/packages/auth test, then green on its re-run; the diff holds no ui/ path). The contract the change implements is ruling 7250307515 (letter A) with its four execution conditions, and the card's acceptance as written.

The scope is widened past the one hits file on purpose. The ruling leaves the batch size and the backlog threshold to this review, and both live in the knowledge worker, so the four implementing files are judged in ④. The two test files, the two generated JSON files and the two changesets are the lane seat's ACCEPT.

Security-touching: no: no hunk changes who may read or write what. The batch re-read (rereadRows) uses the same system identity and the same where AND id predicate as the per-message rereadRow. No .claude/** path is in the diff, so Rule-change-verified: none.

① Derived judgments

  • IQueueService.subscribeBatch is optional, and the three new exported types are additions. An implementation without the member still compiles, and the consumer has a declared fallback. Right: a widening, as ruled.
  • packages/spec/api-surface/contracts.json and export-origins/contracts.json gain exactly the three type names. Right; the spec gates on the head are green.
  • DbQueueAdapter.subscribe gains a refusal (a queue that already has a batch handler), and subscribeBatch refuses the reverse and a second batch handler. Right: reachable only once the new member is used, so no existing caller is narrowed, and it is the contract's own sentence.
  • DbQueueAdapter.unsubscribe now waits out the in-flight batch of that queue (db-queue-adapter.ts:509). Right in itself; see S1 for what the first consumer makes of it.
  • DbQueueAdapter.getQueueSize answers through engine.count when the engine has it. Right: the contract says "number of pending messages", and the old answer stopped at 10,000. The call matches IDataEngine.count(object, query, options) with the system context in options.
  • Per-message queues keep the main loop: pollOnce still claims batchSize per tick for handlers only, publish wakes the main loop for them, and renewLease and settleRow are unchanged for one id. Right: ruling condition 3 holds (mail send, mail attachment reclaim and API-flow files are not in the diff, and the shared code they run is behaviour-identical).
  • The knowledge worker picks subscribeBatch when present, else per-message subscribe (knowledge-service-plugin.ts:966). Right: ruling condition 1.
  • One outcome per message end to end: the adapter settles each row by its own outcome, and the worker falls back to per-record syncing when a group fails, so only the bad record answers ok: false. Right: ruling condition 2 and acceptance 3.
  • KnowledgeRecordSyncOutcome gains covered, answered on BOTH paths (processRecordSync now takes the publish time too). Wrong as built: the set of messages completed without a sync is too wide. See M1.
  • KnowledgeService.processRecordSyncBatch is new and public, and the messages stay identifiers only. One planIndex per group write keeps one fingerprint (ADR-0161 K7), and no IKnowledgeAdapter member is added (K8). Right.
  • The held check sits in resolveRecordSync, after the parse and before any source, store or engine access, on both paths. Right: it is the order feat(service-knowledge)!: a knowledge service the runtime mounts holds its sources without an embedder or its deployment store #38470 merged (malformed first, then held).

② Semver level

Two changesets: @objectstack/spec patch and @objectstack/service-queue patch in one, @objectstack/service-knowledge patch in the other. Every published package the diff moves is covered. Both bodies and the PR body carry Clause-②: yes (widening) and Metadata-protocol: none at line start.

The level is right. The change adds a TypeScript contract member, not anything a metadata author can write, so the kind is none, and AGENTS.md gives none a patch ("a non-protocol change, widening or breaking, ships patch"). Clause-②: yes (widening) is right and is what the ruling states. No narrowing arm applies. Check Changeset is green on the head.

③ Boundary flags

  • Held check placement (dev report 7252039255, "the seat may rule otherwise"): answered, right as built. It keeps feat(service-knowledge)!: a knowledge service the runtime mounts holds its sources without an embedder or its deployment store #38470's order, and both paths sync nothing while held.
  • "Acceptance gap" line in the PR body (50,000 records measured on a local SQLite and libSQL file with a modelled embedder): not closed by this review, escalated to the seat and the maintainer as the PR asks. One thing the local run cannot show: every message still costs two sequential queue writes (one claim, one settle), so on a remote store the drain rate is bounded by write latency, not by the embedder. The card's measured deployment had a remote embedding endpoint; acceptance 2 asks for a real store and embedder.
  • Acceptance 1 wording, for the lane seat: the 1,000-sync test pins adapter writes (at most 10 upserts and 10 deletes) and counts embedded DOCUMENTS (embedCalls has one entry per document handed to upsert, 900). It does not count embedder requests. The PR body calls the 900 "embedder calls". The only request count is the local run's 500 requests per 50,000 records.
  • Ask 3 split to service-knowledge: the sync state shows each source's record-sync backlog while it drains #38489: consistent with triage 7248383369 ("splits off as a Feature if it adds a stored field"). The folded getQueueSize cap is fixed here. Fixes #38413 closes the card with ask 3 moved and acceptance 2 open; that is the seat's call.
  • check:dual-build-cjs-loads not run locally: the head's check-runs are the verdict, and none is red.
  • Analysis 7249459668, "a batch claimed under one lease has to finish inside it or extend it": answered, extended. One compare-and-set write renews every claimed row each third of the lease while the handler runs. Two phases are not renewed: the claim (one write per row under a lease stamped before the candidate read) and the settle (one write per row after renewal stops). At 100 rows and a 30 s lease that leaves about 200 ms per write, which holds for the default.
  • SQL push-down: rereadRows is one read with where AND id $in in place of N reads, getQueueSize is a count in place of a 10,000-row read, and the lease renewal is one multi-row write. All three push down. One finding with no reason given in the diff: the batch claim and the batch settle are per-row writes (N1).
  • open_questions: empty in the final report. The two earlier ones are closed by ruling 7250307515 and by the merge of feat(service-knowledge)!: a knowledge service the runtime mounts holds its sources without an embedder or its deployment store #38470.

④ Design judgment

packages/spec/src/contracts/queue-service.ts against ruling A and its first consumer. The member is optional, takes one handler per queue and a required maxBatch, and settles per message through QueueBatchOutcome. That is what was ruled, and it passes ADR-0119 D3: it lands with its implementation and its first caller. DbQueueAdapter agrees with the doc sentence by sentence: up to maxBatch per call; a throw or a wrong outcome count fails the whole batch; ok: false takes the per-message retry and dead-letter path with error recorded; the other kind of subscription is refused; unsubscribe removes the batch handler; other queues are delivered as before. The name and signature are sound. Outcomes are matched by position, guarded by the length check.

Batch size 100 is supported by its numbers: about 0.48 s per batch against a 30 s lease, the rebuild's page size, and a crashed worker's messages return one lease later.

M1 (must-fix) — covered drops deletes that the build never performed. coveredByBuild (knowledge-service.ts:3490) completes a message without a read whenever the source's last build on this node is done and began more than 5 s after the publish. Its reason is "that walk already wrote the document the message asks for". A message for a deleted row, or a row that left where, asks for a deletion, and only the build's purge deletes. A build ends done with purged: null in two cases: the adapter has no listDocuments (:1205), or the listing failed and the walk went on (:1048, :1204, then finish('done') at :1637). In both, a waiting delete message published before that build is answered covered, and the deleted record's document stays in the index and stays searchable.

  • On an adapter without listDocuments nothing ever removes it: the reconcile excludes such a source, and a rebuild does not purge.
  • On the three in-repo adapters it lasts until a later build lists successfully.
  • On main the same message deletes the document, so this breaks acceptance 4 ("deletes and where-excluded records … leave the index as the per-message path does"), on the per-message path too.
  • It is reachable in the card's own workflow: a bulk change, then an operator rebuild while messages wait.
  • The backlog path checks reconcileExclusion; coveredByBuild does not, and no test covers a delete against a build that purged nothing.
  • The build record already carries what is needed (result.purged is a number only when the purge ran).

S1 (should-fix) — the backlog rule (ask 2) is not supported by its numbers, and waiting inside the batch handler has failure modes the batch path alone does not have. The ruling leaves the threshold to this review.

  • (a) The dev's own figures show no gain: 238,998 ms with the reconcile against 242,086 ms without, 1.3%. At the measured 206.5 messages per second, 5,000 waiting messages drain in about 24 s, while a reconcile walks the whole source whatever the size of the change.
  • (b) The card says "above a backlog threshold for a source". The trigger is the queue's backlog for every source together, plus 50 of one batch. So a 50-row write to a large source B, made while source A is being imported, walks all of B.
  • (c) The handler awaits the reconcile (:3573), and the queue has one batch loop. Every source's syncs wait behind one source's walk, 100 leases are held for the whole walk (the contract's own doc says to size a batch to settle well inside the lease, and says nothing about an adapter keeping messages while the handler runs), and unsubscribe at shutdown waits it out. Messages published during the walk are not covered by it, so when 5,000 arrive during one walk the next batch asks for another: a source under sustained writes never returns to chasing and re-walks back to back.
  • (d) Nothing remembers a reconcile that did not end done. A walk that fails late, loses its lease or times out is asked for again before every 100-message batch while the backlog stays over the threshold.

S2 (should-fix) — sole-writer lease tracking has a window the comment at db-queue-adapter.ts:862 says is closed. claimBatch records each claimed row in unsettledLeases as it claims (:1039), but the rows enter batchInFlight only when dispatchBatch starts (:1148), after the whole claim. A main-loop reclaimExpired whose read is in flight during that claim then deletes those entries (:865), and it did not see the rows. If such a row's settling write later fails, a soleWriter adapter never reads again and the message stays running until restart, which #30228 guarantees against on the per-message path. Both loops tick at once at boot, so the overlap is real. It needs a failed write as well, so it is narrow.

N1 (nit) — the batch claim and settle are 2N sequential single-row writes (claimBatch reads maxBatch * 3 full rows, then writes one row at a time; the settle loop at :1173), where the renewal already shows the one-write id $in shape. The claim write is by id alone, so two nodes draining at once can both claim the same rows. A follow-up card; it is also what a remote-store measurement would expose (③).

N2 (nit) — the settle loop stops at the first settling write that throws. The rest of an already-handled batch is then left to the lease reclaim, which counts a failed attempt for each.

N3 (nit) — a batch-queue row the main loop reclaims is not announced to that queue's loop, so it can wait that loop's idle backoff (30 s ceiling by default) past its own backoff.

N4 (nit) — content/docs/kernel/runtime-services/queue-service.mdx is hand-written, names this contract file as its canonical source and lists every IQueueService method. It has no subscribeBatch line. The package index of service-knowledge also does not export the batch item and result types that processRecordSyncBatch's public signature uses.

M1 fails the round. Its fix, and the fixes of S1 and S2, each earn a delta review.

Implemented-by: claude/project-thread-caiyo5
Reviewed-by: session_01FEkQ5mC8eA4qtKSweeF7wd

VERDICT: FAIL

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

The brief the record above was rendered from (filled from record-recognisers.mjs --brief-template; the reviewer is an isolated model: fable, effort: high sub-agent of this card thread, transcript verified by verify-review-tier.mjs: PASS, 92 of 92 turns at CONTRACT_REVIEW_TIER).

Contract review brief — PR #38509 @ cf05bbcf4f2b58d172cb39cc987879cc0d0dc979 (card #38413)

You review at CONTRACT_REVIEW_TIER. Render ONE ## Contract review record on this head — its shape is
node scripts/pm/record-recognisers.mjs --template — with a PASS or FAIL verdict, and post it as ONE comment
on the PR or its card.

Inputs — these and nothing else:
· card #38413: its body and EVERY comment (rulings and earlier records included)
· PR #38509: its body, its file list, and the net diff against main at cf05bbcf4f2b58d172cb39cc987879cc0d0dc979
· the check-runs on cf05bbcf4f2b58d172cb39cc987879cc0d0dc979: their conclusions ARE the gate verdicts
⛔ Not the dispatch order, ⛔ not the dispatching seat's own conclusions — this brief is adversarial by design.

Scope — the paths reviewFace returns as hits on this PR's file list: packages/spec/src/contracts/queue-service.ts;
plus every file IN THIS DIFF that directly implements or enforces them — the gate that enforces a rule, the code
a jsdoc or schema line describes, the validator a skill teaches — reviewed for agreement with the contract.
Widen it freely, ⛔ never below hits; the record's Scope: line names the implementing files apart from hits.
The rest of the diff (tests, unrelated modules, lockfiles, generated output, changesets) is the lane seat's
ACCEPT at TIER_DEFAULT, exactly as a standalone PR of those files.
④ judges the hits files and those implementing files ONLY:
lockfiles, generated output, changesets and prose elsewhere in the PR are not reviewed;
code outside the diff is READ to judge them, never reviewed.

Security — if a hits path is under skills/** or ui/skills/** and the change teaches security, auth or permission
behaviour the path name doesn't show, the record says so and the seat adopting the record adds the security label.
The record says so on its Security-touching: line, and the arm lands on no alone: write no ONLY when no changed
hunk teaches permission, sharing, credential, token, authentication or other security behaviour, else yes.

Rule change — if a hits path is under .claude/**: the PR body declares Rule-change: and you verify it against the diff.
Write Rule-change-verified: none ONLY when no changed hunk alters what an agent may do without the maintainer
(merge, bypass a check, change repository settings), what gets done and in what order (grading, dispatch, scope), or
what must go to him (decisions, maintainer actions); process steps, scripts, wording, slimming and file moves are not rule
changes. Write ruled ONLY when every such hunk copies the ruling the PR body quotes on its Ruling-ref: line — check the
copy against the quoted words, do not re-rule it. Otherwise yes: the pull request then waits for the maintainer.

⛔ READ-ONLY. No worktree, no checkout, no build, no test run, no gate re-run, no ablation: the check-runs
on the head already answered every derived gate family, and a local run costs more than it returns.
If ONE probe is unavoidable, the record's Local-runs: line says probe — REASON; otherwise none.
Scratch space is /tmp/claude-0/-home-user/abca35f6-7bcb-5f8c-b4fb-93c3e90b6d68/scratchpad/pr-38509/ alone; nothing there you did not write this round is read.

Judge, in the record's own sections:
① Derived judgments — every accept-set and public-surface change the diff implies, each named right or wrong.
② Semver level — the changeset (or skip-changeset) matches what the diff publishes, and the Clause-②: line.
③ Boundary flags — every dev flag and every open_questions entry answered, or escalated.
On every face, SQL push-down: a new id materialisation or in-app join where SQL could push down is a
finding unless a reason is given (AGENTS.md, Prime Directive 5: SQL first).
④ Design judgment — for EVERY hits file: does the change hold against the code it cites and the
scenario it is accepted against? A skill file against the card's eval prompt and the spec it teaches
on main; a schema file against the ruling or ADR it implements and its first consumer; an ADR
against its first consumer and its execution plan. For EVERY implementing file in the diff: does the
code agree with the contract, sentence by sentence? Read the cited code in the live tree, and try to
break the design.
Grade each finding must-fix, should-fix or nit — a nit has no effect on correctness or the contract.
A must-fix is a FAIL; a must-fix or should-fix earns a delta review of its fix; nits alone end the round.
Spell a must-fix or should-fix with its id and grade, S1 (should-fix) — …, and a clean round as
No must-fix, no should-fix.: the queue guard reads a graded finding as OPEN on this head and
refuses the record; the delta record names those it closes by id alone, S1: closed.
A nit is fixed only on the prose faces, or left as an accepted deviation or a follow-up card: a fix
anywhere else moves the head, and this record no longer covers it.
⛔ Judge the tree, never the PR body's account of it.
Sign Implemented-by: with the dev's branch and Reviewed-by: with your session id — the value is the FIRST
thing after each colon.

…per source, scheduled, remembered; batch claims in flight from claim

- coveredByBuild requires a done build whose purge ran, on a source the
  reconcile walks, so a delete is never answered by a build that deleted
  nothing.
- The backlog reconcile is per source (queue waiting count times the
  source's share of the batch, against 5,000 and 5 % of its rows),
  scheduled and never awaited, with a 10 min re-walk wait and a failure
  backoff.
- DbQueueAdapter marks batch rows in flight as they are claimed, settles
  every row of a batch even if one write throws, and wakes a batch queue's
  loop for a reclaimed row.
- subscribeBatch documented; the batch item and result types exported.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEkQ5mC8eA4qtKSweeF7wd
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#5 · os-project-manager · session_01FEkQ5mC8eA4qtKSweeF7wd
Contract-review-claim: session_01FEkQ5mC8eA4qtKSweeF7wd · head 76742ab · 2026-11-29T09:11Z

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

Final green head declared for L1 (delta from cf05bbcf): 76742ab087c2f56ffc73dab9d9a6cef50c7c173c.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

席位核对 — L1 ACCEPT (delta from cf05bbc) · head 76742ab · 2026-11-29T09:14Z

This is a delta from cf05bbc: 2 commits, 9 files, +432/−118. It is read against the L1 checklist and against round-1 contract review 7252567666. Checks on this head: 65 success, 14 skipped, 0 failed. One cancelled "PR-body guards" run (08:44:08Z) was superseded by green runs at 08:44:22Z and 08:59:24Z. The design judgments (batch size, threshold, row share, rewalk and backoff values) are the delta contract review's face, not this record's.

My first-look notes (card thread), now answered.

Round-1 findings, as built at this head.

  • M1. coveredByBuild now needs all three: status === 'done'; result.purged a number and result.ok !== false; and reconcileExclusion(entry) === undefined. A build that purged nothing covers no message. The new describe block "a build that purged nothing covers no delete" runs the delete and the where-exit on both paths, for both no-purge causes. The body's ablation (the purge condition removed) turns the two listing-failed cases red.
  • S1. considerBacklogReconcile schedules the reconcile with void and never awaits it.
    • It is per source: the estimate is waiting × the group's share of the batch, and it must reach 5,000 and 5 % of the source's counted rows. The row count goes through IDataEngine.count, which is a required member, and a failed count schedules nothing.
    • State is remembered per source: 10 min after a reconcile that ended done with its purge run, and a 5 min backoff doubling to 60 min after one that did not.
    • Four new cases pin it: synced without waiting, small against rows, one message in another source's backlog, and no retry before the backoff. The old RECORD_SYNC_BACKLOG_MIN_RUN is gone from code and changeset.
  • S2. claimBatch(queue, max, this.batchInFlight) adds each id to the in-flight set before its unsettledLeases entry, in the same synchronous step after the claim write resolves. So a reclaim tick cannot fall between them. dispatchBatch removes the ids in its finally. The new sole-writer case runs a reclaim during the second claim write, and the body's ablation turns it red.
  • N1. Carried on service-queue: the database queue claims and settles a batch one row write at a time, which bounds a drain on a remote store #38548 (open; its title names the one-row-at-a-time claim and settle and the remote-store bound). The body's acceptance notes say the same.
  • N2. Each settleRow is wrapped, so one failed settle no longer stops the rest. The new case gives completed, running, completed.
  • N3. A reclaimed row wakes its batch queue's loop (queue added to the reclaim read's fields). No test pins the wake. That is a nit, not a hold: the worst case is the idle backoff it replaces.
  • N4. queue-service.mdx gains the subscribeBatch? signature line and a paragraph that matches the contract doc. The service-knowledge index exports KnowledgeRecordSyncBatchItem and KnowledgeRecordSyncBatchResult, and the changeset says so.

Changesets and body. Both changesets still carry Clause-②: yes (widening) and Metadata-protocol: none. The queue changeset adds the per-row settle and the reclaim wake. The knowledge changeset's backlog paragraph describes the shipped rule: scheduled, never waited on, per source, with the rewalk and backoff. The body's acceptance notes give every residual a carrier: acceptance 2 is #38529, ask 3 is #38489, N1 is #38548. The round-1 "embedder calls" wording is now "embedded documents" for the test and "embedder requests" for the measurement.

Not run by me. The service-queue and service-knowledge vitest suites need a built objectql dist that this container lacks. The verdict rests on the head's green Test Core shards and the body's two ablations.

ACCEPT on the L1 face. Landing waits on the delta contract review at this head.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

Contract review

Served-tier: CONTRACT_REVIEW_TIER
Head-sha: 76742ab087c2f56ffc73dab9d9a6cef50c7c173c
Local-runs: none
Scope: packages/spec/src/contracts/queue-service.ts + packages/services/service-queue/src/db-queue-adapter.ts, packages/services/service-knowledge/src/knowledge-service-plugin.ts, packages/services/service-knowledge/src/knowledge-service.ts, packages/services/service-knowledge/src/knowledge-record-sync-queue.ts, packages/services/service-knowledge/src/index.ts, content/docs/kernel/runtime-services/queue-service.mdx
Security-touching: no
Rule-change-verified: none

Round 2 on PR #38509 for card #38413. This is the delta round of record 7252567666 (round 1, FAIL, head cf05bbcf). Read: record 7252567666 and its brief 7252571341; the card body and its comments since round 1 (claim 7253083650, which supersedes 7253073280, and dev report 7253420539); the PR body and its comments since round 1 (claim 7253602895, head note 7253608201); the delta cf05bbcf..76742ab0 (2 commits, 9 files) and, where the delta leans on it, the net diff of 14 files against merge base 91fc3980; and the check-runs on the head: 80 runs, 65 success, 14 skipped, 1 cancelled, none failed. The cancelled run is one PR-body guards run; two later runs of the same check on this head succeeded.

The scope is round 1's, plus two files the delta touches to answer nit N4: the export lines of service-knowledge/src/index.ts and the subscribeBatch lines of queue-service.mdx. Both are read against the contract file. The contract file itself, the two generated JSON files and the plugin file did not change since round 1. The test files and the changesets are the lane seat's ACCEPT; the changesets are read for ② only.

Security is not touched: the delta adds one read, a count of the source's rows under its own where as the system identity, which is the identity and predicate the walk already uses. No hunk changes who may read or write what. No .claude/** path is in the 14 files, so Rule-change-verified: none.

① Derived judgments

  • coveredByBuild (knowledge-service.ts:3513) answers covered for fewer messages than at round 1: only after a build that ended done with result.purged a number, on a source the reconcile walks. Right: it is the narrowing M1 asked for, on both paths, since both go through resolveRecordSync.
  • processRecordSyncBatch no longer waits for a reconcile. considerBacklogReconcile (:3681) schedules one and returns. Right as a reading of ask 2 ("stops chasing messages and schedules one reconcile … then drops the messages that reconcile covers"): the worker keeps syncing until the reconcile ends, which is what leg (c) of round 1's S1 asked for, and drops the covered messages after.
  • The backlog constants changed in knowledge-record-sync-queue.ts: RECORD_SYNC_BACKLOG_MIN_RUN is gone, and five are new (row share, re-walk wait, retry wait and its ceiling, row-count lifetime). Right: none is exported from the package index, and none was ever published.
  • @objectstack/service-knowledge now exports KnowledgeRecordSyncBatchItem and KnowledgeRecordSyncBatchResult (index.ts:97). Right: they are the types of processRecordSyncBatch's public signature, both additions.
  • DbQueueAdapter.claimBatch takes the in-flight set as a private third argument, and only pollBatchOnce passes it. The per-message pollOnce calls it as before. Right: ruling condition 3 still holds, since the main loop's claim, dispatch and settle are unchanged.
  • The batch settle loop catches a settling write that throws and goes on (db-queue-adapter.ts:1192). Right: "each message is settled by its own outcome" now also holds when one write fails.
  • reclaimExpired reads queue with each running row and wakes the batch loop of a reclaimed row's queue (:864). Right: the reclaim's write and its verdict are unchanged, and a per-message queue has no batch loop to wake.
  • queue-service.mdx gains the member's signature line and one paragraph. Right: each sentence matches the contract's doc (up to maxBatch per call, one outcome per message in order, a throw or a wrong count fails the call, one kind of subscription per queue, unsubscribe removes either, per-message fallback).
  • packages/spec/** is unchanged since round 1, and the spec gates are green on the head.

② Semver level

The delta changed both changeset bodies and neither level: @objectstack/spec patch and @objectstack/service-queue patch in one, @objectstack/service-knowledge patch in the other. Both bodies and the PR body still carry Clause-②: yes (widening) and Metadata-protocol: none at line start.

The level is still right. The two new exported types are TypeScript additions on a service package, not anything a metadata author can write, so the kind stays none and AGENTS.md gives none a patch. (widening) fits an addition, and no narrowing arm applies: the narrower covered narrows an outcome this same PR introduces, not a published one. The rewritten sentences agree with the tree: the estimate, the 5,000 and 5 % conditions, covered only after a build that purged, the 10 min and 5 min to 1 h waits, the per-row settle and the reclaim wake. Check Changeset is green on the head.

③ Boundary flags

④ Design judgment

M1: closed — coveredByBuild now returns false unless the last build ended done with result.purged a number. Both causes round 1 named end done with purged: null (:1213 for a listing that failed, :1214 for an adapter without listDocuments), and a source the reconcile does not walk is never covered. Acceptance 4 holds on both paths:

  • Not covered: the per-message path re-reads under where and deletes when no row comes back (syncRow). The batch path does the same in one read and one delete (syncRows, :3744).
  • Covered: the build's purge deleted the document after the same where AND id re-read. A purge that stopped part-way ends failed, not done, and covers nothing.
  • Also tried and held: a retried or replayed message (its publish time is its first publish, and a later build still read the row); two saves of one record (no idempotency key, so each has its own publish time); a publish before commit (on the ObjectQL engine the triggers publish after the unit commits).

S1: closed — each leg of it:

  • (a) The rule is now supported by its numbers: 217 s against 233 s with every record changed, and 91 s against 106 s with none changed, where round 1 had 1.3 %.
  • (b) The trigger is per source, an estimate checked against 5,000 and against 5 % of the source's counted rows. The estimate can still be wrong for a clustered burst; that is N6, and it no longer costs what round 1 described.
  • (c) Nothing waits. The batch handler awaits two cached counts and then syncs; the reconcile runs on the service's own serial reconcile queue; unsubscribe waits for the batch in flight only; a walk does not hold 100 leases. A source under sustained writes waits 10 min between walks.
  • (d) A reconcile that did not end done with a purge is remembered: 5 min, doubling to 1 h.
  • Also tried and held: while the scheduled build runs, the source's record reads running, so nothing is covered and every message is synced; the purge and a batch group share the per-document chain, which only appends, so neither can deadlock the other; a store that lists nothing, a held service and stopped builds schedule nothing.

S2: closed — claimBatch adds each row to batchInFlight in the same synchronous step that records its lease entry (db-queue-adapter.ts:1055), so the reclaim's clean-up (:872) never sees a claimed row's entry without its in-flight mark. The marks are cleared in dispatchBatch's finally; the only code between a claim and it is the message mapping, the handler call and its catch. A settling write that fails leaves the lease entry, and the entry's expiry makes the sole writer read again.

Nits of round 1: N2, N3 and N4 are fixed in this head (the per-row settle, the reclaim wake, the docs lines and the two exports). N1 is carried on #38548.

No must-fix, no should-fix.

Four nits follow. None loses a message, and none leaves a wrong index past the next reconcile. N5 and N8 each need an unusual latency plus a coincidence of events; N6 and N7 cost a walk or a log line.

N5 (nit) — covered has no guard against a sync still in flight, other than the 5 s margin, whose docblock names clock skew only (knowledge-record-sync-queue.ts:217).

  • The case: a sync re-reads a record; the record is then written again; a build of the source starts more than 5 s after that second write while the first sync is still waiting on its store write; and that write lands after the walk wrote the record, or after the listing for a record created and then deleted.
  • The result: the older document, or a deleted record's document, stays in the index, and the second write's message completes as covered. On main that message repairs it. Here the next build that purges does, which is where ADR-0161 K1 puts an index's correctness ("a reconcile pass keeps it correct").
  • Reach: one sync must stay in flight for more than 5 s. A 100-message batch takes about 0.5 s in the dev's model. The in-repo embedder neither retries nor bounds a request, so a slow provider answer is the way there.
  • It was in the round-1 head. The delta adds one way in: a backlog reconcile queued behind another source's walk now starts while batches run.
  • A follow-up card is owed. Two ways to answer it: a wider margin (at the queue lease, 30 s, the only cost is a normal sync for the messages inside it), or a docblock that says the margin is also this guard.

N6 (nit) — the per-source estimate reads another source's backlog as this source's when a burst is clustered in one batch.

  • The estimate is the queue's whole waiting count times the source's share of the one batch in hand (knowledge-service.ts:3691).
  • Round 1's own example still walks: 50 rows written to source B at once, inside source A's 50,000-message backlog, fill half a batch, so B's estimate is 25,000 and B is walked if it has up to 500,000 rows.
  • The row-share check does not stop this, because it is fed the same estimate. The docblock sentence "so a small write to a large source is drained, not walked" is true only of a write spread across batches.
  • The cost is now one walk that embeds nothing for unchanged rows, beside the drain, at most once per 10 min per source. An exact count is service-knowledge: the sync state shows each source's record-sync backlog while it drains #38489's stored counter.

N7 (nit) — the reconcile's completion handler reads the source's last build record, not the pass it scheduled (:3710).

  • rebuildOf does not double a running build, so a backlog reconcile that meets an operator rebuild in progress returns at once and is logged and counted as a failed reconcile ("ended running"), with a 5 min wait.
  • A pass that walked nothing because builds stopped at shutdown is counted from whatever older record is there.
  • Both are bounded by the waits. armReconcile shows the other shape: it waits for a running build.

N8 (nit) — one interleaving is left in the sole-writer tracking: a reclaim read that starts before a batch's claim and returns after that whole batch has settled, with one settling write failed, still drops that row's lease entry unseen, and the message then stays running until the next reclaim read or a restart. One read would have to outlast the batch's claim, handler and settle. Taking the entry keys before the read, and clearing only those, would close it.

Implemented-by: claude/project-thread-caiyo5
Reviewed-by: session_01FEkQ5mC8eA4qtKSweeF7wd

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

维护者速读

席位意见:同意合并。

席位核对 — ACCEPT · repo:objectstack#5 · Head-sha 76742ab087c2f56ffc73dab9d9a6cef50c7c173c · 2026-11-29T09:32Z

  1. 形态:open draft → main,14 files,+1,468/−77,Part of #38413,Clause-②: yes (widening),Metadata-protocol: none,两条 changeset 均为 patch。
  2. 前提实测:Tier H(spec 契约面加可选成员,裁决 A 7250307515 授权其形状)。契约记录 7253810720:VERDICT PASS,Served-tier CONTRACT_REVIEW_TIER,Head-sha 即本 head,Security-touching: no,Rule-change-verified: none;M1、S1、S2 已闭,N2–N4 已修。前序:第 1 轮 FAIL 7252567666(brief 7252571341)。复审由卡线程的独立子代理按自带 brief 完成,实现由 os-dev 子代理完成,按席位对独立性的既有采纳办。
  3. 门禁 check-runs:本 head 65 success、14 skipped、0 失败;1 条 cancelled 是被同 head 两次成功跑次取代的 PR-body guards。mergeable_state clean。
  4. 接受的偏差:吞吐数字来自标注清楚的本地模型,不当生产数据;真实服务的读数归 service-knowledge: measure a 50,000-record bulk-import drain with a real embedding provider, against a rebuild of the same records #38529。
  5. 范围外去向:验收 2 → service-knowledge: measure a 50,000-record bulk-import drain with a real embedding provider, against a rebuild of the same records #38529;ask 3(按源精确积压计数)→ service-knowledge: the sync state shows each source's record-sync backlog while it drains #38489;N1(多节点同时认领与逐行写)→ service-queue: the database queue claims and settles a batch one row write at a time, which bounds a drain on a remote store #38548;N5(covered 对仍在途同步只有 5 秒余量)→ 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 #38556;N6–N8 是有界的小问题,不另立卡(每源每 10 分钟至多多走一次对账,或一条日志、一次重读)。
  6. 落地条款:Tier H,维护者批准后才入队;契约档 L2 PASS 7253810720 与 L1-a ACCEPT 7253631797 同在本 head。批准后由席位落地(ready + auto-merge)。合并后 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 是部分落地,席位按部分落地处理。⛔ 未批不入队。

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

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

Approval requested (Tier H: Clause-②: yes (widening), an optional member on the IQueueService contract under ruling A 7250307515) · 2026-11-29T09:33Z

@objectstack-fleet objectstack-fleet Bot added the pm:awaiting-merge PR only: landing waits on the maintainer's own review and merge (SKILL.md 复核 ②); never on an issue label Nov 29, 2026
@os-zhuang
os-zhuang marked this pull request as ready for review November 29, 2026 09:36
@os-zhuang
os-zhuang added this pull request to the merge queue Nov 29, 2026
Merged via the queue into main with commit a5fe764 Nov 29, 2026
85 of 86 checks passed
@os-zhuang
os-zhuang deleted the claude/project-thread-caiyo5 branch November 29, 2026 10:02
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
…ce.documentBy`); record search groups by it by default (objectstack-ai#38564)

<!-- claude-projects-attribution: {"github_login":"os-project-manager"}
-->
_Requested by **Leehom** · [project
thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XDXvJPPtrTGfdDYhWWpihq5)_

Part of objectstack-ai#38537
Clause-②: yes (widening)
Metadata-protocol: added

## 维护者速读

- 用户能看到什么变化:知识源可以声明“文档单位”(指向父记录的字段);AI
按记录检索时,同一份父记录(如一份制度)下的多条子记录(条款)只返回一条命中,原来是每条子记录各一条;Studio
知识源表单多了一个“文档单位”选择框。
-
为什么做:属于“知识源声明文档单位、按父记录计数与聚合”专题,替把段落写成子记录的应用(例如制度下的条款)解决按记录检索时同一份制度刷屏的问题,也是云端按父记录计文档数的前置。
- 出错会怎样:只有声明了该字段的知识源受影响,索引内容不变、不触发重建;若分组有误,AI 检索会多返回或少返回命中,删掉该字段即恢复原行为。
- 要你做什么:无。

## What changes

PR 1 of 2 for the card. This PR lands the key, its parse rule, its
save-time refusal and its first reader; the `os validate` rule (in the
lint package, held by another seat until it is released) is PR 2, which
closes the card.

- **Spec** — `ObjectKnowledgeSourceSchema` gains `documentBy?: string`.
A refinement refuses a value that `metadataFields` does not list, with a
message that names the field, the list, and the fix (add it to
`metadataFields`, name a listed field, or remove the key). The
refinement is a cross-key rule JSON Schema cannot state, so it is
ledgered in `dropped-refinements.baseline.json` (two schemas plus the
four installed-package response schemas that embed a source; header
totals updated).
- **Parent-link rule, exported** — `knowledge-search-scope.ts` now
exports `parentLinkRule(schema)` (the rule `scopeTermsFor` already used,
factored out of the private `parentLinksOf`, which now calls it; scope
behaviour unchanged) and `documentUnitOf(field, schema)` (the rule plus
"not `multiple: true`"). Both are pure functions of the object
definition, so PR 2 can call them with no knowledge service.
- **Save door** — `admitAuthoredSource` refuses a `documentBy` that
`metadataFields` lists and that is not a single-valued parent link: `400
VALIDATION_ERROR`, `field` set, after the "does not exist" arm and
before every permission arm. The sentence is built by
`documentUnitRefusalText` in `knowledge-source-admission.ts`, one
wording per reason (undeclared, withheld, not a link, no readable
target, multiple). A `documentBy` that `metadataFields` does not list is
left to the parse, which already names that fix.
- **Reader (ADR-0049, ADR-0161 K4)** — in `searchByKey`, with record
granularity and no `groupBy`, `groupKeyOf` now asks `documentKeyOf(hit,
documentBy)`: `parent:SOURCE#VALUE` when the hit's source declares
`documentBy` and the hit carries a parent, else the existing per-record
key. The explicit `groupBy` path, `sourcesGroupableBy` and chunk
granularity are untouched.
- **Tool** — `hitOf` sets `groupValue` to the parent under the default
grouping too (absent for a record with no parent). `documentUnitValueOf`
is the one predicate both the service key and the tool read. Like its
`groupBy` arm, the tool serves the parent only for a source that lists
`documentBy` in `metadataFields`.
- **Hashes** — `documentBy` is in neither the index fingerprint nor the
recipe hash (both enumerate their inputs explicitly);
`__tests__/index-fingerprint.test.ts` is unchanged and green.
- **Form** — the form-coverage gate
(`metadata-form-zod-reconciliation.test.ts`) refused the key without a
form row, so the single picker is added beside `metadataFields`
(`widget: 'field-ref'`, `dependsOn: 'object'`) with its form test.
**This folds in the form half of objectstack-ai#38538**; the docs and `skills/**` half
stays there. The row brings its regenerated translation bundles (ja-JP,
es-ES and zh-CN authored, the rest the extractor's fill) and the
catalog's positive-control count (866 to 867).
- Regenerated: authorable-surface, the reference page, the liveness
ledger row and counts.
- **Changeset** — `minor` for `@objectstack/spec` (the new authorable
key), `@objectstack/service-knowledge` (the reader and the save refusal)
and `@objectstack/platform-objects` (the form row's translated label and
help), with `Metadata-protocol: added`: a new key a metadata author can
write.

## Zone 2 choices

- **Where the parent value is read from:** the hit's own
`metadata[documentBy]`, the value assembly stored beside the passage.
The parse holds `documentBy` in `metadataFields`, so every hit of such a
source carries it; grouping runs over the hits the adapters already
answered and reads no record (SQL first: no per-hit read was added). The
freshness check and the permission re-check are unchanged.
- **Default key spelling:** `parent:` + index key of the hit's source +
`#` + `String(value)`. The source key keeps two sources apart on equal
parent ids; the `parent:` prefix keeps it apart from `record:` and
`document:` keys; `String()` compares values as a scope term does. A
value that is absent, null, empty, or not a string or finite number
falls back to the per-record key, so those records are never dropped.
- **Form row:** forced by the gate (it reported
`knowledge_source.source: accepted by the Zod but unauthorable in the
form — documentBy`), so it is in this PR.

## Acceptance

| Card acceptance line | Test |
|:--|:--|
| Parse refuses `documentBy` absent from `metadataFields` |
`knowledge-source.test.ts` › "refuses a `documentBy` that
`metadataFields` does not list…", "…when `metadataFields` is omitted…" |
| Save refuses a text field, a `user` field, an `internal` lookup and a
`multiple` lookup, each naming the fix | `document-by-38537.test.ts` ›
"refuses a text field / a user field / an internal lookup / a multiple
lookup, 400 VALIDATION_ERROR, naming the field and the fix" (+ positive
controls: lookup and master_detail admitted) |
| 6 records under 2 parents + 1 null parent, record granularity, topK 10
→ 3 hits | `document-by-38537.test.ts` › "6 records under 2 parents plus
1 with no parent…: 3 hits" |
| Explicit `groupBy: 'clause_hash'` unchanged; a source without
`documentBy` unchanged | `document-by-38537.test.ts` › "an explicit
groupBy is answered as before…", "a source without documentBy is
answered as before…", "chunk granularity is answered as before" |
| Fingerprint pins unchanged | `index-fingerprint.test.ts` unchanged and
green; `document-by-38537.test.ts` › "the fingerprint and the recipe
hash are the same with and without documentBy" |
| Default key includes the source; `hitOf` sets `groupValue` | "two
sources never share a group…", "search_knowledge: each hit carries its
parent as groupValue…" |

## Ablation

Both legs run with `scripts/ablation-replace.mjs` (mutation verified on
disk, restore verified as blob equal to HEAD and an empty `git diff
HEAD`). No build was needed: both suites import the subject from `src/`.

<details><summary>Reader reverted (default key back to the per-record
key): 4 red</summary>

Anchor `if (groupBy === undefined) return documentKeyOf(...)` replaced
with `return recordKeyOf(hit)` in `knowledge-service.ts`.
`document-by-38537.test.ts`: 4 failed / 12 passed — the 3-hit test, the
empty-parent test, the two-sources test and the `groupValue` test.
Restored: blob c98a036 equals HEAD.
</details>

<details><summary>Parse rule removed (the refinement dropped): 2
red</summary>

Anchor `.superRefine(refuseDocumentByOutsideMetadataFields)` removed
from `knowledge-source.zod.ts`. `knowledge-source.test.ts`: 2 failed /
35 passed — both refusal tests. Restored: blob 211cb6d equals HEAD.
(A first attempt was refused by the tool before running anything,
because its replacement text already occurred in the file; it was re-run
with a distinct replacement.)
</details>

<details><summary>Delta round 1: the tool's metadataFields guard
removed: 1 red</summary>

The condition `&&
objSource.metadataFields?.includes(objSource.documentBy)` removed from
`hitOf` in `knowledge-tools.ts` (on-disk count 0).
`document-by-38537.test.ts`: 1 failed / 16 passed, the stub-service test
("expected … to not have property groupValue"). Restored from a copy
(on-disk count 1) before commit `12cd7dc8a6`, whose blob `e49165a005`
carries the condition. This leg used a copy-and-restore, not
`ablation-replace.mjs`.
</details>

## Tests

**Delta round 1 (contract review 7254573293, PASS with S1 open), head
`e0ebb9ad8e`.** S1: the `documentBy` docblock names the save refusal
alone, and says a source registered in code or installed with a package
meets no save and is not judged yet. N1: the docblock and the changeset
say where each surface carries the parent: `metadata[documentBy]` on
`IKnowledgeService.search`, and also `groupValue` on a
`search_knowledge` hit. N2: the form help reads "Setting it rebuilds
nothing; adding the field to Filter fields does." The changeset says the
same, and the zh-CN, ja-JP and es-ES help is retranslated. The eleven
bundles are regenerated: `check:i18n` reports all in sync, and
`check:i18n-stale-fill` finds no new stale fill. N3: the `hitOf` guard,
pinned by one stub-service test with a positive control. Claim widening:
the contract TSDoc and the tool description above. Readings on
`e0ebb9ad8e`:
- `@objectstack/service-knowledge`: test 23/23 files, 803/803 tests; the
new test file 17/17 after its type fix; typecheck exit 0.
- `@objectstack/spec` test: 913/913 files, 28896 passed, 1 todo.
- `@objectstack/platform-objects` test: 130/130 files, 2218/2218 tests.
- spec `check:generated`: all 14 artifacts up to date, against a dist
built after the spec edits.
- Changeset and byte gates, each exit 0: `check-changeset-no-major` with
this body as its event payload (level axis `yes (widening)` / `added`),
`check-empty-changeset`, `check-adr-0087-registration`,
`check-changeset-fixed`, `check-nul-bytes`,
`check-spec-docblock-symbol-anchors`.
- overlap-check: origin/main merges cleanly; it conflicts only with
objectstack-ai#38550 and objectstack-ai#38497, on the hand-maintained counters as before.

**Delta round 1, second commit, head `43de68d58f`.** The claim was
amended to add the `topK` TSDoc and the tool's `granularity` input
description. Both now say what the fixed docblocks say: "for a source
that declares `documentBy` (its document unit), one hit per parent
record instead". So do the other record-unit sentences in the two files
(see Acceptance notes). Readings on `43de68d58f`:
- `@objectstack/service-knowledge`: test 23/23 files, 803/803 tests;
typecheck exit 0. This covers the `granularity` refusal sentence: no
test pins its text.
- spec `check:generated`: all 14 artifacts up to date, against a dist
built after the edit.
- `check-spec-docblock-symbol-anchors` and `check-nul-bytes`: each exit
0.
- overlap-check: unchanged (origin/main clean; conflicts only with
objectstack-ai#38550 and objectstack-ai#38497 on the counters).

The `@objectstack/mcp` knowledge-tool tests compare the listed
description with the definition itself and pin no text, so they were not
re-run here.

Earlier, the head was `5bbac4b457`, a clean merge of main that brings in
objectstack-ai#38509 (the record sync change in `knowledge-service.ts`). Re-checked on
that head: `@objectstack/service-knowledge` test 23/23 files, 802/802
tests; its typecheck exits 0; `@objectstack/spec` `check:generated`
reports all 14 artifacts up to date; overlap-check finds origin/main
merges cleanly. Below it, `231e7c6339` changes only the changeset (level
`minor`, `Metadata-protocol: added`); the changeset families were re-run
there (`check-changeset-no-major` with this body as its event payload,
`check-empty-changeset`, `check-adr-0087-registration`, all exit 0). The
gate union was re-run after the last code commit, at `a92874657e` (the
translation commit landed while it ran, and the families that read it,
`check:i18n`, `check:i18n-stale-fill` and `check:nul-bytes`, were run
again on `a92874657e`).

<details><summary>Package suites and typecheck</summary>

- `pnpm --filter @objectstack/service-knowledge test` — Test Files 23
passed (23), Tests 788 passed (788). `typecheck` (tsc + test layer) —
exit 0.
- `pnpm --filter @objectstack/spec test` — Test Files 912 passed / 1
failed (913), Tests 28895 passed / 1 failed: the dropped-refinements
ledger's header totals; corrected, `scripts/dropped-refinements.test.ts`
re-run 30/30. `typecheck` — exit 0.
- `pnpm --filter @objectstack/platform-objects test` — Test Files 130
passed (130), Tests 2218 passed (2218). `typecheck` — exit 0.
- `pnpm --filter @objectstack/spec check:generated` — two stale
artifacts found (reference page, liveness counts), regenerated with
`--fix`, re-checked green.
</details>

<details><summary>Derived gate families (dispatch-gates --commands,
120)</summary>

`node scripts/pm/dispatch-gates.mjs --ran` — "120 derived, 120 run, 0
NOT-MEASURED, 0 UNRUN"; every family exit 0 on the re-run. On the first
run three families refused with exit 3 (prerequisite not met: no built
CLI, client-react or package dists); each was built and re-run green,
and `check:i18n` then reported the form row's bundles drifted,
regenerated in this PR.
</details>

Not run locally: `check:i18n-coverage` (not derived for this diff;
prerequisite needs the example apps built) and every CI-only family; CI
reports them on this PR. Dogfood: n/a (no `!` in the title, no
`(narrowing)` arm).

## Acceptance notes

- **Files beyond the original claim's list, each forced by a Zone 1 line
(recorded by the claim amendment on the card):** the save refusal is
wired in `admitAuthoredSource` in `knowledge-service.ts` (the save-time
admission lives there, not in `knowledge-source-admission.ts`, which
holds the sentence); `dropped-refinements.baseline.json` (the parse rule
is a refinement, which the spec build refuses unledgered); the
platform-objects translation bundles and the catalog positive control
(forced by the form row the gate required).
- **Spec contract prose:** with the widened claim, this PR now updates
the TSDoc of `KnowledgeSearchOptions.granularity` and `groupBy`
(`packages/spec/src/contracts/knowledge-service.ts`) and the
`search_knowledge` description: a source's `documentBy` sets the unit
for record-level results. After the claim's second amendment, every
other sentence in those two files that stated the record-level unit as
"record" now names the document unit too: the `topK` TSDoc and the
`groupBy` "instead of by record" line in the contract; in the tool, the
`topK`, `granularity` and `groupBy` input descriptions, the matching
`SearchKnowledgeInput` and `SearchKnowledgeOutput.hits` TSDoc, and the
`granularity` refusal sentence. Left for objectstack-ai#38538, outside those two
files: `content/docs/ai/knowledge-rag.mdx` (the `granularity` row) and
`content/docs/protocol/knowledge.mdx` (the record-level paragraph).
- **Not judged:** a source registered in code passes the parse
(membership in `metadataFields`) but no save door, so the parent-link
rule does not judge it; PR 2's `os validate` rule covers packaged
sources.
- **For PR 2 (the `os validate` rule), left undecided here:**
`@objectstack/lint` does not depend on `@objectstack/service-knowledge`,
and `parentLinkRule` / `documentUnitOf` are pure over the object
definition (they read `@objectstack/core`'s withheld-field collectors
and the spec's `referenceTargetOf`). Two ways for PR 2 to call them: (A)
add the `@objectstack/lint` to `@objectstack/service-knowledge`
dependency and import the functions, which first need a line in that
package's `index.ts`: today they are module exports only, not on its
`exports` surface; (B) move the pure rule to a package lint already
reads (for example `@objectstack/core`) and have
`knowledge-search-scope.ts` import it from there. PR 2 chooses.
- **Live check:** no pgvector or turso live suite touches record
granularity or `groupBy` (grouping runs in the service over adapter
answers), so no live cluster was started.
- **Overlap:** `overlap-check` is clean against `main` and objectstack-ai#38509
(shares `knowledge-service.ts`). It reports textual conflicts with two
open drafts on hand-maintained counters: objectstack-ai#38550 (the dropped-refinements
ledger and the catalog positive control) and objectstack-ai#38497 (the positive
control). Whichever lands second re-applies its lines.

## Read first

1. `packages/services/service-knowledge/src/knowledge-service.ts` —
`groupKeyOf` / `documentKeyOf` (the reader) and the new arm in
`admitAuthoredSource`.
2. `packages/services/service-knowledge/src/knowledge-search-scope.ts` —
`parentLinkRule` replaces the body of `parentLinksOf`; check the scope
still behaves the same.
3. `packages/spec/src/ai/knowledge-source.zod.ts` — the key and its
refinement.

**Two-minute check:** `pnpm --filter @objectstack/service-knowledge exec
vitest run src/__tests__/document-by-38537.test.ts` — 16 passed,
including "…: 3 hits, each parent's best and the orphan".

Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- signed: repo:objectstack#5 · os-project-manager ·
session_01FEkQ5oQLfL8thb6wtUHnTb -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Nenzyz pushed a commit to Nenzyz/objectstack that referenced this pull request Dec 1, 2026
… writes (objectstack-ai#38575)

<!-- claude-projects-attribution: {"github_login":"os-project-manager"}
-->
_Requested by **Leehom** · [project
thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XDXvJPPtrTGfdDYhWWpihq5)_
Fixes objectstack-ai#38548
Clause-②: no
Metadata-protocol: none

## 维护者速读

- 用户能看到什么变化:批量导入后知识库索引同步更快;用户界面没有变化。本地实测排空五万条消息从约六十四秒降到约八秒。
- 为什么做:知识库批量同步合入时,评审指出的下一处瓶颈:队列成批领取和完成消息时一条一条写库,在远程数据库上会成为排空速度的上限。
- 出错会怎样:只影响按批消费的队列(目前只有知识库同步);出错时消息会重试或进入死信,不会丢失;可以直接撤回。
- 要你做的:无。

## Step 1 finding (measured before any change)

The claim write of `claimBatch` is `engine.update(sys_job_queue, { id,
status: 'running', ... })`: a by-id write, matched by id alone. Two
adapters over one store that both read a row as pending both overwrite
its lease and both dispatch it.

- **Batch path: reproduced.** Fake engine (copies on read, every claim
read held until both adapters read): 20 messages, `claimedA + claimedB =
40`, every message handed to a handler twice. Real store (ObjectQL over
`SqlDriver`, better-sqlite3 on a file, same barrier): 200 messages,
`claimedA 100, claimedB 100`, all 100 claimed rows handled twice.
- **Main loop (`subscribe`, the per-message path): reproduced.** Same
harness over `pollOnce`: 5 messages, each handled twice. **Not fixed
here** (ruling 7250307515: per-message queues' behaviour and pacing stay
untouched). It is reported to the seat as an open question; the
reproduction stays in the suite as the CONTROL case below.

## What changes

`packages/services/service-queue/src/db-queue-adapter.ts`, batch path
only (`pollBatchOnce` / `dispatchBatch`):

- **Claim: one compare-and-set write over the id set** (`claimSet`). The
read takes up to `maxBatch` due candidates (it was `maxBatch * 3`), then
one `multi: true` update sets `running` + this worker's lease, matched
on `id $in ids` AND `status: 'pending'` AND due (`scheduled_for` null or
not after now). A row another node claimed between the read and the
write matches nothing. When the store answers fewer matched rows than
asked, one read of `id $in ids, status running, locked_by me` says which
rows this worker won; the rest are dropped from the batch.
- **Settle: one write per attempt count for completed rows**
(`settleCompleted`), the lease renewal's shape: `where { id $in ids,
status: 'running', locked_by: me }`, `multi: true`. A fresh backlog is
one settle write per batch. A row whose lease was reclaimed underneath
keeps its new holder's state; fewer matched rows is logged as a lost
lease, as the renewal logs it. A set write that throws falls back to one
`settleRow` per row, so one bad row does not strand the rest.
- **One outcome per message kept**: a failed row still settles alone
through `settleRow` (its own backoff, error and dead letter).
- Sole-writer lease tracking: candidate ids enter `batchInFlight` before
the claim write and lease entries are recorded after it, so a main-loop
reclaim during the claim cannot drop an entry.
- **Main loop untouched**: `claimBatch` keeps its per-row by-id claim
and `max * 3` over-fetch; its candidate read and claimability check
moved into two shared helpers (`readClaimCandidates`, `isClaimable`)
with the same predicates, order and limits.

Tests went into the shared harness `db-queue-adapter.test.ts` as one new
top-level `describe` rather than a new file (ruling record 6583487846).
Its fake `update` now honours `multi: true` predicate writes and answers
the matched count, as the engine's predicate path does.

## Write-count table

Writes to `sys_job_queue` while draining the batch queue (renewals
excluded; none fired):

| Scenario | claim writes before | claim writes after | settle writes
before | settle writes after |
|:---|---:|---:|---:|---:|
| 250 messages, `maxBatch` 100 (unit test) | 250 | 3 | 250 | 3 |
| 6 messages, one failed, one on its 2nd attempt (unit test) | 6 | 1 | 6
| 3 |
| 50,000 messages, `maxBatch` 100 (SQLite, below) | 50,000 | 500 |
50,000 | 500 |

## Drain before / after

Store: the one PR objectstack-ai#38509 measured on, ObjectQL over `SqlDriver` with
better-sqlite3 on a file, `sys_job_queue` registered by
`QueueServicePlugin`. Bench: publish N messages, `subscribeBatch` with a
no-op handler (`maxBatch` 100), call `pollBatchOnce` until it claims 0.
Base = the adapter at `d08d2ae972`; head = this branch. Shared box,
under the verify lock (absolutes are shared-box readings; the ratio is
the reading).

| N = 50,000 | drain | per message | messages/s | queue updates | queue
reads |
|:---|---:|---:|---:|---:|---:|
| base | 63,896 ms | 1.278 ms | 783 | 100,000 | 501 |
| head | 7,865 ms | 0.157 ms | 6,357 | 1,000 | 501 |

8.1x faster drain, 100x fewer writes. Remote store: NOT MEASURED (none
reachable). On a remote store each removed write is a network round
trip, so the saving there is larger than the local ratio.

## Ablation

On committed code, through `scripts/ablation-replace.mjs` (mutation
proved on disk by anchor count and blob; restored to blob `8ccbd947`,
`git diff HEAD` empty):

<details><summary>Claim set write reverted to the per-row by-id claim: 3
red</summary>

`claimSet(queue, batch.maxBatch, this.batchInFlight)` replaced by
`claimBatch(queue, batch.maxBatch)`:
- write count: `expected { claim: 250, settle: 3, renew: 0 } to deeply
equal { claim: 3, settle: 3, renew: 0 }`
- failed-row case: `expected { claim: 6, settle: 3, renew: 0 } to deeply
equal { claim: 1, settle: 3, renew: 0 }`
- two adapters: `expected 40 to be 20`
</details>

<details><summary>Settle set write reverted to per-row settles: 2
red</summary>

- write count: `expected { claim: 3, settle: 250, renew: 0 } to deeply
equal { claim: 3, settle: 3, renew: 0 }`
- failed-row case: `expected { claim: 1, settle: 6, renew: 0 } to deeply
equal { claim: 1, settle: 3, renew: 0 }`
</details>

<details><summary>Unclaimed-state match removed from the claim (id set
only): 1 red</summary>

- two adapters: `expected 40 to be 20`
</details>

## Tests

<details><summary>Readings</summary>

Under the verify lock. The code is the same from `2f602bfc28` to head
`1515a3ea7d`: the later commits add only the changeset and the
regenerated census. On `1515a3ea7d`, in a fresh worktree after building
the dependency closure: `pnpm --filter @objectstack/service-queue test`
gave `Test Files 5 passed (5)`, `Tests 106 passed (106)`, VERDICT
command-exit 0.

- `pnpm --filter @objectstack/service-queue test`: `Test Files 5 passed
(5)`, `Tests 106 passed (106)` (102 before + 4 new), VERDICT
command-exit 0.
- `pnpm --filter @objectstack/service-queue typecheck`: VERDICT
command-exit 0; `tsc --listFiles` reaches all 5 test files of the
package.
- `pnpm --filter @objectstack/service-knowledge exec vitest run
--maxWorkers=2 src/__tests__/record-sync-queue.test.ts` after rebuilding
service-queue's `dist` (the knowledge suite imports it from `dist`;
`claimSet` found 3 times in it): `Tests 41 passed (41)`. This is the
real kernel over `SqlDriver` (better-sqlite3 on a file), including the
batch cases (1,000 syncs in batches, a poisoned record dead-lettering
alone), so the set writes run against the real engine's `multi: true`
path.
- Step 1, the new cases against the UNCHANGED adapter: 3 failed / 1
passed: `{ claim: 250, settle: 250 }` against `{ claim: 3, settle: 3 }`;
`{ claim: 6, settle: 6 }` against `{ claim: 1, settle: 3 }`; `expected
40 to be 20`; the CONTROL passed (each per-message message handled
twice).
</details>

## Acceptance notes

- **Open question for the seat (not filed by this PR):** the main loop's
`claimBatch` claims by id alone, so two nodes draining one per-message
queue (mail send, mail attachment reclaim, API-flow subscriptions) can
both run a message. Reproduced by the CONTROL case `the main loop's
claim, matched by id alone and unchanged here, lets both adapters claim
the rows they both read` (5 messages, each handled twice). Left
untouched per ruling 7250307515; the same set-write CAS would close it.
- The batch claim's candidate read now takes `maxBatch` rows, not
`maxBatch * 3`: a single CAS write gains nothing from over-fetching. A
batch that loses rows to another node comes back short and its loop
waits as for any short batch.
- A settle write is now a compare-and-set on `running` under this
worker. Before, a batch whose lease was reclaimed underneath overwrote
the new state; now it does not, and the message runs again where it went
(at-least-once, as before).
- Not a new test file: the claim named
`db-queue-batch-writes-38548.test.ts`; ruling record 6583487846 puts a
new pin for a component with a shared harness into that file. The claim
amendment accepts this.

## Verification

Read first (risk order): `claimSet` and `settleCompleted` in
`db-queue-adapter.ts`, then the new `describe` at the end of
`db-queue-adapter.test.ts`.

Two-minute check: `pnpm --filter @objectstack/service-queue exec vitest
run --maxWorkers=2 src/db-queue-adapter.test.ts -t 'set writes'` should
show 4 passed, including `drains N batch messages with O(N / maxBatch)
claim and settle writes, not 2N`.

<details><summary>Local gates</summary>

`node scripts/pm/dispatch-gates.mjs --commands --repo
objectstack-ai/objectstack` derived 65 commands for the 3 changed paths
(merge base `d08d2ae97`). Each was run with its exit code captured
before any pipe.

- 62 exit 0 on `e0c5953f74` (64 after the census re-run), among them
`check:engine-double-contract` ("OK — 1403 pinned, 119 in the DEBT
ledger, 3 exempt"), `check:nul-bytes`, `check:type-check-coverage`,
`check:cross-package-test-inputs`, `check:where-matcher`.
- `node scripts/check-tenant-audit-census.mjs` and its `--self-test`:
exit 0 on head `1515a3ea7d` ("OK -- 354 write call sites certified
across 19 package shard(s)"; self-test "29 cases pass"). The first run
on `e0c5953f74` was red (the committed census counted 11 write call
sites against 13 in the tree, from the two new set writes). The census
was regenerated by `node scripts/tenant-audit-census.mjs --write` alone
and committed by itself as `1515a3ea7d`:
`docs/audits/2026-08-tenant-audit-write-call-sites.counts/services/service-queue.md`,
8 lines, counts 11 to 13 and `update` 8 to 10. The claim amendment added
that file to the surface.
- NOT MEASURED, 1: `pnpm check:dual-build-cjs-loads`, exit 3
PREREQUISITE NOT MET (65 published packages have no `dist`; it needs a
full build). CI runs it.
- `--ran`: "65 derived famil(ies) accounted for — 64 run, 1
NOT-MEASURED".
- `node scripts/pm/overlap-check.mjs --branch=HEAD` on `1515a3ea7d`,
before its push: "origin/main: merges cleanly" (`a133c8ad1b`), VERDICT
clean exit 0.
</details>

Session: https://claude.ai/code/session_01FEkQ5oQLfL8thb6wtUHnTb

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- signed: repo:objectstack#5 · os-project-manager ·
session_01FEkQ5oQLfL8thb6wtUHnTb -->

---------

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 pm:awaiting-merge PR only: landing waits on the maintainer's own review and merge (SKILL.md 复核 ②); never on an issue size/xl 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.

3 participants