OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[OV JS] Fix GC safety for zero-copy tensor construction from TypedArray (#35668)
Kirill Suvorov23fd5d90b3b8
diff --git a/src/bindings/js/node/CMakeLists.txt b/src/bindings/js/node/CMakeLists.txtindex e2de621b1fb..cdc6d2999eb 100644--- a/src/bindings/js/node/CMakeLists.txt+++ b/src/bindings/js/node/CMakeLists.txt@@ -61,6 +61,7 @@ add_library(${PROJECT_NAME} SHARED${CMAKE_CURRENT_SOURCE_DIR}/src/errors.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/helper.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/type_validation.cpp+ ${CMAKE_CURRENT_SOURCE_DIR}/src/tensor_impl.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/tensor.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/infer_request.cpp${CMAKE_CURRENT_SOURCE_DIR}/src/compiled_model.cpp@@ -80,7 +81,7 @@ target_include_directories(${PROJECT_NAME} PRIVATE"${CMAKE_CURRENT_SOURCE_DIR}/..")-target_link_libraries(${PROJECT_NAME} PRIVATE openvino::core::dev openvino::runtime openvino::util ${DELAYIMP_LIB} ${CMAKE_JS_LIB})+target_link_libraries(${PROJECT_NAME} PRIVATE openvino::core::dev openvino::runtime::dev openvino::runtime openvino::util ${DELAYIMP_LIB} ${CMAKE_JS_LIB})if(MSVC AND CMAKE_JS_NODELIB_DEF AND CMAKE_JS_NODELIB_TARGET)# Generate node.libdiff --git a/src/bindings/js/node/include/tensor_impl.hpp b/src/bindings/js/node/include/tensor_impl.hppnew file mode 100644index 00000000000..5aa2691a433--- /dev/null+++ b/src/bindings/js/node/include/tensor_impl.hpp@@ -0,0 +1,80 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <napi.h>++#include <atomic>++#include "openvino/runtime/itensor.hpp"+#include "openvino/runtime/tensor.hpp"++namespace ov {+namespace js {++/**+ * @brief An ov::ITensor decorator that pins a JS TypedArray's ArrayBuffer in V8 heap.+ *+ * Delegates all tensor operations to a wrapped ov::ITensor implementation.+ * Holds a strong napi_ref so V8 cannot GC the ArrayBuffer while any C++ copy of+ * this tensor is alive.+ *+ * The reference is scheduled for deletion on the JS thread via a TSFN finalizer,+ * making destruction safe from OpenVINO thread-pool threads (e.g. async inference).+ */+class TensorImpl final : public ov::ITensor {+public:+ struct CleanupContext {+ explicit CleanupContext(Napi::Reference<Napi::TypedArray>* typed_array_ref) : ref(typed_array_ref) {}++ void release_owner();+ void release_tsfn();+ void remove_cleanup_hook();+ static void cleanup_hook(napi_async_cleanup_hook_handle handle, void* data);++ std::atomic<uint32_t> owners{2};+ std::atomic<bool> tsfn_released{false};+ std::atomic<bool> cleanup_handle_removed{false};+ napi_async_cleanup_hook_handle cleanup_handle{nullptr};+ Napi::ThreadSafeFunction tsfn;+ Napi::Reference<Napi::TypedArray>* ref;+ };++ /**+ * @brief Construct a TensorImpl that zero-copies @p typed_array data into a tensor.+ *+ * Must be called on the JS thread.+ *+ * @param env Current JS environment.+ * @param typed_array Source TypedArray whose ArrayBuffer supplies tensor memory.+ * @param type OpenVINO element type.+ * @param shape TensorImpl shape.+ */+ TensorImpl(Napi::Env env,+ const Napi::TypedArray& typed_array,+ const ov::element::Type& type,+ const ov::Shape& shape);++ ~TensorImpl() override;++ void set_shape(ov::Shape shape) override;+ const ov::element::Type& get_element_type() const override;+ const ov::Shape& get_shape() const override;+ const ov::Strides& get_strides() const override;+ void* data() override;+ const void* data() const override;+ void* data_rw() override;+ void* data(const ov::element::Type& type) override;+ const void* data(const ov::element::Type& type) const override;+ void* data_rw(const ov::element::Type& type) override;++private:+ ov::Tensor _impl;+ ov::Strides _strides;+ CleanupContext* _cleanup_ctx{nullptr};+};++} // namespace js+} // namespace ovdiff --git a/src/bindings/js/node/package.json b/src/bindings/js/node/package.jsonindex 750e9af7256..ca309580fd4 100644--- a/src/bindings/js/node/package.json+++ b/src/bindings/js/node/package.json@@ -20,7 +20,7 @@"lint": "eslint .","format": "prettier --ignore-path .gitignore --write .","test_setup": "node ./tests/setup.js",- "test": "npm run test_setup && node --test ./tests/unit/*.test.js",+ "test": "npm run test_setup && node --expose-gc --test ./tests/unit/*.test.js","test:e2e": "mocha ./tests/e2e/electron-app.test.js","tsc": "tsc","postinstall": "npm run install_runtime",diff --git a/src/bindings/js/node/src/helper.cpp b/src/bindings/js/node/src/helper.cppindex b0e2eda0631..deb4b510f2b 100644--- a/src/bindings/js/node/src/helper.cpp+++ b/src/bindings/js/node/src/helper.cpp@@ -7,7 +7,9 @@#include "node/include/compiled_model.hpp"#include "node/include/node_wrap.hpp"#include "node/include/tensor.hpp"+#include "node/include/tensor_impl.hpp"#include "node/include/type_validation.hpp"+#include "openvino/runtime/make_tensor.hpp"const std::vector<std::string>& get_supported_types() {static const std::vector<std::string> supported_element_types =@@ -369,17 +371,10 @@ ov::Tensor cast_to_tensor(const Napi::CallbackInfo& info, int index) {ov::Tensor cast_to_tensor(const Napi::TypedArray& typed_array,const ov::Shape& shape,const ov::element::Type_t& type) {- /* The difference between TypedArray::ArrayBuffer::Data() and e.g. Float32Array::Data() is byteOffset- because the TypedArray may have a non-zero `ByteOffset()` into the `ArrayBuffer`. */- if (typed_array.ByteOffset() != 0) {- OPENVINO_THROW("TypedArray.byteOffset has to be equal to zero.");- }- auto array_buffer = typed_array.ArrayBuffer();- auto tensor = ov::Tensor(type, shape, array_buffer.Data());- if (tensor.get_byte_size() != array_buffer.ByteLength()) {- OPENVINO_THROW("Memory allocated using shape and element::type mismatch passed data's size");- }- return tensor;+ OPENVINO_ASSERT(typed_array.ByteOffset() == 0,+ "TypedArray.byteOffset must be zero for zero-copy tensor construction.");+ auto impl = std::make_shared<ov::js::TensorImpl>(typed_array.Env(), typed_array, type, shape);+ return ov::make_tensor(ov::SoPtr<ov::ITensor>{impl, nullptr});}void fill_tensor_from_strings(ov::Tensor& tensor, const Napi::Array& arr) {diff --git a/src/bindings/js/node/src/tensor_impl.cpp b/src/bindings/js/node/src/tensor_impl.cppnew file mode 100644index 00000000000..df8ded01ee9--- /dev/null+++ b/src/bindings/js/node/src/tensor_impl.cpp@@ -0,0 +1,140 @@+// Copyright (C) 2018-2026 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "node/include/tensor_impl.hpp"++#include "openvino/core/except.hpp"+#include "openvino/runtime/tensor.hpp"++namespace ov {+namespace js {++// Drops one native owner of the shared cleanup state and deletes it on the last release.+void TensorImpl::CleanupContext::release_owner() {+ if (owners.fetch_sub(1) == 1) {+ delete this;+ }+}++// Releases the TSFN exactly once because both destructor and env cleanup may race here.+void TensorImpl::CleanupContext::release_tsfn() {+ if (!tsfn_released.exchange(true)) {+ const auto status = tsfn.Release();+ OPENVINO_ASSERT(status == napi_ok || status == napi_closing,+ "TensorImpl: failed to release ThreadSafeFunction.");+ }+}++// Unregisters the async cleanup hook exactly once to avoid double removal during shutdown.+void TensorImpl::CleanupContext::remove_cleanup_hook() {+ if (cleanup_handle != nullptr && !cleanup_handle_removed.exchange(true)) {+ const auto status = napi_remove_async_cleanup_hook(cleanup_handle);+ OPENVINO_ASSERT(status == napi_ok, "TensorImpl: failed to remove async cleanup hook.");+ }+}++// Handles Node environment teardown by forcing TSFN shutdown through the cleanup hook path.+void TensorImpl::CleanupContext::cleanup_hook(napi_async_cleanup_hook_handle handle, void* data) {+ auto* cleanup_ctx = static_cast<TensorImpl::CleanupContext*>(data);+ cleanup_ctx->cleanup_handle = handle;+ cleanup_ctx->release_tsfn();+ cleanup_ctx->remove_cleanup_hook();+}++TensorImpl::TensorImpl(Napi::Env env,+ const Napi::TypedArray& typed_array,+ const ov::element::Type& type,+ const ov::Shape& shape) {+ _impl = ov::Tensor(type, shape, typed_array.ArrayBuffer().Data());+ _strides = _impl.get_strides();+ OPENVINO_ASSERT(_impl.get_byte_size() == typed_array.ByteLength(),+ "Memory allocated using shape and element::type mismatch TypedArray byte length.");++ // TSFN keep a strong reference to the TypedArray, preventing GC of its ArrayBuffer while this TensorImpl is alive.+ // - ~TensorImpl() calls Release() from any thread (thread-safe) and releases the strong reference.+ auto* ref = new Napi::Reference<Napi::TypedArray>(Napi::Persistent(typed_array));+ _cleanup_ctx = new CleanupContext(ref);+ auto tsfn =+ Napi::ThreadSafeFunction::New(env,+ Napi::Function{}, // no JS callback needed+ "ovTensorCleanup",+ 0, // unlimited queue+ 1, // initial_thread_count+ _cleanup_ctx, // context (passed to finalizer)+ [](Napi::Env, CleanupContext* cleanup_ctx) {+ delete cleanup_ctx->ref; // runs on JS thread: releases strong reference+ cleanup_ctx->release_owner();+ });+ OPENVINO_ASSERT(tsfn, "TensorImpl: failed to create ThreadSafeFunction for cleanup.");++ // Creates a zero-copy tensor over TypedArray storage and pins the JS object until native teardown completes.+ _cleanup_ctx->tsfn = tsfn;+ const auto status =+ napi_add_async_cleanup_hook(env, CleanupContext::cleanup_hook, _cleanup_ctx, &_cleanup_ctx->cleanup_handle);+ OPENVINO_ASSERT(status == napi_ok, "TensorImpl: failed to register async cleanup hook.");++ // Unref so the TSFN does not prevent the event loop from exiting.+ tsfn.Unref(env);+}++// Tears down the shutdown coordination state from any thread-safe destruction path.+TensorImpl::~TensorImpl() {+ _cleanup_ctx->remove_cleanup_hook();+ _cleanup_ctx->release_tsfn();+ _cleanup_ctx->release_owner();+}++// Reshapes the wrapped tensor and refreshes cached strides that are exposed by reference.+void TensorImpl::set_shape(ov::Shape shape) {+ _impl.set_shape(std::move(shape));+ _strides = _impl.get_strides();+}++// Forwards element type queries to the wrapped tensor.+const ov::element::Type& TensorImpl::get_element_type() const {+ return _impl.get_element_type();+}++// Forwards shape queries to the wrapped tensor.+const ov::Shape& TensorImpl::get_shape() const {+ return _impl.get_shape();+}++// Returns cached strides because ov::Tensor::get_strides() produces a temporary value.+const ov::Strides& TensorImpl::get_strides() const {+ return _strides;+}++// Returns mutable raw data from the wrapped tensor.+void* TensorImpl::data() {+ return _impl.data();+}++// Returns const raw data from the wrapped tensor.+const void* TensorImpl::data() const {+ return std::as_const(_impl).data();+}++// Returns writable raw data from the wrapped tensor.+void* TensorImpl::data_rw() {+ return _impl.data();+}++// Returns mutable typed data after validating the requested element type.+void* TensorImpl::data(const ov::element::Type& type) {+ return _impl.data(type);+}++// Returns const typed data after validating the requested element type.+const void* TensorImpl::data(const ov::element::Type& type) const {+ return std::as_const(_impl).data(type);+}++// Returns writable typed data after validating the requested element type.+void* TensorImpl::data_rw(const ov::element::Type& type) {+ return _impl.data(type);+}++} // namespace js+} // namespace ovdiff --git a/src/bindings/js/node/tests/unit/infer_request.test.js b/src/bindings/js/node/tests/unit/infer_request.test.jsindex eac05c3b522..7b8f43ffa1b 100644--- a/src/bindings/js/node/tests/unit/infer_request.test.js+++ b/src/bindings/js/node/tests/unit/infer_request.test.js@@ -68,7 +68,10 @@ describe("ov.InferRequest tests", () => {const inputMessagePairs = [["string", "Cannot create a tensor from the passed Napi::Value."],[tensorData.slice(-10), /Memory allocated using shape and element::type mismatch/],- [new Float32Array(buffer, 4), "TypedArray.byteOffset has to be equal to zero."],+ [+ new Float32Array(buffer, 4),+ /TypedArray.byteOffset must be zero for zero-copy tensor construction./,+ ],[{}, /Invalid argument/], // Test for object that is not Tensor];@@ -403,3 +406,77 @@ describe("ov.InferRequest tests with missing outputs names", () => {assert.deepStrictEqual(Object.keys(result).length, 1);});});++describe("GC safety infer() / inferAsync()", () => {+ const { reluLargeModel } = testModels;+ const iterationCount = 5;+ const elementCount = lengthFromShape(reluLargeModel.inputShape);+ let compiledModel = null;+ let inferRequest = null;++ before(() => {+ const core = new ov.Core();+ const model = core.readModelSync(reluLargeModel.xml);+ compiledModel = core.compileModelSync(model, "CPU");+ inferRequest = compiledModel.createInferRequest();+ });++ it("original TypedArray is alive during infer()", async () => {+ function testInfer() {+ const inputData = new Float32Array(elementCount).fill(128.0);+ const tensor = new ov.Tensor(ov.element.f32, reluLargeModel.inputShape, inputData);+ return inferRequest.infer({ [reluLargeModel.inputName]: tensor });+ }++ const results = [];+ for (let i = 0; i < iterationCount; i++) {+ results.push(testInfer());+ }+ for (const result of results) {+ const data = result["relu_out"].getData();+ assert.strictEqual(data[0], 128.0, "First element should be 128");+ assert.strictEqual(data[elementCount - 1], 128.0, "Last element should be 128");+ }+ });++ it("original TypedArray is alive during inferAsync()", async () => {+ async function testInferAsync() {+ const inputData = new Float32Array(elementCount).fill(128.0);+ const tensor = new ov.Tensor(ov.element.f32, reluLargeModel.inputShape, inputData);+ return inferRequest.inferAsync({ [reluLargeModel.inputName]: tensor });+ }++ const promises = [];+ for (let i = 0; i < iterationCount; i++) {+ promises.push(testInferAsync());+ }+ if (typeof global.gc === "function") global.gc();+ const results = await Promise.all(promises);+ for (const result of results) {+ const data = result["relu_out"].getData();+ assert.strictEqual(data[0], 128.0, "First element should be 128");+ assert.strictEqual(data[elementCount - 1], 128.0, "Last element should be 128");+ }+ });++ it("Full-cycle tensor converting test", () => {+ function fillInferRequest(inferRequest) {+ // 1. TypedArray → TensorWrap+ const buf = new Float32Array(elementCount).fill(128.0);+ const tensor = new ov.Tensor(ov.element.f32, reluLargeModel.inputShape, buf);+ // 2. TensorWrap → ov::Tensor+ inferRequest.setInputTensor(tensor);+ }++ fillInferRequest(inferRequest);++ // Intermediate execution, where GC collects buffer+ if (typeof global.gc === "function") global.gc();++ // 3. the same ov::Tensor → new TensorWrap+ const sameTensor = inferRequest.getInputTensor();++ // 4. read data from buffer, but it is not available or rewrote+ assert.deepStrictEqual(sameTensor.getData(), new Float32Array(elementCount).fill(128.0));+ });+});diff --git a/src/bindings/js/node/tests/unit/tensor.test.js b/src/bindings/js/node/tests/unit/tensor.test.jsindex 95f99c0a027..6aa49f8f8d9 100644--- a/src/bindings/js/node/tests/unit/tensor.test.js+++ b/src/bindings/js/node/tests/unit/tensor.test.js@@ -43,6 +43,23 @@ describe("ov.Tensor tests", () => {assert.strictEqual(tensor.data.length, elemNum);});+ test("Memory safe after the original TypedArray goes out of scope", () => {+ const tensors = [];+ const iterationCount = 5;+ for (let i = 0; i < iterationCount; i++) {+ const shape = [1, 3, 1024, 1024];+ const itemCount = lengthFromShape(shape);+ const img = new Float32Array(itemCount).fill(128.0);+ tensors.push(new ov.Tensor(ov.element.f32, shape, img));+ }+ if (typeof global.gc === "function") global.gc();++ for (const tensor of tensors) {+ const view = tensor.getData();+ assert.strictEqual(view[0], 128.0);+ }+ });+describe("Tensor data", () => {it("set tensor data with element type", () => {params.forEach(([type, , data]) => {diff --git a/src/bindings/js/node/tests/unit/test_models/relu_large_model.xml b/src/bindings/js/node/tests/unit/test_models/relu_large_model.xmlnew file mode 100644index 00000000000..7067cb6b206--- /dev/null+++ b/src/bindings/js/node/tests/unit/test_models/relu_large_model.xml@@ -0,0 +1,49 @@+<?xml version="1.0"?>+<net name="relu_large_model" version="11">+ <layers>+ <layer id="0" name="data" type="Parameter" version="opset1">+ <data shape="1,3,1024,1024" element_type="f32" />+ <output>+ <port id="0" precision="FP32" names="data">+ <dim>1</dim>+ <dim>3</dim>+ <dim>1024</dim>+ <dim>1024</dim>+ </port>+ </output>+ </layer>+ <layer id="1" name="relu" type="ReLU" version="opset1">+ <input>+ <port id="0" precision="FP32">+ <dim>1</dim>+ <dim>3</dim>+ <dim>1024</dim>+ <dim>1024</dim>+ </port>+ </input>+ <output>+ <port id="1" precision="FP32" names="relu_out">+ <dim>1</dim>+ <dim>3</dim>+ <dim>1024</dim>+ <dim>1024</dim>+ </port>+ </output>+ </layer>+ <layer id="2" name="Result_2" type="Result" version="opset1">+ <input>+ <port id="0" precision="FP32">+ <dim>1</dim>+ <dim>3</dim>+ <dim>1024</dim>+ <dim>1024</dim>+ </port>+ </input>+ </layer>+ </layers>+ <edges>+ <edge from-layer="0" from-port="0" to-layer="1" to-port="0" />+ <edge from-layer="1" from-port="1" to-layer="2" to-port="0" />+ </edges>+ <rt_info />+</net>diff --git a/src/bindings/js/node/tests/utils.js b/src/bindings/js/node/tests/utils.jsindex 47459fb634d..836818a8044 100644--- a/src/bindings/js/node/tests/utils.js+++ b/src/bindings/js/node/tests/utils.js@@ -42,6 +42,13 @@ const testModels = {reluModel: {xml: getModelPath("relu_model.xml"),},+ reluLargeModel: {+ xml: getModelPath("relu_large_model.xml"),+ inputShape: [1, 3, 1024, 1024],+ outputShape: [1, 3, 1024, 1024],+ inputName: "data",+ outputName: "relu_out",+ },};module.exports = {