Skip to content

Commit fd9ac00

Browse files
feat(service-knowledge): each source's sync state is one durable record, the same on every node (#38307)
Fixes #37736 Clause-②: yes (widening) — a new system object `sys_knowledge_sync_state` and its Setup entry, new `@objectstack/service-knowledge` exports (the store, its types, `KnowledgeIndexStatusBuild`, the Setup entry), new `index_status` members (`build.counts`, `failures`, `syncStateError`, `queue`) and the build status `interrupted`, and one more object in plugin-audit's exclusion roster; nothing a caller read before is removed Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:管理员在设置里多了「知识同步状态」列表,每个知识源一行,显示上次重建或对账的时间和结果、失败了几条同步、最近一次失败的原因。命令行查到的是同一份数据,不管问哪台服务器、重启前后都一样。 - 为什么做:知识库这一阶段承诺「管理员能看到同步状态」。以前这些信息只存在跑重建的那台机器的内存里:多节点时能不能看到要碰运气,重启就丢;同步失败只写在日志里。 - 出错会怎样:最坏的情况是状态记录写不进去。这时服务器日志会报一次错误并说明怎么修,知识检索和同步本身照常工作。撤回本次改动,就回到只能用命令行、按单台机器回答的旧行为。 - 要你做什么:本次改动超过三千行(大部分是各语言的翻译文件),按规则需要你本人审核并合并。 ## What changes One durable record per knowledge source, the same on every node (ruling B on the card, comments 7207326903 and 7208881866; ADR-0161). - **The object.** `sys_knowledge_sync_state` is declared in `@objectstack/platform-objects/system` and listed in `packages/spec/src/system/constants/platform-object-names.ts`. - `KnowledgeServicePlugin` registers it with its manifest, as the queue plugin registers `sys_job_queue`, so it exists only where the service is mounted. - There is one row per source index key. A row holds: - the source as callers name it, its package, adapter and object; - the last build: trigger, status, started and finished times, the counts (pages, rows read, written, unchanged, purged, cannot be indexed) and one platform sentence; - the sync failures: count, first and last time, and the last error, bounded to 500 characters. - There is no organization column: the state is deployment-level (ADR-0131 D7). - Rows are read-only at every data door. The object is `managedBy: 'engine-owned'`, so the engine-owned write guard refuses any write that is not the system's. `enable.apiMethods` is `get` and `list` only, every field is `readonly`, and reading needs `manage_platform_settings`. - A source's row goes when the source is dropped (`dropMetadataSource`). No run history is kept. - `@objectstack/plugin-audit` lists the object in `SKIP_OBJECTS`, beside `sys_job_queue` and `sys_job_run`, so none of the service's writes to it writes a row in `sys_audit_log` or `sys_activity`. - **Writers** (`knowledge-sync-state.ts` and `KnowledgeService`). - `rebuildSource` writes the row for every trigger: at the start (once it holds the lease), at most every `BUILD_PROGRESS_LOG_INTERVAL_MS` while it walks, and at the end. The end lands before the lease is released. A build that did not run writes nothing. - Progress and end writes land only while the row still names the build's id, so a build that lost its lease never overwrites the build that took over. - A build that a stopped node left `running` is closed as `interrupted`, after the `closeInterruptedSyncRuns` precedent. The next boot closes it (`closeInterruptedBuilds`, only while the source's lease is free), or the next lease holder does (`closeStaleBuild`). - The record-sync worker adds one failure per dead letter, never one per attempt (`recordSyncFailure`, a compare-and-set on the count). - **The reconcile reads the counts.** - A reconcile that completes clears the failures recorded before its walk began and removes their dead letters (`purgeFailed`). Failures recorded during the walk stay. - The dead letters are filtered by source in the service, because `listFailed` takes no predicate. Each letter is kept once, by its id. - The first failure of a source that had none asks for one reconcile, through the coalesced request a predicate write uses. Later failures ask for nothing, and so does a failed reconcile. - **Readers for people.** - `index_status` answers `build` and `failures` from the row, and the live pending count (`getQueueSize`) under `queue`. `build` carries `counts` beside the members it carried before: `sourceId`, plus `progress` and `result` (both deprecated in favour of `counts`), all filled from the same row. - A composition with no durable record (no manifest service, or no data engine) answers this node's build record, exactly as before. - The `rebuild` action answers once the build holds the source's lease and its start is recorded. A build that does not start still answers `ok`, as before, with `build.status` `not-run` and the reason in the message. - The per-node caveats in `knowledge-build-actions.ts` and `os knowledge status` are gone. - `os knowledge rebuild` follows the durable record, and the index-state inference added before is removed. A `not-run` answer exits 1 at once. For the `memory` adapter, one closing line remains: its index lives in each process. - Setup gets one `object` entry, **Knowledge Sync Status**, beside the Knowledge settings entry and gated on `manage_platform_settings` (the `nav_http_deliveries` precedent). It uses the generic list and record page. - The labels are in the generated translation bundles for every locale. - **No record content.** `build_message` and `last_error` are the platform's own sentences (`storedBuildMessage`, `syncFailureText`). A provider's text stays in the node's server log. - **Texts.** - `content/docs/ai/knowledge-rag.mdx` says where to look, what each status means (spelled as `index_status` answers it), what clears a failure and when the count is exact. - The `service-knowledge` README. - One changeset over the five packages. Read first, by risk: 1. `packages/services/service-knowledge/src/knowledge-service.ts`. In `rebuildOf` / `buildUnderLease`, the durable write chain (now awaited before the lease is released) and the lease-holder close. In `clearRepairedFailures`, the cut at the start of the walk. 2. `packages/services/service-knowledge/src/knowledge-build-actions.ts`: `indexStatusBuild` (the kept members, from the row), the path with no durable record, and the `ok` answer for a build that does not start. 3. `packages/services/service-knowledge/src/knowledge-sync-state.ts`: the predicate updates keyed on `build_id`, and the compare-and-set in `addFailure`. ## Tests Tests ran on head `81483db761`. For the packages other than service-knowledge, they ran on `5f51cac09d`; the only later change is a doc comment in `knowledge-build-actions.ts`. <details><summary>service-knowledge: 20 files, 695 tests, typecheck 0</summary> `pnpm --filter @objectstack/service-knowledge test && pnpm --filter @objectstack/service-knowledge typecheck` gave `Test Files 20 passed (20)` and `Tests 695 passed (695)`, and exited 0. `src/__tests__/sync-state.test.ts` (12 tests) runs on real kernels: `ObjectQLPlugin` over `SqlDriver` (better-sqlite3 on one file), the platform's `QueueServicePlugin` on `sys_job_queue`, and `KnowledgeServicePlugin`. Two nodes are two kernels over the one database file. The sync-state record is the real object store over SQL, not a mock. The knowledge adapter is an in-memory double that both nodes share, the way two replicas share one vector store. It pins: - A rebuild through node A reads identically on node B while it runs and after it ends, including an index that was already current, and after both nodes restart. The ended build carries `sourceId`, `progress` (pages included) and `result` beside `counts`, with the same numbers. - A build whose node stopped mid-walk reads `running` until the next boot or lease holder, then `interrupted`. A boot leaves alone a build whose lease another node holds. - A rebuild that another node holds answers `ok`, with `build.status` `not-run`, and the record keeps that node's build. - One failure per dead letter, with both times. A retried sync that succeeds counts nothing. - After a failure whose provider error quoted the record, the stored row holds none of the record's values. After a build that failed on such an error, the stored row holds the platform's fixed sentence and none of those values. - A completed reconcile clears the failures that preceded it and removes their dead letters. A failure during its walk survives. - One reconcile for the first failure, and one for a hundred. - Every source has a row at boot, and the row is removed with the source. The object's data-door posture and its Setup entry. `src/__tests__/knowledge-build.test.ts` pins the composition with no durable record: `index_status` answers this node's record as before (`sourceId`, `progress`, `result`, with `counts` beside them). A build that does not start answers `ok` with `not-run`, and `index_status` then reports `not-run`. </details> <details><summary>plugin-audit, platform-objects, spec, cli</summary> - plugin-audit: `pnpm --filter @objectstack/plugin-audit test` gave `Test Files 114 passed (114)` and `Tests 1894 passed (1894)`. Its typecheck exited 0. The new case in `audit-writers.test.ts` fires the knowledge service's seven writes to a source's row (insert, start, progress, end, a counted failure, a clear, delete) and expects no ledger or activity row. The same seven writes on a business object are audited, which is the control. - platform-objects: `Test Files 130 passed (130)` and `Tests 2218 passed (2218)`. Its typecheck exited 0. - spec: `platform-object-names.test.ts` and `api-methods-batch-conformance.test.ts` gave `Tests 18 passed (18)`, on the first head. - cli: `src/commands/knowledge/knowledge.test.ts` gave `Tests 12 passed (12)`. The new case: a `not-run` rebuild answer exits 1 at once, with and without `--no-wait`. `pnpm --filter @objectstack/cli typecheck` exited 0. The cli `integration` tier is left to CI. </details> <details><summary>Ablations: each red under its mutation, green on restore</summary> Both mutations went through `scripts/ablation-replace.mjs`. In each case the anchor hit once, the blob moved, and the restore was proven by the blob matching HEAD and an empty `git diff HEAD`. Both tests import from `src`, so no build leg is involved. - The no-record-content pin, its guard in `syncFailureText` mutated (blob `55e611958578` to `e93983d70bc5`): `Tests 1 failed`, on `expected '{"id":"kb",…' not to contain 'Salary bands'`. Restored: `Tests 1 passed`. - The audit exclusion, the `sys_knowledge_sync_state` line deleted from `SKIP_OBJECTS` (blob `0bf9f62c59d9` to `8a87f1966c18`): `Tests 1 failed`, on `expected [ …(14) ] to deeply equal []`. Restored: `Tests 1 passed`. </details> ## Acceptance notes - A record's id is not a field value of a record under the card's carried rule (seat ruling), so `last_error` carries the truncated id with the error's class, code and status, and never its message. - Changed lines are 4210, over the 3000 human-merge threshold, and most are the generated translation bundles. This PR lands by the maintainer's merge or an authorized approval. - The ADR-0161 Consequences sentence ("The service keeps none of its own") gets its dated note in a follow-up. `docs/adr/**` is the maintainer's merge, so that note is not on this head. - `status: 'not-run'` stays in the `index_status` build type but is never answered from the durable record. A build that did not run leaves the row with the build that ran. Writing `not-run` there would hide a build another node is running. - Known limit: the failure count is exact after a completed reconcile, which sets it from the dead letters it finds. Between two reconciles it can miss a message the queue dead-letters without running it (its lease ran out), or count twice a message delivered twice on its last attempt. The docs say so. - Known limit: only `dropMetadataSource` removes a row. A code-declared source that is unregistered, or dropped from the plugin's options between deploys, keeps its row until someone removes it. - Known limit: only a completed reconcile clears failures, never an operator rebuild. The failures of a source the reconcile does not walk (its store lists no documents) stay counted. The docs say so. - Known limit: the database queue counts at most 10,000 waiting messages, so `queue.pending` reads 10,000 for a larger backlog. The docs say so. - Known limit: with no cluster service, the contract on `main` is that a composition is one node. A second node booting over the same database without one closes a live build as `interrupted` until that build writes its end. - Without a manifest service or a bound data engine (lean kernels, test hosts), the plugin says once, at `warn`, that it keeps the last build in memory only, and `index_status` answers this node's record. - If a sync-state write fails, the service says so once, at `error`, naming what is lost and the fix (schema sync for the object). It does not fail the build or sync it records. A cluster-lock failure while closing interrupted builds at boot is a separate `warn` that names the lock. ## Verification <details><summary>Derived gates on 81483db</summary> `node scripts/pm/dispatch-gates.mjs --commands` derived 143 commands, and all 143 exited 0. - On the first pass, three gates exited 3 with `PREREQUISITE NOT MET` because their build output was missing in the recreated worktree: `check:dual-build-cjs-loads`, `check:i18n-coverage` and `check:skill-examples`. After a locked `turbo run build` of the packages and examples, all three exited 0. - `pnpm check:type-check-debt` ran under the lock and printed `OK — 0 ledger entr(ies) re-measured … none above its recorded number`. - The `--ran` reconciliation answered `143 derived, 143 run, 0 NOT-MEASURED, 0 UNRUN`. </details> Two-minute check: `pnpm --filter @objectstack/service-knowledge exec vitest run src/__tests__/sync-state.test.ts` should report 12 passed, with the two-node case first. --- _Generated by [Claude Code](https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP)_ <!-- signed: repo:objectstack#1 · os-elon-musk · session_016WV4cwPhGV4g9p1BGQaZbP --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent a56e1da commit fd9ac00

52 files changed

Lines changed: 3930 additions & 280 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: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
'@objectstack/service-knowledge': patch
3+
'@objectstack/platform-objects': patch
4+
'@objectstack/spec': patch
5+
'@objectstack/cli': patch
6+
'@objectstack/plugin-audit': patch
7+
---
8+
9+
feat(service-knowledge): each source's sync state is one durable record, the same on every node
10+
11+
Clause-②: yes (widening) — a new system object `sys_knowledge_sync_state` and its Setup entry, new `@objectstack/service-knowledge` exports (the store, its types, `KnowledgeIndexStatusBuild`, the Setup entry), new `index_status` members (`build.counts`, `failures`, `syncStateError`, `queue`) and the build status `interrupted`, and one more object in plugin-audit's exclusion roster; nothing a caller read before is removed
12+
Metadata-protocol: none
13+
14+
Each knowledge source now has one row in the new system object `sys_knowledge_sync_state` (declared in `@objectstack/platform-objects/system`, listed in the spec's platform object names, registered by `KnowledgeServicePlugin` with its manifest). The row holds the source (name, package, adapter, object), its last build (who started it, how it ended, its start and end times, its counts and one platform sentence) and its record syncs that failed and are not yet repaired (how many, first and last time, one sentence naming the record, the attempts and the kind of error). It never holds a field value or a provider's own error text.
15+
16+
- Every node reads and writes the same row, so `index_status`, `os knowledge status` and Setup answer the same whichever node is asked, and a restart forgets nothing. A build that did not run is not written.
17+
- A build writes its start, its counts at most every ten seconds, and its end, for every trigger. A build left `running` by a node that stopped is closed `interrupted` by the next boot (only while its build lease is free) or by the next node that takes the lease.
18+
- Each dead-lettered record sync adds one failure; a sync that succeeds on a retry adds nothing. The first failure of a source asks for one reconcile of it after the quiet period. A completed reconcile clears the failures recorded before its walk and removes their dead letters; failures during the walk stay.
19+
- `index_status` answers each source's `build` from the row: `counts` (pages, rows read, written, unchanged, purged, cannot be indexed) beside the members it carried before, `sourceId`, `progress` and `result` (both deprecated in favour of `counts`), filled from the same row; the status vocabulary adds `interrupted`. It also answers `failures`, and the queue's pending count under `queue`. A composition with no durable record (no manifest service or no data engine) answers this node's build record, as before.
20+
- The `rebuild` action answers once the build holds the source's lease and its start is recorded. A build that did not start still answers `ok`, as before, with `build.status` `not-run` and the reason in the message.
21+
- Setup gets a **Knowledge Sync Status** entry beside the Knowledge settings, for accounts with `manage_platform_settings`. The object is engine-owned with `get`/`list` only: no data door writes it.
22+
- `os knowledge status` prints the last build, the failed syncs and the queue's pending count without the per-node caveat. `os knowledge rebuild` follows the build through the durable record and no longer infers its end from the index state; a rebuild the server did not start (`not-run`) now exits 1 at once, with or without `--no-wait`. On the `memory` adapter the index stays per process, which the command says when the build ends.
23+
- `@objectstack/plugin-audit` leaves `sys_knowledge_sync_state` out of `sys_audit_log` and `sys_activity`, beside `sys_job_queue` and `sys_job_run`: the service's writes to a source's row (its start, progress every ten seconds, end, failures, clears) write no ledger or activity row.
24+
- `@objectstack/service-knowledge` now depends on `@objectstack/platform-objects` at runtime (it was a dev dependency).
25+
26+
Nothing to migrate: the table is created by schema sync, and the first build or failure fills it.

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

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -342,11 +342,30 @@ The default `memory` adapter holds nothing after a restart, so with it **every b
342342
To rebuild a source yourself, as an administrator (an account with `manage_platform_settings`):
343343

344344
```bash
345-
os knowledge status # each source: built, never built or due a rebuild, and the last build
345+
os knowledge status # each source: built, never built or due a rebuild, its last build and failed syncs
346346
os knowledge rebuild support_articles # start a complete build and follow its progress
347347
```
348348

349-
`os knowledge rebuild` starts the build on the server and prints its progress — rows read, documents written, unchanged, purged, and those that cannot be indexed — until it ends; `--no-wait` returns once it has started. Both commands call the `knowledge` settings actions `rebuild` and `index_status` (`POST /api/settings/knowledge/rebuild` with `{ "source": "ID" }`). The server logs each build's start, its progress every ten seconds, and its result. A build's progress lives on the node that runs it: behind a load balancer, read it from that node.
349+
`os knowledge rebuild` starts the build on the server and prints its progress — rows read, documents written, unchanged, purged, and those that cannot be indexed — until it ends; `--no-wait` returns once it has started. Both commands call the `knowledge` settings actions `rebuild` and `index_status` (`POST /api/settings/knowledge/rebuild` with `{ "source": "ID" }`). The server logs each build's start, its progress every ten seconds, and its result. The progress the commands read is the source's sync state (below), so behind a load balancer any node answers it. On the `memory` adapter the index itself lives in each server process: a rebuild fills the index of the node that ran it only, and the command says so when it ends.
350+
351+
### Each source's sync state
352+
353+
Every source has one sync-state row, in the system object `sys_knowledge_sync_state`, which every node reads and writes, so every node answers the same and a restart forgets nothing. A platform administrator reads it in **Setup → Knowledge Sync Status** (beside the Knowledge settings), with `os knowledge status`, or through the `index_status` action. Nothing but the knowledge service writes it, and no other account reads it.
354+
355+
The row holds the source (its name, package, adapter and object), its **last build** and its **failed syncs**. The statuses below are spelled as `index_status` and `os knowledge status` answer them; Setup shows each one's label:
356+
357+
| Last build status | What it means |
358+
|:--|:--|
359+
| `running` | the build is walking; its counts are written at most every ten seconds |
360+
| `done` | every row was read and the index recorded the build |
361+
| `failed` | it did not finish; the reason is in the server log of the node that ran it |
362+
| `lease-lost` | its cluster lease was lost, so it stopped; another node may build the source now |
363+
| `timed-out` | no page finished in time, so it was cancelled |
364+
| `interrupted` | the node running it stopped; the next boot, or the next node that takes the source's build lease, closes it |
365+
366+
After any status but `done`, the index keeps what it held, and the next reconcile, boot or rebuild builds again. A build that did not run (another node held the source's build, or nothing was due) is not written: the row keeps the build that did. Only the last build is kept; the reconcile job's run history is the job service's.
367+
368+
A **failed sync** is a record sync that spent every attempt and waits as a dead letter on the `knowledge-record-sync` queue. Each one adds one to the count, with its time and a sentence naming the record, the attempts and the kind of error. It never holds a field value, and never the embedding provider's own text, which may quote the record: that is in the server log of the node that ran the sync. A sync that succeeds on a retry counts nothing. The first failure of a source asks for a reconcile of that source two minutes later, however many follow. When a reconcile of the source completes, it clears the failures recorded before its walk began and removes their dead letters; failures recorded during its walk stay counted for the next one. The count is exact after a completed reconcile, which sets it from the dead letters it finds; between two reconciles it can miss a message the queue dead-letters without running it (its lease ran out), or count one message twice when it is delivered twice on its last attempt. Only a reconcile clears failures, not an operator rebuild, so the failures of a source the reconcile does not walk (its store lists no documents) stay counted until the source is removed. `os knowledge status` also prints how many record syncs are waiting on the queue (every source's together); the database queue counts at most 10,000 waiting messages, so a larger backlog reads as 10,000. Removing a source removes its row.
350369

351370
## Self-hosted vector store: PostgreSQL + pgvector
352371

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<!-- GENERATED — DO NOT EDIT BY HAND. -->
2+
<!-- Regenerate: node scripts/tenant-audit-census.mjs --write -->
3+
4+
# `services/service-knowledge` — tenant-audit census shard (generated)
5+
6+
The write call sites in `packages/services/service-knowledge/`, as `scripts/tenant-audit-census.mjs`
7+
derives them from the tree: this package's totals and every one of its sites.
8+
One file per package, and no total across packages is committed anywhere —
9+
`node scripts/check-tenant-audit-census.mjs` prints the census totals. The
10+
method is in [the ledger index](../../2026-08-tenant-audit-write-call-sites.counts.md). ⛔ Never hand-patch
11+
a row or a number here — fix the code, or the census, and regenerate.
12+
13+
## Totals in this package
14+
15+
| Measure | Value |
16+
|---|---:|
17+
| Write call sites | 5 |
18+
| Object name statically decidable | 5 |
19+
| Object name chosen at run time | 0 |
20+
| Object name spelled inline | 0 |
21+
| Object name spelled through a `const` | 5 |
22+
| Object name is an `object: string` parameter | 0 |
23+
| Object name is some other run-time expression | 0 |
24+
| Against a tenancy-enabled object | 5 |
25+
| Against an object declaring tenancy off | 0 |
26+
| Threading a tenant context | 5 |
27+
| Provably carrying none (options read, no context key) | 0 |
28+
| …and decidably tenancy-enabled | 0 |
29+
| Options argument unreadable | 0 |
30+
| …and decidably tenancy-enabled | 0 |
31+
| Threading a decidably elevated (`isSystem`) context | 5 |
32+
| Threading a decidably non-elevated context | 0 |
33+
| Threading a context of undecidable elevation | 0 |
34+
| Receiver carried a readable engine type | 5 |
35+
| Receiver erased, placed by the object NAME | 0 |
36+
| Receiver erased, placed by an `object: string` PARAMETER | 0 |
37+
| Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 0 |
38+
39+
## Subtractions the census could NOT defend — enforced
40+
41+
| what | count |
42+
|---|---:|
43+
| Write calls subtracted with no defensible reason | 0 |
44+
| …whose declared type text states an engine door anyway | 0 |
45+
46+
## Every site
47+
48+
| file | verb | object | tenancy | tenant context | n |
49+
|---|---|---|---|---|---:|
50+
| `packages/services/service-knowledge/src/knowledge-sync-state.ts` | `delete` | `sys_knowledge_sync_state` | enabled | elevated | 1 |
51+
| `packages/services/service-knowledge/src/knowledge-sync-state.ts` | `insert` | `sys_knowledge_sync_state` | enabled | elevated | 3 |
52+
| `packages/services/service-knowledge/src/knowledge-sync-state.ts` | `update` | `sys_knowledge_sync_state` | enabled | elevated | 1 |

0 commit comments

Comments
 (0)