Skip to content

Commit 3a69848

Browse files
committed
fix(service-knowledge): a source that needs the index proof is never searched without it
The adapter a source binds to is resolved once per search, in the plan: the index proof is read from that instance, both search rounds search that instance, and a source whose adapter does not resolve at the plan carries the coded refusal and is refused, never searched. Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cwPhGV4g9p1BGQaZbP
1 parent f10feed commit 3a69848

2 files changed

Lines changed: 68 additions & 19 deletions

File tree

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -809,6 +809,39 @@ describe('field gate — the earlier title rule: searched only once the index is
809809
expect(await svc.search('q', { executionContext: MEMBER })).toEqual([]);
810810
});
811811

812+
it('a source that needs the index proof is never searched without it: the round searches the adapter the proof was read from', async () => {
813+
const { svc, adapter, currentHit } = proven();
814+
const source = svc.getSource('s')!;
815+
const unproven = makeAdapter();
816+
unproven.searchSpy.mockImplementation(async () => [currentHit(source)]);
817+
const readStatus = adapter.indexStatus!.getMockImplementation() as (ctx: AdapterContext) => Promise<AdapterIndexStatus>;
818+
// Another instance takes the adapter id while the proof is being read.
819+
adapter.indexStatus!.mockImplementation(async (ctx: AdapterContext) => {
820+
svc.registerAdapter('memory', unproven);
821+
return readStatus(ctx);
822+
});
823+
expect(await svc.search('q', { executionContext: MEMBER })).toEqual([currentHit(source)]);
824+
expect(adapter.searchSpy).toHaveBeenCalledOnce();
825+
expect(unproven.searchSpy).not.toHaveBeenCalled();
826+
});
827+
828+
it('a source that needs the index proof is never searched without it: an adapter that resolves only after the plan is not searched', async () => {
829+
const late = { ...objectSource('late', 'account', ['body']), adapter: 'late' } as KnowledgeSource;
830+
const { svc, adapter } = proven({ sources: [late, objectSource('s', 'account', ['body'])] });
831+
const lateAdapter = makeAdapter(true);
832+
const readStatus = adapter.indexStatus!.getMockImplementation() as (ctx: AdapterContext) => Promise<AdapterIndexStatus>;
833+
// The adapter `late` names registers after its source was planned, while another source's proof is read.
834+
adapter.indexStatus!.mockImplementation(async (ctx: AdapterContext) => {
835+
if (!svc.listAdapters().includes('late')) svc.registerAdapter('late', lateAdapter);
836+
return readStatus(ctx);
837+
});
838+
const report = await svc.searchWithRefusals('q', { executionContext: MEMBER });
839+
expect(ids(report.hits)).toEqual(['s']);
840+
expect(report.refused).toEqual([expect.objectContaining({ sourceId: 'late', code: 'SERVICE_UNAVAILABLE', status: 503 })]);
841+
expect(lateAdapter.searchSpy).not.toHaveBeenCalled();
842+
expect(lateAdapter.indexStatus).not.toHaveBeenCalled();
843+
});
844+
812845
it('only a proven source is checked: a source searched without the proof is served as the store answered it', async () => {
813846
const { svc, adapter, currentHit } = setup({
814847
objects: [ACCOUNT, TICKET],

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

Lines changed: 35 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2291,9 +2291,10 @@ export class KnowledgeService implements IKnowledgeService {
22912291
}
22922292

22932293
/**
2294-
* Each admitted source paired with the fingerprint its search carries
2295-
* ({@link planIndex}); a source whose adapter is not registered carries none
2296-
* (the round skips it, as before).
2294+
* Each admitted source paired with the adapter it binds to, resolved here
2295+
* once for the whole search, and the fingerprint its search carries
2296+
* ({@link planIndex}); a source whose adapter does not resolve carries the
2297+
* coded refusal instead and is refused by the round, never searched.
22972298
*
22982299
* A source admitted with `proveIndex` ({@link admitSources}) is searched
22992300
* only when its index is proven built under the current recipe
@@ -2313,10 +2314,18 @@ export class KnowledgeService implements IKnowledgeService {
23132314
let target: Promise<number | undefined> | undefined;
23142315
const chunkTarget = (): Promise<number | undefined> => (target ??= this.readChunkTarget());
23152316
for (const { proveIndex, ...entry } of admitted) {
2316-
const adapterId = this.boundAdapterId(entry.source);
2317-
const adapter = adapterId === undefined ? undefined : this.adapters.get(adapterId);
2318-
if (!adapter) {
2319-
out.push(entry);
2317+
// The adapter is resolved here, once per search: the proof below is read
2318+
// from this instance and both rounds search this instance, so a source
2319+
// cannot change binding between the check and the use.
2320+
let adapterId: string;
2321+
let adapter: IKnowledgeAdapter;
2322+
try {
2323+
adapterId = this.adapterIdFor(entry.source);
2324+
adapter = this.getAdapter(adapterId);
2325+
} catch (err) {
2326+
// Refused like an adapter that cannot serve, as the round refuses it; a
2327+
// source that needs the index proof is never searched without it.
2328+
out.push({ ...entry, binding: { refusal: codedRefusalOf(err) } });
23202329
continue;
23212330
}
23222331
const plan = await this.planIndex(entry.source, adapter, chunkTarget);
@@ -2340,7 +2349,12 @@ export class KnowledgeService implements IKnowledgeService {
23402349
continue;
23412350
}
23422351
}
2343-
out.push({ ...entry, fingerprint: plan.index.fingerprint, ...(proveIndex === true ? { verifyHits: true as const } : {}) });
2352+
out.push({
2353+
...entry,
2354+
binding: { adapterId, adapter },
2355+
fingerprint: plan.index.fingerprint,
2356+
...(proveIndex === true ? { verifyHits: true as const } : {}),
2357+
});
23442358
}
23452359
return out;
23462360
}
@@ -2444,21 +2458,17 @@ export class KnowledgeService implements IKnowledgeService {
24442458
refused: KnowledgeSearchRefusal[],
24452459
): Promise<Map<string, { hits: KnowledgeHit[]; answered: number }>> {
24462460
const out = new Map<string, { hits: KnowledgeHit[]; answered: number }>();
2447-
for (const { source, organizationIds, fingerprint, scope } of sources) {
2461+
for (const { source, organizationIds, fingerprint, scope, binding } of sources) {
24482462
// Refused like an adapter that cannot serve: the caller is told which
24492463
// source was not searched and why; the boot said so at `error`
2450-
// (`reportUnmountedAdapters`), so no line per search. A source that
2451-
// names no adapter is placed here, as everywhere (`adapterIdFor`).
2452-
let adapterId: string;
2453-
let adapter: IKnowledgeAdapter;
2454-
try {
2455-
adapterId = this.adapterIdFor(source);
2456-
adapter = this.getAdapter(adapterId);
2457-
} catch (err) {
2458-
const coded = codedRefusalOf(err);
2459-
if (coded !== undefined) refused.push({ sourceId: source.name, ...coded });
2464+
// (`reportUnmountedAdapters`), so no line per search. The adapter was
2465+
// resolved once for the whole search ({@link planSearches}); a round
2466+
// searches that instance and never looks it up again.
2467+
if ('refusal' in binding) {
2468+
if (binding.refusal !== undefined) refused.push({ sourceId: source.name, ...binding.refusal });
24602469
continue;
24612470
}
2471+
const { adapterId, adapter } = binding;
24622472
try {
24632473
const hits = await adapter.search(query, {
24642474
source,
@@ -3275,6 +3285,12 @@ const INDEX_NOT_PROVEN_CODE = 'KNOWLEDGE_REBUILD_REQUIRED';
32753285

32763286
interface SearchTarget {
32773287
source: KnowledgeSource;
3288+
/**
3289+
* The adapter the source binds to, resolved once per search
3290+
* ({@link KnowledgeService.planSearches}), or the coded refusal its
3291+
* resolution answered (`undefined`: an uncoded failure, skipped unsearched).
3292+
*/
3293+
binding: { adapterId: string; adapter: IKnowledgeAdapter } | { refusal: Omit<KnowledgeSearchRefusal, 'sourceId'> | undefined };
32783294
organizationIds?: string[];
32793295
fingerprint?: string;
32803296
scope?: AdapterScopeTerm[];

0 commit comments

Comments
 (0)