Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
fix(streams): settle transform cancellation at promise reaction
ldm04f5e3af3912b
diff --git a/moli-renderer-v8/src/context_bootstrap/stream_adapter/callbacks.rs b/moli-renderer-v8/src/context_bootstrap/stream_adapter/callbacks.rsindex 7f247a5b2..613449c46 100644--- a/moli-renderer-v8/src/context_bootstrap/stream_adapter/callbacks.rs+++ b/moli-renderer-v8/src/context_bootstrap/stream_adapter/callbacks.rs@@ -376,9 +376,9 @@ pub(in crate::context_bootstrap) fn invoke_stored_stream_promise_algorithm<'s>(return Err(error);}};- if let Ok(promise) = v8::Local::<v8::Promise>::try_from(result) {- return Ok(Some(promise.into()));- }+ // Web IDL Promise<T> conversion creates a new capability even+ // when the callback returned a Promise. Resolving it observes+ // thenables and preserves the adoption boundary in this Realm.let Some(resolver) = v8::PromiseResolver::new(scope) else {return Err(v8::undefined(scope).into());};diff --git a/moli-renderer-v8/src/context_bootstrap/stream_adapter/writable.rs b/moli-renderer-v8/src/context_bootstrap/stream_adapter/writable.rsindex 1307b9227..cb172ff12 100644--- a/moli-renderer-v8/src/context_bootstrap/stream_adapter/writable.rs+++ b/moli-renderer-v8/src/context_bootstrap/stream_adapter/writable.rs@@ -745,21 +745,6 @@ pub(in crate::context_bootstrap::stream_adapter) fn transform_stream_readable_calet FinishAlgorithm::Cancel(algorithm) = algorithm else {unreachable!("readable cancel must claim the transform cancel algorithm")};- let writable_state_before_algorithm = writable_stream_snapshot(scope, writable).state();- if matches!(algorithm, TransformCancelAlgorithm::None) {- clear_transform_stream_terminal_algorithms(scope, writable);- let fulfillment_plan = transform_stream_snapshot(scope, writable, readable)- .plan_source_cancel_fulfillment_after_algorithm(writable_state_before_algorithm);- apply_transform_source_cancel_fulfillment(- scope,- writable,- residence,- reason,- fulfillment_plan,- );- rv.set(finish_promise.into());- return;- }let cancel_result =invoke_transform_stream_cancel_algorithm(scope, writable, reason, algorithm);clear_transform_stream_terminal_algorithms(scope, writable);@@ -775,20 +760,7 @@ pub(in crate::context_bootstrap::stream_adapter) fn transform_stream_readable_carv.set(finish_promise.into());return;};- // Freeze the writable-side outcome at the cancel-algorithm boundary.- // A synchronous controller error or abort from inside `cancel()` must- // reject this finish residence, while a controller action after- // `readable.cancel()` returns must not retroactively reject it.- let fulfillment_plan = transform_stream_snapshot(scope, writable, readable)- .plan_source_cancel_fulfillment_after_algorithm(writable_state_before_algorithm);- attach_transform_source_cancel_reactions(- scope,- cancel_promise,- writable,- residence,- reason,- fulfillment_plan,- );+ attach_transform_source_cancel_reactions(scope, cancel_promise, writable, residence, reason);rv.set(finish_promise.into());}@@ -932,21 +904,11 @@ fn attach_transform_source_cancel_reactions<'s>(writable: v8::Local<'s, v8::Object>,residence: v8::Local<'s, v8::Object>,reason: v8::Local<'s, v8::Value>,- fulfillment_plan: FinishSettlementPlan,) {- let data = v8::Array::new(scope, 4);+ let data = v8::Array::new(scope, 3);let _ = data.set_index(scope, 0, writable.into());let _ = data.set_index(scope, 1, residence.into());let _ = data.set_index(scope, 2, reason);- let reject_with_stored_error = matches!(- fulfillment_plan,- FinishSettlementPlan::RejectWithWritableStoredError- );- let _ = data.set_index(- scope,- 3,- v8::Boolean::new(scope, reject_with_stored_error).into(),- );publish_required_stream_promise_reactions(scope,cancel_promise,@@ -964,31 +926,33 @@ fn transform_source_cancel_fulfilled_callback<'s>(args: v8::FunctionCallbackArguments<'s>,mut rv: v8::ReturnValue<'_, v8::Value>,) {- let Some((writable, residence, reason, fulfillment_plan)) =+ let Some((writable, residence, reason)) =transform_source_cancel_reaction_values(scope, args.data())else {rv.set_undefined();return;};- let Some(_readable) = stream_slot_object(scope, writable, WRITABLE_STREAM_TARGET_READABLE_SLOT)+ let Some(readable) = stream_slot_object(scope, writable, WRITABLE_STREAM_TARGET_READABLE_SLOT).filter(|readable| !readable.is_null_or_undefined())else {reject_pending_read(scope, residence, reason);rv.set_undefined();return;};- apply_transform_source_cancel_fulfillment(scope, writable, residence, reason, fulfillment_plan);+ apply_transform_source_cancel_fulfillment(scope, writable, readable, residence, reason);rv.set_undefined();}fn apply_transform_source_cancel_fulfillment<'s>(scope: &mut v8::PinScope<'s, '_>,writable: v8::Local<'s, v8::Object>,+ readable: v8::Local<'s, v8::Object>,residence: v8::Local<'s, v8::Object>,reason: v8::Local<'s, v8::Value>,- fulfillment_plan: FinishSettlementPlan,) {- match fulfillment_plan {+ match transform_stream_snapshot(scope, writable, readable)+ .plan_finish_settlement(FinishOperation::ReadableCancel, AlgorithmOutcome::Fulfilled)+ {FinishSettlementPlan::RejectWithWritableStoredError => {let error = writable_stream_stored_error(scope, writable).unwrap_or(reason);reject_pending_read(scope, residence, error);@@ -1006,7 +970,7 @@ fn transform_source_cancel_rejected_callback<'s>(args: v8::FunctionCallbackArguments<'s>,mut rv: v8::ReturnValue<'_, v8::Value>,) {- let Some((writable, residence, _, _)) =+ let Some((writable, residence, _)) =transform_source_cancel_reaction_values(scope, args.data())else {rv.set_undefined();@@ -1039,7 +1003,6 @@ fn transform_source_cancel_reaction_values<'s>(v8::Local<'s, v8::Object>,v8::Local<'s, v8::Object>,v8::Local<'s, v8::Value>,- FinishSettlementPlan,)> {let data = v8::Local::<v8::Array>::try_from(data).ok()?;let writable = data@@ -1051,15 +1014,7 @@ fn transform_source_cancel_reaction_values<'s>(let reason = data.get_index(scope, 2).unwrap_or_else(|| v8::undefined(scope).into());- let fulfillment_plan = if data- .get_index(scope, 3)- .is_some_and(|value| value.boolean_value(scope))- {- FinishSettlementPlan::RejectWithWritableStoredError- } else {- FinishSettlementPlan::ErrorWritableWithOriginalReasonAndResolve- };- Some((writable, residence, reason, fulfillment_plan))+ Some((writable, residence, reason))}fn transform_stream_sink_abort_algorithm<'s>(@@ -1100,11 +1055,6 @@ fn transform_stream_sink_abort_algorithm_in_relevant_realm<'s>(let FinishAlgorithm::Cancel(algorithm) = algorithm else {unreachable!("writable abort must claim the transform cancel algorithm")};- if matches!(algorithm, TransformCancelAlgorithm::None) {- clear_transform_stream_terminal_algorithms(scope, writable);- apply_transform_sink_abort_fulfillment(scope, writable, readable, residence, reason);- return Some(finish_promise.into());- }let cancel_result =invoke_transform_stream_cancel_algorithm(scope, writable, reason, algorithm);clear_transform_stream_terminal_algorithms(scope, writable);@@ -1425,7 +1375,18 @@ pub(in crate::context_bootstrap) fn set_transform_stream_start_result<'s>(readable: v8::Local<'s, v8::Object>,result: Option<v8::Local<'s, v8::Value>>,) {- let Some(promise) = normalize_stream_algorithm_result(scope, result) else {+ // InitializeTransformStream gives the underlying controllers an algorithm+ // returning the shared startPromise, resolved with transformer.start's+ // result. SetUpWritableStreamDefaultController in turn resolves its own+ // start promise with that result. Preserve this adoption: writable must+ // remain Erroring until the controller's start reaction can run.+ let result = result.unwrap_or_else(|| v8::undefined(scope).into());+ let Some(start_promise) = resolved_promise_value(scope, result) else {+ return;+ };+ let Some(promise) = resolved_promise_value(scope, start_promise)+ .and_then(|promise| v8::Local::<v8::Promise>::try_from(promise).ok())+ else {return;};let data = transform_promise_reaction_data(scope, writable, readable);diff --git a/moli-renderer-v8/src/script_vm/tests/streams.rs b/moli-renderer-v8/src/script_vm/tests/streams.rsindex db163ad60..5364e51d8 100644--- a/moli-renderer-v8/src/script_vm/tests/streams.rs+++ b/moli-renderer-v8/src/script_vm/tests/streams.rs@@ -1,6 +1,7 @@use super::*;mod compression;+mod transform_finish;fn stream_test_vm() -> StandaloneScriptVmHarness {new_storage_test_vm("https://stream-runtime.test/")@@ -404,10 +405,12 @@ fn transform_stream_cancel_callback_uses_one_shared_terminal_residence() {}});const nestedCancelPromise = nested.readable.cancel(nestedCancelReason);+ nested.writable.getWriter().closed.catch(error => {+ events.push(`nested:closed:${error === nestedAbortReason}`);+ });Promise.allSettled([nestedCancelPromise, nestedAbortPromise]).then(results => {events.push(- `nested:settled:${nestedCalls}:${results[0].reason === nestedAbortReason}:` +- `${results[1].reason === nestedAbortReason}`+ `nested:settled:${nestedCalls}:${results[0].status}:${results[1].status}`);});})()@@ -438,7 +441,8 @@ JSON.stringify({abortFulfilled:__transformCancelCallbackEvents.includes("abort:fulfilled"),nestedSharedFinish:- __transformCancelCallbackEvents.includes("nested:settled:1:true:true"),+ __transformCancelCallbackEvents.includes("nested:settled:1:fulfilled:fulfilled") &&+ __transformCancelCallbackEvents.includes("nested:closed:true"),unexpectedFlush:__transformCancelCallbackEvents.some(event =>event.includes("unexpected-flush")@@ -3795,7 +3799,7 @@ fn readable_stream_pipe_through_duck_typed_pass_through_drains_async_pulls() {assert_eq!(result,- r#"{"result":"[1,2,3,4,5]","events":["pull:1","write:1","pull:2","pull:3","write:2","pull:4","write:3","pull:5","write:4","pull:6","write:5","close-writable","resolved"]}"#+ r#"{"result":"[1,2,3,4,5]","events":["pull:1","write:1","pull:2","write:2","pull:3","write:3","pull:4","write:4","pull:5","write:5","pull:6","close-writable","resolved"]}"#);}diff --git a/moli-renderer-v8/src/script_vm/tests/streams/transform_finish.rs b/moli-renderer-v8/src/script_vm/tests/streams/transform_finish.rsnew file mode 100644index 000000000..5a26c7eae--- /dev/null+++ b/moli-renderer-v8/src/script_vm/tests/streams/transform_finish.rs@@ -0,0 +1,154 @@+use super::*;++#[test]+fn transform_finish_pending_cancel_observes_writable_error_at_fulfillment() {+ let mut vm = stream_test_vm();+ vm.eval(+ r#"+(() => {+ globalThis.__finishEvents = [];+ const error = { name: 'controller error' };+ let controller, release;+ const gate = new Promise(resolve => { release = resolve; });+ const stream = new TransformStream({+ start(c) { controller = c; },+ cancel() { return gate; }+ });+ const writer = stream.writable.getWriter();+ stream.readable.cancel({ name: 'cancel reason' }).then(+ () => __finishEvents.push('cancel:fulfilled'),+ reason => __finishEvents.push(`cancel:${reason === error}`)+ );+ writer.closed.catch(reason => {+ __finishEvents.push(`closed:${reason === error}`);+ // The writable has completed Erroring -> Errored before cancel can finish.+ release();+ });+ controller.error(error);+})()+"#,+ )+ .expect("pending cancel setup");+ assert_eq!(+ vm.eval("JSON.stringify(__finishEvents)")+ .expect("pending cancel result"),+ r#"["closed:true","cancel:true"]"#+ );+}++#[test]+fn transform_finish_pending_cancel_rejection_keeps_callback_error() {+ let mut vm = stream_test_vm();+ vm.eval(+ r#"+(() => {+ globalThis.__finishEvents = [];+ const storedError = { name: 'controller error' };+ const callbackError = { name: 'callback error' };+ let controller, reject;+ const gate = new Promise((_, rejectPromise) => { reject = rejectPromise; });+ const stream = new TransformStream({+ start(c) { controller = c; },+ cancel() { return gate; }+ });+ const writer = stream.writable.getWriter();+ stream.readable.cancel({ name: 'cancel reason' }).then(+ () => __finishEvents.push('cancel:fulfilled'),+ reason => __finishEvents.push(`cancel:${reason === callbackError}`)+ );+ writer.closed.catch(reason => {+ __finishEvents.push(`closed:${reason === storedError}`);+ reject(callbackError);+ });+ controller.error(storedError);+})()+"#,+ )+ .expect("rejecting cancel setup");+ assert_eq!(+ vm.eval("JSON.stringify(__finishEvents)")+ .expect("rejecting cancel result"),+ r#"["closed:true","cancel:true"]"#+ );+}++#[test]+fn transform_finish_cancellation_observes_algorithm_return_kind() {+ let mut vm = stream_test_vm();+ vm.eval(+ r#"+(async () => {+ globalThis.__finishEvents = [];+ for (const during of [false, true]) {+ for (const kind of ['absent', 'undefined', 'promise']) {+ if (during && kind === 'absent') continue;+ const error = {};+ let controller, calls = 0;+ const transformer = { start(c) { controller = c; } };+ if (kind !== 'absent') transformer.cancel = () => {+ calls++;+ if (during) controller.error(error);+ if (kind === 'promise') return Promise.resolve();+ };+ const stream = new TransformStream(transformer);+ const writer = stream.writable.getWriter();+ const closed = writer.closed.then(() => false, reason => reason === error);+ const canceled = stream.readable.cancel({}).then(+ () => 'fulfilled', reason => reason === error ? 'stored-error' : 'wrong-error'+ );+ if (!during) controller.error(error);+ __finishEvents.push(`${kind}:${during}:${await canceled}:${await closed}:${calls}`);+ }+ }+})()+"#,+ )+ .expect("cancel return kind setup");+ assert_eq!(+ vm.eval("JSON.stringify(__finishEvents)")+ .expect("cancel return kind results"),+ r#"["absent:false:fulfilled:true:0","undefined:false:fulfilled:true:1","promise:false:stored-error:true:1","undefined:true:fulfilled:true:1","promise:true:stored-error:true:1"]"#+ );+}++#[test]+fn transform_finish_webidl_callback_adopts_returned_promise_once() {+ let mut vm = stream_test_vm();+ vm.eval(+ r#"+(async () => {+ globalThis.__finishEvents = [];+ for (const throws of [false, true]) {+ let gets = 0, calls = 0;+ const error = {};+ const returned = Promise.resolve();+ const then = Promise.prototype.then;+ Object.defineProperty(returned, 'then', {+ get() {+ gets++;+ if (throws) throw error;+ return function(...args) {+ calls++;+ return Reflect.apply(then, this, args);+ };+ }+ });+ const stream = new TransformStream({ cancel() { return returned; } });+ const writer = stream.writable.getWriter();+ const cancelReason = {};+ const closed = writer.closed.then(() => false, reason => reason === (throws ? error : cancelReason));+ const result = await stream.readable.cancel(cancelReason).then(+ () => 'fulfilled', reason => reason === error ? 'callback-error' : 'wrong-error'+ );+ __finishEvents.push(`${throws}:${gets}:${calls}:${result}:${await closed}`);+ }+})()+"#,+ )+ .expect("Web IDL returned Promise setup");+ assert_eq!(+ vm.eval("JSON.stringify(__finishEvents)")+ .expect("Web IDL returned Promise result"),+ r#"["false:1:1:fulfilled:true","true:1:0:callback-error:true"]"#+ );+}diff --git a/moli-streams/src/transform.rs b/moli-streams/src/transform.rsindex 83527dc8e..9e414bdcc 100644--- a/moli-streams/src/transform.rs+++ b/moli-streams/src/transform.rs@@ -353,28 +353,6 @@ impl TransformSnapshot {}}- /// Choose the readable-cancel fulfillment outcome at the synchronous- /// cancel-algorithm boundary. An error started by the cancel callback- /// itself wins the shared finish residence. An error already in progress,- /// or one started after the callback returns, does not retroactively reject- /// the readable cancellation.- #[must_use]- pub const fn plan_source_cancel_fulfillment_after_algorithm(- self,- writable_state_before_algorithm: WritableState,- ) -> FinishSettlementPlan {- if matches!(writable_state_before_algorithm, WritableState::Writable)- && matches!(- self.writable_state,- WritableState::Erroring | WritableState::Errored- )- {- FinishSettlementPlan::RejectWithWritableStoredError- } else {- FinishSettlementPlan::ErrorWritableWithOriginalReasonAndResolve- }- }-#[must_use]pub const fn plan_finish_setup_failure(self,@@ -854,47 +832,6 @@ mod tests {);}- #[test]- fn source_cancel_fulfillment_freezes_reentrant_writable_errors() {- let readable_snapshot = readable(ReadableState::Closed, 0, false, 1.0, 0.0);- let writable = snapshot(- readable_snapshot,- WritableState::Writable,- TransformMode::Callback,- );- let erroring = snapshot(- readable_snapshot,- WritableState::Erroring,- TransformMode::Callback,- );- let errored = snapshot(- readable_snapshot,- WritableState::Errored,- TransformMode::Callback,- );-- assert_eq!(- writable.plan_source_cancel_fulfillment_after_algorithm(WritableState::Writable),- FinishSettlementPlan::ErrorWritableWithOriginalReasonAndResolve- );- assert_eq!(- erroring.plan_source_cancel_fulfillment_after_algorithm(WritableState::Writable),- FinishSettlementPlan::RejectWithWritableStoredError- );- assert_eq!(- errored.plan_source_cancel_fulfillment_after_algorithm(WritableState::Writable),- FinishSettlementPlan::RejectWithWritableStoredError- );- assert_eq!(- erroring.plan_source_cancel_fulfillment_after_algorithm(WritableState::Erroring),- FinishSettlementPlan::ErrorWritableWithOriginalReasonAndResolve- );- assert_eq!(- errored.plan_source_cancel_fulfillment_after_algorithm(WritableState::Erroring),- FinishSettlementPlan::ErrorWritableWithOriginalReasonAndResolve- );- }-#[test]fn setup_failures_and_enqueue_failures_preserve_error_ownership() {let current = snapshot(