Repository navigation
feat(service-knowledge): a narrow caller's search ranks only the records they may read - #38160
Conversation
…rds they may read Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
… with the caller scope Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
…e turso record index Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
…an of the passage table Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
📓 Docs Drift CheckThis PR changes 3 package(s): 3 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 — 4 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 af477a5eae98371c118ddb6ae57eb4125df72c3a && git checkout af477a5eae98371c118ddb6ae57eb4125df72c3a
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 581ae76a23c6b3ba8e2b69e7d8a920838bc51194 27b7a296bb23c656d6cc0dba7785cbe8331132dc && git checkout -B drift-repro 581ae76a23c6b3ba8e2b69e7d8a920838bc51194 && git merge --no-ff 27b7a296bb23c656d6cc0dba7785cbe8331132dc
node scripts/docs-audit/affected-docs.mjs --json 581ae76a23c6b3ba8e2b69e7d8a920838bc51194
|
|
repo:objectstack#1 · os-elon-musk · session_016WV4czzx9dtSEm3jWWL9c3 L1 verdict (L1-a): ACCEPT at head Review summaryShape. The PR touches 11 files, +483/-14, and is NOT governed. It declares Permission face, read against the code.
Indexes. turso adds a Docs and changeset. Read sentence by sentence against the diff, and true. The 500 bound, the four fall-back conditions and the unchanged re-check are each named once. Gates. CI on this head at 05:07Z: 36 success, 0 failed, 3 Test Core shards pending. This ACCEPT is on the code. The landing waits on every check at this head being green, which the area reads before it lands. The PR is still a draft. Next: the area lands it on all-green at this head. |
|
repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP Landing · area o1-C · head
State: ready + auto-merge; #37957 closes on merge via |
…approximate pass before the exact scan (objectstack-ai#38229) Fixes objectstack-ai#38066 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:托管版大知识源上,按上级记录(例如某个客户名下)限定、只覆盖一到两成内容的检索,从约 0.9 秒降到约 0.35 秒;按具体记录限定的检索保持原样。 - 为什么做:属于“云上知识库(Turso)”主线,替检索范围窄的用户提速;席位已按实测把范围收窄到这一种限定方式。 - 出错会怎样:最坏是多做一次近似检索后照旧逐条比对,结果与以前一致、只慢约 0.2 秒;召回率实测与原规则相同;改动可以直接撤回,无需迁移。 - 要你做的:无。 ## What changes `TursoKnowledgeAdapter.search`, the approximate vector leg (`packages/plugins/knowledge-turso/src/turso-adapter.ts`). Today, the leg runs the exact scan when the filter leaves fewer than 8 x `topK` of its `topK x vectorIndexOverfetch` candidates in scope. Such a leg now first runs one more approximate pass over 10 times the candidates (`VECTOR_RETRY_POOL`, not exported), with the same `WHERE` and the same floor. It keeps that answer only if it clears the floor; otherwise the exact scan answers, as before. The second pass is tried only when both hold: - **The scope cannot use the record index.** That means no scope, or a scope with at least one parent (`metadata`) term. A scope of record terms alone keeps today's path, because since objectstack-ai#38160 its exact scan reads only the rows in scope through the record index. This is the seat's ruling B on this card, comment 7236023531 (option A of os-dev-report 7235999186). The ruling also files a separate card for a narrow record-only scope that skips the one-bit pass; this PR does not touch that path. - **The first pool says the wider pass can clear the floor**, that is pool x 10 is at least 8 x `topK`. A scope too narrow for that goes to the exact scan without a pass that could not answer. A failed second statement is treated like a failed first one: the index memory is forgotten and the exact scan answers. No option, export or stored shape changes. The README Search section and the jsdoc carry the rule and the numbers. ## Tests `src/__tests__/acceptance.test.ts` gets a new case, run on each store kind, with an explicit 30 s timeout. The corpus is 400 passages with tag lists that a parent scope term matches; `topK` is 2 and over-fetch 8, so there are 16 candidates, a floor of 16 and 160 for the second pass. Every scope's hits equal the exact scan's. - `wide` (the 2 best plus half the far passages): `{ approximate: 2, exact: 0 }`. The bound candidate counts are `[16, 160]`, and each pass binds exactly the values it reads. - `short` (5 passages): `{ approximate: 2, exact: 1 }`. Both passes fall short, then the exact scan answers. - `thin` (one far passage): `{ approximate: 1, exact: 1 }`. The pool is too thin for a second pass. - **Record-only control** (the `wide` passages as record ids): `{ approximate: 1, exact: 1 }`. There is no second pass. The two existing pins that run a record scope under the floor, the over-fetch case and the term-less binding case, keep their expectations unchanged. That is the record-only path staying as it is. **Ablation**, an on-disk edit replacing the second pass's condition with `false`: `Tests 2 failed | 126 skipped` (the new case on both store kinds, `{ approximate: 1, exact: 1 }` instead of `{ approximate: 2, exact: 0 }`). The file was restored to a blob equal to `HEAD:` (`git hash-object` 5573a5c on both sides), with an empty `git status`. <details><summary>Local runs on the final head</summary> All ran on head `07a84d2e10` (origin/main `2d95781690` merged), under `os-verify-lock` (`VERDICT command-exit 0`, held 1,194 s). - **Typecheck:** `pnpm --filter @objectstack/knowledge-turso typecheck` exits 0. `check:test-typecheck` is OK (0 errors). - **Tests:** `pnpm --filter @objectstack/knowledge-turso exec vitest run --maxWorkers=2` exits 0, with `Test Files 4 passed (4)` and `Tests 278 passed (278)`. - **Derived gates:** `dispatch-gates --commands` derived 67 commands at `07a84d2e10`. 66 ran, and each exited 0. - `check:dual-build-cjs-loads` was left to CI. A first pass refused it with exit 3 (`PREREQUISITE NOT MET`: 60 packages have no `dist` in this worktree; it needs a whole-repo build). - Reconciled with `--ran`: `67 derived, 66 run, 0 NOT-MEASURED, 1 UNRUN`. The one UNRUN is that gate. - **Tests on `5447b42c76`:** the run there found a TS18048 in the new test's fixture (`d.metadata` possibly undefined). `07a84d2e10` fixes it. </details> ## Acceptance notes **Real-store bench, restated to the parent scope by the ruling.** 200,000 passages of 1,536 dimensions, clustered synthetic (the data model of `scoped-recall-floor8-retry-sim.py`: latent 384, 200 clusters, sigma 1.0). The `file:` store was built through the adapter: upsert 149 s, `completeBuild` with the one-bit index 8.1 s, 1.72 GB. - Each share ran 50 vector-only queries at `topK` 10. Each query was run by the exact scan (an adapter at `vectorIndexThreshold: Infinity`, which is also the recall truth) and by the adapter under test, interleaved. - The parent scope is one `metadata` term over a `bucket` key holding 10, 15 or 20 of 100 buckets. - "Floor 8" is this head with the second pass ablated on disk, which equals `main`'s rule. - Everything ran under `os-verify-lock` (`VERDICT command-exit 0`) on head 6c530b0; later commits change only a test line. The box was shared (load 1.6 to 3.3 on 4 cores), and each row's exact column is that same run's. | Parent scope | Exact scan p95 | Floor 8 p95 | Second pass p95 | recall@10, floor 8 / second pass | Sent exact, floor 8 / second pass | |---|---|---|---|---|---| | 10% | 810 / 848 ms | 947 ms | **351 ms** | 1.000 / 1.000 | 100% / 0% | | 15% | 824 / 907 ms | 948 ms | **328 ms** | 1.000 / 1.000 | 100% / 0% | | 20% | 910 / 908 ms | 974 ms | **337 ms** | 0.986 / 0.986 (worst 0.8 on both) | 44% / 0% | - The exact column gives two readings: the one from the floor-8 run, then the one from the second-pass run. - **Ablation pin on the bench.** With the second pass removed, the share of queries sent exact goes back up from 0% to 100%, 100% and 44%. - **Statement costs (p50):** the first one-bit pass (400 candidates) takes 115 to 119 ms, and the second (4,000) takes 168 to 175 ms. - **The recall at 20% is the first pass's.** The 56% of queries that clear the floor in the first pass are answered there, under both rules. The second pass answered the other 44% with the exact scan's top 10. **Record-scope control** (this head): the second pass never runs (0 of 150), and the path is the floor-8 rule. | Record scope | Exact scan p95 | This head p95 | Sent exact | |---|---|---|---| | 10% | 135 ms | 262 ms | 100% | | 15% | 177 ms | 345 ms | 98% | | 20% | 269 ms | 422 ms | 48% | Under a record scope, the ungated second pass measured 333, 313 and 407 ms p95 against 128, 207 and 265 ms for the exact scan (os-dev-report 7235999186). That is why the record-only path is left alone here. The floor-8 path's own excess over the exact scan in the table above belongs to the separate card the ruling files. - **Caveats.** - Synthetic vectors only, as in objectstack-ai#38056. - The bench is a scratch script and is not committed. Its data was deleted after the run; rebuilding it is `gen.py` (5 s) plus a 200,000-passage build (about 160 s). - A hybrid query also re-runs its keyword leg in the second statement. This bench measured vector-only queries. - **Out of scope, noted:** none beyond the ruling's separate card. ## Verification Read first, by risk: 1. `turso-adapter.ts`, `searchAttempt`: the `recordScope` flag set in the scope loop, the `approximate` and `stands` closures, and the order first pass, second pass, exact. 2. `turso-adapter.ts`, `VECTOR_RETRY_POOL`: the gate: the first pool times `VECTOR_RETRY_POOL` is at least `VECTOR_MIN_POOL * topK`. 3. `acceptance.test.ts`, the fixture of the new case: which tags hold which passages. Two-minute check: ``` pnpm --filter @objectstack/knowledge-turso exec vitest run --maxWorkers=2 src/__tests__/acceptance.test.ts -t "tries 10" ``` Expected: 2 passed, one per store kind. Then, in `searchAttempt`, replace the whole condition of the `if` that guards `approximate(candidates * VECTOR_RETRY_POOL)` with `false` and run it again: both turn red with `{ approximate: 1, exact: 1 }`. --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP
Fixes #37957
Clause-②: no
Metadata-protocol: none
维护者速读
What changes
Problem. A knowledge search re-checks every hit as the caller after ranking and refills once at
topK × 20. A caller who may read 20 of 1,000 indexed records gets none of them when they all rank below that cap.@objectstack/service-knowledge. Before the first round, for a caller who is not the system identity (and has an engine to re-check with), each object source is narrowed to the records that caller may read (sourcesNarrowedToVisible,readVisibleIds):where, as the caller:find(object, { where: source.where, fields: ['id'], limit: 501, context }).recordscope term holding them, so the adapter ranks only those rows.narrowToVisible, a pure function inknowledge-search-scope.ts), never appended: a one-record scope stays one record.metadata) term, the card's first option, since a union of terms cannot say "this parent AND these records" without an adapter contract change; a narrowing that names no record (so a caller who reads nothing is answered as before, no hit or the source's refusal, never a new kind of empty); a read that fails (logged atwarn); the system identity.@objectstack/knowledge-turso.passageTableDdladdsCREATE INDEX TABLE_record ON TABLE (source_record_id). New generations carry it; an existing generation gets it from its next build. No migration.@objectstack/knowledge-pgvector. Its DDL lacked the index too:vectorTableDdladdsCREATE INDEX IF NOT EXISTS "TABLE_record" ON TABLE (source_id, generation, source_record_id)(the table is shared by every source and generation, hence the prefix).Conformance harness (
@objectstack/service-knowledge/testing): its engine double answers the caller's visible-id read under the case'swall, and one new case runs the narrowed search through each real adapter.Docs:
content/docs/protocol/knowledge.mdx(the re-check paragraph, both stores' table lines). Changeset: patch on the three packages.Read first
packages/services/service-knowledge/src/knowledge-search-scope.ts,narrowToVisible: the intersection. A union here would widen a caller's own scope; ablation A1 below.packages/services/service-knowledge/src/knowledge-service.ts,sourcesNarrowedToVisible/readVisibleIds: the read as the caller, the 500 bound, the fall-backs.packages/plugins/knowledge-pgvector/src/sql.ts: the new index on an existing shared table (see Acceptance notes).Tests
All on head
27b7a296bb(after mergingorigin/main9726bd8), underscripts/pm/os-verify-lock.sh.Package suites and typechecks: all exit 0
The pgvector live-Postgres files skip here (no Postgres server in this container): the pgvector index and the conformance case through pgvector are NOT MEASURED locally.
New pins:
knowledge-service.test.ts, describe "a narrow caller's search ranks only the records they may read" (13 cases): 20 of 1,000 readable, all ranked 900th to 919th, answered best first in one round; more than 500 readable takes the path before (control: none reached); exactly 500 narrows, 501 does not; a one-record scope stays one record; mixed readable/unreadable scope ids keep only the readable, in the caller's order; no readable id in scope, and no readable record at all, search as before; a parent term reads nothing and hands the caller's terms unchanged; the system identity reads nothing and is handed no scope; the organization filter is handed beside the narrowed term, equal to the unnarrowed path's; the source'swhereis the read'swhere, one read for two sources sharing it; a failed read warns and searches as before; a record the read answered but the re-check refuses is not served.knowledge-search-scope.test.ts:narrowToVisible(7 cases).testing.ts, through memory and turso): a caller who may read only the two clauses every other outranks is answered from them past the refill cap; their one-record scope stays one record.knowledge-tursoacceptance:EXPLAIN QUERY PLANof the adapter's own scoped search SQL (captured from the client) showsUSING INDEX TABLE_recordand no scan of the passage table.Fixture updates (same assertions, now naming the extra caller read): three pins that counted the caller's reads (
drops hits the user cannot read,the permission re-read stays one query as the caller,passes the caller's context to the row-level re-check) now see the visible-id read before the re-check.Ablations: each mutation reds its pins, then restored (git status clean after)
Measurements (amendment)
Scratch script, not committed: 100,000 passages (one per record) bulk-loaded into one turso generation table (
file:database, 64-wide fake embedder), the adapter's own search SQL captured and planned. Shared box, so read the ratios.EXPLAIN QUERY PLAN, 20 visible ids of 100k passages
Adapter search latency, median of 7 (index dropped: median of 3)
The 500 cap is not raised. 500 to 2,000 ids costs about 2.6x on the vector leg (3.3 to 8.5 ms) and about 1.1x on a keyword-heavy query.
Acceptance notes
MULTI-INDEX ORover the FTS matches), so a query of very common words still costs FTS-match time. Measured, not filed: no contract or recall defect.CREATE INDEX IF NOT EXISTSruns on an existing table at the first write or build per process after the upgrade. It is notCONCURRENTLY, so writes to that table wait while it builds. Same shape as the existing keyword index's creation.finddoes not promisemin(limit, remaining)rows (anafterFindhook may drop rows from a page). If a hook drops rows from the 501-row page, a caller with more than 500 rows could be read as having 500 or fewer, and their search narrowed to a subset. Recall only, never exposure: every hit is still re-checked. The platform's row security is pushed into the query, not intoafterFind.TABLE_recordshares SQLite's table/index namespace with a legacy table nameknowledge_SOURCEonly for a source id ending in_gN_record. The existingTABLE_documentindex has the same property.node scripts/pm/overlap-check.mjson the branch before the merge:VERDICT clean exit 0againstorigin/mainand feat(knowledge)!: refuse a knowledge_source save that names an adapter the running deployment does not mount #38060, feat(knowledge-turso): an approximate vector index for a large source of one organization #38056, docs(knowledge): the 18 to 19 id row names the underscore exception and the dropSource cleanup #38050, fix(lint)!: knowledge-source review follow-ups: absent platform objects refused at publish, ai_context accepts id, search refusal names list #38038, feat(metadata-core)!: a knowledge source is saved only on a deployment that mounts the knowledge service #38013. feat(knowledge-turso): an approximate vector index for a large source of one organization #38056 (F6) sharessql.tsand the turso acceptance file and merges cleanly. Whichever lands second merges main.Verification
Two minutes:
pnpm --filter @objectstack/service-knowledge exec vitest run --maxWorkers=2 src/__tests__/knowledge-service.test.ts -t "narrow caller". Expect 13 passed. Thenpnpm --filter @objectstack/knowledge-turso exec vitest run --maxWorkers=2 src/__tests__/acceptance.test.ts -t "source_record_id index". Expect 2 passed (:memory:andfile:).Local gate families (
dispatch-gates --commands) NOT MEASURED: the run was denied by the session's action classifier. CI runs them all.Generated by Claude Code