Skip to content

Commit 2776e88

Browse files
feat(record-context): citation verifier reports failures apart from refusals (#37438)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wgToQGw4qwp7m57qUh2sLcjt)_ Fixes #37418 Clause-②: yes (widening) — new optional third argument of the exported verifyRecordCitations and two new exported types; existing calls unchanged Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:用户无感;AI 回答里的引用核对时,数据库故障不再被当成「无权查看」悄悄丢掉,而是报给后台。 - 为什么做:AI 回答引用专题的后续,替云端产生引用的那一步和运维排障的人解决「一次故障让引用永久消失且无人知晓」。 - 出错会怎样:故障时引用照样不显示(宁缺勿错),只是多报一条错误;无权查看和记录不存在对后台仍是同一个结果,不泄露记录是否存在;可直接撤回本改动。 - 要你做什么:无。 ## What changes `verifyRecordCitations(citations, door, options?)` in `packages/services/service-record-context/src/verify-citations.ts`: - **Refusal vs failure.** A throw carrying an ADR-0112 `code` with a declared 4xx status is a refusal. The status is read as ADR-0112's reader (`resolveThrownHttpError`'s `declaredStatus`) reads it, `.status` then `.statusCode`, mirrored locally because the package does not depend on `@objectstack/types`. A refusal is the only shape `get_record_context` refuses with: its citations are dropped and nothing is reported, as before. Any other throw (no code, a driver code with no status, a 5xx) is a failure: its citations are dropped too, so the result stays fail-closed, and the failure goes to the new optional `options.onError(error, call)`, once per verifying call. A callback that throws, or returns a promise that rejects, is ignored, so the verifier still never throws for a citation and leaves no unhandled rejection. The served-definition read behind the HTML-body check reports too; there the call answered and only the tag-removed reading is lost, which the option's JSDoc says. - **Why status, not the code string.** ADR-0112's 2026-08-27 amendment names the status channel as the one structural signal between a refusal and a fault: a driver errno (`ECONNRESET`, `SQLITE_ERROR`) also arrives on `.code`, so the string alone cannot tell. - **Design choice: a callback, not a new result shape.** It is the smaller change. The return type stays `RecordCitationParsed[]`, existing two-argument callers see nothing, and the result carries nothing that could tell a caller a hidden record from a missing one. A `{ verified, unverifiable }` result would put the failure next to data the caller may see, and would change the signature every caller reads. - New exported types `VerifyRecordCitationsOptions` and `VerifyingCall` (`src/index.ts`). - **Nits from the PR #37396 review:** - The module doc says which list cap a producer gets: the verifier reads the first 20 (`RECORD_CITATIONS_MAX`) and drops the rest, where `RecordCitationsSchema` refuses a list of 21. - The module doc corrects the "tag-stripping only makes verification stricter" note: the tag-removed reading is a second string, and removing a tag joins adjacent text (`<p>Fire</p><p>cover</p>` reads `Firecover`). A test pins it. - `stripBodyTags` (`packages/spec/src/ai/record-body-anchor.ts`) says it is not a sanitizer. JSDoc only. ## Tests `src/__tests__/verify-citations.test.ts`, new block "a refusal and a failure": - A door whose root read throws an uncoded `Error`: citations dropped, failure reported once per distinct call (two calls, three citations → two reports). Control: the same citations verify through a door that answers. - A driver code with no status and a coded 500: dropped and reported. - Control: coded 403, 404 and 400 refusals: dropped, not reported. - A refused read (`unreadableRows`) and a missing record (`p404`) give the host the identical `{ quotes: [], reported: [] }`, with a control leg that verifies the readable record. - A throwing callback is ignored; no callback still drops the failed call. - Rework (contract review 7184346569, seat REWORK 7184355118): a coded refusal declared with `statusCode` only is not reported (control: coded 503 `statusCode` is); a 4xx with no code, a thrown string and a thrown `undefined` are reported; a failing definition read behind an HTML body is reported once while the field quote and the as-stored quote still verify; an async callback that rejects leaves no unhandled rejection. - The adjacent-text join of the tag-removed reading. Ablation (one, on the coded-vs-uncoded split): `isRefusal` reduced to "has a string code" → "reports a driver code with no status, and a coded 5xx, as failures" goes red (1 failed, 20 passed); restored → green. Rework ablations: dropping the `.statusCode` limb → the statusCode-only test red (1 failed | 24 passed); dropping the returned-promise handler → the async-callback test red (1 failed | 24 passed); both restored → green. ## Acceptance notes - `record-context-tools.ts` (fenced, sibling #37361) turns some door failures into coded refusals before they reach the verifier: a failing related-object definition read or published-definition read becomes `PERMISSION_DENIED` 403 so the refusal names nothing. Those failures are therefore not reported, and the module doc now says so. The follow-up card is #37463. - The whole 4xx band is a refusal, so a door declaring a coded 408 or 429 would drop a transient condition without a report. No door on the read path declares one today; the module doc records it (review N4). - `Clause-②: yes (widening)` (seat ruling, same as the #37412 precedent): the new parameter is optional and the return type is unchanged, so no existing caller changes; there is no caller outside this package today. Bump stays patch. ## Verification Two-minute check: `pnpm --filter @objectstack/service-record-context exec vitest run src/__tests__/verify-citations.test.ts` — 25 tests pass. Read first: `verify-citations.ts` `isRefusal`, `declaredStatusOf` and `report` (the split and the async guard), then the `haystackOf` catch. --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CZnFSe9yjMwBFr33Rk)_ <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CZnFSe9yjMwBFr33Rk --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent cc38a91 commit 2776e88

5 files changed

Lines changed: 296 additions & 14 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/service-record-context': patch
3+
'@objectstack/spec': patch
4+
---
5+
6+
feat(record-context): the citation verifier tells a refusal from a failure and reports failures to the host
7+
8+
Clause-②: yes (widening) — new optional third argument of the exported verifyRecordCitations and two new exported types; existing calls unchanged
9+
Metadata-protocol: none
10+
11+
ADR-0160 D9 verifies an answer's citations once, so a citation lost to an outage is lost for good. `verifyRecordCitations` used to drop a citation the same way whether the verifying call was refused or failed.
12+
13+
- **A refusal** is a throw carrying an ADR-0112 `code` with a declared 4xx status (read as ADR-0112's reader reads it: `.status`, then `.statusCode`), the only shape `get_record_context` refuses with. Its citations are dropped and nothing is reported, as before.
14+
- **Any other throw** (no code, a driver code with no status, a 5xx) is a failure. Its citations are still dropped, so the result stays fail-closed, and the failure goes to the new optional `onError(error, call)` option, once per verifying call, so the host can log or retry. A failed read of the served definition behind an HTML body is reported too; there only the tag-removed reading is lost. A callback that throws, or returns a promise that rejects, is ignored.
15+
- A refused read and a missing record still give the host the same answer: dropped, not reported.
16+
- New exported types `VerifyRecordCitationsOptions` and `VerifyingCall`. Existing two-argument calls are unchanged.
17+
- Docs: the verifier says which list cap a producer gets (the first 20 read, where `RecordCitationsSchema` refuses 21) and that the tag-removed reading of an HTML body joins adjacent text, so it is not only stricter than matching as stored. `stripBodyTags` says it is not a sanitizer.

‎packages/services/service-record-context/src/__tests__/verify-citations.test.ts‎

Lines changed: 144 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@
1212

1313
import { describe, expect, it } from 'vitest';
1414
import { RECORD_CITATIONS_MAX } from '@objectstack/spec/ai';
15-
import { executeGetRecordContext, verifyRecordCitations } from '../index.js';
16-
import { fakeDoor, policyApp, type FakeApp } from './fake-door.js';
15+
import { executeGetRecordContext, verifyRecordCitations, type VerifyingCall } from '../index.js';
16+
import { fakeDoor, policyApp, type FakeApp, type FakeDoor } from './fake-door.js';
1717

1818
const ROOT = { object: 'policy', id: 'p1' };
1919

@@ -85,6 +85,11 @@ describe('[ADR-0160 D9] what a quote is matched against', () => {
8585
'Covers <b>fire</b>',
8686
]);
8787
}
88+
// Removing a tag joins the text on either side: the tag-removed reading is
89+
// not only stricter than matching as stored.
90+
const joined = htmlApp('html');
91+
joined.records.policy[0].content = '<p>Fire</p><p>cover</p>';
92+
expect(await surviving(joined, [cite('Firecover')])).toEqual(['Firecover']);
8893
expect(await surviving(htmlApp('markdown'), [cite('Covers fire damage.'), cite('Covers <b>fire</b>')])).toEqual([
8994
'Covers <b>fire</b>',
9095
]);
@@ -150,6 +155,143 @@ describe('[ADR-0160 D9] a caller with no read access', () => {
150155
});
151156
});
152157

158+
describe('[ADR-0160 D9] a refusal and a failure', () => {
159+
/** A door whose root read guard throws `err` instead of answering. */
160+
const throwingDoor = (err: unknown): FakeDoor => {
161+
const door = fakeDoor(policyApp());
162+
door.readGuard = async () => {
163+
throw err;
164+
};
165+
return door;
166+
};
167+
const coded = (code: string, status: number) => Object.assign(new Error(code), { code, status });
168+
169+
/** The surviving quotes and every failure the host was handed. */
170+
async function run(door: FakeDoor, citations: unknown[]) {
171+
const reported: Array<{ error: unknown; call: VerifyingCall }> = [];
172+
const verified = await verifyRecordCitations(citations, door, { onError: (error, call) => reported.push({ error, call }) });
173+
return { quotes: verified.map((c) => c.quote), reported };
174+
}
175+
176+
it('drops the citations of a call that fails without a code and reports the failure, once per call', async () => {
177+
// Control: the same citations verify through a door that answers.
178+
expect((await run(fakeDoor(policyApp()), [cite('Fire cover'), cite('Acme')])).quotes).toEqual(['Fire cover', 'Acme']);
179+
180+
const outage = new Error('connection reset');
181+
const { quotes, reported } = await run(throwingDoor(outage), [cite('Fire cover'), cite('Acme'), cite('Arson.', { anchor: 'exclusions' })]);
182+
expect(quotes).toEqual([]);
183+
expect(reported).toEqual([
184+
{ error: outage, call: { object: 'policy', id: 'p1' } },
185+
{ error: outage, call: { object: 'policy', id: 'p1', anchor: 'exclusions' } },
186+
]);
187+
});
188+
189+
it('reports a driver code with no status, and a coded 5xx, as failures', async () => {
190+
for (const err of [Object.assign(new Error('reset'), { code: 'ECONNRESET' }), coded('INTERNAL_ERROR', 500)]) {
191+
const { quotes, reported } = await run(throwingDoor(err), [cite('Fire cover')]);
192+
expect(quotes).toEqual([]);
193+
expect(reported.map((r) => r.error)).toEqual([err]);
194+
}
195+
});
196+
197+
it('drops the citations of a coded 4xx refusal and reports nothing', async () => {
198+
for (const err of [coded('PERMISSION_DENIED', 403), coded('RECORD_NOT_FOUND', 404), coded('VALIDATION_ERROR', 400)]) {
199+
expect(await run(throwingDoor(err), [cite('Fire cover')])).toEqual({ quotes: [], reported: [] });
200+
}
201+
});
202+
203+
it('gives the host the same answer for a refused read and a missing record', async () => {
204+
const refused = await run(fakeDoor(policyApp({ unreadableRows: ['p1'] })), [cite('Fire cover')]);
205+
const missing = await run(fakeDoor(policyApp()), [{ object: 'policy', id: 'p404', quote: 'Fire cover' }]);
206+
expect(refused).toEqual({ quotes: [], reported: [] });
207+
expect(missing).toEqual(refused);
208+
// Control: the readable record verifies the quote.
209+
expect((await run(fakeDoor(policyApp()), [cite('Fire cover')])).quotes).toEqual(['Fire cover']);
210+
});
211+
212+
it('reads the declared status as ADR-0112 does: a coded refusal declared with statusCode only is not reported', async () => {
213+
const statusCodeOnly = Object.assign(new Error('denied'), { code: 'PERMISSION_DENIED', statusCode: 403 });
214+
expect(await run(throwingDoor(statusCodeOnly), [cite('Fire cover')])).toEqual({ quotes: [], reported: [] });
215+
// Control: the same code with a 5xx statusCode is a failure.
216+
const fault = Object.assign(new Error('down'), { code: 'INTERNAL_ERROR', statusCode: 503 });
217+
expect((await run(throwingDoor(fault), [cite('Fire cover')])).reported.map((r) => r.error)).toEqual([fault]);
218+
});
219+
220+
it('reports a 4xx with no code, and a thrown value that is not an Error, as failures', async () => {
221+
for (const err of [Object.assign(new Error('gone'), { status: 404 }), 'socket hang up', undefined]) {
222+
const { quotes, reported } = await run(throwingDoor(err), [cite('Fire cover')]);
223+
expect(quotes).toEqual([]);
224+
expect(reported).toEqual([{ error: err, call: { object: 'policy', id: 'p1' } }]);
225+
}
226+
});
227+
228+
it('reports a failed read behind an html body once, and still verifies what the answer carries', async () => {
229+
const app = policyApp();
230+
const policy = app.objects.policy as { fields: Record<string, Record<string, unknown>> };
231+
policy.fields.content = { ...policy.fields.content, type: 'html' };
232+
app.records.policy[0].content = '<p>Covers <b>fire</b> damage.</p>';
233+
// Control: through a door that answers, the tag-removed reading verifies.
234+
expect((await run(fakeDoor(app), [cite('Covers fire damage.')])).quotes).toEqual(['Covers fire damage.']);
235+
236+
// The executor's own definition reads, counted on a door that answers.
237+
const probe = fakeDoor(app);
238+
let executorReads = 0;
239+
const served = probe.servedObjectDefinitionOf.bind(probe);
240+
probe.servedObjectDefinitionOf = async (object) => {
241+
executorReads++;
242+
return served(object);
243+
};
244+
await executeGetRecordContext({ objectName: 'policy', recordId: 'p1' }, probe);
245+
246+
// The same door, failing every definition read after the executor's.
247+
const door = fakeDoor(app);
248+
const outage = new Error('metadata store down');
249+
let reads = 0;
250+
const answer = door.servedObjectDefinitionOf.bind(door);
251+
door.servedObjectDefinitionOf = async (object) => {
252+
if (++reads > executorReads) throw outage;
253+
return answer(object);
254+
};
255+
const { quotes, reported } = await run(door, [cite('Covers fire damage.'), cite('Fire cover'), cite('Covers <b>fire</b>')]);
256+
expect(quotes).toEqual(['Fire cover', 'Covers <b>fire</b>']);
257+
expect(reported).toEqual([{ error: outage, call: { object: 'policy', id: 'p1' } }]);
258+
});
259+
260+
it('ignores an async callback whose promise rejects: no unhandled rejection', async () => {
261+
const unhandled: unknown[] = [];
262+
const onUnhandled = (reason: unknown) => unhandled.push(reason);
263+
process.on('unhandledRejection', onUnhandled);
264+
try {
265+
let called = 0;
266+
await expect(
267+
verifyRecordCitations([cite('Fire cover')], throwingDoor(new Error('down')), {
268+
onError: async () => {
269+
called++;
270+
throw new Error('logger down');
271+
},
272+
}),
273+
).resolves.toEqual([]);
274+
await new Promise((resolve) => setTimeout(resolve, 20));
275+
expect(called).toBe(1);
276+
expect(unhandled).toEqual([]);
277+
} finally {
278+
process.off('unhandledRejection', onUnhandled);
279+
}
280+
});
281+
282+
it('never throws when the callback throws, and drops the failed call without one', async () => {
283+
const door = throwingDoor(new Error('down'));
284+
await expect(
285+
verifyRecordCitations([cite('Fire cover')], door, {
286+
onError: () => {
287+
throw new Error('logger down');
288+
},
289+
}),
290+
).resolves.toEqual([]);
291+
await expect(verifyRecordCitations([cite('Fire cover')], throwingDoor(new Error('down')))).resolves.toEqual([]);
292+
});
293+
});
294+
153295
describe('[ADR-0160 D9] the list', () => {
154296
it('makes one call per distinct (object, id, context, anchor)', async () => {
155297
const door = fakeDoor(policyApp());

‎packages/services/service-record-context/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ export {
1515
export type { RecordContextTools } from './record-context-tools.js';
1616
export type { RecordContextDoor } from './door.js';
1717
export { verifyRecordCitations } from './verify-citations.js';
18+
export type { VerifyRecordCitationsOptions, VerifyingCall } from './verify-citations.js';
1819
export { RECORD_CONTEXT_BODY_MAX_CHARS, RECORD_CONTEXT_OUTLINE_MAX_ENTRIES } from './body-outline.js';
1920
export {
2021
contextPackCandidates,

0 commit comments

Comments
 (0)