diff --git a/CHANGELOG.md b/CHANGELOG.md index 48f2cf54..0b990c15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,13 @@ Earlier release notes are in [docs/releases](docs/releases/). ## [Unreleased] +### Fixed + +- Return JavaScript-owned Node byte buffers so native workspace and restore + operations remain safe when workers close during background garbage collection. + This avoids the external-buffer shutdown race in Node 24.22.2 and 25.8.2 + without changing the public byte-array APIs. + ## [1.8.0] - 2026-11-18 ### Changed diff --git a/Cargo.lock b/Cargo.lock index d4aa918d..49a2d899 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -115,6 +115,7 @@ dependencies = [ "napi-derive", "serde", "serde_json", + "zeroize", ] [[package]] diff --git a/bindings/node/Cargo.toml b/bindings/node/Cargo.toml index c1d55a6e..e68165a7 100644 --- a/bindings/node/Cargo.toml +++ b/bindings/node/Cargo.toml @@ -16,6 +16,7 @@ napi = { version = "=3.12.2", features = ["serde-json"] } napi-derive = "=3.6.3" serde_json = "1" serde = { version = "1", features = ["derive"] } +zeroize = "1" [build-dependencies] napi-build = "=2.4.1" diff --git a/bindings/node/src/lib.rs b/bindings/node/src/lib.rs index e1dd8667..9056dfe0 100644 --- a/bindings/node/src/lib.rs +++ b/bindings/node/src/lib.rs @@ -1,5 +1,6 @@ //! Node binding for datafog-core. mod models; +mod output_buffer; mod workspace; pub use models::open_model_session; pub use workspace::{NativeRestoreStream, NativeWorkspace}; @@ -7,6 +8,7 @@ pub use workspace::{NativeRestoreStream, NativeWorkspace}; use napi::bindgen_prelude::Buffer; use napi::{Env, Error, Status, Unknown}; use napi_derive::napi; +use output_buffer::copied_output_buffer; use std::collections::BTreeMap; /// Workspace API contract implemented by this compiled Core. @@ -612,14 +614,16 @@ pub fn required_restore_items( let context = datafog_core::parse_privacy_context(&value).map_err(js_privacy_error)?; datafog_core::required_restore_items(&text, &context) .map_err(js_privacy_error) - .map(|items| { + .and_then(|items| { items .into_iter() - .map(|item| RestoreItem { - id: item.id().to_owned(), - token_ref: item.token_ref().to_owned(), - resolved_version: item.resolved_version().to_owned(), - payload: Buffer::from(item.payload()), + .map(|item| { + Ok(RestoreItem { + id: item.id().to_owned(), + token_ref: item.token_ref().to_owned(), + resolved_version: item.resolved_version().to_owned(), + payload: copied_output_buffer(&env, item.payload())?, + }) }) .collect() }) @@ -965,14 +969,16 @@ pub fn structured_required_restore_items( let context = datafog_core::parse_privacy_context(&value).map_err(js_privacy_error)?; datafog_core::structured::required_restore_items(&text, &context) .map_err(js_privacy_error) - .map(|items| { + .and_then(|items| { items .into_iter() - .map(|item| RestoreItem { - id: item.id().to_owned(), - token_ref: item.token_ref().to_owned(), - resolved_version: item.resolved_version().to_owned(), - payload: Buffer::from(item.payload()), + .map(|item| { + Ok(RestoreItem { + id: item.id().to_owned(), + token_ref: item.token_ref().to_owned(), + resolved_version: item.resolved_version().to_owned(), + payload: copied_output_buffer(&env, item.payload())?, + }) }) .collect() }) diff --git a/bindings/node/src/output_buffer.rs b/bindings/node/src/output_buffer.rs new file mode 100644 index 00000000..abaadbd5 --- /dev/null +++ b/bindings/node/src/output_buffer.rs @@ -0,0 +1,29 @@ +use napi::bindgen_prelude::{Buffer, FromNapiValue}; +use napi::{Env, Error, Status, sys}; +use std::ptr; + +/// Use JavaScript-owned storage so worker teardown cannot strand an external +/// Buffer finalizer on a closing Node environment (nodejs/node#67417). +pub(crate) fn copied_output_buffer(env: &Env, bytes: &[u8]) -> napi::Result { + let mut value = ptr::null_mut(); + // The input remains borrowed and live until the synchronous copy completes. + let status = unsafe { + sys::napi_create_buffer_copy( + env.raw(), + bytes.len(), + bytes.as_ptr().cast(), + ptr::null_mut(), + &mut value, + ) + }; + if status != sys::Status::napi_ok { + return Err(Error::new( + Status::from(status), + "Failed to copy output into a JavaScript-owned Buffer", + )); + } + // This value is a Buffer in the callback's live environment. Retaining its + // reference makes Buffer's output conversion reuse it without an external + // backing-store callback. + unsafe { Buffer::from_napi_value(env.raw(), value) } +} diff --git a/bindings/node/src/workspace.rs b/bindings/node/src/workspace.rs index b832844f..014c3fbf 100644 --- a/bindings/node/src/workspace.rs +++ b/bindings/node/src/workspace.rs @@ -1,16 +1,18 @@ mod conversation; mod stream; +use crate::copied_output_buffer; use datafog_core::workspace::{ self, ErrorCode, Head, PreparedChange, Workspace, WorkspaceError, WorkspaceFinding, WorkspaceInput, }; use napi::bindgen_prelude::Buffer; -use napi::{Error, Status}; +use napi::{Env, Error, Status}; use napi_derive::napi; use serde::Deserialize; use serde_json::json; use std::collections::BTreeMap; pub use stream::NativeRestoreStream; +use zeroize::Zeroizing; fn range_value(range: datafog_core::TextRange) -> serde_json::Value { json!({"start": range.start, "end": range.end}) @@ -396,15 +398,13 @@ impl NativeWorkspace { Ok(head_value(self.inner.head().map_err(from_error)?).to_string()) } #[napi(js_name = "namespace")] - pub fn namespace(&self) -> Result { - Ok(self.inner.namespace().map_err(from_error)?.to_vec().into()) + pub fn namespace(&self, env: Env) -> Result { + copied_output_buffer(&env, &self.inner.namespace().map_err(from_error)?) } #[napi(js_name = "export_bundle")] - pub fn export_bundle(&self) -> Result { - self.inner - .export_bundle() - .map(Buffer::from) - .map_err(from_error) + pub fn export_bundle(&self, env: Env) -> Result { + let bytes = Zeroizing::new(self.inner.export_bundle().map_err(from_error)?); + copied_output_buffer(&env, &bytes) } #[napi(js_name = "policy")] pub fn policy(&self) -> Result { @@ -672,13 +672,13 @@ impl NativeWorkspace { Ok(json!({"expectedHead": head_value(plan.expected_head().map_err(from_error)?), "candidateHead": head_value(plan.candidate_head().map_err(from_error)?)}).to_string()) } #[napi(js_name = "export_candidate_bundle")] - pub fn export_candidate_bundle(&self, handle: u32) -> Result { - Ok(self - .plan(handle)? - .export_candidate_bundle() - .map_err(from_error)? - .to_vec() - .into()) + pub fn export_candidate_bundle(&self, env: Env, handle: u32) -> Result { + copied_output_buffer( + &env, + self.plan(handle)? + .export_candidate_bundle() + .map_err(from_error)?, + ) } // Finalization is idempotent and cannot introduce a fallible cleanup result. #[napi(js_name = "release")] diff --git a/bindings/node/src/workspace/conversation.rs b/bindings/node/src/workspace/conversation.rs index e3824658..2d436ce6 100644 --- a/bindings/node/src/workspace/conversation.rs +++ b/bindings/node/src/workspace/conversation.rs @@ -123,16 +123,22 @@ impl NativeWorkspace { ) } #[napi(js_name = "conversation_for_site")] - pub fn conversation_for_site(&self, surface: String, site_id: String) -> Result { + pub fn conversation_for_site( + &self, + env: Env, + surface: String, + site_id: String, + ) -> Result { if surface.len().saturating_add(site_id.len()) > workspace::MAX_BUNDLE_BYTES { return Err(failure(ErrorCode::ResourceLimit)); } - Ok(self - .inner - .conversation_for_site(&surface, &site_id) - .map_err(from_error)? - .to_vec() - .into()) + copied_output_buffer( + &env, + &self + .inner + .conversation_for_site(&surface, &site_id) + .map_err(from_error)?, + ) } #[napi(js_name = "send_intent_status")] pub fn send_intent_status(&self, intent_json: String) -> Result { diff --git a/scripts/node-workspace-host-conformance.mjs b/scripts/node-workspace-host-conformance.mjs index de7b786c..d3313fbd 100644 --- a/scripts/node-workspace-host-conformance.mjs +++ b/scripts/node-workspace-host-conformance.mjs @@ -45,10 +45,10 @@ export async function verifyNodeWorkspaceHost() { for(const item of workers) assert.deepEqual((await item.ready).head,initial); const results=workers.map(({worker})=>new Promise((resolve,reject)=>{worker.once("message",resolve);worker.once("error",reject);worker.postMessage("save");})); const outcomes=await Promise.all(results),winners=outcomes.filter(result=>result.saved),losers=outcomes.filter(result=>!result.saved); - assert.equal(winners.length,1);assert.equal(losers.length,1); + assert.equal(winners.length,1,JSON.stringify(outcomes));assert.equal(losers.length,1,JSON.stringify(outcomes)); assert(winners[0].activated && winners[0].released); assert(!losers[0].activated && !losers[0].released); - assert(["workspace_conflict","storage_busy"].includes(losers[0].code)); + assert(["workspace_conflict","storage_busy"].includes(losers[0].code),JSON.stringify(outcomes)); assert.deepEqual(losers[0].head,initial); const winner=open(scope); try {assert.equal(winner.restore(winners[0].text),value);}finally{winner.close();} @@ -56,17 +56,29 @@ export async function verifyNodeWorkspaceHost() { // No-op candidates intentionally keep their head; CAS is not a delivery lock. const noOpScope={...scope,workspaceId:"noop_race"},noOpHead=initialize(noOpScope,23); const noOpWorkers=[]; - for(const operation of [25,26]) { + for(const operation of [25,26,27]) { const worker=new Worker(new URL("./node-workspace-host-worker.mjs",import.meta.url),{workerData:{database,key:new Uint8Array(key),scope:noOpScope,input:{text:"ordinary",scannerFindings:[],userSelections:[]},operationId:id(operation)}}); const ready=new Promise((resolve,reject)=>{worker.once("message",resolve);worker.once("error",reject);}); const item={worker,ready};workers.push(item);noOpWorkers.push(item); } for(const item of noOpWorkers)assert.deepEqual((await item.ready).head,noOpHead); - const noOpOutcomes=await Promise.all(noOpWorkers.map(({worker})=>new Promise((resolve,reject)=>{ + const saveNoOp=({worker})=>new Promise((resolve,reject)=>{ worker.once("message",resolve);worker.once("error",reject);worker.postMessage("save"); - }))); - assert(noOpOutcomes.every(result=>result.saved && result.activated && result.released)); - assert(noOpOutcomes.every(result=>JSON.stringify(result.head)===JSON.stringify(noOpHead))); + }); + // Even an unchanged head needs SQLite's writer lock; contention must fail closed. + const noOpBusy=new DatabaseSync(database,{timeout:250});noOpBusy.exec("BEGIN IMMEDIATE"); + try { + const blocked=await saveNoOp(noOpWorkers[2]); + assert.equal(blocked.code,"storage_busy",JSON.stringify(blocked)); + assert(!blocked.saved && !blocked.activated && !blocked.released,JSON.stringify(blocked)); + assert.deepEqual(blocked.head,noOpHead); + } finally {noOpBusy.exec("ROLLBACK");noOpBusy.close();} + // Both candidates were prepared from the same head. Serialize only writes so + // this CAS proof does not assume either writer finishes within the busy timeout. + const noOpOutcomes=[]; + for(const item of noOpWorkers.slice(0,2))noOpOutcomes.push(await saveNoOp(item)); + assert(noOpOutcomes.every(result=>result.saved && result.activated && result.released),JSON.stringify(noOpOutcomes)); + assert(noOpOutcomes.every(result=>JSON.stringify(result.head)===JSON.stringify(noOpHead)),JSON.stringify(noOpOutcomes)); // Equal revisions with different commit IDs must not pass a revision-only CAS. const sameRevisionScope={...scope,workspaceId:"same_revision"};initialize(sameRevisionScope,31); diff --git a/scripts/test-node-package.mjs b/scripts/test-node-package.mjs index fd2a66aa..acc06e94 100644 --- a/scripts/test-node-package.mjs +++ b/scripts/test-node-package.mjs @@ -23,9 +23,9 @@ function npm(arguments_, options) { return execFileSync("npm", arguments_, options); } -function run(command, arguments_, cwd) { - if (command === "npm") return npm(arguments_, { cwd, stdio: "inherit" }); - return execFileSync(command, arguments_, { cwd, stdio: "inherit" }); +function run(command, arguments_, cwd, timeout) { + if (command === "npm") return npm(arguments_, { cwd, stdio: "inherit", timeout }); + return execFileSync(command, arguments_, { cwd, stdio: "inherit", timeout }); } function fixtureRecords(name) { @@ -888,14 +888,20 @@ try { temporaryDirectory, ); - run( - process.execPath, - ["test-installed.mjs", fixturesDirectory], - temporaryDirectory, - ); + // Repeated natural exits exercise external-byte finalizers after worker cleanup. + for (let iteration = 0; iteration < 10; iteration++) { + console.log(`Installed Node consumer natural exit ${iteration + 1}/10`); + run( + process.execPath, + ["test-installed.mjs", fixturesDirectory], + temporaryDirectory, + 60_000, + ); + } run(process.execPath,["--expose-gc","native-node-workspace-gc.mjs","node-workspace-host.mjs","node-workspace-host-worker.mjs","node-workspace-host-crash.mjs","node-workspace-host-conformance.mjs"],temporaryDirectory); + run( process.execPath, [path.join(temporaryDirectory, "node_modules", "typescript", "bin", "tsc"), "--project", "tsconfig.json"],