Repository navigation
Commit 9981f27
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
File tree
- .changeset
- .github/workflows
- content/docs
- ai
- permissions
- protocol
- references/api
- packages
- plugins
- embedder-openai/src
- __tests__
- knowledge-memory/src
- __tests__
- knowledge-pgvector
- src
- __tests__
- services/service-knowledge/src
- __tests__
- split
- spec
- api-surface
- export-origins
- src
- api
- contracts
Some content is hidden
Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
78 | 78 | | |
79 | 79 | | |
80 | 80 | | |
| 81 | + | |
81 | 82 | | |
82 | 83 | | |
83 | 84 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
794 | 794 | | |
795 | 795 | | |
796 | 796 | | |
| 797 | + | |
| 798 | + | |
| 799 | + | |
| 800 | + | |
797 | 801 | | |
798 | 802 | | |
799 | 803 | | |
| |||
2568 | 2572 | | |
2569 | 2573 | | |
2570 | 2574 | | |
2571 | | - | |
| 2575 | + | |
2572 | 2576 | | |
2573 | 2577 | | |
2574 | 2578 | | |
2575 | | - | |
| 2579 | + | |
2576 | 2580 | | |
2577 | 2581 | | |
2578 | 2582 | | |
| |||
2798 | 2802 | | |
2799 | 2803 | | |
2800 | 2804 | | |
| 2805 | + | |
| 2806 | + | |
| 2807 | + | |
| 2808 | + | |
| 2809 | + | |
| 2810 | + | |
| 2811 | + | |
| 2812 | + | |
| 2813 | + | |
| 2814 | + | |
| 2815 | + | |
| 2816 | + | |
| 2817 | + | |
| 2818 | + | |
| 2819 | + | |
| 2820 | + | |
| 2821 | + | |
| 2822 | + | |
| 2823 | + | |
| 2824 | + | |
| 2825 | + | |
| 2826 | + | |
| 2827 | + | |
| 2828 | + | |
| 2829 | + | |
| 2830 | + | |
2801 | 2831 | | |
2802 | 2832 | | |
2803 | 2833 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
9 | 9 | | |
10 | 10 | | |
11 | 11 | | |
12 | | - | |
| 12 | + | |
13 | 13 | | |
14 | 14 | | |
15 | 15 | | |
| |||
131 | 131 | | |
132 | 132 | | |
133 | 133 | | |
| 134 | + | |
134 | 135 | | |
135 | 136 | | |
136 | 137 | | |
| |||
158 | 159 | | |
159 | 160 | | |
160 | 161 | | |
| 162 | + | |
| 163 | + | |
| 164 | + | |
| 165 | + | |
| 166 | + | |
| 167 | + | |
| 168 | + | |
| 169 | + | |
| 170 | + | |
| 171 | + | |
| 172 | + | |
| 173 | + | |
| 174 | + | |
| 175 | + | |
| 176 | + | |
| 177 | + | |
| 178 | + | |
| 179 | + | |
| 180 | + | |
161 | 181 | | |
162 | 182 | | |
163 | 183 | | |
| |||
0 commit comments