diff --git a/.changeset/37463-record-context-outage.md b/.changeset/37463-record-context-outage.md new file mode 100644 index 00000000000..d6c8f6e9c37 --- /dev/null +++ b/.changeset/37463-record-context-outage.md @@ -0,0 +1,18 @@ +--- +'@objectstack/service-record-context': patch +--- + +fix(record-context): a related object's read that fails is answered as a failure, not as "no access" + +Clause-②: no +Metadata-protocol: none + +`get_record_context` reads each related object of a pack before it answers: the object's API exposure, its definition as the caller is served it, its published definition, and the related list itself. When one of the first three reads failed for a reason that is not a refusal (the database or the metadata store down, a bug), the call was refused `PERMISSION_DENIED` (403), as if the caller could not read the object. When the related-list read failed that way, the raw error left the executor and the MCP doors answered it `INTERNAL_ERROR` (500). Such a failure now fails the call `INTERNAL_ERROR` (500) at all four reads, and the thrown error carries the original on `cause`. + +What an MCP caller sees for it, on either door: `{ code: 'INTERNAL_ERROR', status: 500 }` with the message `Internal server error`. The doors withhold a 5xx's own sentence, so the executor's sentence (which names the pack and the root record's object only) is read in-process only, for example by the host of `verifyRecordCitations`. Nothing names the related object, a field, a package or what the failed read said. Each door logs the failure at `error` on every call, with the thrown error and its `cause`. + +A refusal at the same reads is answered as before. At the first three reads a coded refusal (a string `code` with a declared 4xx status, a disabled package's included) refuses `PERMISSION_DENIED` (403). At the related-list read, a throw the `/data` door answers below 500 is left to the door as before: a sandboxed `beforeFind` hook's plain throw still answers `400 HOOK_ABORTED`, and a `PERMISSION_DENIED` with no status still answers 403. + +`verifyRecordCitations` therefore reports such a failure through `onError` (its citations are still dropped), where at the first three reads it used to drop them without a report. A host that retries or logs on `onError` now sees outages behind a pack with related lists. + +The package gains one dependency, `@objectstack/types` (already a dependency of `@objectstack/core`), for the `/data` door's classifier the related-list read asks. diff --git a/packages/runtime/src/mcp-record-context-tools-bridge.test.ts b/packages/runtime/src/mcp-record-context-tools-bridge.test.ts index fb9ccad51f2..da3059d9a53 100644 --- a/packages/runtime/src/mcp-record-context-tools-bridge.test.ts +++ b/packages/runtime/src/mcp-record-context-tools-bridge.test.ts @@ -776,6 +776,77 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel: expect(answer.text).not.toContain('rc_off'); }); + it('[ADR-0112] a related child whose list read fails (an outage, no coded refusal) fails the call INTERNAL_ERROR on both doors, naming nothing, never as a refusal', async () => { + const OUTAGE = 'disk I/O error reading rc_revision.version'; + const real = engine.find.bind(engine); + const failing = vi.spyOn(engine, 'find').mockImplementation(async (object: string, ...rest: any[]) => { + if (object === 'rc_revision') throw new Error(OUTAGE); + return (real as any)(object, ...rest); + }); + // The doors' fault log (`logServerFault`, `@objectstack/types`) writes to the console here. + const errorLines = vi.spyOn(console, 'error').mockImplementation(() => {}); + const warnLines = vi.spyOn(console, 'warn').mockImplementation(() => {}); + try { + const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' }); + await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' }); + // An outage is a fault, never a declared capability absence: each door logs it at error, + // with the outage as its cause, on every call, the second included. + expect(warnLines.mock.calls.filter(([line]) => String(line).includes('capability absence'))).toEqual([]); + const faults = errorLines.mock.calls.filter(([line]) => + typeof line === 'string' && line.startsWith('[5xx] 500') && line.includes('get_record_context rc_policy')); + expect(faults).toHaveLength(4); + for (const [, meta] of faults) { + expect(meta).toMatchObject({ status: 500, code: 'INTERNAL_ERROR' }); + expect(String((meta as { stack?: unknown }).stack)).toContain(`Caused by: Error: ${OUTAGE}`); + } + // Reached through each door, so the answer is the outage's on both. + expect(failing.mock.calls.filter(([object]) => object === 'rc_revision').length).toBeGreaterThanOrEqual(4); + expect(answer.isError).toBe(true); + expect(answer.payload.error).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 }); + for (const word of ['rc_revision', 'disk I/O', 'version']) expect(answer.text).not.toContain(word); + } finally { + failing.mockRestore(); + errorLines.mockRestore(); + warnLines.mockRestore(); + } + // Control: the same call reads once the list read answers. + const control = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' }); + expect(control.isError).toBe(false); + expect(control.payload.data.related[0]).toMatchObject({ object: 'rc_revision' }); + }); + + it.each<[string, () => unknown, Record]>([ + [ + 'a sandboxed beforeFind hook\'s plain throw stays 400 HOOK_ABORTED, in the hook\'s words', + () => Object.assign(new Error("beforeFind hook 'rc_gate' threw: Revisions are closed for review"), { innerMessage: 'Revisions are closed for review' }), + { code: 'HOOK_ABORTED', status: 400, message: 'Revisions are closed for review' }, + ], + [ + 'a PERMISSION_DENIED with no status stays PERMISSION_DENIED, as the door renders it', + () => Object.assign(new Error('Permission denied'), { code: 'PERMISSION_DENIED' }), + { code: 'PERMISSION_DENIED' }, + ], + ])('[ADR-0112] at the related list read, a throw the /data door answers as a refusal stays that refusal on both doors: %s', async (_label, thrown, expected) => { + const real = engine.find.bind(engine); + const refusing = vi.spyOn(engine, 'find').mockImplementation(async (object: string, ...rest: any[]) => { + if (object === 'rc_revision') throw thrown(); + return (real as any)(object, ...rest); + }); + try { + const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' }); + expect(refusing.mock.calls.filter(([object]) => object === 'rc_revision').length).toBeGreaterThanOrEqual(2); + expect(answer.isError).toBe(true); + expect(answer.payload.error).toMatchObject(expected); + // The door's refusal, as main answered it: never the fault's 500. + expect([undefined, 400, 403]).toContain(answer.payload.error.status); + } finally { + refusing.mockRestore(); + } + const control = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_main' }); + expect(control.isError).toBe(false); + expect(control.payload.data.related[0]).toMatchObject({ object: 'rc_revision' }); + }); + it('[ADR-0160 D3, second amendment] where, orderBy and limit on a related list answer the same bytes on both doors: filtered, ordered, cut at the limit and stated', async () => { const answer = await both({ objectName: 'rc_policy', recordId: 'p1', context: 'rc_filtered' }); expect(answer.isError).toBe(false); diff --git a/packages/services/service-record-context/package.json b/packages/services/service-record-context/package.json index cc88ee493f5..c7425fb3c9f 100644 --- a/packages/services/service-record-context/package.json +++ b/packages/services/service-record-context/package.json @@ -27,7 +27,8 @@ }, "dependencies": { "@objectstack/core": "workspace:*", - "@objectstack/spec": "workspace:*" + "@objectstack/spec": "workspace:*", + "@objectstack/types": "workspace:*" }, "devDependencies": { "@types/node": "^26.6.5", diff --git a/packages/services/service-record-context/src/__tests__/record-context-tools.test.ts b/packages/services/service-record-context/src/__tests__/record-context-tools.test.ts index 6f1120d0680..9f2e29c7915 100644 --- a/packages/services/service-record-context/src/__tests__/record-context-tools.test.ts +++ b/packages/services/service-record-context/src/__tests__/record-context-tools.test.ts @@ -314,11 +314,13 @@ describe('get_record_context — object level: a gate that refuses everyone refu expect(door.reads).toEqual([]); }); - it('a served-definition read that throws is no answer about this caller: it refuses the call unnamed, never left out', async () => { + it('a served-definition read that throws a coded refusal refuses the call unnamed, never left out', async () => { const door = fakeDoor(twoChildren()); const servedOf = door.servedObjectDefinitionOf.bind(door); door.servedObjectDefinitionOf = async (object) => { - if (object === 'policy_revision') throw new Error('metadata store down: policy_revision'); + if (object === 'policy_revision') { + throw Object.assign(new Error(`Object '${object}' not found`), { code: 'OBJECT_NOT_FOUND', status: 404 }); + } return servedOf(object); }; const refused = await refusalOf(executeGetRecordContext(CALL, door)); @@ -402,6 +404,115 @@ describe('get_record_context — object level: a gate that refuses everyone refu }); }); +describe('get_record_context — a read of a related object that fails is a failure, not a refusal (ADR-0112, ADR-0160 D3 "Object level")', () => { + /** What the outage says: every name in it is one the caller is not shown. */ + const OUTAGE = 'store down: policy_revision.secret_note in package acme_private'; + const outage = () => new Error(OUTAGE); + + /** The thrown failure, with what it must not carry. */ + async function failureOf(promise: Promise): Promise<{ code: string; status: number; message: string; cause: unknown; stack?: string }> { + try { + await promise; + } catch (err) { + const e = err as { code: string; status: number; message: string; cause: unknown; stack?: string }; + return { code: e.code, status: e.status, message: e.message, cause: e.cause, stack: e.stack }; + } + throw new Error('expected a failure'); + } + + /** A door whose `member` throws `thrown()` for `policy_revision`, and answers as the fixture otherwise. */ + const throwingAt = ( + member: 'assertApiExposed' | 'servedObjectDefinitionOf' | 'publishedObjectDefinitionOf' | 'query', + thrown: () => unknown, + app: FakeApp = policyApp(), + ) => { + const door = fakeDoor(app); + const real = (door[member] as (...a: unknown[]) => Promise).bind(door); + (door as unknown as Record)[member] = async (object: string, ...rest: unknown[]) => { + if (object === 'policy_revision') throw thrown(); + return real(object, ...rest); + }; + return door; + }; + + /** The failure's answer: `INTERNAL_ERROR` 500, naming the pack and the root and nothing the outage said. */ + const expectFailureNamingNothing = (failed: Awaited>, original: unknown) => { + expect(failed).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 }); + expect(failed.message).toBe(sentencesFor([]).readFailed('policy_document', 'policy')); + for (const word of ['policy_revision', 'secret_note', 'acme_private', 'store down']) { + expect(failed.message).not.toContain(word); + } + // The original is the host's, on `cause` (which no door puts on the wire), and at the foot of the + // stack, which the doors' fault line prints where it prints no `cause`. + expect(failed.cause).toBe(original); + expect(failed.stack).toContain(`Caused by: ${original instanceof Error ? original.stack : String(original)}`); + }; + + it.each([ + ['step 4a: the API-exposure check', 'assertApiExposed'], + ['step 4a: the served-definition read', 'servedObjectDefinitionOf'], + ['publishedOf: the published-definition read', 'publishedObjectDefinitionOf'], + ['the child list query', 'query'], + ] as const)('%s throwing an uncoded error fails the call INTERNAL_ERROR, naming nothing', async (_site, member) => { + const thrown = outage(); + const door = throwingAt(member, () => thrown); + expectFailureNamingNothing(await failureOf(executeGetRecordContext(CALL, door)), thrown); + }); + + it.each([ + ['step 4a: the API-exposure check', 'assertApiExposed'], + ['step 4a: the served-definition read', 'servedObjectDefinitionOf'], + ['publishedOf: the published-definition read', 'publishedObjectDefinitionOf'], + ] as const)('control, %s: a coded refusal (a disabled package\'s 404) stays PERMISSION_DENIED 403, unnamed', async (_site, member) => { + const door = throwingAt(member, () => + Object.assign(new Error("Object 'policy_revision' belongs to a disabled package"), { code: 'OBJECT_PACKAGE_DISABLED', status: 404 })); + const refused = await refusalOf(executeGetRecordContext(CALL, door)); + expect(refused).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 }); + expect(refused.message).toBe(sentencesFor([]).objectRefusedUnnamed('policy_document', 'policy')); + }); + + it('control, the child list query: the door\'s own coded refusal of a served child is answered as the door wrote it', async () => { + const refusal = Object.assign(new Error("Field 'version' cannot be filtered or sorted on"), { code: 'PERMISSION_DENIED', status: 403 }); + const door = throwingAt('query', () => refusal); + await expect(executeGetRecordContext(CALL, door)).rejects.toBe(refusal); + }); + + it.each<[string, () => unknown]>([ + ['a sandboxed beforeFind hook\'s plain throw (no code; the door answers 400 HOOK_ABORTED)', () => + Object.assign(new Error("beforeFind hook 'step_gate' threw: Steps are closed for review"), { innerMessage: 'Steps are closed for review' })], + ['a PERMISSION_DENIED with no status (the door answers 403)', () => Object.assign(new Error('denied'), { code: 'PERMISSION_DENIED' })], + ])('the child list query: %s stays the door\'s refusal, rethrown as main left it', async (_label, thrown) => { + const refusal = thrown(); + const door = throwingAt('query', () => refusal); + await expect(executeGetRecordContext(CALL, door)).rejects.toBe(refusal); + // Control: at an object-level read, the same throw is no coded refusal, so it fails the call. + expectFailureNamingNothing(await failureOf(executeGetRecordContext(CALL, throwingAt('servedObjectDefinitionOf', () => refusal))), refusal); + }); + + it('the child list query: a sandboxed body that CRASHED (a native error name) is a fault at the door, so it fails the call', async () => { + const crash = Object.assign(new Error("beforeFind hook 'step_gate' threw: TypeError: x is not a function"), { innerMessage: 'TypeError: x is not a function' }); + expectFailureNamingNothing(await failureOf(executeGetRecordContext(CALL, throwingAt('query', () => crash))), crash); + }); + + it.each<[string, () => unknown]>([ + ['a driver errno on `.code` with no status',() => Object.assign(new Error(OUTAGE), { code: 'SQLITE_BUSY' })], + ['a coded 5xx', () => Object.assign(new Error(OUTAGE), { code: 'SERVICE_UNAVAILABLE', status: 503 })], + ['a status with no code', () => Object.assign(new Error(OUTAGE), { status: 404 })], + ['a thrown value that is not an object', () => OUTAGE], + ])('%s is a failure too, not a refusal', async (_label, thrown) => { + let original: unknown; + const door = throwingAt('servedObjectDefinitionOf', () => (original = thrown())); + expectFailureNamingNothing(await failureOf(executeGetRecordContext(CALL, door)), original); + }); + + it('the failure sentence is written in the caller\'s locale', async () => { + const door = throwingAt('publishedObjectDefinitionOf', outage, policyApp({ locales: ['zh-CN'] })); + const failed = await failureOf(executeGetRecordContext(CALL, door)); + expect(failed.message).toBe(sentencesFor(['zh-CN']).readFailed('policy_document', 'policy')); + expect(failed.message).not.toBe(sentencesFor([]).readFailed('policy_document', 'policy')); + }); +}); + describe('get_record_context — field level: omit and state, or name the withheld (ADR-0160 D3)', () => { it('a field the caller\'s schema hides is not named, and the notes carry ONE not-visible statement', async () => { const out = await run(policyApp({ hiddenFields: { policy: ['secret_terms'], policy_revision: ['note'] } })); 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 de62cb0e7d9..bb955ec9dde 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 @@ -217,6 +217,33 @@ describe('[ADR-0160 D9] a refusal and a failure', () => { expect((await run(throwingDoor(fault), [cite('Fire cover')])).reported.map((r) => r.error)).toEqual([fault]); }); + it('a related child\'s read that throws an uncoded error drops the citation and is reported; a coded refusal there is dropped and not reported', async () => { + /** A door whose served-definition read of the related child throws `err`. */ + const childThrows = (err: unknown): FakeDoor => { + const door = fakeDoor(policyApp()); + const servedOf = door.servedObjectDefinitionOf.bind(door); + door.servedObjectDefinitionOf = async (object) => { + if (object === 'policy_revision') throw err; + return servedOf(object); + }; + return door; + }; + // Control: the same citation verifies through a door whose child read answers. + expect((await run(fakeDoor(policyApp()), [cite('Fire cover')])).quotes).toEqual(['Fire cover']); + + const outage = new Error('metadata store down: policy_revision'); + const failed = await run(childThrows(outage), [cite('Fire cover')]); + expect(failed.quotes).toEqual([]); + expect(failed.reported).toHaveLength(1); + expect(failed.reported[0].call).toEqual({ object: 'policy', id: 'p1' }); + // The executor's failure, naming nothing, with the outage on its cause. + expect(failed.reported[0].error).toMatchObject({ code: 'INTERNAL_ERROR', status: 500, cause: outage }); + expect((failed.reported[0].error as Error).message).not.toContain('policy_revision'); + + const refusal = Object.assign(new Error("Object 'policy_revision' not found"), { code: 'OBJECT_NOT_FOUND', status: 404 }); + expect(await run(childThrows(refusal), [cite('Fire cover')])).toEqual({ quotes: [], reported: [] }); + }); + 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')]); diff --git a/packages/services/service-record-context/src/record-context-tools.ts b/packages/services/service-record-context/src/record-context-tools.ts index d953a7d334e..a2fe90f0055 100644 --- a/packages/services/service-record-context/src/record-context-tools.ts +++ b/packages/services/service-record-context/src/record-context-tools.ts @@ -1,6 +1,7 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. import { recordNotFoundError, wrapRecordMaterial } from '@objectstack/core'; +import { isServerFault, mapDataError } from '@objectstack/types'; import { AI_CONTEXT_BODY_FIELD_TYPES, AI_CONTEXT_MAX_RELATED_ROWS, @@ -75,6 +76,12 @@ import { sentencesFor, type Sentences } from './sentences.js'; * carries no value and is marked `withheld` (#35137). A name the published * definition lacks is an author defect and states nothing. * + * A read of a related object that FAILS rather than refuses (a throw that is + * no coded refusal, {@link isCodedRefusal}, or at the child list query one + * the `/data` door answers as a fault: an outage, a bug) is no answer about + * the caller, so it is never answered as a refusal: the call fails + * `INTERNAL_ERROR` (500), naming the pack and the root only. + * * ## A related list's `where`, `orderBy` and `limit` (D1, D3: second amendment) * * They run inside the one capped child query, as the caller: `where` joined @@ -136,6 +143,44 @@ function refusal(code: string, status: number, message: string): Coded { return Object.assign(new Error(message), { code, status }); } +/** + * [ADR-0112] Whether a throw is a coded refusal: a non-empty string `code` + * and a declared 4xx status, read as ADR-0112's reader reads it + * (`resolveThrownHttpError`'s `declaredStatus`, `@objectstack/types`): + * `.status`, then `.statusCode`. Anything else is a failure, not an answer + * about the caller: no code, no status, a 5xx, a driver errno on `.code` + * with no status, a thrown value that is not an object (an outage, a bug). + * 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. + * + * The one line, drawn once for both of its readers: the executor asks it at + * the object-level reads of a related object ({@link executeGetRecordContext}, + * step 4a and the published definitions), and the citation verifier asks it + * of the executor's own throw (`verifyRecordCitations`). So what the executor + * refuses there, the verifier drops without a report, and what fails, it + * reports. The child list query alone asks the `/data` door's classifier + * instead, since the doors classified that read's throw before the executor + * caught it, and a refusal there is rethrown as the door reads it. + */ +export function isCodedRefusal(err: unknown): boolean { + if (err == null || typeof err !== 'object') return false; + const { code, status, statusCode } = err as { code?: unknown; status?: unknown; statusCode?: unknown }; + const declared = typeof status === 'number' ? status : typeof statusCode === 'number' ? statusCode : undefined; + return typeof code === 'string' && code.length > 0 && declared !== undefined && declared >= 400 && declared < 500; +} + +/** A thrown value as a log reads it: its stack, else its text. */ +function describeThrown(thrown: unknown): string { + if (thrown instanceof Error) return thrown.stack ?? `${thrown.name}: ${thrown.message}`; + if (typeof thrown === 'string') return thrown; + try { + return JSON.stringify(thrown) ?? String(thrown); + } catch { + return String(thrown); + } +} + /** The call's arguments, or a `VALIDATION_ERROR` carrying the spec's own words. */ function parseInput(input: unknown): GetRecordContextInput { const parsed = GetRecordContextInputSchema.safeParse(input); @@ -387,6 +432,45 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex ); }; + // [ADR-0112, ADR-0160 D3 "Object level"] The one line between a refusal and + // a failure at the reads of a related object this executor judges: step + // 4a's exposure check and served definition, a published definition + // (`publishedOf`), and the child list query. A coded refusal + // ({@link isCodedRefusal}; at the child list query, what the `/data` door + // answers below 500) answers as `refused` says, as it always has. Any + // other throw is a failure, which says nothing about what this caller may + // read, so it is not answered as a refusal: the call fails `INTERNAL_ERROR` + // (500) in the executor's own sentence, which names the pack and the root + // only. No door renders the original error, so nothing it says can name an + // object, a field or a package the caller is not shown; it rides on + // `cause` and at the foot of the stack, neither of which a door puts on the + // wire, and the doors' fault line prints it. The doors withhold a 5xx's + // sentence too (`Internal server error`), so the sentence is read + // in-process only (the citation verifier's host, through `onError`). + // + // ⛔ Not `SERVICE_UNAVAILABLE`: with a 5xx that code is a declared + // capability absence (`CAPABILITY_ABSENCE_CODES`, `@objectstack/types` + // `server-fault-log.ts`), which the doors' fault log prints once per route + // per process at `warn`, without the error. An outage is a fault: logged at + // `error`, with the thrown error and its `cause`, on every call. + const refusedOrFailed = async ( + err: unknown, + refused: () => Promise, + isRefusal: (err: unknown) => boolean = isCodedRefusal, + ): Promise => { + if (isRefusal(err)) return refused(); + const failure = Object.assign(new Error(say.readFailed(pack.name, root)), { + code: 'INTERNAL_ERROR', + status: 500, + cause: err, + }); + // The doors' fault line prints an error's message and stack, never its + // `cause` (`logServerFault`, and `ObjectLogger` behind it), so the stack + // carries the original too. A stack is never on the wire. + failure.stack = `${failure.stack ?? `Error: ${failure.message}`}\nCaused by: ${describeThrown(err)}`; + throw failure; + }; + // Whether something the pack covers was left out for this caller: the one // not-visible statement, whatever was removed. let hidden = false; @@ -410,22 +494,25 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex try { await door.assertApiExposed(entry.object, 'query'); } catch (err) { - // Only API exposure's own refusal is about the object itself, and it is - // named only when the caller's served schema shows the object (the - // naming bound); any other failure (a package gate, an outage) names - // nothing. - let shown = false; - if (API_EXPOSURE_REFUSALS.has(String((err as { code?: unknown } | null)?.code))) { - shown = (await door.servedObjectDefinitionOf(entry.object).catch(() => null)) != null; - } - await refuseObject(entry.object, shown); + // A coded refusal refuses the call. Only API exposure's own refusal is + // about the object itself, and it is named only when the caller's + // served schema shows the object (the naming bound); any other refusal + // (a disabled package's) names nothing. A failure fails the call. + await refusedOrFailed(err, async () => { + let shown = false; + if (API_EXPOSURE_REFUSALS.has(String((err as { code?: unknown }).code))) { + shown = (await door.servedObjectDefinitionOf(entry.object).catch(() => null)) != null; + } + return refuseObject(entry.object, shown); + }); } let served: Record | null; try { served = await door.servedObjectDefinitionOf(entry.object); - } catch { - // A read that failed is no answer about this caller: it refuses, unnamed. - return refuseObject(entry.object, false); + } catch (err) { + // A coded refusal refuses, unnamed; a read that failed is no answer + // about this caller, so it fails the call, naming nothing. + return refusedOrFailed(err, () => refuseObject(entry.object, false)); } if (!served) { leftOut.add(entry.object); @@ -436,16 +523,17 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex } // Every published-definition read from here on is of an object whose gates - // already passed; one that still throws refuses the call unnamed, so no - // door's own rendering of the failure can name what the caller is not shown. - // A child left out for this caller is never read, its definition included: - // the plan reads it as having no published definition. + // already passed; one that still throws a coded refusal refuses the call + // unnamed, and one that fails fails it, naming nothing, so no door's own + // rendering of either can name what the caller is not shown. A child left + // out for this caller is never read, its definition included: the plan + // reads it as having no published definition. const publishedOf = async (name: string): Promise | null> => { if (leftOut.has(name)) return null; try { return await door.publishedObjectDefinitionOf(name); - } catch { - return refuseObject(name, false); + } catch (err) { + return refusedOrFailed(err, () => refuseObject(name, false)); } }; // The read set is the plan: every object read below is one of these. @@ -586,15 +674,32 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex const probe = cap + 1; const projection = [...new Set(['id', ...(plan.displayField ? [plan.displayField] : []), ...plan.columns])]; const linkWhere = { [plan.link]: plan.multiValueLink ? { $contains: recordId } : recordId }; - const rows = rowsOf( - await door.query(plan.object, { + let read: unknown; + try { + read = await door.query(plan.object, { where: plan.where !== undefined ? { $and: [linkWhere, plan.where] } : linkWhere, fields: projection, ...(plan.orderBy ? { orderBy: plan.orderBy } : {}), ...(plan.lookups.length > 0 ? { expand: plan.lookups } : {}), limit: probe, - }), - ); + }); + } catch (err) { + // The child is one this caller is served (step 4a). Its list read is the + // one read whose throw the doors classified before this line existed, + // so what the `/data` door answers below 500 stays the door's refusal, + // rethrown as the door reads it (a sandboxed `beforeFind` hook's plain + // throw: `400 HOOK_ABORTED`; a `PERMISSION_DENIED` with no status: 403), + // asked of the door's own classifier, never a copy of it. A throw the + // door answers as a fault fails the call, naming nothing. + return refusedOrFailed( + err, + async () => { + throw err; + }, + (thrown) => !isServerFault(mapDataError(thrown, plan.object).status), + ); + } + const rows = rowsOf(read); const truncated = rows.length > cap; const kept = truncated ? rows.slice(0, cap) : rows; const childWithheld = await withheldAmong(door, plan.object, plan.columns); diff --git a/packages/services/service-record-context/src/sentences.ts b/packages/services/service-record-context/src/sentences.ts index d985ac87671..81018cff360 100644 --- a/packages/services/service-record-context/src/sentences.ts +++ b/packages/services/service-record-context/src/sentences.ts @@ -103,6 +103,10 @@ const WRITTEN = { objectRefusedUnnamed: (pack: string, root: string) => `Context pack '${pack}' on '${root}' reads an object you cannot read, so the pack cannot be read for you. ` + 'Nothing was returned. Read the record with get_record.', + // A failure, not a refusal: it says nothing about what the caller may read. + readFailed: (pack: string, root: string) => + `Context pack '${pack}' on '${root}' could not be read just now: a read it needs failed. This says nothing ` + + 'about what you may read. Nothing was returned. Try again later, or read the record with get_record.', anchorUnresolved: (anchor: string) => `No section '${anchor}' can be read through this pack for this record. Call get_record_context without ` + '\'anchor\' to read the current outline.', @@ -146,6 +150,8 @@ const WRITTEN = { `'${root}' 上的资料包 '${pack}' 会读取对象 '${object}',而本入口不向你提供它,因此无法为你读取这个资料包。没有返回任何内容。请用 get_record 读取记录。`, objectRefusedUnnamed: (pack: string, root: string) => `'${root}' 上的资料包 '${pack}' 会读取一个你无权读取的对象,因此无法为你读取这个资料包。没有返回任何内容。请用 get_record 读取记录。`, + readFailed: (pack: string, root: string) => + `'${root}' 上的资料包 '${pack}' 暂时无法读取:它需要的一次读取失败了。这与你能读取什么无关。没有返回任何内容。请稍后再试,或用 get_record 读取记录。`, anchorUnresolved: (anchor: string) => `无法通过这个资料包为这条记录读取章节 '${anchor}'。请不带 'anchor' 调用 get_record_context 以读取当前大纲。`, outlineFromUnresolved: (from: number) => diff --git a/packages/services/service-record-context/src/verify-citations.ts b/packages/services/service-record-context/src/verify-citations.ts index 5d81d1ffbac..8a78e507e84 100644 --- a/packages/services/service-record-context/src/verify-citations.ts +++ b/packages/services/service-record-context/src/verify-citations.ts @@ -10,7 +10,7 @@ import { } from '@objectstack/spec/ai'; import { isHtmlBodyType } from './body-outline.js'; import type { RecordContextDoor } from './door.js'; -import { executeGetRecordContext } from './record-context-tools.js'; +import { executeGetRecordContext, isCodedRefusal } from './record-context-tools.js'; /** * [ADR-0160 D9, third amendment] The citation verifier: which citations of an @@ -48,11 +48,12 @@ import { executeGetRecordContext } from './record-context-tools.js'; * 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 + * The executor draws the same line with the same reader + * (`isCodedRefusal`) at the object-level reads of a related object it + * judges, and at its child list query asks the `/data` door's classifier, + * so a failure there is no refusal either: it arrives here as + * `INTERNAL_ERROR` (500), naming nothing, with the original error on its + * `cause`, and is reported. 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 @@ -153,32 +154,9 @@ export interface VerifyingCall { anchor?: string; } -/** - * Whether a throw is an ADR-0112 refusal: a non-empty string `code` and a - * declared 4xx status. Anything else is a failure. - */ -function isRefusal(err: unknown): boolean { - if (err == null || typeof err !== 'object') return false; - const { code } = err as { code?: unknown }; - const status = declaredStatusOf(err); - return typeof code === 'string' && code.length > 0 && status !== undefined && status >= 400 && status < 500; -} - -/** - * The status a throw declares, read as ADR-0112's reader reads it: - * `.status`, then `.statusCode` (`resolveThrownHttpError`'s `declaredStatus`, - * `@objectstack/types`). Both spellings are produced in this repo. - */ -function declaredStatusOf(err: object): number | undefined { - const { status, statusCode } = err as { status?: unknown; statusCode?: unknown }; - if (typeof status === 'number') return status; - if (typeof statusCode === 'number') return statusCode; - return undefined; -} - /** Hand a failure to the host; a callback that throws changes nothing. */ function report(onError: VerifyRecordCitationsOptions['onError'], err: unknown, c: RecordCitationParsed): void { - if (onError === undefined || isRefusal(err)) return; + if (onError === undefined || isCodedRefusal(err)) return; const call: VerifyingCall = { object: c.object, id: c.id, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 0f3012c670a..b7659acf658 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3493,6 +3493,9 @@ importers: '@objectstack/spec': specifier: workspace:* version: link:../../spec + '@objectstack/types': + specifier: workspace:* + version: link:../../types devDependencies: '@types/node': specifier: ^26.6.5