Skip to content

Commit c8b1dbb

Browse files
fix(service-knowledge)!: a source whose adapter's search throws without a code is refused, never answered as no hits (objectstack-ai#38761)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9DAwBxBGNv4CexdUyBYJXSw)_ Fixes objectstack-ai#38728 repo:objectstack#3 · os-steve · session_01ADHkmPDtfMCw4FJfyFfQ7v Clause-②: no (narrowing) Metadata-protocol: none ## 维护者速读 - 变化:知识库检索时,某个来源的检索服务出错(如向量服务连不上)不再显示成「什么都没搜到」,而是列为「该来源未能检索」。 - 谁会碰到:只在某来源检索抛出无错误码的异常时出现;若它是本次唯一被检索的来源,整次检索改为报「服务不可用」(503),其他来源照常返回结果。 - 出错会怎样:最坏是把出错来源误报为不可用;改动集中在一处,可直接撤回。 - 要你做什么:无。 ## BREAKING **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; the operator's `error` log line keeps it. 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). Declared as a narrowing per L1 REWORK 7279138481; registered in the ADR-0087 ledger as semantic entry `knowledge-search-uncoded-adapter-throw-refused` (`packages/spec/src/migrations/entries/semantic/19.knowledge-search-uncoded-adapter-throw-refused.ts`, a new file; the registry is generated, no existing spec file edited), added to the file surface by claim amendment 2 (comment 7279244160). 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: 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. Fix for each reader: a caller reads `refused` and the 503 instead of treating an empty answer as no match; an operator repairs the adapter or embedder the `error` line names. ## What changes `searchRound` (`packages/services/service-knowledge/src/knowledge-service-search.ts`) catches an adapter's throw from `search`. A coded refusal (ADR-0112 `code` + `status`) was already pushed to `refused`; any other throw was only logged at `error`, so the source read as zero hits. Now an uncoded throw is pushed to `refused` as `{ sourceId, code: 'SERVICE_UNAVAILABLE', status: 503, message }`, where `message` is a platform sentence naming the source and its adapter id (never the thrown text, which can carry hosts, SQL or keys). The operator `error` line is unchanged and still carries the thrown message. The docblock states the new outcome. Code choice: the existing `SERVICE_UNAVAILABLE` (503), the code this package already answers for an adapter that cannot serve (`UNMOUNTED_ADAPTER_CODE`, `knowledge-service-top-level.ts`). No new code is minted, so no ledger or `StandardErrorCode` change. The literal is written in the catch (not the constant imported) to stay inside the claimed hunk. Consequences that follow from the existing refusal machinery, unchanged by this diff: - When no searched source answers (`first.size === 0 && refused.length > 0`), the search is refused whole (`wholeRefusal`), so a search whose only source's embedder is down now rejects with `SERVICE_UNAVAILABLE` / 503 and `refused`, instead of resolving `[]`. - Refill: a source refilled is one that answered round one, so it is never refused twice in one search. A source that fails the refill uncoded is now refused for the whole search and its round-one hits dropped, as a coded refusal of the refill already was (`refusedInRefill`). ## Public doors Measured on `origin/main` acf3b33 plus this branch; there is no REST knowledge search route (a grep of `packages/rest/src` and `packages/runtime/src` for a knowledge search route finds none; the same grep finds the `search_knowledge` registrations below). - `search_knowledge` executor, `packages/services/service-knowledge/src/knowledge-tools.ts:662-671`: with other sources answering, the tool output now carries `refused: [{ sourceId, code: 'SERVICE_UNAVAILABLE', message }]` beside their hits (before: no `refused`, the source silent). When it is the only searched source, the executor rejects with the whole refusal (`wholeRefusal`, thrown at `knowledge-service-search.ts:231`, or `:258` on a refill): `code: 'SERVICE_UNAVAILABLE'`, `status: 503`, `refused` naming the source (before: `{ hits: [] }`). - MCP `search_knowledge`, `packages/mcp/src/mcp-http-tools.ts:3824-3826` (registered for HTTP at `mcp-http-tools.ts:3428` via `packages/runtime/src/domains/mcp.ts:1786`, and for stdio at `packages/mcp/src/plugin.ts:1068` via `stdio-data-bridge.ts:1998`): the partial case returns the text result with `refused`; the only-source case returns `errorResultWithCode` (`mcp-http-tools.ts:1636`), an error result with the ADR-0112 envelope `SERVICE_UNAVAILABLE` / 503 (before: a text result with no hits). - In-process `KnowledgeService.search` / `searchWithRefusals` callers (no other non-test caller in this repo): same as the executor. ## Tests New `src/__tests__/search-uncoded-throw-38728.test.ts` (5 cases): plain `Error` gives one `refused` entry naming the source (code + status asserted, thrown text absent from the caller's message, present in the `error` line), other sources' hits still served; only source throwing uncoded refuses the search whole (503); coded refusal unchanged; source matching nothing answers no hits and no refusal; refill failure refused once, round-one hits dropped. Flipped pins of the old "logged, zero hits" outcome (each now asserts the refusal's sourceId/code/status): - `knowledge-service.test.ts` "a refill the adapter fails keeps the source's round-one survivors" -> refused as a coded refill refusal is. - `knowledge-tools.test.ts` "control: a failure without a code is logged and skipped as before" -> refused `SERVICE_UNAVAILABLE`, text withheld. - `knowledge-settings-contribution.test.ts`: "no settings: ... search answer an error", "the API key is in no log line and no error", "a plugin a host mounts itself, no embedder" -> search rejects `SERVICE_UNAVAILABLE` / 503 naming `docs`. - `packages/plugins/knowledge-pgvector/bench/instrument.test.mjs` "a failed embed is counted, and the search answers no hit with the service's "search failed" line" (`s.ok` true, `s.hits` 0) -> "a failed embed is counted, and the search is refused SERVICE_UNAVAILABLE naming the source, with the service's "search failed" line": `s.ok` false, `s.errorCode` `SERVICE_UNAVAILABLE`, the thrown refusal `SERVICE_UNAVAILABLE` / 503 with `refused` naming `clauses`; `embedFailures` 1, `calls.ranking` 0 and the one "search failed" operator line kept. This sixth pin was added to the file surface by claim amendment 1 (comment 7278305559). Files changed (8): - `packages/services/service-knowledge/src/knowledge-service-search.ts` - `packages/services/service-knowledge/src/__tests__/search-uncoded-throw-38728.test.ts` - `packages/services/service-knowledge/src/__tests__/knowledge-service.test.ts` - `packages/services/service-knowledge/src/__tests__/knowledge-settings-contribution.test.ts` - `packages/services/service-knowledge/src/__tests__/knowledge-tools.test.ts` - `packages/plugins/knowledge-pgvector/bench/instrument.test.mjs` - `.changeset/38728-uncoded-search-throw.md` (`@objectstack/service-knowledge` and `@objectstack/spec` patch, `fix(service-knowledge)!:`, `Clause-②: no (narrowing)`, the ADR-0087 `registered` marker) - `packages/spec/src/migrations/entries/semantic/19.knowledge-search-uncoded-adapter-throw-refused.ts` (new; claim amendment 2, comment 7279244160) <details><summary>Readings (tests at 43def1f; e52b762 adds only the changeset sentence)</summary> - `pnpm --filter @objectstack/service-knowledge test`: Test Files 26 passed (26), Tests 841 passed (841). - `pnpm --filter @objectstack/service-knowledge typecheck` (tsc over `src`, tests included, plus `check:test-typecheck`): exit 0. - Ablation: catch reverted to `acf3b33e` on disk, new file run: 3 failed / 2 passed (the three uncoded pins red; coded and no-match pins green). Fix restored. - Local derived gates: 40 of 69 run, all exit 0 except `check-plugin-teardown-shape --self-test` (exit 3, shallow-clone prerequisite, NOT MEASURED) and `check:type-check-debt` (local 100 s timeout, NOT MEASURED). The other 29 are left to CI. - `overlap-check.mjs`: VERDICT clean exit 0 (merges cleanly with main, objectstack-ai#38722, objectstack-ai#38730, objectstack-ai#38732). - Round 2 (6348efa): `bench/instrument.test.mjs` alone 8 passed (8); `pnpm --filter @objectstack/knowledge-pgvector test` 46 passed, 95 skipped (live-postgres); knowledge-turso 301 passed; knowledge-memory 66 passed; overlap-check VERDICT clean exit 0 (also objectstack-ai#38758). </details> ## Acceptance notes - Read first: the catch block in `searchRound` (the only runtime hunk); then the refill pin flip in `knowledge-service.test.ts`, which is the one behaviour change beyond the card's literal Ask (a refill failure now drops round-one survivors instead of keeping them, to match the coded path). - The stand-in embedder's "No embedder is configured ... restart" text is uncoded, so the caller now reads the generic platform sentence and the remedy stays on the operator line. Coding that error at its producer would let the caller read the remedy; noted, not filed. - `content/docs/protocol/knowledge.mdx` not edited (open PRs edit it; skipped per dispatch). ## Verification Two-minute check: `pnpm --filter @objectstack/service-knowledge exec vitest run src/__tests__/search-uncoded-throw-38728.test.ts` -> 5 passed. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmPDtfMCw4FJfyFfQ7v <!-- signed: repo:objectstack#3 · os-steve · session_01ADHkmPDtfMCw4FJfyFfQ7v --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 643519b commit c8b1dbb

11 files changed

Lines changed: 307 additions & 33 deletions
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
---
2+
'@objectstack/service-knowledge': patch
3+
'@objectstack/spec': patch
4+
---
5+
6+
fix(service-knowledge)!: a source whose adapter's search throws without a code is refused, never answered as no hits
7+
8+
Clause-②: no (narrowing)
9+
Metadata-protocol: none
10+
11+
<!-- adr-0087: registered knowledge-search-uncoded-adapter-throw-refused -->
12+
13+
**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).
14+
15+
## FROM → TO
16+
17+
- No searched source answers and at least one threw without a code — two cells:
18+
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).
19+
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`.
20+
- 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.
21+
22+
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.
23+
24+
`@objectstack/spec` adds only the upgrade-guide entry `knowledge-search-uncoded-adapter-throw-refused`.

‎packages/plugins/knowledge-pgvector/bench/instrument.test.mjs‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -203,14 +203,19 @@ describe('bench instrument — segment seams over the real adapter and service',
203203
expect(extractRankingWhere('WITH cand AS (SELECT chunk_id, 0 AS distance FROM t WHERE x)', ['a', 1, 5])).toBeUndefined();
204204
});
205205

206-
it('a failed embed is counted, and the search answers no hit with the service\'s "search failed" line', async () => {
206+
it('a failed embed is counted, and the search is refused SERVICE_UNAVAILABLE naming the source, with the service\'s "search failed" line', async () => {
207207
const { search, errors } = setup({ failEmbed: true });
208208
const outcome = await search({ query: 'leave policy', topK: TOP_K }, CALLER);
209209
const s = summarizeRecord(outcome);
210210
expect(s.embedFailures).toBe(1);
211211
expect(s.calls.ranking).toBe(0);
212-
expect(s.ok).toBe(true);
213-
expect(s.hits).toBe(0);
212+
expect(s.ok).toBe(false);
213+
expect(s.errorCode).toBe('SERVICE_UNAVAILABLE');
214+
expect(outcome.error).toMatchObject({
215+
code: 'SERVICE_UNAVAILABLE',
216+
status: 503,
217+
refused: [expect.objectContaining({ sourceId: 'clauses', code: 'SERVICE_UNAVAILABLE', status: 503 })],
218+
});
214219
expect(errors.filter((m) => /search failed/.test(m))).toHaveLength(1);
215220
});
216221
});

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

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1533,14 +1533,19 @@ describe('KnowledgeService — search refills after the permission filter', () =
15331533
expect(asked()).toEqual([['s1', 15], ['s2', 15], ['s1', 60]]);
15341534
});
15351535

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

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

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -616,11 +616,16 @@ describe('#37094 — the open edition registers EMBEDDER_SERVICE from the ai.emb
616616
const named = /No embedder is configured[\s\S]*ai\.embedder_provider[\s\S]*restart/;
617617

618618
await expect(indexOne(knowledge, 'hello')).rejects.toThrow(named);
619-
// The adapter's search answers the error; the service's search reports it
620-
// per source and answers no hits.
619+
// The adapter's search answers the error; the service's search refuses
620+
// 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.
621622
await expect(knowledge.getAdapter('vec').search('hello', { source: knowledge.getSource('docs')!, topK: 5 }))
622623
.rejects.toThrow(named);
623-
await expect(knowledge.search('hello', { sourceIds: ['docs'], executionContext: SYSTEM })).resolves.toEqual([]);
624+
await expect(knowledge.search('hello', { sourceIds: ['docs'], executionContext: SYSTEM })).rejects.toMatchObject({
625+
code: 'SERVICE_UNAVAILABLE',
626+
status: 503,
627+
refused: [expect.objectContaining({ sourceId: 'docs', code: 'SERVICE_UNAVAILABLE', status: 503 })],
628+
});
624629
expect(lines.some((l) => l.level === 'error' && named.test(l.line))).toBe(true);
625630
// A vector column cannot be sized from it either.
626631
expect(() => embedder.dimensions).toThrow(named);
@@ -740,7 +745,12 @@ describe('#37094 — the open edition registers EMBEDDER_SERVICE from the ai.emb
740745
(err: unknown) => err as Error,
741746
);
742747
expect(failure.message).not.toContain(API_KEY);
743-
await rejected.knowledge.search('hello', { sourceIds: ['docs'], executionContext: SYSTEM });
748+
const searched = await rejected.knowledge.search('hello', { sourceIds: ['docs'], executionContext: SYSTEM }).then(
749+
() => { throw new Error('expected a refusal'); },
750+
(err: unknown) => err as Error & { code?: string; status?: number },
751+
);
752+
expect(searched).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
753+
expect(searched.message).not.toContain(API_KEY);
744754
expect(requests.length).toBeGreaterThan(0);
745755
expect(rejected.lines.filter((l) => l.line.includes(API_KEY))).toEqual([]);
746756
});
@@ -1061,7 +1071,11 @@ describe('[ADR-0161 K8, note on item 12] a runtime-composed knowledge service is
10611071
expect(heldLines()).toEqual([]);
10621072
expect(knowledge.knowledgeTools().definitions.map((d) => d.name)).toEqual(['search_knowledge']);
10631073
expect(lines.some((l) => l.level === 'info' && l.line.includes('no embedder is configured ('))).toBe(true);
1064-
await expect(knowledge.search('granite', { sourceIds: ['docs'], executionContext: SYSTEM })).resolves.toEqual([]);
1074+
await expect(knowledge.search('granite', { sourceIds: ['docs'], executionContext: SYSTEM })).rejects.toMatchObject({
1075+
code: 'SERVICE_UNAVAILABLE',
1076+
status: 503,
1077+
refused: [expect.objectContaining({ sourceId: 'docs', code: 'SERVICE_UNAVAILABLE', status: 503 })],
1078+
});
10651079
expect(calls).toContain('search');
10661080
});
10671081
});

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

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -258,11 +258,14 @@ describe('search_knowledge — a refused source (ADR-0161 K7, rule 5)', () => {
258258
});
259259
});
260260

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

268271
it('an answer with nothing refused carries no refused list', async () => {
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
// An adapter whose `search` throws without both an ADR-0112 `code` and `status` (an embedder that
4+
// cannot be reached, a timeout outside the store) is refused for that source,
5+
// never answered as zero hits: the caller reads a `refused` entry naming the
6+
// source, coded SERVICE_UNAVAILABLE (503), under a platform sentence; the
7+
// thrown message reaches the operator's `error` line only.
8+
9+
import { describe, it, expect, vi } from 'vitest';
10+
import { KnowledgeService, SEARCH_FIRST_ROUND_FACTOR } from '../knowledge-service.js';
11+
import type { IKnowledgeAdapter } from '@objectstack/spec/contracts';
12+
import type { KnowledgeHit, KnowledgeSource, ObjectKnowledgeSource } from '@objectstack/spec/ai';
13+
14+
const SYSTEM = { positions: [], permissions: [], isSystem: true };
15+
const INTERNAL = 'embedder down at http://10.0.0.7:11434 (key sk-secret)';
16+
17+
function source(name: string, adapter: string): KnowledgeSource {
18+
return {
19+
name,
20+
label: name,
21+
adapter,
22+
source: { kind: 'object', object: 'task', content: ['title'], metadataFields: ['status'] } as ObjectKnowledgeSource,
23+
};
24+
}
25+
26+
function hit(sourceId: string, record: string, n = 0, score = 0.9): KnowledgeHit {
27+
return { chunkId: `${sourceId}:${record}#${n}`, documentId: `${sourceId}:${record}`, sourceId, sourceRecordId: record, score, snippet: 'ok' };
28+
}
29+
30+
function adapter(id: string, search: IKnowledgeAdapter['search']): IKnowledgeAdapter {
31+
return { id, upsert: vi.fn(async () => undefined), delete: vi.fn(async () => undefined), search: vi.fn(search) };
32+
}
33+
34+
function setup(adapters: IKnowledgeAdapter[]) {
35+
const logger = { debug: vi.fn(), warn: vi.fn(), error: vi.fn() };
36+
const svc = new KnowledgeService({ logger: logger as never });
37+
for (const a of adapters) {
38+
svc.registerAdapter(a.id, a);
39+
svc.registerSource(source(a.id, a.id));
40+
}
41+
return { svc, logger };
42+
}
43+
44+
describe('knowledge search: an adapter throw without a code is refused for its source, never zero hits', () => {
45+
it('a plain Error from search: one refused entry naming the source, SERVICE_UNAVAILABLE / 503; other sources still served', async () => {
46+
const { svc, logger } = setup([
47+
adapter('failing', async () => { throw new Error(INTERNAL); }),
48+
adapter('answering', async () => [hit('answering', 'r1')]),
49+
]);
50+
const report = await svc.searchWithRefusals('q', { executionContext: SYSTEM });
51+
expect(report.hits.map((h) => h.documentId)).toEqual(['answering:r1']);
52+
expect(report.refused).toHaveLength(1);
53+
expect(report.refused[0]).toMatchObject({ sourceId: 'failing', code: 'SERVICE_UNAVAILABLE', status: 503 });
54+
// The caller's sentence names the source; the thrown text stays with the operator.
55+
expect(report.refused[0].message).toContain("source 'failing'");
56+
expect(report.refused[0].message).not.toContain('10.0.0.7');
57+
expect(report.refused[0].message).not.toContain('sk-secret');
58+
expect(logger.error.mock.calls.some(([line]) => String(line).includes(INTERNAL))).toBe(true);
59+
});
60+
61+
it('the only source throws uncoded: the search is refused whole, SERVICE_UNAVAILABLE / 503, not answered empty', async () => {
62+
const { svc } = setup([adapter('failing', async () => { throw new Error(INTERNAL); })]);
63+
const thrown = await svc.searchWithRefusals('q', { executionContext: SYSTEM }).then(
64+
() => undefined,
65+
(e: unknown) => e as { code?: string; status?: number; message: string; refused?: Array<{ sourceId: string; code: string }> },
66+
);
67+
expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
68+
expect(thrown?.refused).toEqual([expect.objectContaining({ sourceId: 'failing', code: 'SERVICE_UNAVAILABLE', status: 503 })]);
69+
expect(thrown?.message).not.toContain('sk-secret');
70+
});
71+
72+
it('every searched source throws uncoded (an embedder outage): refused whole, 503, refused naming each', async () => {
73+
const { svc } = setup([
74+
adapter('first', async () => { throw new Error(INTERNAL); }),
75+
adapter('second', async () => { throw new Error(INTERNAL); }),
76+
]);
77+
const thrown = await svc.searchWithRefusals('q', { executionContext: SYSTEM }).then(
78+
() => undefined,
79+
(e: unknown) => e as { code?: string; status?: number; message: string; refused?: Array<{ sourceId: string; code: string }> },
80+
);
81+
expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
82+
expect(thrown?.refused?.map((r) => [r.sourceId, r.code])).toEqual([
83+
['first', 'SERVICE_UNAVAILABLE'],
84+
['second', 'SERVICE_UNAVAILABLE'],
85+
]);
86+
expect(thrown?.message).not.toContain('sk-secret');
87+
});
88+
89+
it('an uncoded throw beside a coded refusal, none answering: refused names both, top-level code is the first in source order', async () => {
90+
const { svc } = setup([
91+
adapter('failing', async () => { throw new Error(INTERNAL); }),
92+
adapter('refusing', async () => {
93+
throw Object.assign(new Error("Knowledge source 'refusing' needs a rebuild."), { code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409 });
94+
}),
95+
]);
96+
const thrown = await svc.searchWithRefusals('q', { executionContext: SYSTEM }).then(
97+
() => undefined,
98+
(e: unknown) => e as { code?: string; status?: number; message: string; refused?: Array<{ sourceId: string; code: string; status: number }> },
99+
);
100+
expect(thrown).toMatchObject({ code: 'SERVICE_UNAVAILABLE', status: 503 });
101+
expect(thrown?.refused?.map((r) => [r.sourceId, r.code, r.status])).toEqual([
102+
['failing', 'SERVICE_UNAVAILABLE', 503],
103+
['refusing', 'KNOWLEDGE_REBUILD_REQUIRED', 409],
104+
]);
105+
});
106+
107+
it('a coded refusal is unchanged: its own code, status and message', async () => {
108+
const { svc } = setup([
109+
adapter('refusing', async () => {
110+
throw Object.assign(new Error("Knowledge source 'refusing' needs a rebuild."), { code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409 });
111+
}),
112+
adapter('answering', async () => [hit('answering', 'r1')]),
113+
]);
114+
const report = await svc.searchWithRefusals('q', { executionContext: SYSTEM });
115+
expect(report.hits.map((h) => h.documentId)).toEqual(['answering:r1']);
116+
expect(report.refused).toEqual([
117+
{ sourceId: 'refusing', code: 'KNOWLEDGE_REBUILD_REQUIRED', status: 409, message: "Knowledge source 'refusing' needs a rebuild." },
118+
]);
119+
});
120+
121+
it('a source that matches nothing answers no hits and no refusal', async () => {
122+
const { svc, logger } = setup([adapter('empty', async () => [])]);
123+
const report = await svc.searchWithRefusals('q', { executionContext: SYSTEM });
124+
expect(report).toEqual({ hits: [], refused: [] });
125+
expect(logger.error).not.toHaveBeenCalled();
126+
});
127+
128+
it('a source that answers the first round and throws uncoded on the refill: refused once, its first-round hits dropped', async () => {
129+
const topK = 5;
130+
let calls = 0;
131+
const { svc } = setup([
132+
// Round one fills its ask with passages of one record, so the record-level search refills it.
133+
adapter('flaky', async () => {
134+
calls += 1;
135+
if (calls > 1) throw new Error(INTERNAL);
136+
return Array.from({ length: topK * SEARCH_FIRST_ROUND_FACTOR }, (_, n) => hit('flaky', 'r0', n, 1 - n / 1000));
137+
}),
138+
adapter('answering', async () => [hit('answering', 'r9', 0, 0.5)]),
139+
]);
140+
const report = await svc.searchWithRefusals('q', { granularity: 'record', topK, executionContext: SYSTEM });
141+
expect(calls).toBe(2);
142+
expect(report.hits.map((h) => h.sourceId)).toEqual(['answering']);
143+
expect(report.refused).toEqual([expect.objectContaining({ sourceId: 'flaky', code: 'SERVICE_UNAVAILABLE', status: 503 })]);
144+
});
145+
});

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

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ import {
6363
SEARCH_FRESHNESS_ROUNDS,
6464
SEARCH_REFILL_FACTOR,
6565
type SearchTarget,
66+
UNMOUNTED_ADAPTER_CODE,
6667
UNPROVEN_CALLER_TEXT,
6768
UNPROVEN_OPERATOR_TEXT,
6869
type UnprovenEnd,
@@ -917,8 +918,12 @@ export async function unprovenIndex(plan: IndexPlan): Promise<{ why: string; end
917918
* the adapter returned (`answered`, before a hit naming another source or
918919
* outside the scope is dropped — what decides whether the adapter may hold
919920
* more). A source whose adapter is unknown or throws is absent from the
920-
* answer: a coded refusal (ADR-0112 `code` and `status`) is added to
921-
* `refused`, anything else is logged.
921+
* answer and named in `refused`, never answered as no hits: a coded refusal
922+
* (ADR-0112 `code` and `status`) keeps its code and message; any other throw
923+
* (an embedder that cannot be reached, a timeout outside the store) is
924+
* refused as ADR-0112 `SERVICE_UNAVAILABLE` (503) under a platform sentence
925+
* naming the source, and its own message goes to the operator's `error` line
926+
* only.
922927
*
923928
* Under a scope, the adapter is handed the source's terms, and every hit it
924929
* answers is checked against them ({@link scopeCheck}, fail closed). The first
@@ -986,6 +991,16 @@ export async function searchRound(
986991
);
987992
continue;
988993
}
994+
// Refused like an adapter that cannot serve, never answered as zero
995+
// hits: the caller is told which source was not searched. The thrown
996+
// message can carry hosts, SQL or keys, so the caller reads a platform
997+
// sentence; the operator reads the adapter's own text here.
998+
refused.push({
999+
sourceId: source.name,
1000+
code: UNMOUNTED_ADAPTER_CODE,
1001+
status: 503,
1002+
message: `[knowledge] source '${this.label(source)}' could not be searched: its adapter '${adapterId}' failed.`,
1003+
});
9891004
this.options.logger?.error?.(
9901005
`[knowledge] adapter '${adapterId}' search failed for source '${this.label(source)}': ${(err as Error).message}`,
9911006
);

‎packages/services/service-knowledge/src/knowledge-service-top-level.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -287,15 +287,22 @@ export function describeName(input: unknown): string {
287287
/**
288288
* A source that refused a search (ADR-0161 K7, rule 5): its adapter answered
289289
* an ADR-0112 coded error — `KNOWLEDGE_REBUILD_REQUIRED` when its index holds
290-
* another fingerprint than the one the search carried.
290+
* another fingerprint than the one the search carried — or threw without both
291+
* an ADR-0112 `code` and `status`. For such an uncoded throw, `code`, `status`
292+
* and `message` are the platform's (`SERVICE_UNAVAILABLE`, 503, a sentence
293+
* naming the source), and the message is deliberately not the adapter's text,
294+
* which goes to the operator's `error` line only.
291295
*/
292296
export interface KnowledgeSearchRefusal {
293297
sourceId: string;
294-
/** The adapter's error code. */
298+
/** The adapter's error code; `SERVICE_UNAVAILABLE` for an uncoded throw. */
295299
code: string;
296-
/** The adapter's HTTP-shaped status. */
300+
/** The adapter's HTTP-shaped status; 503 for an uncoded throw. */
297301
status: number;
298-
/** The adapter's message, which says what to do. */
302+
/**
303+
* The adapter's message, which says what to do; for an uncoded throw, the
304+
* platform's sentence naming the source, never the adapter's text.
305+
*/
299306
message: string;
300307
}
301308

0 commit comments

Comments
 (0)