diff --git a/.changeset/37418-citation-refusal-vs-failure.md b/.changeset/37418-citation-refusal-vs-failure.md new file mode 100644 index 00000000000..f5ed4be11fd --- /dev/null +++ b/.changeset/37418-citation-refusal-vs-failure.md @@ -0,0 +1,17 @@ +--- +'@objectstack/service-record-context': patch +'@objectstack/spec': patch +--- + +feat(record-context): the citation verifier tells a refusal from a failure and reports failures to the host + +Clause-②: yes (widening) — new optional third argument of the exported verifyRecordCitations and two new exported types; existing calls unchanged +Metadata-protocol: none + +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. + +- **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. +- **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. +- A refused read and a missing record still give the host the same answer: dropped, not reported. +- New exported types `VerifyRecordCitationsOptions` and `VerifyingCall`. Existing two-argument calls are unchanged. +- 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. diff --git a/packages/services/service-record-context/src/__tests__/verify-citations.test.ts b/packages/services/service-record-context/src/__tests__/verify-citations.test.ts index c8dbb87416b..de62cb0e7d9 100644 --- a/packages/services/service-record-context/src/__tests__/verify-citations.test.ts +++ b/packages/services/service-record-context/src/__tests__/verify-citations.test.ts @@ -12,8 +12,8 @@ import { describe, expect, it } from 'vitest'; import { RECORD_CITATIONS_MAX } from '@objectstack/spec/ai'; -import { executeGetRecordContext, verifyRecordCitations } from '../index.js'; -import { fakeDoor, policyApp, type FakeApp } from './fake-door.js'; +import { executeGetRecordContext, verifyRecordCitations, type VerifyingCall } from '../index.js'; +import { fakeDoor, policyApp, type FakeApp, type FakeDoor } from './fake-door.js'; const ROOT = { object: 'policy', id: 'p1' }; @@ -85,6 +85,11 @@ describe('[ADR-0160 D9] what a quote is matched against', () => { 'Covers fire', ]); } + // Removing a tag joins the text on either side: the tag-removed reading is + // not only stricter than matching as stored. + const joined = htmlApp('html'); + joined.records.policy[0].content = '
Fire
cover
'; + expect(await surviving(joined, [cite('Firecover')])).toEqual(['Firecover']); expect(await surviving(htmlApp('markdown'), [cite('Covers fire damage.'), cite('Covers fire')])).toEqual([ 'Covers fire', ]); @@ -150,6 +155,143 @@ describe('[ADR-0160 D9] a caller with no read access', () => { }); }); +describe('[ADR-0160 D9] a refusal and a failure', () => { + /** A door whose root read guard throws `err` instead of answering. */ + const throwingDoor = (err: unknown): FakeDoor => { + const door = fakeDoor(policyApp()); + door.readGuard = async () => { + throw err; + }; + return door; + }; + const coded = (code: string, status: number) => Object.assign(new Error(code), { code, status }); + + /** The surviving quotes and every failure the host was handed. */ + async function run(door: FakeDoor, citations: unknown[]) { + const reported: Array<{ error: unknown; call: VerifyingCall }> = []; + const verified = await verifyRecordCitations(citations, door, { onError: (error, call) => reported.push({ error, call }) }); + return { quotes: verified.map((c) => c.quote), reported }; + } + + it('drops the citations of a call that fails without a code and reports the failure, once per call', async () => { + // Control: the same citations verify through a door that answers. + expect((await run(fakeDoor(policyApp()), [cite('Fire cover'), cite('Acme')])).quotes).toEqual(['Fire cover', 'Acme']); + + const outage = new Error('connection reset'); + const { quotes, reported } = await run(throwingDoor(outage), [cite('Fire cover'), cite('Acme'), cite('Arson.', { anchor: 'exclusions' })]); + expect(quotes).toEqual([]); + expect(reported).toEqual([ + { error: outage, call: { object: 'policy', id: 'p1' } }, + { error: outage, call: { object: 'policy', id: 'p1', anchor: 'exclusions' } }, + ]); + }); + + it('reports a driver code with no status, and a coded 5xx, as failures', async () => { + for (const err of [Object.assign(new Error('reset'), { code: 'ECONNRESET' }), coded('INTERNAL_ERROR', 500)]) { + const { quotes, reported } = await run(throwingDoor(err), [cite('Fire cover')]); + expect(quotes).toEqual([]); + expect(reported.map((r) => r.error)).toEqual([err]); + } + }); + + it('drops the citations of a coded 4xx refusal and reports nothing', async () => { + for (const err of [coded('PERMISSION_DENIED', 403), coded('RECORD_NOT_FOUND', 404), coded('VALIDATION_ERROR', 400)]) { + expect(await run(throwingDoor(err), [cite('Fire cover')])).toEqual({ quotes: [], reported: [] }); + } + }); + + it('gives the host the same answer for a refused read and a missing record', async () => { + const refused = await run(fakeDoor(policyApp({ unreadableRows: ['p1'] })), [cite('Fire cover')]); + const missing = await run(fakeDoor(policyApp()), [{ object: 'policy', id: 'p404', quote: 'Fire cover' }]); + expect(refused).toEqual({ quotes: [], reported: [] }); + expect(missing).toEqual(refused); + // Control: the readable record verifies the quote. + expect((await run(fakeDoor(policyApp()), [cite('Fire cover')])).quotes).toEqual(['Fire cover']); + }); + + it('reads the declared status as ADR-0112 does: a coded refusal declared with statusCode only is not reported', async () => { + const statusCodeOnly = Object.assign(new Error('denied'), { code: 'PERMISSION_DENIED', statusCode: 403 }); + expect(await run(throwingDoor(statusCodeOnly), [cite('Fire cover')])).toEqual({ quotes: [], reported: [] }); + // Control: the same code with a 5xx statusCode is a failure. + const fault = Object.assign(new Error('down'), { code: 'INTERNAL_ERROR', statusCode: 503 }); + expect((await run(throwingDoor(fault), [cite('Fire cover')])).reported.map((r) => r.error)).toEqual([fault]); + }); + + it('reports a 4xx with no code, and a thrown value that is not an Error, as failures', async () => { + for (const err of [Object.assign(new Error('gone'), { status: 404 }), 'socket hang up', undefined]) { + const { quotes, reported } = await run(throwingDoor(err), [cite('Fire cover')]); + expect(quotes).toEqual([]); + expect(reported).toEqual([{ error: err, call: { object: 'policy', id: 'p1' } }]); + } + }); + + it('reports a failed read behind an html body once, and still verifies what the answer carries', async () => { + const app = policyApp(); + const policy = app.objects.policy as { fields: RecordCovers fire damage.
'; + // Control: through a door that answers, the tag-removed reading verifies. + expect((await run(fakeDoor(app), [cite('Covers fire damage.')])).quotes).toEqual(['Covers fire damage.']); + + // The executor's own definition reads, counted on a door that answers. + const probe = fakeDoor(app); + let executorReads = 0; + const served = probe.servedObjectDefinitionOf.bind(probe); + probe.servedObjectDefinitionOf = async (object) => { + executorReads++; + return served(object); + }; + await executeGetRecordContext({ objectName: 'policy', recordId: 'p1' }, probe); + + // The same door, failing every definition read after the executor's. + const door = fakeDoor(app); + const outage = new Error('metadata store down'); + let reads = 0; + const answer = door.servedObjectDefinitionOf.bind(door); + door.servedObjectDefinitionOf = async (object) => { + if (++reads > executorReads) throw outage; + return answer(object); + }; + const { quotes, reported } = await run(door, [cite('Covers fire damage.'), cite('Fire cover'), cite('Covers fire')]); + expect(quotes).toEqual(['Fire cover', 'Covers fire']); + expect(reported).toEqual([{ error: outage, call: { object: 'policy', id: 'p1' } }]); + }); + + it('ignores an async callback whose promise rejects: no unhandled rejection', async () => { + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown) => unhandled.push(reason); + process.on('unhandledRejection', onUnhandled); + try { + let called = 0; + await expect( + verifyRecordCitations([cite('Fire cover')], throwingDoor(new Error('down')), { + onError: async () => { + called++; + throw new Error('logger down'); + }, + }), + ).resolves.toEqual([]); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(called).toBe(1); + expect(unhandled).toEqual([]); + } finally { + process.off('unhandledRejection', onUnhandled); + } + }); + + it('never throws when the callback throws, and drops the failed call without one', async () => { + const door = throwingDoor(new Error('down')); + await expect( + verifyRecordCitations([cite('Fire cover')], door, { + onError: () => { + throw new Error('logger down'); + }, + }), + ).resolves.toEqual([]); + await expect(verifyRecordCitations([cite('Fire cover')], throwingDoor(new Error('down')))).resolves.toEqual([]); + }); +}); + describe('[ADR-0160 D9] the list', () => { it('makes one call per distinct (object, id, context, anchor)', async () => { const door = fakeDoor(policyApp()); diff --git a/packages/services/service-record-context/src/index.ts b/packages/services/service-record-context/src/index.ts index 2dc447157e0..f7ec8879f5b 100644 --- a/packages/services/service-record-context/src/index.ts +++ b/packages/services/service-record-context/src/index.ts @@ -15,6 +15,7 @@ export { export type { RecordContextTools } from './record-context-tools.js'; export type { RecordContextDoor } from './door.js'; export { verifyRecordCitations } from './verify-citations.js'; +export type { VerifyRecordCitationsOptions, VerifyingCall } from './verify-citations.js'; export { RECORD_CONTEXT_BODY_MAX_CHARS, RECORD_CONTEXT_OUTLINE_MAX_ENTRIES } from './body-outline.js'; export { contextPackCandidates, diff --git a/packages/services/service-record-context/src/verify-citations.ts b/packages/services/service-record-context/src/verify-citations.ts index c35fc72964d..5d81d1ffbac 100644 --- a/packages/services/service-record-context/src/verify-citations.ts +++ b/packages/services/service-record-context/src/verify-citations.ts @@ -35,6 +35,26 @@ import { executeGetRecordContext } from './record-context-tools.js'; * served: each is an answer with no data member, so its citations are * dropped (ADR-0160 point 23). No pack is picked for a citation that named * none, and no call is retried without the offending argument. + * - **A failed call verifies nothing either, and is reported.** A refusal is + * a throw carrying an ADR-0112 `code` with a declared 4xx status — the only + * shape `get_record_context` refuses with. The declared status is read as + * ADR-0112's reader reads it (`resolveThrownHttpError`'s `declaredStatus` + * in `@objectstack/types`): `.status`, then `.statusCode`. Any other throw + * (no `code`, no status, a 5xx, a thrown value that is not an object: an + * outage, a bug) is a failure, not an answer: its citations are dropped all + * the same, so the result stays fail-closed, and the failure goes to + * `options.onError`, once per call, so the host can log or retry it. + * ADR-0112 names the status channel as the one structural signal between a + * refusal and a fault; a driver errno also arrives on `.code`, so the + * string alone cannot tell. + * + * That holds at this function's boundary only. The executor itself turns + * some failures into a refusal so that it names nothing: a related object's + * definition read, or a published-definition read, that throws arrives here + * as `PERMISSION_DENIED` 403, and is dropped without a report (#37463). + * The whole 4xx band is a refusal, so a door that declared a coded 408 or + * 429 would have a transient condition dropped without a report; no door on + * the read path declares one today. * - **What a quote is matched against** — the strings of the data member, and * no other: * - a field entry's `value`, when it is a string, and its `display`, at the @@ -49,6 +69,13 @@ import { executeGetRecordContext } from './record-context-tools.js'; * not a string (a number, a boolean, a list or an object; its `display`, * where the entry carries one, is matched). A withheld or hidden field has * no value in the answer, so nothing is matched in it. + * + * The tag-removed reading is a second string, not a replacement, so it can + * verify a quote the stored text does not hold: removing a tag joins the + * text on either side of it, so `Fire
cover
` reads as + * `Firecover`. It never verifies a quote that is not in the body's + * characters in order, but it is not "only stricter" than matching as + * stored. * - **Verbatim, with whitespace runs collapsed.** Every run of whitespace in * the quote and in the matched string reads as one space, and the quote is * trimmed. Case and every other character must agree. A quote that is empty @@ -59,14 +86,21 @@ import { executeGetRecordContext } from './record-context-tools.js'; * It never throws for a citation. A citation that does not parse * (`RecordCitationSchema`) is dropped like one that is not found, and only the * first {@link RECORD_CITATIONS_MAX} entries of the list are read, so a list a - * model wrote cannot make the platform read without bound. A dropped citation - * leaves no trace in the result: a caller who cannot read a record learns - * nothing from its citations' fate that tells a hidden record from a missing - * one. + * model wrote cannot make the platform read without bound. That is the cap a + * producer gets: this function reads the first 20 and drops the rest, where + * `RecordCitationsSchema` refuses a list of 21 outright; a producer that + * verifies a model's list with this function persists at most 20. A dropped + * citation leaves no trace in the result: a caller who cannot read a record + * learns nothing from its citations' fate that tells a hidden record from a + * missing one. `onError` is for the host, never the caller: it is called for a + * failure only, never for a refusal, so a refused read and a missing record + * give the host the same answer too. A callback that throws, or returns a + * promise that rejects, is ignored. */ export async function verifyRecordCitations( citations: unknown, door: RecordContextDoor, + options: VerifyRecordCitationsOptions = {}, ): Promise