Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .changeset/37465-knowledge-build-lease-fence.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
'@objectstack/service-knowledge': patch
'@objectstack/knowledge-pgvector': patch
'@objectstack/cli': patch
---

fix(service-knowledge, knowledge-pgvector): a build that loses its lease stops at the next page, and a build that stalls is cancelled

Clause-②: yes (widening)
Metadata-protocol: none

- **A build that loses its cluster lease stops.** Before each page, a build checks that it still holds its cluster lease. The lease counts as lost when the lock says so, or when no renewal has succeeded within the 60-second lease (the lock store is unreachable, or a renewal hangs). The build then stops before reading or embedding another page. It neither purges nor completes, and its record (`buildRecord`, `os knowledge status`) reads the new status `lease-lost`. Before this change the build only logged a warning and went on, so a second node could build the same source and the embedding spend doubled.
- **A build that stalls is cancelled.** A build that finishes no page for 15 minutes (a fixed ceiling, not a setting) is cancelled, for example when an embedding call never answers. The walk stops waiting on that call and the lease is released. The record reads the new status `timed-out`, and a new rebuild can start without a restart. The limit applies to the time between two pages, not to the whole build, so a large source that keeps making progress is never cut short.
- **pgvector: a build that lost its builder lock writes and completes nothing.** Each write and removal of a build checks, on the lock's own session, that the source's session advisory lock is still held. Once the lock is gone (freed after `buildLockIdleMs`, or its session ended), the write is refused `LOCK_CONFLICT` (409) before anything is embedded. `completeBuild` completes only the build this adapter began, and only the generation that build began. Otherwise it is refused `LOCK_CONFLICT` and switches, records and deletes nothing, so a build that lost its lock can no longer switch a generation another build has taken up since. A lock kept from an earlier build is re-checked at the next `beginBuild`, so a session that ended is never taken for a lock that is still held. **Behind a transaction-mode connection pooler** (PgBouncer transaction pooling, or a hosted provider's pooled URL), a deployment the store already did not support, the advisory lock does not stay with the session that took it. The check therefore reads a held lock as lost, and every complete build is now refused `LOCK_CONFLICT` at its first page, where before it ran with a release warning. Point the store's `url` at a direct or session-mode endpoint; the refusal's remedy says so.
- **pgvector: a search whose source's index was switched under it three times** is now refused `CONCURRENT_MODIFICATION` (409) instead of throwing an error with no code.

Widening: the exported `KnowledgeBuildRecord.status` type gains `lease-lost` and `timed-out`. A consumer that switches over it should handle both the way it handles `failed`. No other export changes: the fence and its 15-minute limit are internal to the service.

`os knowledge rebuild` and `os knowledge status` know the two new statuses: a followed rebuild that ends `lease-lost` or `timed-out` exits 1 with the build's message, as a `failed` one does.
8 changes: 7 additions & 1 deletion content/docs/ai/knowledge-rag.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,8 @@ A store that keeps **generations** (pgvector and Turso) does not throw the old i
2. **Search during the build is refused, never answered from the old index.** A search of the source answers `KNOWLEDGE_REBUILD_REQUIRED` (409) and says the source *is being rebuilt*. A search over several sources still answers from the others, and `search_knowledge` names this one in `refused`.
3. **At the end, the switch.** Once the walk is done, the purge runs once. Then the new generation becomes the active one, and the old one is deleted. pgvector deletes it in batches of 1,000 rows, so no long lock is held over a large source. If the deletion stops part-way, the source's next build finishes it, and the old rows are never searched meanwhile.
4. **One builder per source.** pgvector takes a PostgreSQL advisory lock on the source when its build begins and holds it until the switch. A second build of the source, from another node or process, is refused `LOCK_CONFLICT` (409) and walks nothing. This is a *session* lock, so the store needs a direct or session-mode PostgreSQL connection. Behind a transaction-mode pooler (PgBouncer transaction pooling, or a hosted provider's pooled URL), the lock does not stay with the store's session. Point the store's `url` at a direct or session-mode endpoint. A release whose session no longer held the lock is logged as a warning.
5. **A build that stops is resumed, not restarted.** The generation under construction is kept, with everything written into it so far. The next build under the same fingerprint takes it up, and skips every document it already holds unchanged, so only the rest is sent to the embedding provider. If the process stops, PostgreSQL frees the lock at once. If the build fails on a process that keeps running, the lock is freed after 15 minutes without a call of the build itself. Record events that keep arriving for the source do not hold it. A build under yet another fingerprint abandons the unfinished generation and deletes it.
5. **A build that stops is resumed, not restarted.** The generation under construction is kept, with everything written into it so far. The next build under the same fingerprint takes it up, and skips every document it already holds unchanged, so only the rest is sent to the embedding provider. If the process stops, PostgreSQL frees the lock at once. If the build fails on a process that keeps running, the lock is freed after 15 minutes without a call of the build itself. Record events that keep arriving for the source do not hold it. A build under yet another fingerprint abandons the unfinished generation and deletes it, and so does a build under the active fingerprint, when the change was reverted before the new index was finished.
6. **A build that lost the lock writes nothing more.** Before each page it writes, pgvector checks that its session still holds the source's lock. Once the lock is gone (freed after the idle time, or its session dropped), the next page is refused `LOCK_CONFLICT` (409) before it is embedded, and the walk stops. Its switch is refused the same way, so a build that lost the lock never switches or deletes a generation another build has taken up since.

## The first build, and rebuilding a source

Expand All @@ -242,6 +243,11 @@ Event sync keeps an index in step with rows as they are written; it never indexe

A source with `refresh.onRecordChange: false` is left to its external indexer, and an adapter that reports neither an index status nor its documents is never built automatically: the boot log says so, and you rebuild it by hand. With several server nodes sharing a cluster lock driver (`OS_CLUSTER_DRIVER=redis`, [Cluster](/docs/kernel/cluster)), only one builds a source: the build runs under the `cluster` service's lock, and a node that finds the source built when it gets the lock builds nothing. `KnowledgeServicePlugin({ buildAtBoot: false })` turns the boot builds off.

Two things stop a build before it ends. Neither purges or completes anything. The store keeps what was written, and the next build skips it as unchanged:

- **The build lost its lease.** Before each page, the build checks that it still holds its cluster lease. The lease is lost when the lock says so, or when no renewal has succeeded within the 60-second lease (the lock store is unreachable, or a renewal hangs). Then the build stops before the next page, so no further page is read or sent to the embedding provider. Its record reads `lease-lost`, and another node may build the source from then on. On pgvector, the stopped build's own builder lock stays with this node until its idle time passes ([item 5 above](#generations-the-new-index-is-built-beside-the-old-one)), so another node's build is refused `LOCK_CONFLICT` until then.
- **The build stalled.** If no page finishes for 15 minutes, for example because an embedding call or a store call never answers, the build is cancelled. Its lease is released and its record reads `timed-out`, so a new rebuild can start without a restart. The limit is on the time between two pages, not on the whole build, so a large source that keeps making progress is never cut short. A call the build stopped waiting on cannot be withdrawn: if it answers later, its page is written, and the walk does not go on after it.

<Callout type="warn">
**A build costs money.** A complete build reads every row the source's `where` matches and sends the listed content fields of each one the index does not already hold unchanged to your embedding provider, which bills for them. The first build of a large source, or a rebuild after you change the embedding model or the split, sends all of it. The boot log line that starts a build says so.

Expand Down
8 changes: 5 additions & 3 deletions packages/cli/src/commands/knowledge/rebuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@ import {
* seconds and prints the build's progress until it ends. Exits 0 when the
* build finished, 1 when it did not run or did not finish. With `--no-wait`
* it exits 0 once the build has started and reports no outcome: the build
* may still end `not-run` (another node holds the source's lock) or
* `failed`, which only `os knowledge status` then shows.
* may still end `not-run` (another node holds the source's lock), `failed`,
* `lease-lost` (its cluster lease was lost mid-build) or `timed-out` (no page
* finished within the build's bound), which only `os knowledge status` then
* shows.
*
* A build sends the content fields of every row the source's `where` matches,
* except those the index already holds unchanged, to the embedding provider,
Expand Down Expand Up @@ -64,7 +66,7 @@ export default class KnowledgeRebuild extends Command {
const startedBuild = started.details.build as KnowledgeBuildView | null | undefined;
if (!flags.wait) {
// Exit 0 here says "started", never "built": the build can still end
// not-run (another node holds the lock) or failed.
// not-run (another node holds the lock), failed, lease-lost or timed-out.
this.log('Not followed (--no-wait): the build may still not run or fail. Read its outcome with os knowledge status.');
return;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/utils/knowledge-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export interface KnowledgeBuildProgressView {
/** A build record, as the server reports it. */
export interface KnowledgeBuildView {
trigger?: string;
status?: 'running' | 'done' | 'failed' | 'not-run';
status?: 'running' | 'done' | 'failed' | 'not-run' | 'lease-lost' | 'timed-out';
startedAt?: string;
finishedAt?: string;
progress?: KnowledgeBuildProgressView;
Expand Down
Loading
Loading