Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
fix(bb-logger): log the invocation id as reserved awsRequestId
An app's own requestId context field is now left alone and can't replace
the invocation id, so every line one request logs shares one id. Adds
deployed E2E checks that each call logs one UUID and calls differ.
  • Loading branch information
osama-rizk committed Nov 6, 2026
commit d287cae4900977fad5a0847631f071804606dead
2 changes: 1 addition & 1 deletion .changeset/logger-request-id.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
"@aws-blocks/blocks": patch
---

On the Lambda functions AWS Blocks runs through `createLambdaHandler` (the backend API and its event handlers), every `Logger` line now carries `requestId`, the invocation's request id, so you can correlate everything one request logged (for example `filter requestId = "<id>"` in CloudWatch Logs Insights). Core's `createLambdaHandler` runs each invocation with its `awsRequestId` in scope, and overlapping invocations on one container each see their own id. A `requestId` you pass in context still takes precedence. Building Block authors can read the same id with `currentRequestId()` from `@aws-blocks/core/bb-utils`. Local dev, SSR hosting web functions and container compute set no request id, so the field is absent there.
On the Lambda functions AWS Blocks runs through `createLambdaHandler` (the backend API and its event handlers), every `Logger` line now carries `awsRequestId`, the invocation's request id, so you can correlate everything one request logged (for example `filter awsRequestId = "<id>"` in CloudWatch Logs Insights). Core's `createLambdaHandler` runs each invocation with its `awsRequestId` in scope, and overlapping invocations on one container each see their own id. `awsRequestId` is reserved, so context can't replace it, and your own context fields such as `requestId` are kept as is. Building Block authors can read the same id with `currentRequestId()` from `@aws-blocks/core/bb-utils`. Local dev, SSR hosting web functions and container compute set no request id, so the field is absent there.
4 changes: 2 additions & 2 deletions packages/bb-logger/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Fields:
- `timestamp` — ISO 8601 timestamp from `new Date().toISOString()`.
- `logger` — The `id` passed to the constructor.
- `traceId` — X-Ray trace ID (auto-injected from `_X_AMZN_TRACE_ID` env var when present).
- `requestId` — the Lambda invocation's `awsRequestId`. Core's `createLambdaHandler` runs each invocation inside an `AsyncLocalStorage` scope holding it (`request-context.ts`, registered on `globalThis.__BLOCKS_REQUEST_ID_STORE__`), and the serializer reads it with `currentRequestId()` from `@aws-blocks/core/bb-utils` when it builds a line. A separately resolved copy of core reuses the store already registered on the global, so it still sees the id. The backend import and Building Block constructors run outside the first invocation's scope, so long-lived state created at init doesn't keep that request's id. Only functions built with `createLambdaHandler` set the id; SSR hosting web functions, container compute and AgentCore runtimes don't yet. It is not a reserved field: a `requestId` in context overrides it. Overlapping invocations on one container each see their own id.
- `awsRequestId` — the Lambda invocation's `awsRequestId`. Core's `createLambdaHandler` runs each invocation inside an `AsyncLocalStorage` scope holding it (`request-context.ts`, registered on `globalThis.__BLOCKS_REQUEST_ID_STORE__`), and the serializer reads it with `currentRequestId()` from `@aws-blocks/core/bb-utils` when it builds a line. A separately resolved copy of core reuses the store already registered on the global, so it still sees the id. The backend import and Building Block constructors run outside the first invocation's scope, so long-lived state created at init doesn't keep that request's id. Only functions built with `createLambdaHandler` set the id; SSR hosting web functions, container compute and AgentCore runtimes don't yet. It is a reserved field, so a context value under that key is ignored; it uses its own key so an app's `requestId` context field (a common name for an app-chosen correlation id) is neither replaced nor replaces it. Overlapping invocations on one container each see their own id.
- Spread fields from `defaultContext`, `child()` context, and per-call `context` (later wins).

### Serialization Safety
Expand Down Expand Up @@ -99,4 +99,4 @@ The mock entry point (`index.mock.ts`) re-exports the AWS runtime (`index.aws.ts
| No log retention enforcement | Logs are ephemeral in local terminal | No mitigation needed — local logs don't persist |
| No log group/stream structure | Cannot test subscription filters | Sandbox testing covers these |
| No X-Ray trace ID injection | `traceId` field absent locally | Set `_X_AMZN_TRACE_ID` env var manually if needed |
| No request id | `requestId` field absent locally (the dev server sets none) | Pass a `requestId` in `child()` context if you need correlation locally |
| No request id | `awsRequestId` field absent locally (the dev server sets none) | Pass your own correlation field (e.g. `requestId`) in `child()` context if you need correlation locally |
6 changes: 3 additions & 3 deletions packages/bb-logger/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,12 @@ Every log entry is a JSON object written to stdout (or stderr for errors):
"message": "User logged in",
"timestamp": "2024-01-15T10:30:00.000Z",
"logger": "app",
"requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
"awsRequestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
"userId": "user-123"
}
```

On the Lambda functions AWS Blocks runs through `createLambdaHandler` (the backend API and its event handlers), `requestId` is the invocation's request id (the same id as in the function's `START`/`END`/`REPORT` lines), added to every line automatically, so you can find everything one request logged, for example with CloudWatch Logs Insights: `filter requestId = "<id>"`. A `requestId` you pass in context takes precedence. Local dev, SSR hosting web functions and container compute set no request id, so the field is absent there.
On the Lambda functions AWS Blocks runs through `createLambdaHandler` (the backend API and its event handlers), `awsRequestId` is the invocation's request id (the same id as in the function's `START`/`END`/`REPORT` lines), added to every line automatically, so you can find everything one request logged, for example with CloudWatch Logs Insights: `filter awsRequestId = "<id>"`. It is reserved: a context value under that key is ignored. Your own correlation fields, such as a `requestId` passed to `child()`, are separate keys and are kept as is. Local dev, SSR hosting web functions and container compute set no request id, so the field is absent there.

### Child Loggers

Expand Down Expand Up @@ -150,7 +150,7 @@ In local dev (`npm run dev`), the Logger BB:
- Does NOT create any files in `.bb-data/`
- Retention has no local effect (it is a cloud-only, compute-level setting)
- Log level comes from the `Logger`'s `level` option (default `'info'`)
- Lines have no `requestId` field: the dev server doesn't set a request id
- Lines have no `awsRequestId` field: the dev server doesn't set a request id

## Errors

Expand Down
66 changes: 52 additions & 14 deletions packages/bb-logger/src/request-id.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
/**
* On AWS, core's Lambda handler runs each invocation with its awsRequestId in
* the `__BLOCKS_REQUEST_ID_STORE__` store (see core's request-context.ts), and
* every log line carries it as `requestId`.
* every log line carries it as `awsRequestId`.
*/
import { test } from 'node:test';
import assert from 'node:assert';
Expand All @@ -22,46 +22,84 @@ const parse = (line: string) => JSON.parse(line) as Record<string, unknown>;

test('a line logged inside an invocation carries its request id', () => {
const entry = store.run('req-123', () => parse(buildEntry('info', 'hello', 'app', [])));
assert.strictEqual(entry.requestId, 'req-123');
assert.strictEqual(entry.awsRequestId, 'req-123');
assert.strictEqual('requestId' in entry, false, 'the app-owned requestId key is left alone');
});

test('a line logged outside an invocation has no request id', () => {
assert.strictEqual('requestId' in parse(buildEntry('info', 'hello', 'app', [])), false);
assert.strictEqual('awsRequestId' in parse(buildEntry('info', 'hello', 'app', [])), false);
});

test('a requestId the caller passes in context wins', () => {
test("an app's own requestId in context is kept and doesn't replace the invocation id", () => {
const entry = store.run('req-123', () => parse(buildEntry('info', 'hello', 'app', [{ requestId: 'mine' }])));
assert.strictEqual(entry.awsRequestId, 'req-123');
assert.strictEqual(entry.requestId, 'mine');
});

test('awsRequestId is reserved: a context value under that key is ignored', () => {
const inside = store.run('req-123', () => parse(buildEntry('info', 'm', 'app', [{ awsRequestId: 'spoofed' }])));
assert.strictEqual(inside.awsRequestId, 'req-123');
const outside = parse(buildEntry('info', 'm', 'app', [{ awsRequestId: 'spoofed' }]));
assert.strictEqual('awsRequestId' in outside, false);
});

test('overlapping invocations each log their own id', async () => {
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const logAfter = (id: string, ms: number) =>
store.run(id, async () => {
await sleep(ms);
return parse(buildEntry('info', id, 'app', [])).requestId;
return parse(buildEntry('info', id, 'app', [])).awsRequestId;
});
const [a, b] = await Promise.all([logAfter('req-a', 30), logAfter('req-b', 5)]);
assert.deepStrictEqual([a, b], ['req-a', 'req-b']);
});

test('the structural fields keep their order, with requestId after logger', () => {
test('the structural fields keep their order, with awsRequestId after logger', () => {
const entry = store.run('req-1', () => parse(buildEntry('warn', 'm', 'app', [{ k: 1 }])));
assert.deepStrictEqual(Object.keys(entry).slice(0, 5), ['level', 'message', 'timestamp', 'logger', 'requestId']);
assert.deepStrictEqual(Object.keys(entry).slice(0, 5), ['level', 'message', 'timestamp', 'logger', 'awsRequestId']);
});

test('the degraded line written on a serialization failure keeps requestId and traceId', () => {
const unserializable = { toJSON() { throw new Error('boom'); } };
test('the degraded line written on a serialization failure keeps the correlation ids', () => {
const unserializable = {
toJSON() {
throw new Error('boom');
},
};
const line = parse(
safeStringify({ level: 'error', message: 'm', timestamp: 't', logger: 'app', requestId: 'req-9', traceId: '1-abc', bad: unserializable }),
safeStringify({
level: 'error',
message: 'm',
timestamp: 't',
logger: 'app',
awsRequestId: 'req-9',
requestId: 'app-1',
traceId: '1-abc',
bad: unserializable,
}),
);
assert.strictEqual(line._serializationError, 'SerializationFailedException');
assert.strictEqual(line.requestId, 'req-9');
assert.strictEqual(line.awsRequestId, 'req-9');
assert.strictEqual(line.requestId, 'app-1');
assert.strictEqual(line.traceId, '1-abc');
});

test('the degraded line drops a non-string requestId rather than failing again', () => {
const unserializable = { toJSON() { throw new Error('boom'); } };
const line = parse(safeStringify({ level: 'error', message: 'm', timestamp: 't', logger: 'app', requestId: 1n, bad: unserializable }));
test('the degraded line drops a non-string id rather than failing again', () => {
const unserializable = {
toJSON() {
throw new Error('boom');
},
};
const line = parse(
safeStringify({
level: 'error',
message: 'm',
timestamp: 't',
logger: 'app',
awsRequestId: 1n,
requestId: 2n,
bad: unserializable,
}),
);
assert.strictEqual('awsRequestId' in line, false);
assert.strictEqual('requestId' in line, false);
});
15 changes: 8 additions & 7 deletions packages/bb-logger/src/serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export function safeStringify(obj: Record<string, unknown>): string {
timestamp: obj.timestamp,
logger: obj.logger,
// Keep the correlation ids: degraded lines are the ones most worth tracing.
awsRequestId: typeof obj.awsRequestId === 'string' ? obj.awsRequestId : undefined,
requestId: typeof obj.requestId === 'string' ? obj.requestId : undefined,
traceId: typeof obj.traceId === 'string' ? obj.traceId : undefined,
_serializationError: LoggingErrors.SerializationFailed,
Expand All @@ -74,13 +75,13 @@ export function safeStringify(obj: Record<string, unknown>): string {
* key like `{ level: 'debug' }` on an error log would silently corrupt the
* entry and break level-based CloudWatch filtering/queries.
*/
const RESERVED_FIELDS = new Set(['level', 'message', 'timestamp', 'logger', 'traceId']);
const RESERVED_FIELDS = new Set(['level', 'message', 'timestamp', 'logger', 'traceId', 'awsRequestId']);

/**
* Build a serialized log entry string. Structural fields are written first to
* guarantee consistent JSON property order (`level` always appears first), then
* user contexts are merged — reserved keys are skipped so user data can never
* clobber level/message/timestamp/logger/traceId.
* clobber level/message/timestamp/logger/traceId/awsRequestId.
*
* @param level - Log severity level.
* @param message - Log message.
Expand All @@ -102,11 +103,11 @@ export function buildEntry(
logger: loggerName,
};

// The id of the request being handled (the Lambda invocation's awsRequestId),
// so every line one request logs can be correlated. Not a reserved field: a
// `requestId` the caller puts in context still wins below.
const requestId = currentRequestId();
if (requestId) entry.requestId = requestId;
// The Lambda invocation's awsRequestId, so every line one request logs can be
// correlated. Reserved, so context can't replace it; an app's own `requestId`
// context field is a separate key and is left alone.
const awsRequestId = currentRequestId();
if (awsRequestId) entry.awsRequestId = awsRequestId;

// Merge user context — reserved keys are skipped (structural fields already written above).
for (const ctx of contexts) {
Expand Down
9 changes: 5 additions & 4 deletions packages/bb-logger/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,12 @@ export interface LogEntry {
/** X-Ray trace ID. Auto-injected when running in Lambda with X-Ray enabled. */
traceId?: string;
/**
* The id of the request that logged this line: the Lambda invocation's
* `awsRequestId`. Auto-injected on AWS Lambda; absent in local dev. A
* `requestId` you pass in context takes precedence.
* The id of the Lambda invocation that logged this line (its `awsRequestId`).
* Auto-injected on functions built with `createLambdaHandler`; absent in local
* dev. Reserved: a context value under this key is ignored. A `requestId` you
* pass in context is a separate field and is kept as is.
*/
requestId?: string;
awsRequestId?: string;
[key: string]: unknown;
}

Expand Down
39 changes: 39 additions & 0 deletions test-apps/comprehensive/test/logging.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import { describe, test } from 'node:test';
import assert from 'node:assert';
import type { api as apiType } from 'aws-blocks';

const ENV = process.env.BLOCKS_TEST_ENV || 'local';
const isLocal = ENV === 'local';
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

interface CapturedEntry {
level: string;
message: string;
Expand Down Expand Up @@ -174,6 +178,41 @@ export function loggingTests(getApi: () => typeof apiType) {
});
});

describe('invocation request id', () => {
test('lines carry no awsRequestId locally', { skip: !isLocal && 'local dev server only' }, async () => {
const api = getApi();
const result: LogResult = await api.logTestAllLevels();
const all = [...result.stdout, ...result.stderr];
assert.ok(all.length > 0, 'Expected log entries');
for (const entry of all) assert.strictEqual(entry.awsRequestId, undefined);
});

test('every line of one call carries the same invocation id, and calls differ', { skip: isLocal && 'deployed Lambda only' }, async () => {
const api = getApi();
const idsOf = (r: LogResult) => new Set([...r.stdout, ...r.stderr].map((e) => e.awsRequestId));
const first = idsOf(await api.logTestAllLevels());
const second = idsOf(await api.logTestAllLevels());
assert.strictEqual(first.size, 1, 'one invocation logs one id');
assert.strictEqual(second.size, 1, 'one invocation logs one id');
const [a] = first;
const [b] = second;
assert.match(String(a), UUID, 'the id is the Lambda awsRequestId');
assert.match(String(b), UUID, 'the id is the Lambda awsRequestId');
assert.notStrictEqual(a, b, 'separate calls carry separate ids');
});

test("an app's own requestId context field sits beside the invocation id", { skip: isLocal && 'deployed Lambda only' }, async () => {
const api = getApi();
const result = await api.logTestChildLoggers();
const all = [...result.stdout, ...result.stderr];
const ids = new Set(all.map((e: CapturedEntry) => e.awsRequestId));
assert.strictEqual(ids.size, 1, 'request-scoped and other child loggers share the invocation id');
assert.match(String([...ids][0]), UUID);
const reqEntries = all.filter((e: CapturedEntry) => e.requestId === result.requestId);
assert.ok(reqEntries.length > 0, 'the app-chosen requestId is kept');
});
});

describe('error object serialization', () => {
test('Error objects are serialized with name/message/stack', async () => {
const api = getApi();
Expand Down
Loading