Repository navigation
feat(service-knowledge)!: a knowledge service the runtime mounts holds its sources without an embedder or its deployment store - #38470
Conversation
…ources without an embedder or its store Claude-Session: https://claude.ai/code/session_01FEkQ5m2rYCwPR3qqhnZDfW Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEkQ5m2rYCwPR3qqhnZDfW Co-authored-by: Claude <noreply@anthropic.com>
… sources without an embedder or its store Pins for the reap guard, both MCP transports and the runtime bridge; the ADR-0087 upgrade-guide entry and the changeset. Claude-Session: https://claude.ai/code/session_01FEkQ5m2rYCwPR3qqhnZDfW Co-authored-by: Claude <noreply@anthropic.com>
…h the predicate; type the store plugin Claude-Session: https://claude.ai/code/session_01FEkQ5m2rYCwPR3qqhnZDfW Co-authored-by: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FEkQ5m2rYCwPR3qqhnZDfW Co-authored-by: Claude <noreply@anthropic.com>
📓 Docs Drift CheckThis PR changes 4 package(s): 5 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:
What this run could not see
Coarse fallback — 191 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 67415c35ceb8646cfe2c137015ce9db8dd42f8d2 && git checkout 67415c35ceb8646cfe2c137015ce9db8dd42f8d2
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 16f132fbe76686713b709934389113f915c7d647 4659f2a3698c259199e3a1f8e628552a6a6a922d && git checkout -B drift-repro 16f132fbe76686713b709934389113f915c7d647 && git merge --no-ff 4659f2a3698c259199e3a1f8e628552a6a6a922d
node scripts/docs-audit/affected-docs.mjs --json 16f132fbe76686713b709934389113f915c7d647
|
…owledge-held-not-served
…ledge pages Claude-Session: https://claude.ai/code/session_01FEkQ5m2rYCwPR3qqhnZDfW Co-authored-by: Claude <noreply@anthropic.com>
…owledge-held-not-served
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5m2rYCwPR3qqhnZDfW Final green head:
This head is not to move under review. Generated by Claude Code |
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5oQLfL8thb6wtUHnTb Contract-review-claim: session_01FEkQ5oQLfL8thb6wtUHnTb · head 4659f2a · 2026-11-29T05:01Z Face: narrowing ( |
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5nNJM8FQkBco82NDFb 席位核对L1 (thread L1-a, area o5-ai37000) · read 2026-11-29T05:04Z · Head-sha: This is the first L1 record on this PR, a full review. The contract review (fable) on this head is running and is a separate record. Checklist (l1-face
My readings, at this head
Must-fix (body only)
After the fix: a delta L1 on the body. The head does not move. |
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5oQLfL8thb6wtUHnTb Contract reviewServed-tier: Reviewed as the net diff of the head against its merge base with ① Derived judgmentsEach accept-set and public-surface change the diff implies:
② Semver levelClause-②: no (narrowing) The PR body and the changeset both carry ③ Boundary flags
④ Design judgmentThe narrowing is read against the ADR-0161 K8 dated note on item 12 on Does it take a declared capability away at the consumer, or make the spec's own refusal real? The second. On Attempts to break it:
Findings:
No must-fix, no should-fix. Implemented-by: VERDICT: PASS |
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5nNJM8FQkBco82NDFb 席位核对L1 (thread L1-a, area o5-ai37000) · read 2026-11-29T05:09Z · Head-sha: This is a delta from my REWORK 7251041412. The head has not moved, and the rest of that record stands.
Owed before landing: the contract review on this head (running). Then the seat lands it (Tier H). |
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5mzSTSPADAvwapnhxr 维护者速读
席位意见:同意合并。合并后 #38413(队列成批消费,你已裁 A)在它之后接着做,把这个未启用拦截也放进批量路径。 席位核对 — ACCEPT · repo:objectstack#5 · Head-sha
|
|
repo:objectstack#5 · os-project-manager · session_01FEkQ5mzSTSPADAvwapnhxr Approval requested (narrowing,
|
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
…Korean questions by 2- and 3-character pieces (objectstack-ai#38469) <!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XJFhX5XfWT8anspjCw9gfjz)_ Part of objectstack-ai#38411. This PR covers Ask 1, Ask 2 and the first two Acceptance items, plus the model-free half of the eval, and on pgvector the cheaper matcher for a caseless piece (`LIKE` instead of `ILIKE`). Still open: the BrightRule model-graded before/after (needs a running BrightRule environment and model credentials), and Ask 3 (not measured, see below). Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:在本地 libSQL 和 PostgreSQL 两种存储上,用中文、日文或韩文不加空格整句提问时,知识检索的关键词一路终于能匹配到段落;英文提问不受影响。 - 为什么做:属于知识平台专题,解决混合检索在中文问题上实际只剩向量一路的问题。 - 出错会怎样:代价是检索变慢(数字见下),最坏情况是关键词一路排序变差,向量一路照常作答;不改索引、不需重建,可直接撤回。 - 要你做什么:无。 取舍数字(合成制度题集,约 6.7 万段落,218 道中文题): - 中文题关键词一路前 5 名命中率:0.028 → 0.495。 - 本地 libSQL 关键词一路 p95:约 0.12 秒 → 约 0.5 秒。 - 本地 libSQL 混合检索 p95:0.41 秒 → 0.84 秒。 - PostgreSQL 关键词一路 p95:约 0.6 秒 → 约 1.9 秒(本 PR 已把中文片段改成更便宜的匹配方式,排序不变;改之前约 3 秒)。 - 检索词上限 16 是实测拐点:再往上每多约 40% 耗时只多约 1 个点命中率。 - 想再降延迟的两个杠杆:把上限降到 12(命中率 0.459,libSQL 关键词 p95 约 0.31 秒);PostgreSQL 上给段落正文加三元组索引,已立后续卡 objectstack-ai#38473,不在本 PR。 - 未测:BrightRule 模型评分的前后对比,需要运行环境和模型凭据。 ## What changes - `keywordTerms` in `knowledge-turso/src/sql.ts` and `knowledge-pgvector/src/sql.ts` (one body, kept identical) cuts a run of Han, Hiragana, Katakana (including the prolonged sound mark) or Hangul inside a term into overlapping pieces of three characters and of two. A run of two characters is one piece. A run of one is dropped, because it would match nearly every passage. Figures and codes next to a run (`2000`, `X-200`) stay whole terms. Latin-script and spaced queries get exactly the terms they had before. - **Selection rule (Ask 2).** `MAX_KEYWORD_TERMS` stays at 16, re-decided by measurement (below). The cap is filled in this order: figures, codes and words; then pieces of three characters and runs of two; then pieces of two characters. A long question therefore keeps the pieces the libSQL trigram index serves; a short one fills the cap with pieces of two. Matching is unchanged. No index change, no fingerprint change, no reindex. - **pgvector matcher (round 2).** A keyword term the `tsvector` does not serve is matched as a substring by `LIKE` when it holds no cased letter (`containsOperator` in `knowledge-pgvector/src/sql.ts`: `term.toLowerCase() === term.toUpperCase()`; a Han, kana or Hangul piece, a figure), and by `ILIKE` otherwise. Case folding can find nothing more for such a term, so the rankings are identical. Nothing else in the Search section changes. libSQL is unchanged. - **Docs.** `content/docs/protocol/knowledge.mdx` (the contract's optional `keywordLeg` case; both Search bullets: the CJK pieces, and on pgvector `LIKE` / `ILIKE`) and both plugin READMEs. The turso README said "a Chinese question is one term", which this change made false. - **Contract (H2 placement, Clause-② yes).** `@objectstack/service-knowledge/testing`: `KnowledgeAdapterContractOptions.implements` gains an **optional** `keywordLeg` member (absent means `false`). When an adapter declares it, the shared suite asks the unspaced question 「出差住宿费超标的话2000元以下除外的情况还要部门经理审批吗」 over one passage holding 「2000元以下除外」 and five passages holding the question's characters one by one but none of its words. The passage must be ranked at `topK` 3. knowledge-turso and knowledge-pgvector declare it. knowledge-memory and the service stubs have no keyword leg and are untouched. No placement with zero new exported members exists: the memory adapter and the stubs run the same suite and have no keyword leg, and the spec contract has no capability flag to read. The member is optional, so existing callers compile unchanged; that makes it widening. ## Tests <details><summary>Unit pins, contract case, ablation (head b511770)</summary> - knowledge-turso `acceptance.test.ts`: the Latin and spaced pin is kept exactly (`What is the X-200 pump? …` gives today's 10 terms; `出差 住宿` gives `['出差','住宿']`; cap 16). New pin: an unspaced question gives its figure and then its pieces; `X-200型号的保修期` keeps `X-200`; runs of two and one; kana and Hangul. - knowledge-pgvector `keyword-terms.test.ts` (new, no database): the same pins, plus which matcher each term goes to (`isWordTerm`). - Contract case: knowledge-turso on `:memory:` and on a `file:` URL, and knowledge-pgvector on a live PostgreSQL 16 with pgvector 0.6.0 started in this container. - Results, local: knowledge-turso `Test Files 4 passed, Tests 284 passed`; knowledge-pgvector live (`OS_TEST_POSTGRES_URL` set, `OS_EXPECT_LIVE_DIALECT_MATRIX=1`) `Test Files 11 passed, Tests 108 passed`; service-knowledge `21 files, 726 tests passed`; knowledge-memory `3 files, 66 tests passed`. Type check is green for knowledge-turso, knowledge-pgvector, service-knowledge and knowledge-memory. - Ablation (base `sql.ts` swapped in, checked by blob hash, then restored and checked by hash again): turso goes red with 4 failures (the piece pin and the contract case, on both store kinds; the Latin pin stays green); pgvector, live, goes red with 3 failures (the contract case and two pins). - Reverse type check: the turso type check first read a `dist/testing.d.ts` built before this change and refused `keywordLeg` (TS2353). After the rebuild it passes. </details> <details><summary>Round 2: the pgvector matcher (head cde0bbe; code identical to 81be16f)</summary> - `keyword-terms.test.ts` gains two pins. `containsOperator` gives `LIKE` for `元以下`, `出差`, `コー`, `휴가`, `42` and `ILIKE` for `ab`, `X-200`, `É`. A statement pin runs `adapter.search('出差 ab', …)` against a recording pool and reads, from the ranking statement itself, the operator in front of the placeholder each pattern is bound to: `%出差%` gets `content LIKE`, `%ab%` gets `content ILIKE`. - knowledge-pgvector live (PostgreSQL 16 + pgvector 0.6.0, `OS_EXPECT_LIVE_DIALECT_MATRIX=1`), contract case included: `Test Files 11 passed (11)`, `Tests 110 passed (110)`, verify lock `VERDICT command-exit 0`. - `pnpm --filter @objectstack/knowledge-pgvector typecheck`: `VERDICT command-exit 0`. - Ablation: with the adapter reverted to b511770 (blob hash checked, then restored and checked again), the statement pin fails: `Tests 1 failed | 4 passed (5)`. - CI on b511770 (job 141221631158) and on 923c009 (jobs 141222136228 and 141222139195): every failing step is an aggregator reading a `cancelled` lane (for example "type-check lane `typecheck-workspace` concluded `cancelled` -- expected `success`"). Each later push to this branch cancelled the run in flight. 923c009 also held one real error, TS2353 in the new statement pin (`recipeHash` is not a member of the search options' `index`), fixed in 81be16f and green locally as above. </details> ## Measurement Every harness is a scratch script outside the repository. Corpus: the BrightRule synthetic set (`scripts/eval/build.ts --distractors 1500`, brightrule @ 07e21ac). Passages are cut one per article or section, with attachments kept on their own and each passage prefixed `【unit|title|attachment】 path`, as the app's clause hook does. Each document is indexed through `TursoKnowledgeAdapter.upsert` (the real write path). Two tables: - 11k: 1,577 documents, 11,025 passages. - 67k: the same plus 8,000 distractors from seeds 11 to 14, giving 9,577 documents and **67,421 passages**. The card's table had 67,379. Questions: the **218 zh questions whose expected policies are Chinese** (230 counting the zh-to-English ones). A hit means a passage of an expected policy (P) or of the expected article (C) in the keyword leg's top 5 or top 10. The keyword leg is isolated with an all-zero query vector, which turns the vector leg off. Intervals are 95% bootstrap intervals over questions (2,000 resamples). Retrieval is deterministic: **each side was run 3 times and the rankings were identical on every run**, on both stores and both tables. So the interval comes from the question sample, not from run noise. <details><summary>Keyword leg, libSQL store, before and after</summary> | table | side | P@5 | P@10 | C@5 | C@10 | questions with any hit | p50 | p95 | |---|---|---|---|---|---|---|---|---| | 11k | before | 0.032 [0.009, 0.055] | 0.037 [0.014, 0.064] | 0.028 [0.009, 0.051] | 0.032 [0.009, 0.060] | 31 | 0.7 ms | 20 ms | | 11k | after | **0.500** [0.431, 0.569] | 0.514 [0.450, 0.583] | 0.486 [0.421, 0.556] | 0.500 [0.435, 0.569] | 206 | 52 to 56 ms | 80 to 93 ms | | 67k | before | 0.028 [0.009, 0.050] | 0.032 [0.009, 0.060] | 0.028 [0.009, 0.051] | 0.032 [0.009, 0.060] | 31 | 1.4 ms | 113 to 132 ms | | 67k | after | **0.495** [0.427, 0.564] | 0.500 [0.431, 0.569] | 0.486 [0.421, 0.556] | 0.491 [0.421, 0.560] | 206 | 305 to 328 ms | **491 to 516 ms** | All 230 zh questions, 67k: P@5 goes from 0.026 [0.009, 0.048] to 0.470 [0.404, 0.530]. </details> <details><summary>Choosing the cap and the order (67k, keyword leg alone)</summary> | order / cap | P@5 | p50 | p95 | |---|---|---|---| | pieces of three and runs of two only (no pieces of two) | 0.404 | 7 ms | 155 ms | | three-first, cap 12 | 0.459 | 136 ms | 314 ms | | **three-first, cap 16 (shipped)** | **0.495** | 321 ms | 507 ms | | three-first, cap 20 | 0.505 | 440 ms | 690 ms | | three-first, cap 24 | 0.509 | 552 ms | 910 ms | | by position, cap 16 | 0.495 | 445 ms | 746 ms | | by position, cap 32 (every piece of every question but a few) | 0.518 | 670 ms | 1,277 ms | The questions are 16 characters at the median and 24 at p90, which gives 23 uncapped terms at the median and 34 at p90; 202 of 230 exceed 16. On the 67k table, a piece of two characters costs one scan of the rows in scope, about 23 ms (`LIKE` and `instr` cost the same). A piece of three is served by the trigram index and is nearly free, except for a trigram most passages hold: about 30 ms to materialise one held by 48,000 rows. Past 16, recall gains about one point for each further 40% of latency, and every interval overlaps. Cap 16 with the three-first order is the knee. Keeping a one-character run measured no recall change. </details> <details><summary>Hybrid search latency, libSQL 67k with a 1024-wide vector column (exact scan)</summary> | side | p50 | p95 | |---|---|---| | before | 258 ms | 410 ms | | pieces of three only | 266 ms | 429 ms | | after (three-first, cap 16) | 563 ms | 837 ms | | three-first, cap 24 | 818 ms | 1,244 ms | The vector leg here is a bag-of-characters fake embedder, used for its cost only. Its fused ranking is not reported: a lexical stand-in for an embedder measures the fusion of two lexical legs, not hybrid retrieval. </details> <details><summary>pgvector, live PostgreSQL 16 + pgvector 0.6.0, the same 67k passages, keyword leg alone</summary> | side | P@5 | p50 | p95 | |---|---|---|---| | before (3 runs) | 0.028 | 132 to 150 ms | 617 to 691 ms | | pieces, every substring term by `ILIKE` (b511770, 3 runs) | 0.495 | 538 to 563 ms | 2,883 to 3,085 ms | | **pieces, a caseless term by `LIKE` (this head, 3 runs)** | 0.495 | 187 to 195 ms | **1,832 to 1,925 ms** | The rankings are identical on every run, identical between the `ILIKE` and the `LIKE` heads, and the same hit set as libSQL. The tail is questions holding 公司: its pieces are held by 67,125 of 67,421 passages, because every clause prefix names its company, so nearly every row becomes a candidate. On this server `ILIKE '%公司%'` costs 90 ms per scan against 18 ms for `LIKE` or `strpos`, with identical counts; that is the matcher change in this PR. What remains of the tail is one substring scan per piece over nearly every row, and the candidate `tsvector` computed for each of them. </details> Commands, all run from a scratch directory outside the repository: ``` pnpm run eval:build -- --distractors 1500 --out EVALSET (in a scratch copy of brightrule, pnpm install --ignore-scripts) pnpm run eval:build -- --distractors 2000 --seed 11..14 --out EVALSET-sN (distractors only, keys suffixed) python3 -I prep.py CORPUS docs.json (clause passages) tsx eval.ts index docs.json DB 8 zero and tsx eval.ts search docs.json DB questions.json VARIANT out.json tsx eval.mts index / search (pgvector, the same shape) python3 -I score.py zh RUN.json … (recall, bootstrap intervals, p50/p95) ``` All timings are seconds on a shared 4-core container, with sibling agents running. - NOT MEASURED: BrightRule model-graded eval, reason: it needs a running BrightRule environment and model credentials, and this container has neither. The keyword-leg retrieval above is the model-free stand-in. - NOT MEASURED: fused hybrid recall, reason: no real embedder in this container. A lexical stand-in would measure the fusion of two lexical legs. - NOT MEASURED: Ask 3 (a larger per-leg pool before fusion), reason: it is judged on fused ranking, which needs a real embedder. Ask 3 also reaches `knowledge-tools.ts`, which is outside this claim. ## Acceptance notes - **pgvector keyword-leg cost (carrier: objectstack-ai#38473, filed by the seat).** With the `LIKE` matcher in, pgvector's keyword-leg p95 on the 67k table goes from about 0.6 s to about 1.9 s. Two levers remain, both outside this claim. First, compute the candidate `tsvector` only when a word term needs it (a Search-section change). Second, a pg_trgm GIN index on the passage content, which serves `LIKE` / `ILIKE` substrings. That is an index change: a second DDL beside `keywordIndexDdl` (`knowledge-pgvector/src/sql.ts`), created through `ensureKeywordIndex` (`pgvector-adapter.ts`), plus a `pg_trgm` extension dependency next to the `vector` one. It is not a fingerprint change: the index fingerprint hashes only the embedding model, variant, dimensions and split, and an older table gets the keyword index at its first search without a rebuild. - A lower cap is the cheapest lever on both stores: cap 12 measured P@5 0.459 and libSQL keyword p95 314 ms (cap 16: 0.495 and 507 ms). - libSQL: a piece of two characters costs one scan of the rows in scope. Scoring pieces of two only among the candidates that the index-served terms recruit would remove that scan. It is a Search-section change and moves each piece's document frequency, so it needs its own measurement. - **Separator class takes 々, 〆 and 〇 (carrier: objectstack-ai#38411, a remaining item there, filed by the seat).** The class `\u3000-\u303f` holds 々 (U+3005), 〆 (U+3006) and 〇 (U+3007, the ideographic zero), in both stores. With this PR's rule that drops a one-character run, 「人々」 yields no keyword term (on main it kept 「人」) and 「二〇二四年」 loses 「二」. The fix (take U+3005–U+3007 out of the separator class and into the run, pins in both stores) lands as a follow-up PR on objectstack-ai#38411 after this one merges, so this approved head does not move (L1 7250902792). - To run the pgvector live suites, this container installed `postgresql-16-pgvector` (0.6.0, Ubuntu noble) and ran a private cluster on a random port, removed afterwards. ## Verification - Read first: `packages/plugins/knowledge-turso/src/sql.ts` (`keywordTerms`: the run split and the final order and cap), `packages/services/service-knowledge/src/testing.ts` (the optional `keywordLeg` member and its case), `packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts` (the keyword branch of the ranking statement, where `containsOperator` picks `LIKE` or `ILIKE`). - Two-minute check: `pnpm --filter @objectstack/knowledge-turso exec vitest run --maxWorkers=2 src/__tests__/contract.test.ts` should show the case `the keyword leg › an unspaced question ranks the passage …` passing on both `:memory:` and `file:`. <details><summary>Local gate subset at cde0bbe (CI runs the full farm)</summary> - Tests and type checks: listed under Tests above. - `node scripts/pm/dispatch-gates.mjs --commands` derived 101 families for the 12 changed files (70 at b511770, plus 31 the docs edit brings in). Each ran with its exit code captured before any pipe. The 31 docs families and 8 families that read the round-2 files were run at cde0bbe; the others read files unchanged since b511770 and carry that reading. `--ran` reconciliation at cde0bbe: `101 derived, 101 run, 0 NOT-MEASURED, 0 UNRUN`. Exit codes: **96 exit 0**, and five not measured: - NOT MEASURED: `check:skill-examples`, reason: exit 3, PREREQUISITE NOT MET, it needs the client SDK's `dist/`. No skill file is touched. - NOT MEASURED: `check-plugin-teardown-shape.mjs --self-test`, reason: PREREQUISITE NOT MET, its pinned positive-control commit is beyond this shallow clone. - NOT MEASURED: `check:dual-build-cjs-loads`, reason: PREREQUISITE NOT MET, it needs every package's `dist/`. - NOT MEASURED: `check:query-options-erasure` and `check:type-check-debt`, reason: repo-wide ESLint and `tsc` scans that passed the 240 s per-gate limit. CI's Lint & Repo Gates and TypeScript Type Check carry them. - `overlap-check` before the push: `VERDICT clean` against origin/main and the two open PRs that share `knowledge.mdx` (objectstack-ai#38468, objectstack-ai#38470), and clean against `origin/claude/project-thread-mu3i0t`. - Self-scan of the changed files for control bytes: no hits. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5pfJqySEaVD3CKvevm <!-- signed: repo:objectstack#5 · os-project-manager · session_01FEkQ5pfJqySEaVD3CKvevm --> --------- Co-authored-by: Claude <noreply@anthropic.com>
…atches of 100, and a large backlog is reconciled (objectstack-ai#38509) <!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1XTxm2XFTJzP3Vgjt9Rqx2C2)_ Part of objectstack-ai#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: objectstack-ai#38529 (a 50k drain with a real embedding provider, Blocked-by objectstack-ai#38509). Clause-②: yes (widening) Metadata-protocol: none Ask 3: split to objectstack-ai#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 objectstack-ai#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. <details><summary>Suite and ablation readings (head 76742ab)</summary> - 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"). </details> ## 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 - **Acceptance 1** (bounded embedder work and adapter writes, an index equal to a rebuild): covered by the 1,000-sync case, which counts adapter writes and embedded documents, and by the measurement, which counts embedder requests. - **Acceptance 2**: open; see the Acceptance gap line. carrier: objectstack-ai#38529. - **Acceptance 3**: covered by the poisoned-record case. - **Acceptance 4**: covered by the mixed-batch parity case and the M1 cases on both paths. - **Ask 2**: per source, scheduled, remembered, with the numbers above. - **Ask 3**: split to objectstack-ai#38489. - **N1**: the batch claim and settle are 2N single-row writes, and the claim write matches by id alone, so two nodes draining at once can claim the same rows. carrier: objectstack-ai#38548. It is also the drain floor the measurement shows. - **N3**: fixed here. A row the main loop reclaims for a batch-consumed queue wakes that queue's loop. - **Local gates**: `check:dual-build-cjs-loads` was NOT MEASURED locally, because it needs every package's dist. CI runs it. ## 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. <details><summary>Local gates (head 76742ab)</summary> - 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. </details> 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01FEkQ5mC8eA4qtKSweeF7wd <!-- signed: repo:objectstack#5 · os-project-manager · session_01FEkQ5mC8eA4qtKSweeF7wd --> --------- Co-authored-by: Claude <noreply@anthropic.com>
Requested by Leehom · project thread
Refs #38369
Clause-②: no (narrowing)
Metadata-protocol: narrowed
Skills-docs: follow-up #38475
维护者速读
search_knowledge;启动日志说一次缺了哪一半、怎么补。以前这种部署照样启动构建和同步,工具也列出来,但每次构建和检索都报错。What changes
The authority is the ADR-0161 K8 dated note on item 12 (PR #38401, 0c1b2ff), with ruling 7248214179 (amendment 7248231750, points 1–4) and build notes 7248592159 (points 1–4). This PR is part 1 of the three serial PRs the card names: items 1–2, ruling points 2–3, build notes 1, 2 and 4. Part 2 (the save refusal: item 3, points 1 and 4, build note 3) and part 3 (items 4–5) follow from
mainafter this merges.packages/services/service-knowledge/src/knowledge-service-plugin.ts). The capability composition (packages/core/src/capability-composition.ts) now passesruntimeComposed: { declared }besidedeploymentAdapter;declaredis true only when the stack listsknowledgeinrequires. WithruntimeComposedset, the plugin reads atkernel:bootstrapped, after every store'sstart()registered its adapter: an embedder is available (another plugin registered one, or the savedai.embedder_*settings build one) and the deployment's store is mounted (an adapter ofdeploymentAdapter's id is registered). Both ⇒ the boot goes on as today. Either missing ⇒ held. A plugin a host mounts (noruntimeComposed) is untouched: it serves from the start, as before.packages/services/service-knowledge/src/knowledge-service.ts,KnowledgeService.settleEnablement). Every source, whichever store it names (point 2: an application-registered store too), is loaded and listed, and never built, synced, reconciled or searched: the boot build, the reload build, the reconcile pass and its job, the record sync (enqueue, upsert, delete and the queued worker), the predicate-write note and the unmounted-adapter report all return. A dropped source keeps its index (a warn line says no store is called).search,rebuildSourceandreindexSourcethrowheldSourcesError: status503, codeSERVICE_UNAVAILABLE, and a message naming the missing half and the fix (build note 2).kernel:ready, before the reading; the lifecycle service has no unregister. A runtime-composed plugin now registers it only once the reading says enabled. Held, a retention sweep deletes on time and calls no store.infowhen only a shippedknowledge_sourcemounted the service and nothing was saved;warnwhen the stack declaresrequires: ['knowledge'], when a saved embedder provider builds nothing (a provider saved without its key), or when the store is not mounted. The embedder's own boot line is not also said when held.KnowledgeService.knowledgeTools()answersdefinitions: []). HTTP MCP reads the definitions per request, so it listssearch_knowledgeonly once enabled.packages/mcp/src/plugin.ts, build note 4). The stdio bridge reads the tool in its ownstart(), before the reading, so a runtime-composed service hands out nothing there.MCPServerPluginnow registerssearch_knowledgeatkernel:listening(after everykernel:bootstrappedhandler) only when the service then hands out its definition. Fail-closed: an unknown state reads as absent, never listed and then withdrawn. The MCP SDK takes a tool after the transport attached and sendsnotifications/tools/list_changed; skill prompts read the served tools at each listing. A host-mounted service's tool still registers instart(), once.packages/spec/src/migrations/entries/semantic/19.knowledge-service-held-without-embedder-or-store.ts(notice only, no D2 conversion: the fix is the deployment's configuration, never the item). The changeset carriesregisteredwith that id.Boot window
Between
kernel:readyandkernel:bootstrappedthe reading is pending. In that window no tool definition is handed out (fail-closed); a record write's sync behaves as today (it embeds through the stand-in embedder, which refuses). Gating starts when the reading settles. No reap guard registers in that window on a runtime-composed plugin.Point 2 measurement
None of
@objectstack/verify'sharness.required-providerscases reads as held: every one registers an embedder. The file is unchanged and its 16 cases pass.Docs
content/docs/ai/knowledge-rag.mdx: a "Mounted is not enabled" bullet under Turning it on (held state, the boot line and its level, the remedy, host-mounted not held), a clause on the "Nothing is configured" embedder bullet, and one sentence under Thesearch_knowledgetool (not listed while held; on stdio registered after the reading, withnotifications/tools/list_changed).content/docs/protocol/knowledge.mdx: a "Mounted is not enabled" paragraph after What mounts the service, and the reap-guard section says a runtime-composed service registers no guard until it is read as enabled. Added after sibling #38439 (#38351) merged (f19ee34), withmainmerged in first.skills/objectstack-ai/SKILL.mdis out of scope: follow-up #38475 rewrites its knowledge wording once, frommain, after part 3.Tests
packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts, new describe "a runtime-composed knowledge service is enabled by configuration", booted onLiteKernelwith a store plugin that counts every call (10 cases): held with no embedder saved (oneinfoline, zero store calls after writes and a delete); nosearch_knowledgedefinition, search answers503 SERVICE_UNAVAILABLEnaming the missing half, rebuild refused;requires: ['knowledge']⇒warn; a provider saved without its key ⇒warn(build note 3's state, read here; its save refusal is part 2); store not mounted ⇒warn; both halves missing named together; point 2 (an application-registered store is held too); controls: enabled through a host-registered embedder and through saved settings (built, definition handed out); a host-mounted plugin builds as before.packages/services/service-knowledge/src/__tests__/reap-guard.test.ts(point 3, build note 1): held ⇒registerReapGuardnever called and the retention sweep deletesk1,k2on time with no store call; control: enabled ⇒ the guard registers for['task']after the reading and de-indexes before the delete.packages/mcp/src/mcp-knowledge-tools.test.ts(build note 4): HTTP lists the tool only once enabled (pending, held: absent; host-mounted: listed from the start); stdio throughMCPServerPluginwith the boot hooks fired by hand: held is never listed and nolist_changedis sent; enabled registers atkernel:listeningwithnotifications/tools/list_changedand the same description; host-mounted registers once instart().packages/runtime/src/mcp-knowledge-tools-bridge.test.ts: the runtime bridge reads the definitions per listing (pending and held[], enabled['search_knowledge']).packages/core/src/capability-composition.test.ts:runtimeComposed: { declared }is passed,declaredonly when the stack lists the token.scripts/engine-double-contract.pinned.jsonlearns the stdio double'sfindOnepin (the double routes throughassertEngineFindOnePredicate).Verification
Final head
4659f2a369(mainmerged twice since72a9cbfb6a, for #38439 and #38436; plus the docs commit). At that head, under the lock: closure build exit 0;@objectstack/service-knowledgepnpm test751 passed;@objectstack/mcppnpm test1655 passed; core 26, runtime 7, verify 16 passed; typecheck exit 0 for service-knowledge, core, mcp and runtime;check:engine-double-contract,check:slot-lookup,check-adr-0087-registration(entry at or above PROTOCOL_MAJOR 19), speccheck:docs,check:doc-authoring,check-affected-docs,check:adr-anchorsexit 0. Dogfood battery at4659f2a369: VERDICT command-exit 0 · Test Files 495 passed, 3 skipped (498) · Tests 4183 passed, 68 skipped (4251) · 0 failed. CI at4659f2a369: 62 check-runs success, 10 skipped, none failed.The readings below were taken at
72a9cbfb6aand stand where noted. Shared container; every build and test ran throughscripts/pm/os-verify-lock.sh.Tests and typecheck at 72a9cbf
pnpm --filter '@objectstack/dogfood^...' --filter '@objectstack/cli...' --filter '@objectstack/lint...' build): VERDICT command-exit 0.@objectstack/service-knowledgepnpm test: Test Files 21 passed, Tests 738 passed;typecheckexit 0.@objectstack/mcppnpm test: Test Files 88 passed, Tests 1655 passed;typecheckexit 0.@objectstack/corecapability-composition.test.ts: Tests 26 passed;typecheckexit 0.@objectstack/runtimemcp-knowledge-tools-bridge.test.ts: Tests 7 passed;typecheckexit 0.@objectstack/verifyharness.required-providers.test.ts: Tests 16 passed (point 2 measurement above; file unchanged).@objectstack/cliplan.artifact-item-capabilities.test.ts,boot-preparation-parity.test.ts,migrate-meta-engine-guidance.test.ts: Tests 44 passed.@objectstack/spectypecheckexit 0 (migration registry regenerated with the new entry)..tsfile: exit 0.Ablation
At
2d6c3dfd(plugin unchanged since):scripts/ablation-replace.mjsreplacedconst held = this.settleEnablement(ctx, this.service, embedder);withconst held = false; void this.settleEnablement;. The runtime-composed describe went 9 failed / 1 passed (the host-mounted control stayed green). Restored; blob back to HEAD,git diff HEADempty.Dogfood battery at 72a9cbf
pnpm --filter @objectstack/dogfood testunder the lock: VERDICT command-exit 0 · Test Files 495 passed, 3 skipped (498) · Tests 4183 passed, 68 skipped (4251) · 0 failed.Live positive control (os dev, showcase app)
The showcase mounts
KnowledgeServicePluginitself (host-mounted, unchanged by this PR), so for the control its two knowledge plugins and the source'sadapter: 'memory'were commented out in the worktree only (never committed; restored withgit checkout), which lets the runtime compose the service with the Turso store.objectstack dev --seed-admin --log-level infoon a file database, signed in as the seeded admin:INFO KnowledgeServicePlugin: the knowledge service is not enabled on this deployment: no embedder is configured (no embedder provider is saved — …). Its sources are held: none is built, synced or searched. To enable it, save an embedder provider, then restart. 1 source(s) held: showcase-showcase_task_notes.(hidden at the default log level, asinfoshould be). No build line.index_statuslists the source withbuild: null. The Knowledge page's rebuild action answers "was not started: [knowledge] the knowledge service is not enabled on this deployment: …". MCP over HTTP:tools/list20 tools,search_knowledgeabsent.PUT /api/settings/aisaved acustomprovider pointing at a local OpenAI-compatible stub. The boot registered the embedder, registered the reap guard for[showcase_task]after the reading, and built the source: "8 row(s) read, 8 written". MCPtools/list21 tools withsearch_knowledge; asearch_knowledgecall answered hits fromshowcase-showcase_task_notes; the stub logged one call of 8 inputs (build) and one of 1 (search).ERROR [knowledge] the start of the build … was not recorded (Duplicate record refused on 'Knowledge Sync State' …)whenever a build starts, host-mounted or not. That is service-knowledge: every boot logs a false ERROR because the sync-state upsert reads a by-id update as "no row changed" #38418 (open, seat 1), not this change.index_statusstill reads the adapter while held (here:state: unreadablewith the embedder's reason). Saying "not enabled" there, and inos knowledge status/rebuild, is card item 4, part 3.Gates at 72a9cbf
dispatch-gates --ran: 106 derived families accounted for, 105 run with exit 0, 1 NOT MEASURED:check:dual-build-cjs-loadsexits 3 (nodist/for@objectstack/studio,client-react,scenarios, outside this closure); CI runs it. Among them:check-adr-0087-registration(1 declared-breaking changeset,registered knowledge-service-held-without-embedder-or-store),check-changeset-no-major,check-empty-changeset, speccheck:upgrade-guide,check:spec-changes,check:api-surface,check:liveness,check:engine-double-contract(after the stdio double's fix),check:slot-lookup(after typing the store plugin),check:error-status-conformance,check:type-check-debt,check:nul-bytes.check-plugin-teardown-shape --self-testexit 0 after fetching its pinned fixture commit.overlap-checkbefore the push: clean againstmainand against #38439, #38435 and #38268 (#38418 has no PR yet).🤖 Generated with Claude Code
https://claude.ai/code/session_01FEkQ5m2rYCwPR3qqhnZDfW