Skip to content
Merged
24 changes: 24 additions & 0 deletions .changeset/38728-uncoded-search-throw.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
'@objectstack/service-knowledge': patch
'@objectstack/spec': patch
---

fix(service-knowledge)!: a source whose adapter's search throws without a code is refused, never answered as no hits

Clause-②: no (narrowing)
Metadata-protocol: none

<!-- adr-0087: registered knowledge-search-uncoded-adapter-throw-refused -->

**BREAKING** for a caller of a knowledge search (the `search_knowledge` tool, its MCP HTTP and stdio faces, and in-process `KnowledgeService.search` / `searchWithRefusals`) when a source's adapter throws from `search` with an error that does not carry both an ADR-0112 `code` and `status` (an embedder that cannot be reached, a timeout outside the store). The search now names that source in `refused`, coded `SERVICE_UNAVAILABLE` (503), with a platform sentence naming the source; before, the source read as if it had matched nothing. The thrown message is not shown to the caller (it can carry hosts, SQL or keys); the operator's `error` log line keeps it, as before. Sources that answer are still served beside the refusal. A source that matches nothing is unchanged, and so is a coded refusal's own `refused` entry; a whole rejection that also names an uncoded throw may take that throw's top-level code (cell 2 below).

## FROM → TO

- No searched source answers and at least one threw without a code — two cells:
1. Every searched source throws without a code (one source, or several failing on the same embedder outage). FROM: the search succeeded with `{ hits: [] }`. TO: the search is rejected `SERVICE_UNAVAILABLE` / 503 with `refused` naming each source (the `search_knowledge` executor and in-process `search` reject with `refused`; MCP answers an error result whose envelope is `code`, `message` and `status`, the sources named in the message).
2. A source throws without a code beside a source refused with a code, none answering. FROM: rejected with the coded source's `code` / `status` and `refused` naming it alone. TO: `refused` names both, and the rejection's top-level `code` / `status` are the first refusal's in source order, so a 409 `KNOWLEDGE_REBUILD_REQUIRED` rejection may now read 503 `SERVICE_UNAVAILABLE`.
- A refill fails without a code. FROM: the source's round-one survivors were served. TO: they are dropped and the source is refused for the whole search, as a coded refusal of the refill already was.

A caller reads `refused` (each source's own `code`, not only the top-level one) and the 503 instead of treating an empty answer as no match. An operator repairs the adapter or embedder the `error` line names.

`@objectstack/spec` adds only the upgrade-guide entry `knowledge-search-uncoded-adapter-throw-refused`.
11 changes: 8 additions & 3 deletions packages/plugins/knowledge-pgvector/bench/instrument.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -203,14 +203,19 @@ describe('bench instrument — segment seams over the real adapter and service',
expect(extractRankingWhere('WITH cand AS (SELECT chunk_id, 0 AS distance FROM t WHERE x)', ['a', 1, 5])).toBeUndefined();
});

it('a failed embed is counted, and the search answers no hit with the service\'s "search failed" line', async () => {
it('a failed embed is counted, and the search is refused SERVICE_UNAVAILABLE naming the source, with the service\'s "search failed" line', async () => {
const { search, errors } = setup({ failEmbed: true });
const outcome = await search({ query: 'leave policy', topK: TOP_K }, CALLER);
const s = summarizeRecord(outcome);
expect(s.embedFailures).toBe(1);
expect(s.calls.ranking).toBe(0);
expect(s.ok).toBe(true);
expect(s.hits).toBe(0);
expect(s.ok).toBe(false);
expect(s.errorCode).toBe('SERVICE_UNAVAILABLE');
expect(outcome.error).toMatchObject({
code: 'SERVICE_UNAVAILABLE',
status: 503,
refused: [expect.objectContaining({ sourceId: 'clauses', code: 'SERVICE_UNAVAILABLE', status: 503 })],
});
expect(errors.filter((m) => /search failed/.test(m))).toHaveLength(1);
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1533,14 +1533,19 @@ describe('KnowledgeService — search refills after the permission filter', () =
expect(asked()).toEqual([['s1', 15], ['s2', 15], ['s1', 60]]);
});

it('a refill the adapter fails keeps the source\'s round-one survivors', async () => {
it('a refill the adapter fails without a code refuses the source, as a coded refusal of the refill does', async () => {
const { svc, adapter } = setup({ s1: rankedHits('s1', 100) }, ['rec_2']);
const first = adapter.searchSpy.getMockImplementation()!;
adapter.searchSpy.mockImplementationOnce(first).mockImplementationOnce(async () => {
throw new Error('store unavailable');
});
const out = await svc.search('q', { topK: 5, executionContext: MEMBER });
expect(out.map((h) => h.sourceRecordId)).toEqual(['rec_2']);
// The only source refused the refill: its round-one survivors are dropped
// and the search is refused whole, never answered with a partial read.
await expect(svc.search('q', { topK: 5, executionContext: MEMBER })).rejects.toMatchObject({
code: 'SERVICE_UNAVAILABLE',
status: 503,
refused: [expect.objectContaining({ sourceId: 's1', code: 'SERVICE_UNAVAILABLE', status: 503 })],
});
expect(adapter.searchSpy).toHaveBeenCalledTimes(2);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -616,11 +616,16 @@ describe('#37094 — the open edition registers EMBEDDER_SERVICE from the ai.emb
const named = /No embedder is configured[\s\S]*ai\.embedder_provider[\s\S]*restart/;

await expect(indexOne(knowledge, 'hello')).rejects.toThrow(named);
// The adapter's search answers the error; the service's search reports it
// per source and answers no hits.
// 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.
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 })).resolves.toEqual([]);
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);
// A vector column cannot be sized from it either.
expect(() => embedder.dimensions).toThrow(named);
Expand Down Expand Up @@ -740,7 +745,12 @@ describe('#37094 — the open edition registers EMBEDDER_SERVICE from the ai.emb
(err: unknown) => err as Error,
);
expect(failure.message).not.toContain(API_KEY);
await rejected.knowledge.search('hello', { sourceIds: ['docs'], executionContext: SYSTEM });
const searched = await rejected.knowledge.search('hello', { sourceIds: ['docs'], executionContext: SYSTEM }).then(
() => { throw new Error('expected a refusal'); },
(err: unknown) => err as Error & { code?: string; status?: number },
);
expect(searched).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
expect(searched.message).not.toContain(API_KEY);
expect(requests.length).toBeGreaterThan(0);
expect(rejected.lines.filter((l) => l.line.includes(API_KEY))).toEqual([]);
});
Expand Down Expand Up @@ -1061,7 +1071,11 @@ describe('[ADR-0161 K8, note on item 12] a runtime-composed knowledge service is
expect(heldLines()).toEqual([]);
expect(knowledge.knowledgeTools().definitions.map((d) => d.name)).toEqual(['search_knowledge']);
expect(lines.some((l) => l.level === 'info' && l.line.includes('no embedder is configured ('))).toBe(true);
await expect(knowledge.search('granite', { sourceIds: ['docs'], executionContext: SYSTEM })).resolves.toEqual([]);
await expect(knowledge.search('granite', { sourceIds: ['docs'], executionContext: SYSTEM })).rejects.toMatchObject({
code: 'SERVICE_UNAVAILABLE',
status: 503,
refused: [expect.objectContaining({ sourceId: 'docs', code: 'SERVICE_UNAVAILABLE', status: 503 })],
});
expect(calls).toContain('search');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -258,11 +258,14 @@ describe('search_knowledge — a refused source (ADR-0161 K7, rule 5)', () => {
});
});

it('control: a failure without a code is logged and skipped as before, and carries no refused list', async () => {
it('a failure without a code refuses its source as SERVICE_UNAVAILABLE, its own text withheld — never no hits', async () => {
const answer = await createKnowledgeTools(twoSources(['policy_clauses'], () => new Error('socket hang up')))
.searchKnowledge({ query: 'q' }, caller);
expect(answer.hits.map((h) => h.sourceId)).toEqual(['faq']);
expect(answer).not.toHaveProperty('refused');
expect(answer.refused).toEqual([
{ sourceId: 'policy_clauses', code: 'SERVICE_UNAVAILABLE', message: expect.stringContaining("source 'policy_clauses'") },
]);
expect(answer.refused?.[0].message).not.toContain('socket hang up');
});

it('an answer with nothing refused carries no refused list', async () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.

// An adapter whose `search` throws without both an ADR-0112 `code` and `status` (an embedder that
// cannot be reached, a timeout outside the store) is refused for that source,
// never answered as zero hits: the caller reads a `refused` entry naming the
// source, coded SERVICE_UNAVAILABLE (503), under a platform sentence; the
// thrown message reaches the operator's `error` line only.

import { describe, it, expect, vi } from 'vitest';
import { KnowledgeService, SEARCH_FIRST_ROUND_FACTOR } from '../knowledge-service.js';
import type { IKnowledgeAdapter } from '@objectstack/spec/contracts';
import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai';

const SYSTEM = { positions: [], permissions: [], isSystem: true };
const INTERNAL = 'embedder down at http://10.0.0.7:11434 (key sk-secret)';

function source(name: string, adapter: string): KnowledgeSource {
return {
name,
label: name,
adapter,
source: { kind: 'object', object: 'task', content: ['title'], metadataFields: ['status'] } as ObjectKnowledgeSource,
};
}

function hit(sourceId: string, record: string, n = 0, score = 0.9): KnowledgeHit {
return { chunkId: `${sourceId}:${record}#${n}`, documentId: `${sourceId}:${record}`, sourceId, sourceRecordId: record, score, snippet: 'ok' };
}

function adapter(id: string, search: IKnowledgeAdapter['search']): IKnowledgeAdapter {
return { id, upsert: vi.fn(async () => undefined), delete: vi.fn(async () => undefined), search: vi.fn(search) };
}

function setup(adapters: IKnowledgeAdapter[]) {
const logger = { debug: vi.fn(), warn: vi.fn(), error: vi.fn() };
const svc = new KnowledgeService({ logger: logger as never });
for (const a of adapters) {
svc.registerAdapter(a.id, a);
svc.registerSource(source(a.id, a.id));
}
return { svc, logger };
}

describe('knowledge search: an adapter throw without a code is refused for its source, never zero hits', () => {
it('a plain Error from search: one refused entry naming the source, SERVICE_UNAVAILABLE / 503; other sources still served', async () => {
const { svc, logger } = setup([
adapter('failing', async () => { throw new Error(INTERNAL); }),
adapter('answering', async () => [hit('answering', 'r1')]),
]);
const report = await svc.searchWithRefusals('q', { executionContext: SYSTEM });
expect(report.hits.map((h) => h.documentId)).toEqual(['answering:r1']);
expect(report.refused).toHaveLength(1);
expect(report.refused[0]).toMatchObject({ sourceId: 'failing', code: 'SERVICE_UNAVAILABLE', status: 503 });
// The caller's sentence names the source; the thrown text stays with the operator.
expect(report.refused[0].message).toContain("source 'failing'");
expect(report.refused[0].message).not.toContain('10.0.0.7');
expect(report.refused[0].message).not.toContain('sk-secret');
expect(logger.error.mock.calls.some(([line]) => String(line).includes(INTERNAL))).toBe(true);
});

it('the only source throws uncoded: the search is refused whole, SERVICE_UNAVAILABLE / 503, not answered empty', async () => {
const { svc } = setup([adapter('failing', async () => { throw new Error(INTERNAL); })]);
const thrown = await svc.searchWithRefusals('q', { executionContext: SYSTEM }).then(
() => undefined,
(e: unknown) => e as { code?: string; status?: number; message: string; refused?: Array<{ sourceId: string; code: string }> },
);
expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
expect(thrown?.refused).toEqual([expect.objectContaining({ sourceId: 'failing', code: 'SERVICE_UNAVAILABLE', status: 503 })]);
expect(thrown?.message).not.toContain('sk-secret');
});

it('every searched source throws uncoded (an embedder outage): refused whole, 503, refused naming each', async () => {
const { svc } = setup([
adapter('first', async () => { throw new Error(INTERNAL); }),
adapter('second', async () => { throw new Error(INTERNAL); }),
]);
const thrown = await svc.searchWithRefusals('q', { executionContext: SYSTEM }).then(
() => undefined,
(e: unknown) => e as { code?: string; status?: number; message: string; refused?: Array<{ sourceId: string; code: string }> },
);
expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
expect(thrown?.refused?.map((r) => [r.sourceId, r.code])).toEqual([
['first', 'SERVICE_UNAVAILABLE'],
['second', 'SERVICE_UNAVAILABLE'],
]);
expect(thrown?.message).not.toContain('sk-secret');
});

it('an uncoded throw beside a coded refusal, none answering: refused names both, top-level code is the first in source order', async () => {
const { svc } = setup([
adapter('failing', async () => { throw new Error(INTERNAL); }),
adapter('refusing', async () => {
throw Object.assign(new Error("Knowledge source 'refusing' needs a rebuild."), { code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409 });
}),
]);
const thrown = await svc.searchWithRefusals('q', { executionContext: SYSTEM }).then(
() => undefined,
(e: unknown) => e as { code?: string; status?: number; message: string; refused?: Array<{ sourceId: string; code: string; status: number }> },
);
expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
expect(thrown?.refused?.map((r) => [r.sourceId, r.code, r.status])).toEqual([
['failing', 'SERVICE_UNAVAILABLE', 503],
['refusing', 'KNOWLEDGE_REBUILD_REQUIRED', 409],
]);
});

it('a coded refusal is unchanged: its own code, status and message', async () => {
const { svc } = setup([
adapter('refusing', async () => {
throw Object.assign(new Error("Knowledge source 'refusing' needs a rebuild."), { code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409 });
}),
adapter('answering', async () => [hit('answering', 'r1')]),
]);
const report = await svc.searchWithRefusals('q', { executionContext: SYSTEM });
expect(report.hits.map((h) => h.documentId)).toEqual(['answering:r1']);
expect(report.refused).toEqual([
{ sourceId: 'refusing', code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409, message: "Knowledge source 'refusing' needs a rebuild." },
]);
});

it('a source that matches nothing answers no hits and no refusal', async () => {
const { svc, logger } = setup([adapter('empty', async () => [])]);
const report = await svc.searchWithRefusals('q', { executionContext: SYSTEM });
expect(report).toEqual({ hits: [], refused: [] });
expect(logger.error).not.toHaveBeenCalled();
});

it('a source that answers the first round and throws uncoded on the refill: refused once, its first-round hits dropped', async () => {
const topK = 5;
let calls = 0;
const { svc } = setup([
// Round one fills its ask with passages of one record, so the record-level search refills it.
adapter('flaky', async () => {
calls += 1;
if (calls > 1) throw new Error(INTERNAL);
return Array.from({ length: topK * SEARCH_FIRST_ROUND_FACTOR }, (_, n) => hit('flaky', 'r0', n, 1 - n / 1000));
}),
adapter('answering', async () => [hit('answering', 'r9', 0, 0.5)]),
]);
const report = await svc.searchWithRefusals('q', { granularity: 'record', topK, executionContext: SYSTEM });
expect(calls).toBe(2);
expect(report.hits.map((h) => h.sourceId)).toEqual(['answering']);
expect(report.refused).toEqual([expect.objectContaining({ sourceId: 'flaky', code: 'SERVICE_UNAVAILABLE', status: 503 })]);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ import {
SEARCH_FRESHNESS_ROUNDS,
SEARCH_REFILL_FACTOR,
type SearchTarget,
UNMOUNTED_ADAPTER_CODE,
UNPROVEN_CALLER_TEXT,
UNPROVEN_OPERATOR_TEXT,
type UnprovenEnd,
Expand Down Expand Up @@ -888,8 +889,12 @@ export async function unprovenIndex(plan: IndexPlan): Promise<{ why: string; end
* the adapter returned (`answered`, before a hit naming another source or
* outside the scope is dropped — what decides whether the adapter may hold
* more). A source whose adapter is unknown or throws is absent from the
* answer: a coded refusal (ADR-0112 `code` and `status`) is added to
* `refused`, anything else is logged.
* answer and named in `refused`, never answered as no hits: a coded refusal
* (ADR-0112 `code` and `status`) keeps its code and message; any other throw
* (an embedder that cannot be reached, a timeout outside the store) is
* refused as ADR-0112 `SERVICE_UNAVAILABLE` (503) under a platform sentence
* naming the source, and its own message goes to the operator's `error` line
* only.
*
* Under a scope, the adapter is handed the source's terms, and every hit it
* answers is checked against them ({@link scopeCheck}, fail closed). The first
Expand Down Expand Up @@ -956,6 +961,16 @@ export async function searchRound(
);
continue;
}
// Refused like an adapter that cannot serve, never answered as zero
// hits: the caller is told which source was not searched. The thrown
// message can carry hosts, SQL or keys, so the caller reads a platform
// sentence; the operator reads the adapter's own text here.
refused.push({
sourceId: source.name,
code: UNMOUNTED_ADAPTER_CODE,
status: 503,
message: `[knowledge] source '${this.label(source)}' could not be searched: its adapter '${adapterId}' failed.`,
});
this.options.logger?.error?.(
`[knowledge] adapter '${adapterId}' search failed for source '${this.label(source)}': ${(err as Error).message}`,
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -281,15 +281,22 @@ export function describeName(input: unknown): string {
/**
* A source that refused a search (ADR-0161 K7, rule 5): its adapter answered
* an ADR-0112 coded error — `KNOWLEDGE_REBUILD_REQUIRED` when its index holds
* another fingerprint than the one the search carried.
* another fingerprint than the one the search carried — or threw without both
* an ADR-0112 `code` and `status`. For such an uncoded throw, `code`, `status`
* and `message` are the platform's (`SERVICE_UNAVAILABLE`, 503, a sentence
* naming the source), and the message is deliberately not the adapter's text,
* which goes to the operator's `error` line only.
*/
export interface KnowledgeSearchRefusal {
sourceId: string;
/** The adapter's error code. */
/** The adapter's error code; `SERVICE_UNAVAILABLE` for an uncoded throw. */
code: string;
/** The adapter's HTTP-shaped status. */
/** The adapter's HTTP-shaped status; 503 for an uncoded throw. */
status: number;
/** The adapter's message, which says what to do. */
/**
* The adapter's message, which says what to do; for an uncoded throw, the
* platform's sentence naming the source, never the adapter's text.
*/
message: string;
}

Expand Down
Loading
Loading