Skip to content

Commit 039b288

Browse files
fix(service-knowledge): search refills after the permission filter; a hit's title is the object's display field (#37301)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ8HtXJcvyDnGVcP1BL7DwnBY)_ Fixes #36993 Fixes #36994 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:在挂了知识库的应用里,一个人能看的记录很少时,AI 检索不再返回空或只剩一两条,而是继续往后找,补满到要的条数;命中结果的标题改为取对象的名称字段(比如客户的「名称」、发票的编号),不再只认名为 title 的字段。 - 为什么做:知识检索平台化专题的第一、四阶段两张卡,同一个文件一起修;「按记录返回」那张卡要在这次的补齐逻辑上继续做。 - 出错会怎样:最坏是检索多读一轮、稍慢,或某条命中没有标题。权限检查只多不少:名称字段对某人不可查时,这个知识源对他不检索;旧索引里的标题还取自名为 title 的字段,所以在索引重建之前,title 字段对某人不可查时同样不检索。可以直接撤回。 - 要你做的:无。 ## What changes **Search refills after the permission filter (#36993).** `KnowledgeService.search` re-checks every object-source hit as the caller *after* ranking, so a caller who may read few of the matching rows was answered from what was left of `topK` ranked hits. Now: - When the re-check can remove hits (a caller who is not the system identity, with a data engine bound), each `object` source is asked for `topK × SEARCH_FIRST_ROUND_FACTOR` (5). - When the survivors name fewer than `topK` records (several passages of one record count once: an object hit is its source and record id, any other hit its document), every `object` source that answered as many hits as it was asked (the only ones that may hold more) is asked once more, for `topK × SEARCH_REFILL_FACTOR` (20, the cap). That round's answer replaces the source's first-round hits; a source whose refill throws keeps its first-round survivors. At most two rounds; an adapter that caps `topK` answers fewer than asked and is never asked again. - A `file` / `http` source is asked for `topK` once (the re-check never removes its hits). The system identity gets one round of `topK`, no refill. No context: object sources stay unsearched, as before (fail closed). - The answer is still at most `topK` chunk-level hits, sorted by score; `search`'s return type is unchanged (`expectTypeOf` pin). The count the re-check removed is logged at `debug` only, never returned. - The adapter loop moved into a private `searchRound`, unchanged in behaviour (foreign-source hits dropped and warned, a throwing adapter logged and skipped). **A hit's title is the object's display field (#36994).** `recordToDocument` read `record.title`. Per ADR-0161 K5 ("the title is the object's display field"), it now reads the field `documentTitleField(schema)` names: `resolveDisplayField` (ADR-0079: `nameField`, its deprecated alias, else the derivation), and with no object definition a field named `title`, as before. A withheld field (credential-class or `internal`), an empty value, a value that is not text or a finite number, a definition that resolves no display field, or a `nameField` the definition does not declare gives no title. `resolveRecordDisplayName` is not used: its `Record #id` floor is a UI label. The source admission's field gate (`servedFieldsOf`) asks about the same field through the same `documentTitleField`. So a source whose object's display field the caller may not query is not searched for that caller at all. It also keeps asking about a declared field named `title`, as before: documents indexed under the earlier rule carry that field's value as their title and stay in the index until a complete reindex writes them again, and nothing reindexes at boot. That arm is retired once the index is proven rebuilt under the display-field rule (the recipe hash that names the title rule, ADR-0161 K7, and the rebuild of a stale source, #37099); the code comment says so. Docs: `content/docs/protocol/knowledge.mdx` states the refill and its cap, and the display-field title (three places that said "the record `title`"); `content/docs/ai/knowledge-rag.mdx` says the same in two sentences. `content/docs/permissions/system-context.mdx` row 46 keys `search` too (it now reads `isSystem`: the system identity skips the over-fetch and the refill), and its generated register is regenerated (`check:system-context-census --write`). ## Tests `packages/services/service-knowledge`: `pnpm test` 8 files / 219 tests passed at 4621738; `pnpm typecheck` exit 0 (incl. `check:test-typecheck`). New pins in `knowledge-service.test.ts` (two top-level describes) and `knowledge-source-admission.test.ts` (one): - 100 hits, the caller may read 5 spread across them → those 5, best first; asked `[s1, 25]` then `[s1, 100]`. - A readable row beyond the cap → fewer than `topK`, never a third round. Enough survivors → no refill. An adapter capping at 10 → asked once. Several sources → only the saturated one refilled. The refill decision counts records: topK 3, one source answers two passages of one readable record, another holds a readable record past its first round that outranks both → it is refilled and answers `[s1-c0, s1-c15, s2-a]`. A failed refill keeps round one. System identity → one round of `topK`, no re-check. No context → only the file source, asked `topK`. A file source beside an object source → asked `topK` once. - Removed count only in the `debug` log; answer and return type unchanged. - Title: explicit `nameField`; derived `name` over `title`; formula (text) and autonumber name fields (a number value → its text); withheld internal / secret name fields; empty, non-text, unresolvable and undeclared-`nameField` cases; no definition → `title`; the event sync and the reindex walk read the definition off the engine. - Field gate: hiding the display field refuses the source even with `title` visible; hiding a declared `title` that is not the display field refuses it too (the adapter returns a stored hit carrying an old-rule title, and the answer is empty); a caller who may query both gets the hit. <details><summary>Ablations: each committed first, mutated through scripts/ablation-replace.mjs, restored to HEAD with git diff HEAD empty</summary> - Refill disabled (`if (false && filtered && kept.length < topK)`): 6 refill tests red, 5 green (the ones that pin "no refill"). - Title back to `record.title`: 5 title tests red. - Field gate back to `title` only: both display-field gate tests red. - Refill decision back to counting hits (`kept.length`): the record-counting test red, 150 green. - The declared-`title` arm deleted from the gate: its refusal pin red, 24 green. </details> ## Acceptance notes - **#36993 point 2 is applied to the refill decision only.** The answer stays at most `topK` chunk-level hits (`KnowledgeSearchOptions.topK` is "Max number of hits to return"; `search_knowledge` returns "at most `topK`" passages; the card: "what is returned stays chunk-level hits"). Counting records decides whether to refill, and with several sources that changes the answer: another source's refill can outrank a second passage of a record already counted (pinned above). - **The declared `title` arm of the field gate is temporary.** Retire it when the index is proven rebuilt under the display-field rule (ADR-0161 K7 recipe hash, #37099). - **Title egress** (the question raised on #36994): ADR-0161 K5 declares the title as the object's display field, so it is sent whether or not the source lists that field among its content fields. It is withheld when the field is credential-class or `internal`. The field-egress declaration of cloud ADR-0119 does not exist yet; when it does, `documentTitleField` is the one place assembly and the gate both read. - The title enters `docHash`, so the first complete reindex after this lands rewrites the documents whose title changed. - Seat 4's #37287 edits the same file; `scripts/pm/overlap-check.mjs` merges this branch with its head cleanly (the search factors sit beside `LIST_DOCUMENTS_PAGE_SIZE` to stay clear of its new constant). ## Verification Files to read first: `packages/services/service-knowledge/src/knowledge-service.ts` (`search`, `searchRound`, `documentTitle`), `knowledge-source-admission.ts` (`documentTitleField`, `servedFieldsOf`). Two-minute check: `pnpm --filter @objectstack/service-knowledge exec vitest run src/__tests__/knowledge-service.test.ts -t refills` — 11 tests pass; the first shows a caller reading 5 of 100 hits getting all 5. <details><summary>Local gate families: the derived list (scripts/pm/dispatch-gates.mjs --commands, 98 commands, derived at ecb0842), run in order; CI runs the full farm</summary> - Rework round (4621738): package test 8 files / 219, typecheck 0, eslint on the four changed source and test files 0, check:doc-anchors 0, check:system-context-census 0, overlap-check clean against origin/main, #37287 and #37265. - 79 of 98 run: 76 exit 0; 3 PREREQUISITE NOT MET (not verdicts, NOT MEASURED locally, CI builds them): check-plugin-teardown-shape --self-test (shallow clone cannot reach its pinned fixture commit), spec check:skill-examples (client-react dist not built), check:dual-build-cjs-loads (hono / account dist not built). - The remaining 19 (the repo-wide eslint-backed ratchets onward) were still running when this was written: NOT MEASURED locally; their CI check-runs are the reading. - Also run: package typecheck (exit 0, incl. check:test-typecheck), eslint on the four changed source and test files (exit 0), check:doc-anchors (exit 0), check:system-context-census (exit 0 after row 46 below), scripts/pm/overlap-check.mjs (clean against origin/main, #37287 and #37265). </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (not touched) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01JQwxbWqwmAwx7eD4Xf3dv1 --- _Generated by [Claude Code](https://claude.ai/code/session_01JQwxbWqwmAwx7eD4Xf3dv1)_ <!-- signed: repo:cloud#1 · os-warren · session_01JQwxbWqwmAwx7eD4Xf3dv1 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d88c41e commit 039b288

8 files changed

Lines changed: 502 additions & 28 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/service-knowledge': patch
3+
---
4+
5+
fix(service-knowledge): search refills after the permission filter, and a hit's title is the object's display field
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
- **Search refills after the permission filter.** The permission re-check runs after ranking, so a caller who may read few of the matching rows used to get a short or empty answer. For a caller who is not the system identity, each `object` source is now asked for `topK × 5` hits; when the hits that survive the re-check name fewer than `topK` records (several passages of one record count once), each `object` source that answered as many as it was asked is asked once more, for `topK × 20` (the cap). At most two rounds; an adapter that answers fewer than it was asked is not asked again. A `file` / `http` source, and every source for the system identity, is asked for `topK` once. The answer is still at most `topK` hits; how many the re-check removed is logged at `debug`, never returned.
11+
- **A hit's title is the object's display field** (ADR-0161 K5; ADR-0079 `resolveDisplayField`: `nameField`, else the derived title field), not a field that happens to be named `title`. A credential-class or `internal` display field, an empty value, or an object with no display field gives no title; a source over an object with no registered definition still reads `title`. The source admission's field gate asks about the same field: a source whose object's display field the caller may not query is not searched for that caller at all. A declared field named `title` still gates the source too, because documents indexed before this change carry its value until a complete reindex writes them again.
12+
- The title enters `docHash`, so the next complete reindex rewrites the documents whose title changed.

‎content/docs/ai/knowledge-rag.mdx‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,13 @@ kernel.use(new KnowledgeMemoryPlugin());
4848
Retrieval is a plain service call — no AI runtime required. Resolve the `knowledge`
4949
service and call `search`. Hits are re-checked against the caller's
5050
`ExecutionContext` (RLS), sorted by score, and capped at `topK` before they come
51-
back.
51+
back. Because the re-check runs after ranking, for a caller other than the
52+
system identity the service asks each object source for more hits than `topK`,
53+
and asks once more when too few records survive, so a caller who may read few of
54+
the matching records still gets up to `topK` hits
55+
([the protocol](/docs/protocol/knowledge) gives the factors and the cap). A
56+
hit's `title` is the value of the object's display field (`nameField`, else the
57+
derived title field).
5258

5359
```ts
5460
const knowledge = ctx.getService('knowledge');

‎content/docs/permissions/system-context.mdx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ One of the largest consumers of the flag;
189189
| 43 | Approval actor / submitter / pending-approver checks bypassed (9 sites) | plugin-approvals | Get: approve, reject, recall, reassign without being a pending approver or the submitter, and a decision or comment that attaches files the actor did not upload (every other caller attaches only files it uploaded, in the request's organization) | `isOverrideActor`, `resolveActor`, `sendBack`, `resubmit`, `reassign`, `remind`, `requestInfo`, `comment`, `assertAttachmentsUploadedByCaller` |
190190
| 44 | Attachment access hooks return early (insert + update + delete, the referenced-file check on insert + update, and the read AST) | service-storage | Lose: attachment visibility scoping | `installAttachmentAccessHooks`, `installAttachmentFileReferenceGate`, `installAttachmentReadVisibility` |
191191
| 45 | Comment access hooks return early (insert + update + delete, and the read AST), and so do the activity and audit-log read gates (their read AST), the activity field redaction and the audit-log field redaction (the rows a read serves), the activity summary's message code (the rows a read serves), and the query guard over both objects' value-bearing columns (the read AST) | plugin-audit | Get: the whole activity row and the whole `sys_audit_log` row, its before/after snapshots included, and the activity row's stored summary code (`metadata.summary_message`), on `find` / `findOne` — the audit writer, each read gate's bounded probe and the activity backfill — and a filter, sort or grouping by those columns. Lose: comment visibility scoping, the narrowing of `sys_activity` and of `sys_audit_log` to rows whose parent record the caller can read, the redaction of a parent field's value from an activity row's text and recorded change and from a ledger row's before/after snapshots, the withholding of an activity row recording an update whose every changed field the reader is withheld, of a fired milestone row whose watched fields it is not all served, and of an unstamped row (on `count` and `aggregate` too, so a total agrees with the rows), the removal of that summary code from the activity row's `metadata` (its params are field values), and the refusal of a query over those columns for a reader withheld a field of the objects it can reach, and the withholding of those columns from such a reader's server-chosen search set (#34700) | `installCommentAccessHooks`, `installCommentReadVisibility`, `installActivityReadVisibility`, `installAuditLogReadVisibility`, `installActivityFieldRedaction`, `installAuditLogFieldRedaction`, `installActivitySummaryLocale`, `installParentFieldQueryGuard`, `withheldSearchColumns` |
192-
| 46 | Knowledge search returns hits unfiltered, and searches every source | service-knowledge | Lose: the permission filter over search results, and the source admission ahead of it — an `object` source over an object the caller's exposure decision refuses (disabled package, `apiEnabled` / `apiMethods` for `search`, a `sys_*` object without `enable.aiReadable: true`), or serving a field the caller may not query, is searched | `applyPermissionFilter`, `admitSources` |
192+
| 46 | Knowledge search returns hits unfiltered, and searches every source | service-knowledge | Lose: the permission filter over search results, and the source admission ahead of it — an `object` source over an object the caller's exposure decision refuses (disabled package, `apiEnabled` / `apiMethods` for `search`, a `sys_*` object without `enable.aiReadable: true`), or serving a field the caller may not query, is searched | `applyPermissionFilter`, `admitSources`, `search` |
193193
| 47 | The inbound-mail read gates return early (the read AST) | service-mailbox | Get: every `sys_mail_message` and `sys_mail_association` row on `find` / `findOne` — the ingest writer and each gate's own pre-scan, which read the association and mailbox rows a decision needs. Lose: the narrowing of a message to callers who can read a record it is associated with or who own its mailbox (so the unassociated pool is restricted), and of an association to callers who can read the record it names (on `count` and `aggregate` too, so a total agrees with the rows) | `gateMiddleware` |
194194
| 47b | The inbound-mail ingest seam: `ingest` admits the system context ALONE, and `rematch` admits it without the organization, owner or `manage_mailboxes` check | service-mailbox | Get: a mail source hands a mailbox its messages, and server code re-matches any mailbox. Lose: nothing a user held — every other caller of `ingest` is refused (`PERMISSION_DENIED`), because an ingested message is shown on every record its correspondents' addresses match and a user who could hand the seam a message could write one in a correspondent's name; every other caller of `rematch` must be in the mailbox's organization and own the mailbox or hold `manage_mailboxes` | `ingest`, `authorizeRematch` |
195195
| 47c | The inbound-mail IMAP sync: `syncMailbox` and `syncAll` admit the system context ALONE | service-mailbox | Get: the sync job reads every mailbox row (its organization, address and IMAP cursor), writes the cursor back, and hands each fetched message to `ingest` under the system context. Lose: nothing a user held — every other caller is refused (`PERMISSION_DENIED`), because a sync stores a mailbox's mail and moves its cursor | `syncMailbox`, `syncAll` |
@@ -703,6 +703,7 @@ and CI refuses one that differs from what the tree produces.
703703
| `packages/services/service-automation/src/runtime-identity.ts#stampSystemInsertOwner` | 1 | 60 |
704704
| `packages/services/service-knowledge/src/knowledge-service.ts#admitSources` | 1 | 46 |
705705
| `packages/services/service-knowledge/src/knowledge-service.ts#applyPermissionFilter` | 1 | 46 |
706+
| `packages/services/service-knowledge/src/knowledge-service.ts#search` | 1 | 46 |
706707
| `packages/services/service-mailbox/src/ingest/mail-ingest-service.ts#authorizeRematch` | 1 | 47b |
707708
| `packages/services/service-mailbox/src/ingest/mail-ingest-service.ts#ingest` | 1 | 47b |
708709
| `packages/services/service-mailbox/src/mail-read-visibility.ts#gateMiddleware` | 1 | 47 |

‎content/docs/protocol/knowledge.mdx‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,30 @@ caller's `ExecutionContext` and drops hits the user is not allowed to
183183
read. **A hit that the user could not have queried directly is never
184184
returned.**
185185

186+
The re-check runs after ranking, so the service asks for more than it
187+
answers. For a caller who is not the system identity, each `object`
188+
source is asked for `topK × 5` hits. When the hits that survive the
189+
re-check name fewer than `topK` records (several passages of one record
190+
count once), every `object` source that answered as many hits as it was
191+
asked is asked once more, for `topK × 20`. That is the cap: a caller who may
192+
read fewer than `topK` of the rows within the cap gets fewer than `topK`
193+
hits. An
194+
adapter that answers fewer than it was asked (one that caps `topK`) is not
195+
asked again. A `file` or `http` source is asked for `topK` once, and so is
196+
every source for the system identity. The answer is at most `topK` hits.
197+
How many hits the re-check removed is logged at `debug`, never returned to
198+
the caller.
199+
200+
A hit's `title` is the value of the object's display field (ADR-0079
201+
`resolveDisplayField`: `nameField`, else the derived title field), set
202+
when the document is built. It is empty when that field is a
203+
credential-class or `internal` field, when the value is empty, and when
204+
the object resolves no display field. A source over an object with no
205+
registered definition reads a field named `title`. Documents indexed
206+
before this rule carry the value of a field named `title` until a complete
207+
reindex writes them again, so the source admission below still asks about a
208+
declared `title` field as well as the display field.
209+
186210
### 3.3 `IKnowledgeService` (consumed by the ObjectOS AI runtime, REST, Console)
187211

188212
```ts
@@ -379,8 +403,8 @@ hashes as before, and the reindex skips it as before.
379403
### Source admission: exposure and field-level rules
380404

381405
A passage is built at index time, under a system context, from every
382-
`contentFields` member of its source, the record `title` and the source's
383-
`metadataFields`. A row re-check alone would therefore serve a caller the text
406+
`contentFields` member of its source, the object's display field (the
407+
title) and the source's `metadataFields`. A row re-check alone would therefore serve a caller the text
384408
of a field a field-level rule hides from them. So before an `object` source is
385409
searched for a non-system caller, the service asks, once per object per search:
386410

@@ -394,7 +418,8 @@ searched for a non-system caller, the service asks, once per object per search:
394418
`enable.aiReadable: true` (the AI read tools' posture).
395419
- **Field-level rules** — every field the source serves (each `contentFields`
396420
member, `'*'` meaning every field the object declares except `id`; each `metadataFields`
397-
member; `title`), less the credential-class and `internal: true` fields an
421+
member; the display field the title is read from, and a declared `title`
422+
field), less the credential-class and `internal: true` fields an
398423
index never carries, must be one the caller may **query**, per the `security`
399424
service's `getQueryableFields`. Without that answer: its `getReadableFields`
400425
less every field declaring a `maskingRule`; with no `security` service at
@@ -444,7 +469,8 @@ when the source has no `where`).
444469
the event's `after`, so a write result that omits a field (a projected
445470
result, a formula the write did not return) cannot leave the document
446471
short. The same field rules as a reindex apply: the fields the source lists
447-
and the record `title`, never a credential-class or `internal` field.
472+
and the object's display field as the title, never a credential-class or
473+
`internal` field.
448474
- **No row comes back** — the row does not match (a draft, or a row that
449475
stopped matching), and its document is deleted. Deleting an absent document
450476
changes nothing.

0 commit comments

Comments
 (0)