Skip to content

feat(performance): chunked trace buffer parser for large recordings - #2721

Merged
jackfranklin merged 3 commits into
mainfrom
chunked-trace-parsing
Sep 17, 2026
Merged

jackfranklin merged 3 commits into
mainfrom
chunked-trace-parsing

Conversation

@jackfranklin

Copy link
Copy Markdown
Contributor

Note

This PR is marked as WIP (Work in Progress) / Draft to gather feedback and extra opinions on the streaming / chunked parsing strategy for large performance traces.

Problem Statement

When recording performance traces on busy sites or over long recording durations, the resulting trace buffer often exceeds 512 MB (and can reach 1 GB+).

Currently, parseRawTraceBuffer decodes the entire raw buffer into a single string via new TextDecoder().decode(buffer) and parses it with JSON.parse(asString). In V8 (64-bit), strings are strictly limited to $2^{29} - 24$ characters (~512 MB). Any trace exceeding ~512 MB throws a fatal error:

RangeError: Cannot create a string longer than 0x1fffffe8 characters

This prevents the MCP server from parsing and analyzing large traces even when sufficient heap memory is available.

Proposed Solution: Chunked Trace Buffer Scanner

This change introduces ChunkedTraceParser.ts to extract trace events directly from the raw binary buffer in bounded batches without materializing the full trace JSON into a single string:

  1. Byte-Level Delimiter & Escape Scanning:

    • Scans the Uint8Array directly using ASCII byte codes (0x7B {, 0x7D }, 0x22 ", 0x5C \).
    • Tracks brace nesting depth while properly handling escaped quotes within strings.
    • Supports both bare JSON arrays ([ {...}, ... ]) and top-level object envelopes ({ "traceEvents": [ ... ], "metadata": { ... } }).
  2. Batched Native JSON.parse:

    • Accumulates slices of events into bounded batches (default: 5,000 events) wrapped in [ and ].
    • Parses each batch using native V8 JSON.parse, keeping intermediate string allocations small (< 5 MB) and short-lived.
    • Pushes parsed events iteratively to avoid V8 function call argument stack limits.
  3. Metadata Preservation:

    • Extracts top-level metadata from object envelopes (such as cpuThrottling and networkThrottling) and merges it with caller options.
  4. Strict Structural Validation:

    • Enforces valid structural tokens (closing brackets, braces, colons, commas) and prevents silent truncation on incomplete buffers or unexpected EOF.

Testing

  • Unit tests in tests/trace-processing/ChunkedTraceParser.test.ts covering:
    • Both top-level array and object formats.
    • Custom batch sizes and large batches exceeding function call argument limits (70,000+ events).
    • Malformed inputs: truncated arrays, unterminated strings, unquoted keys, trailing characters.
    • Multibyte UTF-8 characters split across byte boundaries.
  • Full regression tests against existing trace fixtures (basic-trace.json.gz, web-dev-with-commit.json.gz).

@jackfranklin

Copy link
Copy Markdown
Contributor Author

The buffer limit in Chrome Tracing does not align with the final JSON output, because it limits the size of the binary protobuf that is captured. So I also think separately we might want to consider reducing the limit from 1.2gb.

@jackfranklin

Copy link
Copy Markdown
Contributor Author

Please note also this PR is a WIP and is not fully ready for code review, sharing to get early thoughts on if we want to pursue it.

@jackfranklin jackfranklin changed the title WIP: feat(performance): chunked trace buffer parser for large recordings feat(performance): chunked trace buffer parser for large recordings Sep 16, 2026
@jackfranklin

Copy link
Copy Markdown
Contributor Author

@OrKoN PTAL. Not fully ready yet but keen to get your early opinion on this fix.

@jackfranklin
jackfranklin requested a review from OrKoN September 16, 2026 09:18
@OrKoN

OrKoN commented Sep 16, 2026

Copy link
Copy Markdown
Collaborator

Some AI-advice that seems to make sense:

1. Batching Only by Event Count (eventsPerBatch = 10_000) Can Still Hit V8's Max String Length Limit

  • Location: src/processors/ChunkedTraceParser.ts:293 (if (batchCount >= eventsPerBatch) flushBatch();)
  • Problem:
    • V8's string limit (RangeError: Invalid string length, ~512 MB) is a byte/character length limit, not an event count limit.
    • Chrome traces frequently include events with very large payloads, such as base64-encoded screenshots (disabled-by-default-devtools.screenshot), inline script source texts/source maps (v8.compile), or heap profiler chunks. A batch of 10,000 events containing screenshots or large script sources can easily exceed 256–512 MB.
    • Furthermore, flushBatch() constructs `[${chunkText}]` (line 241), allocating a second copy of the entire batch string in memory and doubling peak string allocation per batch.
    • Additionally, if options.eventsPerBatch is passed as NaN, batchCount >= eventsPerBatch is always false, causing the parser to buffer the entire file into a single flushBatch() call at the end.
  • Recommendation:
    • Enforce a byte-size limit per batch alongside eventsPerBatch (e.g. const MAX_BATCH_BYTES = 32 * 1024 * 1024; and flush when batchCount >= eventsPerBatch || (lastEventEnd - batchStart) >= MAX_BATCH_BYTES).
    • Validate eventsPerBatch (if (!Number.isFinite(eventsPerBatch) || eventsPerBatch <= 0)).

2. undefined Properties in Caller metadata Clobber Extracted File Metadata in Production

  • Location: src/processors/PerformanceTrace.ts:534-536
    const combinedMetadata = fileMetadata
      ? {...fileMetadata, ...metadata}
      : metadata;
  • Problem:
    • In production (src/tools/performance.ts:224-227), parseRawTraceBuffer is called as:
      const result = await parseRawTraceBuffer(traceEventsBuffer, {
        cpuThrottling: page.cpuThrottlingRate,
        networkThrottling: page.networkConditions ?? undefined,
      });
    • When network throttling is not active on page, page.networkConditions is null, so metadata is { cpuThrottling: 1, networkThrottling: undefined }.
    • In JavaScript, { ...fileMetadata, ...metadata } overwrites fileMetadata.networkThrottling with undefined because networkThrottling is an own property on metadata.
    • Similarly, page.cpuThrottlingRate defaults to 1 even when never explicitly configured via emulate, which clobbers any cpuThrottling value stored in fileMetadata.
    • Note: The snapshot diffs in tests/McpResponse.test.js.snapshot and tests/trace-processing/parse.test.js.snapshot changed to 1x / No throttling only because those tests call parseRawTraceBuffer(rawData) with metadata === undefined.
  • Recommendation:
    • Filter out undefined properties from metadata before merging so they do not overwrite defined properties in fileMetadata:
      const combinedMetadata = {
        ...fileMetadata,
        ...(metadata?.cpuThrottling !== undefined ? {cpuThrottling: metadata.cpuThrottling} : {}),
        ...(metadata?.networkThrottling !== undefined ? {networkThrottling: metadata.networkThrottling} : {}),
      };

3. parseEventsArray Silently Ignores Tokens at depth === 0 (Missing Commas, Trailing Commas, Non-Object Items, and Nested Brackets)

  • Location: src/processors/ChunkedTraceParser.ts:251-308
  • Problem:
    Because flushBatch() only slices from batchStart (the opening { of the first event in a batch) to lastEventEnd (the closing } of the last event in a batch), any bytes at depth === 0 before the first {, between batches, or after the last } before ] are never passed to JSON.parse and are ignored by the scanner:
    1. Missing commas at batch boundaries: If eventsPerBatch is 2, [{"name":"e1"},{"name":"e2"} {"name":"e3"},{"name":"e4"}] (missing comma between e2 and e3) parses without error.
    2. Trailing commas: [{"name":"e1"}, ] parses without throwing SyntaxError.
    3. Non-object array items silently dropped: In [null, "string", 123, {"name":"e1"}], the non-object items before {"name":"e1"} are silently skipped and omitted from events.
    4. Premature termination on array elements ([]): parseEventsArray does not track BYTE_OPEN_BRACKET ([). If traceEvents contains an array element (e.g. [ [], {"name":"e1"} ]), the closing ] of [] is encountered at depth === 0 and triggers line 301 (if (byte === BYTE_CLOSE_BRACKET && depth === 0)), prematurely terminating parseEventsArray.

4. skipValue Mismatched Delimiter Bug & Missing Value Handling

  • Location: src/processors/ChunkedTraceParser.ts:155-205
  • Problem:
    1. Single depth counter for {} and []: skipValue increments depth on both { and [, and decrements on both } and ]. If a skipped property precedes traceEvents and contains mismatched delimiters (e.g., {"other": {"a": ]}, "traceEvents": [...]}), depth reaches 0 at ], causing skipValue to return early. The outer object loop then sees the remaining } of "other" and mistakes it for the closing brace of the root JSON object, terminating parsing before "traceEvents" is read.
    2. Empty primitive values: In primitive scanning (lines 190-205), if a property value is missing before a comma ({"other": , "traceEvents": []}), the loop immediately breaks on BYTE_COMMA after advancing 0 bytes, silently accepting invalid JSON.
    3. Out-of-bounds index on trailing backslash: If a skipped compound object/array ends with a trailing backslash \ at buffer[buffer.length - 1], pos += 2 (line 164) advances pos to buffer.length + 1 and returns an index strictly greater than buffer.length.

5. Unescaped Object Keys in parseTraceEventsFromBuffer

  • Location: src/processors/ChunkedTraceParser.ts:390-393
  • Problem:
    const key = decoder.decode(buffer.subarray(keyStart, keyEnd)); decodes the raw bytes between quotes without JSON.parse. If a JSON property key contains escape sequences (e.g. \", \\, or \uXXXX), key will contain the raw unescaped sequence rather than the parsed string value.
  • Recommendation: Parse the key slice using JSON.parse(decoder.decode(buffer.subarray(keyStart - 1, pos))).

@jackfranklin

Copy link
Copy Markdown
Contributor Author

@OrKoN PTanotherL

Comment thread src/processors/ChunkedTraceParser.ts Resolved
Decoding full trace buffers into a single string fails with a V8 RangeError when recordings exceed ~512 MB due to V8's maximum string length limit (2^29 - 24 characters).

This introduces a byte-level scanner that identifies JSON boundaries directly on the Uint8Array using brace-depth and string-escape tracking. Events are sliced and parsed in bounded batches using native JSON.parse, keeping intermediate string allocations small and avoiding V8 argument stack limits. Top-level file metadata is extracted and merged with caller throttling options.
@jackfranklin
jackfranklin marked this pull request as ready for review September 17, 2026 09:13
@jackfranklin
jackfranklin added this pull request to the merge queue Sep 17, 2026
Merged via the queue into main with commit 23b9a48 Sep 17, 2026
30 of 33 checks passed
@jackfranklin
jackfranklin deleted the chunked-trace-parsing branch September 17, 2026 13:39
pull Bot pushed a commit to oogalieboogalie/chrome-devtools-mcp that referenced this pull request Sep 23, 2026
🤖 I have created a release *beep* *boop*
---


##
[1.10.0](ChromeDevTools/chrome-devtools-mcp@chrome-devtools-mcp-v1.9.0...chrome-devtools-mcp-v1.10.0)
(2026-09-23)


### 🎉 Features

* add css formatter class
([ChromeDevTools#2707](ChromeDevTools#2707))
([f0b5fa4](ChromeDevTools@f0b5fa4))
* add get_css_style tool
([ChromeDevTools#2612](ChromeDevTools#2612))
([4454ae0](ChromeDevTools@4454ae0))
* **performance:** chunked trace buffer parser for large recordings
([ChromeDevTools#2721](ChromeDevTools#2721))
([23b9a48](ChromeDevTools@23b9a48))
* set default pageSize and pageIdx for get_css_styles tool
([ChromeDevTools#2799](ChromeDevTools#2799))
([dc9d14d](ChromeDevTools@dc9d14d))
* support config file
([ChromeDevTools#2661](ChromeDevTools#2661))
([314a5fa](ChromeDevTools@314a5fa))
* **telemetry:** persist date of the last tool call.
([ChromeDevTools#2705](ChromeDevTools#2705))
([c54a493](ChromeDevTools@c54a493))
* **telemetry:** recording a sanitized version of the client name
([ChromeDevTools#2757](ChromeDevTools#2757))
([55fbc57](ChromeDevTools@55fbc57))
* **telemetry:** report hermes client usage.
([ChromeDevTools#2703](ChromeDevTools#2703))
([fb47e6c](ChromeDevTools@fb47e6c))
* update css formatter class to add AtRule, PositionTryRule,
PropertyRule, FunctionRule
([ChromeDevTools#2717](ChromeDevTools#2717))
([d4a0620](ChromeDevTools@d4a0620))
* update css formatter class to add inherited rules
([ChromeDevTools#2715](ChromeDevTools#2715))
([3d7e7bb](ChromeDevTools@3d7e7bb))
* update css formatter class to add matched rules
([ChromeDevTools#2713](ChromeDevTools#2713))
([8c8616f](ChromeDevTools@8c8616f))
* update css formatter class to add pseudo element
([ChromeDevTools#2716](ChromeDevTools#2716))
([df1469a](ChromeDevTools@df1469a))
* update css formatter to add keyframes rules
([ChromeDevTools#2718](ChromeDevTools#2718))
([cdc365c](ChromeDevTools@cdc365c))


### 🛠️ Fixes

* bound ConsoleCollector retention per navigation
([ChromeDevTools#2773](ChromeDevTools#2773))
([e98a3ca](ChromeDevTools@e98a3ca))
* **cli:** forward explicit false options on start
([ChromeDevTools#2702](ChromeDevTools#2702))
([d9a8cb6](ChromeDevTools@d9a8cb6))
* **config:** preserve raw values for config coercion
([ChromeDevTools#2747](ChromeDevTools#2747))
([906c83b](ChromeDevTools@906c83b))
* don't log Puppeteer logs to file unless requested
([ChromeDevTools#2743](ChromeDevTools#2743))
([4fbfbc4](ChromeDevTools@4fbfbc4))
* explain launch failures caused by running as root
([ChromeDevTools#2634](ChromeDevTools#2634))
([9d29223](ChromeDevTools@9d29223))
* handle JavaScript dialogs opened during input tool actions
([ChromeDevTools#2794](ChromeDevTools#2794))
([266112b](ChromeDevTools@266112b))
* **performance:** prevent memory leak by scoping trace engine model per
parse
([ChromeDevTools#2720](ChromeDevTools#2720))
([d05cbc0](ChromeDevTools@d05cbc0))
* preserve console history across same-document navigations
([ChromeDevTools#2676](ChromeDevTools#2676))
([aa25562](ChromeDevTools@aa25562))
* preserve underlying error message in input tool actions
([ChromeDevTools#2792](ChromeDevTools#2792))
([6e47dbb](ChromeDevTools@6e47dbb))
* set emulatedUserAgent and use finalDisplayedUrl in lighthouse_audit
([ChromeDevTools#2795](ChromeDevTools#2795))
([941f82a](ChromeDevTools@941f82a))
* timout in WaitForHelper.ts
([ChromeDevTools#2772](ChromeDevTools#2772))
([dc1d055](ChromeDevTools@dc1d055))


### 📄 Documentation

* add FLUJO client configuration
([ChromeDevTools#2690](ChromeDevTools#2690))
([65a679e](ChromeDevTools@65a679e))
* fix categories not being configured correclty
([ChromeDevTools#2807](ChromeDevTools#2807))
([2250cdc](ChromeDevTools@2250cdc))
* fix defaults for non-boolean values
([ChromeDevTools#2744](ChromeDevTools#2744))
([342d243](ChromeDevTools@342d243))
* update page routing option name
([ChromeDevTools#2748](ChromeDevTools#2748))
([8939965](ChromeDevTools@8939965))
* update SKILL for chrome-devtools to use get_css_styles tool
([ChromeDevTools#2760](ChromeDevTools#2760))
([421011e](ChromeDevTools@421011e))


### 🏗️ Refactor

* disable tools instead of not registering them
([ChromeDevTools#2636](ChromeDevTools#2636))
([b455469](ChromeDevTools@b455469))
* extract browser in a BrowserManager class
([ChromeDevTools#2787](ChromeDevTools#2787))
([3228f44](ChromeDevTools@3228f44))
* migrate the MCP SDK to v2
([ChromeDevTools#2408](ChromeDevTools#2408))
([da3c406](ChromeDevTools@da3c406))
* move comments formatting to CommentFormatter class
([ChromeDevTools#2719](ChromeDevTools#2719))
([e3cded0](ChromeDevTools@e3cded0))
* prepare for SDK v2
([ChromeDevTools#2771](ChromeDevTools#2771))
([61780c7](ChromeDevTools@61780c7))
* simplify our gen scritps
([ChromeDevTools#2793](ChromeDevTools#2793))
([5068584](ChromeDevTools@5068584))
* unify call type and ensure typesafety
([ChromeDevTools#2659](ChromeDevTools#2659))
([882f93e](ChromeDevTools@882f93e))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants