Repository navigation
feat(service-knowledge): record sync consumes the database queue in batches of 100, and a large backlog is reconciled - #38509
Conversation
…ation Claude-Session: https://claude.ai/code/session_01FEkQ5mC8eA4qtKSweeF7wd Co-Authored-By: Claude <noreply@anthropic.com>
…cile Claude-Session: https://claude.ai/code/session_01FEkQ5mC8eA4qtKSweeF7wd Co-Authored-By: Claude <noreply@anthropic.com>
…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>
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5mC8eA4qtKSweeF7wd
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
…eason Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5mC8eA4qtKSweeF7wd
📓 Docs Drift CheckThis PR changes 3 package(s): 6 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:
⛔ 1 release-owned page(s) also name something this change touched. These are read-only:
What this run could not see
Coarse fallback — 181 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): Which tree this was computed onThis run read A worktree cut from an older # while this PR is open — GitHub drops the merge commit once it closes
git fetch origin 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
|
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5mC8eA4qtKSweeF7wd
|
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5mC8eA4qtKSweeF7wd |
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5mC8eA4qtKSweeF7wd Final green head declared for L1:
|
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5mC8eA4qtKSweeF7wd Contract reviewServed-tier: 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 The scope is widened past the one
① Derived judgments
② Semver levelTwo changesets: The level is right. The change adds a TypeScript contract member, not anything a metadata author can write, so the kind is ③ Boundary flags
④ Design judgment
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) —
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.
S2 (should-fix) — sole-writer lease tracking has a window the comment at N1 (nit) — the batch claim and settle are 2N sequential single-row writes ( 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) — M1 fails the round. Its fix, and the fixes of S1 and S2, each earn a delta review. Implemented-by: VERDICT: FAIL |
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5mC8eA4qtKSweeF7wd The brief the record above was rendered from (filled from Contract review brief — PR #38509 @
|
…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
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5mC8eA4qtKSweeF7wd
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5mC8eA4qtKSweeF7wd |
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5mC8eA4qtKSweeF7wd Final green head declared for L1 (delta from
|
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5nNJM8FQkBco82NDFb 席位核对 — L1 ACCEPT (delta from cf05bbc) · head 76742ab · 2026-11-29T09:14ZThis 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.
Changesets and body. Both changesets still carry 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. |
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5mC8eA4qtKSweeF7wd Contract reviewServed-tier: Round 2 on PR #38509 for card #38413. This is the delta round of record 7252567666 (round 1, FAIL, head The scope is round 1's, plus two files the delta touches to answer nit N4: the export lines of Security is not touched: the delta adds one read, a count of the source's rows under its own ① Derived judgments
② Semver levelThe delta changed both changeset bodies and neither level: 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 ③ Boundary flags
④ Design judgmentM1: closed —
S1: closed — each leg of it:
S2: closed — 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) —
N6 (nit) — the per-source estimate reads another source's backlog as this source's when a burst is clustered in one batch.
N7 (nit) — the reconcile's completion handler reads the source's last build record, not the pass it scheduled (
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 Implemented-by: VERDICT: PASS |
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5mzSTSPADAvwapnhxr 维护者速读
席位意见:同意合并。 席位核对 — ACCEPT · repo:objectstack#5 · Head-sha
|
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5mzSTSPADAvwapnhxr Approval requested (Tier H:
|
…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>
… 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>
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).
维护者速读
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 }andQueueBatchSubscribeOptions = { maxBatch: number }. The handler answers one outcome per message. A queue takes either per-message handlers or one batch handler, andunsubscriberemoves either. The member is optional: every existing implementation keeps compiling, and a consumer falls back to per-messagesubscribe. It is documented incontent/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:maxBatchdue rows, marking each row in flight as it is claimed;leaseMswhile the handler runs;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
batchSizeperpollIntervalMs.getQueueSizenow counts throughengine.count.Knowledge worker. It uses
subscribeBatchwithmaxBatch100 (RECORD_SYNC_BATCH_SIZE) when the queue has it, and per-messagesubscribeotherwise. For each source and object in a batch,processRecordSyncBatchdoes one re-read (whereANDid $in), oneplanIndex(one fingerprint, ADR-0161 K7), one split, one adapterupsertand onedelete. When a group with more than one record fails, its records are synced again one at a time. Messages stay identifiers only, and noIKnowledgeAdaptermember 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:doneand its purge ran (result.purgedis a number);reconcileExclusion);A build that ended
donewithout purging covers nothing, so a waiting delete or where-exit is still synced on both paths. This covers an adapter withoutlistDocumentsand 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) andRECORD_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, andunsubscribedoes not wait for a walk. Once the reconcile endsdonewith its purge run, the waiting messages it covers complete ascovered. After it ends, the next backlog reconcile of that source waits:done, so a source under sustained writes is not re-walked back to back;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 asnot-synced.Contract faces touched:
IQueueService.subscribeBatch(optional), plus the exported typesQueueBatchHandler,QueueBatchOutcomeandQueueBatchSubscribeOptions.api-surface/contracts.jsonandexport-origins/contracts.jsonregenerated (+3 lines each); signatures unchanged.KnowledgeService.processRecordSynctakes an optionalpublishedAtand can answercovered.KnowledgeService.processRecordSyncBatchis new.KnowledgeRecordSyncBatchItemandKnowledgeRecordSyncBatchResultare now exported from@objectstack/service-knowledge.Tests
record-sync-queue.test.ts, realDbQueueAdapter, 100 drafts outsidewhere): 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 equalsreindexSource(content and docHash).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.donebuild withpurged: nullstill remove their documents. This is tested on both paths, for both no-purge causes: nolistDocuments, and a listing that failed.knowledge-build.test.ts):coveredwith no re-read and no second reconcile (re-walk wait);db-queue-adapter.test.ts):Suite and ablation readings (head 76742ab)
typeof build.result?.purged !== 'number' || build.result.ok === falsewas removed fromcoveredByBuild. Both listing-failed cases went red ("2 failed | 2 passed"); the rebuild-unlisted cases stayed green throughreconcileExclusion. Restored to the HEAD blob.inFlight?.add(String(row.id))was removed fromclaimBatch. The S2 case went red ("expected [ false, true, true ] to deeply equal [ true, true, true ]"). Restored to the HEAD blob.Measurement: 50,000 records, LOCAL MODEL
This is a labelled local model, not a production figure.
Acceptance notes
check:dual-build-cjs-loadswas NOT MEASURED locally, because it needs every package's dist. CI runs it.Verification
Read first, by risk:
packages/services/service-knowledge/src/knowledge-service.ts:coveredByBuild,considerBacklogReconcileandprocessRecordSyncBatch.packages/services/service-queue/src/db-queue-adapter.ts:claimBatchand its in-flight mark,dispatchBatchwith its per-row settle, and the reclaim wake.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)
dispatch-gates.mjs --commands --repo objectstack-ai/objectstackon head 76742ab: 120 commands, all run, each exiting 0 with the code captured before any pipe.check-plugin-teardown-shape --self-testpassed after the pinned fixture commit was fetched into the shallow clone.check:skill-examplesfirst exited 3 (PREREQUISITE NOT MET: client dist missing). It exited 0 after@objectstack/clientand@objectstack/client-reactwere built: "352 prose examples type-check".check:dual-build-cjs-loads: "126 published require entry point(s) across 74 package(s) load".--ranreconciliation: "Run reconciliation — 120 derived, 120 run, 0 NOT-MEASURED, 0 UNRUN".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