Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .changeset/37418-citation-refusal-vs-failure.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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' };

Expand Down Expand Up @@ -85,6 +85,11 @@ describe('[ADR-0160 D9] what a quote is matched against', () => {
'Covers <b>fire</b>',
]);
}
// 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 = '<p>Fire</p><p>cover</p>';
expect(await surviving(joined, [cite('Firecover')])).toEqual(['Firecover']);
expect(await surviving(htmlApp('markdown'), [cite('Covers fire damage.'), cite('Covers <b>fire</b>')])).toEqual([
'Covers <b>fire</b>',
]);
Expand Down Expand Up @@ -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: Record<string, Record<string, unknown>> };
policy.fields.content = { ...policy.fields.content, type: 'html' };
app.records.policy[0].content = '<p>Covers <b>fire</b> damage.</p>';
// 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 <b>fire</b>')]);
expect(quotes).toEqual(['Fire cover', 'Covers <b>fire</b>']);
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());
Expand Down
1 change: 1 addition & 0 deletions packages/services/service-record-context/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading