Skip to content

feat(service-knowledge): a narrow caller's search ranks only the records they may read - #38160

Merged
objectstack-fleet[bot] merged 5 commits into
mainfrom
claude/area-o1C-37957
Nov 28, 2026
Merged

objectstack-fleet[bot] merged 5 commits into
mainfrom
claude/area-o1C-37957

Conversation

@objectstack-fleet

Copy link
Copy Markdown
Contributor

repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP
Fixes #37957
Clause-②: no
Metadata-protocol: none

维护者速读

  • 用户能看到什么变化:只能看到少量记录的用户(例如一千条里只能看二十条)在知识库搜索里,能搜到自己有权看的答案了;以前这些答案排名靠后时会一条都搜不到。系统身份和能看到很多记录的用户行为不变。
  • 为什么做:属于“云上知识库(Turso)”这一主线,替权限范围窄的普通用户解决“明明有答案却搜不到”。
  • 出错会怎样:最坏是这类用户仍然搜不到(回到以前的样子),不会多看到无权看的内容,因为每条结果仍逐条按权限复核;改动可以直接撤回,旧索引无需迁移。
  • 要你做什么:无。

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):

  • One read per object and where, as the caller: find(object, { where: source.where, fields: ['id'], limit: 501, context }).
  • 500 or fewer ids: the source is handed one record scope term holding them, so the adapter ranks only those rows.
  • The adapters OR their scope terms, so the visible ids are INTERSECTED with a caller-given record scope (narrowToVisible, a pure function in knowledge-search-scope.ts), never appended: a one-record scope stays one record.
  • Unchanged path (searched exactly as before): more than 500 ids; a caller scope holding a parent (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 at warn); the system identity.
  • The rounds, the refill, the per-hit permission re-check and the organization filter are untouched. The removed-hit count is still never returned.

@objectstack/knowledge-turso. passageTableDdl adds CREATE 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: vectorTableDdl adds CREATE 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's wall, 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

  1. 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.
  2. packages/services/service-knowledge/src/knowledge-service.ts, sourcesNarrowedToVisible / readVisibleIds: the read as the caller, the 500 bound, the fall-backs.
  3. packages/plugins/knowledge-pgvector/src/sql.ts: the new index on an existing shared table (see Acceptance notes).

Tests

All on head 27b7a296bb (after merging origin/main 9726bd8), under scripts/pm/os-verify-lock.sh.

Package suites and typechecks: all exit 0
build closure (service-knowledge, knowledge-turso, knowledge-memory, knowledge-pgvector ^...) B=0
@objectstack/service-knowledge   Test Files 19 passed (19)   Tests 677 passed (677)   typecheck 0
@objectstack/knowledge-turso     Test Files 4 passed (4)     Tests 235 passed (235)   typecheck 0
@objectstack/knowledge-memory    Test Files 3 passed (3)     Tests 66 passed (66)     typecheck 0
@objectstack/knowledge-pgvector  Test Files 3 passed | 7 skipped (10)  Tests 14 passed | 90 skipped (104)  typecheck 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's where is the read's where, 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).
  • Conformance (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-turso acceptance: EXPLAIN QUERY PLAN of the adapter's own scoped search SQL (captured from the client) shows USING INDEX TABLE_record and 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)
A1 intersection -> union (visible ids appended as one more term)   8 failed | 205 passed  exit=1
   incl. "a caller's one-record scope stays one record", "a one-record scope stays one record however many ids are visible",
   "20 records, two of them in scope, topK 5", "a caller scope naming readable and unreadable records"
A2 no narrowing at all                                              7 failed  exit=1
   incl. "a caller who may read 20 of 1,000 records is answered from their 20"
A3 the 500 bound dropped                                            2 failed  exit=1
   "control: ... more than 500 records takes the path before", "exactly 500 ... still narrow; 501 do not"
A4 the system identity narrowed too                                 1 failed  exit=1
   "the system identity: no read, no scope handed, one round of topK"
A5 the organization filter dropped when narrowing                   1 failed  exit=1
   "the organization filter is handed as before beside the narrowed term"
A6 turso source_record_id index removed from passageTableDdl        2 failed (memory and file: URL)  exit=1

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
SEARCH knowledge_bench_g1 USING INDEX knowledge_bench_g1_record (source_record_id=?)          vector leg
SEARCH knowledge_bench_g1 USING INDEX knowledge_bench_g1_record (source_record_id=?)          keyword leg candidates
SEARCH knowledge_bench_g1 USING COVERING INDEX knowledge_bench_g1_record (source_record_id=?) count(*) in scope
Adapter search latency, median of 7 (index dropped: median of 3)
query                       ids    with index   index dropped
vector-led ("zebra quokka")  20      1.1 ms       38.2 ms
vector-led                  500      3.3 ms       48.5 ms
vector-led                 2000      8.5 ms       55.2 ms
vector-led, unscoped topK 100        59.0 ms
keyword-heavy (3 words each in ~30% of passages)
                             20    232.4 ms      346.3 ms
                            500    240.9 ms      376.4 ms
                           2000    262.9 ms      388.8 ms
keyword-heavy, unscoped topK 25     521.6 ms;  topK 100: 533.0 ms

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

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. Then pnpm --filter @objectstack/knowledge-turso exec vitest run --maxWorkers=2 src/__tests__/acceptance.test.ts -t "source_record_id index". Expect 2 passed (:memory: and file:).

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

…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
@github-actions github-actions Bot added size/m documentation Improvements or additions to documentation tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Nov 28, 2026
@github-actions

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

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

3 hand-written doc(s) NAME something this change touched and may need an implementation-accuracy re-verification:

  • content/docs/ai/knowledge-rag.mdx (via KnowledgeService (symbol, a top-level class))
  • content/docs/permissions/system-context.mdx (via searchByKey (symbol, a method of class KnowledgeService))
  • content/docs/protocol/knowledge.mdx (via KnowledgeService (symbol, a top-level class), runKnowledgeAdapterContract (symbol, a top-level function))
What this run could not see
  • the SDK route bridge reached 69 of 252 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 — 4 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 581ae76a23c6b3ba8e2b69e7d8a920838bc51194 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from af477a5eae98371c118ddb6ae57eb4125df72c3a — the merge of head 27b7a296bb23c656d6cc0dba7785cbe8331132dc into base 581ae76a23c6b3ba8e2b69e7d8a920838bc51194, 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 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

⚠️ 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 581ae76a23c6b3ba8e2b69e7d8a920838bc51194 → 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#1 · os-elon-musk · session_016WV4czzx9dtSEm3jWWL9c3

L1 verdict (L1-a): ACCEPT at head 27b7a296bb23c656d6cc0dba7785cbe8331132dc (Fixes #37957). Full read, including the permission face.

Review summary

Shape. The PR touches 11 files, +483/-14, and is NOT governed. It declares Clause-②: no and Metadata-protocol: none, and the face reader decides no contract face, so no contract review is owed. Patch changesets for service-knowledge, knowledge-turso and knowledge-pgvector are right, since no option or published type is added.

Permission face, read against the code.

  • narrowToVisible intersects the visible ids with the caller's own scope and never adds them as one more OR term. A parent term returns undefined, so the caller's terms go unchanged. Ablation A1 (union in place of intersection) reds 8 pins.
  • readVisibleIds reads as the caller, with the caller's context and under the source's where. It reads ids only, with limit 501. Anything over 500, or a failed read (a warn), answers undefined, which means the current path.
  • A narrowing that names no record is not applied, so a caller who may read none of a source's records is answered exactly as before.
  • The system identity and a context-less caller skip the read.
  • The per-hit re-check as the caller, the refill and the organization filter are untouched. A pin shows that a record the read answered but the re-check refuses is not served. Narrowing can therefore only shrink what reaches the re-check; it never decides access.
  • Reads are shared per object and where within one search.

Indexes. turso adds a source_record_id index to each new generation's passage table. pgvector adds (source_id, generation, source_record_id) with CREATE INDEX IF NOT EXISTS. The changeset states truthfully that the pgvector build holds writes to that table while it runs. The dev's note that it is not CONCURRENTLY is accepted: there are no production customers yet. The turso EXPLAIN QUERY PLAN pin shows the index is used. pgvector live is NOT MEASURED here (no Postgres), as the body says.

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.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP

Landing · area o1-C · head 27b7a296bb · 2026-11-28T05:11Z · ACCEPT → PR #38160 comment 7234460475 (L1-a, permission face read)

Probe Reading
check-runs at 27b7a296bb 40 success · 15 expected skip · 0 failed · 0 pending · mergeable_state clean
check-governed-merges.mjs --pr 38160 NOT governed (0 of 11 paths) · +483 / −14
landing-k.mjs --pr 38160 K = 5 < 15

State: ready + auto-merge; #37957 closes on merge via Fixes. Clause-②: no, patch on service-knowledge, knowledge-turso and knowledge-pgvector; no contract review owed per L1. The dev's local derived gates are NOT MEASURED (a background run was refused and not retried); CI's green check-runs are the reading. pgvector against a live PostgreSQL is NOT MEASURED in the area (no server), as the PR body says.

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/m 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.

service-knowledge: search pre-filters by the caller's visible record ids within the record scope

2 participants