Repository navigation
Commit 40570d6
feat(knowledge): knowledge-turso moves into objectstack — Apache-2.0, platform embedder and splitter, generations, the contract suite (#37388)
<!-- claude-projects-attribution: {"github_login":"os-warren"} -->
_Requested by **Warren** · [project
thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ88NDT2MrJFi2ZJy4HVSApob)_
Fixes #37107
Clause-②: yes
Metadata-protocol: none
## 维护者速读
- 本地开发(默认 SQLite)和不用 PostgreSQL 的部署,现在也能用开源自带的向量知识库:向量存在项目数据目录下单独的
knowledge.db 文件里,中文检索可用;换嵌入模型时在旁边建新索引,建好再切换,旧索引在此期间照常回答。
- 属于「知识检索平台化」专题:把原来放在 cloud 仓库的 libSQL
向量库搬进开源框架(Apache-2.0),改用平台统一的嵌入器和切分器,并通过与 pgvector 同一套契约测试。
- 新包默认不启用,撤回只需不注册该插件;它绝不写平台自己的数据库文件;在没有 libSQL 原生构建的平台(Windows
ARM)上照常启动,只是知识源回答「暂不可用」。
- 已按第一轮复核修完:只认旧版完整表结构,不会误删登记表或别人的表;远程库每次请求有 10
秒上限(按单次请求计时,重建一整批也不会超时;超时只回滚、不会事后提交);并补上「限定范围检索」。
- 要你做的:无(专题席位做差量复核;cloud 仓库删除旧包是另一张 cloud 卡)。
## What changes
**`@objectstack/knowledge-turso` moves into
`packages/plugins/knowledge-turso`** (Apache-2.0 `LICENSE` text,
settling cloud ADR-0119 D5's mixed licence). Same package name; the next
version publishes from here, in the fixed version group.
- **Its own libSQL database, never the platform's file.** `url` option
(`file:`, `:memory:`, `libsql://`), else `file:` + project root +
`/.objectstack/data/knowledge.db` (`defaultStoreUrl`, for #37102 to
name). A URL naming `objectstack.db`, `dev.db`, `standalone.db` or the
file `OS_DATABASE_URL` names (a URL or a bare path) is refused, compared
percent-decoded, without case, as the file a link resolves to, and with
SQLite's `-wal` / `-shm` / `-journal` side files read as their database
(os-bob's #37106 measurement, comment 7143523345: two engines on one
file lose rows). On a file: `PRAGMA journal_mode = WAL` and a busy
timeout (`busyTimeoutMs`, default 5000). In one process all database
work of one client runs through one queue: a write transaction holds its
connection across awaits, and a second in-process writer would otherwise
wait in SQLite's synchronous busy handler on the very thread the holder
needs. On a remote URL each request is bounded on its own
(`requestTimeoutMs`, default 10000): a statement, a document's batch (a
write sends each document's statements as one batch, so a 100-document
page is ~100 requests), opening a transaction, a commit or rollback.
Past it the call answers `503 SERVICE_UNAVAILABLE` naming
`requestTimeoutMs`, and the queue moves on. A request that times out
inside a write is followed by a rollback, never a commit; only a commit
that itself times out may still land, and its remedy says so (writes are
idempotent).
- **Platform embedder and splitter.** The package's own embedding
provider, hash embedder and chunker are deleted; it reads the kernel
`embedder` service at each call (or `embedder`), reports `embedding`
(model, dimensions, maxInputTokens), and declares `capabilities.chunks`.
- **Layout (card item 4).** `knowledge_generation` (source_id,
generation, fingerprint, recipe_hash, dim, model, state, created_at)
with two partial unique indexes: one `active` and one `building` row per
source; the second is the lock row that keeps one builder per source.
One passage table per source and generation, `knowledge_SOURCE_gN`
(chunk_id PK, document_id, source_record_id, organization_id, content,
title, heading_path, doc_hash, chunk_hash, metadata, embedding
`F32_BLOB(dim)`). Source ids are held to the spec's `^[a-z_][a-z0-9_]*$`
before any SQL (refused `400 VALIDATION_ERROR`); every value is a bind
parameter. The unique index keeps one generation under construction per
source, not one builder: a second `beginBuild` under the same
fingerprint joins the build, one under another fingerprint replaces it,
and the first builder's writes are then refused 409.
- **Generations (card item 5; ADR-0161 K7, K8 item 8).** Writes go to
the generation of the carried fingerprint (active or building), else
`409 KNOWLEDGE_REBUILD_REQUIRED`; a search under another fingerprint
than the active one's is refused the same way ("is being rebuilt" while
a build for it runs). `beginBuild` under a new fingerprint creates
`knowledge_SOURCE_gN+1` beside the active table; a build of a third
fingerprint drops the unfinished one. `completeBuild` makes it active,
records the recipe hash, drops the old table. `indexStatus` answers
fingerprint, recipeHash and `building`. Unlike knowledge-pgvector (which
refuses a second generation, #37101), this store runs the suite with
`generations: true`.
- **Legacy table (card item 4, last bullet).** A `knowledge_SOURCE`
table of the cloud releases, recognised by exactly their seven columns
and an `F32_BLOB` vector, is never served. A table of any other shape
under a store name (the store's own generation table, another source's
generation table, a table the store did not make in a shared database)
is neither served nor dropped; `openGeneration` remakes a table only
when it has the passage shape: search answers
`KNOWLEDGE_REBUILD_REQUIRED`, a write outside a build is refused,
`beginBuild` opens generation 1 as building, and `completeBuild` drops
the legacy table.
- **Search.** Exact cosine scan (`vector_distance_cos`) with the
organization filter, the record scope and the metadata `filter` (JSON
equality per top-level key) in the same `WHERE`, before ranking; hits
carry `docHash` and `headingPath`. No DiskANN index: `vector_top_k`
ranks before it filters, which breaks K8 item 9, and it is what made
os-bob's 1,000 × 1,536 file 329 MB with a 21.8 s build. Measured here
without it: 1,000 passages 8.3 MB, write 0.7 s, search ~5 ms; 10,000
passages 82 MB, write 7.2 s, search ~52 ms (Linux x64). Docs say so and
point larger sources at pgvector.
- **Record scope (#37308, merged as 98b17fe), as knowledge-pgvector.**
A scope with no term that has ids answers `[]` before any query; terms
are ORed inside the organization-filtered `WHERE`. A `record` term
matches `source_record_id`; a `metadata` term matches a stored string or
number equal to an id as text, or a list with such an element, by the
field's stored key (bound, never a JSON path). Each term's ids go as one
bound JSON array. The suite declares `implements.scope: true`.
- **listDocuments (card item 6)**, byte-order cursor, the generation
writes go to. A passage whose `chunk_hash` is stored is not re-embedded;
a passage removed by a concurrent write is re-planned (3 attempts), as
in pgvector.
- **Degrades instead of crashing (os-bob comment, Windows on ARM).**
`@libsql/client` is imported lazily in `start()`; a failed load (no
native build), an unopenable file or a refused URL registers the adapter
unavailable: boot continues, `healthCheck` `ok: false`, every call `503
SERVICE_UNAVAILABLE`, one-sentence message, reason in `remedy`.
- **Wiring (named in the claim).** `.changeset/config.json` fixed group;
`pnpm-lock.yaml` (no new external dependency: `@libsql/client@0.18.0` is
already in the lockfile); one ledger row `@objectstack/knowledge-turso:
[KNOWLEDGE_REBUILD_REQUIRED]` in
`packages/spec/src/api/error-code-ledger.zod.ts` (its docs mirror lists
codes only, unchanged); `packages/spec/llms.txt` package count 77 → 78
(`check:llms-txt` demanded it).
- **Settings hint made false by this PR, fixed (claim amended).**
`knowledge.manifest.ts`: the Turso "Test connection" hint said the
package "this platform does not ship", from the ObjectOS Cloud monorepo,
and that a store with no URL reuses the tenant's primary libSQL
connection; both are now false. It now names the plugin registered
beside the knowledge service and its default file; header list updated;
the two tests re-pinned as properties. Minimal, as #37104 rewrites this
manifest.
- **Docs.** `content/docs/protocol/knowledge.mdx` new section 4.2,
overview diagram, contract paragraph, example, status table;
`content/docs/ai/knowledge-rag.mdx` new section "Local vector store: a
libSQL file".
## Why
Card #37107 (ADR-0161 Execution row 7; cloud ADR-0119 D5 「都放开源」): every
deployment not on PostgreSQL, `os dev` included, gets an open vector
store that follows the platform's embedder, splitter, listing and
fingerprint contract.
## Tests
`packages/plugins/knowledge-turso`, 143 cases, no service or image
(libSQL runs in-process):
- `contract.test.ts` — `runKnowledgeAdapterContract` with every member
declared (`listDocuments`, `chunks`, `organizationIds`, `indexStatus`,
`builds`, `refusesOtherFingerprint`, `generations`, `scope`) on
`:memory:` and on a `file:` URL: 92/92.
- `acceptance.test.ts` (42, both stores plus two request-bound cases):
Chinese text found with a fixed fake embedder; same content re-upserted
→ no embed call, changed passage → only it embedded; model changed at
the same width and at another width → through `KnowledgeService` the
search is refused, a complete reindex builds `_g2`, `_g1` is dropped,
the generation row records the new width and model; mid-build the old
generation answers its own fingerprint and the new one is "being
rebuilt", a third fingerprint abandons the unfinished build and a write
under the abandoned fingerprint is refused; two organizations never see
each other's hits (topK 1, filter before ranking); metadata filter by
JSON type (`2` vs `"2"`); legacy table → `KNOWLEDGE_REBUILD_REQUIRED`,
write refused, `indexStatus` empty, then a reindex replaces and drops
it; another source's generation table never read as legacy; a source
named `generation` reindexed with the store's generation table intact
and other sources still answering; a table the store did not make under
a legacy name kept through a reindex, and under a generation name
refused and kept; a passage table left without its generation row remade
afresh, not adopted; a write whose generation is switched while it
embeds refused 409, never written elsewhere; a record scope by stored
key (a dotted name is a key), strings and numbers only (a boolean or
object matches no id), a quote in a name, an injection-shaped id
matching nothing; 12 concurrent upserts and searches on one `:memory:`
client all succeed; an unsafe source id refused before SQL; no client /
no embedder → `SERVICE_UNAVAILABLE` with the reason only in `remedy`,
`listDocuments` included (503, not 409); a request that never answers is
bounded by `requestTimeoutMs` and the queue moves on; on a slow client
(15 ms a request, 120 ms bound) a page of 40 documents of 2 passages is
written whole, twice; a write whose second batch hangs answers 503
naming `requestTimeoutMs` and nothing of it lands, then the next write
goes through; a table with the legacy column names but no `F32_BLOB`
vector is not legacy; a search whose generation is switched at every
embed stops after three attempts (503); a source id outside the pattern
is `400 VALIDATION_ERROR`, an 80-character one accepted.
- `plugin.test.ts` (9): default URL; platform database refused by name
(percent-encoded and differently cased too) and by `OS_DATABASE_URL` (a
URL or a bare path); an undecodable `file:` URL refused; side files and
links (a linked file, a linked directory) refused; the remote default
bound (`requestBoundFor`); the opened file is in WAL with the generation
table; a `@libsql/client` that fails to load (mocked `win32-arm64-msvc`
error) registers an unavailable adapter and boot continues; a kernel
embedder registered after `start` is read.
Single-change ablations, each restored: the old legacy rule (4 red),
`openGeneration` remaking a foreign table (2 red), the fresh-table
`DROP` (2 red), `listDocuments` comparing before the embedder (1 red),
the request bound (1 red), the old whole-turn bound (both request-bound
cases red), a commit instead of a rollback after a timeout (1 red), the
vector-type half (2 red), the `VALIDATION_ERROR` code (2 red), the
search retry bound (2 red), the remote default (1 red), the side-file
reading (1 red), the write-time generation recheck (2 red), the scope
scalar guard (2 red), the scope `WHERE` (12 red in the suite).
Not covered here: two processes writing one file (the busy timeout is
set and pinned by `PRAGMA`, not by a two-process race). Scope ids are
compared with a stored number's SQLite text: exponent forms and numbers
past 15 significant digits match no id here (fewer hits, never more; the
service's check after the answer stays the guard).
## Acceptance notes
- `carrier: cloud` — `packages/knowledge-turso` in the cloud repo is now
a duplicate; its removal is the cloud card the card names (out of
scope). Nothing in cloud imports the package outside its own directory
(searched cloud `origin/main`).
- `carrier: #37102` — the runtime mount names the store's path;
`defaultStoreUrl(projectRoot)` and `PLATFORM_DATABASE_FILES` are
exported for it.
- noted, not filed — the `knowledge` settings namespace (`turso_url`,
`turso_auth_token`) is still read by no plugin; #37104 rewrites the
manifest.
- Breaking for npm consumers of the cloud-repo 6.x releases (removed
exports and options, listed in the changeset); the version moves from
6.9.0 to this repo's track.
## Verification
Two-minute check: `pnpm --filter @objectstack/knowledge-turso test` →
`Test Files 3 passed (3)`, `Tests 143 passed (143)`.
Read first: `src/turso-adapter.ts` `beginBuild` / `completeBuild` /
`writeTarget` (generation switching), `hasLegacy` / `openGeneration`
with `tableShape` in `src/sql.ts` (the legacy rule), the `serial` queue
and its bound at its top, and `src/plugin.ts` `resolveStoreUrl` (the
platform-file refusal).
<details><summary>Local gates at head 796b204: 133 of 134 derived
families exit 0, 1 not measured; CI at 796b204: 62 success, 9 skipped,
0 failed</summary>
- `node scripts/pm/dispatch-gates.mjs --ran` (with exit codes): 134
derived famil(ies) accounted for, 133 run, 1 NOT-MEASURED (1 derived
from a recorded exit 3).
- `pnpm --filter @objectstack/knowledge-turso test`: Test Files 3 passed
(3), Tests 143 passed (143) (lock VERDICT command-exit 0). `typecheck`
(incl. `check:test-typecheck`) and `build` exit 0.
- `service-settings`: `knowledge.manifest.test.ts` 25/25; `typecheck`
exit 0.
- `check:llms-txt` green at 78 packages. `check:error-code-provenance`,
`check:docs`, `check:package-naming`, `check:changeset-no-major`,
`check:dual-build-cjs-loads`, `check:published-readme-exports`,
`check:skill-examples` exit 0 at this head.
- NOT MEASURED locally (exit 3, prerequisite not met):
`check-plugin-teardown-shape --self-test` (needs an unshallow clone; its
scan passed).
- No `.github/workflows` edit: the libSQL suite runs in the normal test
shards, no service image needed. Dogfood battery: n/a (no `!` in the
title, no narrowing arm).
- History: `56f3dc5e` (first hand-back) → `68654e1d` merges `main` at
`db77cc49` (brings #37342) → `9c469ddf` the record scope → `f073750a`
review round 1 (seat comment 7179839476) → `796b204c` review round 2
(seat comment 7180860083).
</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 (CI).
- [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 (none change for a ledger row;
`check:error-code-provenance` and `check:docs` green).
- [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_01JQwxbaMuehXzctoWq7iRsV)_
<!-- signed: repo:cloud#1 · os-warren · session_01JQwxbaMuehXzctoWq7iRsV
-->
---------
Co-authored-by: Claude <noreply@anthropic.com>1 parent f9dd033 commit 40570d6
23 files changed
Lines changed: 2885 additions & 37 deletions
File tree
- .changeset
- content/docs
- ai
- protocol
- packages
- plugins/knowledge-turso
- src
- __tests__
- services/service-settings/src/manifests
- spec
- src/api
| 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 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
79 | 79 | | |
80 | 80 | | |
81 | 81 | | |
| 82 | + | |
82 | 83 | | |
83 | 84 | | |
84 | 85 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
9 | 9 | | |
10 | 10 | | |
11 | 11 | | |
12 | | - | |
| 12 | + | |
13 | 13 | | |
14 | 14 | | |
15 | 15 | | |
| |||
212 | 212 | | |
213 | 213 | | |
214 | 214 | | |
| 215 | + | |
| 216 | + | |
| 217 | + | |
| 218 | + | |
| 219 | + | |
| 220 | + | |
| 221 | + | |
| 222 | + | |
| 223 | + | |
| 224 | + | |
| 225 | + | |
| 226 | + | |
| 227 | + | |
| 228 | + | |
215 | 229 | | |
216 | 230 | | |
217 | 231 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
84 | 84 | | |
85 | 85 | | |
86 | 86 | | |
| 87 | + | |
| 88 | + | |
87 | 89 | | |
88 | 90 | | |
89 | 91 | | |
| |||
374 | 376 | | |
375 | 377 | | |
376 | 378 | | |
377 | | - | |
| 379 | + | |
| 380 | + | |
378 | 381 | | |
379 | 382 | | |
380 | 383 | | |
| |||
485 | 488 | | |
486 | 489 | | |
487 | 490 | | |
| 491 | + | |
488 | 492 | | |
489 | 493 | | |
490 | 494 | | |
| |||
495 | 499 | | |
496 | 500 | | |
497 | 501 | | |
| 502 | + | |
498 | 503 | | |
499 | 504 | | |
500 | 505 | | |
| |||
569 | 574 | | |
570 | 575 | | |
571 | 576 | | |
| 577 | + | |
| 578 | + | |
| 579 | + | |
| 580 | + | |
| 581 | + | |
| 582 | + | |
| 583 | + | |
| 584 | + | |
| 585 | + | |
| 586 | + | |
| 587 | + | |
| 588 | + | |
| 589 | + | |
| 590 | + | |
| 591 | + | |
| 592 | + | |
| 593 | + | |
| 594 | + | |
| 595 | + | |
| 596 | + | |
| 597 | + | |
| 598 | + | |
| 599 | + | |
| 600 | + | |
| 601 | + | |
| 602 | + | |
| 603 | + | |
| 604 | + | |
| 605 | + | |
| 606 | + | |
| 607 | + | |
| 608 | + | |
| 609 | + | |
| 610 | + | |
| 611 | + | |
| 612 | + | |
| 613 | + | |
| 614 | + | |
| 615 | + | |
| 616 | + | |
| 617 | + | |
| 618 | + | |
| 619 | + | |
| 620 | + | |
| 621 | + | |
| 622 | + | |
| 623 | + | |
| 624 | + | |
| 625 | + | |
| 626 | + | |
572 | 627 | | |
573 | 628 | | |
574 | 629 | | |
| |||
928 | 983 | | |
929 | 984 | | |
930 | 985 | | |
| 986 | + | |
931 | 987 | | |
932 | 988 | | |
933 | 989 | | |
| |||
0 commit comments