Skip to content

[Feature]: Lower the CPU cost of tracing (DOM snapshots, screencast, network, zip) #44053

Closed as not planned

Description

🚀 Feature Request

Tracing with snapshots: true makes action-heavy tests about 2× slower, and the cost grows with the size of the DOM. I measured where the time goes, and I have fixes ready that keep the trace content the same. I would like to work on this.

Where the time goes

Measured on Linux (4 cores, no GPU), Chromium 158 headless shell, Playwright 1.66.0-next. 150 actions (fill, click, textContent) on a page with ~2,100 elements (~3,000 nodes). Median of 3 runs.

  1. DOM snapshots. Each action takes 2 or 3 snapshots. Each snapshot walks the full DOM in the page (snapshotterInjected.ts) and reads scrollTop and scrollLeft of every element. The scroll reads alone are ~45% of the walk. But 349 of 400 snapshots send 10 nodes or fewer: almost all of the walk is for unchanged nodes. Here that is ~5 ms per snapshot. On a page with ~20,000 elements it is ~60 ms per snapshot, and 60 actions take 11 s instead of 2.5 s.
  2. Screencast throttling does not slow the browser down. Chromium starts the screencast with maxFramesInFlight: 5. While ScreencastTracingRecorder throttles, it acks the frames that it drops at once, so the browser keeps sending frames at full rate. On an idle page with a CSS spinner, the browser sends 180 frames in 3 s and tracing keeps ~15.
  3. Network recording fetches script bodies that it drops. With omitScripts, HarTracer still calls response.internalBody() for every script, and only then drops the body.
  4. tracing.stop(). localUtils.zip uses one deflate stream for each file. With many small files (screencast frames), this costs much more CPU than one deflate call for each file.
  5. Every evaluate formats an error stack. LongStandingScope.race formats new Error().stack on each call, but it needs the stack only when the scope closes. This is not specific to tracing, but snapshots add one evaluate per frame and phase.
  6. Trace writes. Outside of ui mode, each action event and each frame snapshot is written to the trace file at once: an open, a write and a close for each event, with their promises and timers. Also, each protocol message goes to the browser pipe in two writes (the message, then the zero byte).

Proposed changes

  1. Visit only changed nodes in a snapshot.
    • A MutationObserver (on the document and on open shadow roots) marks changed nodes and their ancestors. The walk returns the reference of an unchanged subtree without a visit to it. Inserted nodes always get a full visit.
    • State that changes without a DOM mutation is checked only on the elements that can have it: form controls, canvases, iframes, popovers, images that are still loading, and scroll candidates. Loaded images are marked by their load and error events.
    • Scroll offsets are read only on scroll containers (found from the computed overflow, which costs less than the old scroll reads), on the scrolling element, and on elements that got a scroll event.
    • Frame snapshot events are written without a deep copy in visitTraceEvent, because they hold only plain data from the page.
  2. Make the browser wait while screencast frames are throttled. A dropped frame waits for the pending ack. Other clients (video) still ack at once.
  3. Do not fetch the body of an omitted script.
  4. Compress small files in one call when zipping. Small files (up to 1 MB each, 64 MB in total) use addBuffer; larger files still use a stream. The compression level and the zip size are the same.
  5. Format the stack of LongStandingScope.race only when the scope closes. The error text does not change.
  6. Write trace events in batches outside of ui mode. A flush writes the text that is buffered at that time ~100 ms later, in one write together with the other flushes. Console events are still not flushed (as TR-039 expects), and ui mode still writes each event at once. Each protocol message goes to the pipe in one write.

To check change 1, I rendered every snapshot of traces made with the old and the new code with SnapshotRenderer and compared the HTML, on Chromium, Firefox and WebKit. The only differences were from timing (an image that was still loading, a new iframe) and one bug fix: after history.pushState() the old code kept the old <base href> in snapshots.

Tests:

  • The trace viewer and tracing tests pass on Chromium, Firefox and WebKit.
  • The HAR, video, screencast, page and frame evaluate, test-runner trace, ui mode and MCP tracing tests pass on Chromium.
  • There is one new test: state that changes between snapshots without a DOM mutation.

Results (before → after)

150 actions Wall Node CPU Renderer CPU tracing.stop()
no tracing 2.83–2.90 s 510–560 ms ~1,670 ms –
tracing, no snapshots, no screenshots 2.88 → 2.82 s 739 → 618 ms ~1,700 ms 17 → 17 ms
snapshots: true 5.70 → 3.73 s 1,079 → 797 ms 4,620 → 2,110 ms 23 → 22 ms
screenshots: true 2.83 → 2.83 s 818 → 688 ms ~1,700 ms 139 → 75 ms
both 6.12 → 3.59 s 1,285 → 832 ms 5,070 → 1,990 ms 212 → 68 ms
Other cases Before After
~20,000 elements, 60 actions, snapshots: true (no tracing: 2.5–2.6 s) 10.99 s, renderer 11,560 ms, Node 801 ms 2.98 s, renderer 2,520 ms, Node 366 ms
20 loads of a page with 3 MB of JS, snapshots: true (no tracing: 2.4 s) 3.21 s, browser process 1,060 ms, Node 915 ms 2.53 s, browser process 550 ms, Node 629 ms
Idle animated page, screenshots: true, 3 s 181 frames, browser process 590 ms, Node 192 ms 90 frames, browser process 320 ms, Node 163 ms

With screenshots: true, change 2 helps only when the page is idle: tracing keeps every frame for 500 ms after each action.

Known limits of change 1

  • First snapshot: it is a full walk, at the trace start and in each new document. On the ~20,000-element page it costs about the same as before, or up to ~10% more (~90 ms). Each later snapshot on that page costs ~0.2 ms instead of ~60 ms.
  • Scroll: a scroll can be missed for one snapshot. This happens when an element becomes a scroll container, or its content starts to overflow, without a change in its subtree (for example after a style sheet change), and it is then scrolled before the browser fires its scroll event.
  • Images: a loaded image that selects another srcset source keeps its old currentSrc in snapshots until its load event.
  • Page work: the observer also watches childList and characterData, so pages with many DOM changes do a little more work while the snapshot script is installed.

Not in scope

With screenshots: true, the GPU process uses ~1,300 ms of CPU per 3 s on an animated page. This cost does not change with the frame rate, everyNthFrame, the JPEG quality or the ack timing, so it is inside Chromium.

Example

There is no API change. The same configuration becomes faster:

// playwright.config.ts
use: { trace: 'on' }

// or
await context.tracing.start({ snapshots: true, screenshots: true });

I can share the benchmark scripts.

Motivation

Many projects run CI with trace: 'on', 'on-first-retry' or 'retain-on-failure'. With snapshots on, every action pays for a full DOM walk, so large pages and long tests are slowed down the most, and CI uses more CPU. #32746 reported the same slowdown with snapshots: true.

I noticed this while working on Piwi, which reads the network requests and stack traces from Playwright traces. CPU usage and run times dropped clearly when tracing was off. I did not measure it precisely at that time: the numbers above come from a plain Playwright benchmark that I wrote afterwards.

The six changes are independent. I can send them as 6 small PRs (snapshots, screencast, network, zip, race stack, trace writes), or in a different split if you prefer.

Activity

  1. microsoft-playwright-automation commented on Nov 11, 2026

    @microsoft-playwright-automation
  2. microsoft-playwright-automation commented on Nov 11, 2026

    @microsoft-playwright-automation
    Contributor

    Hi, I'm the Playwright bot. I checked the tracing code and measured a separate, self-contained workload.

    Confirmed: DOM snapshot overhead grows substantially with page size in all three browsers. On Linux at 1.66.0-next, commit d3ca7ab3750151b3a636e878d6e3a7ba4c60db18, 60 actions on a page with 20,000 repeated elements took 7.0 s with snapshots versus 1.0 s without tracing in Chromium. Firefox and WebKit showed the same size-dependent slowdown.

    This is a valid performance request, but the main snapshot change needs a wider design decision, not just an implementation change. A subtree without DOM mutations can still change its scroll position, control values, selected image source, adopted stylesheets, or layout. The reported scroll and image limitations would change captured state; they are not equivalent to keeping trace content unchanged. I have not proposed that tradeoff as a fix.

    Measurements and condensed workload

    These are medians of three headless runs per configuration on this runner, not a reproduction of the reporter's benchmark. Each run used a new context, one input, one button, one output, and 2,100 or 20,000 repeated <div>Unchanged text</div> elements. Timings cover the action loop; export time is separate. Other validation work overlapped part of this measurement, so these numbers establish the size-dependent cost, not a precise speed target.

    await page.setContent(
      '<input><button>Click</button><output>Value</output>' +
      '<div>Unchanged text</div>'.repeat(elementCount)
    );
    // Traced runs only:
    await context.tracing.start({ snapshots: true, screenshots: false });
    for (let i = 0; i < 20; i++) {
      await page.locator('input').fill(String(i));
      await page.locator('button').click();
      await page.locator('output').textContent();
    }
    await context.tracing.stop({ path: 'trace.zip' });

    The comparison runs omitted both tracing calls.

    Browser Repeated elements No tracing DOM snapshots Snapshot collection total Trace export
    Chromium 158, headless shell 2,100 0.68 s 1.35 s 0.36 s 30 ms
    Chromium 158, headless shell 20,000 1.05 s 6.99 s 3.38 s 337 ms
    Firefox 159 2,100 1.06 s 1.81 s 0.31 s 35 ms
    Firefox 159 20,000 1.80 s 9.57 s 2.92 s 338 ms
    WebKit 27.2 2,100 0.68 s 0.98 s 0.17 s 36 ms
    WebKit 27.2 20,000 1.03 s 4.54 s 1.91 s 348 ms

    Every traced run recorded 160 frame snapshots. Snapshot collection totals come from their collectionTime fields. All 36 configurations completed on Linux. I did not run headed browsers or older releases: the request concerns current performance, not a reported release regression.

    Source findings and existing checks

    At the tested commit:

    • snapshotterInjected.ts traverses descendants before returning a cached subtree reference. Its mutation observer caches attributes, not entire unchanged subtrees. Scroll offsets and non-attribute state are read during that traversal.
    • ScreencastTracingRecorder returns immediately for additional frames while _pendingAck exists; Chromium permits five outstanding frames at the default frame rate. That confirms the early-ack path described here, but I did not measure a replacement.
    • HarTracer calls response.internalBody() before checking omitScripts.
    • localUtils.zip uses yazl.addFile, and LongStandingScope._race reads and splits Error.stack for each race.
    • Action and snapshot events request a flush. SerializedFS already buffers other appends and merges adjacent pending writes, so this is not unconditionally one filesystem operation per event. The browser pipe currently writes the JSON and terminator separately.

    These source findings confirm work that could be avoided; they do not independently verify the proposed speedups or behavior preservation.

    npm run build passed. The following existing tests passed on Chromium, Firefox, and WebKit, 15 tests total:

    • TR-001 should collect trace with resources, but no js
    • TV-044 should work with adopted style sheets and replace/replaceSync
    • TV-048 should restore scroll positions
    • TV-049 should restore control values
    • TV-055 should register custom elements

    The linked #32746 was closed for lack of a reproduction, not by a verified performance fix. No PR linked to this issue was found. No code change is proposed: the unresolved part is the snapshot invalidation and freshness contract across these changes, rather than a browser-specific defect.

    Triaged on Linux by the Playwright bot - agent run

  3. PhenX commented on Nov 11, 2026

    @PhenX
    Author

    Thanks for the triage !

    Changes 2–6: They do not change the trace content, and each one is small. If you agree, I can send them now as 5 separate PRs (screencast, network, zip, race stack, trace writes), while we discuss change 1.

    Change 1: I agree that it needs a decision. I can make the difference from a full walk smaller:

    • Images: I can remove this limit. A loaded image with srcset, or in a <picture>, would get its currentSrc read on every snapshot, as the full walk does today. This read does not cause a layout, so it costs little.
    • Scroll: one case stays. An element becomes scrollable only because of a style change (no DOM change in its subtree), and a script scrolls it before the browser fires scroll. Then one snapshot can miss the scroll position. To close this case, the snapshot must read the scroll position of every element, and that is the cost that the change removes.

    To make the decision safer, I can also add one or both of these:

    • A check mode for Playwright's own tests: each incremental snapshot is compared with a full walk, and a difference fails the test.
    • A switch that turns the full walk back on.

    Is the scroll case acceptable to you, and which safety option do you prefer?

    I'd just like to talk about something: CI resources matter more now. With coding agents, more code and more tests are written, and the tests run more often: on each change, and in loops while an agent works. Many projects use trace: 'on' or 'retain-on-failure', and with 'retain-on-failure' every passing test also pays the full tracing cost. In my measurements, an action-heavy test with snapshots and screenshots took ~40% less time and used ~60% less renderer CPU with these changes. For large CI fleets this is real cost and energy, and faster feedback for people and agents.

    That's why I would like to continue on issues like this one:

    • UI mode: while a long test runs, the memory and CPU of UI mode grow with the length of the test. I have a follow-up issue and fixes ready. For a test with ~3,000 API calls, the UI renderer peak memory goes from ~2.2 GB to ~0.7 GB, and its CPU from ~87 s to ~17 s. I will open it after this issue moves forward, because it uses change 6.
    • Aria snapshots in traces (snapshots: { aria: true }): on a page with ~2,100 elements, each one costs ~90 ms, so the same test runs ~4× slower than with DOM snapshots only.
    • Playwright internals: costs that every call pays, like the stack formatting in change 5.

    If you have a list of known performance problems, or areas where you want help, I am happy to take them.

  4. yury-s commented on Nov 11, 2026

    @yury-s
    Member

    Thank you for the detailed measurements.

    We looked at each item. The screencast throttling change is small and safe, and we landed it in #44068.

    The snapshot change is different. Today each snapshot reads the full state of the page: scroll offsets, control values, image sources. We confirmed that the scroll reads are about half of the walk. But the proposed change replaces the reads with tracking, and the limits you list (a missed scroll position, an old currentSrc) mean that a snapshot can differ from the page. We prefer exact snapshots to faster ones, because the trace is what people use to debug a failure. We do not plan to make that tradeoff now.

    The other items give small gains for the amount of code they change, so we will not take them at this time.

    If tracing cost is a problem in CI, trace: 'on-first-retry' or 'retain-on-failure' with snapshots only where needed keeps the cost down. I will close this issue. If you find a way to skip unchanged nodes that keeps the snapshots exact, please open a new issue with that design.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions