feat(engine): a late image's load time is logged when it arrives (#8372)

* feat(engine): a late image's load time is logged when it arrives

A frame that shows a still-loading image waits for it, which can hold a render for minutes, but nothing said where that time went. When a late image arrives, the engine now logs [FrameCapture:late_image_arrived] with the frame, whether it came from the page's own server, the path depth and extension, and its resource timing split into queued, connect, first byte and download. No host, query or file name is logged.

* fix(engine): a late image whose request timing is hidden logs only its total

For another origin without Timing-Allow-Origin, Chrome zeroes connectStart, connectEnd, requestStart and responseStart, so the split read a slow server as a slow download. Such an entry now logs requestedAtMs and totalMs with split: not-exposed; every record also carries totalMs.
This commit is contained in:
Miguel Ángel
2026-11-21 13:31:59 +00:00
committed by GitHub
parent 9a618b798f
commit e65b11e5c2
4 changed files with 199 additions and 3 deletions
@@ -6,7 +6,13 @@ import {
type CaptureSession,
} from "./frameCapture.js";
type Reading = { arrived: string[]; waiting: string[]; broken: string[] };
type Reading = {
arrived: string[];
waiting: string[];
broken: string[];
timings?: Record<string, unknown>;
origin?: string;
};
function sessionReading(readings: Reading[], late: string[], playerReadyTimeout = 60_000) {
const evaluate = vi.fn(async () => readings.shift() ?? { arrived: [], waiting: [], broken: [] });
@@ -43,6 +49,61 @@ describe("waitForShownLateImages", () => {
expect(evaluate).toHaveBeenCalledTimes(2);
});
it("logs one load-time record when a late image arrives, without its file name", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
try {
const timing = {
startTime: 0,
fetchStart: 0,
connectStart: 0,
connectEnd: 0,
requestStart: 30_000,
responseStart: 30_005,
responseEnd: 30_006,
};
const { session } = sessionReading(
[
{ arrived: [], waiting: [PHOTO], broken: [] },
{
arrived: [PHOTO],
waiting: [],
broken: [],
timings: { [PHOTO]: timing },
origin: "http://localhost:1",
},
],
[PHOTO],
);
await waitForShownLateImages(session, 12);
await waitForShownLateImages(session, 13);
const records = warn.mock.calls.filter(
([text]) => text === "[FrameCapture:late_image_arrived]",
);
expect(records).toEqual([
[
"[FrameCapture:late_image_arrived]",
{
frameIndex: 12,
from: "page-server",
pathDepth: 2,
extension: "png",
timing: {
requestedAtMs: 0,
totalMs: 30_006,
queuedMs: 30_000,
connectMs: 0,
firstByteMs: 5,
downloadMs: 1,
},
},
],
]);
expect(JSON.stringify(records)).not.toContain("photo");
} finally {
warn.mockRestore();
}
});
it("captures on when the late image is not in this frame, and keeps it listed", async () => {
const { session } = sessionReading([{ arrived: [], waiting: [], broken: [] }], [PHOTO]);
await waitForShownLateImages(session, 0);
+18 -2
View File
@@ -134,6 +134,7 @@ import {
import { sampleProcessRss } from "../utils/processRss.js";
import type { CompositionLengthSource } from "@hyperframes/core/runtime/composition-length";
import { assertVariablesMatchPage } from "./variablesCheck.js";
import { describeLateImage, type RawResourceTiming } from "./lateImageTiming.js";
export { isMemoryExhaustionError, isTransientBrowserError } from "./captureFailure.js";
export type { CaptureOptions, CaptureResult, CaptureBufferResult, CapturePerfSummary };
@@ -2613,7 +2614,7 @@ export async function waitForShownLateImages(
const timeoutMs = session.config?.playerReadyTimeout ?? DEFAULT_CONFIG.playerReadyTimeout;
const deadline = Date.now() + timeoutMs;
for (;;) {
const { arrived, waiting, broken } = await session.page.evaluate(async (urls: string[]) => {
const reading = await session.page.evaluate(async (urls: string[]) => {
const listed = new Set(urls);
const found = Array.from(document.querySelectorAll("img")).filter((img) =>
listed.has(img.src),
@@ -2641,9 +2642,24 @@ export async function waitForShownLateImages(
arrived: loaded.map((img) => img.src),
waiting: shown.filter((img) => !img.complete).map((img) => img.src),
broken: shown.filter((img) => img.complete).map((img) => img.src),
timings: Object.fromEntries(
loaded.map((img) => [
img.src,
performance.getEntriesByName(img.src, "resource").at(-1)?.toJSON(),
]),
),
origin: location.origin,
};
}, Array.from(lateImages));
for (const source of arrived) lateImages.delete(source);
const { arrived, waiting, broken } = reading;
for (const source of arrived) {
if (!lateImages.delete(source)) continue;
const timing = reading.timings?.[source] as RawResourceTiming | undefined;
console.warn("[FrameCapture:late_image_arrived]", {
frameIndex,
...describeLateImage(source, reading.origin ?? "", timing),
});
}
const missing = Date.now() >= deadline ? [...waiting, ...broken] : broken;
if (missing.length > 0) {
const stopped = new ImageMissingFromFrameError(
@@ -0,0 +1,57 @@
import { describe, expect, it } from "vitest";
import { describeLateImage, type RawResourceTiming } from "./lateImageTiming.js";
const PAGE = "http://localhost:42957";
// Waited 40 s for a connection slot on a reused connection, then answered at once.
const QUEUED: RawResourceTiming = {
startTime: 1_500,
fetchStart: 1_500,
connectStart: 1_500,
connectEnd: 1_500,
requestStart: 41_500,
responseStart: 41_510,
responseEnd: 41_512,
};
describe("describeLateImage", () => {
it("splits a late image's load into queued, connect, first byte and download", () => {
expect(describeLateImage(`${PAGE}/assets/logo.svg`, PAGE, QUEUED)).toEqual({
from: "page-server",
pathDepth: 2,
extension: "svg",
timing: {
requestedAtMs: 1_500,
totalMs: 40_012,
queuedMs: 40_000,
connectMs: 0,
firstByteMs: 10,
downloadMs: 2,
},
});
});
it("counts a new connection as connect time, not queue time", () => {
const fresh = { ...QUEUED, connectStart: 1_600, connectEnd: 1_900, requestStart: 1_900 };
const record = describeLateImage(`${PAGE}/assets/logo.svg`, PAGE, fresh);
expect(record.timing).toMatchObject({ queuedMs: 100, connectMs: 300 });
});
it("keeps no host, query or file name from the URL", () => {
const src = "https://cdn.customer-brand.example/team/acme-secret-logo.PNG?token=abc";
const record = describeLateImage(src, PAGE, QUEUED);
expect(record).toMatchObject({ from: "other-origin", pathDepth: 2, extension: "png" });
expect(JSON.stringify(record)).not.toMatch(/customer-brand|acme|secret|token|team/);
});
// fails without the fix: the zeroed fields made a slow server read as a slow download.
it("reports only the total for another origin that hides its request timing", () => {
// What Chrome records for another origin without Timing-Allow-Origin.
const hidden = { ...QUEUED, connectStart: 0, connectEnd: 0, requestStart: 0, responseStart: 0 };
const record = describeLateImage("https://cdn.example/a/b.png", PAGE, hidden);
expect(record.timing).toEqual({ requestedAtMs: 1_500, totalMs: 40_012, split: "not-exposed" });
});
it("says so when the page kept no timing entry for the image", () => {
expect(describeLateImage(`${PAGE}/a.svg`, PAGE, undefined).timing).toBe("no-entry");
});
});
@@ -0,0 +1,62 @@
/** The PerformanceResourceTiming fields a late image's record is built from, read in the page. */
export interface RawResourceTiming {
startTime: number;
fetchStart: number;
connectStart: number;
connectEnd: number;
requestStart: number;
responseStart: number;
responseEnd: number;
}
/** Where a late image's load time went, with no host, query or file name. */
export interface LateImageRecord {
from: "page-server" | "other-origin";
pathDepth: number;
extension: string;
timing: LateImageTiming | "no-entry";
}
/** Another origin without Timing-Allow-Origin zeroes the request fields, so only the total is known. */
type LateImageTiming =
| {
requestedAtMs: number;
totalMs: number;
queuedMs: number;
connectMs: number;
firstByteMs: number;
downloadMs: number;
}
| { requestedAtMs: number; totalMs: number; split: "not-exposed" };
const ms = (value: number) => Math.max(0, Math.round(value));
function splitTiming(raw: RawResourceTiming): LateImageTiming {
const known = { requestedAtMs: ms(raw.startTime), totalMs: ms(raw.responseEnd - raw.startTime) };
if (raw.requestStart === 0 || raw.responseStart === 0) return { ...known, split: "not-exposed" };
const connectMs = raw.connectEnd - raw.connectStart;
return {
...known,
queuedMs: ms(raw.requestStart - raw.fetchStart - connectMs),
connectMs: ms(connectMs),
firstByteMs: ms(raw.responseStart - raw.requestStart),
downloadMs: ms(raw.responseEnd - raw.responseStart),
};
}
export function describeLateImage(
src: string,
pageOrigin: string,
raw: RawResourceTiming | undefined,
): LateImageRecord {
const url = new URL(src);
const segments = url.pathname.split("/").filter(Boolean);
const name = segments.at(-1) ?? "";
const dot = name.lastIndexOf(".");
return {
from: url.origin === pageOrigin ? "page-server" : "other-origin",
pathDepth: segments.length,
extension: dot > 0 ? name.slice(dot + 1).toLowerCase() : "",
timing: raw ? splitTiming(raw) : "no-entry",
};
}