Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions .changeset/37308-knowledge-search-scope.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
'@objectstack/spec': patch
'@objectstack/service-knowledge': patch
'@objectstack/knowledge-memory': patch
'@objectstack/knowledge-pgvector': patch
---

feat(service-knowledge): a knowledge search can be held to chosen records, or to the records under one parent, and the adapter filters before it ranks

Clause-②: yes
Metadata-protocol: none

A knowledge search can now look only inside chosen records, for example only inside one policy, and every one of the `topK` hits comes from inside that scope. A scope only narrows what is searched; each hit is still re-read as the caller, as before.

New, both optional, in `@objectstack/spec` (types only, no metadata key):

- `KnowledgeSearchOptions.scope?: Array<{ object: string; ids: string[] }>`. An entry naming the object a source indexes holds that source to those records. An entry naming another object reaches a source that lists, in its `metadataFields`, a `lookup` or `master_detail` field pointing at that object, and holds it to the documents whose stored value of that field is one of the ids. Entries are a union. A source no entry reaches is not searched, and a `file` / `http` source answers nothing under a scope. `scope: []`, or an entry with no ids, answers no hits; it never means "no scope". At most 10 entries, each with at most 500 ids, every `object` and id a non-empty string, no other key on an entry; past those bounds `search` refuses before any adapter is called, with an error carrying `code: 'VALIDATION_ERROR'` and `status: 400` and naming the bound.
- `AdapterSearchOptions.scope?: AdapterScopeTerm[]`, and the exported type `AdapterScopeTerm` (`{ kind: 'record', ids }` or `{ kind: 'metadata', field, ids }`). The knowledge service builds it per source from `KnowledgeSearchOptions.scope`; an adapter that reads it ranks only the documents some term holds for, filtering before it ranks, comparing values as strings (a list value matches when any element does).

`KnowledgeService` checks every hit after the adapter answers and drops a hit no term holds for, including a hit that does not carry the value, so an adapter returns the document's `metadata` on its hits. An adapter that ignores the member keeps working: its scoped searches may answer fewer than `topK`, and the service logs that once per adapter at `warn`. A source that lists two or more lookups to the scoped object is not reached by that entry, logged once at `warn` naming the fields. A `user` field is not a parent link, and a parent two hops away is not reached. How many hits the scope removed is logged, never returned.

`@objectstack/knowledge-memory` applies `scope` before ranking, and `@objectstack/knowledge-pgvector` applies it in the same SQL `WHERE` as the organization filter, ids and field names as bound parameters. `runKnowledgeAdapterContract` (from `@objectstack/service-knowledge/testing`) now requires `implements.scope`. It adds scope cases for the adapter alone, for each term kind, and cases through a real `KnowledgeService`, including one over the adapter with the member stripped.

What to do: an adapter package reads `scope` in its search, returns each document's `metadata` on its hits, and passes `implements.scope` to the contract suite. A source that should be searchable inside one parent record lists the lookup to that parent in `metadataFields`; documents indexed before the lookup was listed are in no parent scope until a complete reindex writes them again.
15 changes: 15 additions & 0 deletions content/docs/ai/knowledge-rag.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,21 @@ Protocol, adapters, embedder, and `KnowledgeService.search` — is open, so you
installed ([Connect an MCP Client](/docs/ai/connect-mcp)).
</Callout>

## Searching inside chosen records

Pass `scope` to search only inside some records: the records an object source indexes, or a parent record that source reaches through a lookup it lists in `metadataFields`.

```ts
// Only the clauses of one policy: the clause source lists its `policy` lookup in metadataFields.
const hits = await knowledge.search('notice period', {
topK: 5,
scope: [{ object: 'policy', ids: [policyId] }],
executionContext,
});
```

An adapter that reads the scope filters before it ranks, so the `topK` hits all come from inside the scope. Whatever the adapter does, the service drops any hit outside the scope, so an adapter that ignores it may answer fewer than `topK`. A source the scope does not reach is not searched, and `scope: []` answers nothing, never everything. A scope narrows what is searched; each hit is still re-checked against the caller, so it never shows a record the caller could not read. Bounds, the parent-link rules and what an adapter must do are in [the protocol's record scope](/docs/protocol/knowledge#record-scope).

## What you get for free

- **Permission-aware retrieval.** Every hit with a `sourceRecordId` is re-checked against the caller's `ExecutionContext` via `IDataEngine` — the same RLS that gates plain ObjectQL queries. A salesperson asking "find proposals about ACME" only sees the proposals they could already read directly. Before a source is searched, the caller's field-level read rules and the object's API exposure are asked too: a source serving a field the caller may not query is not searched for them (see [the protocol's source admission](/docs/protocol/knowledge#source-admission-exposure-and-field-level-rules)). File / HTTP hits pass through (ACL is the adapter's problem).
Expand Down
69 changes: 65 additions & 4 deletions content/docs/protocol/knowledge.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,9 @@ K8): an adapter that lacks one keeps working, and the service does what it
did before that member existed. `AdapterSearchOptions.organizationIds` is the
caller's organizations; an adapter that reads it ranks only those
organizations' documents, filtering before it ranks — see
[Organization scope](#organization-scope). `listDocuments` lists the documents the
[Organization scope](#organization-scope). `AdapterSearchOptions.scope` holds a
search to chosen records the same way — see [Record scope](#record-scope).
`listDocuments` lists the documents the
adapter holds for a source, a page of at most `limit` entries at a time, each
with the `docHash` it was stored with; `nextCursor` is absent once the
listing is complete. A document written while a listing runs may be missing
Expand All @@ -354,6 +356,7 @@ runKnowledgeAdapterContract({
implements: {
listDocuments: true, chunks: true, organizationIds: true,
indexStatus: true, builds: true, refusesOtherFingerprint: true, generations: true,
scope: true,
},
});
```
Expand Down Expand Up @@ -543,8 +546,9 @@ an exact scan.
no SQL. A caller reads one sentence; the driver's text and the SQL go only
to the operator — the health check, the boot warning and the log.
- **Search.** An exact scan by cosine distance, so any width works —
including a 3072-wide model. The organization filter and the metadata
`filter` (equality per key) run in the same `WHERE`, before ranking.
including a 3072-wide model. The organization filter, the
[record scope](#record-scope) and the metadata `filter` (equality per key)
run in the same `WHERE`, before ranking.
`queryPrefix` is put before every query before it is embedded, for a model
that embeds questions and passages differently.
- **Re-embedding.** A passage whose text is unchanged (its `chunk_hash`) is
Expand Down Expand Up @@ -635,6 +639,63 @@ them again. The organization is part of `docHash`, so the reindex does not
skip them. Under `single` nothing changes: a document without an organization
hashes as before, and the reindex skips it as before.

### Record scope

A search can be held to chosen records (ADR-0161 K8, item 17): "only inside
this policy". `KnowledgeSearchOptions.scope` is a list of `{ object, ids }`
entries.

```ts
const hits = await knowledge.search('notice period', {
topK: 5,
scope: [{ object: 'policy', ids: [policyId] }],
executionContext: ctx,
});
```

- **The object a source indexes.** An entry naming it holds that source to
those records.
- **A parent object.** An entry naming another object reaches a source that
lists, in its `metadataFields`, a `lookup` or `master_detail` field pointing
at that object. The source is then held to the documents whose stored value
of that field is one of the ids (any one of them, for a lookup declared
`multiple`). A `user` field is not a parent link. A source that lists no such
field is not reached by the entry, and neither is one that lists two or more
of them (logged once at `warn`, naming the fields). A parent two hops away
(policy → chapter → clause) is not reached.
- **Several entries** are a union. A source no entry reaches is not searched,
and a `file` / `http` source answers nothing under a scope.
- **Empty.** `scope: []`, or an entry whose `ids` is empty, answers no hits; it
never means "no scope". Without `scope`, nothing changes.
- **Bounds.** At most 10 entries, each with at most 500 ids; `object` and every
id a non-empty string, and no other key on an entry. Past them the call is
refused before any adapter is asked, with `code: 'VALIDATION_ERROR'`,
`status: 400` and a message naming the bound.

The service turns the entries into terms for each source and hands them to the
adapter as `AdapterSearchOptions.scope`: `{ kind: 'record', ids }`, judged on
the document's `sourceRecordId`, or `{ kind: 'metadata', field, ids }`, judged
on its stored `metadata[field]`, values compared as strings. An adapter that
reads the member filters before it ranks, so `topK` is filled from in-scope
documents; `organizationIds`, `scope` and the opaque `filter` all apply.
Whatever the adapter does, the service checks every hit after it answers and
drops a hit no term holds for, a hit without the value included, so an adapter
returns the document's `metadata` on its hits. An adapter written before the
member keeps working: out-of-scope documents then take ranking places, its
scoped searches may answer fewer than `topK`, and the service logs that once
for the adapter. The contract suite pins both halves: each term kind on the
adapter alone, and the service's check over the adapter with the member
stripped.

The scope is judged on the index copy and only narrows. Every hit is still
re-read as the caller, so a caller who cannot read a scoped record gets
nothing from it. Source admission already requires each `metadataFields`
member to be queryable by the caller, and the parent record is never read. A
document indexed before its source listed the lookup is in no parent scope
until a complete reindex writes it again. How many hits the scope removed is
logged, never returned, and an entry that reaches no source answers the same
empty result a source withheld from the caller gives.

### Source admission: exposure and field-level rules

A passage is built at index time, under a system context, from every
Expand Down Expand Up @@ -866,7 +927,7 @@ up.
| Audit + metrics | ⏳ Phase 2 | |
| `knowledge-llamaindex` | ⏳ Phase 2 | |
| `knowledge-dify` | ⏳ Phase 3 / community | |
| `knowledge-pgvector` | ✅ | PostgreSQL + pgvector; exact scan, organization and metadata filter in SQL, index fingerprint (§4.1) |
| `knowledge-pgvector` | ✅ | PostgreSQL + pgvector; exact scan, organization, record scope and metadata filter in SQL, index fingerprint (§4.1) |

### 7.1 Non-goals for Phase 1

Expand Down
10 changes: 10 additions & 0 deletions packages/core/src/security/second-object-read-exposure.pin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,16 @@ const CALLERS: Record<string, Classification> = {
"each target the decision before the engine reads it: the data door's `refuseUnservedRelationTarget`, the MCP " +
"stdio data bridge's `enforceRelationTargetExposure` and the runtime `callData`'s `refuseUnservedRelationTargets`",
},
// [#37308] A knowledge search's record scope (ADR-0161 K8, item 17).
'packages/services/service-knowledge/src/knowledge-search-scope.ts': {
kind: 'not-a-served-read',
reason:
"names the object a knowledge source's listed lookup points at, only to turn a search scope entry that names " +
"that parent into a filter on the source's own stored lookup value; it reads no record of the parent and serves " +
"nothing of it. The hits are the source's own documents, each re-read as the caller (`applyPermissionFilter`). " +
'Pinned by `packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts` (a parent-scoped ' +
'search makes no engine call naming the parent object) and `knowledge-search-scope.test.ts`',
},
'packages/qa/scenarios/src/score/scenario-graph.ts': {
kind: 'not-a-served-read',
reason:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@ runKnowledgeAdapterContract({
builds: true,
refusesOtherFingerprint: true,
generations: true,
scope: true,
},
});
34 changes: 32 additions & 2 deletions packages/plugins/knowledge-memory/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type {
AdapterIndexStatus,
AdapterListDocumentsOptions,
AdapterListDocumentsPage,
AdapterScopeTerm,
AdapterSearchOptions,
} from '@objectstack/spec/contracts';
import type {
Expand Down Expand Up @@ -35,6 +36,15 @@ import { KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts';
* document-id order, the cursor being the last id of the page before. It runs
* the contract suite of `@objectstack/service-knowledge/testing`.
*
* The first reader of the record scope (ADR-0161 K8, item 17): when a search
* is handed `scope`, it ranks only the passages of documents some term holds
* for — a `record` term on the document's `sourceRecordId`, a `metadata` term
* on its stored `metadata[field]` (a list when any element is in `ids`),
* compared as strings — after the organization filter and before the scoring,
* so `topK` is filled from them alone. An empty list ranks nothing. Each hit
* carries its document's `metadata`, which the service's check after the
* answer reads.
*
* The first reader of the organization filter (ADR-0161 K8, item 9): it
* stores each document's `organizationId` as given and, when a search is
* handed `organizationIds`, ranks only the documents whose organization is in
Expand Down Expand Up @@ -205,10 +215,13 @@ export class KnowledgeMemoryAdapter implements IKnowledgeAdapter {
const inScope = organizations === undefined
? chunks
: chunks.filter((c) => c.organizationId !== undefined && organizations.has(c.organizationId));
// The record scope next (ADR-0161 K8, item 17): absent → every document;
// present → only the documents some term holds for; `[]` → nothing.
const scoped = opts.scope === undefined ? inScope : inScope.filter(inRecordScope(opts.scope));
const filter = opts.filter ?? {};
const filtered = Object.keys(filter).length
? inScope.filter((c) => matchesFilter(c.metadata, filter))
: inScope;
? scoped.filter((c) => matchesFilter(c.metadata, filter))
: scoped;

const scored = filtered.map((c) => ({
chunk: c,
Expand Down Expand Up @@ -356,6 +369,23 @@ function cosineSimilarity(
return dot / (aNorm * bNorm);
}

/**
* Whether a passage's document is in the record scope: some term holds, a
* `record` term on `sourceRecordId`, a `metadata` term on `metadata[field]`.
* A stored string or number matches when `String(value)` is one of the ids, a
* list when any element does; anything else, or no value, never.
*/
function inRecordScope(terms: readonly AdapterScopeTerm[]): (chunk: ChunkRecord) => boolean {
const compiled = terms.map((term) => ({ term, ids: new Set(term.ids) }));
const holds = (value: unknown, ids: ReadonlySet<string>): boolean =>
(typeof value === 'string' || typeof value === 'number') && ids.has(String(value));
return (chunk) =>
compiled.some(({ term, ids }) => {
const value = term.kind === 'record' ? chunk.sourceRecordId : chunk.metadata[term.field];
return Array.isArray(value) ? value.some((element) => holds(element, ids)) : holds(value, ids);
});
}

function matchesFilter(
metadata: Record<string, unknown>,
filter: Record<string, unknown>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector on a LIVE PostgreSQL', () => {
builds: true,
refusesOtherFingerprint: true,
generations: false,
scope: true,
},
});
});
27 changes: 27 additions & 0 deletions packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,8 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
async search(query: string, opts: AdapterSearchOptions): Promise<KnowledgeHit[]> {
// An empty organization set ranks nothing (ADR-0161 K8, item 9).
if (opts.organizationIds !== undefined && opts.organizationIds.length === 0) return [];
// A record scope with no term that has ids ranks nothing (ADR-0161 K8, item 17).
if (opts.scope !== undefined && !opts.scope.some((term) => term.ids.length > 0)) return [];
const pool = this.requirePool();
const readiness = await this.ready();
// The embedder first: without one the service's fingerprint carries no
Expand Down Expand Up @@ -414,6 +416,31 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
params.push(opts.organizationIds);
where.push(`organization_id = ANY($${params.length}::text[])`);
}
if (opts.scope !== undefined) {
// The record scope (ADR-0161 K8, item 17), a union of terms, beside the
// organization filter so `topK` is filled from in-scope documents. Ids
// and field names go as bound parameters. A `metadata` term holds for a
// stored string or number equal to an id as text, or a list with such an
// element; a missing value or any other kind holds for nothing.
const terms: string[] = [];
for (const term of opts.scope) {
if (term.ids.length === 0) continue;
params.push(term.ids);
const ids = `$${params.length}::text[]`;
if (term.kind === 'record') {
terms.push(`source_record_id = ANY(${ids})`);
continue;
}
params.push(term.field);
const value = `(metadata -> $${params.length}::text)`;
terms.push(
`EXISTS (SELECT 1 FROM jsonb_array_elements(CASE jsonb_typeof(${value}) WHEN 'array' THEN ${value} ` +
`ELSE jsonb_build_array(${value}) END) AS e(v) ` +
`WHERE jsonb_typeof(e.v) IN ('string', 'number') AND e.v #>> '{}' = ANY(${ids}))`,
);
}
where.push(`(${terms.join(' OR ')})`);
}
for (const [key, value] of Object.entries(opts.filter ?? {})) {
params.push(key, JSON.stringify(value === undefined ? null : value));
where.push(`(metadata -> $${params.length - 1}) = $${params.length}::jsonb`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@
* handed exactly as given, one hit per passage.
*
* Neither implements `listDocuments`, so the suite also runs its
* "without listDocuments" cases against them.
* "without listDocuments" cases against them. Neither applies
* `AdapterSearchOptions.scope` (ADR-0161 K8, item 17), and their hits carry no
* `metadata`: an adapter written before the member, over which the service's
* check after the answer still answers no out-of-scope hit.
*/

import type { AdapterContext, AdapterSearchOptions, IKnowledgeAdapter } from '@objectstack/spec/contracts';
Expand Down Expand Up @@ -106,6 +109,7 @@ runKnowledgeAdapterContract({
builds: false,
refusesOtherFingerprint: false,
generations: false,
scope: false,
},
});

Expand All @@ -120,5 +124,6 @@ runKnowledgeAdapterContract({
builds: false,
refusesOtherFingerprint: false,
generations: false,
scope: false,
},
});
Loading
Loading