Skip to content

Commit 760716b

Browse files
committed
feat(knowledge-pgvector): apply the record scope in the search SQL
knowledge-pgvector landed first (#37337), so it implements the scope as every in-tree adapter that runs the suite does (#37308 item 4). The terms are a union in the same inner WHERE as the organization filter, before ranking: a record term on source_record_id, a metadata term on the stored jsonb value of its field (a string or number equal to an id as text, or a list with such an element; anything else holds for nothing). Ids and field names go as bound parameters. A scope with no term that has ids ranks nothing. The live contract run declares implements.scope, so the suite's record-term, metadata-term and service-level parent cases run against PostgreSQL. Claude-Session: https://claude.ai/code/session_01JQwxbZmjM1KubX3ZAoJPPm Co-authored-by: Claude <noreply@anthropic.com>
1 parent 4552e7c commit 760716b

4 files changed

Lines changed: 34 additions & 4 deletions

File tree

‎.changeset/37308-knowledge-search-scope.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
'@objectstack/spec': patch
33
'@objectstack/service-knowledge': patch
44
'@objectstack/knowledge-memory': patch
5+
'@objectstack/knowledge-pgvector': patch
56
---
67

78
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
@@ -18,6 +19,6 @@ New, both optional, in `@objectstack/spec` (types only, no metadata key):
1819

1920
`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.
2021

21-
`@objectstack/knowledge-memory` applies `scope` before ranking. `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.
22+
`@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.
2223

2324
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.

‎content/docs/protocol/knowledge.mdx‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -546,8 +546,9 @@ an exact scan.
546546
no SQL. A caller reads one sentence; the driver's text and the SQL go only
547547
to the operator — the health check, the boot warning and the log.
548548
- **Search.** An exact scan by cosine distance, so any width works —
549-
including a 3072-wide model. The organization filter and the metadata
550-
`filter` (equality per key) run in the same `WHERE`, before ranking.
549+
including a 3072-wide model. The organization filter, the
550+
[record scope](#record-scope) and the metadata `filter` (equality per key)
551+
run in the same `WHERE`, before ranking.
551552
`queryPrefix` is put before every query before it is embedded, for a model
552553
that embeds questions and passages differently.
553554
- **Re-embedding.** A passage whose text is unchanged (its `chunk_hash`) is
@@ -926,7 +927,7 @@ up.
926927
| Audit + metrics | ⏳ Phase 2 | |
927928
| `knowledge-llamaindex` | ⏳ Phase 2 | |
928929
| `knowledge-dify` | ⏳ Phase 3 / community | |
929-
| `knowledge-pgvector` | ✅ | PostgreSQL + pgvector; exact scan, organization and metadata filter in SQL, index fingerprint (§4.1) |
930+
| `knowledge-pgvector` | ✅ | PostgreSQL + pgvector; exact scan, organization, record scope and metadata filter in SQL, index fingerprint (§4.1) |
930931

931932
### 7.1 Non-goals for Phase 1
932933

‎packages/plugins/knowledge-pgvector/src/__tests__/contract.live-postgres.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ describe.skipIf(!PG_URL)('knowledge-pgvector on a LIVE PostgreSQL', () => {
2727
builds: true,
2828
refusesOtherFingerprint: true,
2929
generations: false,
30+
scope: true,
3031
},
3132
});
3233
});

‎packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,8 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
380380
async search(query: string, opts: AdapterSearchOptions): Promise<KnowledgeHit[]> {
381381
// An empty organization set ranks nothing (ADR-0161 K8, item 9).
382382
if (opts.organizationIds !== undefined && opts.organizationIds.length === 0) return [];
383+
// A record scope with no term that has ids ranks nothing (ADR-0161 K8, item 17).
384+
if (opts.scope !== undefined && !opts.scope.some((term) => term.ids.length > 0)) return [];
383385
const pool = this.requirePool();
384386
const readiness = await this.ready();
385387
// The embedder first: without one the service's fingerprint carries no
@@ -414,6 +416,31 @@ export class PgvectorKnowledgeAdapter implements IKnowledgeAdapter {
414416
params.push(opts.organizationIds);
415417
where.push(`organization_id = ANY($${params.length}::text[])`);
416418
}
419+
if (opts.scope !== undefined) {
420+
// The record scope (ADR-0161 K8, item 17), a union of terms, beside the
421+
// organization filter so `topK` is filled from in-scope documents. Ids
422+
// and field names go as bound parameters. A `metadata` term holds for a
423+
// stored string or number equal to an id as text, or a list with such an
424+
// element; a missing value or any other kind holds for nothing.
425+
const terms: string[] = [];
426+
for (const term of opts.scope) {
427+
if (term.ids.length === 0) continue;
428+
params.push(term.ids);
429+
const ids = `$${params.length}::text[]`;
430+
if (term.kind === 'record') {
431+
terms.push(`source_record_id = ANY(${ids})`);
432+
continue;
433+
}
434+
params.push(term.field);
435+
const value = `(metadata -> $${params.length}::text)`;
436+
terms.push(
437+
`EXISTS (SELECT 1 FROM jsonb_array_elements(CASE jsonb_typeof(${value}) WHEN 'array' THEN ${value} ` +
438+
`ELSE jsonb_build_array(${value}) END) AS e(v) ` +
439+
`WHERE jsonb_typeof(e.v) IN ('string', 'number') AND e.v #>> '{}' = ANY(${ids}))`,
440+
);
441+
}
442+
where.push(`(${terms.join(' OR ')})`);
443+
}
417444
for (const [key, value] of Object.entries(opts.filter ?? {})) {
418445
params.push(key, JSON.stringify(value === undefined ? null : value));
419446
where.push(`(metadata -> $${params.length - 1}) = $${params.length}::jsonb`);

0 commit comments

Comments
 (0)