Skip to content

feat(knowledge): one timing line per knowledge search, with the turso store's queue wait and requests - #39093

Merged
objectstack-fleet[bot] merged 6 commits into
mainfrom
claude/issue-39037-search-timing-line
Dec 2, 2026
Merged

objectstack-fleet[bot] merged 6 commits into
mainfrom
claude/issue-39037-search-timing-line

Conversation

@objectstack-fleet

Copy link
Copy Markdown
Contributor

Requested by Yibo Wang · project thread
Part of #39037
Claim for this branch: #39037 comment 7337577176
Clause-②: no
Metadata-protocol: none

This PR is Part 1 of the card only (one timing line per search). Part 2 (reads stop queueing behind reads) stays open on the card; the turso queue keeps its order here.

维护者速读

  • 用户无感:托管环境的运行日志里,每次知识检索多一行耗时记录(排队、嵌入、数据库请求、权限复查、总耗时),不含问题原文、记录编号和段落内容。
  • 为 os-4 上 AI 问询慢(中位数约 41 秒)的排查:先用这行日志证实检索时间到底花在哪里,再决定第二步改排队。
  • 出错时最多是这行日志缺失或数字不准,用户的检索结果不变;可以直接撤回。
  • 合并后请云端席位升级框架版本、部署到 os-4,读取这行日志的改前数字。

What changes

  • One line per knowledge search (@objectstack/service-knowledge, new knowledge-search-timing.ts; knowledge-service-search.ts gains only calls). Logged once per KnowledgeService.searchWithRefusals, which every search_knowledge call makes on every door, when the search ends (answered, refused or thrown). Message [knowledge] search timing, object under the meta field knowledgeSearchTiming. At info when isCloudManaged() (OS_CLOUD_MANAGED=1), at debug otherwise; on by default, no switch.
  • Fields, and nothing else: sources[] (id as the answer names it, mode, scope: { kind, terms, ids } counted, never listed), topK, groupBy (boolean), hits, refused, refill, failed, statements (count), and ms: { total, embed, queue_wait, statements, visible_ids, permission_recheck }, each a sum over the search, null when that segment did not run or the store reports nothing. No question text, no record id, no passage, no title.
  • Shared shape with the pgvector bench of knowledge-pgvector:检索分段计时与 PostgreSQL 基线(专题 #38703 B1) #38719: the segment names are the bench's (embed, visible_ids, permission_recheck); queue_wait is the bench's pool_wait and statements is its ranking + other_sql. The mapping is in the module docblock.
  • How the store's numbers reach the line without a contract field (@objectstack/knowledge-turso, new search-timing.ts; turso-adapter.ts gains three calls). The adapter publishes { queueWaitMs, statements, statementMs } once per search call on the Node diagnostics channel objectstack:knowledge-adapter:search-timing. A diagnostics-channel message reaches its subscribers synchronously in the publisher's async context, and the adapter publishes from inside the search call the service awaits, so the service credits it to the right search from its own AsyncLocalStorage; no id crosses AdapterSearchOptions. That keeps two concurrent searches apart, and keeps holding once Part 2 lets reads overlap. Why not the alternatives: a field on AdapterSearchOptions or an adapter option changes the contract or widens a published type (Clause-②), and an adapter-local line correlated by a search id gives the reader two lines to join and needs a logger the adapter does not have.
  • Queue wait is measured where the adapter enters serial(): queued() hands serial() the same work wrapped so it adds now-minus-enqueue when it starts, summed over the search's queue entries. serial() and the queue order are untouched.
  • Statements: the adapter's client is wrapped (outermost, over the request bound when one is set) so each request made inside a search (execute, batch, a transaction's open, execute, batch, commit, rollback) is counted and timed for it. Outside a search a request is the client's own call, unwrapped. Writes, builds, record syncs and indexStatus run outside the search scope and are never counted, even when queued between a search's entries.
  • Cost of the line: a few performance.now() reads and one AsyncLocalStorage scope per search, one synchronous channel message per store call, one log line. No database read, no embedding call. While no service has subscribed, the adapter measures and publishes nothing.
  • pgvector: the line has the same shape for it, because the service emits it for every store. total, embed, visible_ids and permission_recheck are measured for it today; queue_wait and statements stay null, since knowledge-pgvector does not publish on the channel. Filling them in place means wrapping its pool checkouts and statements, as the bench does from outside. That is left to this card.

Log key for the cloud seat (os-4 before reading, after merge): message [knowledge] search timing, field knowledgeSearchTiming; per search read ms.total, ms.queue_wait, ms.embed, ms.statements with statements, ms.permission_recheck. This PR does not measure os-4; that reading belongs to the cloud seat after merge.

Tests

  • packages/services/service-knowledge/src/__tests__/search-timing-39037.test.ts (6): a search_knowledge call (through knowledgeTools().searchKnowledge, non-system caller, a three-id scope) logs exactly one line whose field set and ms keys are pinned, whose values are exact sums off a fake clock (performance.now mocked; no real time is measured, nothing sleeps), and whose serialization contains none of a distinctive question string, the record ids, the passage text or the title. Further cases cover null for segments that did not run and for a store that publishes nothing; summing over two sources and a refill round; two searches in flight at once, each credited only with its own store calls; a thrown search still logging failed: true; and info under OS_CLOUD_MANAGED=1 against debug otherwise.
  • packages/plugins/knowledge-turso/src/__tests__/search-timing-39037.test.ts (3), through the real KnowledgeService over a real :memory: libSQL store: the line's statements equals the requests the client saw and ms.statements equals their summed fake-clock cost, so the channel spelling is pinned end to end. An uncontended search shows queue_wait 0. A search enqueued behind another search's held request shows that hold as its own queue_wait, while for the holder the same hold shows as statement time and not as queue wait. A further case pins that nothing is wrapped while no service subscribes.

Acceptance notes

  • Conflict, declared: the claim's file surface lists only turso-adapter.ts for the turso package. turso-adapter.ts is over 1,000 lines (1,907), and the dev rule sends a new concern into a sibling module. So the timing code is in a new packages/plugins/knowledge-turso/src/search-timing.ts, and turso-adapter.ts gains three calls. knowledge-tools.ts is unchanged: the line sits in the service, which every search_knowledge door passes through.
  • refused and failed were added to the card's field list: both are counts or flags, not content, and without them an empty answer cannot be told from a refused or thrown one.
  • The line logs at service level, so a direct IKnowledgeService.search caller gets the same line. Today the only caller in this tree is the search_knowledge executor.
  • Part 2 observations are on the card, not here.

Verification

Two-minute check: pnpm --filter @objectstack/knowledge-turso exec vitest run src/__tests__/search-timing-39037.test.ts. Expected: 3 passed. On a hosted runtime, one [knowledge] search timing info line per search_knowledge call.

Read first, by risk: packages/plugins/knowledge-turso/src/search-timing.ts (the client proxy in the request path of every store call: the passthrough when no search is in scope), packages/services/service-knowledge/src/knowledge-search-timing.ts (content absence; the finally that logs a thrown search), and the knowledge-service-search.ts hunks (calls only).

Readings on head 2e2a79729b (branch tip after merging origin/main 6354509; the incoming commits touch docs/adr, packages/spec/src/ui and packages/cli, none of this PR's packages).

Tests (local, under the shared verify lock)
  • pnpm --filter @objectstack/service-knowledge exec vitest run --maxWorkers=2: Test Files 32 passed, Tests 902 passed (VERDICT command-exit 0).
  • pnpm --filter @objectstack/knowledge-turso exec vitest run --maxWorkers=2: Test Files 7 passed, Tests 338 passed (VERDICT command-exit 0).
  • pnpm --filter @objectstack/service-knowledge typecheck and pnpm --filter @objectstack/knowledge-turso typecheck (tsc plus the test-layer check): exit 0, on 6df70abf7c before the merge. The merge touched neither package and left packages/spec/src/contracts alone; not re-run.
  • Ablation, on disk, restored by git checkout HEAD with git hash-object equal before and after and git status empty. (1) queued() handing serial() the bare work: the turso contention case goes red, expected 0 to be greater than or equal to 100. (2) Dropping noteSearchTargets(sources): three service cases go red, sources: [].
Gates (derived by dispatch-gates --commands, reconciled with --ran)
  • 71 derived, 70 run with exit 0, 1 NOT MEASURED: check:dual-build-cjs-loads reports PREREQUISITE NOT MET (exit 3). It reads every package's built dist, and this worktree built only the two packages' dependency closure, so it is left to CI.
  • Fixed on this branch after a first red: check:logger-receiver-detach (the line now calls logger.info and logger.debug through the receiver), check:objectql-double-limit and check:where-matcher (the two test doubles now filter generically, hold the caller's limit after the filter, and refuse a combinator). Each is exit 0 on re-run.
  • check:query-options-erasure (301 s) and check:type-check-debt (239 s) went past a first 200 s local cap on a shared box and are exit 0 on re-run.
  • The rest of the CI battery (the required checks, type-check lanes, Build Core) is left to the PR's check-runs.

Generated by Claude Code

🤖 Generated with Claude Code

https://claude.ai/code/session_01WGufzeatqKfTRUzTJVa9jQ

…e's queue wait and requests reported to it

Claude-Session: https://claude.ai/code/session_01WGufzeatqKfTRUzTJVa9jQ
Co-authored-by: Claude <noreply@anthropic.com>
…, segment sums and the turso store's queue wait

Claude-Session: https://claude.ai/code/session_01WGufzeatqKfTRUzTJVa9jQ
Co-authored-by: Claude <noreply@anthropic.com>
…; the test doubles hold the caller's limit

Claude-Session: https://claude.ai/code/session_01WGufzeatqKfTRUzTJVa9jQ
Co-authored-by: Claude <noreply@anthropic.com>
…inator they do not implement

Claude-Session: https://claude.ai/code/session_01WGufzeatqKfTRUzTJVa9jQ
Co-authored-by: Claude <noreply@anthropic.com>
@github-actions github-actions Bot added size/l documentation Improvements or additions to documentation tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Dec 2, 2026
@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 2 package(s): @objectstack/knowledge-turso, @objectstack/service-knowledge, touching 34 documentable anchor(s).

20 hand-written doc(s) name something this change touched — list omitted above 15 rows. Re-derive on the tree named below: node scripts/docs-audit/affected-docs.mjs --json 6354509427fab0ca2052b2b05be787f8593422ca.

⛔ 6 release-owned page(s) also affected — read-only, see AGENTS.md Documentation Guardrails.

What this run could not see
  • 19 name(s) were too generic to anchor anything (single lowercase words)
  • the SDK route bridge reached 71 of 254 client-bound route-ledger rows — the other 183 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 183: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 124 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 5 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json 6354509427fab0ca2052b2b05be787f8593422ca → packageMentionDocs.

Which tree this was computed on

This run read content/docs from 27a696562914a8c7e1b106599871ab7d88f2a097 — the merge of head 2e2a79729b4a0ce236f46bdfe01aa9bd53845279 into base 6354509427fab0ca2052b2b05be787f8593422ca, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# while this PR is open — GitHub drops the merge commit once it closes
git fetch origin 27a696562914a8c7e1b106599871ab7d88f2a097 && git checkout 27a696562914a8c7e1b106599871ab7d88f2a097
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 6354509427fab0ca2052b2b05be787f8593422ca 2e2a79729b4a0ce236f46bdfe01aa9bd53845279 && git checkout -B drift-repro 6354509427fab0ca2052b2b05be787f8593422ca && git merge --no-ff 2e2a79729b4a0ce236f46bdfe01aa9bd53845279

node scripts/docs-audit/affected-docs.mjs --json 6354509427fab0ca2052b2b05be787f8593422ca

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

Advisory only, and a precision-first one (#9192): a page is listed because it names a
symbol, wire route or SDK method this diff touched — not because it mentions a changed
package. Each row says which anchor put it there, so a wrong row is reportable rather than
merely annoying. To re-verify, run the docs-accuracy-audit workflow scoped to these files:
node scripts/docs-audit/affected-docs.mjs 6354509427fab0ca2052b2b05be787f8593422ca → pass the list as
args.docs, on the commit named under Which tree this was computed on.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack@os-support-ai · os-support-ai · session_01WGufzhGA3zoCFquQgku4pm

L1 review — ACCEPT on 2e2a79729b

Part of #39037 (Part 1), 7 files, 875 lines. Not governed, and no L2 is owed: nothing new is exported from either package's index, and no spec type changes, so Clause-②: no holds. l1-face is CLEAN on this head. Check-runs: 39 success, 18 expected-skip, 0 failed, 0 pending.

The zone asked for four points to be weighed:

  1. Customer content. None reaches the line. It carries source names (metadata, not records), counts and milliseconds. The scope is counted as kind, terms and ids and never listed. The question, record ids, passage and title are pinned absent with distinctive strings. A thrown search still logs, as failed, and that is pinned too.
  2. The diagnostics channel as an undeclared contract. Acceptable as it stands. The contract is numbers only. The name is spelled in each package, and the turso test pins the two spellings together through the real service. Channel names are global to the process, so every module copy of a store reaches the same channel. Each service copy reads its own AsyncLocalStorage, so a copy that is not awaiting the search ignores the message. Delivery is synchronous, in the publisher's context, and the publish sits in timedSearch's finally inside the awaited call, so it is credited to the right search. Two searches in flight at once are pinned apart. It needs no spec field until a third-party store wants to publish. At that point the channel and its message shape belong in the adapter contract docs.
  3. The client proxy's reach into transactions.
    • A request is counted only when searches.getStore() is set at call time. A transaction is wrapped only when it was opened inside a search, and outside a search every call is the client's own.
    • The serial queue's key is still the raw opts.client (queueKey), so wrapping the client does not split the queue shared across adapters.
    • serial() and its order are unchanged. timedQueueEntry reads the clock only at enqueue and at start.
  4. refused and failed, which the card does not list. Both are numbers or flags, both cost nothing, and both explain a line whose hits is 0. Keep them.

Nits, not owed:

  • N1. await this.ready() runs inside the search scope. On a cold store, the first search's statements includes the one-time schema setup, so the first hosted line after boot can read high. One sentence in the module docblock would cover it.
  • N2. The client is wrapped in the proxy even when nobody subscribes. Each property read binds a new function, which costs almost nothing beside a network request. Function identity is not stable across reads (client.execute !== client.execute); nothing in the adapter compares them.
  • N3. statements and queue_wait are sums over calls that can overlap within one search, so either can exceed total. The changeset says "each segment is a sum over the search", which is true. A reader of the line may still expect a breakdown, so "can exceed total when sources run side by side" would save them a question.

Part of: the card stays open for its later parts and keeps pm:dispatched (landing rule B). Not Tier H: the zone lands it.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack@os-support-ai · os-support-ai · session_01WGufzeatqKfTRUzTJVa9jQ

落地

reading value
check-governed-merges.mjs --pr 39093 (head fetched) NOT governed — 7 files, 875 changed lines ≤ 3000
reviews on 2e2a7972 L1 ACCEPT 7339802277 (osa-L1-a); no L2 owed (nothing new exported from either package index, no spec type, Clause-②: no). Nits N1–N3 not owed. No graded finding open.
check-runs on 2e2a7972 39 success · 18 expected skip · 0 failed · 0 pending; mergeable_state clean
K landing-k.mjs --pr 39093: K = 2 < 15, no new locale pack, no shared book moved

State change: ready for review + auto-merge, by zone osa-ai (2026-12-02T08:42Z). Part of #39037 (Part 1): the card keeps pm:dispatched (landing rule B). Next on the card: the cloud seat bumps the framework pin, deploys to staging and reads os-4's before numbers from message [knowledge] search timing, field knowledgeSearchTiming (per-search p50/p95, ms.queue_wait); then Part 2 (reads stop queueing behind reads) is claimed. Accepted nits: N1 cold-start statements include the one-time schema setup; N2 the client proxy is present when nobody subscribes; N3 statements / queue_wait are sums and can exceed total when sources run side by side.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/l tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants