From 74117a722b93c8cec526849d7451b46f0a45416b Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:10:17 +0000 Subject: [PATCH 1/3] fix(observability): ConsoleLogger and JsonLogger record an error's cause chain Both loggers now add `causes` (message and stack per link, at most five links, cycle-safe) beside `error` and `stack`, in the shape faultCauseChain and ObjectLogger record. The helper is a pinned copy, since the package depends on @objectstack/spec alone; a parity test against faultCauseChain (devDependency on @objectstack/types, aliased to source) holds the two to one output. core's parity fixture now glues every redact qualifier to a default word. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc --- ...37658-observability-loggers-cause-chain.md | 12 ++ packages/core/src/logger-error-cause.test.ts | 20 ++ packages/observability/package.json | 1 + .../src/__tests__/loggers.test.ts | 165 +++++++++++++++++ packages/observability/src/loggers.ts | 174 +++++++++++++++++- packages/observability/vitest.config.ts | 33 +++- pnpm-lock.yaml | 3 + 7 files changed, 402 insertions(+), 6 deletions(-) create mode 100644 .changeset/37658-observability-loggers-cause-chain.md diff --git a/.changeset/37658-observability-loggers-cause-chain.md b/.changeset/37658-observability-loggers-cause-chain.md new file mode 100644 index 00000000000..61761694102 --- /dev/null +++ b/.changeset/37658-observability-loggers-cause-chain.md @@ -0,0 +1,12 @@ +--- +'@objectstack/observability': patch +--- + +fix(observability): `ConsoleLogger` and `JsonLogger` record an error's `cause` chain + +Clause-②: no +Metadata-protocol: none + +`error(message, err)` and `fatal(message, err)` on both loggers used to record the error's own message and stack only, so an error wrapped around an original on `cause` (`new Error(say, { cause })`) logged without its root cause. The record now carries `causes` beside `error` and `stack`: one entry per link, outermost first, each with the link's message and stack. The chain is bounded at five links and stops at the first repeat of a cycle, ending in a marker entry whenever it was cut. It is the same shape the 5xx fault line (`faultCauseChain` in `@objectstack/types`) and `ObjectLogger` in `@objectstack/core` record. + +An error with no `cause` logs exactly as before: `causes` is omitted. No new exports, and no new runtime dependency. diff --git a/packages/core/src/logger-error-cause.test.ts b/packages/core/src/logger-error-cause.test.ts index adbcfb5a9b3..3f9273c2c10 100644 --- a/packages/core/src/logger-error-cause.test.ts +++ b/packages/core/src/logger-error-cause.test.ts @@ -114,7 +114,26 @@ describe('a cause is redacted like the error', () => { }); }); +/** + * The glued redact qualifiers (`CONCATENATED_SECRET_QUALIFIERS`, one copy in + * `logger.ts` and one in `@objectstack/types`), each glued to a default word, + * so an edit to either copy's list fails the parity block below. + */ +const GLUED_QUALIFIERS = [ + 'access', 'account', 'admin', 'api', 'app', 'auth', 'bearer', 'client', 'csrf', 'db', 'database', + 'encryption', 'id', 'jwt', 'master', 'oauth', 'private', 'public', 'refresh', 'root', 'secret', + 'service', 'session', 'shared', 'sign', 'signing', 'ssh', 'token', 'user', 'webhook', 'xsrf', +]; +const gluedQualifierCause = () => Object.fromEntries(GLUED_QUALIFIERS.map((qualifier) => [`${qualifier}key`, 'x'])); + describe('parity — the logger and the fault log render one shape', () => { + it('CONTROL — the glued-qualifier fixture is withheld field by field, so it exercises each qualifier', () => { + const [line] = faultCauseChain(new Error('w', { cause: gluedQualifierCause() })); + const parsed = JSON.parse(line.message) as Record; + expect(Object.keys(parsed)).toHaveLength(GLUED_QUALIFIERS.length); + expect(Object.values(parsed).every((value) => value === '***REDACTED***')).toBe(true); + }); + const cycle = () => { const a = new Error('a'); (a as { cause?: unknown }).cause = new Error('b', { cause: a }); @@ -138,6 +157,7 @@ describe('parity — the logger and the fault log render one shape', () => { apiKey: 'x', apikey: 'x', accesstoken: 'x', refresh_tokens: ['x'], clientSecret: 'x', password: 'x', API_KEY: 'x', }, })], + ['every glued qualifier on a default word', () => new Error('w', { cause: gluedQualifierCause() })], ['an array inside an object cause', () => new Error('w', { cause: { code: 'E3', attempts: [{ host: 'db-1', password: 'x' }, { host: 'db-2', authToken: 'y' }] }, })], diff --git a/packages/observability/package.json b/packages/observability/package.json index 871b4206c44..d2dc875348d 100644 --- a/packages/observability/package.json +++ b/packages/observability/package.json @@ -28,6 +28,7 @@ "@objectstack/spec": "workspace:*" }, "devDependencies": { + "@objectstack/types": "workspace:*", "@types/node": "^26.6.5", "typescript": "^6.0.3", "vitest": "^4.1.11" diff --git a/packages/observability/src/__tests__/loggers.test.ts b/packages/observability/src/__tests__/loggers.test.ts index 2d326088b75..10f62a0697e 100644 --- a/packages/observability/src/__tests__/loggers.test.ts +++ b/packages/observability/src/__tests__/loggers.test.ts @@ -1,6 +1,7 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. import { describe, it, expect } from 'vitest'; +import { faultCauseChain, FAULT_CAUSE_DEPTH_LIMIT } from '@objectstack/types'; import type { Logger } from '../contracts.js'; import { NoopLogger, ConsoleLogger, JsonLogger } from '../loggers.js'; @@ -112,3 +113,167 @@ describe('JsonLogger', () => { expect(error).toHaveLength(1); }); }); + +// --------------------------------------------------------------------------- +// An error record carries the error's `cause` chain, in the shape the 5xx fault +// line (`faultCauseChain`, `@objectstack/types`) and `ObjectLogger` record. The +// loggers keep their own copy (this package depends on `@objectstack/spec` +// alone); the parity block pins it to `faultCauseChain`'s output. +// --------------------------------------------------------------------------- + +type CauseLine = { message: string; stack?: string }; +type ErrorRecord = { error?: string; stack?: string; causes?: CauseLine[] }; + +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) }) }); + +/** The JSON tail of a `ConsoleLogger` line: `[error] msg {...}`. */ +function consoleRecord(line: string, msg: string): ErrorRecord { + const prefix = `[error] ${msg} `; + expect(line.startsWith(prefix)).toBe(true); + return JSON.parse(line.slice(prefix.length)) as ErrorRecord; +} + +/** One error record from each logger, for the same call. */ +const LOGGERS: Array<[string, (error: Error) => ErrorRecord]> = [ + ['ConsoleLogger', (error) => { + const { sink, error: lines } = makeSink(); + new ConsoleLogger({ level: 'debug', sink }).error('boom', error); + expect(lines).toHaveLength(1); + return consoleRecord(lines[0], 'boom'); + }], + ['JsonLogger', (error) => { + const { sink, error: lines } = makeSink(); + new JsonLogger({ level: 'debug', sink }).error('boom', error); + expect(lines).toHaveLength(1); + return JSON.parse(lines[0]) as ErrorRecord; + }], +]; + +describe.each(LOGGERS)('%s — an error record carries the cause chain', (_name, recordOf) => { + it('logs each cause\'s message and stack, outermost first', () => { + const record = recordOf(wrapped()); + expect(record.error).toBe(OUTER); + expect(record.stack).toContain(OUTER); + const causes = record.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('CONTROL — an error with no cause carries no causes field', () => { + const record = recordOf(new Error(OUTER)); + expect(record.error).toBe(OUTER); + expect(record).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; + expect(recordOf(a).causes?.map((c) => c.message)).toEqual([ + 'Error: b', + '[cause chain cycle: this link repeats an earlier one]', + ]); + }); + + it(`stops a deep chain after ${FAULT_CAUSE_DEPTH_LIMIT} 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(error).causes ?? []; + expect(causes).toHaveLength(FAULT_CAUSE_DEPTH_LIMIT + 1); + expect(causes[FAULT_CAUSE_DEPTH_LIMIT]).toEqual({ + message: `[cause chain truncated after ${FAULT_CAUSE_DEPTH_LIMIT} links]`, + }); + }); +}); + +describe('fatal carries the cause chain too', () => { + it('ConsoleLogger', () => { + const { sink, error } = makeSink(); + new ConsoleLogger({ level: 'debug', sink }).fatal('down', wrapped()); + const record = JSON.parse(error[0].slice('[fatal] down '.length)) as ErrorRecord; + expect(record.causes?.[1].message).toBe(`Error: ${ROOT}`); + }); + + it('JsonLogger', () => { + const { sink, error } = makeSink(); + new JsonLogger({ level: 'debug', sink }).fatal('down', wrapped()); + expect((JSON.parse(error[0]) as ErrorRecord).causes?.[1].message).toBe(`Error: ${ROOT}`); + }); +}); + +/** The redact qualifiers a glued field name may start with, each glued to a default word. */ +const GLUED_QUALIFIERS = [ + 'access', 'account', 'admin', 'api', 'app', 'auth', 'bearer', 'client', 'csrf', 'db', 'database', + 'encryption', 'id', 'jwt', 'master', 'oauth', 'private', 'public', 'refresh', 'root', 'secret', + 'service', 'session', 'shared', 'sign', 'signing', 'ssh', 'token', 'user', 'webhook', 'xsrf', +]; + +describe('the glued-qualifier fixture', () => { + it('CONTROL — faultCauseChain withholds it field by field, so it exercises each qualifier', () => { + const cause = Object.fromEntries(GLUED_QUALIFIERS.map((qualifier) => [`${qualifier}key`, 'x'])); + const [line] = faultCauseChain(new Error('w', { cause })); + const parsed = JSON.parse(line.message) as Record; + expect(Object.keys(parsed)).toHaveLength(GLUED_QUALIFIERS.length); + expect(Object.values(parsed).every((value) => value === '***REDACTED***')).toBe(true); + }); +}); + +describe.each(LOGGERS)('parity — %s and faultCauseChain render one shape', (_name, recordOf) => { + 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' } })], + ['an object cause with secret-named fields', () => 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', + }, + })], + ['every glued qualifier on a default word', () => new Error('w', { + cause: Object.fromEntries(GLUED_QUALIFIERS.map((qualifier) => [`${qualifier}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 = { 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', (_fixture, make) => { + const error = make(); + // The record omits `causes` when the chain is empty; the fault log's helper answers `[]`. + expect(recordOf(error).causes ?? []).toEqual(faultCauseChain(error)); + }); +}); diff --git a/packages/observability/src/loggers.ts b/packages/observability/src/loggers.ts index 8971e222504..d037c912f88 100644 --- a/packages/observability/src/loggers.ts +++ b/packages/observability/src/loggers.ts @@ -14,6 +14,172 @@ const LEVEL_PRIORITY: Record = { fatal: 50, }; +/** One link of an error's `cause` chain, as an error record prints it. */ +interface CauseLine { + message: string; + /** Absent when the cause was not an `Error`, or carried none. */ + stack?: string; +} + +/** How many `cause` links an error record prints before it says it stopped. */ +const CAUSE_DEPTH_LIMIT = 5; + +/** + * The fields an `error` / `fatal` record carries for its `Error`: the + * message, the stack, and — when the error wraps an original on `cause` + * (`new Error(say, { cause })`) — `causes`, the chain under it, outermost + * first. Without it a wrapped fault logged as the wrapper alone, and the root + * cause was missing from the line an operator reads. + * + * `causes` is omitted when the chain is empty, so an unwrapped error's record + * is byte-identical to what it was. + */ +function errorFields(error: Error): Record { + const causes = causeChain(error); + return { error: error.message, stack: error.stack, ...(causes.length > 0 ? { causes } : {}) }; +} + +/** + * The `cause` chain under an error, in the shape `faultCauseChain` + * (`@objectstack/types`, the 5xx fault line) and `ObjectLogger` + * (`@objectstack/core`) record: each link's message and stack, at most + * {@link CAUSE_DEPTH_LIMIT} links, a cycle stopped at its first repeat, and a + * last marker link whenever the chain was cut. + * + * A copy, not an import: this package depends on `@objectstack/spec` alone, + * and a runtime edge to `@objectstack/types` for one helper is not worth it. + * `__tests__/loggers.test.ts` runs a fixture set through both + * loggers and `faultCauseChain` and fails on any drift, the field-name rule + * for object causes included. + * + * ⛔ Operator-only: it feeds the log record and nothing else. + */ +function causeChain(error: Error): CauseLine[] { + const lines: CauseLine[] = []; + const seen = new Set([error]); + let current = causeOf(error); + while (current !== undefined && current !== null) { + if (seen.has(current)) { + lines.push({ message: '[cause chain cycle: this link repeats an earlier one]' }); + break; + } + if (lines.length >= CAUSE_DEPTH_LIMIT) { + lines.push({ message: `[cause chain truncated after ${CAUSE_DEPTH_LIMIT} links]` }); + break; + } + seen.add(current); + try { + lines.push(causeLine(current)); + } catch { + // A link whose name, message or stack read throws ends the chain in + // a marker; it must not cost the record. + lines.push({ message: '[cause chain link unreadable: reading it threw]' }); + break; + } + current = causeOf(current); + } + return lines; +} + +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; + } +} + +function causeLine(cause: unknown): CauseLine { + 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 !== '' && isDefaultRedactedFieldName(key) ? '***REDACTED***' : value, + ); + return { message: text ?? String(cause) }; + } catch { + return { message: String(cause) }; + } +} + +/** + * `LoggerConfig.redact`'s default words (`@objectstack/spec` `logging.zod.ts`), + * the list `faultCauseChain` applies by default. + */ +const DEFAULT_REDACTED_WORDS = ['password', 'token', 'secret', 'key'] as const; + +/** + * The default field-name rule for an object cause, whole-word matched — a + * copy of `faultCauseChain`'s (itself a copy of `ObjectLogger`'s matcher), + * pinned to it by the same parity test as {@link causeChain}. + */ +function isDefaultRedactedFieldName(key: string): boolean { + const nameWords = tokenizeFieldName(key); + return DEFAULT_REDACTED_WORDS.some((word) => fieldWordsMatchPattern(nameWords, [word])); +} + +function tokenizeFieldName(name: string): string[] { + return name + .replace(/([a-z0-9])([A-Z])/g, '$1 $2') + .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2') + .replace(/([a-zA-Z])([0-9])/g, '$1 $2') + .split(/[^A-Za-z0-9]+/) + .filter(Boolean) + .map((word) => word.toLowerCase()); +} + +function singularizeWord(word: string): string { + if (/(?:ss|us|is)$/.test(word)) return word; + if (/(?:ch|sh|s|x|z)es$/.test(word)) return word.slice(0, -2); + if (/[a-z0-9]s$/.test(word)) return word.slice(0, -1); + return word; +} + +/** Glued qualifiers that mark the secret sense: `apikey`, `accesstoken`, `clientsecret`. */ +const CONCATENATED_SECRET_QUALIFIERS = new Set([ + 'access', 'account', 'admin', 'api', 'app', 'auth', 'bearer', 'client', 'csrf', 'db', 'database', + 'encryption', 'id', 'jwt', 'master', 'oauth', 'private', 'public', 'refresh', 'root', 'secret', + 'service', 'session', 'shared', 'sign', 'signing', 'ssh', 'token', 'user', 'webhook', 'xsrf', +]); + +function isQualifiedConcatenation(word: string, redactWord: string): boolean { + for (const base of [word, singularizeWord(word)]) { + if (base.length <= redactWord.length || !base.endsWith(redactWord)) continue; + if (CONCATENATED_SECRET_QUALIFIERS.has(base.slice(0, base.length - redactWord.length))) return true; + } + return false; +} + +function containsWordRun(words: string[], run: string[]): boolean { + for (let i = 0; i + run.length <= words.length; i++) { + if (run.every((word, offset) => words[i + offset] === word)) return true; + } + return false; +} + +function fieldWordsMatchPattern(nameWords: string[], patternWords: string[]): boolean { + if (patternWords.length === 0 || nameWords.length === 0) return false; + if (patternWords.length > 1) { + const glued = patternWords.join(''); + return ( + containsWordRun(nameWords, patternWords) || + nameWords.some((word) => word === glued || singularizeWord(word) === glued) + ); + } + const redactWord = patternWords[0]; + const isCompound = nameWords.filter((word) => /[a-z]/.test(word)).length > 1; + return nameWords.some( + (word) => + word === redactWord || + (isCompound && singularizeWord(word) === redactWord) || + isQualifiedConcatenation(word, redactWord), + ); +} + /** No-op logger — discards every message. */ export class NoopLogger implements Logger { debug(): void { } @@ -53,10 +219,10 @@ export class ConsoleLogger implements Logger { info(message: string, meta?: Record): void { this.emit('info', message, meta); } warn(message: string, meta?: Record): void { this.emit('warn', message, meta); } error(message: string, error?: Error, meta?: Record): void { - this.emit('error', message, { ...(meta ?? {}), ...(error ? { error: error.message, stack: error.stack } : {}) }); + this.emit('error', message, { ...(meta ?? {}), ...(error ? errorFields(error) : {}) }); } fatal(message: string, error?: Error, meta?: Record): void { - this.emit('fatal', message, { ...(meta ?? {}), ...(error ? { error: error.message, stack: error.stack } : {}) }); + this.emit('fatal', message, { ...(meta ?? {}), ...(error ? errorFields(error) : {}) }); } child(context: Record): Logger { return new ConsoleLogger({ ...this.opts, context: { ...this.context, ...context } }); @@ -111,10 +277,10 @@ export class JsonLogger implements Logger { info(message: string, meta?: Record): void { this.emit('info', message, meta); } warn(message: string, meta?: Record): void { this.emit('warn', message, meta); } error(message: string, error?: Error, meta?: Record): void { - this.emit('error', message, { ...(meta ?? {}), ...(error ? { error: error.message, stack: error.stack } : {}) }); + this.emit('error', message, { ...(meta ?? {}), ...(error ? errorFields(error) : {}) }); } fatal(message: string, error?: Error, meta?: Record): void { - this.emit('fatal', message, { ...(meta ?? {}), ...(error ? { error: error.message, stack: error.stack } : {}) }); + this.emit('fatal', message, { ...(meta ?? {}), ...(error ? errorFields(error) : {}) }); } child(context: Record): Logger { return new JsonLogger({ ...this.opts, context: { ...this.context, ...context } }); diff --git a/packages/observability/vitest.config.ts b/packages/observability/vitest.config.ts index 1579376748b..2f85a0eb652 100644 --- a/packages/observability/vitest.config.ts +++ b/packages/observability/vitest.config.ts @@ -1,4 +1,33 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// This package needs nothing beyond the shared preset; see its header. -export { default } from '../../vitest.preset.mts'; +import { defineConfig } from 'vitest/config'; +import path from 'node:path'; + +// The shared preset's one setting, plus this package's own. +// `check-console-intercept-disarm.mjs` reads this file's source, so the +// setting is spelled here instead of merged in from `vitest.preset.mts`. +export default defineConfig({ + resolve: { + // `__tests__/loggers.test.ts` pins the loggers' cause-chain copy to + // `faultCauseChain`, so `@objectstack/types` is this checkout's source, + // not a `types/dist` build that may be behind it + // (`pnpm check:test-source-alias`). A devDependency only: the package's + // runtime edge is `@objectstack/spec` alone. Anchored, array form: a bare + // string `find` matches by prefix. + alias: [ + { + find: /^@objectstack\/types$/, + replacement: path.resolve(__dirname, '../types/src/index.ts'), + }, + ], + }, + test: { + // A late console.* must not redden a green suite (#10374): vitest's worker + // forwards console output over RPC and discards the promise, and a write + // landing after teardown's rpcDone() snapshot is rejected into an unhandled + // error — a fully green run that exits 1. Disarming removes the mechanism. + // Mechanism + measured costs: examples/app-showcase/vitest.config.ts. + // Enforced repo-wide by scripts/check-console-intercept-disarm.mjs. + disableConsoleIntercept: true, + }, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index caf480db694..a5e98d42a74 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1719,6 +1719,9 @@ importers: specifier: workspace:* version: link:../spec devDependencies: + '@objectstack/types': + specifier: workspace:* + version: link:../types '@types/node': specifier: ^26.6.5 version: 26.6.5 From d2a09be4539616e39c8dc20aaf78d67b38c32f77 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 23:14:41 +0000 Subject: [PATCH 2/3] test(observability): spell cause-wrapped errors for the package's ES2020 lib Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc --- .../src/__tests__/loggers.test.ts | 43 +++++++++---------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/packages/observability/src/__tests__/loggers.test.ts b/packages/observability/src/__tests__/loggers.test.ts index 10f62a0697e..6863332b118 100644 --- a/packages/observability/src/__tests__/loggers.test.ts +++ b/packages/observability/src/__tests__/loggers.test.ts @@ -121,6 +121,9 @@ describe('JsonLogger', () => { // alone); the parity block pins it to `faultCauseChain`'s output. // --------------------------------------------------------------------------- +/** `new Error(message, { cause })`, spelled for the ES2020 `lib` this package compiles under. */ +const withCause = (message: string, cause: unknown): Error => Object.assign(new Error(message), { cause }); + type CauseLine = { message: string; stack?: string }; type ErrorRecord = { error?: string; stack?: string; causes?: CauseLine[] }; @@ -128,7 +131,7 @@ 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) }) }); +const wrapped = () => withCause(OUTER, withCause(MID, new Error(ROOT))); /** The JSON tail of a `ConsoleLogger` line: `[error] msg {...}`. */ function consoleRecord(line: string, msg: string): ErrorRecord { @@ -174,7 +177,7 @@ describe.each(LOGGERS)('%s — an error record carries the cause chain', (_name, it('stops a cycle at its first repeat, and says so', () => { const a = new Error('a'); - const b = new Error('b', { cause: a }); + const b = withCause('b', a); (a as { cause?: unknown }).cause = b; expect(recordOf(a).causes?.map((c) => c.message)).toEqual([ 'Error: b', @@ -184,7 +187,7 @@ describe.each(LOGGERS)('%s — an error record carries the cause chain', (_name, it(`stops a deep chain after ${FAULT_CAUSE_DEPTH_LIMIT} 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 }); + for (let i = 1; i <= 20; i += 1) error = withCause(`link ${i}`, error); const causes = recordOf(error).causes ?? []; expect(causes).toHaveLength(FAULT_CAUSE_DEPTH_LIMIT + 1); expect(causes[FAULT_CAUSE_DEPTH_LIMIT]).toEqual({ @@ -214,11 +217,11 @@ const GLUED_QUALIFIERS = [ 'encryption', 'id', 'jwt', 'master', 'oauth', 'private', 'public', 'refresh', 'root', 'secret', 'service', 'session', 'shared', 'sign', 'signing', 'ssh', 'token', 'user', 'webhook', 'xsrf', ]; +const gluedQualifierCause = () => Object.fromEntries(GLUED_QUALIFIERS.map((qualifier) => [`${qualifier}key`, 'x'])); describe('the glued-qualifier fixture', () => { it('CONTROL — faultCauseChain withholds it field by field, so it exercises each qualifier', () => { - const cause = Object.fromEntries(GLUED_QUALIFIERS.map((qualifier) => [`${qualifier}key`, 'x'])); - const [line] = faultCauseChain(new Error('w', { cause })); + const [line] = faultCauseChain(withCause('w', gluedQualifierCause())); const parsed = JSON.parse(line.message) as Record; expect(Object.keys(parsed)).toHaveLength(GLUED_QUALIFIERS.length); expect(Object.values(parsed).every((value) => value === '***REDACTED***')).toBe(true); @@ -228,42 +231,38 @@ describe('the glued-qualifier fixture', () => { describe.each(LOGGERS)('parity — %s and faultCauseChain render one shape', (_name, recordOf) => { const cycle = () => { const a = new Error('a'); - (a as { cause?: unknown }).cause = new Error('b', { cause: a }); + (a as { cause?: unknown }).cause = withCause('b', 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 }); + for (let i = 1; i <= 9; i += 1) error = withCause(`link ${i}`, 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' } })], - ['an object cause with secret-named fields', () => 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', - }, - })], - ['every glued qualifier on a default word', () => new Error('w', { - cause: Object.fromEntries(GLUED_QUALIFIERS.map((qualifier) => [`${qualifier}key`, 'x'])), + ['a string cause', () => withCause('w', 'socket hang up')], + ['an object cause', () => withCause('w', { code: 'ECONNRESET' })], + ['an object cause with secret-named fields', () => withCause('w', { code: 'E1', password: 'p', apiKey: 'k' })], + ['field names under the default redact words, whole-word matched', () => withCause('w', { + 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' }] }, + ['every glued qualifier on a default word', () => withCause('w', gluedQualifierCause())], + ['an array inside an object cause', () => withCause('w', { + code: 'E3', attempts: [{ host: 'db-1', password: 'x' }, { host: 'db-2', authToken: 'y' }], })], ['an object cause that cannot be serialized', () => { const loop: Record = { code: 'E2' }; loop.self = loop; - return new Error('w', { cause: loop }); + return withCause('w', 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 }) }); + return withCause('w', withCause('mid', unreadable)); }], ['a throwing cause getter', () => { const hostile = new Error('w'); From 80855b22b02063419c2db2e6dab9bb9b2983eb0c Mon Sep 17 00:00:00 2001 From: os-bill Date: Thu, 26 Nov 2026 23:52:47 +0000 Subject: [PATCH 3/3] =?UTF-8?q?chore(changeset):=20Clause-=E2=91=A1=20yes?= =?UTF-8?q?=20(widening)=20for=20the=20additive=20causes=20log=20field?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6CbeF2saT6wUBV4E9uc --- .changeset/37658-observability-loggers-cause-chain.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/37658-observability-loggers-cause-chain.md b/.changeset/37658-observability-loggers-cause-chain.md index 61761694102..fe047f85f34 100644 --- a/.changeset/37658-observability-loggers-cause-chain.md +++ b/.changeset/37658-observability-loggers-cause-chain.md @@ -4,7 +4,7 @@ fix(observability): `ConsoleLogger` and `JsonLogger` record an error's `cause` chain -Clause-②: no +Clause-②: yes (widening) Metadata-protocol: none `error(message, err)` and `fatal(message, err)` on both loggers used to record the error's own message and stack only, so an error wrapped around an original on `cause` (`new Error(say, { cause })`) logged without its root cause. The record now carries `causes` beside `error` and `stack`: one entry per link, outermost first, each with the link's message and stack. The chain is bounded at five links and stops at the first repeat of a cycle, ending in a marker entry whenever it was cut. It is the same shape the 5xx fault line (`faultCauseChain` in `@objectstack/types`) and `ObjectLogger` in `@objectstack/core` record.