selenium icon indicating copy to clipboard operation
selenium copied to clipboard

[🐛 Bug]: [java] [bidi] RemoteValue decoding re-serializes every nested subtree, so a large console argument costs gigabytes and seconds per `log.entryAdded` and can OOM the client

Open pwspot opened this issue 2 months ago • 8 comments

What happened?

Context. We moved console/log capture from CDP (Runtime.consoleAPICalled, Log.entryAdded) to WebDriver BiDi (LogInspector) following #13990, which deprecates CDP in favour of BiDi and asks users to report what is not yet possible over BiDi. Over CDP a logged object arrives as a small preview with an objectId; over BiDi the whole object graph is serialized into the log.entryAdded event, and decoding it is where this issue lives. The switch is what exposed it, and one part of the report — the lack of any client-side bound on log-event serialization — is the kind of gap #13990 asks about.

RemoteValue.fromJson reads the value field as a raw Object tree and hands it to deserializeValue, which converts every child of a MAP/OBJECT back into a RemoteValue by serializing the child to JSON text and parsing it again:

// RemoteValue.deserializeValue, MAP / OBJECT case
for (List<Object> list : result) {
  Object key = list.get(0);
  if (!(key instanceof String)) {
    try (StringReader reader = new StringReader(JSON.toJson(key));
        JsonInput keyInput = JSON.newInput(reader)) {
      key = keyInput.read(RemoteValue.class);
    }
  }
  try (StringReader reader = new StringReader(JSON.toJson(list.get(1)));
      JsonInput valueInput = JSON.newInput(reader)) {
    RemoteValue value1 = valueInput.read(RemoteValue.class);   // -> fromJson -> deserializeValue, recursively
    map.put(key, value1);
  }
}

JSON.toJson(list.get(1)) serializes the child's entire remaining subtree, and the recursive read(RemoteValue.class) does the same one level down, so every node is re-serialized once per level above it. The decode cost is the number of nodes multiplied by a per-node cost that grows with depth.

Measured on Selenium 4.48.0 (Temurin 25.0.3, macOS arm64) by decoding real log.entryAdded payloads captured from chromedriver 152 through Log.entryAdded().getMapper(). "Allocated" is total temporary allocation for one decode (ThreadMXBean.getThreadAllocatedBytes), not memory held:

console.log argument wire size nodes allocated per decode per node time
Array.from({length: 100000}, (_, i) => i) 3.1 MB 100k 3.45 GB ~35 KB 5.2 s
array of 10,000 records with 2 fields 1.1 MB 30k 4.68 GB 152 KB —
array of 10,000 records with 8 fields 3.2 MB 90k 10.2 GB ~113 KB 13 s
object tree, depth 8, 3 keys per level 349 KB 9,841 7.16 GB 711 KB ~10 s
single chain, depth 14, one key per level 0.5 KB 15 15 MB 976 KB —

The depth dependence in isolation (a chain of nested objects, one key each):

depth JSON chars allocated
2 100 110 KB
4 168 494 KB
6 236 1.3 MB
8 304 2.8 MB
10 372 5.0 MB

3.7x more input, 45x more work.

This becomes an OOM because Connection.Listener.onText hands each incoming event to an unbounded cached thread pool (Executors.newCachedThreadPool, threads named BiDi Connection) with no backpressure. A page that logs a large object on every state change emits an entry every few hundred milliseconds; each decode takes seconds and holds ~300 MB of intermediate ArrayList/String/LinkedHashMap state live while it runs, so decodes pile up until the heap is exhausted. With -Xmx1536m the reproduction below dies in about 40 s with ~30 decodes in flight.

There is no client-side way to bound this for log events: SerializationOptions.maxObjectDepth is only wired into script.evaluate, script.callFunction and browsingContext.locateNodes, and session.subscribe carries no serialization options in the spec. The only workaround we found is to register our own Event for log.entryAdded whose mapper prunes the raw Map (capping entries per level and depth) before delegating to Log.entryAdded().getMapper().

The same code is present on trunk as of 2026-09-23: RemoteValue.deserializeValue still round-trips each child through StringReader(JSON.toJson(...)), so there is no newer release that avoids this.

How can we reproduce the issue?

ChromeOptions options = new ChromeOptions();
options.setBinary("/path/to/chrome-headless-shell");   // Chrome for Testing headless shell 152, as tested
options.enableBiDi();
ChromeDriver driver = new ChromeDriver(options);

new LogInspector(driver).onConsoleEntry(entry -> System.out.println("entry received"));

driver.get("about:blank");
((JavascriptExecutor) driver).executeScript(
    "const a = Array.from({ length: 100000 }, (_, i) => i);"
        + "let n = 0;"
        + "const t = setInterval(() => { console.log(a); if (++n >= 40) clearInterval(t); }, 250);");

Thread.sleep(120_000);
driver.quit();

Run with -Xmx1536m. Only the headless shell was run; full Chrome with --headless=new was not tried. It should behave the same, since the cost is in the Java client's decode rather than in the browser, but that is an inference. Expected: 40 lines of entry received within a few seconds. Actual: the heap fills within ~20 s, OutOfMemoryError: Java heap space is thrown on BiDi Connection threads from ~40 s, and few or none of the entries reach the listener. With a large heap instead, each entry takes ~5 s to decode and allocates ~3.4 GB.

Single-decode micro-benchmark (no browser): build the wire form of a nested object as a String and time new Json().newInput(new StringReader(json)).read(RemoteValue.class) — see the depth table above.

Relevant log output

Stack of a BiDi Connection thread at the time of the OOM (from a heap dump):

at org.openqa.selenium.json.JsonOutput.write(...)
at org.openqa.selenium.json.Json.toJson(Json.java:128)
at org.openqa.selenium.bidi.script.RemoteValue.deserializeValue(RemoteValue.java:216)
at org.openqa.selenium.bidi.script.RemoteValue.fromJson(RemoteValue.java:151)
at org.openqa.selenium.json.StaticInitializerCoercer.lambda$apply$0(StaticInitializerCoercer.java:59)
at org.openqa.selenium.json.JsonTypeCoercer.coerce(JsonTypeCoercer.java:154)
at org.openqa.selenium.json.JsonInput.read(JsonInput.java:517)
at org.openqa.selenium.bidi.script.RemoteValue.deserializeValue(RemoteValue.java:218)
at org.openqa.selenium.bidi.script.RemoteValue.fromJson(RemoteValue.java:151)
...
at org.openqa.selenium.bidi.log.ConsoleLogEntry.fromJson(ConsoleLogEntry.java:98)
at org.openqa.selenium.bidi.log.Log.lambda$entryAdded$0(Log.java:51)
at org.openqa.selenium.bidi.Connection.lambda$handleEventResponse$2(Connection.java:378)
at org.openqa.selenium.bidi.Connection.handleEventResponse(Connection.java:373)
at org.openqa.selenium.bidi.Connection.handle(Connection.java:312)
at org.openqa.selenium.bidi.Connection$Listener.lambda$onText$0(Connection.java:281)
Exception in thread "BiDi Connection" java.lang.OutOfMemoryError: Java heap space

Suggested direction

Decode children directly from the already-parsed Object tree instead of round-tripping each one through JSON text — e.g. a RemoteValue.fromObject(Map<String, Object>) used by deserializeValue for MAP/OBJECT/ARRAY/SET children — so each node is visited once. Independently of that, a way to bound decoded depth/breadth for log events on the client (an option on LogInspector, or on the Event) would let users protect themselves, since the protocol offers nothing for log.entryAdded.

Operating System

macOS 26.6 (arm64); also reproduced on Linux (ECS)

Selenium version

Java 4.48.0; the same code is present on trunk as of 2026-09-23

What are the browser(s) and version(s) where you see this issue?

Chrome for Testing headless shell 152.0.7977.64 (via options.setBinary); full Chrome not tested

What are the browser driver(s) and version(s) where you see this issue?

ChromeDriver 152.0.7977.64

Are you using Selenium Grid?

No

Are you willing to submit a PR?

Not committing to one at the moment. The change looks contained — decode container children (ARRAY / SET / NODE_LIST / MAP / OBJECT) from the already-parsed Map/List tree via a fromMap path instead of round-tripping each through JSON text, leaving the leaf types (RegExpValue, WindowProxyProperties, NodeProperties) as they are, plus a unit test on nested payloads — and if that shape is right and the hand-written RemoteValue is where you would want it (rather than the generated layer from #17777), we may pick it up later.

pwspot avatar Sep 25 '26 12:09 pwspot

.NET/C# is safe:

    [Test]
    public async Task CanReceiveConsoleLogWithLargeNestedObjectArgument()
    {
        await using var subscription = await context.Log.EntryAdded.SubscribeAsync(e =>
        {
            Assert.That(e, Is.TypeOf<ConsoleEntryAddedEventArgs>());
            Assert.That(e.Text, Is.Not.Null);
        });

        await context.Script.EvaluateAsync(
            "console.log(Array.from({ length: 10000 }, (_, index) => ({ index, nested: { value: index } })));",
            awaitPromise: true);
    }
19:34:15.214 TRACE Broker: BiDi SND --> {"id":2,"method":"session.subscribe","params":{"events":["log.entryAdded"],"contexts":["2505d8ad-9c22-43fb-81df-885407d10ec4"]}}

19:34:15.219 TRACE Broker: BiDi RCV <-- {"type":"success","id":2,"result":{"subscription":"9041c297-6625-4395-b9cc-10da90e52153"}}

19:34:15.238 TRACE Broker: BiDi SND --> {"id":3,"method":"script.evaluate","params":{"expression":"console.log(Array.from({ length: 10000 }, (_, index) =\u003E ({ index, nested: { value: index } })));","target":{"context":"2505d8ad-9c22-43fb-81df-885407d10ec4"},"awaitPromise":true}}

19:34:15.323 TRACE Broker: BiDi RCV <-- {"type":"event","method":"log.entryAdded","params":{"type":"console","method":"log","source":{"realm":"f55ba859-0404-41b3-b799-6e0b930d829f","context":"2505d8ad-9c22-43fb-81df-885407d10ec4","userContext":"default"},"args":[{"type":"array","value":[{"type":"object","value":[["index",{"type":"number","value":0}],["nested",{"type":"object","value":[["value",{"type":"number","value":0}]]}]]},{"type":"object","value":[["index",{"type":"number","value":1}],["nested",{"type...[truncated 1487210 chars]...alue":9997}]]}]]},{"type":"object","value":[["index",{"type":"number","value":9998}],["nested",{"type":"object","value":[["value",{"type":"number","value":9998}]]}]]},{"type":"object","value":[["index",{"type":"number","value":9999}],["nested",{"type":"object","value":[["value",{"type":"number","value":9999}]]}]]}]}],"level":"info","text":"Array(10000)","timestamp":1790354055240,"stackTrace":{"callFrames":[{"columnNumber":8,"functionName":"","lineNumber":0,"url":"about:blank"}]}}}

19:34:15.324 TRACE Broker: BiDi RCV <-- {"type":"success","id":3,"result":{"realm":"f55ba859-0404-41b3-b799-6e0b930d829f","type":"success","result":{"type":"undefined"}}}

19:34:15.462 TRACE Broker: BiDi SND --> {"id":4,"method":"session.unsubscribe","params":{"subscriptions":["9041c297-6625-4395-b9cc-10da90e52153"]}}

250ms for roundtrip: subscribe -> evaluate -> parse event -> unsubscribe

nvborisenko avatar Sep 25 '26 16:09 nvborisenko

Hi @pwspot @titusfortner, I'd like to work on this if nobody else has picked it up. I've confirmed the round-trip on trunk. It also affects the ARRAY/SET/NODE_LIST branch, not only MAP/OBJECT. My plan is to add a fromMap path that builds child RemoteValues directly from the already-parsed tree, so each node is decoded once. The leaf types (RegExpValue, WindowProxyProperties, NodeProperties) stay as they are. I'll add unit tests covering nested objects, arrays of records, and maps with non-string keys. I'd keep the thread-pool backpressure and log-event depth bounding out of this PR and leave them for a separate discussion. @titusfortner, is a fix in the hand-written RemoteValue still wanted for 4.x given #17777, or would you rather this wait for the generated layer?

yashp676 avatar Sep 26 '26 17:09 yashp676

Beyond implementing a direct fromMap path, have you considered whether we can leverage a shared JsonInput instance or a streaming parser to avoid the overhead of repeated serialization entirely? Since the tree is already parsed into memory, converting the raw Map nodes directly into RemoteValue instances should bypass the StringReader bottleneck entirely. If we shift to a factory pattern for the deserializer, we could pass the existing JsonNode tree down the recursion stack rather than serializing to a string at every depth level.

cherryrodney26 avatar Sep 26 '26 23:09 cherryrodney26

Thanks @cherryrodney26, that's the direction I'm taking. fromMap passes the already-parsed Map/List tree down the recursion and builds each child RemoteValue directly, so there's no StringReader round-trip at any level and each node is visited once.

I'd avoid a fully streaming decode inside fromJson: the spec doesn't guarantee type comes before value, so we can't know how to decode value until type has been read. Buffering it as a parsed tree and then decoding from that tree keeps it order-independent, and the parse is already linear. (For reference, Selenium's JSON layer parses into plain Map/List objects rather than a JsonNode tree, so fromMap works on those directly.)

I'll hold off opening the PR until @titusfortner confirms whether a fix in the hand-written RemoteValue is wanted for 4.x given #17777.

yashp676 avatar Sep 27 '26 07:09 yashp676

@yashp676 go ahead. The generated layer in #17777 has the same round trip issue and isn't a substitute.

Considerations:

  • NodeProperties isn't a leaf. It holds children and shadowRoot, both remote values, so it re-enters the round trip once per level and needs the parsed-tree path too. RegExpValue and WindowProxyProperties are genuine leaves. Leaving it to the shared coercion won't help either — ConstructorCoercer.coerceValue does the same round trip.
  • Don't name the factory fromJson. StaticInitializerCoercer binds a class only when it has exactly one static fromJson, so an overload silently drops RemoteValue off that coercer. fromMap is fine.
  • There's a hard depth ceiling, so this isn't only about speed: three JSON levels per RemoteValue against JsonOutput.MAX_DEPTH of 100 means a chain past ~30 levels throws Reached the maximum depth of 100 while writing JSON. Depth 40 fails on trunk, depth 20 passes — worth a regression test.

Agreed on keeping the thread-pool backpressure and log-event depth bounding out; the unbounded pool survives this fix and wants its own discussion.

titusfortner avatar Sep 29 '26 20:09 titusfortner

Hi @titusfortner - #18095 this is ready for review. It covers the points you raised on #18076: NodeProperties now decodes children and shadowRoot through the parsed-tree path (NodeProperties.fromMap → RemoteValue.fromMap), so it no longer goes through ConstructorCoercer's round trip. RegExpValue and WindowProxyProperties are left as they are. Naming: the new factory is fromMap, so fromJson(JsonInput) is still the only static fromJson and StaticInitializerCoercer keeps binding RemoteValue. Depth ceiling: I added regression tests for an object chain at depths 20/40/200 and a node tree 40 levels deep. With RemoteValue/NodeProperties reverted to trunk, both fail with Reached the maximum depth of 100 while writing JSON. With the fix, all 9 tests pass.

The thread-pool backpressure and log-event depth bounding are left out, as agreed.

yashp676 avatar Sep 30 '26 08:09 yashp676

Thanks @yashp676 for picking this up so quickly!

pwspot avatar Sep 30 '26 09:09 pwspot

This issue has been automatically locked since there has not been any recent activity since it was closed. Please open a new issue for related bugs.

github-actions[bot] avatar Nov 07 '26 10:11 github-actions[bot]