fix(runtime): finish parser script cleanup after engine termination

This commit is contained in:
ldm0
2026-11-20 22:47:58 +08:00
parent dead4b1585
commit 72dfd35242
4 changed files with 143 additions and 11 deletions
+9 -1
View File
@@ -3657,7 +3657,15 @@ impl PageVm {
),
Err(error) => {
let error = error.into_message();
if script_element_event.is_none() {
if script.kind == crate::types::ScriptKind::Classic
&& body_activity == crate::script_vm::PreparedScriptBodyActivity::Entered
{
// Internal execution failures are diagnostics, not a
// JavaScript exception or a deferred parser terminal.
self.vm_mut().record_runtime_warning(format_args!(
"parser-owned classic script failed: {error}"
));
} else if script_element_event.is_none() {
if self
.vm_mut()
.parser_owned_inline_importmap_reports_window_error_immediately(&script)
@@ -9,6 +9,7 @@ mod dom_tracking;
mod inserted_resource_lifecycle;
mod layout_and_tables;
mod parser_blocking_scripts;
mod parser_classic_aborts;
mod parser_custom_elements;
mod parser_flow;
mod parser_script_handoffs;
@@ -0,0 +1,89 @@
use super::*;
#[test]
fn parser_classic_abort_preserves_cleanup_context() {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("current-thread runtime");
runtime.block_on(tokio::task::LocalSet::new().run_until(async {
let _timeout = crate::v8_execution_watchdog::V8ExecutionWatchdog::override_timeout_for_test(
crate::v8_execution_watchdog::V8ExecutionWatchdogKind::ScriptTurn,
std::time::Duration::from_millis(500),
);
let mut page_vm = parse_phase_one_html_into_page_vm_for_test(
r#"<!doctype html><script>
globalThis.events=[];
function note(value) {
events.push(value);
queueMicrotask(() => {
events.push(value + ':micro');
if (value === 'start') events.push('currentScript:' + (document.currentScript?.id || 'null'));
});
}
onerror=()=>{note('window:error');return true;};
</script><script id="run" onload="note('element:load')" onerror="note('element:error')">
note('start');for(;;){}
</script><script>note('after');</script>"#,
)
.await;
assert_eq!(
page_vm
.vm_mut()
.eval("JSON.stringify(events)")
.expect("recovered isolate"),
r#"["start","start:micro","currentScript:run","after","after:micro"]"#,
"aborted evaluation must clean up before the parser continuation"
);
let diagnostics = page_vm
.vm_mut()
.runtime_observable_lifecycle_errors_for_testing();
assert!(
diagnostics
.iter()
.any(|message| message.contains("script execution exceeded")),
"the original watchdog failure must remain visible: {diagnostics:?}"
);
assert!(
diagnostics
.iter()
.all(|message| !message.contains("parser-boundary lifecycle")),
"parser failure must not enter the ordinary lifecycle queue: {diagnostics:?}"
);
}));
}
#[test]
fn parser_classic_exception_keeps_original_window_error_and_cleanup_order() {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("current-thread runtime");
runtime.block_on(tokio::task::LocalSet::new().run_until(async {
let mut page_vm = parse_phase_one_html_into_page_vm_for_test(
r#"<!doctype html><script>
globalThis.events=[];
globalThis.originalError=new Error('original');
function note(value) {
events.push(value);
queueMicrotask(() => {
events.push(value + ':micro');
if (value === 'start') events.push('currentScript:' + (document.currentScript?.id || 'null'));
});
}
onerror=(_message,_source,_line,_column,error)=>{
note('window:error:' + (error === originalError));return true;
};
</script><script id="run">
note('start');throw originalError;
</script><script>note('after');</script>"#,
).await;
assert_eq!(
page_vm.vm_mut().eval("JSON.stringify(events)").expect("exception result"),
r#"["start","window:error:true","start:micro","currentScript:run","window:error:true:micro","after","after:micro"]"#,
"JavaScript exceptions must retain their identity and report exactly once"
);
}));
}
@@ -309,22 +309,56 @@ impl ScriptVm {
let document_owner_before_run = self
.current_main_document_task_owner()
.expect("parser-owned classic execution requires a current main Document owner");
let result = {
let (result, failure_evaluation) = {
let _parser_script_nesting = execution_context
.is_parser_blocking()
.then(|| self.document_runtime.enter_parser_script_nesting());
self.execute_prepared_script_run_body(script, run_input.body)
.await
let result = self
.execute_prepared_script_run_body(script, run_input.body)
.await;
// Engine termination skips the normal evaluation cleanup. Keep
// recovery inside currentScript and parser nesting, while nested
// execution still leaves its checkpoint to the enclosing script.
let failure_evaluation = match &result {
Err(error)
if script.kind == ScriptKind::Classic
&& error.body_activity() == PreparedScriptBodyActivity::Entered =>
{
match self.with_default_context_scope(|scope, _| {
if crate::script_cleanup::can_perform_script_cleanup_checkpoint(scope) {
Self::perform_microtask_checkpoints(scope, Some(&script.url))?;
}
Ok(())
}) {
Ok(()) => ParserOwnedClassicScriptEvaluationSettlement::Settled,
Err(error) => {
self.record_runtime_warning(format_args!(
"parser-owned classic script cleanup failed: {error}"
));
ParserOwnedClassicScriptEvaluationSettlement::NotSettled
}
}
}
_ => ParserOwnedClassicScriptEvaluationSettlement::NotSettled,
};
(result, failure_evaluation)
};
self.document_runtime.clear_current_script_handle();
let outcome = match result {
Ok(outcome) => outcome,
Err(error) => {
let script_element_event = self
.plan_parser_owned_external_classic_completion_event(
script,
ScriptEventKind::Error,
);
let body_activity = error.body_activity();
// An entered classic script was successfully fetched. An
// engine failure does not turn its terminal into a load error.
let event_kind = if script.kind == ScriptKind::Classic
&& body_activity == PreparedScriptBodyActivity::Entered
{
ScriptEventKind::Load
} else {
ScriptEventKind::Error
};
let script_element_event =
self.plan_parser_owned_external_classic_completion_event(script, event_kind);
tracing::debug!(
url = %script.url,
event_planned = script_element_event.is_some(),
@@ -336,8 +370,8 @@ impl ScriptVm {
error.into_message(),
)),
script_element_event,
ParserOwnedClassicScriptEvaluationSettlement::NotSettled,
PreparedScriptBodyActivity::Entered,
failure_evaluation,
body_activity,
);
}
};