Skip to content

Commit 9981f27

Browse files
feat(knowledge): knowledge-pgvector, an open vector store on PostgreSQL, and the index fingerprint (#37100) (#37337)
Fixes #37100 Clause-②: yes Metadata-protocol: none ## 维护者速读 - 自建部署的知识库可以直接用自己的 PostgreSQL(装 pgvector 扩展)存向量做检索,不再需要另外的向量服务;换了嵌入模型或切分方式后,旧索引会被明确拒绝并提示重建,而不是悄悄返回混杂的结果。 - 属于「知识检索」专题,补上开源向量库这一块,并为后续的新代际重建和其他存储打好统一的指纹规则。 - 数据库没装扩展或没权限时,系统照常启动,知识源返回「暂不可用」;要执行的 SQL 和数据库报错只给运维看(健康检查、启动日志),不会出现在用户的检索回答里。新包默认不启用,撤回只需不注册该插件。 - 本 PR 改了 CI 工作流文件,需要你批准。新加的两步 CI 只在完整跑批和合并队列里运行(队列里不卡合并),席位无权在分支上手动触发;本地已用 CI 同一镜像(pgvector 0.8.7)跑通。如需在 CI 里看到绿灯,可在分支上手动触发一次 ci.yml。 ## What changes **New package `@objectstack/knowledge-pgvector`** (Apache-2.0) — `KnowledgePgvectorPlugin` registers `PgvectorKnowledgeAdapter` (id `pgvector`). - Storage in its own schema `os_knowledge` (option `schema`): `knowledge_generation` (source_id, generation, fingerprint, recipe_hash, dim, model, state, created_at) and one passage table per width, `knowledge_vec_dWIDTH` (source_id, generation, chunk_id, document_id, source_record_id, organization_id, content, title, heading_path, doc_hash, chunk_hash, metadata jsonb, embedding vector(WIDTH)). Object tables live in the connection's `current_schema()`, and the driver's introspection / `os migrate plan` read only that schema, so these tables can neither collide with an object table nor be reported as drift. - Database: the `url` option, else `OS_DATABASE_URL` / legacy `DATABASE_URL` when it is `postgres://`; its own `pg.Pool` (`poolMax`, default 4; `connectTimeoutMs`, default 5000, so an unreachable host does not hold boot). Every embed runs before a connection is checked out for the write. The kernel's embedder is read at each call, never cached. Two deployments sharing one database set their own `schema` (README). With per-organization databases the store is still the one database the plugin connects to; isolation is the `organization_id` column, filtered in SQL. - Not ready (no `vector` extension and no right to create it, or no right to create the schema): nothing is created past the failing step, the plugin still registers, boot continues, `healthCheck` answers `ok: false` and the boot warning carries the SQL, every call answers `503 SERVICE_UNAVAILABLE`; the next call retries (no restart). An unreachable database is diagnosed as unreachable, with no SQL. - What a caller reads: every refusal's `message` is one sentence (no driver text, SQL or schema name). Operator text travels in the error's `remedy`, shown by `healthCheck`, the boot warning, a reindex result and the service's `warn` log — never in `refused[].message` or a thrown search refusal. The contract TSDoc of `beginBuild` states this convention. - Search: the embedder is resolved before the fingerprint is compared (no embedder ⇒ 503, never a 409 on a healthy index); exact cosine scan via the extension's own schema-qualified cosine-distance operator and `vector` type (no HNSW, so 3072 dims work); organization filter and metadata-equality `filter` in the same `WHERE`, before `ORDER BY distance LIMIT topK`; a passage with cosine similarity not above 0 is not a hit. Hits carry the stored `docHash` (K8 item 3, read by #37103's record-level freshness check) and the passage's `headingPath` (item 14). `queryPrefix` option is prepended to queries only. - Writes: takes the service's chunks (`capabilities.chunks`); `chunk_hash` per passage; an unchanged passage is not re-embedded (row metadata rewritten, the UPDATE checked for its row: one removed by a concurrent write makes the batch plan again, so the passage is embedded, not lost); stale chunks of a document deleted in the same transaction. - `listDocuments` on the write-target generation, byte order (`COLLATE "C"`) for both the order and the cursor. - Fingerprint: a write or search under another fingerprint, or with an embedder of another width, is refused `409 KNOWLEDGE_REBUILD_REQUIRED`; `beginBuild` under the stored fingerprint is a no-op, under another it is refused and its `remedy` (the convention is stated once on `IKnowledgeAdapter`) (carried into the reindex result) is the exact statements that clear the source: one `DELETE` per existing passage table, then the generation row (second-generation builds are #37101). A first generation never adopts leftovers: opening it deletes the source's passage rows left without a generation row, in the same transaction, only by the call whose insert opened it; `completeBuild` records the recipe hash; `indexStatus` reads both back. - README: options, database/schema, setup SQL, HNSW as an operator step with the 2,000-dimension limit, rebuilds, and that stored text is as sensitive as the record and is in backups. **K8 item 8 (ADR-0161 K7), whole, as the Execution note asks** - `@objectstack/service-knowledge`: `computeIndexFingerprint` (model, variant, dimensions from the adapter's `embedding` descriptor; resolved split + `SPLIT_ALGORITHM_VERSION`; content recipe + `ASSEMBLY_RULE_VERSION`) and `computeRecipeHash` (`where`, `metadataFields`, title field + `TITLE_RULE_VERSION`, withheld fields), SHA-256 over sorted-key JSON, pinned by `index-fingerprint.test.ts`. Every adapter call carries them (`AdapterContext.index`, `AdapterSearchOptions.index`). `indexExpectation` is exported. A complete reindex calls `beginBuild` before listing or writing (refusal ⇒ `ok: false`, nothing written, the adapter's `remedy` in the message) and `completeBuild` after the purge (a throw ⇒ `ok: false`); a capped or dry-run walk calls neither. The repair of a stale record (#37103's `repairStale`) goes through the event-sync path, whose upsert/delete carry `index`. The chunk-target setting is read once per search. - `@objectstack/spec/contracts`: `AdapterEmbeddingDescriptor.model/dimensions/variant`, `AdapterIndexExpectation`, `AdapterIndexStatus`, `IKnowledgeAdapter.indexStatus?/beginBuild?/completeBuild?`, `IEmbedder.model?`. All optional. - Coded refusal through search (card comment, K7 rule 5): `KnowledgeService.search` keeps its signature (K9 rule 3); a source refused with a coded error (SCREAMING code + 4xx/5xx status) is dropped from the answer and logged by name; when no source answers, the refusal is thrown with its code/status and `refused` naming each source. A source that answers the first round and refuses the refill is refused for the whole search (its first-round hits dropped), so no source is both answered and named as refused. `KnowledgeService.searchWithRefusals` returns `{ hits, refused }`; `search_knowledge` adds `refused` (sources the caller can see only) when non-empty. - `knowledge-memory` is the reference: active + under-construction generations, switch at `completeBuild`, all flags true in its contract run. - `embedder-openai`: `model` is public and reported. - Contract suite: `implements` gains `indexStatus`, `builds`, `refusesOtherFingerprint`, `generations` with 9 cases (carry, fingerprint vs recipe-hash variation, build pair, status, search refusal, write refusal, through-service named/whole refusal, generation switch, rebuild after recipe change). - `KNOWLEDGE_REBUILD_REQUIRED` registered in the error-code ledger under service-knowledge (the suite asserts it), knowledge-memory and knowledge-pgvector; generated references regenerated. **CI (Tier H — `.github/workflows/ci.yml`)**: `Temporal Conformance` never runs on `pull_request`; it runs on the full battery and, for an entry whose diff hits the `temporal_live` paths (this one does), in the merge queue, where it is advisory, not a required check. No existing step of `Temporal Conformance (live PG + MySQL)` runs this package, so two steps are added after the runtime leg (build `@objectstack/knowledge-pgvector...`, then `vitest run live-postgres` with `OS_TEST_POSTGRES_URL` and `OS_EXPECT_LIVE_DIALECT_MATRIX=1`, so a missing server is red, never a skip); `service-knowledge/src/testing.ts` joins the `temporal_live` merge-queue paths; the build-step count comment says five. The job's image is already pgvector's (#37095). ## Why Card #37100 (ADR-0161 Execution row 8a): the open, self-hosted vector store, and the fingerprint that keeps two models' vectors from ever being ranked against each other. ## Open question `searchWithRefusals` is a class method of `KnowledgeService`, not a member of `IKnowledgeService` (K9 rule 3 keeps `search`'s signature and return type). `search_knowledge` reads it structurally. Options: (A) keep it on the class (this PR); (B) add an optional `IKnowledgeService.searchWithRefusals?` member in a follow-up with its own K9 dated note. Recommendation A until a second consumer needs it. ## Deviations from the card - `title` and `heading_path` columns beyond the card's list: hits return the document title and, since #37103 landed, the passage's `headingPath`. - The generation table also holds `recipe_hash` (K8 item 8 c). - Store keying by package is #37304's (ruling 7168239918, Q1 = B); nothing built for it here. ## Tests At head `065c98ff` (main merged at `83fef223`, after #37335 landed as `38017753`): - `@objectstack/knowledge-pgvector`, live, against the CI job's own image (`mirror.gcr.io/pgvector/pgvector:0.8.7-pg16@sha256:484e8380…`, run locally in Docker), the CI step's exact command (`pnpm --filter @objectstack/knowledge-pgvector exec vitest run live-postgres`, `OS_EXPECT_LIVE_DIALECT_MATRIX=1`): `Test Files 3 passed (3)`, `Tests 47 passed (47)` (contract suite 34, acceptance 11, real-driver reindex 2). The whole package against PostgreSQL 16 + pgvector 0.6: `Test Files 4 passed (4)`, `Tests 57 passed (57)` (the above plus 10 unit cases; one of them now also pins `listDocuments` answering 503 with no embedder). - `@objectstack/service-knowledge`: `Test Files 12 passed (12)`, `Tests 315 passed (315)` (one case pins that a refusal's `remedy` reaches the `warn` log and never `refused[].message` or the thrown message). `@objectstack/knowledge-memory`: `46 passed`. `@objectstack/embedder-openai`: `31 passed`. `typecheck` (source and tests) green for all four; eslint clean. <details><summary>Ablations of the review fixes (one-shot, each restored; each fails exactly one case)</summary> - fingerprint compared before the embedder is resolved: the not-ready "no embedder ⇒ 503" case fails. - leftover passage rows not deleted when a first generation opens: the acceptance "never adopts passages left behind" case fails (the passage is not re-embedded). - the unchanged-passage UPDATE not checked for its row: the acceptance concurrent-write case fails (the passage is lost). - a refused `beginBuild` ignored by the service: the service stub "stops before any listing or write" case fails. - a throwing `completeBuild` swallowed: the service stub `ok: false` case fails. - the kernel embedder cached by the plugin: the plugin "re-registered embedder is reported at once" case fails. - (round 2) `listDocuments` compares before resolving the embedder: the not-ready no-embedder case fails; the service hands the `remedy` to the caller: the remedy-boundary case fails. Earlier ablations (organization filter, chunk-hash skip, search fingerprint check) and the docHash/headingPath ablation (3 suite cases fail) are unchanged. </details> <details><summary>Local derived gates (dispatch-gates --commands, 167 commands)</summary> At `7027f457`: 166 exit 0 (the round-2 delta at `065c98ff` re-ran typecheck, eslint, api-surface, spec docs, engine-double, tenant-audit and system-context censuses: all green). One NOT MEASURED (exit 3, a prerequisite refusal left to CI): `check-plugin-teardown-shape --self-test` (needs a full clone). The push hook's commit-trailer check is green (the two new commits carry the model-free trailer pair). </details> ## Acceptance notes | Acceptance | Where | |:--|:--| | 3072-dim works | `acceptance.live-postgres.test.ts` — stores and ranks 3072-wide vectors (column type read back as `vector(3072)`) | | two orgs never see each other's hits (adapter + service) | adapter: `acceptance…` two organizations case; service: contract suite organization cases under `isolated` / `group` | | missing extension → readable error with SQL, boot continues | `not-ready.test.ts` (adapter refusal text, healthCheck false, plugin start resolves and warns, recovery after the SQL runs) | | same content re-indexed → no embed call | `acceptance…` unchanged passage case (adapter) and second complete reindex case (service) | | changed fingerprint → rebuild-needed error, old rows not served | contract suite search/write refusal cases; `acceptance…` changed embedding model case through the service; `acceptance…` printed statements run as printed, and a first generation that never adopts rows left behind (L1 must-fix 2) | | contract suite passes in CI on real PG | `contract.live-postgres.test.ts` in the new Temporal Conformance step | | reindex over a real driver, mixed-case and numeric-looking ids (comment 7145881825) | `reindex-real-driver.live-postgres.test.ts` — 227 records over 3 walk pages, each indexed once, second reindex writes and embeds nothing | ## Verification Two-minute check: `OS_TEST_POSTGRES_URL=postgres://… pnpm --filter @objectstack/knowledge-pgvector exec vitest run` against any PostgreSQL with pgvector available — expect `Test Files 4 passed`, `Tests 57 passed`. CI evidence for the two new live steps: the relay lets a seat dispatch no `ci.yml` run, so the reading above (the CI image by digest, the step's exact command) stands in for it. A maintainer who wants it in CI can run `ci.yml` by `workflow_dispatch` on this branch; the job is advisory in the merge queue either way. Read first: `packages/plugins/knowledge-pgvector/src/pgvector-adapter.ts` (`upsert`, `search`, `ready`), `packages/services/service-knowledge/src/knowledge-service.ts` (walk build calls, `searchWithRefusals`), `.github/workflows/ci.yml` (the two new steps). Overlap: #37335 (#37103) landed first; main is merged here (`83fef223`), keeping both intents in `knowledge-service.ts` (record-level answers and freshness repair from main, the refusal report from here), `testing.ts` and `knowledge-memory/src/index.ts`. ## 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. - [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 by [Claude Code](https://claude.ai/code/session_01JQwxbX5BF433x8ooJNQVRp)_ <!-- signed: repo:cloud#1 · os-warren · session_01JQwxbX5BF433x8ooJNQVRp --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d5ae7a4 commit 9981f27

46 files changed

Lines changed: 3984 additions & 100 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@objectstack/knowledge-pgvector': patch
3+
'@objectstack/spec': patch
4+
'@objectstack/service-knowledge': patch
5+
'@objectstack/knowledge-memory': patch
6+
'@objectstack/embedder-openai': patch
7+
---
8+
9+
feat(knowledge): an open vector store on PostgreSQL with pgvector, and the index fingerprint every knowledge index is built under
10+
11+
Clause-②: yes
12+
Metadata-protocol: none
13+
14+
ADR-0161 Execution row 8a and K8 item 8 (#37100).
15+
16+
- **New package `@objectstack/knowledge-pgvector`.** `KnowledgePgvectorPlugin` registers a `PgvectorKnowledgeAdapter` (adapter id `pgvector`): passages and vectors in PostgreSQL with the pgvector extension, in a schema of its own (`os_knowledge`, option `schema`) — a generation table `knowledge_generation` and one passage table per vector width, `knowledge_vec_d<width>` — so no table collides with an object table or is read as schema drift. The database is the `url` option when given, else the platform's when `OS_DATABASE_URL` is PostgreSQL; the plugin keeps its own small pool (`poolMax`, default 4; `connectTimeoutMs`, default 5000, so an unreachable host does not hold boot), no pooled connection waits on the embedder, and the kernel's embedder is read at each call. Two deployments sharing one database set their own `schema`. Search is an exact cosine scan (a 3072-wide model works); the organization filter and the metadata `filter` run in the same `WHERE`, before ranking. A passage whose text is unchanged is not embedded again; one whose row a concurrent write removed is embedded and written, not lost. `queryPrefix` is put before every query before it is embedded. Without the `vector` extension, or the right to create it or the schema, the plugin still registers and boot goes on: it creates nothing, warns with the SQL to run, `healthCheck` answers `ok: false` with that SQL, and every call answers `503 SERVICE_UNAVAILABLE` until it has run; a database it cannot reach is reported as unreachable, with no SQL. A caller reads one sentence; the driver's text and the SQL travel in the error's `remedy`, for the operator. The store does not yet build a second generation beside the first: `beginBuild` under a new fingerprint is refused, and the reindex result carries the exact statements that clear the source (passages, then the generation row); a first generation never takes over passage rows left behind. An approximate (HNSW) index is an operator's step, documented with the package.
17+
- **The index fingerprint (ADR-0161 K7).** The knowledge service computes, per source and adapter, a fingerprint over the embedding model and dimensions the adapter reports, the resolved split and the splitter's version, and the content recipe; and a recipe hash over `where`, `metadataFields`, the title rule and the withheld fields. New exports from `@objectstack/service-knowledge`: `computeIndexFingerprint`, `computeRecipeHash`, `indexExpectation`, `INDEX_FINGERPRINT_VERSION`, `RECIPE_HASH_VERSION`, `ASSEMBLY_RULE_VERSION`, `TITLE_RULE_VERSION`, `SPLIT_ALGORITHM_VERSION`. Every adapter call carries them: `AdapterContext.index` and `AdapterSearchOptions.index` (`@objectstack/spec/contracts`).
18+
- **Adapter contract members (all optional).** `AdapterEmbeddingDescriptor` gains `model`, `dimensions` and `variant`; `IKnowledgeAdapter` gains `indexStatus`, and `beginBuild` / `completeBuild` as a pair: a complete reindex calls `beginBuild` before it lists or writes, and `completeBuild` once every row is written and the purge is done. `IEmbedder` gains `model`; `OpenAIEmbedder` reports the model it sends.
19+
- **A refused source is named, never read as empty.** A write or a search under another fingerprint is refused `409 KNOWLEDGE_REBUILD_REQUIRED` (registered in the error-code ledger). `KnowledgeService.search` over several sources answers from the searchable ones and logs each refused one with the adapter's `remedy`; a source that refuses the refill round is refused for the whole search, its first-round hits dropped; it throws the refusal (code, status, and `refused` naming every source) only when none could be searched. A caller is given the code and the adapter's one-sentence message, never its `remedy`; a reindex result carries the `remedy`. `KnowledgeService.searchWithRefusals` returns both, and the `search_knowledge` tool adds `refused` to its output when a source is refused.
20+
- **`knowledge-memory` is the reference.** It keeps an active generation and, while a build of another fingerprint runs, one under construction, switching at `completeBuild`.
21+
- **Contract suite.** `runKnowledgeAdapterContract`'s `implements` gains `indexStatus`, `builds`, `refusesOtherFingerprint` and `generations`, with cases for each. `knowledge-pgvector` runs the suite, the card's acceptance cases and a complete reindex over a real ObjectQL + SqlDriver against a live PostgreSQL in the `Temporal Conformance` job.

‎.changeset/config.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@
7878
"@objectstack/service-settings",
7979
"@objectstack/service-storage",
8080
"@objectstack/knowledge-memory",
81+
"@objectstack/knowledge-pgvector",
8182
"@objectstack/knowledge-ragflow",
8283
"@objectstack/embedder-openai",
8384
"@objectstack/account",

‎.github/workflows/ci.yml‎

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -794,6 +794,10 @@ jobs:
794794
# be added here by hand), and this file.
795795
temporal_live:
796796
- 'packages/plugins/knowledge-pgvector/**'
797+
# [#37100] The adapter contract suite the pgvector store runs
798+
# against the live PostgreSQL: a change to it is a change to that
799+
# step's verdict.
800+
- 'packages/services/service-knowledge/src/testing.ts'
797801
- 'packages/drivers/driver-sql/**'
798802
- 'packages/metadata-protocol/src/**/*live-mysql*'
799803
- 'packages/metadata-protocol/src/**/*live-postgres*'
@@ -2568,11 +2572,11 @@ jobs:
25682572
${{ runner.os }}-turbo-build-core-${{ github.ref_name }}-
25692573
${{ runner.os }}-turbo-build-core-
25702574
2571-
# Turbo remote cache (#22077), on all four of this job's build steps: the
2575+
# Turbo remote cache (#22077), on all five of this job's build steps: the
25722576
# four TURBO_* lines are Build Core's, verbatim, and Build Core's "Turbo
25732577
# remote cache (#21186)" comment holds the write rule, the signing and the
25742578
# PINS. Each of these plans is all `build` tasks with Build Core's hashes
2575-
# (8, 18, 14 and 31 nodes, measured). The suites between them run vitest
2579+
# (8, 18, 14, 31 and 20 nodes, measured). The suites between them run vitest
25762580
# through `pnpm --filter`, not turbo, and carry no credentials.
25772581
- name: Build driver-sql and its dependencies
25782582
env:
@@ -2798,6 +2802,32 @@ jobs:
27982802
pnpm --filter @objectstack/runtime exec vitest run --project local \
27992803
cascade-delete-multivalue-lookup-real-driver
28002804
2805+
# ── The pgvector knowledge store, on the live PostgreSQL (#37100) ──
2806+
#
2807+
# The service image above is pgvector's for this package: the
2808+
# `IKnowledgeAdapter` contract suite (`@objectstack/service-knowledge/testing`),
2809+
# the card's acceptance cases (a 3072-wide model, two organizations, no
2810+
# re-embedding, a refused fingerprint) and a complete reindex over a real
2811+
# ObjectQL + SqlDriver, each in a schema of its own. Without a URL these
2812+
# files are a named skip; the flag turns that into a red, as on the legs
2813+
# above. The positional is a SUBSTRING, not a glob (see the
2814+
# metadata-protocol step): it selects the three `*.live-postgres.test.ts`
2815+
# files; the unit file runs in Test Core.
2816+
- name: Build knowledge-pgvector and its dependencies
2817+
env:
2818+
TURBO_CACHE: ${{ (github.event_name == 'merge_group' || ((github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main')) && 'local:rw,remote:rw' || 'local:rw,remote:r' }}
2819+
TURBO_TOKEN: ${{ (github.event_name == 'merge_group' || github.ref == 'refs/heads/main') && secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY != '' && secrets.TURBO_TOKEN || '' }}
2820+
TURBO_TEAM: ${{ vars.TURBO_TEAM }}
2821+
TURBO_REMOTE_CACHE_SIGNATURE_KEY: ${{ (github.event_name == 'merge_group' || github.ref == 'refs/heads/main') && secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY || '' }}
2822+
run: pnpm exec turbo run build --filter=@objectstack/knowledge-pgvector... --concurrency=4
2823+
2824+
- name: Run the pgvector knowledge store against live PostgreSQL
2825+
env:
2826+
OS_TEST_POSTGRES_URL: postgres://postgres:postgres@127.0.0.1:5432/postgres
2827+
OS_EXPECT_LIVE_DIALECT_MATRIX: '1'
2828+
run: |
2829+
pnpm --filter @objectstack/knowledge-pgvector exec vitest run live-postgres
2830+
28012831
dogfood:
28022832
# Sharded 3-way: the suite is ~60 independent test files, each booting its
28032833
# own in-process app; a single 4-vCPU runner needed ~7½ minutes for the

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

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ Part of the [AI module](/docs/ai) — how agents retrieve knowledge through the
99
ObjectStack ships a Knowledge Protocol that lets you retrieve from pluggable backends (RAGFlow, LlamaIndex, Dify, custom pgvector, …) with one call: `KnowledgeService.search(query, { sourceIds?, topK? })`. The framework defines the contract and runs permission-aware filtering; the adapter plugin does the actual retrieval. See [the protocol design](/docs/protocol/knowledge) for the rationale.
1010

1111
<Callout type="info">
12-
**This whole stack is open.** The `@objectstack/service-knowledge` service, the adapter plugins (`@objectstack/knowledge-memory`, `@objectstack/knowledge-ragflow`), the `@objectstack/embedder-openai` embedder, and the permission-aware retrieval + event sync below all ship in the **open-source framework**. The workflow is: declare your knowledge sources, pick an adapter, and call `search` — retrieval respects the same row-level security as any ObjectQL query. Only the in-product chat *runtime* that consumes retrieval ships in ObjectOS; see the callout under [Retrieving knowledge](#retrieving-knowledge).
12+
**This whole stack is open.** The `@objectstack/service-knowledge` service, the adapter plugins (`@objectstack/knowledge-memory`, `@objectstack/knowledge-ragflow`, `@objectstack/knowledge-pgvector`), the `@objectstack/embedder-openai` embedder, and the permission-aware retrieval + event sync below all ship in the **open-source framework**. The workflow is: declare your knowledge sources, pick an adapter, and call `search` — retrieval respects the same row-level security as any ObjectQL query. Only the in-product chat *runtime* that consumes retrieval ships in ObjectOS; see the callout under [Retrieving knowledge](#retrieving-knowledge).
1313
</Callout>
1414

1515
## Wiring
@@ -131,6 +131,7 @@ Every embedding model accepts a text up to some length, counted in tokens. A pro
131131
- The limit comes from the known-model table, which carries each provider's documented per-input limit (OpenAI `text-embedding-3-*` 8192, DashScope `text-embedding-v3` 8192, BigModel `embedding-3` 3072, SiliconFlow `BAAI/bge-m3` 8192, `BAAI/bge-large-*-v1.5` 512, …). Set `maxInputTokens` to override it.
132132
- A model that is not in the table, with no `maxInputTokens`, has no limit — its inputs are sent at any length — and the embedder warns once when it is constructed.
133133
- The embedder reports the limit it applies as `maxInputTokens` (`IEmbedder.maxInputTokens`), so a knowledge adapter can pass it on (`embedding.maxInputTokens`) and the service's passages fit it.
134+
- It reports the model it sends as `model` (`IEmbedder.model`), so a knowledge adapter can pass it on (`embedding.model`) and the index fingerprint sees a model change.
134135

135136
```ts
136137
new OpenAIEmbedder({
@@ -158,6 +159,25 @@ The sum is multiplied by 1.1 and rounded up. On the sampled classes — Chinese,
158159

159160
Known residual: text made mostly of random hex or base64 — UUIDs, sha256 digests, encoded blobs — tokenizes at about 1–1.4 characters per token and can estimate below its real count. Emoji and rare ideographs (CJK Extension B and later) may also estimate low: `cl100k` spends two to four tokens on each. Other providers' tokenizers are not sampled.
160161

162+
## When the model or the split changes: rebuild
163+
164+
Vectors from two embedding models are not comparable, and neither are the passages of two splits. So every source's index is built under one **index fingerprint** — the embedding model and dimensions the adapter reports, the resolved split, and the content list — which the knowledge service computes and carries on every write and every search, and the adapter checks against the index it holds. Change any of them and the source's stored index is **refused** (`KNOWLEDGE_REBUILD_REQUIRED`, 409) until a complete reindex rebuilds it; it never answers with vectors of the old model ranked against the new one. A search over several sources still answers from the others, and the `search_knowledge` tool names each refused source in `refused`. Changing `where` or `metadataFields` changes no vector: a complete reindex repairs it in place. The full rules are in [the protocol's fingerprint section](/docs/protocol/knowledge#36-the-index-fingerprint).
165+
166+
## Self-hosted vector store: PostgreSQL + pgvector
167+
168+
`@objectstack/knowledge-pgvector` keeps passages and vectors in PostgreSQL with the pgvector extension — a `url` you give it, else the platform database when that is PostgreSQL — in a schema of its own (`os_knowledge`), so nothing collides with your objects' tables. Register it beside the knowledge service and point a source at it with `adapter: 'pgvector'`:
169+
170+
```ts
171+
new KnowledgePgvectorPlugin({ queryPrefix: '' /* e.g. BGE's query instruction */ }),
172+
```
173+
174+
- It searches by an exact scan, so a 3072-wide model works; the organization filter and the metadata `filter` run in SQL before ranking.
175+
- An unchanged passage is not sent to the embedder again on a reindex.
176+
- Without the `vector` extension (or the right to create it), boot goes on: the plugin warns with the SQL a database owner runs, and its sources answer `SERVICE_UNAVAILABLE` until then.
177+
- It stores each passage's text, which is as sensitive as the record it came from and is in every backup.
178+
179+
Details — the tables, an approximate index as an operator's step, rebuilds — are in [the protocol's pgvector section](/docs/protocol/knowledge#41-knowledge-pgvector--the-open-vector-store-on-postgresql).
180+
161181
## Why we did not build a vector DB
162182

163183
Mature OSS (RAGFlow, LlamaIndex, Dify) already nail embedding, hybrid retrieval, rerank, and OCR. ObjectStack's value is **the metadata-native source declaration, one structural split for every adapter, and the permission-aware filter on top of those engines** — not yet-another-RAG-stack. Customers pick the retrieval engine that matches their data; we make sure it talks to ObjectStack the same way every time.

0 commit comments

Comments
 (0)