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
14 changes: 14 additions & 0 deletions .changeset/37598-fault-log-cause-chain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@objectstack/types': patch
'@objectstack/core': patch
'@objectstack/service-record-context': patch
---

fix: the 5xx fault log and `ObjectLogger` print an error's `cause` chain

Clause-②: yes (widening)
Metadata-protocol: none

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.

`@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.
166 changes: 166 additions & 0 deletions packages/core/src/logger-error-cause.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* `ObjectLogger` prints an error's `cause` chain.
*
* `logger.error(message, err)` used to record `{ message, stack }` of the
* error alone, so a wrapper thrown with the original on `cause` logged
* without its root cause — the 5xx fault line (`logServerFault`,
* `@objectstack/types`) hands its injected logger exactly such a wrapper.
* The record now carries `error.causes`, bounded, in the same shape the fault
* log's console fallback prints; the parity block below pins the two copies
* to one output.
*/

import { describe, it, expect, vi, afterEach } from 'vitest';
import { faultCauseChain } from '@objectstack/types';

import { createLogger } from './logger.js';

const ROOT = 'SQLITE_IOERR: disk I/O error reading policy_revision.version';
const MID = 'driver read failed for policy_revision';
const OUTER = 'The related records of policy could not be read.';

const wrapped = () => new Error(OUTER, { cause: new Error(MID, { cause: new Error(ROOT) }) });

type ErrorRecord = { error?: { message: string; stack?: string; causes?: Array<{ message: string; stack?: string }> } };

/** One `error`-level record as the JSON format writes it to stderr. */
function recordOf(log: (logger: ReturnType<typeof createLogger>) => void): ErrorRecord {
const chunks: string[] = [];
vi.spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => {
chunks.push(String(chunk));
return true;
}) as never);
log(createLogger({ format: 'json', level: 'debug' }));
const lines = chunks.join('').split('\n').filter(Boolean);
expect(lines).toHaveLength(1);
return JSON.parse(lines[0]) as ErrorRecord;
}

afterEach(() => {
vi.restoreAllMocks();
});

describe('ObjectLogger — an error record carries the cause chain', () => {
it('logs each cause\'s message and stack, outermost first', () => {
const record = recordOf((logger) => logger.error('[5xx] 500 GET /api/v1/x — boom', wrapped(), { status: 500 }));
expect(record.error?.message).toBe(OUTER);
expect(record.error?.stack).toContain(OUTER);
const causes = record.error?.causes ?? [];
expect(causes).toHaveLength(2);
expect(causes[0].message).toBe(`Error: ${MID}`);
expect(causes[0].stack).toContain(MID);
expect(causes[1].message).toBe(`Error: ${ROOT}`);
expect(causes[1].stack).toContain(ROOT);
});

it('fatal renders it too', () => {
const record = recordOf((logger) => logger.fatal('down', wrapped()));
expect(record.error?.causes?.[1].message).toBe(`Error: ${ROOT}`);
});

it('CONTROL — an error with no cause carries no causes field', () => {
const record = recordOf((logger) => logger.error('plain', new Error(OUTER)));
expect(record.error).toBeDefined();
expect(record.error).not.toHaveProperty('causes');
});

it('stops a cycle at its first repeat, and says so', () => {
const a = new Error('a');
const b = new Error('b', { cause: a });
(a as { cause?: unknown }).cause = b;
const record = recordOf((logger) => logger.error('cycle', a));
expect(record.error?.causes?.map((c) => c.message)).toEqual([
'Error: b',
'[cause chain cycle: this link repeats an earlier one]',
]);
});

it('stops a deep chain after five links, and says so', () => {
let error = new Error('link 0');
for (let i = 1; i <= 20; i += 1) error = new Error(`link ${i}`, { cause: error });
const causes = recordOf((logger) => logger.error('deep', error)).error?.causes ?? [];
expect(causes).toHaveLength(6);
expect(causes[5]).toEqual({ message: '[cause chain truncated after 5 links]' });
});
});

describe('a cause is redacted like the error', () => {
it('under the logger\'s own redact list', () => {
const chunks: string[] = [];
vi.spyOn(process.stderr, 'write').mockImplementation(((chunk: unknown) => {
chunks.push(String(chunk));
return true;
}) as never);
const logger = createLogger({ format: 'json', level: 'debug', redact: ['password', 'apiKey', 'pin'] });
logger.error('withheld', new Error('w', { cause: { code: 'ECONNRESET', password: 'hunter2', apiKey: 'sk-live-1', pin: '0000' } }));
const line = chunks.join('');
for (const value of ['hunter2', 'sk-live-1', '0000']) expect(line).not.toContain(value);
const record = JSON.parse(line.trim()) as ErrorRecord;
expect(JSON.parse(record.error?.causes?.[0].message ?? '')).toEqual({
code: 'ECONNRESET',
password: '***REDACTED***',
apiKey: '***REDACTED***',
pin: '***REDACTED***',
});
});

it('a link whose message read throws ends the chain in a marker, and the record is still written', () => {
const unreadable = new Error('unreadable');
Object.defineProperty(unreadable, 'message', { get() { throw new Error('getter'); } });
const record = recordOf((logger) => logger.error('unreadable', new Error('w', { cause: unreadable })));
expect(record.error?.causes).toEqual([{ message: '[cause chain link unreadable: reading it threw]' }]);
});
});

describe('parity — the logger and the fault log render one shape', () => {
const cycle = () => {
const a = new Error('a');
(a as { cause?: unknown }).cause = new Error('b', { cause: a });
return a;
};
const deep = () => {
let error = new Error('link 0');
for (let i = 1; i <= 9; i += 1) error = new Error(`link ${i}`, { cause: error });
return error;
};
const fixtures: Array<[string, () => Error]> = [
['a nested Error chain', wrapped],
['a cycle', cycle],
['a deep chain', deep],
['a string cause', () => new Error('w', { cause: 'socket hang up' })],
['an object cause', () => new Error('w', { cause: { code: 'ECONNRESET' } })],
['a cause redacted like the error', () => new Error('w', { cause: { code: 'E1', password: 'p', apiKey: 'k' } })],
['field names under the default redact words, whole-word matched', () => new Error('w', {
cause: {
keys: ['a'], tokens: 3, monkey: 'm', keyword: 'k', secretary: 's', tokenizer: 't',
apiKey: 'x', apikey: 'x', accesstoken: 'x', refresh_tokens: ['x'], clientSecret: 'x', password: 'x', API_KEY: 'x',
},
})],
['an array inside an object cause', () => new Error('w', {
cause: { code: 'E3', attempts: [{ host: 'db-1', password: 'x' }, { host: 'db-2', authToken: 'y' }] },
})],
['an object cause that cannot be serialized', () => {
const loop: Record<string, unknown> = { code: 'E2' };
loop.self = loop;
return new Error('w', { cause: loop });
}],
['a link whose message read throws', () => {
const unreadable = new Error('unreadable');
Object.defineProperty(unreadable, 'message', { get() { throw new Error('getter'); } });
return new Error('w', { cause: new Error('mid', { cause: unreadable }) });
}],
['a throwing cause getter', () => {
const hostile = new Error('w');
Object.defineProperty(hostile, 'cause', { get() { throw new Error('getter'); } });
return hostile;
}],
];
it.each(fixtures)('%s', (_name, make) => {
const error = make();
const record = recordOf((logger) => logger.error('parity', error));
// The record omits `causes` when the chain is empty; the fault log's helper answers `[]`.
expect(record.error?.causes ?? []).toEqual(faultCauseChain(error));
});
});
82 changes: 81 additions & 1 deletion packages/core/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,86 @@ function colorEnabled(stream: { isTTY?: boolean } | undefined): boolean {
return Boolean(stream?.isTTY);
}

/** How many `cause` links an error record prints before it says it stopped. */
const CAUSE_DEPTH_LIMIT = 5;

/**
* An error as a log record carries it: message and stack, and the `cause`
* chain under it, outermost first.
*
* A wrapper thrown with the original on `cause` (`new Error(say, { cause })`)
* used to log as the wrapper alone, so the root cause of a wrapped fault was
* missing from the line. Each link is its message and stack. Bounded both
* ways: a cycle stops at the first repeat, a chain past
* {@link CAUSE_DEPTH_LIMIT} stops there, and either says so in a last link;
* a link whose read throws ends the chain in a marker link too.
*
* The same shape as `faultCauseChain` in `@objectstack/types`, which the 5xx
* fault log prints on its console fallback. A copy rather than an import:
* this entry is browser-safe and `@objectstack/client` bundles it without
* depending on `@objectstack/types`, whose root entry would come along with
* `@objectstack/spec` behind it. `logger-error-cause.test.ts` pins the two to one output,
* the field-name rule for object causes included (the types copy carries this
* file's whole-word matcher for its default list).
*/
function renderError(
error: Error,
isRedacted: (key: string) => boolean,
): { message: string; stack?: string; causes?: Array<{ message: string; stack?: string }> } {
const causes: Array<{ message: string; stack?: string }> = [];
const seen = new Set<unknown>([error]);
let current = causeOf(error);
while (current !== undefined && current !== null) {
if (seen.has(current)) {
causes.push({ message: '[cause chain cycle: this link repeats an earlier one]' });
break;
}
if (causes.length >= CAUSE_DEPTH_LIMIT) {
causes.push({ message: `[cause chain truncated after ${CAUSE_DEPTH_LIMIT} links]` });
break;
}
seen.add(current);
try {
causes.push(causeLine(current, isRedacted));
} catch {
// A link whose name, message or stack read throws (a hostile getter, a Proxy)
// ends the chain in a marker; it must not cost the whole line.
causes.push({ message: '[cause chain link unreadable: reading it threw]' });
break;
}
current = causeOf(current);
}
return { message: error.message, stack: error.stack, ...(causes.length > 0 ? { causes } : {}) };
}

function causeOf(value: unknown): unknown {
if (typeof value !== 'object' || value === null) return undefined;
try {
return (value as { cause?: unknown }).cause;
} catch {
// A throwing `cause` getter ends the chain; it must not cost the record.
return undefined;
}
}

/**
* One link as text. A non-Error object cause is serialized with the logger's
* own redaction applied key by key, the same rule the record's fields get.
* A read that throws is the caller's to catch (`renderError` ends the chain).
*/
function causeLine(cause: unknown, isRedacted: (key: string) => boolean): { message: string; stack?: string } {
if (cause instanceof Error) {
return { message: `${cause.name}: ${cause.message}`, ...(cause.stack ? { stack: cause.stack } : {}) };
}
if (typeof cause === 'string') return { message: cause };
try {
const text = JSON.stringify(cause, (key, value) => (key !== '' && isRedacted(key) ? '***REDACTED***' : value));
return { message: text ?? String(cause) };
} catch {
return { message: String(cause) };
}
}

/**
* Resolve a Node builtin without putting it in this module's import graph.
*
Expand Down Expand Up @@ -340,7 +420,7 @@ export class ObjectLogger implements Logger {
const context = this.redactSensitive({
...this.bindings,
...meta,
...(error ? { error: { message: error.message, stack: error.stack } } : {}),
...(error ? { error: renderError(error, (key) => this.isRedactedFieldName(key)) } : {}),
});

const hasContext = Object.keys(context).length > 0;
Expand Down
10 changes: 8 additions & 2 deletions packages/runtime/src/mcp-record-context-tools-bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -797,13 +797,19 @@ describe('[ADR-0149 D7 · ADR-0160 D4] get_record_context over one real kernel:
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}`);
// The original reaches the line through the fault log's own `cause` rendering,
// not through a suffix on the failure's stack.
const { causes, stack } = meta as { causes?: Array<{ message: string; stack?: string }>; stack?: unknown };
expect(causes?.[0]?.message).toBe(`Error: ${OUTAGE}`);
expect(causes?.[0]?.stack).toContain(OUTAGE);
expect(String(stack)).not.toContain('Caused by:');
}
// 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);
// The wire carries no cause text: the fault line is the operator's alone.
for (const word of ['rc_revision', 'disk I/O', 'version', 'causes', 'Caused by']) expect(answer.text).not.toContain(word);
} finally {
failing.mockRestore();
errorLines.mockRestore();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -443,10 +443,10 @@ describe('get_record_context — a read of a related object that fails is a fail
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`.
// The original is the host's, on `cause` (which no door puts on the wire and the doors' fault line
// prints). The failure's own stack does not repeat it: the fault line renders the `cause` chain.
expect(failed.cause).toBe(original);
expect(failed.stack).toContain(`Caused by: ${original instanceof Error ? original.stack : String(original)}`);
expect(failed.stack ?? '').not.toContain('Caused by:');
};

it.each([
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,17 +194,6 @@ export function doorAnswersItself(thrown: unknown, object: string): boolean {
return !Object.entries(body).every(([key, value]) => key === 'error' || (key === 'code' && value === 'INTERNAL_ERROR'));
}

/** 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);
Expand Down Expand Up @@ -468,8 +457,8 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex
// (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
// `cause`, which no door puts on the wire and the doors' fault line prints
// (`logServerFault` and `ObjectLogger` render the `cause` chain). 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`).
//
Expand All @@ -489,10 +478,6 @@ export async function executeGetRecordContext(input: unknown, door: RecordContex
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;
};

Expand Down
Loading
Loading