Skip to content

[worker] startCpuProfile can return invalid JSON for RegExp frames #67097

Open

Description

@papercupai

Version

Node.js v25.9.0

Reproduction

import { Worker } from "node:worker_threads";

const source = [
  'const re = new RegExp("^(\\\\d{6})");',
  "function work() {",
  "  let matches = 0;",
  "  for (let i = 0; i < 30000; i++) if (re.test(String(i))) matches++;",
  "  return matches;",
  "}",
  "setInterval(work, 0);",
].join("\n");

const worker = new Worker(source, { eval: true });
await new Promise((resolve, reject) => {
  worker.once("online", resolve);
  worker.once("error", reject);
});
try {
  const handle = await worker.startCpuProfile();
  await new Promise((resolve) => setTimeout(resolve, 450));
  const profileJson = await handle.stop();
  JSON.parse(profileJson);
} finally {
  await worker.terminate();
}

Actual result

The stop call returns a string, and JSON.parse throws SyntaxError: Bad escaped character in JSON. The malformed callFrame.functionName is RegExp: ^(\d{6}); its backslash is not escaped in the JSON string.

Expected result

The returned profile string should be valid JSON, or the API should return a structured profile object.

Control

For the same workload, an Inspector Profiler.stop response was an object and successfully round-tripped through JSON.stringify followed by JSON.parse.

Activity

  1. shahinsamiur commented on Oct 29, 2026

    @shahinsamiur

    Hello, I would like to work on this problem. I will look into the reason why worker.startCpuProfile() can produce invalid JSON because of backslashes in the RegExp frames, and try to work on a fix for this issue along with a regression test to make sure that the output is valid JSON.

  2. shahinsamiur commented on Oct 29, 2026

    @shahinsamiur

    The problem seems to be the serialization of CPU profile where some strings are written to JSON without escaping the special characters. In case the RegExp frame name contains a backslash, the JSON created may be invalid and cause an error SyntaxError in JSON.parse().

    I have raised PR #67103 for the same where JSON string escaping will be added to OutputStreamWriter for function names, script URLs and deoptimization reasons along with a regression test for worker CPU profiles with RegExp frames.

    The objective here is to make sure that worker.startCpuProfile() returns valid JSON.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions