← Back to Pull requests

test: cover immutable ArrayBuffer known issues #66350

Closed
panva closed this pull request without merging on Oct 07, 2026 14:58 UTC
View on GitHub
panva panva commented on Sep 27, 2026 13:56 UTC
Author

Cover native writes, immutable source copies, and view serialization across the affected API families. Exercise the Node-API detach abort using the existing typed-array addon and mark it as an expected failure.

Refs: https://github.com/nodejs/node/issues/66346

Diff: 896 lines (+896 / -0) across 13 files Reviewer: avivkeller Review duration: 14462m
All Vouch review confidence checks passed
Residual risk 0.11 = Change Risk (0.61) × (1 − Review Confidence (0.82)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.61 · 896 lines diff across 13 files
0.61
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.74 · 5 substantive comment(s)
0.74
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
81%
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
Real PR Conversation Timeline
17 items
codecov[bot] codecov[bot] commented on Sep 27, 2026 15:46 UTC
Bot

Codecov Report


:white_check_mark: All modified and coverable lines are covered by tests.
:white_check_mark: Project coverage is 90.92%. Comparing base (3641c36) to head (bb73a20).
:warning: Report is 208 commits behind head on main.

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

@@            Coverage Diff             @@
##             main   #66350      +/-   ##
==========================================
+ Coverage   90.36%   90.92%   +0.56%     
==========================================
  Files         792      793       +1     
  Lines      275386   283479    +8093     
  Branches    52770    60259    +7489     
==========================================
+ Hits       248859   257760    +8901     
+ Misses      16936    16315     -621     
+ Partials     9591     9404     -187     

see 119 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>

    avivkeller avivkeller approved these changes on Sep 28, 2026 14:38 UTC
    Approved Reviewer

    Approved these changes.

    avivkeller avivkeller commented on Sep 28, 2026 14:40 UTC
    Contributor

    LGTM, but we should try and fix these rather than marking them as known issues. I'll work on fs.

    aduh95 aduh95 commented on code on Sep 30, 2026 08:13 UTC
    Code Review
    test/known_issues/test-immutable-arraybuffer-buffer.js:1
    @@ -0,0 +1,79 @@
    +// Flags: --js-immutable-arraybuffer
    +'use strict';
    +
    +require('../common');
    +const assert = require('assert');
    +const { test } = require('node:test');
    +
    +// Native Buffer mutators must preserve immutable backing storage, whether they
    +// reject the operation or return without modifying the bytes.
    +function checkImmutable(mutate) {
    +  const expected = Array.from({ length: 64 }, (_, i) => i);
    +  const ab = Uint8Array.from(expected).buffer.transferToImmutable();
    +  const buffer = Buffer.from(ab);
    +
    +  try {
    +    mutate(buffer);
    +  } catch (err) {
    +    if (!(err instanceof TypeError)) throw err;

    nit

        if (err?.name !== 'TypeError') throw err;
    

    it would be interesting to have a comment explaining why an optional TypeError is fine here, shouldn't we add assert.throws when applicable in mutate instead?

    aduh95 aduh95 commented on code on Sep 30, 2026 08:14 UTC
    Code Review
    test/js-native-api/js-native-api.status:1
    @@ -0,0 +1,5 @@
    +prefix js-native-api
    +
    +[true]
    +# napi_detach_arraybuffer() aborts when given an immutable ArrayBuffer.
    +test_typedarray/test-immutable-arraybuffer: FAIL

    Why not known_issues?

    aduh95 aduh95 commented on code on Sep 30, 2026 08:19 UTC
    Code Review
    test/known_issues/test-immutable-arraybuffer-encoding.js:1
    @@ -0,0 +1,24 @@
    +// Flags: --js-immutable-arraybuffer
    +'use strict';
    +
    +require('../common');
    +const assert = require('assert');
    +const { test } = require('node:test');
    +
    +for (const [name, input] of [['short', 'hello'], ['long', 'hello'.repeat(16)]]) {
    +  test(`TextEncoder.encodeInto with ${name} input preserves immutable bytes`, () => {
    +    const expected = Array(128).fill(0xaa);
    +    const ab = Uint8Array.from(expected).buffer.transferToImmutable();
    +    const destination = new Uint8Array(ab);
    +
    +    // The short and long inputs exercise different native encoding paths.
    +    // Do not require a particular rejection behavior, only unchanged bytes.
    +    try {
    +      new TextEncoder().encodeInto(input, destination);
    +    } catch (err) {
    +      if (!(err instanceof TypeError)) throw err;
    +    }

        new TextEncoder().encodeInto(input, destination);
    

    or
        assert.throws(() => new TextEncoder().encodeInto(input, destination), {
          name: 'TypeError',
        });
    

    aduh95 aduh95 commented on code on Sep 30, 2026 08:23 UTC
    Code Review
    test/known_issues/test-immutable-arraybuffer-fs-copy.js:1
    @@ -0,0 +1,138 @@
    +// Flags: --js-immutable-arraybuffer
    +'use strict';
    +
    +const common = require('../common');
    +const assert = require('node:assert');
    +const fs = require('node:fs');
    +const { once } = require('node:events');
    +const { join } = require('node:path');
    +const { test } = require('node:test');
    +const { spawnSyncAndAssert } = require('../common/child_process');
    +const tmpdir = require('../common/tmpdir');
    +
    +// These APIs only read the supplied bytes. Internal copies must accept an
    +// immutable source just as they accept a mutable one.
    +function immutable(value) {
    +  return Buffer.from(Uint8Array.from(Buffer.from(value)).buffer.transferToImmutable());
    +}
    +
    +const cases = new Map();
    +const options = { recursive: true, withFileTypes: true };
    +
    +for (const method of ['readdirSync', 'readdir', 'promises.readdir']) {
    +  cases.set(`fs.${method} with a recursive Buffer path`, (directory) => checkReaddir(directory, method));
    +}
    +
    +async function checkReaddir(directory, method) {
    +  fs.mkdirSync(join(directory, 'nested'));
    +  fs.writeFileSync(join(directory, 'nested', 'file'), 'contents');
    +  const path = immutable(directory);
    +  let entries;
    +  if (method === 'readdirSync') {
    +    entries = fs.readdirSync(path, options);
    +  } else if (method === 'readdir') {
    +    entries = await new Promise((resolve) => {
    +      fs.readdir(path, options, common.mustSucceed(resolve));
    +    });
    +  } else {
    +    entries = await fs.promises.readdir(path, options);
    +  }
    +  assert.deepStrictEqual(entries.map((entry) => entry.name).sort(), ['file', 'nested']);
    +  const file = entries.find((entry) => entry.name === 'file');
    +  assert(file.isFile());
    +  assert.strictEqual(file.parentPath.toString(), join(directory, 'nested'));
    +}
    +
    +for (const method of ['rm', 'promises.rm']) {
    +  cases.set(`fs.${method} with a recursive Buffer path`, (directory) => checkRm(directory, method));
    +}
    +
    +async function checkRm(directory, method) {
    +  fs.writeFileSync(join(directory, 'file'), 'contents');
    +  const path = immutable(directory);
    +  if (method === 'rm') {

    I think I'd rather have WET code in this file

    aduh95 aduh95 commented on code on Sep 30, 2026 08:25 UTC
    Code Review
    test/known_issues/test-immutable-arraybuffer-fs.js:1
    @@ -0,0 +1,76 @@
    +// Flags: --js-immutable-arraybuffer
    +'use strict';
    +
    +require('../common');
    +const assert = require('assert');
    +const fs = require('fs');
    +const { test } = require('node:test');
    +const tmpdir = require('../common/tmpdir');
    +
    +// Reading into an immutable backing store must not change its bytes.
    +tmpdir.refresh();
    +const path = tmpdir.resolve('immutable-arraybuffer');
    +fs.writeFileSync(path, 'test');
    +
    +async function checkRead(read) {
    +  const buffer = new Uint8Array(new ArrayBuffer(4).transferToImmutable());
    +  try {
    +    await read(buffer);
    +  } catch (err) {
    +    if (!(err instanceof TypeError)) throw err;
    +  }

      await read(buffer);
    

    or
      await assert.rejects(read(buffer), { name: 'TypeError' });
    

    aduh95 aduh95 commented on code on Sep 30, 2026 08:28 UTC
    Code Review
    test/known_issues/test-immutable-arraybuffer-inspector.js:1
    @@ -0,0 +1,91 @@
    +// Flags: --js-immutable-arraybuffer --experimental-network-inspection
    +'use strict';
    +
    +const common = require('../common');
    +if (!common.hasCrypto)
    +  common.skip('missing crypto');
    +common.skipIfInspectorDisabled();
    +
    +const assert = require('node:assert');
    +
    +// Network inspection copies request body chunks, which must also work when
    +// the body is immutable. Isolate uncaught diagnostic-channel errors so both
    +// request paths can be tested.
    +if (process.argv[2]) {
    +  const { once } = require('node:events');
    +  const { Session } = require('node:inspector/promises');
    +  const kind = process.argv[2];
    +  const enabled = process.argv[3] === 'on';
    +
    +  async function run() {
    +    const session = new Session();
    +    session.connect();
    +    const http = require(kind === 'http2' ? 'node:http2' : 'node:http');
    +    const expected = kind === 'http2' ? 'ABCDABCD' : 'ABCD';
    +    const server = http.createServer(common.mustCall((req, res) => {
    +      let body = '';
    +      req.setEncoding('utf8');
    +      req.on('data', (chunk) => { body += chunk; });
    +      req.on('end', common.mustCall(() => {
    +        assert.strictEqual(body, expected);
    +        res.end(body);
    +      }));
    +    }));
    +    let client;
    +    try {
    +      if (enabled) {
    +        session.on('Network.requestWillBeSent', common.mustCall());
    +        await session.post('Network.enable');
    +      }
    +      server.listen(0, '127.0.0.1');
    +      await once(server, 'listening');
    +      const url = `http://127.0.0.1:${server.address().port}`;
    +      const chunk = Buffer.from(Uint8Array.from([65, 66, 67, 68]).buffer.transferToImmutable());
    +      let body = '';
    +      if (kind === 'http2') {
    +        client = http.connect(url);
    +        const req = client.request({ ':method': 'POST' });
    +        req.cork();
    +        req.write(chunk);
    +        req.end(chunk);
    +        for await (const data of req) body += data;
    +      } else {
    +        const stream = new ReadableStream({
    +          start(controller) {
    +            controller.enqueue(chunk);
    +            controller.close();
    +          },
    +        });
    +        const response = await fetch(url, {
    +          method: 'POST', body: stream, duplex: 'half',
    +        });
    +        body = await response.text();
    +      }
    +      assert.strictEqual(body, expected);
    +      assert.strictEqual(chunk.toString(), 'ABCD');
    +      assert.strictEqual(chunk.buffer.immutable, true);
    +    } finally {
    +      client?.destroy();
    +      server.closeAllConnections?.();
    +      if (server.listening) await new Promise((resolve) => server.close(resolve));
    +      session.disconnect();
    +    }
    +  }
    +
    +  run().then(common.mustCall());
    +} else {
    +  const { test } = require('node:test');
    +  const { spawnSyncAndAssert } = require('../common/child_process');
    +
    +  for (const kind of ['http2', 'fetch']) {
    +    test(`${kind} sends immutable chunks with network inspection`, () => {
    +      // The same request succeeds with inspection disabled.
    +      for (const inspection of ['off', 'on']) {
    +        spawnSyncAndAssert(process.execPath, [
    +          '--js-immutable-arraybuffer', '--experimental-network-inspection',
    +          __filename, kind, inspection,
    +        ], { timeout: common.platformTimeout(10000) }, { status: 0 });

    Why do we use that on top of the // Flags comment on top? Also, why that timeout?

    aduh95 aduh95 commented on code on Sep 30, 2026 08:29 UTC
    Code Review
    test/known_issues/test-immutable-arraybuffer-vfs.js:1
    @@ -0,0 +1,83 @@
    +// Flags: --js-immutable-arraybuffer --experimental-vfs
    +'use strict';
    +
    +require('../common');
    +const assert = require('node:assert');
    +const { test } = require('node:test');
    +const vfs = require('node:vfs');
    +const { ZipEntry, ZipBuffer, createZipArchiveSync } = require('node:zlib');
    +
    +const data = Buffer.from('test');
    +
    +function immutable(buffer) {
    +  return Buffer.from(buffer.buffer.sliceToImmutable(
    +    buffer.byteOffset, buffer.byteOffset + buffer.length));
    +}
    +
    +function createZip() {
    +  const entry = ZipEntry.createSync('file', data, { method: 'store' });
    +  const bytes = Buffer.concat([...createZipArchiveSync([entry])]);
    +  return vfs.create(new vfs.ZipProvider(new ZipBuffer(bytes)));
    +}
    +
    +for (const [name, write] of [
    +  ['writeFileSync', (store, path, source) => store.writeFileSync(path, source)],
    +  ['promises.writeFile', (store, path, source) => store.promises.writeFile(path, source)],
    +]) {
    +  test(`ZipProvider ${name} accepts immutable source bytes`, async () => {
    +    const store = createZip();
    +    await write(store, '/control', data);
    +    assert.deepStrictEqual(store.readFileSync('/control'), data);
    +
    +    const source = immutable(data);
    +    await write(store, '/immutable', source);
    +    assert.deepStrictEqual(store.readFileSync('/immutable'), data);
    +    assert.deepStrictEqual([...source], [...data]);
    +  });
    +}
    +
    +const reads = [
    +  ['readSync', (store, fd, buffer) => store.readSync(fd, buffer, 0, buffer.length, null)],
    +  ['read', (store, fd, buffer) => new Promise((resolve, reject) => {
    +    store.read(fd, buffer, 0, buffer.length, null, (err, bytesRead) => {
    +      if (err) reject(err);
    +      else resolve(bytesRead);
    +    });
    +  })],
    +];
    +
    +for (const [provider, create] of [
    +  ['MemoryProvider', () => {
    +    const store = vfs.create();
    +    store.writeFileSync('/file', data);
    +    return store;
    +  }],
    +  ['ZipProvider', createZip],
    +]) {
    +  for (const [method, read] of reads) {
    +    test(`${provider} ${method} with an immutable destination`, async (t) => {
    +      const store = create();
    +      const fd = store.openSync('/file', 'r');
    +      t.after(() => store.closeSync(fd));
    +
    +      const control = Buffer.alloc(data.length);
    +      assert.strictEqual(store.readSync(fd, control, 0, control.length, 0), data.length);
    +      assert.deepStrictEqual(control, data);
    +
    +      const target = immutable(Buffer.alloc(data.length));
    +      let bytesRead = 0;
    +      try {
    +        bytesRead = await read(store, fd, target);
    +      } catch (err) {
    +        if (!(err instanceof TypeError)) throw err;
    +      }

          bytesRead = await read(store, fd, target);
    

    aduh95 aduh95 commented on code on Sep 30, 2026 08:33 UTC
    Code Review
    test/known_issues/test-immutable-arraybuffer-crypto.js:1
    @@ -0,0 +1,52 @@
    +// Flags: --js-immutable-arraybuffer
    +'use strict';
    +
    +const common = require('../common');
    +
    +if (!common.hasCrypto)
    +  common.skip('missing crypto');
    +
    +const assert = require('assert');
    +const crypto = require('crypto');
    +const { test } = require('node:test');
    +
    +const cases = [
    +  ['randomFillSync with an ArrayBuffer', (buffer) => {
    +    crypto.randomFillSync(buffer);
    +  }],
    +  ['randomFill with a DataView', (buffer) => {
    +    return new Promise((resolve, reject) => {
    +      crypto.randomFill(new DataView(buffer), (err) => {
    +        if (err) {
    +          reject(err);
    +          return;
    +        }
    +        resolve();
    +      });
    +    });
    +  }],
    +  ['getRandomValues with a Uint8Array', (buffer) => {
    +    crypto.getRandomValues(new Uint8Array(buffer));
    +  }],
    +  ['global crypto.getRandomValues with a Buffer', (buffer) => {
    +    globalThis.crypto.getRandomValues(Buffer.from(buffer));
    +  }],
    +];
    +
    +for (const [name, fill] of cases) {
    +  test(name, async () => {
    +    const buffer = new ArrayBuffer(32).transferToImmutable();
    +    const bytes = new Uint8Array(buffer);
    +    const original = Array.from(bytes);
    +
    +    try {
    +      await fill(buffer);
    +    } catch (err) {
    +      if (!(err instanceof TypeError))
    +        throw err;
    +    }

    Same here, we should assert, not optionally catch

    aduh95 aduh95 approved these changes on Oct 07, 2026 13:31 UTC
    Approved Reviewer

    Approved these changes.

    avivkeller avivkeller commented on Oct 07, 2026 14:30 UTC
    Contributor

    @panva I think the CI failures are coming from the fact that I backported a V8 ArrayBuffer fix that resolves a few of the known issues :-)

    panva panva commented on Oct 07, 2026 14:57 UTC
    Author

    @panva I think the CI failures are coming from the fact that I backported a V8 ArrayBuffer fix that resolves a few of the known issues :-)

    Why are we backporting things for a flagged V8 feature?

    Reviewers
    Assignees
    panva panva
    Labels
    risk: low confidence: 82.0% 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: 60.6% (MEDIUM) · Higher = larger blast radius
    60.6%
    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: 82.0% · Lower = rushed or shallow review
    82.0%
    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: 10.9% · Safe to merge
    10.9%
    Repository