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(renderer): resume parser on stylesheet settlement
ldm0a942fbec7d26
diff --git a/moli-protocol/src/domains/page/tests/document_content.rs b/moli-protocol/src/domains/page/tests/document_content.rsindex ac95647d3..c56398614 100644--- a/moli-protocol/src/domains/page/tests/document_content.rs+++ b/moli-protocol/src/domains/page/tests/document_content.rs@@ -2439,7 +2439,7 @@ async fn stylesheet_gated_set_document_content_restores_parser_insertion_point()).await,json!({- "order": ["style-load", "script"],+ "order": ["script", "style-load"],"writtenColor": "rgb(11, 12, 13)","bodyChildren": ["SCRIPT", "gate", "gated-script", "gated-written", "gated-tail"],}),@@ -2449,7 +2449,8 @@ async fn stylesheet_gated_set_document_content_restores_parser_insertion_point()}// A failed script-blocking stylesheet still releases Blink's pending parser-// script. Its link error task is observable before the resumed script.+// script. Resource failure releases the parser before the independent link+// error task is dispatched.#[tokio::test(flavor = "multi_thread")]async fn failed_stylesheet_releases_set_document_content_parser_script() {let release_stylesheet = std::sync::Arc::new(tokio::sync::Notify::new());@@ -2531,7 +2532,7 @@ async fn failed_stylesheet_releases_set_document_content_parser_script() {).await,json!({- "order": ["style-error", "script"],+ "order": ["script", "style-error"],"ran": true,"tail": "tail","sheets": 1,@@ -2541,9 +2542,10 @@ async fn failed_stylesheet_releases_set_document_content_parser_script() {server.abort();}-// Ported from Blink's incremental body-stylesheet parser tests. Each link-// owns its load event independently, while the parser-blocking script waits-// until every stylesheet that precedes it has settled.+// Ported from Blink's incremental body-stylesheet parser tests. Each link owns+// its load event independently, while the parser-blocking script waits until+// every stylesheet that precedes it has settled. The final settlement resumes+// the parser before that link's independent load task.#[tokio::test(flavor = "multi_thread")]async fn set_document_content_waits_for_all_prior_stylesheets_but_dispatches_each_load() {let release_first = std::sync::Arc::new(tokio::sync::Notify::new());@@ -2664,7 +2666,7 @@ async fn set_document_content_waits_for_all_prior_stylesheets_but_dispatches_eac).await,json!({- "order": ["first-load", "second-load", "script"],+ "order": ["first-load", "script", "second-load"],"ran": true,"tail": "tail","color": "rgb(21, 22, 23)",@@ -3120,7 +3122,7 @@ async fn stylesheet_blocked_external_set_document_content_script_fetches_in_para).await,json!({- "order": ["style-load", "script-1", "script-1-load"],+ "order": ["script-1", "script-1-load", "style-load"],"color": "rgb(61, 62, 63)","tail": null,}),@@ -3168,9 +3170,9 @@ async fn stylesheet_blocked_external_set_document_content_script_fetches_in_para.await,json!({"order": [- "style-load","script-1","script-1-load",+ "style-load","script-2","script-2-load",],@@ -3968,7 +3970,7 @@ async fn document_written_stylesheet_pauses_set_document_content_parser_tail() {).await,json!({- "order": ["script-end", "style-load", "external-script", "external-load"],+ "order": ["script-end", "external-script", "external-load", "style-load"],"after": "after","color": "rgb(101, 102, 103)","scriptColor": "rgb(101, 102, 103)",diff --git a/moli-renderer-v8/src/document_runtime/document_write.rs b/moli-renderer-v8/src/document_runtime/document_write.rsindex 6aa07e8f2..cc31ce76b 100644--- a/moli-renderer-v8/src/document_runtime/document_write.rs+++ b/moli-renderer-v8/src/document_runtime/document_write.rs@@ -1148,20 +1148,6 @@ impl DocumentRuntime {.is_some_and(|pending| !pending.blocking_signatures_before.is_empty())}- pub(crate) fn has_pending_document_write_parser_created_style_import_pause(&self) -> bool {- self.pending_document_write_stylesheet_parser_pause- .as_ref()- .is_some_and(|pending| {- !pending.blocking_signatures.is_empty()- && pending.blocking_signatures.iter().all(|signature| {- matches!(- signature,- DocumentBlockingStylesheetSignature::ParserCreatedStyleImport { .. }- )- })- })- }-pub(crate) fn document_write_stylesheet_blocked_script_is_ready(&mut self) -> bool {let Some(signatures) = self.pending_document_write_stylesheet_parser_pause@@ -2023,8 +2009,9 @@ impl DocumentRuntime {pending.ready_completion.take()};let Some(completion) = ready_completion else {- // The stylesheet side is ready and its owner events have run;- // the same pending parser script now waits only for its source.+ // The stylesheet side is ready; the same pending parser script+ // now waits only for its source. Element events are separate+ // tasks and do not participate in this gate.return true;};let pending = selfdiff --git a/moli-renderer-v8/src/page_task_queue/stylesheet_task.rs b/moli-renderer-v8/src/page_task_queue/stylesheet_task.rsindex b53486756..8c168fa84 100644--- a/moli-renderer-v8/src/page_task_queue/stylesheet_task.rs+++ b/moli-renderer-v8/src/page_task_queue/stylesheet_task.rs@@ -352,16 +352,6 @@ pub(crate) struct PageConnectedStyleEventTurnAction {pub(crate) target_effect: PageConnectedStyleEventTargetEffect,}-impl PageConnectedStyleEventTurnAction {- pub(crate) const fn settled_current_owner(self) -> bool {- matches!(- self.target_effect,- PageConnectedStyleEventTargetEffect::DispatchedToCurrentOwner { .. }- | PageConnectedStyleEventTargetEffect::CurrentOwnerHadNoEvent { .. }- )- }-}-pub(crate) type PageConnectedStyleEventTurnOutcome =PageOwnerTurnOutcome<PageConnectedStyleEventTurnAction>;diff --git a/moli-renderer-v8/src/runtime/owner.rs b/moli-renderer-v8/src/runtime/owner.rsindex 929d93852..7d31c0b32 100644--- a/moli-renderer-v8/src/runtime/owner.rs+++ b/moli-renderer-v8/src/runtime/owner.rs@@ -327,6 +327,13 @@ enum RenderRuntimeDispatchOutcome {token: RendererPageToken,failure: PageNavigationOwnerFailure,},+ /// One ordinary Page scheduler turn has restored its stable residence.+ /// The admission bit is carried across that restore so the owner can join+ /// a selected parser task directly to its logical phase-one consumer.+ PageTurnComplete {+ result: Result<()>,+ parser_continuation_admitted: bool,+ },ContinueNextTurn(Box<RenderRuntimeTurn>),ContinueAfterPageWakeOrDeadline {turn: Box<RenderRuntimeTurn>,@@ -491,6 +498,25 @@ impl RenderRuntimePendingTurnQueue {Some(turn)}+ fn promote_phase_one_parser_continuation(&mut self, token: RendererPageToken) -> bool {+ let Some(index) = self+ .turns+ .iter()+ .position(|pending| pending.turn.is_phase_one_continuation_for(token))+ else {+ return false;+ };+ let mut pending = self+ .turns+ .remove(index)+ .expect("selected phase-one continuation must remain pending");+ self.page_owner_turn_count -= usize::from(pending.is_page_owner_turn());+ self.owner_maintenance_turn_count -= usize::from(pending.is_owner_maintenance_turn());+ pending.allow_command_overtake = false;+ self.push_front(pending);+ true+ }+const fn has_page_owner_turn(&self) -> bool {self.page_owner_turn_count != 0}@@ -788,6 +814,16 @@ impl RenderRuntimeTurn {}}+ fn is_phase_one_continuation_for(&self, token: RendererPageToken) -> bool {+ matches!(+ self,+ Self::ContinueLivePagePendingLocationNavigationPhaseOne {+ token: continuation_token,+ ..+ } if *continuation_token == token+ )+ }+fn detach_navigation_command_observer(self) -> (Self, bool) {match self {Self::FollowLivePagePendingLocationNavigation {@@ -2730,6 +2766,13 @@ impl RendererOwnerHandle {let outcome = self.run_pending_turn_on_owner_local_store(pending_turn.turn).await;+ let parser_continuation_admitted = matches!(+ &outcome,+ RenderRuntimeDispatchOutcome::PageTurnComplete {+ parser_continuation_admitted: true,+ ..+ }+ );match outcome {RenderRuntimeDispatchOutcome::Reply(result) => {let result = merge_command_admission_output_predecessor(@@ -2810,7 +2853,8 @@ impl RendererOwnerHandle {}}}- RenderRuntimeDispatchOutcome::BackgroundComplete(result) => {+ RenderRuntimeDispatchOutcome::BackgroundComplete(result)+ | RenderRuntimeDispatchOutcome::PageTurnComplete { result, .. } => {if let Some(reply_tx) = pending_turn.reply_tx {let reply = match result {Ok(()) => Err(anyhow!(@@ -2915,6 +2959,13 @@ impl RendererOwnerHandle {}}if let Some(token) = completed_page_turn_token {+ if parser_continuation_admitted {+ self.promote_admitted_phase_one_parser_continuation(+ token,+ &mut parked_turns,+ &mut pending_turns,+ );+ }// A bounded Page turn may have published the exact// lifecycle milestone page creation is waiting for.// Re-admit only that one-shot observer at this owner@@ -3123,7 +3174,8 @@ impl RendererOwnerHandle {remove_page_on_bound_owner_local_store(token);}}- RenderRuntimeDispatchOutcome::BackgroundComplete(result) => {+ RenderRuntimeDispatchOutcome::BackgroundComplete(result)+ | RenderRuntimeDispatchOutcome::PageTurnComplete { result, .. } => {let reply = match result {Ok(()) => Err(anyhow!("renderer command unexpectedly completed as background work"@@ -3238,6 +3290,7 @@ impl RendererOwnerHandle {}RenderRuntimeDispatchOutcome::Reply(_)| RenderRuntimeDispatchOutcome::BackgroundComplete(_)+ | RenderRuntimeDispatchOutcome::PageTurnComplete { .. }| RenderRuntimeDispatchOutcome::PageCreationNavigationFailurePublished { .. } => {}}}@@ -3906,6 +3959,44 @@ impl RendererOwnerHandle {admitted != 0}+ /// Complete the selected Networking continuation's one-way handoff.+ ///+ /// The Page turn only records admission in the resident phase-one parser;+ /// it must not let another ordinary Page task run before that parser+ /// consumes the admission. The logical phase-one driver may already be in+ /// the pending queue (from the producer wake that admitted this Page turn)+ /// or still be parked on Page activity, so promote either residence to the+ /// front without changing task-source arbitration globally.+ fn promote_admitted_phase_one_parser_continuation(+ &self,+ token: RendererPageToken,+ parked_turns: &mut VecDeque<RenderRuntimeParkedTurn>,+ pending_turns: &mut RenderRuntimePendingTurnQueue,+ ) {+ if pending_turns.promote_phase_one_parser_continuation(token) {+ return;+ }++ let index = parked_turns+ .iter()+ .position(|parked| {+ parked.wake_token == token && parked.turn.is_phase_one_continuation_for(token)+ })+ .expect("an admitted main-parser continuation must retain its phase-one driver");+ let parked = parked_turns+ .remove(index)+ .expect("selected phase-one continuation must remain parked");+ if let Some(mut pending) = self.pending_turn_from_parked(parked, pending_turns) {+ pending.allow_command_overtake = false;+ pending_turns.push_front(pending);+ } else {+ // A closed command observer may detach the same continuation into+ // background work while converting the parked turn. Promote that+ // detached driver too; a cancelled page legitimately leaves none.+ let _ = pending_turns.promote_phase_one_parser_continuation(token);+ }+ }+fn enqueue_due_parked_turns(&self,parked_turns: &mut VecDeque<RenderRuntimeParkedTurn>,@@ -4175,6 +4266,7 @@ impl RendererOwnerHandle {mut entry: LivePageEntry,source_label: &'static str,output_ordering: RendererOutputPublicationOrdering,+ parser_continuation_admitted: bool,) -> RenderRuntimeDispatchOutcome {let has_pending_document_lifecycle_turn =entry.pending_document_lifecycle_identity().is_some();@@ -4194,7 +4286,10 @@ impl RendererOwnerHandle {if let Some(output) = concrete_output {self.publish_renderer_output(output);}- return RenderRuntimeDispatchOutcome::BackgroundComplete(Err(error));+ return RenderRuntimeDispatchOutcome::PageTurnComplete {+ result: Err(error),+ parser_continuation_admitted,+ };}let concrete_output = entry.page_vm_mut()@@ -4230,7 +4325,10 @@ impl RendererOwnerHandle {?next_turn,"completed one ordinary Page turn");- RenderRuntimeDispatchOutcome::BackgroundComplete(Ok(()))+ RenderRuntimeDispatchOutcome::PageTurnComplete {+ result: Ok(()),+ parser_continuation_admitted,+ }}async fn run_one_page_turn(&self, token: RendererPageToken) -> RenderRuntimeDispatchOutcome {@@ -4293,6 +4391,11 @@ impl RendererOwnerHandle {let (mut entry, advance_result) =advance_page_owner_one_turn_via_local_task(executor, entry, scheduled_task, loader).await;+ let parser_continuation_admitted = entry+ .page_vm()+ .vm()+ .document_runtime+ .has_main_parser_continuation_admission();if let Err(error) = advance_result {let has_pending_document_lifecycle_turn =@@ -4326,10 +4429,19 @@ impl RendererOwnerHandle {}PageOwnerNextTurn::None => {}}- return RenderRuntimeDispatchOutcome::BackgroundComplete(Ok(()));+ return RenderRuntimeDispatchOutcome::PageTurnComplete {+ result: Ok(()),+ parser_continuation_admitted,+ };}- self.finish_page_turn(token, entry, source_label, output_ordering)+ self.finish_page_turn(+ token,+ entry,+ source_label,+ output_ordering,+ parser_continuation_admitted,+ )}async fn run_one_owner_maintenance_turn(@@ -7305,6 +7417,47 @@ mod tests {);}+ #[test]+ fn selected_parser_admission_promotes_its_phase_one_driver() {+ let parser_token = RendererPageToken::new_for_testing(PageId::new_for_testing(8));+ let unrelated_token = RendererPageToken::new_for_testing(PageId::new_for_testing(9));+ let mut pending = RenderRuntimePendingTurnQueue::default();+ pending.push_back(RenderRuntimePendingTurn {+ reply_tx: None,+ turn: RenderRuntimeTurn::RunPageTurn {+ token: unrelated_token,+ },+ allow_command_overtake: true,+ command_admission_output_predecessor: None,+ });+ pending.push_back(RenderRuntimePendingTurn {+ reply_tx: None,+ turn: RenderRuntimeTurn::ContinueLivePagePendingLocationNavigationPhaseOne {+ token: parser_token,+ follow_count: 0,+ completion: LivePagePendingNavigationCompletion::Background,+ },+ allow_command_overtake: true,+ command_admission_output_predecessor: None,+ });++ assert!(pending.promote_phase_one_parser_continuation(parser_token));+ let promoted = pending+ .pop_front()+ .expect("admitted parser must retain its logical driver");+ assert!(promoted.turn.is_phase_one_continuation_for(parser_token));+ assert!(+ !promoted.allow_command_overtake,+ "no command or unrelated Page turn may split a selected parser task from its phase-one consumer"+ );+ assert_eq!(+ pending+ .pop_front()+ .and_then(|pending| pending.page_owner_token()),+ Some(unrelated_token)+ );+ }+#[test]fn replacement_view_waiter_ignores_generic_activity_and_wrong_document_settlement() {let condition = RenderRuntimeParkCondition::ReplacementDocumentViewSettlement {diff --git a/moli-renderer-v8/src/runtime/page_vm/mod.rs b/moli-renderer-v8/src/runtime/page_vm/mod.rsindex f56f47975..6b9dd4435 100644--- a/moli-renderer-v8/src/runtime/page_vm/mod.rs+++ b/moli-renderer-v8/src/runtime/page_vm/mod.rs@@ -1725,40 +1725,12 @@ impl PageVm {self.vm_mut().prime_document_lifecycle_processing_and_record_stylesheet_network_results();- let mut progressed = false;- loop {- let ready = self- .vm_mut()- .document_runtime- .pop_ready_connected_style_load_before_parser_blocking_script();- let Some(ready) = ready else {- break;- };- progressed = true;- if self- .execute_parse_time_on_existing_live_document_on_named_owner_local_task(- ParseTimeLiveExecution::ConnectedStyleLoad { ready },- )- .await?- .navigation_triggered()- {- return Ok(true);- }- if !self- .vm()- .document_runtime- .has_pending_document_write_stylesheet_blocked_script()- {- return Ok(true);- }- }-if !self.vm_mut().document_runtime.document_write_stylesheet_blocked_script_is_ready(){- return Ok(progressed);+ return Ok(false);}self.vm_mut().sync_live_document_style_sources();@@ -1769,7 +1741,7 @@ impl PageVm {self.vm_mut().prime_document_lifecycle_processing_and_record_stylesheet_network_results();}- Ok(progressed || resumed)+ Ok(resumed)}pub(super) fn devtools_agent_token(&self) -> RendererDevToolsAgentToken {diff --git a/moli-renderer-v8/src/runtime/page_vm/page_dom_manipulation_task_completion.rs b/moli-renderer-v8/src/runtime/page_vm/page_dom_manipulation_task_completion.rsindex f72af4551..07be9e27e 100644--- a/moli-renderer-v8/src/runtime/page_vm/page_dom_manipulation_task_completion.rs+++ b/moli-renderer-v8/src/runtime/page_vm/page_dom_manipulation_task_completion.rs@@ -17,11 +17,6 @@ impl PageVm {action: PageDomManipulationTurnAction,loader: &crate::network::ResourceRequestClient,) -> Result<()> {- let connected_style_event_settled_current_owner = matches!(- action,- PageDomManipulationTurnAction::ConnectedStyleEvent(action)- if action.settled_current_owner()- );let completion = match action {PageDomManipulationTurnAction::BroadcastChannel(action) => {action.into_page_task_completion()@@ -56,16 +51,6 @@ impl PageVm {}};self.finish_selected_page_task_completion(completion, loader)- .await?;- if connected_style_event_settled_current_owner {- // The connected-style event is the last observable action owned- // by the completed stylesheet. Once it has dispatched and- // released its exact load-delay binding, resume a parser parked at- // that stylesheet boundary before lifecycle admission is- // reconsidered for this owner turn.- self.run_ready_document_write_stylesheet_blocked_script()- .await?;- }- Ok(())+ .await}}diff --git a/moli-renderer-v8/src/runtime/page_vm/page_networking_task_completion.rs b/moli-renderer-v8/src/runtime/page_vm/page_networking_task_completion.rsindex c4aa6947f..7805a0f8e 100644--- a/moli-renderer-v8/src/runtime/page_vm/page_networking_task_completion.rs+++ b/moli-renderer-v8/src/runtime/page_vm/page_networking_task_completion.rs@@ -22,21 +22,11 @@ impl PageVm {self.finish_selected_page_resource_completion_task(action)?;}PageNetworkingTurnAction::StyleElementEvent(action) => {- let connected_style_event_settled_current_owner = action.settled_current_owner();self.finish_selected_page_task_completion(action.into_page_task_completion(),loader,).await?;- if connected_style_event_settled_current_owner {- // A style-element event is the last observable action- // owned by the completed stylesheet. Resume a parser- // parked at that stylesheet boundary only after the event- // has dispatched and released its exact load-delay- // binding.- self.run_ready_document_write_stylesheet_blocked_script()- .await?;- }}PageNetworkingTurnAction::TextTrackLoad(action) => {self.finish_selected_page_task_completion(@@ -46,28 +36,18 @@ impl PageVm {.await?;}PageNetworkingTurnAction::StylesheetCompletion(action) => {- let should_resume_parser_created_style = matches!(- action.target_effect,- crate::page_task_queue::PageStylesheetNetworkingTargetEffect::AppliedToCurrentOwner- ) && self- .vm()- .document_runtime- .has_pending_document_write_parser_created_style_import_pause();self.finish_selected_page_task_completion(action.into_page_task_completion(),loader,).await?;- if should_resume_parser_created_style {- // Parser-created <style> owners are intentionally held- // out of the connected-owner initial scan while their- // parser boundary is active. Their @import completion- // therefore releases the parser directly after the- // stylesheet terminal's task-end checkpoint; the later- // connected-style scan owns any load/error event.- self.run_ready_document_write_stylesheet_blocked_script()- .await?;- }+ // A stylesheet terminal may release a parser created by+ // document.write()/Page.setDocumentContent after the initial+ // phase-one driver has retired. Resume that parser at the+ // resource-completion boundary, before the independently+ // queued link/style load event can be selected.+ self.run_ready_document_write_stylesheet_blocked_script()+ .await?;}PageNetworkingTurnAction::WorkerHostBridge(action) => {self.finish_selected_page_task_completion(diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/stylesheet_task.rs b/moli-renderer-v8/src/runtime/page_vm/tests/stylesheet_task.rsindex 2dd46c95c..379f06d5e 100644--- a/moli-renderer-v8/src/runtime/page_vm/tests/stylesheet_task.rs+++ b/moli-renderer-v8/src/runtime/page_vm/tests/stylesheet_task.rs@@ -1708,6 +1708,14 @@ async fn failed_import_installs_an_empty_child_and_errors_the_root_link() {let document_url = Url::parse(&format!("{base_url}/page.html"))?;let (mut page_vm, _resource_source, mut wake_rx) =page_vm_with_bound_task_sources_and_owner_wake(&loader, document_url);+ let owner = page_vm+ .vm()+ .current_main_document_task_owner()+ .expect("main Document owner");+ page_vm+ .vm_mut()+ .document_runtime+ .activate_main_parser_continuation(owner);page_vm.vm_mut().eval(&format!(r#"globalThis.__failedImportEvents = [];@@ -1724,6 +1732,15 @@ document.head.append(link);"queued""#,))?;+ let blocking_inputs = [parser_captured_stylesheet_input_for_test(+ &page_vm,+ "failed-import-root",+ )];+ let signatures = blocking_inputs+ .iter()+ .map(|input| input.signature().clone())+ .collect::<Vec<_>>();+ note_parser_captured_stylesheet_inputs_for_test(&mut page_vm, &blocking_inputs);page_vm.vm_mut().prime_document_lifecycle_processing_and_record_stylesheet_network_results();@@ -1737,6 +1754,13 @@ document.head.append(link);).await?);+ assert!(+ page_vm+ .vm_mut()+ .document_runtime+ .has_pending_parser_script_blocking_stylesheet_signatures(signatures.iter()),+ "the parser must remain blocked while the failing import is pending"+ );wait_for_stylesheet_source(&mut wake_rx, RendererOwnerWakeSource::NetworkingTask).await;assert!(page_vm@@ -1746,6 +1770,15 @@ document.head.append(link);).await?);+ assert!(+ !page_vm+ .vm_mut()+ .document_runtime+ .has_pending_parser_script_blocking_stylesheet_signatures(signatures.iter()),+ "a failed import graph must release script execution before reporting the error"+ );+ assert!(page_vm.has_ready_page_networking_task());+ assert!(page_vm.has_ready_dom_manipulation_task_for_test());assert_eq!(page_vm.vm_mut().eval(@@ -1766,16 +1799,23 @@ document.head.append(link);"true|0|true|rgb(1, 2, 3)|");- wait_for_stylesheet_source(&mut wake_rx, RendererOwnerWakeSource::DomManipulationTask)- .await;- let event = take_next_link_element_event_task_for_test(&mut page_vm)- .expect("the failed graph must publish one link event");- page_vm- .run_claimed_dom_manipulation_task_through_selected_dispatcher_for_test(- crate::page_task_queue::RendererPageDomManipulationTask::ConnectedStyleEvent(event),- &loader,- )- .await?;+ assert!(+ page_vm+ .run_one_oldest_ready_page_task_on_owner_lane_for_test(&loader)+ .await?,+ "the parser continuation must remain production-selectable"+ );+ assert_eq!(+ page_vm.vm_mut().eval("__failedImportEvents.join('|')")?,+ "",+ "the parser continuation must be older than the failed link event"+ );+ assert!(+ page_vm+ .run_one_oldest_ready_page_task_on_owner_lane_for_test(&loader)+ .await?,+ "the failed link event must remain production-selectable"+ );assert_eq!(page_vm.vm_mut().eval("__failedImportEvents.join('|')")?,"error"@@ -2255,7 +2295,12 @@ document.head.append(current);}#[tokio::test(flavor = "current_thread")]-async fn last_blocking_link_event_dispatches_before_parser_continuation() {+async fn last_blocking_link_releases_parser_before_its_event() {+ // Deliberately match Blink: stylesheet/import completion posts parser+ // continuation independently of the later link event. This differs from+ // the current expectation in WPT+ // `link-load-fired-before-scripting-unblocked.html`, which Blink records+ // as a known failure.run_page_vm_async_test(async move {let loader =crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");@@ -2319,31 +2364,28 @@ document.head.append(blocking);"stylesheet settlement should publish Blink-style parser reevaluation");- wait_for_stylesheet_source(&mut wake_rx, RendererOwnerWakeSource::DomManipulationTask)- .await;- let event = take_next_link_element_event_task_for_test(&mut page_vm)- .expect("blocking link load event DOM-manipulation turn");- page_vm- .run_claimed_dom_manipulation_task_through_selected_dispatcher_for_test(- crate::page_task_queue::RendererPageDomManipulationTask::ConnectedStyleEvent(event),- &loader,- )- .await?;+ assert!(+ page_vm+ .run_one_oldest_ready_page_task_on_owner_lane_for_test(&loader)+ .await?,+ "stylesheet settlement must leave one production-selectable task"+ );assert_eq!(page_vm.vm_mut().eval("__blockingLinkEventSeen")?,- "true",- "the observable link event must finish before parser admission"+ "false",+ "the parser continuation must be older than the independent link event");- wait_for_stylesheet_source(&mut wake_rx, RendererOwnerWakeSource::NetworkingTask).await;assert!(page_vm- .run_exact_selected_page_task_for_test(- PageSelectedTaskTestSelector::MainParserContinuation,- &loader,- )+ .run_one_oldest_ready_page_task_on_owner_lane_for_test(&loader).await?,- "stylesheet release must queue an exact main-parser continuation"+ "the link event must remain selectable after parser admission"+ );+ assert_eq!(+ page_vm.vm_mut().eval("__blockingLinkEventSeen")?,+ "true",+ "the later DOM-manipulation turn must dispatch the link event");Ok::<_, anyhow::Error>(())})@@ -2352,9 +2394,10 @@ document.head.append(blocking);}#[tokio::test(flavor = "current_thread")]-async fn shared_blocking_fetch_waits_for_every_link_event_before_parser_continuation() {+async fn shared_blocking_fetch_releases_parser_before_all_link_events() {run_page_vm_async_test(async move {- let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");+ let loader =+ crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");let document_url =Url::parse("https://example.com/shared-stylesheet-parser-continuation").unwrap();let (mut page_vm, _resource_source, mut wake_rx) =@@ -2388,10 +2431,7 @@ for (const id of ["first", "second"]) {parser_captured_stylesheet_input_for_test(&page_vm, "first"),parser_captured_stylesheet_input_for_test(&page_vm, "second"),];- note_parser_captured_stylesheet_inputs_for_test(- &mut page_vm,- &blocking_inputs,- );+ note_parser_captured_stylesheet_inputs_for_test(&mut page_vm, &blocking_inputs);page_vm.vm_mut().prime_document_lifecycle_processing_and_record_stylesheet_network_results();@@ -2412,63 +2452,335 @@ for (const id of ["first", "second"]) {);assert!(page_vm- .run_exact_selected_page_task_for_test(- PageSelectedTaskTestSelector::MainParserContinuation,- &loader,- )+ .run_one_oldest_ready_page_task_on_owner_lane_for_test(&loader).await?,- "shared stylesheet completion must queue an early parser reevaluation turn"+ "the coalesced parser continuation must remain production-selectable");-- wait_for_stylesheet_source(- &mut wake_rx,- RendererOwnerWakeSource::DomManipulationTask,- )- .await;- let first = take_next_link_element_event_task_for_test(&mut page_vm)- .expect("first blocking link event");- page_vm- .run_claimed_dom_manipulation_task_through_selected_dispatcher_for_test(- crate::page_task_queue::RendererPageDomManipulationTask::ConnectedStyleEvent(first),- &loader,- )- .await?;assert_eq!(page_vm.vm_mut().eval("__blockingLinkEvents.length")?,- "1"+ "0",+ "all clients of the shared completion must enqueue their events after parser admission");assert!(!page_vm.has_ready_page_networking_task(),- "the first client of a shared fetch must not release the parser while another blocking link event remains posted"+ "one shared completion must publish only one parser continuation");- let second = take_next_link_element_event_task_for_test(&mut page_vm)- .expect("second blocking link event");- page_vm- .run_claimed_dom_manipulation_task_through_selected_dispatcher_for_test(- crate::page_task_queue::RendererPageDomManipulationTask::ConnectedStyleEvent(- second,- ),- &loader,- )- .await?;+ assert!(+ page_vm+ .run_one_oldest_ready_page_task_on_owner_lane_for_test(&loader)+ .await?,+ "the first link event must remain production-selectable"+ );+ assert_eq!(+ page_vm.vm_mut().eval("__blockingLinkEvents.length")?,+ "1",+ "the first link event must run after parser admission"+ );++ assert!(+ page_vm+ .run_one_oldest_ready_page_task_on_owner_lane_for_test(&loader)+ .await?,+ "the second link event must remain production-selectable"+ );assert_eq!(page_vm.vm_mut().eval("__blockingLinkEvents.join('|')")?,"first|second");+ Ok::<_, anyhow::Error>(())+ })+ .await+ .expect("shared stylesheet parser continuation ordering test should run");+}++#[tokio::test(flavor = "current_thread")]+async fn parser_blocking_link_waits_for_nested_imports_then_releases_before_event() {+ run_page_vm_async_test(async move {+ let (base_url, server) = spawn_path_response_http_server(vec![+ (+ "/blocking-root.css",+ "HTTP/1.1 200 OK",+ "@import './nested/child.css'; .root { color: rgb(1, 2, 3); }".to_owned(),+ Duration::ZERO,+ ),+ (+ "/nested/child.css",+ "HTTP/1.1 200 OK",+ "@import './leaf.css'; .child { color: rgb(4, 5, 6); }".to_owned(),+ Duration::from_millis(100),+ ),+ (+ "/nested/leaf.css",+ "HTTP/1.1 200 OK",+ ".leaf { color: rgb(7, 8, 9); }".to_owned(),+ Duration::ZERO,+ ),+ ])+ .await;+ let loader =+ crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");+ let document_url = Url::parse(&format!("{base_url}/page.html"))?;+ let (mut page_vm, _resource_source, mut wake_rx) =+ page_vm_with_bound_task_sources_and_owner_wake(&loader, document_url);+ let owner = page_vm+ .vm()+ .current_main_document_task_owner()+ .expect("main Document owner");+ page_vm+ .vm_mut()+ .document_runtime+ .activate_main_parser_continuation(owner);++ let href = serde_json::to_string(&format!("{base_url}/blocking-root.css"))?;+ page_vm.vm_mut().eval(&format!(+ r#"+globalThis.__blockingImportEvents = [];+const blockingImport = document.createElement("link");+blockingImport.id = "blocking-import";+blockingImport.rel = "stylesheet";+blockingImport.href = {href};+blockingImport.addEventListener("load", () => __blockingImportEvents.push("load"));+blockingImport.addEventListener("error", () => __blockingImportEvents.push("error"));+document.head.append(blockingImport);+"queued"+"#,+ ))?;+ let blocking_inputs = [parser_captured_stylesheet_input_for_test(+ &page_vm,+ "blocking-import",+ )];+ let signatures = blocking_inputs+ .iter()+ .map(|input| input.signature().clone())+ .collect::<Vec<_>>();+ note_parser_captured_stylesheet_inputs_for_test(&mut page_vm, &blocking_inputs);+ page_vm+ .vm_mut()+ .prime_document_lifecycle_processing_and_record_stylesheet_network_results();++ wait_for_stylesheet_source(&mut wake_rx, RendererOwnerWakeSource::NetworkingTask).await;+ assert!(+ page_vm+ .run_exact_selected_page_task_for_test(+ PageSelectedTaskTestSelector::StylesheetCompletion,+ &loader,+ )+ .await?,+ "the root stylesheet must complete as one Networking turn"+ );+ assert!(+ page_vm+ .vm_mut()+ .document_runtime+ .has_pending_parser_script_blocking_stylesheet_signatures(signatures.iter()),+ "root settlement must not release the parser while its nested import graph is pending"+ );+ assert!(+ !page_vm.has_ready_page_networking_task(),+ "a pending import graph must not publish an early parser continuation"+ );+ assert!(+ !page_vm.has_ready_dom_manipulation_task_for_test(),+ "the link event must also wait for the complete import graph"+ );wait_for_stylesheet_source(&mut wake_rx, RendererOwnerWakeSource::NetworkingTask).await;assert!(page_vm.run_exact_selected_page_task_for_test(- PageSelectedTaskTestSelector::MainParserContinuation,+ PageSelectedTaskTestSelector::StylesheetCompletion,&loader,).await?,- "the last blocking link event must queue the parser continuation"+ "the nested import graph must complete as one Networking turn"+ );+ assert!(+ !page_vm+ .vm_mut()+ .document_runtime+ .has_pending_parser_script_blocking_stylesheet_signatures(signatures.iter()),+ "the complete import graph must release the parser before event dispatch"+ );+ assert!(page_vm.has_ready_page_networking_task());+ assert!(page_vm.has_ready_dom_manipulation_task_for_test());++ assert!(+ page_vm+ .run_one_oldest_ready_page_task_on_owner_lane_for_test(&loader)+ .await?+ );+ assert_eq!(+ page_vm.vm_mut().eval("__blockingImportEvents.join('|')")?,+ "",+ "the parser continuation must be older than the root link event"+ );+ assert!(+ page_vm+ .run_one_oldest_ready_page_task_on_owner_lane_for_test(&loader)+ .await?);+ assert_eq!(+ page_vm.vm_mut().eval("__blockingImportEvents.join('|')")?,+ "load"+ );+ server.await.expect("nested blocking import fixture server");Ok::<_, anyhow::Error>(())}).await- .expect("shared stylesheet parser continuation ordering test should run");+ .expect("parser-blocking nested import ordering test should run");+}++#[tokio::test(flavor = "current_thread")]+async fn removing_pending_parser_blocking_link_releases_parser_without_an_event() {+ run_page_vm_async_test(async move {+ let (base_url, server) = spawn_path_response_http_server(vec![(+ "/slow.css",+ "HTTP/1.1 200 OK",+ "body { color: rgb(1, 2, 3); }".to_owned(),+ Duration::from_secs(2),+ )])+ .await;+ let loader =+ crate::network::ResourceRequestClient::new(&FetchConfig::default()).expect("loader");+ let document_url = Url::parse(&format!("{base_url}/page.html"))?;+ let (mut page_vm, _resource_source, _wake_rx) =+ page_vm_with_bound_task_sources_and_owner_wake(&loader, document_url);+ let owner = page_vm+ .vm()+ .current_main_document_task_owner()+ .expect("main Document owner");+ page_vm+ .vm_mut()+ .document_runtime+ .activate_main_parser_continuation(owner);++ let href = serde_json::to_string(&format!("{base_url}/slow.css"))?;+ page_vm.vm_mut().eval(&format!(+ r#"+globalThis.__removedBlockingEvents = [];+const removedBlocking = document.createElement("link");+removedBlocking.id = "removed-blocking";+removedBlocking.rel = "stylesheet";+removedBlocking.href = {href};+removedBlocking.addEventListener("load", () => __removedBlockingEvents.push("load"));+removedBlocking.addEventListener("error", () => __removedBlockingEvents.push("error"));+document.head.append(removedBlocking);+"queued"+"#,+ ))?;+ let blocking_inputs = [parser_captured_stylesheet_input_for_test(+ &page_vm,+ "removed-blocking",+ )];+ let signatures = blocking_inputs+ .iter()+ .map(|input| input.signature().clone())+ .collect::<Vec<_>>();+ note_parser_captured_stylesheet_inputs_for_test(&mut page_vm, &blocking_inputs);+ page_vm+ .vm_mut()+ .prime_document_lifecycle_processing_and_record_stylesheet_network_results();+ assert!(+ page_vm+ .vm_mut()+ .document_runtime+ .has_pending_parser_script_blocking_stylesheet_signatures(signatures.iter())+ );++ page_vm+ .vm_mut()+ .eval("document.getElementById('removed-blocking').remove(); 'removed'")?;+ assert!(+ !page_vm+ .vm_mut()+ .document_runtime+ .has_pending_parser_script_blocking_stylesheet_signatures(signatures.iter()),+ "disconnecting the owner must remove its exact parser blocker"+ );+ assert!(+ page_vm.has_ready_page_networking_task(),+ "removing the last blocker must wake the parser"+ );+ assert!(+ !page_vm.has_ready_dom_manipulation_task_for_test(),+ "a cancelled owner must not publish a load/error event"+ );+ assert!(+ page_vm+ .run_exact_selected_page_task_for_test(+ PageSelectedTaskTestSelector::MainParserContinuation,+ &loader,+ )+ .await?+ );+ assert_eq!(+ page_vm.vm_mut().eval("__removedBlockingEvents.join('|')")?,+ ""+ );+ server.abort();+ Ok::<_, anyhow::Error>(())+ })+ .await+ .expect("removed parser-blocking link release test should run");+}++#[tokio::test(flavor = "current_thread")]+async fn dynamic_stylesheet_completion_does_not_publish_a_parser_continuation() {+ 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/dynamic-stylesheet-event").unwrap();+ let (mut page_vm, _resource_source, mut wake_rx) =+ page_vm_with_bound_task_sources_and_owner_wake(&loader, document_url);+ let owner = page_vm+ .vm()+ .current_main_document_task_owner()+ .expect("main Document owner");+ page_vm+ .vm_mut()+ .document_runtime+ .activate_main_parser_continuation(owner);++ page_vm.vm_mut().eval(+ r#"+globalThis.__dynamicStyleEvents = [];+const dynamicStyle = document.createElement("link");+dynamicStyle.rel = "stylesheet";+dynamicStyle.href = "data:text/css,body%7Bcolor%3Argb(1%2C%202%2C%203)%7D";+dynamicStyle.addEventListener("load", () => __dynamicStyleEvents.push("load"));+document.head.append(dynamicStyle);+"queued"+"#,+ )?;+ page_vm+ .vm_mut()+ .prime_document_lifecycle_processing_and_record_stylesheet_network_results();+ wait_for_stylesheet_source(&mut wake_rx, RendererOwnerWakeSource::NetworkingTask).await;+ assert!(+ page_vm+ .run_exact_selected_page_task_for_test(+ PageSelectedTaskTestSelector::StylesheetCompletion,+ &loader,+ )+ .await?+ );+ assert!(+ !page_vm.has_ready_page_networking_task(),+ "a dynamic non-parser-owned stylesheet must not manufacture parser work"+ );+ assert!(page_vm.has_ready_dom_manipulation_task_for_test());+ assert!(+ page_vm+ .run_one_oldest_ready_page_task_on_owner_lane_for_test(&loader)+ .await?+ );+ assert_eq!(+ page_vm.vm_mut().eval("__dynamicStyleEvents.join('|')")?,+ "load"+ );+ Ok::<_, anyhow::Error>(())+ })+ .await+ .expect("dynamic stylesheet parser-notification test should run");}diff --git a/moli-renderer-v8/src/runtime/phase_one/document_write_resource_tests.rs b/moli-renderer-v8/src/runtime/phase_one/document_write_resource_tests.rsindex 85ac13495..cfaefdeb2 100644--- a/moli-renderer-v8/src/runtime/phase_one/document_write_resource_tests.rs+++ b/moli-renderer-v8/src/runtime/phase_one/document_write_resource_tests.rs@@ -740,9 +740,9 @@ globalThis.__completedPreloadEvents.push('inline-after');assert_eq!(result.get("value").and_then(serde_json::Value::as_str),Some(- r#"{"events":["inline-before","inline-after","external","script-load"],"linkConnected":true,"sheet":"[object CSSStyleSheet]"}"#,+ r#"{"events":["inline-before","inline-after","external","script-load","tail"],"linkConnected":true,"sheet":"[object CSSStyleSheet]"}"#,),- "the external script callback should synchronously install the completed-preload client but keep the following script behind its event"+ "the completed-preload client must install synchronously and release the following parser script independently of its event");assert!(pending@@ -766,8 +766,8 @@ globalThis.__completedPreloadEvents.push('inline-after');.await;assert_eq!(result.get("value").and_then(serde_json::Value::as_str),- Some("inline-before|inline-after|external|script-load|style-load|tail"),- "the link event must release the parser-inserted script behind the adopted stylesheet"+ Some("inline-before|inline-after|external|script-load|tail|style-load"),+ "the adopted stylesheet event must remain asynchronous after parser execution resumes");server.awaitdiff --git a/moli-renderer-v8/src/runtime/phase_one/owner_turn.rs b/moli-renderer-v8/src/runtime/phase_one/owner_turn.rsindex 240b353a4..c6d8568fa 100644--- a/moli-renderer-v8/src/runtime/phase_one/owner_turn.rs+++ b/moli-renderer-v8/src/runtime/phase_one/owner_turn.rs@@ -51,7 +51,16 @@ impl ConcurrentParseTimeRuntime {}pub(super) async fn drive_owner_step(&mut self) -> Result<OwnerStepProgress> {- self.admit_selected_main_parser_continuation();+ let parser_continuation_admitted = self.admit_selected_main_parser_continuation();+ if parser_continuation_admitted {+ // A selected continuation is the sole authority for resuming all+ // parser residences, including a document.write() insertion+ // suspended behind stylesheets. Link/style load events remain+ // independent tasks and never grant parser progress.+ self.page_vm+ .run_ready_document_write_stylesheet_blocked_script()+ .await?;+ }let ConcurrentParseTimeRuntime {loader,state,diff --git a/moli-renderer-v8/src/runtime/phase_one/scaffold.rs b/moli-renderer-v8/src/runtime/phase_one/scaffold.rsindex 55a557ecd..9d205ab94 100644--- a/moli-renderer-v8/src/runtime/phase_one/scaffold.rs+++ b/moli-renderer-v8/src/runtime/phase_one/scaffold.rs@@ -88,12 +88,18 @@ async fn run_phase_one_creation_session_on_execution_context(scope_phase_one_execution_context_backend(&local_executor, async move {debug_assert_phase_one_execution_context_for(&run_executor, operation);let mut runtime = runtime;- if runtime.page_vm.has_ready_page_networking_task()- || runtime- .page_vm- .vm()- .document_runtime- .has_pending_document_write_external_script_load()+ let main_parser_continuation_is_admitted = runtime+ .page_vm+ .vm()+ .document_runtime+ .has_main_parser_continuation_admission();+ if !main_parser_continuation_is_admitted+ && (runtime.page_vm.has_ready_page_networking_task()+ || runtime+ .page_vm+ .vm()+ .document_runtime+ .has_pending_document_write_external_script_load()){// The unique typed consumer already lives in the owner-local// isolate reservation. Park creation so the stable Page arbiterdiff --git a/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rs b/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rsindex cbd8794d7..3e3ae6a14 100644--- a/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rs+++ b/moli-renderer-v8/src/script_vm/post_parse_lifecycle.rs@@ -2220,14 +2220,10 @@ impl ScriptVm {&mut self,ready: crate::document_runtime::ReadyConnectedStyleLoad,) -> bool {- let parser_blocking_link_event = self- .document_runtime- .ready_connected_style_load_is_parser_blocking_link_event(&ready);let context_ptr: *const v8::Global<v8::Context> = &self.page_default_context;let context_host = self._context_host.clone();let document_runtime = &mut self.document_runtime;- let dispatched = self- .renderer_document_isolate+ self.renderer_document_isolate.with_renderer_document_isolate_mut(|isolate| {let scope = pin!(v8::HandleScope::new(isolate));let scope = &mut scope.init();@@ -2240,12 +2236,7 @@ impl ScriptVm {return false;}document_runtime.dispatch_pending_style_load(scope, host_ptr, ready)- });- if parser_blocking_link_event {- self.document_runtime- .release_main_parser_after_parser_blocking_link_event_if_ready();- }- dispatched+ })}pub(crate) fn apply_pending_stylesheet_source_css_projections(&mut self) {diff --git a/moli-renderer-v8/src/stylesheet_runtime/blocking.rs b/moli-renderer-v8/src/stylesheet_runtime/blocking.rsindex be4664828..883bea07c 100644--- a/moli-renderer-v8/src/stylesheet_runtime/blocking.rs+++ b/moli-renderer-v8/src/stylesheet_runtime/blocking.rs@@ -280,11 +280,9 @@ impl DocumentRuntime {/// Whether a parser-owned script must still wait for one of the blocking/// stylesheet operations captured before it.///- /// Physical stylesheet settlement and the connected `<link>` load/error- /// task are separate browser-observable boundaries. A speculative fetch- /// may already be terminal when the parser creates the real owner, so the- /// posted event must remain part of this script gate even though the- /// physical blocking state has settled.+ /// Resource and `@import` completion release this gate. The later+ /// `<link>` load/error task remains observable and keeps its Document-load+ /// delay, but does not block parser-owned script execution.pub(crate) fn has_pending_parser_script_blocking_stylesheet_signatures<'a>(&mut self,signatures: impl IntoIterator<Item = &'a DocumentBlockingStylesheetSignature>,@@ -313,7 +311,7 @@ impl DocumentRuntime {.owner_states.link_states().any(|(owner, state)| {- (state.is_pending() || state.posted_event_load().is_some())+ state.is_pending()&& self.stylesheet_lifecycle.fetches@@ -328,46 +326,48 @@ impl DocumentRuntime {pub(crate) fn drain_blocking_stylesheet_completions(&mut self) {#[cfg(test)]self.apply_ready_stylesheet_networking_tasks_for_test();+ let mut had_pending_blocker = !self.parser_blocking_stylesheet_release_is_ready();let completed_fetches = self.stylesheet_lifecycle.fetches.drain_ready_completions();for fetch in completed_fetches {- self.promote_stylesheet_link_clients_for_fetch(&fetch);+ self.promote_stylesheet_link_clients_for_fetch(&fetch, had_pending_blocker);+ if self.parser_blocking_stylesheet_release_is_ready() {+ had_pending_blocker = false;+ }}self.reconcile_connected_style_imports_with_blocking_stylesheets();+ self.request_parser_if_stylesheet_blockers_released(had_pending_blocker);}pub(crate) fn apply_blocking_stylesheet_completion(&mut self,completion: crate::stylesheet_blocking::StylesheetCompletion,) {- let had_pending_blocker = self.stylesheet_lifecycle.fetches.has_any_pending_entries();+ let mut had_pending_blocker = !self.parser_blocking_stylesheet_release_is_ready();if let Some(fetch) = self.stylesheet_lifecycle.fetches.apply_completion(completion){- self.promote_stylesheet_link_clients_for_fetch(&fetch);+ self.promote_stylesheet_link_clients_for_fetch(&fetch, had_pending_blocker);+ if self.parser_blocking_stylesheet_release_is_ready() {+ had_pending_blocker = false;+ }}self.reconcile_connected_style_imports_with_blocking_stylesheets();- if had_pending_blocker && !self.stylesheet_lifecycle.fetches.has_any_pending_entries() {- // Match Blink's task publication boundary: stylesheet settlement- // schedules parser reevaluation even when a blocking <link> event- // was posted by the same completion. Phase-one yields to that- // stable event source before executing the script.- self.request_main_parser_continuation_if_active();- }+ self.request_parser_if_stylesheet_blockers_released(had_pending_blocker);}- fn parser_blocking_stylesheet_release_is_ready(&self) -> bool {+ pub(super) fn parser_blocking_stylesheet_release_is_ready(&self) -> bool {!self.stylesheet_lifecycle.fetches.has_any_pending_entries()- && !self.has_unsettled_parser_blocking_link()+ && !self.has_pending_parser_blocking_link()}- fn has_unsettled_parser_blocking_link(&self) -> bool {+ fn has_pending_parser_blocking_link(&self) -> bool {self.stylesheet_lifecycle.owner_states.link_states().any(|(owner, state)| {- (state.is_pending() || state.posted_event_load().is_some())+ state.is_pending()&& self.stylesheet_lifecycle.fetches.owns_blocking_link_fetch(NodeId::new(owner.index()),state.active_load().fetch(),@@ -375,22 +375,29 @@ impl DocumentRuntime {})}- pub(crate) fn ready_connected_style_load_is_parser_blocking_link_event(- &self,- ready: &super::ReadyConnectedStyleLoad,- ) -> bool {- let super::ReadyConnectedStyleLoadOperation::StylesheetLink(load) = ready.operation()- else {- return false;- };- self.stylesheet_lifecycle- .fetches- .owns_blocking_link_fetch(NodeId::new(load.owner().index()), load.fetch())+ pub(super) fn request_parser_if_stylesheet_blockers_released(&self, had_pending_blocker: bool) {+ if had_pending_blocker && self.parser_blocking_stylesheet_release_is_ready() {+ self.request_main_parser_continuation_if_active();+ }}- pub(crate) fn release_main_parser_after_parser_blocking_link_event_if_ready(&self) {- if self.parser_blocking_stylesheet_release_is_ready() {- self.request_main_parser_continuation_if_active();+ /// Finish one atomic stylesheet-state transition in Blink's lifecycle+ /// order: release script execution first, then enqueue independent element+ /// events. All clients of one shared physical fetch are published as one+ /// batch, so iteration order cannot put one of their events ahead of the+ /// parser continuation.+ pub(super) fn publish_stylesheet_link_settlements(+ &mut self,+ had_pending_blocker: bool,+ settlements: impl IntoIterator<Item = super::LinkStyleSettlement>,+ ) {+ self.request_parser_if_stylesheet_blockers_released(had_pending_blocker);+ for settlement in settlements {+ if let Some((load, successful)) = settlement.into_ready_event() {+ self.push_ready_connected_style_load(+ super::ReadyConnectedStyleLoad::for_stylesheet_link(load, successful),+ );+ }}}diff --git a/moli-renderer-v8/src/stylesheet_runtime/completion.rs b/moli-renderer-v8/src/stylesheet_runtime/completion.rsindex f0e9c415d..c77e33285 100644--- a/moli-renderer-v8/src/stylesheet_runtime/completion.rs+++ b/moli-renderer-v8/src/stylesheet_runtime/completion.rs@@ -86,23 +86,27 @@ impl DocumentRuntime {&mut self,load: Arc<StylesheetLinkClient>,) -> Option<StylesheetLinkClientTerminal> {+ let had_pending_blocker = !self.parser_blocking_stylesheet_release_is_ready();let active_link_clients = self.stylesheet_lifecycle.link_client_index.len();- self.promote_stylesheet_link_client_candidates(vec![load], active_link_clients)- .into_iter()- .next()+ let (terminals, settlements) =+ self.promote_stylesheet_link_client_candidates(vec![load], active_link_clients);+ self.publish_stylesheet_link_settlements(had_pending_blocker, settlements);+ terminals.into_iter().next()}pub(super) fn promote_stylesheet_link_clients_for_fetch(&mut self,fetch: &crate::stylesheet_blocking::StylesheetFetch,+ had_pending_blocker: bool,) {let active_link_clients = self.stylesheet_lifecycle.link_client_index.len();let clients = self.stylesheet_lifecycle.link_client_index.take_for_fetch(fetch);- let terminals =+ let (terminals, settlements) =self.promote_stylesheet_link_client_candidates(clients, active_link_clients);+ self.publish_stylesheet_link_settlements(had_pending_blocker, settlements);self.stylesheet_lifecycle.ready_stylesheet_link_client_terminals.extend(terminals);@@ -112,7 +116,7 @@ impl DocumentRuntime {&mut self,candidates: Vec<Arc<StylesheetLinkClient>>,active_link_clients: usize,- ) -> Vec<StylesheetLinkClientTerminal> {+ ) -> (Vec<StylesheetLinkClientTerminal>, Vec<LinkStyleSettlement>) {#[cfg(test)]let trace_enabled = true;#[cfg(not(test))]@@ -121,6 +125,7 @@ impl DocumentRuntime {let mut inspected_link_states = 0_u64;let mut promoted_clients = 0_u64;let mut terminals = Vec::new();+ let mut settlements = Vec::new();for load in candidates {if trace_enabled {inspected_link_states += 1;@@ -130,27 +135,18 @@ impl DocumentRuntime {};let handle = load.owner();let successful = terminal.is_ready();- let (accepted, ready) = self+ let settlement = self.stylesheet_lifecycle.owner_states.link_state_mut(handle)- .map(|state| {- let accepted = state.accept_resource_completion(&load, successful);- let ready = accepted.then(|| state.take_ready_event()).flatten();- (accepted, ready)- })- .unwrap_or((false, None));- if accepted {+ .and_then(|state| state.accept_resource_completion(&load, successful));+ if let Some(settlement) = settlement {promoted_clients += 1;terminals.push(StylesheetLinkClientTerminal::new(Arc::clone(&load),terminal,));- }- if let Some((load, successful)) = ready {- self.push_ready_connected_style_load(ReadyConnectedStyleLoad::for_stylesheet_link(- load, successful,- ));+ settlements.push(settlement);}}if let Some(started) = trace_started {@@ -175,7 +171,7 @@ impl DocumentRuntime {stage = "stylesheet_link_client_promotion_done",);}- terminals+ (terminals, settlements)}pub(super) fn note_connected_style_import_completion(@@ -189,26 +185,19 @@ impl DocumentRuntime {));}- pub(super) fn note_stylesheet_link_import_completion(+ pub(super) fn settle_stylesheet_link_import_completion(&mut self,load: &Arc<StylesheetLinkClient>,successful: bool,- ) {- let ready = self- .stylesheet_lifecycle+ ) -> Option<LinkStyleSettlement> {+ self.stylesheet_lifecycle.owner_states.link_state_mut(load.owner()).and_then(|state| {StylesheetLinkClient::ptr_eq(state.active_load(), load).then(|| state.accept_import_completion(successful))- .filter(|accepted| *accepted)- .and_then(|_| state.take_ready_event())- });- if let Some((load, successful)) = ready {- self.push_ready_connected_style_load(ReadyConnectedStyleLoad::for_stylesheet_link(- load, successful,- ));- }+ .flatten()+ })}pub(in crate::document_runtime) fn apply_network_result_install_authority(@@ -334,11 +323,7 @@ impl DocumentRuntime {#[cfg(test)]pub(in crate::document_runtime) fn drain_ready_connected_style_load_completions(&mut self) {- self.apply_ready_stylesheet_networking_tasks_for_test();- let completed_fetches = self.stylesheet_lifecycle.fetches.drain_ready_completions();- for fetch in completed_fetches {- self.promote_stylesheet_link_clients_for_fetch(&fetch);- }+ self.drain_blocking_stylesheet_completions();}}diff --git a/moli-renderer-v8/src/stylesheet_runtime/connected.rs b/moli-renderer-v8/src/stylesheet_runtime/connected.rsindex 21264036b..dbcca9683 100644--- a/moli-renderer-v8/src/stylesheet_runtime/connected.rs+++ b/moli-renderer-v8/src/stylesheet_runtime/connected.rs@@ -1477,6 +1477,7 @@ impl DocumentRuntime {&mut self,handle: DomHandle,) -> Vec<MainDocumentStyleLoadEventBinding> {+ let had_pending_blocker = !self.parser_blocking_stylesheet_release_is_ready();let node_id = NodeId::new(handle.index());self.stylesheet_lifecycle.pre_initial_scan_processed_owners@@ -1503,6 +1504,7 @@ impl DocumentRuntime {self.invalidate_stylesheet_owner_operations(handle);self.modulepreload_invalid_as_link_errors.remove(&handle);self.stylesheet_lifecycle.fetches.invalidate_node(node_id);+ self.request_parser_if_stylesheet_blockers_released(had_pending_blocker);canceled_bindings}@@ -1661,19 +1663,6 @@ impl DocumentRuntime {}}- pub(crate) fn pop_ready_connected_style_load_before_parser_blocking_script(- &mut self,- ) -> Option<ReadyConnectedStyleLoad> {- // A parser-blocking script resumes from the stylesheet gate using the- // blocking stylesheet state, while <link>/<style> load events are- // tracked by the connected-style lifecycle. Any connected load made- // ready by the same completion must run before the script observes the- // live DOM.- #[cfg(test)]- self.apply_ready_stylesheet_networking_tasks_for_test();- self.pop_ready_connected_style_load()- }-pub(crate) fn accept_native_modulepreload_link_client_terminals(&mut self,key: &ModuleMapKey,@@ -1794,7 +1783,7 @@ impl DocumentRuntime {self.stylesheet_lifecycle.owner_states.link_state_mut(handle)- .is_some_and(|state| state.accept_resource_completion(load, successful))+ .is_some_and(|state| state.accept_resource_completion(load, successful).is_some())}#[cfg(test)]@@ -4143,7 +4132,7 @@ mod tests {}#[tokio::test]- async fn completed_ownerless_failure_keeps_parser_script_behind_link_error_dispatch() {+ async fn completed_ownerless_failure_releases_parser_before_link_error_dispatch() {let listener = TcpListener::bind("127.0.0.1:0").await.expect("stylesheet server");@@ -4205,8 +4194,8 @@ mod tests {"the completed failure must settle the physical stylesheet blocker");assert!(- runtime.has_pending_parser_script_blocking_stylesheet_signatures(signatures.iter()),- "the exact posted link error task must remain in the parser script gate"+ !runtime.has_pending_parser_script_blocking_stylesheet_signatures(signatures.iter()),+ "a terminal stylesheet failure must release script execution before its error task");let load = runtime@@ -4227,7 +4216,7 @@ mod tests {);assert!(!runtime.has_pending_parser_script_blocking_stylesheet_signatures(signatures.iter()),- "dispatching the exact link error task must release the parser script gate"+ "dispatching the exact link error task must not recreate the released script gate");assert!(runtime.pop_ready_connected_style_load().is_none(),diff --git a/moli-renderer-v8/src/stylesheet_runtime/link_state.rs b/moli-renderer-v8/src/stylesheet_runtime/link_state.rsindex a1539dfd8..937f8544b 100644--- a/moli-renderer-v8/src/stylesheet_runtime/link_state.rs+++ b/moli-renderer-v8/src/stylesheet_runtime/link_state.rs@@ -52,6 +52,23 @@ pub(in crate::document_runtime) struct LinkStyleState {event_phase: LinkLoadEventPhase,}+/// Element-local consequence of settling one linked stylesheet phase.+///+/// The caller snapshots global parser-blocker state before accepting a batch+/// of these settlements. It can therefore publish a single parser+/// continuation before enqueueing any independent load/error events from the+/// batch.+#[derive(Debug)]+pub(in crate::document_runtime) struct LinkStyleSettlement {+ ready_event: Option<(Arc<StylesheetLinkClient>, bool)>,+}++impl LinkStyleSettlement {+ pub(super) fn into_ready_event(self) -> Option<(Arc<StylesheetLinkClient>, bool)> {+ self.ready_event+ }+}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum LinkLoadEventPhase {WaitingForCompletion,@@ -92,7 +109,7 @@ impl LinkStyleState {self.resource_completion.followed_by(self.import_completion)}- pub(super) fn take_ready_event(&mut self) -> Option<(Arc<StylesheetLinkClient>, bool)> {+ fn take_ready_event(&mut self) -> Option<(Arc<StylesheetLinkClient>, bool)> {if self.event_phase != LinkLoadEventPhase::WaitingForCompletion {return None;}@@ -105,10 +122,6 @@ impl LinkStyleState {Some((Arc::clone(&self.active_load), successful))}- pub(super) fn posted_event_load(&self) -> Option<&Arc<StylesheetLinkClient>> {- (self.event_phase == LinkLoadEventPhase::Posted).then_some(&self.active_load)- }-pub(super) fn consume_posted_event(&mut self, load: &Arc<StylesheetLinkClient>) -> bool {if self.event_phase != LinkLoadEventPhase::Posted|| !StylesheetLinkClient::ptr_eq(&self.active_load, load)@@ -123,15 +136,28 @@ impl LinkStyleState {&mut self,load: &Arc<StylesheetLinkClient>,successful: bool,- ) -> bool {+ ) -> Option<LinkStyleSettlement> {if !StylesheetLinkClient::ptr_eq(&self.active_load, load) {- return false;+ return None;}- self.resource_completion.settle(successful)+ self.resource_completion+ .settle(successful)+ .then(|| self.settlement_after_phase_change())+ }++ pub(super) fn accept_import_completion(+ &mut self,+ successful: bool,+ ) -> Option<LinkStyleSettlement> {+ self.import_completion+ .settle(successful)+ .then(|| self.settlement_after_phase_change())}- pub(super) fn accept_import_completion(&mut self, successful: bool) -> bool {- self.import_completion.settle(successful)+ fn settlement_after_phase_change(&mut self) -> LinkStyleSettlement {+ LinkStyleSettlement {+ ready_event: self.take_ready_event(),+ }}}diff --git a/moli-renderer-v8/src/stylesheet_runtime/linked_import_graph.rs b/moli-renderer-v8/src/stylesheet_runtime/linked_import_graph.rsindex 44a0ccbed..e041e3046 100644--- a/moli-renderer-v8/src/stylesheet_runtime/linked_import_graph.rs+++ b/moli-renderer-v8/src/stylesheet_runtime/linked_import_graph.rs@@ -443,9 +443,12 @@ impl DocumentRuntime {.filter(|(_, state)| state.active_load().fetch().ptr_eq(fetch)).map(|(_, state)| Arc::clone(state.active_load())).collect::<Vec<_>>();- for client in clients {- self.note_stylesheet_link_import_completion(&client, successful);- }+ let had_pending_blocker = !self.parser_blocking_stylesheet_release_is_ready();+ let settlements = clients+ .into_iter()+ .filter_map(|client| self.settle_stylesheet_link_import_completion(&client, successful))+ .collect::<Vec<_>>();+ self.publish_stylesheet_link_settlements(had_pending_blocker, settlements);}pub(crate) fn apply_linked_stylesheet_import_graph_completion(diff --git a/moli-renderer-v8/src/stylesheet_runtime/mod.rs b/moli-renderer-v8/src/stylesheet_runtime/mod.rsindex f6022930c..b2087a8e1 100644--- a/moli-renderer-v8/src/stylesheet_runtime/mod.rs+++ b/moli-renderer-v8/src/stylesheet_runtime/mod.rs@@ -38,7 +38,7 @@ pub(crate) use import_graph::fetch_complete_stylesheet_import_graph;pub(super) use import_graph::{ConnectedStyleImportReadiness, connected_style_import_readiness};pub(super) use import_graph_projection::fetch_observed_stylesheet_import_graph;pub(crate) use import_graph_projection::live_stylesheet_import_responses;-pub(super) use link_state::{LinkStyleState, StylesheetCompletionState};+pub(super) use link_state::{LinkStyleSettlement, LinkStyleState, StylesheetCompletionState};pub(crate) use linked_import_graph::LinkedStylesheetImportGraphCompletion;pub(super) use linked_import_graph::{LinkedStylesheetImportGraphAdmission, LinkedStylesheetImportGraphs,diff --git a/moli/tests/fetch_cli.rs b/moli/tests/fetch_cli.rsindex 89ad96702..7cc57df94 100644--- a/moli/tests/fetch_cli.rs+++ b/moli/tests/fetch_cli.rs@@ -34,6 +34,8 @@ use support::FixtureServer;use tokio::{io::AsyncReadExt, net::TcpListener, task::JoinHandle};use tracing_subscriber::fmt::MakeWriter;+#[path = "fetch_cli/anubis_async_module.rs"]+mod anubis_async_module;#[path = "fetch_cli/disable_js.rs"]mod disable_js;diff --git a/moli/tests/fetch_cli/anubis_async_module.rs b/moli/tests/fetch_cli/anubis_async_module.rsnew file mode 100644index 000000000..7d1f0fd94--- /dev/null+++ b/moli/tests/fetch_cli/anubis_async_module.rs@@ -0,0 +1,250 @@+use super::clean_output;+use anyhow::Result;+use axum::{+ Router,+ extract::State,+ http::{StatusCode, Uri},+ response::{Html, IntoResponse, Response},+ routing::get,+};+use std::{+ process::Command,+ sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+ },+};+use tokio::{net::TcpListener, sync::Notify, task::JoinHandle};++// Reduced from Anubis 1.26.2 as served by lore.kernel.org. Its async module+// suspends on a locale fetch while a later inline script is parser-blocked by+// an earlier stylesheet. Once the stylesheet becomes available, the parser+// must resume before a later fetch continuation can observe the following DOM.+const CHALLENGE_PAGE: &str = r#"<!doctype html>+<html>+ <head>+ <title>local anubis challenge</title>+ <script>globalThis.__anubisOrder = ["bootstrap"];</script>+ <link rel="stylesheet" href="/anubis/blocked.css" onload="__anubisOrder.push('link-load'); fetch('/anubis/style-activated')">+ </head>+ <body>+ <main id="challenge">+ <p id="status">calculating</p>+ <script async type="module" src="/anubis/main.mjs"></script>+ <script src="/anubis/parser-continuation.js"></script>+ <script>document.documentElement.dataset.executionOrder = __anubisOrder.join(',');</script>+ </main>+ </body>+</html>"#;++const MAIN_MODULE: &str = r#"+const locale = await (await fetch('/anubis/locale.json')).json();+globalThis.__anubisOrder.push('module-continuation');+const progress = document.getElementById('progress');+document.documentElement.dataset.progressAtModuleContinuation = progress ? 'present' : 'missing';+progress.style.display = 'block';+document.getElementById('status').textContent = locale.ready;+location.replace(+ '/anubis/passed?order=' + encodeURIComponent(__anubisOrder.join(',')) ++ '&style=' + encodeURIComponent(document.documentElement.dataset.styleAtParserContinuation || 'missing')+);+"#;++const PARSER_CONTINUATION: &str = r#"+globalThis.__anubisOrder.push('parser-continuation');+document.documentElement.dataset.parserContinuation = 'ran';+document.documentElement.dataset.styleAtParserContinuation =+ getComputedStyle(document.getElementById('status')).color;+const progress = document.createElement('div');+progress.id = 'progress';+progress.innerHTML = '<div class="bar-inner"></div>';+document.currentScript.after(progress);+"#;++#[derive(Default)]+struct Event {+ signaled: AtomicBool,+ notify: Notify,+}++impl Event {+ fn signal(&self) {+ if !self.signaled.swap(true, Ordering::Release) {+ self.notify.notify_waiters();+ }+ }++ async fn wait(&self) {+ loop {+ let notified = self.notify.notified();+ if self.signaled.load(Ordering::Acquire) {+ return;+ }+ notified.await;+ }+ }+}++#[derive(Clone, Default)]+struct FixtureState {+ stylesheet_requested: Arc<Event>,+ parser_continuation_requested: Arc<Event>,+ locale_requested: Arc<Event>,+ style_activated: Arc<Event>,+}++struct AnubisAsyncModuleFixture {+ base_url: String,+ task: JoinHandle<()>,+}++impl AnubisAsyncModuleFixture {+ async fn spawn() -> Result<Self> {+ let state = FixtureState::default();+ let listener = TcpListener::bind("127.0.0.1:0").await?;+ let addr = listener.local_addr()?;+ let app = Router::new()+ .route("/anubis/challenge", get(|| async { Html(CHALLENGE_PAGE) }))+ .route("/anubis/blocked.css", get(blocked_stylesheet))+ .route(+ "/anubis/main.mjs",+ get(|| async { javascript_response(MAIN_MODULE) }),+ )+ .route("/anubis/parser-continuation.js", get(parser_continuation))+ .route("/anubis/style-activated", get(style_activated))+ .route("/anubis/locale.json", get(locale))+ .route("/anubis/passed", get(passed))+ .with_state(state);+ let task = tokio::spawn(async move {+ axum::serve(listener, app)+ .await+ .expect("Anubis async-module fixture should serve");+ });+ Ok(Self {+ base_url: format!("http://{addr}"),+ task,+ })+ }++ fn url(&self, path: &str) -> String {+ format!("{}{path}", self.base_url)+ }+}++async fn passed(uri: Uri) -> Html<String> {+ Html(format!(+ "<!doctype html><title>passed</title><main id='passed' data-query='{}'>passed</main>",+ uri.query().unwrap_or_default()+ ))+}++impl Drop for AnubisAsyncModuleFixture {+ fn drop(&mut self) {+ self.task.abort();+ }+}++async fn blocked_stylesheet(State(state): State<FixtureState>) -> Response {+ state.stylesheet_requested.signal();+ // A parser-blocking external classic script starts its fetch only after+ // the HTML parser has reached that script boundary. Waiting for this+ // request proves the parser is suspended behind this stylesheet before+ // the stylesheet terminal is released; the test does not depend on a+ // sleep being long enough for the parser to get there.+ state.parser_continuation_requested.wait().await;+ state.locale_requested.wait().await;+ (+ StatusCode::OK,+ [+ ("content-type", "text/css; charset=utf-8"),+ ("cache-control", "no-store"),+ ],+ "#status { color: rgb(1, 2, 3); } #progress { display: none; }",+ )+ .into_response()+}++async fn parser_continuation(State(state): State<FixtureState>) -> Response {+ state.parser_continuation_requested.signal();+ javascript_response(PARSER_CONTINUATION)+}++async fn style_activated(State(state): State<FixtureState>) -> StatusCode {+ state.style_activated.signal();+ StatusCode::NO_CONTENT+}++async fn locale(State(state): State<FixtureState>) -> Response {+ state.stylesheet_requested.wait().await;+ state.locale_requested.signal();+ // Keep the async module suspended until the stylesheet's actual DOM event+ // runs. The onload confirmation request is a browser-observed causal edge:+ // it avoids assuming that a server handler returning means response bytes+ // have already reached the renderer. If link-event work can overtake the+ // parser, releasing this response exposes the same Anubis failure.+ state.style_activated.wait().await;+ (+ StatusCode::OK,+ [+ ("content-type", "application/json"),+ ("cache-control", "no-store"),+ ],+ r#"{"ready":"worker-ready"}"#,+ )+ .into_response()+}++fn javascript_response(source: &'static str) -> Response {+ (+ StatusCode::OK,+ [+ ("content-type", "application/javascript; charset=utf-8"),+ ("cache-control", "no-store"),+ ],+ source,+ )+ .into_response()+}++#[test]+fn cli_async_module_does_not_overtake_stylesheet_unblocked_parser() -> Result<()> {+ let runtime = tokio::runtime::Runtime::new()?;+ let server = runtime.block_on(AnubisAsyncModuleFixture::spawn())?;+ let url = server.url("/anubis/challenge");+ let output = Command::new(env!("CARGO_BIN_EXE_moli"))+ .args([+ "fetch",+ "--http-no-proxy",+ "*",+ "--wait-until",+ "done",+ "--delay-ms",+ "250",+ "--timeout",+ "3000",+ "--dump",+ "html",+ &url,+ ])+ .output()?;+ let stdout = clean_output(&output.stdout);+ let stderr = clean_output(&output.stderr);++ assert!(+ output.status.success(),+ "local Anubis fetch failed: stdout={stdout}\nstderr={stderr}"+ );+ assert!(+ stdout.contains("id=\"passed\""),+ "async module resumed before the stylesheet-unblocked parser inserted #progress: stdout={stdout}\nstderr={stderr}"+ );+ assert!(+ stdout.contains("order=bootstrap%2Cparser-continuation%2Clink-load%2Cmodule-continuation"),+ "stylesheet/parser ordering diverged from Chromium: stdout={stdout}\nstderr={stderr}"+ );+ assert!(+ stdout.contains("style=rgb(1%2C%202%2C%203)"),+ "the parser resumed before the completed stylesheet affected computed style: stdout={stdout}\nstderr={stderr}"+ );+ Ok(())+}