Skip to content

Commit 0359bbf

Browse files
committed
fix(types,core): the 5xx fault log and ObjectLogger print an error's cause chain
logServerFault prints the cause chain as causes beside stack on its console fallback; ObjectLogger prints it as error.causes. Bounded at five links, cycle-safe, never on the wire. record-context drops its Caused-by stack suffix. Claude-Session: https://claude.ai/code/session_01Utp6CZHczeF42DiDgkJPmk Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3806b2e commit 0359bbf

8 files changed

Lines changed: 443 additions & 24 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/types': patch
3+
'@objectstack/core': patch
4+
'@objectstack/service-record-context': patch
5+
---
6+
7+
fix: the 5xx fault log and `ObjectLogger` print an error's `cause` chain
8+
9+
Clause-②: no
10+
Metadata-protocol: none
11+
12+
A server fault thrown with the original error on `cause` used to log the wrapper's message and stack only, so the root cause was missing from the operator's line. `logServerFault` (`@objectstack/types`) now prints the chain as `causes` beside `stack` on its console fallback, and `ObjectLogger` (`@objectstack/core`) prints it as `error.causes` for every `logger.error` / `logger.fatal` that passes an error. Each link carries its message and stack; a cycle stops at the first repeat and a chain stops after five links, each saying so in a last link. Nothing reaches a response body.
13+
14+
`@objectstack/service-record-context` drops the `Caused by:` suffix it appended to a failed read's stack, since the fault line now renders the `cause` itself.
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* `ObjectLogger` prints an error's `cause` chain.
5+
*
6+
* `logger.error(message, err)` used to record `{ message, stack }` of the
7+
* error alone, so a wrapper thrown with the original on `cause` logged
8+
* without its root cause — the 5xx fault line (`logServerFault`,
9+
* `@objectstack/types`) hands its injected logger exactly such a wrapper.
10+
* The record now carries `error.causes`, bounded, in the same shape the fault
11+
* log's console fallback prints; the parity block below pins the two copies
12+
* to one output.
13+
*/
14+
15+
import { describe, it, expect, vi, afterEach } from 'vitest';
16+
import { faultCauseChain } from '@objectstack/types';
17+
18+
import { createLogger } from './logger.js';
19+
20+
const ROOT = 'SQLITE_IOERR: disk I/O error reading policy_revision.version';
21+
const MID = 'driver read failed for policy_revision';
22+
const OUTER = 'The related records of policy could not be read.';
23+
24+
const wrapped = () => new Error(OUTER, { cause: new Error(MID, { cause: new Error(ROOT) }) });
25+
26+
type ErrorRecord = { error?: { message: string; stack?: string; causes?: Array<{ message: string; stack?: string }> } };
27+
28+
/** One `error`-level record as the JSON format writes it to stderr. */
29+
function recordOf(log: (logger: ReturnType<typeof createLogger>) => void): ErrorRecord {
30+
const chunks: string[] = [];
31+
vi.spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => {
32+
chunks.push(String(chunk));
33+
return true;
34+
}) as never);
35+
log(createLogger({ format: 'json', level: 'debug' }));
36+
const lines = chunks.join('').split('\n').filter(Boolean);
37+
expect(lines).toHaveLength(1);
38+
return JSON.parse(lines[0]) as ErrorRecord;
39+
}
40+
41+
afterEach(() => {
42+
vi.restoreAllMocks();
43+
});
44+
45+
describe('ObjectLogger — an error record carries the cause chain', () => {
46+
it('logs each cause\'s message and stack, outermost first', () => {
47+
const record = recordOf((logger) => logger.error('[5xx] 500 GET /api/v1/x — boom', wrapped(), { status: 500 }));
48+
expect(record.error?.message).toBe(OUTER);
49+
expect(record.error?.stack).toContain(OUTER);
50+
const causes = record.error?.causes ?? [];
51+
expect(causes).toHaveLength(2);
52+
expect(causes[0].message).toBe(`Error: ${MID}`);
53+
expect(causes[0].stack).toContain(MID);
54+
expect(causes[1].message).toBe(`Error: ${ROOT}`);
55+
expect(causes[1].stack).toContain(ROOT);
56+
});
57+
58+
it('fatal renders it too', () => {
59+
const record = recordOf((logger) => logger.fatal('down', wrapped()));
60+
expect(record.error?.causes?.[1].message).toBe(`Error: ${ROOT}`);
61+
});
62+
63+
it('CONTROL — an error with no cause carries no causes field', () => {
64+
const record = recordOf((logger) => logger.error('plain', new Error(OUTER)));
65+
expect(record.error).toBeDefined();
66+
expect(record.error).not.toHaveProperty('causes');
67+
});
68+
69+
it('stops a cycle at its first repeat, and says so', () => {
70+
const a = new Error('a');
71+
const b = new Error('b', { cause: a });
72+
(a as { cause?: unknown }).cause = b;
73+
const record = recordOf((logger) => logger.error('cycle', a));
74+
expect(record.error?.causes?.map((c) => c.message)).toEqual([
75+
'Error: b',
76+
'[cause chain cycle: this link repeats an earlier one]',
77+
]);
78+
});
79+
80+
it('stops a deep chain after five links, and says so', () => {
81+
let error = new Error('link 0');
82+
for (let i = 1; i <= 20; i += 1) error = new Error(`link ${i}`, { cause: error });
83+
const causes = recordOf((logger) => logger.error('deep', error)).error?.causes ?? [];
84+
expect(causes).toHaveLength(6);
85+
expect(causes[5]).toEqual({ message: '[cause chain truncated after 5 links]' });
86+
});
87+
});
88+
89+
describe('parity — the logger and the fault log render one shape', () => {
90+
const cycle = () => {
91+
const a = new Error('a');
92+
(a as { cause?: unknown }).cause = new Error('b', { cause: a });
93+
return a;
94+
};
95+
const deep = () => {
96+
let error = new Error('link 0');
97+
for (let i = 1; i <= 9; i += 1) error = new Error(`link ${i}`, { cause: error });
98+
return error;
99+
};
100+
const fixtures: Array<[string, () => Error]> = [
101+
['a nested Error chain', wrapped],
102+
['a cycle', cycle],
103+
['a deep chain', deep],
104+
['a string cause', () => new Error('w', { cause: 'socket hang up' })],
105+
['an object cause', () => new Error('w', { cause: { code: 'ECONNRESET' } })],
106+
];
107+
it.each(fixtures)('%s', (_name, make) => {
108+
const error = make();
109+
const record = recordOf((logger) => logger.error('parity', error));
110+
expect(record.error?.causes).toEqual(faultCauseChain(error));
111+
});
112+
});

‎packages/core/src/logger.ts‎

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,67 @@ function colorEnabled(stream: { isTTY?: boolean } | undefined): boolean {
183183
return Boolean(stream?.isTTY);
184184
}
185185

186+
/** How many `cause` links an error record prints before it says it stopped. */
187+
const CAUSE_DEPTH_LIMIT = 5;
188+
189+
/**
190+
* An error as a log record carries it: message and stack, and the `cause`
191+
* chain under it, outermost first.
192+
*
193+
* A wrapper thrown with the original on `cause` (`new Error(say, { cause })`)
194+
* used to log as the wrapper alone, so the root cause of a wrapped fault was
195+
* missing from the line. Each link is its message and stack. Bounded both
196+
* ways: a cycle stops at the first repeat, a chain past
197+
* {@link CAUSE_DEPTH_LIMIT} stops there, and either says so in a last link.
198+
*
199+
* The same shape as `faultCauseChain` in `@objectstack/types`, which the 5xx
200+
* fault log prints on its console fallback. A copy rather than an import:
201+
* this entry is browser-safe and `@objectstack/client` bundles it without
202+
* depending on `@objectstack/types`, whose root entry would come along with
203+
* `@objectstack/spec` behind it. `logger.test.ts` pins the two to one output.
204+
*/
205+
function renderError(error: Error): { message: string; stack?: string; causes?: Array<{ message: string; stack?: string }> } {
206+
const causes: Array<{ message: string; stack?: string }> = [];
207+
const seen = new Set<unknown>([error]);
208+
let current = causeOf(error);
209+
while (current !== undefined && current !== null) {
210+
if (seen.has(current)) {
211+
causes.push({ message: '[cause chain cycle: this link repeats an earlier one]' });
212+
break;
213+
}
214+
if (causes.length >= CAUSE_DEPTH_LIMIT) {
215+
causes.push({ message: `[cause chain truncated after ${CAUSE_DEPTH_LIMIT} links]` });
216+
break;
217+
}
218+
seen.add(current);
219+
causes.push(causeLine(current));
220+
current = causeOf(current);
221+
}
222+
return { message: error.message, stack: error.stack, ...(causes.length > 0 ? { causes } : {}) };
223+
}
224+
225+
function causeOf(value: unknown): unknown {
226+
if (typeof value !== 'object' || value === null) return undefined;
227+
try {
228+
return (value as { cause?: unknown }).cause;
229+
} catch {
230+
// A throwing `cause` getter ends the chain; it must not cost the record.
231+
return undefined;
232+
}
233+
}
234+
235+
function causeLine(cause: unknown): { message: string; stack?: string } {
236+
if (cause instanceof Error) {
237+
return { message: `${cause.name}: ${cause.message}`, ...(cause.stack ? { stack: cause.stack } : {}) };
238+
}
239+
if (typeof cause === 'string') return { message: cause };
240+
try {
241+
return { message: JSON.stringify(cause) ?? String(cause) };
242+
} catch {
243+
return { message: String(cause) };
244+
}
245+
}
246+
186247
/**
187248
* Resolve a Node builtin without putting it in this module's import graph.
188249
*
@@ -340,7 +401,7 @@ export class ObjectLogger implements Logger {
340401
const context = this.redactSensitive({
341402
...this.bindings,
342403
...meta,
343-
...(error ? { error: { message: error.message, stack: error.stack } } : {}),
404+
...(error ? { error: renderError(error) } : {}),
344405
});
345406

346407
const hasContext = Object.keys(context).length > 0;

‎packages/runtime/src/mcp-record-context-tools-bridge.test.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -797,13 +797,19 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel:
797797
expect(faults).toHaveLength(4);
798798
for (const [, meta] of faults) {
799799
expect(meta).toMatchObject({ status: 500, code: 'INTERNAL_ERROR' });
800-
expect(String((meta as { stack?: unknown }).stack)).toContain(`Caused by: Error: ${OUTAGE}`);
800+
// The original reaches the line through the fault log's own `cause` rendering,
801+
// not through a suffix on the failure's stack.
802+
const { causes, stack } = meta as { causes?: Array<{ message: string; stack?: string }>; stack?: unknown };
803+
expect(causes?.[0]?.message).toBe(`Error: ${OUTAGE}`);
804+
expect(causes?.[0]?.stack).toContain(OUTAGE);
805+
expect(String(stack)).not.toContain('Caused by:');
801806
}
802807
// Reached through each door, so the answer is the outage's on both.
803808
expect(failing.mock.calls.filter(([object]) => object === 'rc_revision').length).toBeGreaterThanOrEqual(4);
804809
expect(answer.isError).toBe(true);
805810
expect(answer.payload.error).toMatchObject({ code: 'INTERNAL_ERROR', status: 500 });
806-
for (const word of ['rc_revision', 'disk I/O', 'version']) expect(answer.text).not.toContain(word);
811+
// The wire carries no cause text: the fault line is the operator's alone.
812+
for (const word of ['rc_revision', 'disk I/O', 'version', 'causes', 'Caused by']) expect(answer.text).not.toContain(word);
807813
} finally {
808814
failing.mockRestore();
809815
errorLines.mockRestore();

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -443,10 +443,10 @@ describe('get_record_context — a read of a related object that fails is a fail
443443
for (const word of ['policy_revision', 'secret_note', 'acme_private', 'store down']) {
444444
expect(failed.message).not.toContain(word);
445445
}
446-
// The original is the host's, on `cause` (which no door puts on the wire), and at the foot of the
447-
// stack, which the doors' fault line prints where it prints no `cause`.
446+
// The original is the host's, on `cause` (which no door puts on the wire and the doors' fault line
447+
// prints). The failure's own stack does not repeat it: the fault line renders the `cause` chain.
448448
expect(failed.cause).toBe(original);
449-
expect(failed.stack).toContain(`Caused by: ${original instanceof Error ? original.stack : String(original)}`);
449+
expect(failed.stack ?? '').not.toContain('Caused by:');
450450
};
451451

452452
it.each([

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

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -194,17 +194,6 @@ export function doorAnswersItself(thrown: unknown, object: string): boolean {
194194
return !Object.entries(body).every(([key, value]) => key === 'error' || (key === 'code' && value === 'INTERNAL_ERROR'));
195195
}
196196

197-
/** A thrown value as a log reads it: its stack, else its text. */
198-
function describeThrown(thrown: unknown): string {
199-
if (thrown instanceof Error) return thrown.stack ?? `${thrown.name}: ${thrown.message}`;
200-
if (typeof thrown === 'string') return thrown;
201-
try {
202-
return JSON.stringify(thrown) ?? String(thrown);
203-
} catch {
204-
return String(thrown);
205-
}
206-
}
207-
208197
/** The call's arguments, or a `VALIDATION_ERROR` carrying the spec's own words. */
209198
function parseInput(input: unknown): GetRecordContextInput {
210199
const parsed = GetRecordContextInputSchema.safeParse(input);
@@ -468,8 +457,8 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex
468457
// (500) in the executor's own sentence, which names the pack and the root
469458
// only. No door renders the original error, so nothing it says can name an
470459
// object, a field or a package the caller is not shown; it rides on
471-
// `cause` and at the foot of the stack, neither of which a door puts on the
472-
// wire, and the doors' fault line prints it. The doors withhold a 5xx's
460+
// `cause`, which no door puts on the wire and the doors' fault line prints
461+
// (`logServerFault` and `ObjectLogger` render the `cause` chain). The doors withhold a 5xx's
473462
// sentence too (`Internal server error`), so the sentence is read
474463
// in-process only (the citation verifier's host, through `onError`).
475464
//
@@ -489,10 +478,6 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex
489478
status: 500,
490479
cause: err,
491480
});
492-
// The doors' fault line prints an error's message and stack, never its
493-
// `cause` (`logServerFault`, and `ObjectLogger` behind it), so the stack
494-
// carries the original too. A stack is never on the wire.
495-
failure.stack = `${failure.stack ?? `Error: ${failure.message}`}\nCaused by: ${describeThrown(err)}`;
496481
throw failure;
497482
};
498483

0 commit comments

Comments
 (0)