Skip to content
Draft
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
18 changes: 18 additions & 0 deletions .changeset/37463-record-context-outage.md
Original file line number Diff line number Diff line change
@@ -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.
71 changes: 71 additions & 0 deletions packages/runtime/src/mcp-record-context-tools-bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>]>([
[
'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);
Expand Down
3 changes: 2 additions & 1 deletion packages/services/service-record-context/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
},
"dependencies": {
"@objectstack/core": "workspace:*",
"@objectstack/spec": "workspace:*"
"@objectstack/spec": "workspace:*",
"@objectstack/types": "workspace:*"
},
"devDependencies": {
"@types/node": "^26.6.5",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down Expand Up @@ -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<unknown>): 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<unknown>).bind(door);
(door as unknown as Record<string, unknown>)[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<ReturnType<typeof failureOf>>, 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'] } }));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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')]);
Expand Down
Loading
Loading