← Back to Pull requests

inspector: avoid more JS calls from V8 interrupts #66740

Open
christianaurichzm opened this pull request with 898 lines diff across 22 files
View on GitHub
christianaurichzm christianaurichzm commented on Oct 14, 2026 19:32 UTC
Author

This lands the Node.js side of #65397, which was reverted in #65907, without enabling the V8 check.

The first commit is @deepak1556's inspector: defer JS execution from V8 interrupts from #65397, unchanged apart from a conflict with #65877 and a can_call_into_js() check in FlushPendingMessages(). As before, messages for an in-process inspector.Session that arrive while Node.js handles another client's message in an interrupt are delivered at the next microtask checkpoint instead of synchronously.

The second commit is @deepak1556's patch from the discussion below. DOMStorage.getDOMStorageItems now reads the stores without calling into JavaScript: it no longer goes through the globalThis.localStorage and globalThis.sessionStorage getters, and a store that cannot be opened is reported without creating a JavaScript error. The third commit adds the test-inspector-dom-storage-interrupt-* tests, which read both stores from an interrupt and fail if any JavaScript runs there. They count calls to the storage getters and to an Error.prototype.code setter, so they don't depend on the V8 check. Enabling the check needs v8/v8@35bd1582fe0a, which deps/v8 has since the V8 15.8 update, so that will be a separate PR.

The fourth commit makes a relative --localstorage-file absolute once, when options are parsed, and documents it. It used to be resolved against the cwd at each use, so a process.chdir() could make localStorage, its storage key and the inspector's direct read point at different files. A chdir before localStorage is first used no longer moves the file.

Each commit stands on its own, so this can land with commit-queue-rebase instead of being squashed.

Refs: https://github.com/nodejs/node/pull/65397
Refs: https://github.com/nodejs/node/pull/65907
Refs: https://github.com/nodejs/node/pull/66710

Diff: 898 lines (+647 / -251) across 22 files Reviewer: joyeecheung Review duration: 70364m
All Vouch review confidence checks passed
Residual risk 0.09 = Change Risk (0.79) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.79 · 898 lines diff across 22 files
0.79
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.89 · 5 substantive comment(s)
0.89
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
88%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Mass File Touch mass_file_touch
0.080
Real PR Conversation Timeline
30 items
nodejs-github-bot nodejs-github-bot commented on Oct 14, 2026 19:32 UTC
Bot

Review requested:

  • @nodejs/gyp

  • @nodejs/inspector

  • @nodejs/security-wg

  • @nodejs/v8-update
  • christianaurichzm christianaurichzm commented on Oct 14, 2026 19:37 UTC
    Author

    @legendecas @joyeecheung since you reviewed #65397, could you take a look at the re-land when you get a chance? It also needs a node-test-commit-v8-linux run, since that is what caught the futex failure last time. Thanks!

    codecov[bot] codecov[bot] commented on Oct 14, 2026 22:39 UTC
    Bot

    Codecov Report


    :x: Patch coverage is 69.44444% with 66 lines in your changes missing coverage. Please review.
    :white_check_mark: Project coverage is 90.60%. Comparing base (f2d9356) to head (e466bae).
    :warning: Report is 1 commits behind head on main.

    | Files with missing lines | Patch % | Lines |
    |---|---|---|
    | src/inspector\_agent.cc | 52.94% | 24 Missing and 8 partials :warning: |
    | src/node\_webstorage.cc | 70.66% | 14 Missing and 8 partials :warning: |
    | src/inspector\_js\_api.cc | 75.00% | 3 Missing and 3 partials :warning: |
    | src/inspector/dom\_storage\_agent.cc | 83.87% | 2 Missing and 3 partials :warning: |
    | src/node\_options.cc | 83.33% | 0 Missing and 1 partial :warning: |

    <details><summary>Additional details and impacted files</summary>

    @@            Coverage Diff             @@
    ##             main   #66740      +/-   ##
    ==========================================
    - Coverage   92.96%   90.60%   -2.36%     
    ==========================================
      Files         432      802     +370     
      Lines      201044   286752   +85708     
      Branches    30702    55380   +24678     
    ==========================================
    + Hits       186900   259812   +72912     
    - Misses      13816    17044    +3228     
    - Partials      328     9896    +9568     
    

    | Files with missing lines | Coverage Δ | |
    |---|---|---|
    | lib/internal/inspector/webstorage.js | 100.00% <100.00%> (ø) | |
    | src/inspector\_agent.h | 100.00% <100.00%> (ø) | |
    | src/node\_webstorage.h | 87.50% <100.00%> (ø) | |
    | src/path.cc | 65.04% <100.00%> (ø) | |
    | src/path.h | 100.00% <ø> (ø) | |
    | src/node\_options.cc | 88.21% <83.33%> (ø) | |
    | src/inspector/dom\_storage\_agent.cc | 84.61% <83.87%> (ø) | |
    | src/inspector\_js\_api.cc | 84.26% <75.00%> (ø) | |
    | src/node\_webstorage.cc | 77.61% <70.66%> (ø) | |
    | src/inspector\_agent.cc | 84.30% <52.94%> (ø) | |

    ... and 497 files with indirect coverage changes
    </details>
    <details><summary> :rocket: New features to boost your workflow: </summary>

  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

  • :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

  • </details>

    deepak1556 deepak1556 commented on Oct 15, 2026 04:30 UTC
    Contributor

    Oh another case found,

    1. DOMStorageAgent::getWebStorage() (#62145) looks up globalThis.localStorage / globalThis.sessionStorage via lazy JS accessors.
    2. When Storage::GetAll() opens a malformed database file (#65879), Storage::Open() creates a JS Error only for DOMStorageAgent::getDOMStorageItems() to catch it with v8::TryCatch and extract the message string.

    Rather than deferring DOMStorage.getDOMStorageItems (which would prevent inspecting storage while paused in NodeInspectorClient::runMessageLoopOnPause), could try something like
    0001-inspector-avoid-JS-execution-in-DOMStorage.getDOMSto.patch that keeps everything in C++

    joyeecheung joyeecheung commented on Oct 16, 2026 13:31 UTC
    Contributor

    Note that we are drafting a new policy for updating V8 in Node.js - for V8 commit backports that are justified to be fast tracked and do not have to wait for the regular V8 upgrade, it's better to target release staging branches, instead of main: https://github.com/nodejs/node/pull/66710

    christianaurichzm christianaurichzm commented on Oct 20, 2026 03:41 UTC
    Author

    Thanks @joyeecheung. I dropped the backport and the commit that enables the check. I'll enable it in a separate PR once a V8 update brings in v8/v8@35bd1582fe0a.

    @deepak1556, you're right about the second case: with a code setter on Error.prototype, reading a malformed file from an interrupt aborts, since ERR_INVALID_STATE sets code with Object::Set.

    I tried your patch with the check enabled and both cases work. One thing I hit: Storage::New tells the stores apart by location, but --localstorage-file=:memory: is also valid, so if sessionStorage is created first, getDOMStorageItems for sessionStorage returns the localStorage items, even outside an interrupt. Using the third constructor argument that InspectorLocalStorage and InspectorSessionStorage already pass fixes it:

    BindingData* binding_data = realm->GetBindingData<BindingData>();
    if (binding_data != nullptr && args[2]->IsBoolean()) {
      auto& slot = args[2]->IsTrue() ? binding_data->local_storage
                                     : binding_data->session_storage;
      slot = BaseObjectWeakPtr<Storage>(storage);
    }
    

    If you're OK with that change, I'll add your patch here with you as the author, plus regression tests.

    deepak1556 deepak1556 commented on Oct 20, 2026 09:42 UTC
    Contributor

    Thats a better check, thanks for catching it.

    If you're OK with that change, I'll add your patch here with you as the author, plus regression tests.

    SGTM

    christianaurichzm christianaurichzm commented on Oct 20, 2026 16:05 UTC
    Author

    Thanks @deepak1556, I added it as the second commit with the args[2] change, and the test is in the third one. I also made the untouched-store path skip ToNamespacedPath() for :memory:, like Storage::New does, since on Windows it would resolve :memory: against the cwd and open it as a file.

    One thing: your patch didn't have a Signed-off-by, and the guidelines ask for one from each author, including the commit author. Could you reply with yours so I can amend it in?

    deepak1556 deepak1556 commented on Oct 21, 2026 10:34 UTC
    Contributor

    Signed-off-by: deepak1556 <hop2deep@gmail.com>, thanks!

    christianaurichzm christianaurichzm commented on Oct 21, 2026 13:58 UTC
    Author

    Thanks, added.

    christianaurichzm christianaurichzm commented on Oct 21, 2026 13:59 UTC
    Author

    @joyeecheung, could you add request-ci when you get a chance? Thanks!

    joyeecheung joyeecheung commented on code on Nov 05, 2026 16:33 UTC
    Code Review
    src/inspector/dom_storage_agent.cc:1
    @@ -318,26 +318,60 @@ void DOMStorageAgent::registerStorage(Local<Context> context,
     }
     
     std::optional<node::webstorage::Storage*> DOMStorageAgent::getWebStorage(
    -    bool is_local_storage) {
    +    bool is_local_storage, bool* is_uninitialized) {
    +  *is_uninitialized = false;
    +  if (!env_->options()->webstorage) {
    +    return std::nullopt;
    +  }
    +  if (is_local_storage && env_->options()->localstorage_file.empty()) {
    +    return std::nullopt;
    +  }
    +  if (auto* binding = env_->principal_realm()
    +                          ->GetBindingData<node::webstorage::BindingData>()) {
    +    const auto& storage_ptr =
    +        is_local_storage ? binding->local_storage : binding->session_storage;
    +    if (storage_ptr) {
    +      return storage_ptr.get();
    +    }
    +  }
    +  if (env_->no_browser_globals()) {
    +    return std::nullopt;
    +  }
       v8::Isolate* isolate = env_->isolate();
       v8::HandleScope handle_scope(isolate);
    -  v8::Local<v8::Object> global = env_->context()->Global();
    +  v8::Local<v8::Context> context = env_->context();

    When would we need this fallback? If we are adding the binding data it seems better to just stick to that and if that's not available because the initialization is not yet done, just ignore it?

    christianaurichzm christianaurichzm commented on code on Nov 05, 2026 18:28 UTC
    Code Review
    src/inspector/dom_storage_agent.cc:1
    @@ -318,26 +318,60 @@ void DOMStorageAgent::registerStorage(Local<Context> context,
     }
     
     std::optional<node::webstorage::Storage*> DOMStorageAgent::getWebStorage(
    -    bool is_local_storage) {
    +    bool is_local_storage, bool* is_uninitialized) {
    +  *is_uninitialized = false;
    +  if (!env_->options()->webstorage) {
    +    return std::nullopt;
    +  }
    +  if (is_local_storage && env_->options()->localstorage_file.empty()) {
    +    return std::nullopt;
    +  }
    +  if (auto* binding = env_->principal_realm()
    +                          ->GetBindingData<node::webstorage::BindingData>()) {
    +    const auto& storage_ptr =
    +        is_local_storage ? binding->local_storage : binding->session_storage;
    +    if (storage_ptr) {
    +      return storage_ptr.get();
    +    }
    +  }
    +  if (env_->no_browser_globals()) {
    +    return std::nullopt;
    +  }
       v8::Isolate* isolate = env_->isolate();
       v8::HandleScope handle_scope(isolate);
    -  v8::Local<v8::Object> global = env_->context()->Global();
    +  v8::Local<v8::Context> context = env_->context();

    Good point, removed it. An empty slot now takes the same path as during an interrupt, which still reads localStorage from the file so items from an earlier run show up. Thanks!

    christianaurichzm christianaurichzm commented on Nov 12, 2026 17:51 UTC
    Author

    @joyeecheung @legendecas, could you take a look when you get a chance? Thanks!

    joyeecheung joyeecheung commented on code on Nov 13, 2026 15:30 UTC
    Code Review
    src/inspector_js_api.cc:1
    @@ -62,21 +62,38 @@ struct MainThreadConnection {
     template <typename ConnectionType>
     class JSBindingsConnection : public BaseObject {
      public:
    +  struct PendingMicrotask {
    +    explicit PendingMicrotask(JSBindingsConnection* connection)
    +        : env(connection->env()), connection(connection) {
    +      env->AddCleanupHook(Delete, this);
    +    }
    +
    +    static void Delete(void* data) {
    +      delete static_cast<PendingMicrotask*>(data);
    +    }
    +
    +    static void Run(void* data) {
    +      std::unique_ptr<PendingMicrotask> pending(
    +          static_cast<PendingMicrotask*>(data));
    +      pending->env->RemoveCleanupHook(Delete, pending.get());
    +      pending->connection->FlushPendingMessages();

    In FlushPendingMessages() I think it should guard if (pending_messages_.empty()) return; more now since this comes from a microtask, not a native immediate now, i.e. it should be if (pending_messages_.empty() || !env()->can_call_into_js()) return;

    joyeecheung joyeecheung commented on code on Nov 13, 2026 15:33 UTC
    Code Review
    src/inspector/dom_storage_agent.cc:1
    @@ -100,38 +103,35 @@ protocol::DispatchResponse DOMStorageAgent::getDOMStorageItems(
           is_local_storage ? &local_storage_map_ : &session_storage_map_;
       std::optional<StorageMap> storage_map_fallback;
       if (storage_map->empty()) {
    -    auto web_storage_obj = getWebStorage(is_local_storage);
    +    bool is_uninitialized = false;
    +    auto web_storage_obj = getWebStorage(is_local_storage, &is_uninitialized);
         // Each way of failing below says something different about the store, so
         // each reports a different reason. A frontend that cannot read a store
         // otherwise has no way to tell a missing one from a corrupt one.
    -    if (!web_storage_obj) {
    +    if (!web_storage_obj && !is_uninitialized) {
           return protocol::DispatchResponse::ServerError(
               "Could not read DOM storage items: storage is unavailable");
         }
    -    // A message from a remote frontend is dispatched without a HandleScope
    -    // on the stack, and opening the backing file can throw, so give the
    -    // exception a scope to be allocated in and somewhere to land.
    -    v8::HandleScope handle_scope(env_->isolate());
    -    v8::TryCatch try_catch(env_->isolate());
    -    storage_map_fallback = web_storage_obj.value()->GetAll();
    -    if (try_catch.HasCaught()) {
    -      // Pass the reason along; "the file was written by a newer Node.js" and
    -      // "the file is locked" are not the same problem to the user. Read it
    -      // off the Message, which was built when the exception was thrown.
    -      // Converting the exception itself would call a user-patchable
    -      // Error.prototype.toString, and there is no JavaScript frame here to
    -      // run it from.
    -      Local<v8::Message> message = try_catch.Message();
    -      if (!message.IsEmpty()) {
    -        Utf8Value reason(env_->isolate(), message->Get());
    -        return protocol::DispatchResponse::ServerError(
    -            std::string("Could not read DOM storage items: ") + reason.out());
    +    std::string open_error;
    +    if (web_storage_obj) {
    +      storage_map_fallback = web_storage_obj.value()->GetAll(&open_error);
    +    } else if (is_local_storage) {
    +      std::string location = env_->options()->localstorage_file;

    This is now resolved multiple times in different locations, if any chdir happens in between this can introduce inconsistencies. I think it would be better to resolve it once (maybe during options parsing time, or when the Environment is constructed) and store it in the Environment, the JS side should also read the resolved value instead of resolving it independently in getStorageKey in inspector/webstorage.js. Then you don't need that many changes in src/path.cc, only the namespacing part may be necessary (although, even today I think on main we don't take care of it in this case..)

    joyeecheung joyeecheung commented on code on Nov 13, 2026 15:50 UTC
    Code Review
    test/parallel/test-inspector-dom-storage-interrupt.js:1
    @@ -0,0 +1,138 @@
    +'use strict';
    +const common = require('../common');
    +common.skipIfSQLiteMissing();
    +common.skipIfInspectorDisabled();
    +
    +const assert = require('assert');
    +const { spawnSync } = require('child_process');
    +const { join } = require('path');
    +const { DatabaseSync } = require('node:sqlite');
    +const { NodeInstance } = require('../common/inspector-helper.js');
    +const tmpdir = require('../common/tmpdir');
    +tmpdir.refresh();
    +
    +// While JavaScript runs, a message from a remote frontend is dispatched from a
    +// V8 API interrupt, where JavaScript must not run. Reading a store has to work
    +// from there, whether or not the application has touched it yet. The script
    +// counts calls to the storage getters and to a setter that a JavaScript error
    +// created by Node.js would hit, and reports the count once the reads are done.
    +async function getItemsWhileBusy(localStorageFile, prelude, storageIds) {
    +  const script = `
    +  globalThis.jsCalls = 0;
    +  for (const name of ['localStorage', 'sessionStorage']) {
    +    const desc = Object.getOwnPropertyDescriptor(globalThis, name);
    +    Object.defineProperty(globalThis, name, {
    +      ...desc,
    +      get() { globalThis.jsCalls++; return desc.get.call(this); },
    +    });
    +  }
    +  Object.defineProperty(Error.prototype, 'code', {
    +    set() { globalThis.jsCalls++; }, configurable: true,
    +  });
    +  ${prelude}
    +  globalThis.jsCalls = 0;
    +  console.log('Ready');
    +  const deadline = Date.now() + ${common.platformTimeout(10000)};

    This doesn't seem very reliable on slow machines, maybe replace it with globalThis.interval = setInterval(() => {}, 1000);, and then to shut it down, send a Runtime.evaluate to clear it?

    joyeecheung joyeecheung commented on code on Nov 13, 2026 15:52 UTC
    Code Review
    test/parallel/test-inspector-dom-storage-interrupt.js:1
    @@ -0,0 +1,138 @@
    +'use strict';
    +const common = require('../common');
    +common.skipIfSQLiteMissing();
    +common.skipIfInspectorDisabled();
    +
    +const assert = require('assert');
    +const { spawnSync } = require('child_process');
    +const { join } = require('path');
    +const { DatabaseSync } = require('node:sqlite');
    +const { NodeInstance } = require('../common/inspector-helper.js');
    +const tmpdir = require('../common/tmpdir');
    +tmpdir.refresh();
    +
    +// While JavaScript runs, a message from a remote frontend is dispatched from a
    +// V8 API interrupt, where JavaScript must not run. Reading a store has to work
    +// from there, whether or not the application has touched it yet. The script
    +// counts calls to the storage getters and to a setter that a JavaScript error
    +// created by Node.js would hit, and reports the count once the reads are done.
    +async function getItemsWhileBusy(localStorageFile, prelude, storageIds) {
    +  const script = `
    +  globalThis.jsCalls = 0;
    +  for (const name of ['localStorage', 'sessionStorage']) {
    +    const desc = Object.getOwnPropertyDescriptor(globalThis, name);
    +    Object.defineProperty(globalThis, name, {
    +      ...desc,
    +      get() { globalThis.jsCalls++; return desc.get.call(this); },
    +    });
    +  }
    +  Object.defineProperty(Error.prototype, 'code', {
    +    set() { globalThis.jsCalls++; }, configurable: true,
    +  });
    +  ${prelude}
    +  globalThis.jsCalls = 0;
    +  console.log('Ready');
    +  const deadline = Date.now() + ${common.platformTimeout(10000)};
    +  while (!globalThis.done && Date.now() < deadline);
    +  `;
    +  const child = new NodeInstance([
    +    '--inspect-brk=0',
    +    '--experimental-storage-inspection',
    +    `--localstorage-file=${localStorageFile}`,
    +  ], script);
    +  const session = await child.connectInspectorSession();
    +  await session.send({ method: 'NodeRuntime.enable' });
    +  await session.waitForNotification('NodeRuntime.waitingForDebugger');
    +  await session.send([
    +    { 'method': 'Runtime.enable' },
    +    { 'method': 'Debugger.enable' },
    +  ]);
    +  await session.send({ method: 'Runtime.runIfWaitingForDebugger' });
    +  await session.send({ method: 'NodeRuntime.disable' });
    +  await session.waitForNotification('Debugger.paused', 'Break on start');
    +  await session.send({ 'method': 'Debugger.resume' });
    +  await session.waitForConsoleOutput('log', ['Ready']);
    +  // Enabled late, so items set by the prelude have to be read from the stores.
    +  await session.send({ method: 'DOMStorage.enable' });
    +
    +  const { storageKey } = await session.send({ method: 'Storage.getStorageKey' });
    +  const results = [];
    +  for (const isLocalStorage of storageIds) {
    +    results.push(await session.send({
    +      method: 'DOMStorage.getDOMStorageItems',
    +      params: { storageId: { isLocalStorage, securityOrigin: '', storageKey } },
    +    }).catch((err) => err));
    +  }
    +
    +  const { result } = await session.send({
    +    method: 'Runtime.evaluate',
    +    params: { expression: 'globalThis.done = true; globalThis.jsCalls' },
    +  });
    +  assert.strictEqual(result.value, 0);
    +  await session.waitForDisconnect();
    +  assert.strictEqual((await child.expectShutdown()).exitCode, 0);
    +  return results;
    +}
    +
    +// Node's own tables are created with IF NOT EXISTS, so a file that already
    +// holds tables of those names is adopted as-is, wrong types included.
    +function malformedLocalStorage(name) {
    +  const file = join(tmpdir.path, name);
    +  const db = new DatabaseSync(file);
    +  db.exec(`
    +    CREATE TABLE nodejs_webstorage(
    +      key BLOB NOT NULL, value BLOB NOT NULL, PRIMARY KEY(key)
    +    );
    +    CREATE TABLE nodejs_webstorage_state(
    +      max_size INTEGER NOT NULL DEFAULT 10485760,
    +      total_size INTEGER NOT NULL,
    +      schema_version INTEGER NOT NULL DEFAULT 1,
    +      single_row_ INTEGER NOT NULL DEFAULT 1 CHECK(single_row_ = 1),
    +      PRIMARY KEY(single_row_)
    +    );
    +    INSERT INTO nodejs_webstorage_state (total_size, schema_version)
    +      VALUES (0, 'one');
    +  `);
    +  db.close();
    +  return file;
    +}
    +
    +async function runTest() {
    +  // Stores the application never touched, with localStorage written by an
    +  // earlier run.
    +  const file = join(tmpdir.path, 'storage.db');
    +  const { status } = spawnSync(process.execPath, [
    +    `--localstorage-file=${file}`,
    +    '-e', 'localStorage.setItem("l", "local")',
    +  ]);
    +  assert.strictEqual(status, 0);

    Instead of using spawnSync and then asserting the status directly, which means when the test fail we are only to see very little useful information in the CI, can you move the helper into a test/common file, then split the test cases into their own files, each using spawnSyncAndAssert from test/common/child_process which shows more information when the child process does not operate as expected? See https://github.com/nodejs/node/blob/main/doc/contributing/writing-tests.md#how-to-write-a-good-test

    christianaurichzm christianaurichzm commented on code on Nov 14, 2026 06:28 UTC
    Code Review
    src/inspector_js_api.cc:1
    @@ -62,21 +62,38 @@ struct MainThreadConnection {
     template <typename ConnectionType>
     class JSBindingsConnection : public BaseObject {
      public:
    +  struct PendingMicrotask {
    +    explicit PendingMicrotask(JSBindingsConnection* connection)
    +        : env(connection->env()), connection(connection) {
    +      env->AddCleanupHook(Delete, this);
    +    }
    +
    +    static void Delete(void* data) {
    +      delete static_cast<PendingMicrotask*>(data);
    +    }
    +
    +    static void Run(void* data) {
    +      std::unique_ptr<PendingMicrotask> pending(
    +          static_cast<PendingMicrotask*>(data));
    +      pending->env->RemoveCleanupHook(Delete, pending.get());
    +      pending->connection->FlushPendingMessages();

    Done, thanks.

    christianaurichzm christianaurichzm commented on code on Nov 14, 2026 06:37 UTC
    Code Review
    test/parallel/test-inspector-dom-storage-interrupt.js:1
    @@ -0,0 +1,138 @@
    +'use strict';
    +const common = require('../common');
    +common.skipIfSQLiteMissing();
    +common.skipIfInspectorDisabled();
    +
    +const assert = require('assert');
    +const { spawnSync } = require('child_process');
    +const { join } = require('path');
    +const { DatabaseSync } = require('node:sqlite');
    +const { NodeInstance } = require('../common/inspector-helper.js');
    +const tmpdir = require('../common/tmpdir');
    +tmpdir.refresh();
    +
    +// While JavaScript runs, a message from a remote frontend is dispatched from a
    +// V8 API interrupt, where JavaScript must not run. Reading a store has to work
    +// from there, whether or not the application has touched it yet. The script
    +// counts calls to the storage getters and to a setter that a JavaScript error
    +// created by Node.js would hit, and reports the count once the reads are done.
    +async function getItemsWhileBusy(localStorageFile, prelude, storageIds) {
    +  const script = `
    +  globalThis.jsCalls = 0;
    +  for (const name of ['localStorage', 'sessionStorage']) {
    +    const desc = Object.getOwnPropertyDescriptor(globalThis, name);
    +    Object.defineProperty(globalThis, name, {
    +      ...desc,
    +      get() { globalThis.jsCalls++; return desc.get.call(this); },
    +    });
    +  }
    +  Object.defineProperty(Error.prototype, 'code', {
    +    set() { globalThis.jsCalls++; }, configurable: true,
    +  });
    +  ${prelude}
    +  globalThis.jsCalls = 0;
    +  console.log('Ready');
    +  const deadline = Date.now() + ${common.platformTimeout(10000)};
    +  while (!globalThis.done && Date.now() < deadline);
    +  `;
    +  const child = new NodeInstance([
    +    '--inspect-brk=0',
    +    '--experimental-storage-inspection',
    +    `--localstorage-file=${localStorageFile}`,
    +  ], script);
    +  const session = await child.connectInspectorSession();
    +  await session.send({ method: 'NodeRuntime.enable' });
    +  await session.waitForNotification('NodeRuntime.waitingForDebugger');
    +  await session.send([
    +    { 'method': 'Runtime.enable' },
    +    { 'method': 'Debugger.enable' },
    +  ]);
    +  await session.send({ method: 'Runtime.runIfWaitingForDebugger' });
    +  await session.send({ method: 'NodeRuntime.disable' });
    +  await session.waitForNotification('Debugger.paused', 'Break on start');
    +  await session.send({ 'method': 'Debugger.resume' });
    +  await session.waitForConsoleOutput('log', ['Ready']);
    +  // Enabled late, so items set by the prelude have to be read from the stores.
    +  await session.send({ method: 'DOMStorage.enable' });
    +
    +  const { storageKey } = await session.send({ method: 'Storage.getStorageKey' });
    +  const results = [];
    +  for (const isLocalStorage of storageIds) {
    +    results.push(await session.send({
    +      method: 'DOMStorage.getDOMStorageItems',
    +      params: { storageId: { isLocalStorage, securityOrigin: '', storageKey } },
    +    }).catch((err) => err));
    +  }
    +
    +  const { result } = await session.send({
    +    method: 'Runtime.evaluate',
    +    params: { expression: 'globalThis.done = true; globalThis.jsCalls' },
    +  });
    +  assert.strictEqual(result.value, 0);
    +  await session.waitForDisconnect();
    +  assert.strictEqual((await child.expectShutdown()).exitCode, 0);
    +  return results;
    +}
    +
    +// Node's own tables are created with IF NOT EXISTS, so a file that already
    +// holds tables of those names is adopted as-is, wrong types included.
    +function malformedLocalStorage(name) {
    +  const file = join(tmpdir.path, name);
    +  const db = new DatabaseSync(file);
    +  db.exec(`
    +    CREATE TABLE nodejs_webstorage(
    +      key BLOB NOT NULL, value BLOB NOT NULL, PRIMARY KEY(key)
    +    );
    +    CREATE TABLE nodejs_webstorage_state(
    +      max_size INTEGER NOT NULL DEFAULT 10485760,
    +      total_size INTEGER NOT NULL,
    +      schema_version INTEGER NOT NULL DEFAULT 1,
    +      single_row_ INTEGER NOT NULL DEFAULT 1 CHECK(single_row_ = 1),
    +      PRIMARY KEY(single_row_)
    +    );
    +    INSERT INTO nodejs_webstorage_state (total_size, schema_version)
    +      VALUES (0, 'one');
    +  `);
    +  db.close();
    +  return file;
    +}
    +
    +async function runTest() {
    +  // Stores the application never touched, with localStorage written by an
    +  // earlier run.
    +  const file = join(tmpdir.path, 'storage.db');
    +  const { status } = spawnSync(process.execPath, [
    +    `--localstorage-file=${file}`,
    +    '-e', 'localStorage.setItem("l", "local")',
    +  ]);
    +  assert.strictEqual(status, 0);

    Done. The helper is now in test/common/inspector-dom-storage.js, with a separate file for each case. Only the file case has a setup process, and it uses spawnSyncAndExitWithoutError now. The reads still need NodeInstance, since the parent talks to the child while it's busy, but it already prints the child's stderr.

    christianaurichzm christianaurichzm commented on code on Nov 14, 2026 06:45 UTC
    Code Review
    test/parallel/test-inspector-dom-storage-interrupt.js:1
    @@ -0,0 +1,138 @@
    +'use strict';
    +const common = require('../common');
    +common.skipIfSQLiteMissing();
    +common.skipIfInspectorDisabled();
    +
    +const assert = require('assert');
    +const { spawnSync } = require('child_process');
    +const { join } = require('path');
    +const { DatabaseSync } = require('node:sqlite');
    +const { NodeInstance } = require('../common/inspector-helper.js');
    +const tmpdir = require('../common/tmpdir');
    +tmpdir.refresh();
    +
    +// While JavaScript runs, a message from a remote frontend is dispatched from a
    +// V8 API interrupt, where JavaScript must not run. Reading a store has to work
    +// from there, whether or not the application has touched it yet. The script
    +// counts calls to the storage getters and to a setter that a JavaScript error
    +// created by Node.js would hit, and reports the count once the reads are done.
    +async function getItemsWhileBusy(localStorageFile, prelude, storageIds) {
    +  const script = `
    +  globalThis.jsCalls = 0;
    +  for (const name of ['localStorage', 'sessionStorage']) {
    +    const desc = Object.getOwnPropertyDescriptor(globalThis, name);
    +    Object.defineProperty(globalThis, name, {
    +      ...desc,
    +      get() { globalThis.jsCalls++; return desc.get.call(this); },
    +    });
    +  }
    +  Object.defineProperty(Error.prototype, 'code', {
    +    set() { globalThis.jsCalls++; }, configurable: true,
    +  });
    +  ${prelude}
    +  globalThis.jsCalls = 0;
    +  console.log('Ready');
    +  const deadline = Date.now() + ${common.platformTimeout(10000)};

    With only an interval, the test doesn't guarantee that the reads arrive during a V8 interrupt. I kept the loop to exercise that path and added your interval so the child stays alive if the loop times out. In that case the reads can come from the event loop, but the counters still catch calls to the storage getters and the Error.prototype.code setter.

    christianaurichzm christianaurichzm commented on code on Nov 14, 2026 07:00 UTC
    Code Review
    src/inspector/dom_storage_agent.cc:1
    @@ -100,38 +103,35 @@ protocol::DispatchResponse DOMStorageAgent::getDOMStorageItems(
           is_local_storage ? &local_storage_map_ : &session_storage_map_;
       std::optional<StorageMap> storage_map_fallback;
       if (storage_map->empty()) {
    -    auto web_storage_obj = getWebStorage(is_local_storage);
    +    bool is_uninitialized = false;
    +    auto web_storage_obj = getWebStorage(is_local_storage, &is_uninitialized);
         // Each way of failing below says something different about the store, so
         // each reports a different reason. A frontend that cannot read a store
         // otherwise has no way to tell a missing one from a corrupt one.
    -    if (!web_storage_obj) {
    +    if (!web_storage_obj && !is_uninitialized) {
           return protocol::DispatchResponse::ServerError(
               "Could not read DOM storage items: storage is unavailable");
         }
    -    // A message from a remote frontend is dispatched without a HandleScope
    -    // on the stack, and opening the backing file can throw, so give the
    -    // exception a scope to be allocated in and somewhere to land.
    -    v8::HandleScope handle_scope(env_->isolate());
    -    v8::TryCatch try_catch(env_->isolate());
    -    storage_map_fallback = web_storage_obj.value()->GetAll();
    -    if (try_catch.HasCaught()) {
    -      // Pass the reason along; "the file was written by a newer Node.js" and
    -      // "the file is locked" are not the same problem to the user. Read it
    -      // off the Message, which was built when the exception was thrown.
    -      // Converting the exception itself would call a user-patchable
    -      // Error.prototype.toString, and there is no JavaScript frame here to
    -      // run it from.
    -      Local<v8::Message> message = try_catch.Message();
    -      if (!message.IsEmpty()) {
    -        Utf8Value reason(env_->isolate(), message->Get());
    -        return protocol::DispatchResponse::ServerError(
    -            std::string("Could not read DOM storage items: ") + reason.out());
    +    std::string open_error;
    +    if (web_storage_obj) {
    +      storage_map_fallback = web_storage_obj.value()->GetAll(&open_error);
    +    } else if (is_local_storage) {
    +      std::string location = env_->options()->localstorage_file;

    It's made absolute once now, while the options are parsed, and localStorage, getStorageKey() and both agents read that value. getStorageKey() keeps path.resolve() to normalize it, so ./storage.db still gets the same key as Storage.getStorageKey. I left path.cc as it was, since it only has the namespacing part. On main, Storage::New already namespaces the path on Windows, and the direct read has to match it to open the same file. A chdir before the first use of localStorage no longer moves the file, which I documented under --localstorage-file.

    The two storage keys still differ in some cases, though. getStorageKey() builds the URL by concatenating the path, while Storage.getStorageKey uses FromFilePath() on the canonical path, so a space, a non-ASCII character or a symlink in the path gives the event and the query different keys. That's the same on main. Would it be OK to fix that in a separate PR?

    deepak1556 deepak1556 commented on Nov 26, 2026 05:12 UTC
    Contributor

    Something to prepare for once this lands, https://chromium-review.googlesource.com/c/v8/v8/+/8775587 will now disallow non pausing cdp commands during an interrupt, would need to separate the request queue based on an allowlist similar to blink https://chromium-review.googlesource.com/c/chromium/src/+/8775568

    christianaurichzm christianaurichzm commented on Nov 26, 2026 17:50 UTC
    Author

    @deepak1556 thanks for the heads-up. I can add the allowlist in the follow-up that enables the check, unless you're already on it.

    @joyeecheung could you take another look when you get a chance? Thanks!

    deepak1556 deepak1556 commented on Nov 27, 2026 13:54 UTC
    Contributor

    I want to address it eventually for electron where the feature is enabled but no immediate plans.

    christianaurichzm christianaurichzm commented on Dec 01, 2026 13:26 UTC
    Author

    I rebased to pick up the lint fix from #67904, nothing else changed.

    Reviewers
    Assignees
    christianaurichzm christianaurichzm
    Labels
    risk: low confidence: 88.6% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 78.5% (HIGH) · Higher = larger blast radius
    78.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 88.6% · Lower = rushed or shallow review
    88.6%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 8.9% · Safe to merge
    8.9%
    Repository