From ae799e069838db7e993c7e47ed6288426ec57deb Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:23:50 +0000 Subject: [PATCH 1/3] fix(cli): Reject bodies that are not envelopes An empty body or a first line that is not a JSON object got 204, took a retention slot, and could show up as "Error: Unknown error". Answer these with 400 and a short reason and keep nothing, as Relay does. Relay still accepts an event item whose payload is not JSON and drops it later, so keep accepting it, but show it as invalid instead of as an error. Co-Authored-By: Aditya Mathur <57684218+MathurAditya724@users.noreply.github.com> --- docs/cli/local-control-plane.md | 9 +++-- .../cli/src/commands/local/control-plane.ts | 1 + packages/cli/src/commands/local/envelope.ts | 35 ++++++++++++------ .../cli/src/commands/local/receiver-ingest.ts | 15 +++++--- packages/cli/src/commands/local/server.ts | 1 + packages/cli/src/lib/formatters/local.ts | 15 ++++++-- .../test/commands/local/control-plane.test.ts | 20 +++++++++++ .../commands/local/receiver-ingest.test.ts | 8 ++--- .../cli/test/commands/local/server.test.ts | 36 +++++++++++++++++++ .../cli/test/lib/formatters/local.test.ts | 18 ++++++++++ 10 files changed, 134 insertions(+), 24 deletions(-) diff --git a/docs/cli/local-control-plane.md b/docs/cli/local-control-plane.md index 04a530ce4..d4377f305 100644 --- a/docs/cli/local-control-plane.md +++ b/docs/cli/local-control-plane.md @@ -385,13 +385,16 @@ segments, like the tail's `[N spans]`: the transaction or segment span itself an sampled function rows are not counted. Receiver ingestion bounds encoded bodies to 10 MiB and decoded bodies to 32 MiB. -Invalid compression returns 400, oversized bodies 413, unsupported media or +Invalid compression returns 400, and so does a body that is empty or whose first +line is not a JSON object; like Relay, the receiver keeps nothing for those. +Oversized bodies get 413, unsupported media or encoding 415, and temporary admission overload 503. SDKs drop an envelope that gets 413 without retrying, so `local run` and `local serve` print a warning in their tail when that happens, at most one line every five seconds. Drops in between are counted and printed as one line when the five seconds end. Session tails -get the notice from the daemon as a `sentry.local.oversized` stream event. Malformed envelopes remain -available for raw inspection and byte-exact download through their receiver IDs. +get the notice from the daemon as a `sentry.local.oversized` stream event. Envelopes whose items +are malformed remain available for raw inspection and byte-exact download through +their receiver IDs. An event item that is not JSON shows as `invalid`, not as an error. Receivers drop `http.client` spans and breadcrumbs for requests to their own loopback `/_local/` and `/stream` routes on the same port, which SDKs record for their own deliveries, and do not retain an envelope that has nothing else left. diff --git a/packages/cli/src/commands/local/control-plane.ts b/packages/cli/src/commands/local/control-plane.ts index cc7fc2202..92ce4d240 100644 --- a/packages/cli/src/commands/local/control-plane.ts +++ b/packages/cli/src/commands/local/control-plane.ts @@ -530,6 +530,7 @@ export function createLocalControlPlane({ reportIngestStatus(buffer, result); return result; }); + if (typeof status === "object") return c.json(status, 400); if (status === 410) return closed(); if (status === 503) c.header("Retry-After", "1"); if (status === 204) sessionStore.recordActivity(reference); diff --git a/packages/cli/src/commands/local/envelope.ts b/packages/cli/src/commands/local/envelope.ts index 629b90a76..282cdba84 100644 --- a/packages/cli/src/commands/local/envelope.ts +++ b/packages/cli/src/commands/local/envelope.ts @@ -419,8 +419,27 @@ export function withoutOwnDeliveries( * the read capability, so drop the key. Only the header line is rewritten. */ export function withoutDsnHeader(body: Buffer): Buffer { - // Only the first line is needed, so skip frame(): it would parse every item - // and reject envelopes that still have a usable header. + const parsed = readEnvelopeHeader(body); + if (!parsed || !("dsn" in parsed.header)) return body; + delete parsed.header["dsn"]; + return Buffer.concat([ + Buffer.from(JSON.stringify(parsed.header)), + body.subarray(parsed.end), + ]); +} + +/** Whether the first line is a JSON object, which Relay requires of an envelope. */ +export function hasEnvelopeHeader(body: Buffer): boolean { + return readEnvelopeHeader(body) !== undefined; +} + +/** + * Parse only the first line, without frame(): it would parse every item and + * reject envelopes that still have a usable header. + */ +function readEnvelopeHeader( + body: Buffer, +): { header: Record; end: number } | undefined { const newline = body.indexOf(10); const end = newline < 0 ? body.length : newline; let header: unknown; @@ -432,16 +451,10 @@ export function withoutDsnHeader(body: Buffer): Buffer { .replace(/^\uFEFF/, ""), ); } catch { - // Malformed envelopes stay byte-exact for raw inspection. - logger.debug("Local receiver kept an undecodable envelope header."); - return body; + logger.debug("Local receiver could not parse an envelope header."); + return; } - if (!isEnvelopeObject(header) || !("dsn" in header)) return body; - delete header["dsn"]; - return Buffer.concat([ - Buffer.from(JSON.stringify(header)), - body.subarray(end), - ]); + return isEnvelopeObject(header) ? { header, end } : undefined; } /** Retain raw bytes synchronously; decode lazily without allowing parse errors out. */ diff --git a/packages/cli/src/commands/local/receiver-ingest.ts b/packages/cli/src/commands/local/receiver-ingest.ts index bd2989343..bbe6ef2cf 100644 --- a/packages/cli/src/commands/local/receiver-ingest.ts +++ b/packages/cli/src/commands/local/receiver-ingest.ts @@ -3,6 +3,7 @@ import { brotliDecompress, gunzip, inflate } from "node:zlib"; import { logger } from "../../lib/logger.js"; import { createReceiverEnvelope, + hasEnvelopeHeader, type ReceiverBuffer, withoutDsnHeader, withoutOwnDeliveries, @@ -25,6 +26,8 @@ type ReceiverState = { /** Requests still reading their body or reporting their status. */ requests: Set>; }; +/** A body that is not an envelope: HTTP 400 with this JSON, as Relay answers. */ +type ReceiverRejected = { error: string }; const receivers = new WeakMap(); const oversizedListeners = new WeakMap void>>(); @@ -45,9 +48,9 @@ export function onOversizedEnvelope( /** Tell this receiver's listeners when a delivery got HTTP 413. */ export function reportIngestStatus( buffer: ReceiverBuffer, - status: number, + result: number | ReceiverRejected, ): void { - if (status !== 413) return; + if (result !== 413) return; for (const listener of oversizedListeners.get(buffer) ?? []) listener(); } @@ -158,7 +161,7 @@ export function ingestReceiverEnvelope( */ closed?: boolean; }, -): Promise<204 | 400 | 410 | 413 | 415 | 503> { +): Promise<204 | 400 | 410 | 413 | 415 | 503 | ReceiverRejected> { const contentType = input.contentType?.split(";")[0]?.trim().toLowerCase(); if ( contentType && @@ -173,7 +176,7 @@ export function ingestReceiverEnvelope( if (state.pending.size >= MAX_PENDING) return Promise.resolve(503); const generation = state.generation; const operation = state.queue.then( - async (): Promise<204 | 400 | 410 | 413 | 503> => { + async (): Promise<204 | 400 | 410 | 413 | 503 | ReceiverRejected> => { if (generation !== state.generation) return 503; let body = input.body; if (encoding && encoding !== "identity") { @@ -200,6 +203,10 @@ export function ingestReceiverEnvelope( if (generation !== state.generation) return 503; if (body.length > MAX_DECODED_BYTES) return 413; if (input.closed) return 410; + // Like Relay, reject bodies that are not envelopes and retain nothing. + if (!body.length) return { error: "The envelope is empty." }; + if (!hasEnvelopeHeader(body)) + return { error: "The envelope header is not a JSON object." }; if (input.dropDsnHeader) body = withoutDsnHeader(body); const delivery = input.receiverUrl ? withoutOwnDeliveries(body, input.receiverUrl) diff --git a/packages/cli/src/commands/local/server.ts b/packages/cli/src/commands/local/server.ts index f4ead07b3..5b343719e 100644 --- a/packages/cli/src/commands/local/server.ts +++ b/packages/cli/src/commands/local/server.ts @@ -525,6 +525,7 @@ export function buildApp( }); reportIngestStatus(buffer, status); + if (typeof status === "object") return c.json(status, 400); if (status === 503) c.header("Retry-After", "1"); return c.body(null, status); }; diff --git a/packages/cli/src/lib/formatters/local.ts b/packages/cli/src/lib/formatters/local.ts index 2f4eae0d3..51a22e5ce 100644 --- a/packages/cli/src/lib/formatters/local.ts +++ b/packages/cli/src/lib/formatters/local.ts @@ -377,12 +377,14 @@ type ExceptionValue = { * * `kind` is `message` for events with no typed exception: `captureMessage`, * Python `logging` records, and JavaScript messages that carry only a - * synthetic stack. It is `error` otherwise, with the exception type in - * `errorType` (`Error` when the event names none). + * synthetic stack. It is `invalid`, with level `invalid`, when the payload is + * not JSON, and `error` otherwise, with the exception type in `errorType` + * (`Error` when the event names none). */ type EventSummary = ( | { kind: "message" } | { kind: "error"; errorType: string } + | { kind: "invalid" } ) & { /** Event level (`fatal`, `error`, `warning`, `info`, `debug`); `error` when unset. */ level: string; @@ -396,6 +398,15 @@ type EventSummary = ( /** Summarize an `event` item for its tail line, JSON record, or `event list` entry. */ export function summarizeEvent(event: Record): EventSummary { + // The receiver keeps an item that is not JSON as `{ data }`, without the + // `type` it adds to every decoded item. Relay drops such events. + if (!("type" in event) && typeof event["data"] === "string") { + return { + kind: "invalid", + level: "invalid", + text: "Event payload is not JSON", + }; + } // Exceptions are ordered oldest→newest; the last one is what was thrown. const last = exceptionValues(event["exception"]).at(-1) as | ExceptionValue diff --git a/packages/cli/test/commands/local/control-plane.test.ts b/packages/cli/test/commands/local/control-plane.test.ts index 76c34cdd9..7c4641aa8 100644 --- a/packages/cli/test/commands/local/control-plane.test.ts +++ b/packages/cli/test/commands/local/control-plane.test.ts @@ -230,6 +230,26 @@ describe("Local control plane", () => { ); }); + test("session ingest rejects bodies without an envelope header", async () => { + const plane = createLocalControlPlane({ controlToken: CONTROL_TOKEN }); + const created = await plane.app.request("/_local/v1/sessions", { + method: "POST", + headers: controlHeaders(), + body: JSON.stringify({ label: "malformed", cwd: "/malformed" }), + }); + const { id, ingestUrl } = await created.json(); + for (const body of ["", '{not json\n{"type":"event"}\n{}']) { + const response = await plane.app.request(ingestUrl, { + method: "POST", + headers: { "Content-Type": "application/x-sentry-envelope" }, + body, + }); + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ error: expect.any(String) }); + } + expect(plane.sessionStore.getBuffer(id).read({ all: true })).toEqual([]); + }); + test("replaces expired clientId sessions with usable fresh capabilities on creation", async () => { let now = 1000; const sessionStore = createLocalSessionStore({ now: () => now }); diff --git a/packages/cli/test/commands/local/receiver-ingest.test.ts b/packages/cli/test/commands/local/receiver-ingest.test.ts index 1191ca185..ed010e780 100644 --- a/packages/cli/test/commands/local/receiver-ingest.test.ts +++ b/packages/cli/test/commands/local/receiver-ingest.test.ts @@ -449,9 +449,9 @@ describe.each([false, true])("own ingest telemetry (scoped: %s)", (scoped) => { }); test.each([ - "not-json", - '1\n{"type":"event"}\n{}', - '[]\n{"type":"event"}\n{}', + "{}\nnot-an-item-header\n{}", + '{}\n{"type":"event","length":99}\n{}', + "{}\n[]\n{}", '{}\n{"type":"event"}\nfalse', ])( "retains malformed raw delivery %j with a downloadable stable ID", @@ -615,7 +615,7 @@ test("raw attachments remain byte exact and malformed SSE remains inspectable wi ]); expect(await ingestReceiverEnvelope(retention.buffer, { body })).toBe(204); expect(at(retention.buffer.read({ all: true }), 0).getData()).toEqual(body); - const malformed = Buffer.from("not-an-envelope"); + const malformed = Buffer.from("{}\nnot-an-item-header\n"); expect( await ingestReceiverEnvelope(retention.buffer, { body: malformed }), ).toBe(204); diff --git a/packages/cli/test/commands/local/server.test.ts b/packages/cli/test/commands/local/server.test.ts index 6c20fe88e..d9796239c 100644 --- a/packages/cli/test/commands/local/server.test.ts +++ b/packages/cli/test/commands/local/server.test.ts @@ -8,6 +8,7 @@ import { createLocalControlPlane } from "../../../src/commands/local/control-plane.js"; import { createLocalRetentionBuffer } from "../../../src/commands/local/retention-buffer.js"; import { logger } from "../../../src/lib/logger.js"; +import { gzipSync } from "node:zlib"; import { Hono } from "hono"; import { afterEach, @@ -765,6 +766,41 @@ describe("buildApp", () => { expect(buffer.read({ all: true })).toEqual([]); }); + test("ingest rejects bodies without an envelope header and keeps nothing", async () => { + const buffer = createLocalRetentionBuffer(10).buffer; + const app = buildApp(buffer); + const post = ( + body: string | ReturnType, + encoding?: string, + ) => + app.request("/stream", { + method: "POST", + headers: { + "Content-Type": SENTRY_CONTENT_TYPE, + ...(encoding ? { "Content-Encoding": encoding } : {}), + }, + body, + }); + for (const body of [ + "", + '{not json\n{"type":"event"}\n{}', + '[]\n{"type":"event"}\n{}', + "not-an-envelope", + ]) { + const res = await post(body); + expect(res.status, JSON.stringify(body)).toBe(400); + expect(await res.json()).toEqual({ error: expect.any(String) }); + } + expect((await post(gzipSync("{not json\n"), "gzip")).status).toBe(400); + expect(buffer.read({ all: true })).toEqual([]); + // Like Relay, unknown item types and items without `length` are fine. + const valid = await post( + '{}\n{"type":"future_item"}\n{"x":1}\n{"type":"event"}\n{"message":"ok"}', + ); + expect(valid.ok).toBe(true); + expect(buffer.read({ all: true })).toHaveLength(1); + }); + test("ingest endpoint accepts envelopes and returns 204", async () => { const buffer = createLocalRetentionBuffer(10).buffer; const app = buildApp(buffer); diff --git a/packages/cli/test/lib/formatters/local.test.ts b/packages/cli/test/lib/formatters/local.test.ts index c20e90e1a..003ca165f 100644 --- a/packages/cli/test/lib/formatters/local.test.ts +++ b/packages/cli/test/lib/formatters/local.test.ts @@ -11,6 +11,8 @@ import type { FilterValue } from "../../../src/lib/formatters/local.js"; import { extractTraceId, formatAttributeTable, + formatEnvelopeLines, + formatEnvelopeLinesJson, formatErrorItem, formatItem, formatItemJson, @@ -23,6 +25,8 @@ import { isItemIncluded, itemTypeToFilterCategory, } from "../../../src/lib/formatters/local.js"; +import { createReceiverEnvelope } from "../../../src/commands/local/envelope.js"; +import { summarizeEnvelope } from "../../../src/commands/local/event-summary.js"; import { parseEventTimestamp } from "../../../src/commands/local/timestamp.js"; import { stripAnsi } from "../../../src/lib/formatters/plain-detect.js"; import { at } from "../../helpers.js"; @@ -1497,3 +1501,17 @@ describe("sentry-python ISO 8601 timestamps", () => { ); }); }); + +test("an event item that is not JSON never shows as an error", () => { + const container = createReceiverEnvelope({ + body: Buffer.from('{}\n{"type":"event"}\nnot-json\n'), + }); + const parsed = container.getParsedEnvelope(); + if (!parsed) throw new Error("expected the envelope to decode"); + const [line] = formatEnvelopeLines(container, new Set()); + expect(stripAnsi(line ?? "")).not.toMatch(/ERROR|Unknown error/); + expect(stripAnsi(line ?? "")).toContain("[INVALID]"); + const [json] = formatEnvelopeLinesJson(container, new Set()); + expect(JSON.parse(json ?? "{}")).toMatchObject({ type: "invalid" }); + expect(summarizeEnvelope(parsed)).toMatchObject({ type: "invalid" }); +}); From f89f5a83ef6d5187c17d7cbf3168c5b243ea7acb Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:51:58 +0000 Subject: [PATCH 2/3] fix(cli): Keep invalid events out of --verify and document them An event item that is not JSON now proves nothing to --verify, while the tail still shows it under -f error. Document the invalid JSON record, move the check into event-kind, and give a failed decompression a JSON reason like the other rejected bodies. Co-Authored-By: Aditya Mathur <57684218+MathurAditya724@users.noreply.github.com> --- apps/cli-docs/src/fragments/commands/local.md | 3 ++ packages/cli/src/commands/local/event-kind.ts | 9 ++++++ .../cli/src/commands/local/receiver-ingest.ts | 10 +++--- packages/cli/src/commands/local/run.ts | 7 ++-- packages/cli/src/lib/formatters/local.ts | 32 ++++++++++++++++--- packages/cli/test/commands/local/run.test.ts | 26 +++++++++++++++ .../cli/test/lib/formatters/local.test.ts | 2 ++ 7 files changed, 77 insertions(+), 12 deletions(-) diff --git a/apps/cli-docs/src/fragments/commands/local.md b/apps/cli-docs/src/fragments/commands/local.md index a40d0a970..a79b6a99d 100644 --- a/apps/cli-docs/src/fragments/commands/local.md +++ b/apps/cli-docs/src/fragments/commands/local.md @@ -207,6 +207,9 @@ Events with an exception type are `"type":"error"` records. Events without one, such as `captureMessage` calls and Python `logging` records, are `"type":"message"`. `-f error` returns both, so a script that keeps errors with `jq 'select(.type=="error")'` should also keep `"message"` if it wants them. +An event whose payload is not JSON is a `"type":"invalid"` record with +`"level":"invalid"`, in this stream and in `event list`. `-f error` still shows +it, but `--verify` does not count it as an event from your app. In JSON mode, event records are versioned NDJSON on standard output. Startup, connection, and shutdown messages stay on standard error, so an agent can pipe diff --git a/packages/cli/src/commands/local/event-kind.ts b/packages/cli/src/commands/local/event-kind.ts index 79df5a86c..d8789ab2e 100644 --- a/packages/cli/src/commands/local/event-kind.ts +++ b/packages/cli/src/commands/local/event-kind.ts @@ -30,6 +30,15 @@ export function readMessageText(value: unknown): string | undefined { return undefined; } +/** + * Whether an `event` item could not be decoded. The receiver keeps an item + * that is not JSON as `{ data }`, without the `type` it adds to every decoded + * item, so it is neither an exception nor a message. + */ +export function isUndecodedEvent(event: Record): boolean { + return !("type" in event) && typeof event["data"] === "string"; +} + /** How an event reads: its kind, thrown type, and the text to show for it. */ export type EventDescription = { kind: "exception" | "message" | undefined; diff --git a/packages/cli/src/commands/local/receiver-ingest.ts b/packages/cli/src/commands/local/receiver-ingest.ts index bbe6ef2cf..73b68c05d 100644 --- a/packages/cli/src/commands/local/receiver-ingest.ts +++ b/packages/cli/src/commands/local/receiver-ingest.ts @@ -26,7 +26,7 @@ type ReceiverState = { /** Requests still reading their body or reporting their status. */ requests: Set>; }; -/** A body that is not an envelope: HTTP 400 with this JSON, as Relay answers. */ +/** A body that is not an envelope: HTTP 400 with this JSON, shaped like the 410 body. */ type ReceiverRejected = { error: string }; const receivers = new WeakMap(); const oversizedListeners = new WeakMap void>>(); @@ -161,7 +161,7 @@ export function ingestReceiverEnvelope( */ closed?: boolean; }, -): Promise<204 | 400 | 410 | 413 | 415 | 503 | ReceiverRejected> { +): Promise<204 | 410 | 413 | 415 | 503 | ReceiverRejected> { const contentType = input.contentType?.split(";")[0]?.trim().toLowerCase(); if ( contentType && @@ -176,7 +176,7 @@ export function ingestReceiverEnvelope( if (state.pending.size >= MAX_PENDING) return Promise.resolve(503); const generation = state.generation; const operation = state.queue.then( - async (): Promise<204 | 400 | 410 | 413 | 503 | ReceiverRejected> => { + async (): Promise<204 | 410 | 413 | 503 | ReceiverRejected> => { if (generation !== state.generation) return 503; let body = input.body; if (encoding && encoding !== "identity") { @@ -197,13 +197,13 @@ export function ingestReceiverEnvelope( "code" in error && error.code === "ERR_BUFFER_TOO_LARGE" ? 413 - : 400; + : { error: "The body could not be decompressed." }; } } if (generation !== state.generation) return 503; if (body.length > MAX_DECODED_BYTES) return 413; if (input.closed) return 410; - // Like Relay, reject bodies that are not envelopes and retain nothing. + // Reject bodies that are not envelopes, as Relay does, and retain nothing. if (!body.length) return { error: "The envelope is empty." }; if (!hasEnvelopeHeader(body)) return { error: "The envelope header is not a JSON object." }; diff --git a/packages/cli/src/commands/local/run.ts b/packages/cli/src/commands/local/run.ts index 3e0586f03..cf38b4c00 100644 --- a/packages/cli/src/commands/local/run.ts +++ b/packages/cli/src/commands/local/run.ts @@ -53,6 +53,7 @@ import { createReplayTracker, formatEnvelopeLines, formatEnvelopeLinesJson, + hasOnlyInvalidEvents, type FormatValue, printLocalViewerHint, } from "../../lib/formatters/local.js"; @@ -1042,8 +1043,10 @@ async function* runWithVerify( let subscriptionId: string | undefined; const envelopeReceived = new Promise((resolveEnvelope) => { - subscriptionId = buffer.subscribe(() => { - resolveEnvelope(); + subscriptionId = buffer.subscribe((container) => { + if (!hasOnlyInvalidEvents(container)) { + resolveEnvelope(); + } }); }); diff --git a/packages/cli/src/lib/formatters/local.ts b/packages/cli/src/lib/formatters/local.ts index 51a22e5ce..ef738b1d9 100644 --- a/packages/cli/src/lib/formatters/local.ts +++ b/packages/cli/src/lib/formatters/local.ts @@ -1,6 +1,9 @@ /** Tail formatters for the local dev server. */ -import { describeEvent } from "../../commands/local/event-kind.js"; +import { + describeEvent, + isUndecodedEvent, +} from "../../commands/local/event-kind.js"; import { exceptionValues, frameFile, @@ -398,9 +401,7 @@ type EventSummary = ( /** Summarize an `event` item for its tail line, JSON record, or `event list` entry. */ export function summarizeEvent(event: Record): EventSummary { - // The receiver keeps an item that is not JSON as `{ data }`, without the - // `type` it adds to every decoded item. Relay drops such events. - if (!("type" in event) && typeof event["data"] === "string") { + if (isUndecodedEvent(event)) { return { kind: "invalid", level: "invalid", @@ -1206,7 +1207,8 @@ function formatJsonObservation( /** * Format an `event` item as a JSON object, including the best stack frame. * Exceptions get `type: "error"` and an `error_type`; messages get - * `type: "message"` and no `error_type`. + * `type: "message"` and no `error_type`. An item that is not JSON gets + * `type: "invalid"` and `level: "invalid"`. */ function formatErrorJson( payload: Record, @@ -1481,6 +1483,26 @@ export function formatItem( return [formatFallbackLine(fallbackLabel)]; } +/** + * Whether every item in an envelope is an `event` that is not JSON. The tail + * still shows those under `-f error`, but they prove nothing about the SDK, + * so `--verify` does not count them. + */ +export function hasOnlyInvalidEvents(container: { + getParsedEnvelope: () => { + envelope: [unknown, [{ type?: string }, Record][]]; + } | null; +}): boolean { + const items = container.getParsedEnvelope()?.envelope[1] ?? []; + return ( + items.length > 0 && + items.every( + ([{ type }, payload]) => + ERROR_TYPES.has(type ?? "") && isUndecodedEvent(payload), + ) + ); +} + /** * Check whether an item should be shown given active filters. * diff --git a/packages/cli/test/commands/local/run.test.ts b/packages/cli/test/commands/local/run.test.ts index c657437f0..d1bffd849 100644 --- a/packages/cli/test/commands/local/run.test.ts +++ b/packages/cli/test/commands/local/run.test.ts @@ -1307,6 +1307,32 @@ describe("sentry local run --verify receiver", () => { } }); + test("does not verify on an event that is not JSON", async () => { + const sendInvalidEvent = [ + "-e", + [ + "const body = ['{}', JSON.stringify({ type: 'event' }), 'not-json'].join(String.fromCharCode(10));", + "fetch(process.env.SENTRY_SPOTLIGHT, { method: 'POST', body }).then(() => setTimeout(() => {}, 30000));", + ].join(" "), + ]; + const warn = vi.spyOn(logger, "warn").mockImplementation(() => {}); + try { + const func = (await runCommand.loader()) as unknown as RunFunc; + const error = await func + .call( + makeContext(), + { port: 0, host: "127.0.0.1", verify: true, timeout: 2 }, + process.execPath, + ...sendInvalidEvent, + ) + .catch((err: unknown) => err); + expect(error).toBeInstanceOf(VerifyFailedError); + expect((error as Error).message).toContain("Verification timed out"); + } finally { + warn.mockRestore(); + } + }); + test("verifies on a free port when the default port is busy", async () => { const busy = makeDefaultPortBusy(); const warn = vi.spyOn(logger, "warn").mockImplementation(() => {}); diff --git a/packages/cli/test/lib/formatters/local.test.ts b/packages/cli/test/lib/formatters/local.test.ts index 003ca165f..4beac1e02 100644 --- a/packages/cli/test/lib/formatters/local.test.ts +++ b/packages/cli/test/lib/formatters/local.test.ts @@ -1514,4 +1514,6 @@ test("an event item that is not JSON never shows as an error", () => { const [json] = formatEnvelopeLinesJson(container, new Set()); expect(JSON.parse(json ?? "{}")).toMatchObject({ type: "invalid" }); expect(summarizeEnvelope(parsed)).toMatchObject({ type: "invalid" }); + // The tail keeps it under -f error. + expect(formatEnvelopeLines(container, new Set(["error"]))).toHaveLength(1); }); From 12e026e54ac5529c453deaded70e88370e715ea9 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 19:39:15 +0000 Subject: [PATCH 3/3] fix(cli): Verify only on a valid item the filters show An envelope with an event that is not JSON next to a session or a filtered-out item still passed --verify. Check each item instead: an invalid event never counts, housekeeping items never count, and with -f only items the filters show count. --- apps/cli-docs/src/fragments/commands/local.md | 2 +- packages/cli/src/commands/local/run.ts | 7 ++- packages/cli/src/lib/formatters/local.ts | 47 ++++++++++------ packages/cli/test/commands/local/run.test.ts | 54 +++++++++++++++---- 4 files changed, 81 insertions(+), 29 deletions(-) diff --git a/apps/cli-docs/src/fragments/commands/local.md b/apps/cli-docs/src/fragments/commands/local.md index a79b6a99d..c244f500a 100644 --- a/apps/cli-docs/src/fragments/commands/local.md +++ b/apps/cli-docs/src/fragments/commands/local.md @@ -46,7 +46,7 @@ When `local run` sees `wrangler dev` and a `wrangler.json`, `wrangler.jsonc`, or ### Check your setup with `--verify` -`sentry local run --verify -- ` starts your app, waits for its first event, then stops it. It exits 0 once an event arrives. It fails if the app exits, crashes, or sends nothing within the timeout (30 seconds, or `--timeout `). When port 8969 is busy, it verifies on a free port. +`sentry local run --verify -- ` starts your app, waits for its first event, then stops it. It exits 0 once an event arrives. It fails if the app exits, crashes, or sends nothing within the timeout (30 seconds, or `--timeout `). When port 8969 is busy, it verifies on a free port. Sessions and client reports don't count as an event, and with `-f`, only items those filters show count. A Cloudflare Worker sends nothing until it handles a request, so send one to it while `--verify` waits. diff --git a/packages/cli/src/commands/local/run.ts b/packages/cli/src/commands/local/run.ts index cf38b4c00..cb2f9c563 100644 --- a/packages/cli/src/commands/local/run.ts +++ b/packages/cli/src/commands/local/run.ts @@ -51,9 +51,9 @@ import { type FilterValue, FORMAT_VALUES, createReplayTracker, + envelopeHasTelemetry, formatEnvelopeLines, formatEnvelopeLinesJson, - hasOnlyInvalidEvents, type FormatValue, printLocalViewerHint, } from "../../lib/formatters/local.js"; @@ -1041,10 +1041,13 @@ async function* runWithVerify( const spotlightUrl = `${url}/stream`; + // Only telemetry the active filters show counts: an SDK sends sessions and + // client reports even when nothing else reaches Sentry Local. + const activeFilters = new Set(flags.filter); let subscriptionId: string | undefined; const envelopeReceived = new Promise((resolveEnvelope) => { subscriptionId = buffer.subscribe((container) => { - if (!hasOnlyInvalidEvents(container)) { + if (envelopeHasTelemetry(container, activeFilters)) { resolveEnvelope(); } }); diff --git a/packages/cli/src/lib/formatters/local.ts b/packages/cli/src/lib/formatters/local.ts index ef738b1d9..33c6ed5ba 100644 --- a/packages/cli/src/lib/formatters/local.ts +++ b/packages/cli/src/lib/formatters/local.ts @@ -1484,23 +1484,40 @@ export function formatItem( } /** - * Whether every item in an envelope is an `event` that is not JSON. The tail - * still shows those under `-f error`, but they prove nothing about the SDK, - * so `--verify` does not count them. + * Housekeeping item types an SDK sends on its own, even when nothing else + * reaches Sentry Local. Every other type counts as telemetry, so item types + * that SDKs add later count without a change here. */ -export function hasOnlyInvalidEvents(container: { - getParsedEnvelope: () => { - envelope: [unknown, [{ type?: string }, Record][]]; - } | null; -}): boolean { +const NOT_TELEMETRY_ITEM_TYPES = new Set([ + "session", + "sessions", + "client_report", +]); + +/** + * Whether an envelope shows the app is set up: it holds an item the active + * filters let through, or, with no filters, any item that is not + * housekeeping. An event that is not JSON never counts, even though the tail + * shows it under `-f error`. + */ +export function envelopeHasTelemetry( + container: { + getParsedEnvelope: () => { + envelope: [Record, [{ type?: string }, unknown][]]; + } | null; + }, + activeFilters: ReadonlySet, +): boolean { const items = container.getParsedEnvelope()?.envelope[1] ?? []; - return ( - items.length > 0 && - items.every( - ([{ type }, payload]) => - ERROR_TYPES.has(type ?? "") && isUndecodedEvent(payload), - ) - ); + return items.some(([{ type }, payload]) => { + const item = payload as Record; + if (ERROR_TYPES.has(type ?? "") && isUndecodedEvent(item)) { + return false; + } + return activeFilters.size > 0 + ? isItemIncluded(type, activeFilters, item) + : type !== undefined && !NOT_TELEMETRY_ITEM_TYPES.has(type); + }); } /** diff --git a/packages/cli/test/commands/local/run.test.ts b/packages/cli/test/commands/local/run.test.ts index d1bffd849..f421a8db0 100644 --- a/packages/cli/test/commands/local/run.test.ts +++ b/packages/cli/test/commands/local/run.test.ts @@ -1307,30 +1307,62 @@ describe("sentry local run --verify receiver", () => { } }); - test("does not verify on an event that is not JSON", async () => { - const sendInvalidEvent = [ + /** An app that posts one envelope with these item lines, then idles. */ + function sendItems(...lines: string[]): string[] { + return [ "-e", - [ - "const body = ['{}', JSON.stringify({ type: 'event' }), 'not-json'].join(String.fromCharCode(10));", - "fetch(process.env.SENTRY_SPOTLIGHT, { method: 'POST', body }).then(() => setTimeout(() => {}, 30000));", - ].join(" "), + `fetch(process.env.SENTRY_SPOTLIGHT, { method: 'POST', body: ${JSON.stringify(["{}", ...lines].join("\n"))} }).then(() => setTimeout(() => {}, 30000));`, ]; + } + const invalidEvent = ['{"type":"event","length":8}', "not-json"]; + const session = ['{"type":"session"}', "{}"]; + const transaction = ['{"type":"transaction"}', '{"type":"transaction"}']; + const validEvent = ['{"type":"event"}', '{"message":"verify me"}']; + + async function verifyWithItems( + filter: NonNullable[0]["filter"]>, + lines: string[], + ): Promise { const warn = vi.spyOn(logger, "warn").mockImplementation(() => {}); + const info = vi.spyOn(logger, "info").mockImplementation(() => {}); try { const func = (await runCommand.loader()) as unknown as RunFunc; - const error = await func + return await func .call( makeContext(), - { port: 0, host: "127.0.0.1", verify: true, timeout: 2 }, + { port: 0, host: "127.0.0.1", verify: true, timeout: 2, filter }, process.execPath, - ...sendInvalidEvent, + ...sendItems(...lines), ) .catch((err: unknown) => err); - expect(error).toBeInstanceOf(VerifyFailedError); - expect((error as Error).message).toContain("Verification timed out"); } finally { warn.mockRestore(); + info.mockRestore(); } + } + + test.each([ + ["alone", [], invalidEvent], + ["with a session", [], [...invalidEvent, ...session]], + ["with a session under -f error", ["error"], [...invalidEvent, ...session]], + [ + "with filtered-out telemetry", + ["error"], + [...invalidEvent, ...transaction], + ], + ] as const)( + "does not verify on an event that is not JSON %s", + async (_name, filter, lines) => { + const error = await verifyWithItems([...filter], [...lines]); + expect(error).toBeInstanceOf(VerifyFailedError); + expect((error as Error).message).toContain("Verification timed out"); + }, + ); + + test("verifies on a valid error next to an event that is not JSON", async () => { + expect( + await verifyWithItems(["error"], [...invalidEvent, ...validEvent]), + ).toBeUndefined(); }); test("verifies on a free port when the default port is busy", async () => {