From 262eb45c7e359faa10f581fdff729bf1e130951f Mon Sep 17 00:00:00 2001 From: ldm0 Date: Mon, 21 Sep 2026 04:43:04 +0800 Subject: [PATCH] fix(navigation): preserve queued traversal targets and results Reject retained traversal results in their original realm when the target LocalWindow retires before the history task runs. Complete the Promise reactions without firing navigation events or applying stale history. Keep PageVm namespaces and exact task ownership checks when consuming the payload, and leave classic History tasks without results as no-op cleanup. Choose back/forward destinations from the committed current entry so repeated pending calls share the same destination and result Promises. Cover removed and reinserted frames, same- and cross-document traversals, rejection realms and callback completion, and PageVm task-ID reuse. --- .../page/tests/same_document_history.rs | 1 + .../stale_history_traversal.rs | 168 ++++++++++++++++++ moli-renderer-v8/src/context_bootstrap.rs | 4 +- .../navigation_traversal_execution.rs | 15 +- .../navigation_traversal_plan.rs | 5 +- .../src/native_bridge/history_queue.rs | 9 - .../src/page_task_queue/history_traversal.rs | 1 + .../runtime/page_vm/page_history_traversal.rs | 20 ++- .../page_vm/tests/history_traversal.rs | 130 +++++++++++++- .../src/script_vm/history_traversal.rs | 46 ++++- 10 files changed, 368 insertions(+), 31 deletions(-) create mode 100644 moli-protocol/src/domains/page/tests/same_document_history/stale_history_traversal.rs diff --git a/moli-protocol/src/domains/page/tests/same_document_history.rs b/moli-protocol/src/domains/page/tests/same_document_history.rs index 836a26d2388..a229d071156 100644 --- a/moli-protocol/src/domains/page/tests/same_document_history.rs +++ b/moli-protocol/src/domains/page/tests/same_document_history.rs @@ -3,6 +3,7 @@ use super::*; mod child_history_traversal; mod popup_network_navigation; mod response_gate; +mod stale_history_traversal; use response_gate::ResponseGate; diff --git a/moli-protocol/src/domains/page/tests/same_document_history/stale_history_traversal.rs b/moli-protocol/src/domains/page/tests/same_document_history/stale_history_traversal.rs new file mode 100644 index 00000000000..040ea1010a6 --- /dev/null +++ b/moli-protocol/src/domains/page/tests/same_document_history/stale_history_traversal.rs @@ -0,0 +1,168 @@ +use super::*; + +const REPEATED_PROBE: &str = r#"(async () => { + const method=METHOD, child=CHILD; + let frame,win=window; + if(child) { + frame=document.createElement('iframe');frame.src='history.html?repeated'; + const loaded=new Promise(resolve=>frame.onload=resolve); + document.body.append(frame);await loaded; + await new Promise(resolve=>setTimeout(resolve,0)); + win=frame.contentWindow; + } + const nav=win.navigation,firstKey=nav.currentEntry.key; + await nav.navigate('#one').finished; + await nav.navigate('#two').finished; + if(method==='forward')await nav.traverseTo(firstKey).finished; + const index=nav.currentEntry.index; + const destination=nav.entries()[method==='forward'?index+1:method==='back'?index-1:0]; + const events=[]; + nav.addEventListener('navigate',event=>events.push({ + type:event.navigationType,key:event.destination.key===destination.key + })); + const begin=()=>method==='traverseTo'?nav.traverseTo(firstKey):nav[method](); + const a=begin(),b=begin(); + const queuedIndex=nav.currentEntry.index; + const outcomes=await Promise.all([a.committed,a.finished,b.committed,b.finished].map(p=> + p.then(entry=>entry.key===destination.key,error=>error.name))); + const result={outcomes,events, + sharedCommitted:a.committed===b.committed, + sharedFinished:a.finished===b.finished, + unchangedWhileQueued:queuedIndex===index, + destination:nav.currentEntry.key===destination.key + }; + if(frame)frame.remove(); + return result; +})()"#; + +#[tokio::test(flavor = "multi_thread")] +async fn queued_navigation_api_calls_reuse_the_committed_entry_destination() { + for child in [false, true] { + for method in ["back", "forward", "traverseTo"] { + let mut page = SameDocumentPage::new().await; + let result = page + .evaluate( + &REPEATED_PROBE + .replace("METHOD", &json!(method).to_string()) + .replace("CHILD", &child.to_string()), + ) + .await; + assert_eq!( + result, + json!({ + "outcomes":[true,true,true,true], + "events":[{"type":"traverse", "key":true}], + "sharedCommitted":true, + "sharedFinished":true, + "unchangedWhileQueued":true, + "destination":true, + }), + "{child}/{method}: {result}" + ); + } + } +} + +const REMOVAL_PROBE: &str = r#"(async () => { + const method=METHOD, crossDocument=CROSS_DOCUMENT, reinsert=REINSERT; + const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms)); + const frame=document.createElement('iframe'); + frame.src='history.html?first'; + let loaded=new Promise(resolve=>frame.onload=resolve); + document.body.append(frame);await loaded;await sleep(0); + const firstKey=frame.contentWindow.navigation.currentEntry.key; + if(crossDocument) { + loaded=new Promise(resolve=>frame.onload=resolve); + frame.contentWindow.location.href='history.html?second'; + await loaded;await sleep(0); + } else { + await frame.contentWindow.navigation.navigate('#second').finished; + } + if(method==='forward') { + if(crossDocument) { + loaded=new Promise(resolve=>frame.onload=resolve); + frame.contentWindow.history.back();await loaded;await sleep(0); + } else { + await frame.contentWindow.navigation.back().finished; + } + } + const win=frame.contentWindow,nav=win.navigation; + const Exception=win.DOMException,PromiseConstructor=win.Promise; + const events=[],order=[],errors=[{},{}],states=[{},{}]; + for(const type of ['navigate','navigateerror','navigatesuccess','currententrychange']) { + nav.addEventListener(type,()=>events.push(type)); + } + for(const type of ['popstate','hashchange'])win.addEventListener(type,()=>events.push(type)); + const results=[0,1].map(()=>method==='traverseTo'?nav.traverseTo(firstKey):nav[method]()); + const promiseRealms=results.every(result=> + result.committed instanceof PromiseConstructor && result.finished instanceof PromiseConstructor); + const reactions=results.flatMap((result,index)=>['committed','finished'].map(key=> + result[key].then( + ()=>{states[index][key]='fulfilled';order.push(index+':'+key)}, + error=>{states[index][key]=error.name;errors[index][key]=error;order.push(index+':'+key)} + ) + )); + frame.remove(); + let replacementLoaded=Promise.resolve(); + if(reinsert) { + frame.src='history.html?replacement'; + replacementLoaded=new Promise(resolve=>frame.onload=resolve); + document.body.append(frame); + } + await Promise.all(reactions); + await replacementLoaded; + await sleep(0); + const result={ + events,states,promiseRealms, + errorRealms:errors.every(pair=>['committed','finished'].every(key=> + pair[key] instanceof Exception && !(pair[key] instanceof DOMException))), + sameErrors:errors.every(pair=>pair.committed===pair.finished), + ordered:errors.every((_,index)=>order.indexOf(index+':committed') { @@ -381,9 +383,16 @@ fn reject_cross_document_traversal( scope: &mut v8::PinScope<'_, '_>, traversal: &PendingCrossDocumentTraversal, ) { - if traversal.results.is_empty() { + reject_canceled_history_traversal_results(scope, &traversal.results); +} + +pub(crate) fn reject_canceled_history_traversal_results( + scope: &mut v8::PinScope<'_, '_>, + results: &[PendingNavigationResult], +) { + if results.is_empty() { return; } let error = navigation_dom_exception(scope, "Navigation was canceled", "AbortError"); - reject_pending_navigation_results(scope, &traversal.results, error); + reject_pending_navigation_results(scope, results, error); } diff --git a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs index 8a870a5c0ff..06e20f05506 100644 --- a/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs +++ b/moli-renderer-v8/src/context_bootstrap/navigation_traversal_plan.rs @@ -82,8 +82,9 @@ pub(super) fn navigation_delta_traversal_plan<'s>( )); } let history = window_history_for_holder(scope, owner)?; - let current_index = pending_history_traversal_target_index(scope, history) - .unwrap_or_else(|| history_index(scope, history)) as i64; + // Navigation API methods select an entry relative to the committed + // current entry. Repeated calls before the task runs share that target. + let current_index = i64::from(history_index(scope, history)); let entries = history_entries(scope, history)?; let current_entry = navigation_current_entry(scope, owner); let current_navigation_index = current_entry diff --git a/moli-renderer-v8/src/native_bridge/history_queue.rs b/moli-renderer-v8/src/native_bridge/history_queue.rs index 032c5ec8e28..e8984743475 100644 --- a/moli-renderer-v8/src/native_bridge/history_queue.rs +++ b/moli-renderer-v8/src/native_bridge/history_queue.rs @@ -728,15 +728,6 @@ impl PageScriptHost { .take_pending_history_traversal_task(task_id) } - pub(crate) fn discard_pending_history_traversal_task( - &mut self, - task_id: RendererPageHistoryTraversalTaskId, - ) -> bool { - self.history_queue - .take_pending_history_traversal_task(task_id) - .is_some() - } - pub(crate) fn current_pending_navigation_api_task_owner( &self, task_id: RendererPageNavigationApiTaskId, diff --git a/moli-renderer-v8/src/page_task_queue/history_traversal.rs b/moli-renderer-v8/src/page_task_queue/history_traversal.rs index eca70d3484a..738ad796009 100644 --- a/moli-renderer-v8/src/page_task_queue/history_traversal.rs +++ b/moli-renderer-v8/src/page_task_queue/history_traversal.rs @@ -185,6 +185,7 @@ impl RendererPageHistoryTraversalProducer { #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub(crate) enum PageHistoryTraversalTargetEffect { AppliedToCurrentOwner, + RejectedStaleResults, DiscardedStaleOwner { current_owner: Option, }, diff --git a/moli-renderer-v8/src/runtime/page_vm/page_history_traversal.rs b/moli-renderer-v8/src/runtime/page_vm/page_history_traversal.rs index eb8b7116539..7d2888af489 100644 --- a/moli-renderer-v8/src/runtime/page_vm/page_history_traversal.rs +++ b/moli-renderer-v8/src/runtime/page_vm/page_history_traversal.rs @@ -10,12 +10,14 @@ use super::{IntoPageTaskCompletion, PageTaskCompletion, PageVm}; impl IntoPageTaskCompletion for PageHistoryTraversalTurnAction { fn into_page_task_completion(self) -> PageTaskCompletion { match self.target_effect { - PageHistoryTraversalTargetEffect::AppliedToCurrentOwner => { + PageHistoryTraversalTargetEffect::AppliedToCurrentOwner + | PageHistoryTraversalTargetEffect::RejectedStaleResults => { // A traversal can dispatch Navigation API, popstate, hashchange // and child-traversal callbacks, and can itself publish child // work. Preserve the established full post-checkpoint // reconciliation even when a particular traversal has no - // registered listener. + // registered listener. Rejected results can also publish work + // through their Promise reactions after the target retires. PageTaskCompletion::CallbackCompletion } PageHistoryTraversalTargetEffect::DiscardedStaleOwner { .. } => { @@ -70,9 +72,9 @@ impl PageVm { // Local task ids restart in each PageVm. Only a same-root stale // task may clean this Host's retained payload; an old PageVm task // must never consume a naturally reused id in its replacement. - if owner.root_document() == self.document_lifecycle.identity().document { - self.vm_mut().discard_stale_history_traversal_task(task_id); - } + let rejected_results = owner.root_document() + == self.document_lifecycle.identity().document + && self.vm_mut().reject_stale_history_traversal_results(task)?; tracing::debug!( ?owner, ?current, @@ -80,8 +82,12 @@ impl PageVm { ?kind, "discarded stale exact-owner history traversal" ); - PageHistoryTraversalTargetEffect::DiscardedStaleOwner { - current_owner: current.map(|(owner, _)| owner), + if rejected_results { + PageHistoryTraversalTargetEffect::RejectedStaleResults + } else { + PageHistoryTraversalTargetEffect::DiscardedStaleOwner { + current_owner: current.map(|(owner, _)| owner), + } } }; let action = PageHistoryTraversalTurnAction { diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/history_traversal.rs b/moli-renderer-v8/src/runtime/page_vm/tests/history_traversal.rs index 5729424b748..2b7e9f29ceb 100644 --- a/moli-renderer-v8/src/runtime/page_vm/tests/history_traversal.rs +++ b/moli-renderer-v8/src/runtime/page_vm/tests/history_traversal.rs @@ -319,6 +319,108 @@ history.back(); .expect("history traversal listener document.open completion test should run"); } +#[tokio::test(flavor = "current_thread")] +async fn history_traversal_rejects_removed_child_results_at_selected_completion() { + run_page_vm_async_test(async move { + let loader = + crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader"); + let document_url = Url::parse("https://example.com/history-removed-results").unwrap(); + let (mut page_vm, _resource_source, _owner_wake_rx) = + page_vm_with_bound_task_sources_and_owner_wake(&loader, document_url); + page_vm.vm_mut().eval( + r##" +const frame = document.createElement("iframe"); +frame.id = "history-removed-results"; +frame.srcdoc = "child"; +document.body.appendChild(frame); +"created" +"##, + )?; + run_expected_child_frame_task_source_after_realm_prerequisite_for_wait( + &mut page_vm, + ChildFrameSemanticTurnKind::NavigationCommit, + "removed results srcdoc commit", + ) + .await; + materialize_child_realm_through_page_turn_for_test(&mut page_vm, "history-removed-results")?; + page_vm.vm_mut().eval( + r##" +globalThis.__removedTraversalLog = []; +globalThis.__removedTraversalReasons = []; +const child = frame.contentWindow; +const ChildDOMException = child.DOMException; +const key = child.navigation.currentEntry.key; +child.history.pushState(null, "", "about:srcdoc#queued"); +"prepared" +"##, + )?; + // Finish the setup navigation before observing the queued traversal. + // Removing the frame in the same script as pushState would also cancel + // that earlier navigation's pending success microtask. + page_vm.vm_mut().eval( + r##" +for (const type of ["navigate", "navigateerror", "popstate", "hashchange"]) { + const target = type.startsWith("navigate") ? child.navigation : child; + target.addEventListener(type, () => __removedTraversalLog.push(type)); +} +const result = child.navigation.traverseTo(key); +for (const name of ["committed", "finished"]) { + result[name].then( + () => __removedTraversalLog.push(name + ":fulfilled"), + error => { + __removedTraversalReasons.push(error); + __removedTraversalLog.push([ + name, error.name, error instanceof ChildDOMException, + error instanceof DOMException + ].join(":")); + const script = document.createElement("script"); + script.textContent = "__removedTraversalLog.push('reaction-script')"; + document.body.appendChild(script); + } + ); +} +child.DOMException = () => { throw new Error("author constructor must not run"); }; +frame.remove(); +"retired" +"##, + )?; + let task = page_vm + .take_history_traversal_body_task_for_test() + .expect("the removed child retains its queued traversal results"); + let outcome = page_vm.apply_selected_page_history_traversal_turn(task)?; + assert_eq!( + outcome.action.target_effect, + PageHistoryTraversalTargetEffect::RejectedStaleResults + ); + assert_eq!( + page_vm.vm_mut().eval_without_microtask_checkpoint_for_test( + "__removedTraversalLog.join('|')", + )?, + "", + "the rejection body must leave Promise reactions to selected-task completion" + ); + let completion = outcome.action.into_page_task_completion(); + assert!(matches!(completion, PageTaskCompletion::CallbackCompletion)); + page_vm + .finish_selected_page_task_completion(completion, &loader) + .await?; + assert_eq!( + page_vm.vm_mut().eval("__removedTraversalLog.join('|')")?, + "committed:AbortError:true:false|reaction-script|finished:AbortError:true:false|reaction-script" + ); + assert_eq!( + page_vm.vm_mut().eval( + "String(__removedTraversalReasons.length === 2 && __removedTraversalReasons[0] === __removedTraversalReasons[1])", + )?, + "true" + ); + assert!(page_vm.take_history_traversal_body_task_for_test().is_none()); + Ok::<_, anyhow::Error>(()) + }) + .await + .expect("removed traversal results should settle at the selected task boundary"); +} + #[tokio::test(flavor = "current_thread")] async fn history_traversal_discards_a_retired_child_local_window() { run_page_vm_async_test(async move { @@ -431,7 +533,7 @@ fn history_traversal_rejects_a_real_page_vm_replacement_id_collision() { .vm_mut() .advance_timers_until_deadline_for_test(&loader) .await?; - page_vm.vm_mut().eval("history.back(); 'queued'")?; + page_vm.vm_mut().eval("navigation.back(); 'queued'")?; let retired_root = page_vm.document_lifecycle.identity().document; let replacement_url = format!("{base_url}/replacement.html"); @@ -463,7 +565,19 @@ fn history_traversal_rejects_a_real_page_vm_replacement_id_collision() { .vm_mut() .advance_timers_until_deadline_for_test(&loader) .await?; - page_vm.vm_mut().eval("history.back(); 'queued'")?; + page_vm.vm_mut().eval( + r#" +globalThis.__replacementTraversalResults = []; +const result = navigation.back(); +for (const key of ["committed", "finished"]) { + result[key].then( + () => __replacementTraversalResults.push(key), + error => __replacementTraversalResults.push(error.name) + ); +} +"queued" +"#, + )?; let stale = page_vm .claim_exact_selected_page_task_for_test( @@ -491,6 +605,14 @@ fn history_traversal_rejects_a_real_page_vm_replacement_id_collision() { "retired traversal must not checkpoint or advance replacement runtime work" ); + assert_eq!( + page_vm.vm_mut().eval_without_microtask_checkpoint_for_test( + "__replacementTraversalResults.join('|')", + )?, + "", + "retired PageVm ids must not reject the replacement's pending results" + ); + let current = page_vm .claim_exact_selected_page_task_for_test( PageSelectedTaskTestSelector::HistoryTraversal, @@ -518,6 +640,10 @@ fn history_traversal_rejects_a_real_page_vm_replacement_id_collision() { .run_claimed_selected_page_task_for_test(current, &loader) .await?; assert_eq!(page_vm.vm_mut().eval("location.hash")?, ""); + assert_eq!( + page_vm.vm_mut().eval("__replacementTraversalResults.join('|')")?, + "committed|finished" + ); Ok::<_, anyhow::Error>(()) }) .await diff --git a/moli-renderer-v8/src/script_vm/history_traversal.rs b/moli-renderer-v8/src/script_vm/history_traversal.rs index 536e59bf79a..511ebf2b987 100644 --- a/moli-renderer-v8/src/script_vm/history_traversal.rs +++ b/moli-renderer-v8/src/script_vm/history_traversal.rs @@ -2,9 +2,10 @@ use anyhow::{Result, anyhow}; use super::ScriptVm; use crate::{ + native_bridge::PendingHistoryTraversalAction, page_task_queue::{ - RendererPageHistoryTraversalOwner, RendererPageHistoryTraversalTaskId, - RendererPageHistoryTraversalTaskKind, + RendererPageHistoryTraversalOwner, RendererPageHistoryTraversalTask, + RendererPageHistoryTraversalTaskId, RendererPageHistoryTraversalTaskKind, }, runtime::AuthorizedCurrentPageHistoryTraversal, }; @@ -90,12 +91,43 @@ impl ScriptVm { }) } - pub(crate) fn discard_stale_history_traversal_task( + /// Settle retained results without applying a retired target's traversal. + /// The Page arbiter must first validate the task's root-document namespace. + pub(crate) fn reject_stale_history_traversal_results( &mut self, - task_id: RendererPageHistoryTraversalTaskId, - ) -> bool { - self._context_host + task: RendererPageHistoryTraversalTask, + ) -> Result { + let owner = task.owner(); + let Some(queued) = self + ._context_host .borrow_mut() - .discard_pending_history_traversal_task(task_id) + .take_pending_history_traversal_task_for_exact_owner( + task.task_id(), + owner.execution_context(), + owner.target(), + task.kind(), + ) + else { + return Ok(false); + }; + let results = match queued.action { + PendingHistoryTraversalAction::ByDelta { .. } => return Ok(false), + PendingHistoryTraversalAction::SameDocument(traversal) => traversal.results, + PendingHistoryTraversalAction::CrossDocument(traversal) => traversal.results, + }; + if results.is_empty() { + return Ok(false); + } + // The retired realm owns these Promises and their rejection value. + // Keep its captured context; looking up a live Window could select a + // replacement realm or lose the results when the frame was removed. + let (_, bound_dispatch_scope, _, context) = queued.relevant_context.into_parts(); + let context_ptr: *const v8::Global = &context; + self.with_context_scope_by_ptr(context_ptr, move |scope, _host_ptr| { + let previous_dispatch_scope = bound_dispatch_scope.enter(scope); + crate::context_bootstrap::reject_canceled_history_traversal_results(scope, &results); + bound_dispatch_scope.defer_restore(scope, previous_dispatch_scope); + Ok(true) + }) } }