Skip to content
Merged
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/38775-unconfigured-embedder-coded-refusal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@objectstack/service-knowledge': patch
---

fix(service-knowledge): a host-mounted knowledge service with no embedder answers a search 503 naming the settings to save

Clause-②: no
Metadata-protocol: none

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.
Original file line number Diff line number Diff line change
Expand Up @@ -618,15 +618,16 @@ describe('#37094 — the open edition registers EMBEDDER_SERVICE from the ai.emb
await expect(indexOne(knowledge, 'hello')).rejects.toThrow(named);
// The adapter's search answers the error; the service's search refuses
// the source (never no hits), and the only source refused refuses the
// whole search. The embedder's own text stays on the operator's line.
// whole search. The embedder's refusal is coded (SERVICE_UNAVAILABLE), so
// the search round logs its own text, remedy included, at `warn`.
await expect(knowledge.getAdapter('vec').search('hello', { source: knowledge.getSource('docs')!, topK: 5 }))
.rejects.toThrow(named);
await expect(knowledge.search('hello', { sourceIds: ['docs'], executionContext: SYSTEM })).rejects.toMatchObject({
code: 'SERVICE_UNAVAILABLE',
status: 503,
refused: [expect.objectContaining({ sourceId: 'docs', code: 'SERVICE_UNAVAILABLE', status: 503 })],
});
expect(lines.some((l) => l.level === 'error' && named.test(l.line))).toBe(true);
expect(lines.some((l) => l.level === 'warn' && named.test(l.line))).toBe(true);
// A vector column cannot be sized from it either.
expect(() => embedder.dimensions).toThrow(named);
expect(requests).toHaveLength(0);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* A service a host mounts itself with no embedder configured answers a search
* the way the held path does: ADR-0112 `SERVICE_UNAVAILABLE` (503), with the
* stand-in embedder's own sentence, which names the `ai.embedder_*` settings to
* save and the restart. It is never answered as an outage under a platform
* sentence that withholds the remedy, and never answered empty.
*
* The stand-in (`UnconfiguredEmbedder`) codes its refusal at its source, on
* both of its uses: reading `dimensions` and `embed()`. Two store shapes reach
* it on a search, and both are pinned here, booted the way a host boots them —
* `KnowledgeServicePlugin` with no runtime composition, the settings service
* with nothing saved, and a store plugin that resolves the kernel's
* `embedder` service at each call:
*
* - a store whose `embedding` descriptor reads the embedder's `dimensions`
* (the vector stores' shape): the refusal surfaces while the search is
* planned, before any store is asked;
* - a store that embeds the query inside `search`: the refusal surfaces from
* the store's search and is carried by the search round.
*/

import { createHash } from 'node:crypto';
import { describe, it, expect } from 'vitest';
import { LiteKernel } from '@objectstack/core';
import type { Plugin, PluginContext } from '@objectstack/core';
import { EMBEDDER_SERVICE, KNOWLEDGE_SERVICE } from '@objectstack/spec/contracts';
import type { KnowledgeSource } from '@objectstack/spec/ai';
import type { IEmbedder, IKnowledgeAdapter } from '@objectstack/spec/contracts';
import { SettingsServicePlugin, type CryptoAdapter } from '@objectstack/service-settings';
import { KnowledgeServicePlugin } from '../knowledge-service-plugin.js';
import { KnowledgeService } from '../knowledge-service.js';

const SYSTEM = { positions: [], permissions: [], isSystem: true };

/** The settings service stores the embedder key only through an adapter that declares confidentiality. */
class ConfidentialTestAdapter implements CryptoAdapter {
readonly confidential = true;
async encrypt(plaintext: string): Promise<string> {
return 'kms:' + Buffer.from(plaintext, 'utf8').toString('base64');
}
async decrypt(ciphertext: string): Promise<string> {
return Buffer.from(ciphertext.replace(/^kms:/, ''), 'base64').toString('utf8');
}
digest(plaintext: string): string {
return createHash('sha256').update(plaintext).digest('hex');
}
}

type StoreShape = 'descriptor' | 'search-only';

/** A store that calls the kernel's `embedder` service, resolved at each call. */
class EmbeddingStorePlugin implements Plugin {
name = 'test.knowledge.embedding-store';
version = '1.0.0';
type = 'standard' as const;
dependencies = ['com.objectstack.service.knowledge'];
constructor(private readonly shape: StoreShape, private readonly calls: string[]) {}
async init(): Promise<void> {}
async start(ctx: PluginContext): Promise<void> {
const calls = this.calls;
const embedder = () => ctx.getService<IEmbedder>(EMBEDDER_SERVICE);
const adapter: IKnowledgeAdapter = {
id: 'vec',
async upsert() {
calls.push('upsert');
},
async search(query) {
calls.push('search');
await embedder().embed([query]);
return [];
},
async delete() {
calls.push('delete');
},
};
if (this.shape === 'descriptor') {
Object.defineProperty(adapter, 'embedding', {
get: () => ({ dimensions: embedder().dimensions }),
enumerable: true,
});
}
ctx.getService<KnowledgeService>(KNOWLEDGE_SERVICE).registerAdapter('vec', adapter);
}
}

const SOURCES: KnowledgeSource[] = [
{ name: 'docs', label: 'Docs', adapter: 'vec', source: { kind: 'object', object: 'doc', content: ['body'] } },
];

/** A host-mounted service: no `runtimeComposed`, nothing saved under `ai.embedder_*`. */
async function bootHostMounted(shape: StoreShape) {
const calls: string[] = [];
const kernel = new LiteKernel();
kernel.use(new KnowledgeServicePlugin({
enableEventSync: false,
buildAtBoot: false,
reconcile: false,
sources: SOURCES,
}));
kernel.use(new SettingsServicePlugin({ env: {}, registerRoutes: false, crypto: new ConfidentialTestAdapter() }));
kernel.use(new EmbeddingStorePlugin(shape, calls));
await kernel.bootstrap();
const knowledge = kernel.getService<KnowledgeService>(KNOWLEDGE_SERVICE);
const embedder = kernel.getService<IEmbedder>(EMBEDDER_SERVICE);
return { kernel, knowledge, embedder, calls };
}

type Refusal = { code?: string; status?: number; message: string; refused?: Array<{ sourceId: string; code: string; status: number; message: string }> };

const refusalOf = (p: Promise<unknown>): Promise<Refusal | undefined> =>
p.then(() => undefined, (e: unknown) => e as Refusal);

/** The stand-in's sentence: nothing was embedded or sent, the settings to save, and the restart. */
function expectRemedy(message: string | undefined): void {
expect(message).toMatch(/^No embedder is configured, so nothing was embedded and nothing was sent: /);
expect(message).toContain('ai.embedder_provider');
expect(message).toContain('restart');
}

describe('a host-mounted service with no embedder answers like the held path: 503 SERVICE_UNAVAILABLE naming the setting', () => {
it('the stand-in is what the host-mounted boot registers, and it is not held', async () => {
const { knowledge, embedder } = await bootHostMounted('search-only');
expect(embedder.id).toBe('unconfigured');
expect(knowledge.heldReading()).toBeUndefined();
});

it('reading the stand-in\'s dimensions is refused coded, with the remedy', async () => {
const { embedder } = await bootHostMounted('search-only');
let thrown: Refusal | undefined;
try {
void embedder.dimensions;
} catch (e) {
thrown = e as Refusal;
}
expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
expectRemedy(thrown?.message);
});

it('embed() on the stand-in is refused coded, with the remedy; an empty batch still answers empty', async () => {
const { embedder } = await bootHostMounted('search-only');
const thrown = await refusalOf(embedder.embed(['hello']));
expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
expectRemedy(thrown?.message);
await expect(embedder.embed([])).resolves.toEqual([]);
});

it('a store that embeds inside search: the search is refused 503 with the stand-in\'s own sentence, not the platform\'s', async () => {
const { knowledge, calls } = await bootHostMounted('search-only');
const thrown = await refusalOf(knowledge.searchWithRefusals('q', { executionContext: SYSTEM }));
expect(calls).toEqual(['search']);
expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
expect(thrown?.refused).toHaveLength(1);
expect(thrown?.refused?.[0]).toMatchObject({ sourceId: 'docs', code: 'SERVICE_UNAVAILABLE', status: 503 });
expectRemedy(thrown?.refused?.[0].message);
expect(thrown?.refused?.[0].message).not.toContain('could not be searched');
});

it('a store whose descriptor reads dimensions: the search is refused 503 with the remedy before any store is asked', async () => {
const { knowledge, calls } = await bootHostMounted('descriptor');
const thrown = await refusalOf(knowledge.searchWithRefusals('q', { executionContext: SYSTEM }));
expect(calls).toEqual([]);
expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
expectRemedy(thrown?.message);
});

it('search() (no refusal report) is refused the same way, never answered empty', async () => {
const { knowledge } = await bootHostMounted('search-only');
const thrown = await refusalOf(knowledge.search('q', { executionContext: SYSTEM }));
expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
expect(thrown?.message).toContain('ai.embedder_provider');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,11 @@ interface EmbedderProvision {
* answers the same error, which names the missing settings and the restart, so
* an adapter that embeds refuses indexing and search with that text instead of
* a bare "service not found". Nothing is sent anywhere.
*
* The error is coded at its source, ADR-0112 `SERVICE_UNAVAILABLE` (503), the
* code the held path refuses with (ADR-0161 K8, the dated note on item 12): a
* search reaching it answers 503 with this sentence and its remedy, never as an
* adapter outage under a platform sentence, and never empty.
*/
class UnconfiguredEmbedder implements IEmbedder {
readonly id = 'unconfigured';
Expand All @@ -150,7 +155,10 @@ class UnconfiguredEmbedder implements IEmbedder {
throw this.refusal();
}
private refusal(): Error {
return new Error(`No embedder is configured, so nothing was embedded and nothing was sent: ${this.reason}.`);
return Object.assign(
new Error(`No embedder is configured, so nothing was embedded and nothing was sent: ${this.reason}.`),
{ code: 'SERVICE_UNAVAILABLE', status: 503 },
);
}
}

Expand Down
Loading