Skip to content

Commit 3a73268

Browse files
fix(local): Keep receive times out of trace timing (#2392)
Follow-up to #2373, from its review. To show a time on items that don't have one, like replay recordings and cron check-ins, we wrote the receive time into the item's `timestamp`. Trace timing reads that same field. So a check-in that arrived a few minutes after its transaction made the whole trace look minutes long. Now the receive time goes in its own field, and it's only used to show and sort items. While here: - Span start and end times show milliseconds, plus the date when it isn't today. Before, a 40 ms span showed the same start and end. - ANSI colour codes are stripped from nested values in attribute tables too, not just top-level strings. - A pasted session link is always cleared from the address bar, even when the viewer refuses its stream. This only applies when the link is pasted on the same page, since a different path is a normal page load. **Before / after:** ``` Trace with a 400 ms transaction + a check-in received 222 s later before: nightly-report · 222.40 s after: nightly-report · 400.00 ms Span detail, 40 ms span before: Start 10:13:20 PM End 10:13:20 PM after: Start 11/14/2023 10:13:20.538 PM End 11/14/2023 10:13:20.578 PM ``` <!-- junior-request-attribution:start --> via @MathurAditya724. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:agent%3Ad19d9b34774a206e9eb18be9e235a825 --> -- [View Session](https://junior-prod.sentry.dev/conversations/agent%3Ad19d9b34774a206e9eb18be9e235a825) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3Ad19d9b34774a206e9eb18be9e235a825/?project=4510944073809921) <!-- junior-session-footer:end --> Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Aditya Mathur <57684218+MathurAditya724@users.noreply.github.com>
1 parent 485d8c0 commit 3a73268

13 files changed

Lines changed: 235 additions & 43 deletions

‎apps/local/src/App.capture-lifecycle.test.tsx‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -790,3 +790,57 @@ test("replay recordings show when they were received instead of unknown time", a
790790
expect(row.textContent).not.toContain("unknown time");
791791
expect(row.textContent).toContain(new Date(receivedAt).toLocaleTimeString());
792792
});
793+
794+
test("an untimed item in a trace does not stretch the trace to its receive time", async () => {
795+
// A 400 ms transaction, then a sentry-python cron check-in in the same
796+
// trace that the receiver got 222 s later. Check-ins carry no timestamp.
797+
const uuidv7 = (ms: number) =>
798+
`${ms
799+
.toString(16)
800+
.padStart(12, "0")
801+
.replace(/^(.{8})(.{4})$/, "$1-$2")}-7abc-8def-0123456789ab`;
802+
const finishedAt = 1_794_947_420.913;
803+
const traceId = "8f2a6c1e4b7d4f0a9c3e5b1d7a2f6c8e";
804+
renderCapture({ path: "/traces" });
805+
const source = await openSource();
806+
const send = (lastEventId: string, items: unknown[]) =>
807+
act(async () =>
808+
source.dispatchEvent(
809+
new MessageEvent("application/x-sentry-envelope", {
810+
data: JSON.stringify([{}, items]),
811+
lastEventId,
812+
}),
813+
),
814+
);
815+
await send(uuidv7(finishedAt * 1000 + 50), [
816+
[
817+
{ type: "transaction" },
818+
{
819+
type: "transaction",
820+
transaction: "nightly-report",
821+
start_timestamp: finishedAt - 0.4,
822+
timestamp: finishedAt,
823+
contexts: {
824+
trace: { trace_id: traceId, span_id: "a1b2c3d4e5f60718", op: "task" },
825+
},
826+
},
827+
],
828+
]);
829+
await send(uuidv7(finishedAt * 1000 + 222_000), [
830+
[
831+
{ type: "check_in" },
832+
{
833+
check_in_id: "5f1c0e8a2b9d4c7e8f3a1b6d0c9e2f4a",
834+
monitor_slug: "nightly-report",
835+
status: "ok",
836+
duration: 0.4,
837+
contexts: { trace: { trace_id: traceId, span_id: "a1b2c3d4e5f60718" } },
838+
},
839+
],
840+
]);
841+
const row = await screen.findByRole("button", {
842+
name: "View trace nightly-report",
843+
});
844+
expect(row.textContent).toMatch(/400(\.0+)? ms/);
845+
expect(row.textContent).not.toContain("222");
846+
});

‎apps/local/src/App.sessions.integration.test.tsx‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -729,3 +729,24 @@ test("a new session link in an open tab switches to that run's sessions", async
729729
await second.stop();
730730
}
731731
});
732+
733+
test("a pasted link with a stream the viewer refuses still leaves the address bar", async () => {
734+
const daemon = await startDaemon();
735+
try {
736+
const web = await daemon.create("web");
737+
await daemon.ingest(web, "/first-run");
738+
renderSession(web);
739+
await screen.findAllByText("/first-run");
740+
await act(async () => {
741+
window.location.hash = new URLSearchParams({
742+
stream: "https://collector.example.com/stream",
743+
directory: web.directoryUrl,
744+
}).toString();
745+
});
746+
await waitFor(() => expect(window.location.hash).toBe(""));
747+
expect(screen.getAllByText("/first-run").length).toBeGreaterThan(0);
748+
} finally {
749+
cleanup();
750+
await daemon.stop();
751+
}
752+
});

‎apps/local/src/App.tsx‎

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,8 @@ import {
9090
DEFAULT_STREAM_URL,
9191
decodeEnvelope,
9292
getStreamUrlFromHash,
93+
itemTime,
94+
readConnectionLink,
9395
parseStreamEndpoint,
9496
isLoopbackHost,
9597
REMOTE_STREAM_STORAGE_KEY,
@@ -262,7 +264,7 @@ function EventEntry({
262264
) : null}
263265
{columns.includes("time") ? (
264266
<time className="shrink-0 font-mono text-xs tabular-nums text-muted-foreground">
265-
{formatTimestamp(item.timestamp)}
267+
{formatTimestamp(itemTime(item))}
266268
</time>
267269
) : null}
268270
</button>
@@ -711,18 +713,22 @@ export default function App() {
711713
});
712714
useEffect(() => {
713715
const onHashChange = () => {
716+
const link = readConnectionLink(window.location.hash);
717+
if (!link.present) return;
714718
const linkedStreamUrl = getStreamUrlFromHash(window.location.hash);
715-
if (!linkedStreamUrl) return;
716-
const directory = parseSessionDirectoryUrl(
717-
new URLSearchParams(window.location.hash.slice(1)).get("directory"),
718-
linkedStreamUrl,
719-
);
720-
connectToEndpointRef.current(linkedStreamUrl);
721-
if (directory) {
722-
saveSessionDirectory(directory);
723-
setDirectoryUrl(directory);
719+
if (linkedStreamUrl) {
720+
connectToEndpointRef.current(linkedStreamUrl);
721+
const directory = parseSessionDirectoryUrl(
722+
link.directory,
723+
linkedStreamUrl,
724+
);
725+
if (directory) {
726+
saveSessionDirectory(directory);
727+
setDirectoryUrl(directory);
728+
}
724729
}
725-
// The link carries capabilities; keep them out of the address bar.
730+
// The link carries capabilities, even a refused one; keep them out of
731+
// the address bar.
726732
void navigate(
727733
{ pathname: window.location.pathname, search: window.location.search },
728734
{ replace: true },
@@ -936,11 +942,7 @@ export default function App() {
936942
envelopeReceivedAt(eventId) ??
937943
(Number.isNaN(sentAtMs) ? Date.now() : sentAtMs);
938944
// Items with no SDK time, such as replay recordings, show when they arrived.
939-
items = items?.map((item) =>
940-
item.timestamp === undefined
941-
? { ...item, timestamp: receivedAt / 1000 }
942-
: item,
943-
);
945+
items = items?.map((item) => ({ ...item, receivedAt }));
944946
const itemTypes = [...new Set(items?.map((item) => item.type))];
945947
setLatestEventTime((latest) =>
946948
latest === undefined ? receivedAt : Math.max(latest, receivedAt),

‎apps/local/src/components/event-detail.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ import {
1818
type DetailField,
1919
} from "./inspector-data.ts";
2020
import type { LocalFeedItem } from "@/lib/spotlight.ts";
21-
import { getEventMetadata } from "@/lib/spotlight.ts";
21+
import { getEventMetadata, itemTime } from "@/lib/spotlight.ts";
2222
import { formatTimestamp } from "@/lib/presentation.ts";
2323
import { getEventExceptions } from "@/lib/exceptions.ts";
2424
import type { TraceGroup } from "@/lib/trace-model.ts";
@@ -213,7 +213,7 @@ export function EventDetail({
213213
</Button>
214214
) : null}
215215
<time className="shrink-0 font-mono text-xs tabular-nums text-muted-foreground">
216-
{formatTimestamp(item.timestamp)}
216+
{formatTimestamp(itemTime(item))}
217217
</time>
218218
</header>
219219
<InspectorTabs
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { expect, test } from "vitest";
2+
import { attributeFields } from "./inspector-data.ts";
3+
4+
test("attribute values hide terminal colour codes in nested strings too", () => {
5+
// uvicorn's logging record, kept as breadcrumb data by sentry-python.
6+
const [field] = attributeFields({
7+
record: {
8+
color_message: "Started server process [\u001b[36m%d\u001b[0m]",
9+
args: ["\u001b[1m41234\u001b[0m"],
10+
},
11+
});
12+
expect(field?.value).toBe(
13+
'{"color_message":"Started server process [%d]","args":["41234"]}',
14+
);
15+
});

‎apps/local/src/components/inspector-data.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,16 @@ export function attributeFields(value: unknown): DetailField[] {
1111
return Object.entries(detailRecord(value)).map(([label, attribute]) => {
1212
const record = detailRecord(attribute);
1313
const content = "value" in record ? record["value"] : attribute;
14-
const serialized = JSON.stringify(content) as string | undefined;
14+
const serialized = JSON.stringify(content, (_key, nested: unknown) =>
15+
typeof nested === "string" ? stripAnsi(nested) : nested,
16+
) as string | undefined;
1517
return {
1618
label,
1719
// Display only: the JSON tab keeps SDK text exactly as captured.
18-
value: stripAnsi(
19-
typeof content === "string" ? content : (serialized ?? String(content)),
20-
),
20+
value:
21+
typeof content === "string"
22+
? stripAnsi(content)
23+
: (serialized ?? String(content)),
2124
code: true,
2225
};
2326
});

‎apps/local/src/components/span-detail.test.tsx‎

Lines changed: 53 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
1-
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
1+
import {
2+
cleanup,
3+
fireEvent,
4+
render,
5+
screen,
6+
within,
7+
} from "@testing-library/react";
28
import { afterEach, expect, test, vi } from "vitest";
9+
import { formatDateTime } from "@/lib/presentation.ts";
310
import { decodeEnvelope } from "@/lib/spotlight.ts";
411
import { buildTraceGroups } from "@/lib/trace-model.ts";
512
import { SpanDetail } from "./span-detail.tsx";
@@ -99,6 +106,49 @@ test("span start and end times use local time, not raw epoch seconds", () => {
99106
const details =
100107
screen.getByRole("table", { name: "Span details" }).textContent ?? "";
101108
expect(details).not.toContain("1795010400.538");
102-
expect(details).toContain(new Date(1795010400538).toLocaleTimeString());
103-
expect(details).toContain(new Date(1795010400650).toLocaleTimeString());
109+
expect(details).toContain(
110+
formatDateTime(1795010400.538, { milliseconds: true }),
111+
);
112+
expect(details).toContain(
113+
formatDateTime(1795010400.65, { milliseconds: true }),
114+
);
115+
});
116+
117+
test("span times keep milliseconds and show the date when it is not today", () => {
118+
// A 40 ms span from an earlier day.
119+
const [trace] = buildTraceGroups(
120+
decodeEnvelope(
121+
JSON.stringify([
122+
{},
123+
[
124+
[
125+
{ type: "transaction" },
126+
{
127+
transaction: "GET /orders",
128+
start_timestamp: 1_700_000_000.538,
129+
timestamp: 1_700_000_000.578,
130+
contexts: { trace: { trace_id: "trace", span_id: "root" } },
131+
},
132+
],
133+
],
134+
]),
135+
"fixture",
136+
),
137+
);
138+
const span = trace?.spans.find((entry) => entry.id === "root");
139+
if (!trace || !span) throw new Error("Expected trace span");
140+
render(<SpanDetail trace={trace} span={span} />);
141+
const details = screen.getByRole("table", { name: "Span details" });
142+
const time = (ms: number) =>
143+
new Date(ms).toLocaleTimeString(undefined, {
144+
hour: "numeric",
145+
minute: "2-digit",
146+
second: "2-digit",
147+
fractionalSecondDigits: 3,
148+
});
149+
const start = within(details).getByRole("row", { name: /Start timestamp/ });
150+
const end = within(details).getByRole("row", { name: /End timestamp/ });
151+
const day = new Date(1_700_000_000_538).toLocaleDateString();
152+
expect(start.textContent).toContain(`${day} ${time(1_700_000_000_538)}`);
153+
expect(end.textContent).toContain(`${day} ${time(1_700_000_000_578)}`);
104154
});

‎apps/local/src/components/span-detail.tsx‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { Check, Copy, ChevronLeft } from "lucide-react";
44
import { type KeyboardEvent, type ReactNode, useId, useState } from "react";
55
import type { LocalFeedItem } from "@/lib/spotlight.ts";
66
import type { TraceGroup, TraceSpan } from "@/lib/trace-model.ts";
7-
import { formatTimestamp } from "@/lib/presentation.ts";
7+
import { formatDateTime } from "@/lib/presentation.ts";
88
import { isErrorEvent } from "@/lib/workspace.ts";
99
import { jsonText } from "@/lib/objects.ts";
1010
import { JsonView } from "./json-view.tsx";
@@ -219,7 +219,7 @@ export function SpanDetail({
219219
: [
220220
{
221221
label: "Start timestamp",
222-
value: formatTimestamp(span.startTimestamp),
222+
value: formatDateTime(span.startTimestamp, { milliseconds: true }),
223223
code: true,
224224
},
225225
]),
@@ -228,7 +228,7 @@ export function SpanDetail({
228228
: [
229229
{
230230
label: "End timestamp",
231-
value: formatTimestamp(span.endTimestamp),
231+
value: formatDateTime(span.endTimestamp, { milliseconds: true }),
232232
code: true,
233233
},
234234
]),

‎apps/local/src/lib/event-filters.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { parseEventTimestamp } from "../../../../packages/cli/src/commands/local/timestamp.ts";
2-
import type { LocalFeedItem } from "./spotlight.ts";
2+
import { itemTime, type LocalFeedItem } from "./spotlight.ts";
33
import { spanData, text } from "./inspection.ts";
44
export type EventColumn = "time" | "type" | "level" | "logger" | "duration";
55
export type EventFilters = {
@@ -18,7 +18,7 @@ export function loggerForItem(item: LocalFeedItem): string | undefined {
1818
return text(spanData(item.payload)["sentry.logger.name"]);
1919
}
2020
function timestamp(item: LocalFeedItem): number {
21-
const value = parseEventTimestamp(item.timestamp);
21+
const value = parseEventTimestamp(itemTime(item));
2222
if (value === undefined) return -Infinity;
2323
return value < 1e12 ? value * 1000 : value;
2424
}

‎apps/local/src/lib/inspection.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { classifyEvent } from "../../../../packages/cli/src/commands/local/event-kind.ts";
22
import { jsonText } from "./objects.ts";
3-
import { getEventMetadata, type LocalFeedItem } from "./spotlight.ts";
3+
import { getEventMetadata, itemTime, type LocalFeedItem } from "./spotlight.ts";
44
import { getEventExceptions, formatExceptionTitle } from "./exceptions.ts";
55

66
export function record(value: unknown): Record<string, unknown> {
@@ -258,7 +258,7 @@ export function sdkInventory(items: readonly LocalFeedItem[]): SdkEntry[] {
258258
key = `${name}@${version}`;
259259
const previous = entries.get(key);
260260
const lastSeen =
261-
item.timestamp ??
261+
itemTime(item) ??
262262
text(item.envelopeHeader?.["sent_at"]) ??
263263
previous?.lastSeen;
264264
entries.set(key, {

0 commit comments

Comments
 (0)