Skip to content

Commit 4d9d12a

Browse files
fix(service-knowledge): a host-mounted service with no embedder answers a search 503 naming the settings to save (#38817)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBG4YD4RMAt72Ga5PdYYZDAQ)_ Fixes #38775 Clause-②: no Metadata-protocol: none ## 维护者速读 - 自己挂载知识服务、却没配置向量模型的部署,管理员搜索时以前只看到“服务不可用”,现在会看到同样的 503,但附带要保存哪些设置、然后重启。 - 属于知识库检索(RAG)的可用性收尾:让自挂载路径与运行时托管的“暂停”路径给出同一种带补救说明的答复。 - 只影响没配置向量模型的自挂载部署;改动只是给一条已有错误补上错误码,可直接撤回。 - 要你做什么:无。 ## What changes `UnconfiguredEmbedder.refusal()` (`packages/services/service-knowledge/src/knowledge-service-plugin.ts`) now carries ADR-0112 `SERVICE_UNAVAILABLE` / `status: 503`, the code the held path refuses with (ADR-0161 K8, the dated note on item 12). The message is unchanged: it already names the `ai.embedder_*` settings to save under Settings, AI and Embedder, and the restart. Both uses of the stand-in are coded, reading `dimensions` and `embed()`. No error code, settings key or contract member is added. Measured on `origin/main` 0fc9eab (red run before the fix), a host-mounted service with no embedder answered a search in two different wrong ways, depending on the store's shape: - a store that embeds the query inside `search`: refused 503 `SERVICE_UNAVAILABLE` under the platform sentence "source 'docs' could not be searched: its adapter 'vec' failed." The remedy only reached the operator's `error` line. - a store whose `embedding` descriptor reads the embedder's `dimensions` (the shape of the pgvector and turso stores): the planning step (`planIndex`, before any store is asked) threw the stand-in's plain `Error` with no `code` and no `status`. After the fix, both answer 503 `SERVICE_UNAVAILABLE` with the stand-in's own sentence and remedy. ## Tests - New: `packages/services/service-knowledge/src/__tests__/unconfigured-embedder-code-38775.test.ts`, booted the way a host boots it (LiteKernel, `KnowledgeServicePlugin` with no `runtimeComposed`, `SettingsServicePlugin` with nothing saved, a store plugin resolving the kernel's `embedder` service at each call). Six cases: the stand-in is what the boot registers and the service is not held; `dimensions` and `embed()` refused coded with the remedy; `searchWithRefusals` on both store shapes; `search()` never answered empty. - Red before the fix (5 of 6 failed: the 5 code/remedy cases; the "stand-in registered, not held" case passes on both trees, as expected). - Code ablation (`scripts/ablation-replace.mjs`, anchor hit 1 time, so 1 to 0): removing `code: 'SERVICE_UNAVAILABLE'` from the refusal turns 5 of 6 red. Restored to blob `af4477aa5a93`, equal to HEAD, and `git diff HEAD` is empty. - Updated: `knowledge-settings-contribution.test.ts`, case "no settings: boot succeeds, and indexing and search answer an error naming the missing settings". That case pinned the old uncoded path, which put the stand-in's text on an operator `error` line. Now that the refusal is coded, the search round logs that text, remedy included, at `warn`. The assertion and its comment now say `warn`, and nothing else in the file changed. The claim amendment on the card added this file to the surface. <details><summary>Package runs at a9f74fd</summary> - `pnpm --filter @objectstack/service-knowledge exec vitest run --maxWorkers=2`: Test Files 30 passed (30); Tests 885 passed (885). - `pnpm --filter @objectstack/service-knowledge typecheck`: exit 0 (test layer: 0 files, 0 errors in test-typecheck-debt.json). - At 5c8d03a, before the pin update: Tests 1 failed, 884 passed (885). The failure was that pin. </details> ## Acceptance notes - The search round's files (held by another open PR) are untouched. The one existing pin the coded refusal changed, an operator line at `error` that is now `warn`, is updated in this PR under the amended claim. - CI at 5c8d03a showed `TypeScript Type Check` and `Lint & Repo Gates` red. Both were aggregators reading a `cancelled` lane: `Type Check · consumer gates` and `Lint · repo & tooling gates` logged "The operation was canceled." at 01:56:35 and 01:56:47. That was the lint workflow's per-PR concurrency group cancelling the old head's run when a9f74fd was pushed; the new run started at 01:56:34. Neither lane logged a failure before it was cancelled. At a9f74fd both aggregators and both lanes are success. - The pgvector and turso stores read `embedder.dimensions` in their `embedding` getter, so with the stand-in their search is refused while it is planned, not in the search round. The new test pins that shape with a fake store. A live pgvector run is not part of this PR. ## Verification Files to read first, by risk: 1. `packages/services/service-knowledge/src/knowledge-service-plugin.ts`, the `refusal()` hunk. 2. `packages/services/service-knowledge/src/__tests__/unconfigured-embedder-code-38775.test.ts`, the `EmbeddingStorePlugin` fixture. Two-minute check: `pnpm --filter @objectstack/service-knowledge exec vitest run src/__tests__/unconfigured-embedder-code-38775.test.ts`. Expect 6 passed. <details><summary>Local gates at 5c8d03a</summary> `dispatch-gates.mjs --ran`: 74 derived, 72 run, 2 NOT-MEASURED, 0 UNRUN. Every run gate exited 0. NOT MEASURED: `node scripts/check-plugin-teardown-shape.mjs --self-test` (PREREQUISITE NOT MET: a positive control pinned to a commit this shallow clone cannot reach; this is a checker-health self-test only) and `pnpm check:dual-build-cjs-loads` (PREREQUISITE NOT MET: needs every package built). Both are left to CI. At a9f74fd the derived list is the same 74 commands. I re-ran the ratchet and test-reading families there, all exit 0: cross-package-test-inputs, test-source-alias, nul-bytes, issue-citations (both forms), doc-authoring, refd-timer-probe, logger-receiver-detach, rest-log-spy-declared, registry-log-declared, optional-error-sink, comment-mask adoption and corpus, closing-keyword-parity, engine-double-contract, where-matcher, objectql-double-limit, type-check-coverage, query-options-erasure, slot-lookup and type-check-debt. The rest of the list was not re-run, a declared narrowing: the commit changes two lines in one test file. CI at a9f74fd: 39 success, 18 skipped, 0 failure. </details> Signed: repo:objectstack@os-support-ai · os-support-ai · session_01WGufzeatqKfTRUzTJVa9jQ --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzeatqKfTRUzTJVa9jQ)_ <!-- signed: repo:objectstack@os-support-ai · os-support-ai · session_01WGufzeatqKfTRUzTJVa9jQ --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent e5ae93d commit 4d9d12a

4 files changed

Lines changed: 196 additions & 3 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/service-knowledge': patch
3+
---
4+
5+
fix(service-knowledge): a host-mounted knowledge service with no embedder answers a search 503 naming the settings to save
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
When a host mounts `KnowledgeServicePlugin` itself and no embedder is configured, the plugin registers a stand-in embedder. Its refusal now carries ADR-0112 `SERVICE_UNAVAILABLE` (503), the code the held path already answers, on both of its uses: reading `dimensions` and `embed()`. A search on such a host is refused 503 with the stand-in's own sentence, which names the `ai.embedder_*` settings to save under Settings → AI & Embedder and the restart. Before, a store that embeds inside `search` was refused 503 under a platform sentence that named no remedy, so a missing setting read as an outage; a store whose `embedding` descriptor reads the embedder's dimensions threw an error with no code at all while the search was planned. No error code, settings key or contract member is added.

‎packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -618,15 +618,16 @@ describe('#37094 — the open edition registers EMBEDDER_SERVICE from the ai.emb
618618
await expect(indexOne(knowledge, 'hello')).rejects.toThrow(named);
619619
// The adapter's search answers the error; the service's search refuses
620620
// the source (never no hits), and the only source refused refuses the
621-
// whole search. The embedder's own text stays on the operator's line.
621+
// whole search. The embedder's refusal is coded (SERVICE_UNAVAILABLE), so
622+
// the search round logs its own text, remedy included, at `warn`.
622623
await expect(knowledge.getAdapter('vec').search('hello', { source: knowledge.getSource('docs')!, topK: 5 }))
623624
.rejects.toThrow(named);
624625
await expect(knowledge.search('hello', { sourceIds: ['docs'], executionContext: SYSTEM })).rejects.toMatchObject({
625626
code: 'SERVICE_UNAVAILABLE',
626627
status: 503,
627628
refused: [expect.objectContaining({ sourceId: 'docs', code: 'SERVICE_UNAVAILABLE', status: 503 })],
628629
});
629-
expect(lines.some((l) => l.level === 'error' && named.test(l.line))).toBe(true);
630+
expect(lines.some((l) => l.level === 'warn' && named.test(l.line))).toBe(true);
630631
// A vector column cannot be sized from it either.
631632
expect(() => embedder.dimensions).toThrow(named);
632633
expect(requests).toHaveLength(0);
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* A service a host mounts itself with no embedder configured answers a search
5+
* the way the held path does: ADR-0112 `SERVICE_UNAVAILABLE` (503), with the
6+
* stand-in embedder's own sentence, which names the `ai.embedder_*` settings to
7+
* save and the restart. It is never answered as an outage under a platform
8+
* sentence that withholds the remedy, and never answered empty.
9+
*
10+
* The stand-in (`UnconfiguredEmbedder`) codes its refusal at its source, on
11+
* both of its uses: reading `dimensions` and `embed()`. Two store shapes reach
12+
* it on a search, and both are pinned here, booted the way a host boots them —
13+
* `KnowledgeServicePlugin` with no runtime composition, the settings service
14+
* with nothing saved, and a store plugin that resolves the kernel's
15+
* `embedder` service at each call:
16+
*
17+
* - a store whose `embedding` descriptor reads the embedder's `dimensions`
18+
* (the vector stores' shape): the refusal surfaces while the search is
19+
* planned, before any store is asked;
20+
* - a store that embeds the query inside `search`: the refusal surfaces from
21+
* the store's search and is carried by the search round.
22+
*/
23+
24+
import { createHash } from 'node:crypto';
25+
import { describe, it, expect } from 'vitest';
26+
import { LiteKernel } from '@objectstack/core';
27+
import type { Plugin, PluginContext } from '@objectstack/core';
28+
import { EMBEDDER_SERVICE, KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts';
29+
import type { KnowledgeSource } from '@objectstack/spec/ai';
30+
import type { IEmbedder, IKnowledgeAdapter } from '@objectstack/spec/contracts';
31+
import { SettingsServicePlugin, type CryptoAdapter } from '@objectstack/service-settings';
32+
import { KnowledgeServicePlugin } from '../knowledge-service-plugin.js';
33+
import { KnowledgeService } from '../knowledge-service.js';
34+
35+
const SYSTEM = { positions: [], permissions: [], isSystem: true };
36+
37+
/** The settings service stores the embedder key only through an adapter that declares confidentiality. */
38+
class ConfidentialTestAdapter implements CryptoAdapter {
39+
readonly confidential = true;
40+
async encrypt(plaintext: string): Promise<string> {
41+
return 'kms:' + Buffer.from(plaintext, 'utf8').toString('base64');
42+
}
43+
async decrypt(ciphertext: string): Promise<string> {
44+
return Buffer.from(ciphertext.replace(/^kms:/, ''), 'base64').toString('utf8');
45+
}
46+
digest(plaintext: string): string {
47+
return createHash('sha256').update(plaintext).digest('hex');
48+
}
49+
}
50+
51+
type StoreShape = 'descriptor' | 'search-only';
52+
53+
/** A store that calls the kernel's `embedder` service, resolved at each call. */
54+
class EmbeddingStorePlugin implements Plugin {
55+
name = 'test.knowledge.embedding-store';
56+
version = '1.0.0';
57+
type = 'standard' as const;
58+
dependencies = ['com.objectstack.service.knowledge'];
59+
constructor(private readonly shape: StoreShape, private readonly calls: string[]) {}
60+
async init(): Promise<void> {}
61+
async start(ctx: PluginContext): Promise<void> {
62+
const calls = this.calls;
63+
const embedder = () => ctx.getService<IEmbedder>(EMBEDDER_SERVICE);
64+
const adapter: IKnowledgeAdapter = {
65+
id: 'vec',
66+
async upsert() {
67+
calls.push('upsert');
68+
},
69+
async search(query) {
70+
calls.push('search');
71+
await embedder().embed([query]);
72+
return [];
73+
},
74+
async delete() {
75+
calls.push('delete');
76+
},
77+
};
78+
if (this.shape === 'descriptor') {
79+
Object.defineProperty(adapter, 'embedding', {
80+
get: () => ({ dimensions: embedder().dimensions }),
81+
enumerable: true,
82+
});
83+
}
84+
ctx.getService<KnowledgeService>(KNOWLEDGE_SERVICE).registerAdapter('vec', adapter);
85+
}
86+
}
87+
88+
const SOURCES: KnowledgeSource[] = [
89+
{ name: 'docs', label: 'Docs', adapter: 'vec', source: { kind: 'object', object: 'doc', content: ['body'] } },
90+
];
91+
92+
/** A host-mounted service: no `runtimeComposed`, nothing saved under `ai.embedder_*`. */
93+
async function bootHostMounted(shape: StoreShape) {
94+
const calls: string[] = [];
95+
const kernel = new LiteKernel();
96+
kernel.use(new KnowledgeServicePlugin({
97+
enableEventSync: false,
98+
buildAtBoot: false,
99+
reconcile: false,
100+
sources: SOURCES,
101+
}));
102+
kernel.use(new SettingsServicePlugin({ env: {}, registerRoutes: false, crypto: new ConfidentialTestAdapter() }));
103+
kernel.use(new EmbeddingStorePlugin(shape, calls));
104+
await kernel.bootstrap();
105+
const knowledge = kernel.getService<KnowledgeService>(KNOWLEDGE_SERVICE);
106+
const embedder = kernel.getService<IEmbedder>(EMBEDDER_SERVICE);
107+
return { kernel, knowledge, embedder, calls };
108+
}
109+
110+
type Refusal = { code?: string; status?: number; message: string; refused?: Array<{ sourceId: string; code: string; status: number; message: string }> };
111+
112+
const refusalOf = (p: Promise<unknown>): Promise<Refusal | undefined> =>
113+
p.then(() => undefined, (e: unknown) => e as Refusal);
114+
115+
/** The stand-in's sentence: nothing was embedded or sent, the settings to save, and the restart. */
116+
function expectRemedy(message: string | undefined): void {
117+
expect(message).toMatch(/^No embedder is configured, so nothing was embedded and nothing was sent: /);
118+
expect(message).toContain('ai.embedder_provider');
119+
expect(message).toContain('restart');
120+
}
121+
122+
describe('a host-mounted service with no embedder answers like the held path: 503 SERVICE_UNAVAILABLE naming the setting', () => {
123+
it('the stand-in is what the host-mounted boot registers, and it is not held', async () => {
124+
const { knowledge, embedder } = await bootHostMounted('search-only');
125+
expect(embedder.id).toBe('unconfigured');
126+
expect(knowledge.heldReading()).toBeUndefined();
127+
});
128+
129+
it('reading the stand-in\'s dimensions is refused coded, with the remedy', async () => {
130+
const { embedder } = await bootHostMounted('search-only');
131+
let thrown: Refusal | undefined;
132+
try {
133+
void embedder.dimensions;
134+
} catch (e) {
135+
thrown = e as Refusal;
136+
}
137+
expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
138+
expectRemedy(thrown?.message);
139+
});
140+
141+
it('embed() on the stand-in is refused coded, with the remedy; an empty batch still answers empty', async () => {
142+
const { embedder } = await bootHostMounted('search-only');
143+
const thrown = await refusalOf(embedder.embed(['hello']));
144+
expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
145+
expectRemedy(thrown?.message);
146+
await expect(embedder.embed([])).resolves.toEqual([]);
147+
});
148+
149+
it('a store that embeds inside search: the search is refused 503 with the stand-in\'s own sentence, not the platform\'s', async () => {
150+
const { knowledge, calls } = await bootHostMounted('search-only');
151+
const thrown = await refusalOf(knowledge.searchWithRefusals('q', { executionContext: SYSTEM }));
152+
expect(calls).toEqual(['search']);
153+
expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
154+
expect(thrown?.refused).toHaveLength(1);
155+
expect(thrown?.refused?.[0]).toMatchObject({ sourceId: 'docs', code: 'SERVICE_UNAVAILABLE', status: 503 });
156+
expectRemedy(thrown?.refused?.[0].message);
157+
expect(thrown?.refused?.[0].message).not.toContain('could not be searched');
158+
});
159+
160+
it('a store whose descriptor reads dimensions: the search is refused 503 with the remedy before any store is asked', async () => {
161+
const { knowledge, calls } = await bootHostMounted('descriptor');
162+
const thrown = await refusalOf(knowledge.searchWithRefusals('q', { executionContext: SYSTEM }));
163+
expect(calls).toEqual([]);
164+
expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
165+
expectRemedy(thrown?.message);
166+
});
167+
168+
it('search() (no refusal report) is refused the same way, never answered empty', async () => {
169+
const { knowledge } = await bootHostMounted('search-only');
170+
const thrown = await refusalOf(knowledge.search('q', { executionContext: SYSTEM }));
171+
expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
172+
expect(thrown?.message).toContain('ai.embedder_provider');
173+
});
174+
});

‎packages/services/service-knowledge/src/knowledge-service-plugin.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,11 @@ interface EmbedderProvision {
138138
* answers the same error, which names the missing settings and the restart, so
139139
* an adapter that embeds refuses indexing and search with that text instead of
140140
* a bare "service not found". Nothing is sent anywhere.
141+
*
142+
* The error is coded at its source, ADR-0112 `SERVICE_UNAVAILABLE` (503), the
143+
* code the held path refuses with (ADR-0161 K8, the dated note on item 12): a
144+
* search reaching it answers 503 with this sentence and its remedy, never as an
145+
* adapter outage under a platform sentence, and never empty.
141146
*/
142147
class UnconfiguredEmbedder implements IEmbedder {
143148
readonly id = 'unconfigured';
@@ -150,7 +155,10 @@ class UnconfiguredEmbedder implements IEmbedder {
150155
throw this.refusal();
151156
}
152157
private refusal(): Error {
153-
return new Error(`No embedder is configured, so nothing was embedded and nothing was sent: ${this.reason}.`);
158+
return Object.assign(
159+
new Error(`No embedder is configured, so nothing was embedded and nothing was sent: ${this.reason}.`),
160+
{ code: 'SERVICE_UNAVAILABLE', status: 503 },
161+
);
154162
}
155163
}
156164

0 commit comments

Comments
 (0)