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
10 changes: 10 additions & 0 deletions .changeset/37466-knowledge-cli-load-balancer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@objectstack/cli': patch
---

fix(cli): `os knowledge rebuild` and `os knowledge status` give the right answer behind a load balancer

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

A build's record lives in memory on the node running the build. `os knowledge rebuild` used to exit 1 as soon as a progress read landed on another node, although the build continued and could succeed. It now falls back to the index state the store reports: when a build was due before the rebuild and the adapter keeps a store shared between nodes (not `memory`, whose index is per process), the index turning `current` means the build completed (exit 0, without the counts). It reports failure only on the build's own recorded failure, or after `--timeout` seconds (new flag, default 600) of reads that reached no record of the build, saying the build may still be running. `os knowledge rebuild` now also reads the index state once before it starts the build. `os knowledge status` says when the node that answered holds no build record.
45 changes: 34 additions & 11 deletions content/docs/deployment/cli.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -4014,7 +4014,7 @@ nothing about the sources.

| Command | Description |
|---------|-------------|
| `os knowledge status` | Each source's index state (built, never built, due a rebuild) and the last build the answering node ran |
| `os knowledge status` | Each source's index state (built, never built, due a rebuild) and the last build the answering node ran, or that it holds none |
| `os knowledge rebuild` | Start one complete build of a source on the server and follow its progress |

#### `os knowledge status`
Expand All @@ -4027,10 +4027,14 @@ os knowledge status support_articles # one source
Prints, per source, its adapter and kind, its index state against what the
server expects (and whether a build is due), and the last build the node that
answered ran: its progress while it runs, its counts once it ended. A build's
record lives on the node that ran it, so behind a load balancer the node that
answers may not be the one building; the index state is read from the store and
is the same on every node. Exits `1` with the server's refusal text when the
action is refused.
record lives in memory on the node that ran it, so behind a load balancer the
node that answers may not be the one building, and a restarted node remembers
none. When the answering node holds no record, the command says so: a build
run on another node, or before a restart, is not shown. The index state is read
from the store, and is the same on every node when the adapter's store is
shared between nodes (`pgvector`); the `memory` adapter keeps its index in each
process, so there each node answers for its own. Exits `1` with the server's
refusal text when the action is refused.

#### `os knowledge rebuild`

Expand All @@ -4042,12 +4046,30 @@ os knowledge rebuild support_articles --no-wait # start, and return at once
**A build costs money:** every row the source's `where` matches is read, and the
content fields of each one the index does not already hold unchanged are sent to
the embedding provider, which bills for them. The build runs on the server in
the background; the command reads `index_status` every `--interval` seconds and
prints the build's progress until it ends. It exits `0` when the build finished,
and `1` when the server refused the rebuild (an unknown or `file` source, a
build already running on that node), when the build did not run or did not
finish, or when the progress was answered by another node than the one
building (the build continues there). `--no-wait` exits `0` once the build has
the background; the command reads the index state once before it starts the
build, then reads `index_status` every `--interval` seconds and prints the
build's progress until it ends.

Behind a load balancer a progress read can land on a node that is not running
the build and holds no record of it. That read is not a failure: the command
falls back to the index state, which the store reports and which is the same on
every node when the adapter's store is shared between nodes. When a build was
due before the rebuild (never built, a new fingerprint, a changed recipe), the
index turning `current` means a complete build recorded itself, and the command
exits `0` without the build's counts. When no build was due (the index already
`current`, or unreadable), the state cannot show when the build ends, and the
command keeps polling until a read reaches the node running the build. On the
`memory` adapter, whose index lives in each process, the index state is never
read as the build's end: only the building node's record answers.

It exits `0` when the build finished (its record says done, or the index turned
`current`), and `1` when the server refused the rebuild (an unknown or `file`
source, a build already running on that node), when the build's record says it
did not run or did not finish, or when `--timeout` seconds of reads (counted as
reads times `--interval`) reached no record of the build and did not see the
index turn `current`; it then says the build may still be running and points
at `os knowledge status`. A read that reaches the build's record starts the
timeout again. `--no-wait` exits `0` once the build has
started and reports no outcome: the build can still end without running
(another node holds the source's lock) or fail, which only `os knowledge status`
then shows.
Expand All @@ -4058,6 +4080,7 @@ then shows.
| `-t, --token <token>` | both | `OS_TOKEN` | Bearer token of an administrator |
| `--no-wait` | `rebuild` | — | Return once the build has started; its outcome is not reported |
| `--interval <s>` | `rebuild` | — | Seconds between two progress reads (default `2`) |
| `--timeout <s>` | `rebuild` | — | Seconds of reads that reach no record of the build before it stops following and exits `1` (default `600`) |

### Skills

Expand Down
166 changes: 145 additions & 21 deletions packages/cli/src/commands/knowledge/knowledge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@
* the route it calls, the payload it sends, that it follows a started build
* to its end, and that a build which did not finish exits 1.
*
* Behind a load balancer a progress read can land on a node that holds no
* record of the build (the record lives in memory on the node running it):
* `nodeWithoutRecord` answers such a poll. The command then reads the
* store's index state (the same on every node for a shared store; never
* read as the build's end on the per-process `memory` adapter), and never
* exits 1 for the poll alone.
*
* The oclif `Config` is loaded at module scope, as in
* `commands/datasource/envelope-unwrap.test.ts` (whose header says why).
*/
Expand Down Expand Up @@ -94,31 +101,40 @@ const running = (discovered: number) => ({
trigger: 'operator', status: 'running', startedAt: STARTED_AT,
progress: { pages: 1, discovered, indexed: discovered, skipped: 0, failed: 0 },
});
const statusOf = (build: unknown) => ok({
const CURRENT = { state: 'current', due: false, detail: 'current.' };
const NEVER_BUILT = { state: 'nothing', due: true, detail: 'never built.' };
const UNREADABLE = { state: 'unreadable', due: false, detail: 'reading the adapter failed: connection reset.' };
const statusOf = (build: unknown, index: unknown = CURRENT, adapter = 'pgvector') => ok({
ok: true,
message: '1 source(s)',
details: { sources: [{ id: 'kb', label: 'KB', adapter: 'pgvector', kind: 'object', index: { state: 'current', due: false, detail: 'current.' }, build }] },
details: { sources: [{ id: 'kb', label: 'KB', adapter, kind: 'object', index, build }] },
});
/** A poll answered by a node that is not running this build: no record there. */
const nodeWithoutRecord = (index: unknown) => statusOf(null, index);
const done = {
...running(250),
status: 'done',
finishedAt: '2026-11-26T05:01:00.000Z',
progress: { pages: 3, discovered: 250, indexed: 240, skipped: 10, failed: 0 },
result: { ok: true, discovered: 250, indexed: 240, skipped: 10, purged: 2, failed: 0 },
};

const target = ['--url', SERVER, '--token', 'tok'];

describe('os knowledge rebuild', () => {
it('starts the rebuild through the settings action door and follows it to its end', async () => {
const run = await drive(KnowledgeRebuild, ['kb', ...target], [
statusOf(null),
ok({ ok: true, message: "Rebuild of source 'kb' started.", details: { source: 'kb', build: running(0) } }),
statusOf(running(100)),
statusOf({
...running(250),
status: 'done',
finishedAt: '2026-11-26T05:01:00.000Z',
progress: { pages: 3, discovered: 250, indexed: 240, skipped: 10, failed: 0 },
result: { ok: true, discovered: 250, indexed: 240, skipped: 10, purged: 2, failed: 0 },
}),
statusOf(done),
]);

expect(run.failure).toBeUndefined();
expect(run.requests[0]).toEqual({ url: `${SERVER}/api/settings/knowledge/rebuild`, body: { source: 'kb' }, auth: 'Bearer tok' });
expect(run.requests.slice(1).map((r) => [r.url, r.body])).toEqual([
// The index state is read once before the rebuild: the baseline a poll on another node is judged against.
expect(run.requests[0]).toEqual({ url: `${SERVER}/api/settings/knowledge/index_status`, body: { source: 'kb' }, auth: 'Bearer tok' });
expect(run.requests[1]).toEqual({ url: `${SERVER}/api/settings/knowledge/rebuild`, body: { source: 'kb' }, auth: 'Bearer tok' });
expect(run.requests.slice(2).map((r) => [r.url, r.body])).toEqual([
[`${SERVER}/api/settings/knowledge/index_status`, { source: 'kb' }],
[`${SERVER}/api/settings/knowledge/index_status`, { source: 'kb' }],
]);
Expand All @@ -130,25 +146,131 @@ describe('os knowledge rebuild', () => {

it('exits 1 when the build did not finish', async () => {
const run = await drive(KnowledgeRebuild, ['kb', ...target], [
statusOf(null),
ok({ ok: true, details: { source: 'kb', build: running(0) } }),
statusOf({ ...running(10), status: 'failed', finishedAt: STARTED_AT, message: 'the adapter upsert failed: quota' }),
]);
expect(run.failure).toMatchObject({ message: 'the adapter upsert failed: quota', exit: 1 });
});

it('exits 1 with the server refusal text, and asks nothing more', async () => {
const run = await drive(KnowledgeRebuild, ['kb', ...target], [refused('A build of source \'kb\' is already running on this node.')]);
expect(run.failure).toMatchObject({ message: "A build of source 'kb' is already running on this node.", exit: 1 });
expect(run.requests).toHaveLength(1);
});

it('says so when the progress is answered by a node that is not running this build', async () => {
const run = await drive(KnowledgeRebuild, ['kb', ...target], [
ok({ ok: true, details: { source: 'kb', build: running(0) } }),
statusOf(null),
refused('A build of source \'kb\' is already running on this node.'),
]);
expect(run.failure?.exit).toBe(1);
expect(run.failure?.message).toContain('not running this build');
expect(run.failure).toMatchObject({ message: "A build of source 'kb' is already running on this node.", exit: 1 });
expect(run.requests).toHaveLength(2);
});

describe('a poll that lands on a node without the build record (behind a load balancer)', () => {
it('keeps following while the build is still running, and does not exit 1', async () => {
const run = await drive(KnowledgeRebuild, ['kb', ...target], [
nodeWithoutRecord(NEVER_BUILT),
ok({ ok: true, details: { source: 'kb', build: running(0) } }),
nodeWithoutRecord(NEVER_BUILT),
statusOf(running(100), NEVER_BUILT),
nodeWithoutRecord(NEVER_BUILT),
statusOf(done),
]);
expect(run.failure).toBeUndefined();
expect(run.requests).toHaveLength(6);
const text = run.logs.join('\n');
expect(text).toContain("answered by a node that is not running this build; the store's index state: nothing");
expect(text).toContain('done (operator, ended 2026-11-26T05:01:00.000Z)');
});

it('exits 0 once the store reports the index current after the build succeeded', async () => {
const run = await drive(KnowledgeRebuild, ['kb', ...target], [
nodeWithoutRecord(NEVER_BUILT),
ok({ ok: true, details: { source: 'kb', build: running(0) } }),
nodeWithoutRecord(NEVER_BUILT),
nodeWithoutRecord(CURRENT),
]);
expect(run.failure).toBeUndefined();
expect(run.requests).toHaveLength(4);
expect(run.logs.join('\n')).toContain('The index is current');
});

it('reads a record of an older build on the answering node as no record of this one', async () => {
const older = { ...done, startedAt: '2026-11-25T00:00:00.000Z' };
const run = await drive(KnowledgeRebuild, ['kb', ...target], [
nodeWithoutRecord(NEVER_BUILT),
ok({ ok: true, details: { source: 'kb', build: running(0) } }),
statusOf(older, NEVER_BUILT),
nodeWithoutRecord(CURRENT),
]);
expect(run.failure).toBeUndefined();
expect(run.logs.join('\n')).not.toContain('ended 2026-11-25');
});

it('does not read an index that was already current as done; waits for the building node', async () => {
const run = await drive(KnowledgeRebuild, ['kb', ...target], [
nodeWithoutRecord(CURRENT),
ok({ ok: true, details: { source: 'kb', build: running(0) } }),
nodeWithoutRecord(CURRENT),
nodeWithoutRecord(CURRENT),
statusOf({ ...done, status: 'failed', message: 'the adapter upsert failed: quota' }),
]);
// Only the recorded failure, read on the node that ran the build, exits 1.
expect(run.failure).toMatchObject({ message: 'the adapter upsert failed: quota', exit: 1 });
expect(run.requests).toHaveLength(5);
expect(run.logs.join('\n')).toContain('a build was not due before this rebuild');
});

it('does not read an unreadable baseline as a due build: a current index elsewhere is no exit 0', async () => {
// A transient adapter error on the baseline read answers `unreadable`
// (due: false). The index then reads `current` on another node because a
// same-fingerprint rebuild never leaves it; that is not this build's end.
const run = await drive(KnowledgeRebuild, ['kb', '--interval', '2', '--timeout', '4', ...target], [
nodeWithoutRecord(UNREADABLE),
ok({ ok: true, details: { source: 'kb', build: running(0) } }),
nodeWithoutRecord(CURRENT),
nodeWithoutRecord(CURRENT),
]);
expect(run.failure?.exit).toBe(1);
expect(run.failure?.message).toContain('Stopped following after 4s');
expect(run.logs.join('\n')).not.toContain('The index is current');
});

it('never reads the per-process memory adapter\'s index as this build\'s end; waits for the building node', async () => {
const run = await drive(KnowledgeRebuild, ['kb', ...target], [
statusOf(null, NEVER_BUILT, 'memory'),
ok({ ok: true, details: { source: 'kb', build: running(0) } }),
statusOf(null, CURRENT, 'memory'),
statusOf(done, CURRENT, 'memory'),
]);
expect(run.failure).toBeUndefined();
expect(run.requests).toHaveLength(4);
const text = run.logs.join('\n');
expect(text).not.toContain('The index is current');
expect(text).toContain('the memory adapter keeps its index per process');
expect(text).toContain('done (operator, ended 2026-11-26T05:01:00.000Z)');
});

it('exits 1 after --timeout seconds of polls that reach no record, and says the build may still run', async () => {
const run = await drive(KnowledgeRebuild, ['kb', '--interval', '2', '--timeout', '4', ...target], [
nodeWithoutRecord(NEVER_BUILT),
ok({ ok: true, details: { source: 'kb', build: running(0) } }),
nodeWithoutRecord(NEVER_BUILT),
nodeWithoutRecord(NEVER_BUILT),
]);
expect(run.failure?.exit).toBe(1);
expect(run.failure?.message).toContain('Stopped following after 4s');
expect(run.failure?.message).toContain('may still be running');
expect(run.requests).toHaveLength(4);
});

it('starts the timeout again each time a read reaches the build record', async () => {
const run = await drive(KnowledgeRebuild, ['kb', '--interval', '2', '--timeout', '4', ...target], [
nodeWithoutRecord(NEVER_BUILT),
ok({ ok: true, details: { source: 'kb', build: running(0) } }),
nodeWithoutRecord(NEVER_BUILT),
statusOf(running(50), NEVER_BUILT),
nodeWithoutRecord(NEVER_BUILT),
statusOf(done),
]);
expect(run.failure).toBeUndefined();
});
});

it('--no-wait returns once the build has started, and says its outcome is not reported', async () => {
Expand Down Expand Up @@ -180,7 +302,9 @@ describe('os knowledge status', () => {
const text = run.logs.join('\n');
expect(text).toContain('kb (KB; adapter pgvector, object source)');
expect(text).toContain('index: nothing — a build is due — never built.');
expect(text).toContain('last build on this node: none');
expect(text).toContain('last build on the node that answered: none recorded there');
expect(text).toContain('a build run on another node');
expect(text).toContain('not on the memory adapter');
});

it('exits 1 with the server refusal text', async () => {
Expand Down
Loading
Loading