Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
refactor(renderer): split owner-local store modules
ldm09843922de400
diff --git a/moli-renderer-v8/src/runtime/owner_local_store/bound.rs b/moli-renderer-v8/src/runtime/owner_local_store/bound.rsnew file mode 100644index 000000000..e95504bf3--- /dev/null+++ b/moli-renderer-v8/src/runtime/owner_local_store/bound.rs@@ -0,0 +1,954 @@+use super::*;++pub(in crate::runtime) struct RenderRuntimeOwnerLocalStoreBinding;++fn with_bound_render_runtime_owner_local_store_session<R>(+ f: impl FnOnce(RendererOwnerLocalStoreSession<'_>) -> R,+) -> R {+ CURRENT_RENDER_RUNTIME_OWNER_LOCAL_STORE.with(|current_store| {+ let mut store = current_store+ .borrow()+ .expect("bound render-runtime owner-local store should exist on current thread");+ // Safety: the pointer is installed only for the lifetime of the+ // render-runtime owner loop on the current thread.+ unsafe {+ f(RendererOwnerLocalStoreSession {+ store: store.as_mut(),+ })+ }+ })+}++pub(in crate::runtime) fn bind_render_runtime_owner_local_store(+ store: &mut RendererOwnerLocalStore,+) -> RenderRuntimeOwnerLocalStoreBinding {+ CURRENT_RENDER_RUNTIME_OWNER_LOCAL_STORE.with(|current_store| {+ let mut current_store = current_store.borrow_mut();+ assert!(+ current_store.is_none(),+ "render-runtime owner-local store must not be rebound while already active"+ );+ *current_store = Some(NonNull::from(store));+ });+ RenderRuntimeOwnerLocalStoreBinding+}++pub(in crate::runtime) fn has_current_render_runtime_owner_local_store() -> bool {+ CURRENT_RENDER_RUNTIME_OWNER_LOCAL_STORE.with(|current_store| current_store.borrow().is_some())+}++pub(in crate::runtime) fn owner_local_store_session(+ store: &mut RendererOwnerLocalStore,+) -> RendererOwnerLocalStoreSession<'_> {+ RendererOwnerLocalStoreSession { store }+}++pub(in crate::runtime) fn install_page_vm_on_bound_owner_local_store(+ owner_local: &RendererOwnerLocalContext,+ requested_url: Url,+ navigation_initiator_url: Option<Url>,+ navigation_redirected: bool,+ navigation_redirect_count: usize,+ response_status: u16,+ response_headers: Vec<(String, String)>,+ vm: PageVm,+ pending_download: Option<RendererPendingDownloadActivation>,+ lifecycle_gate: Option<PageVmInitStage>,+) -> Result<RendererPendingPageCreation> {+ with_bound_render_runtime_owner_local_store_session(|mut session| {+ session.install_page_vm(+ owner_local,+ requested_url,+ navigation_initiator_url,+ navigation_redirected,+ navigation_redirect_count,+ response_status,+ response_headers,+ vm,+ pending_download,+ lifecycle_gate,+ )+ })+}++pub(in crate::runtime) fn install_phase_one_blocked_page_on_bound_owner_local_store(+ owner_local: &RendererOwnerLocalContext,+ requested_url: Url,+ navigation_initiator_url: Option<Url>,+ navigation_redirected: bool,+ navigation_redirect_count: usize,+ response_status: u16,+ response_headers: Vec<(String, String)>,+ pending_navigation: PageVmPendingPhaseOneNavigation,+ lifecycle_gate: Option<PageVmInitStage>,+) -> Result<RendererPendingPageCreation> {+ with_bound_render_runtime_owner_local_store_session(|mut session| {+ session.install_phase_one_blocked_page_for_owner(+ owner_local,+ requested_url,+ navigation_initiator_url,+ navigation_redirected,+ navigation_redirect_count,+ response_status,+ response_headers,+ pending_navigation,+ lifecycle_gate,+ )+ })+}++pub(in crate::runtime) fn finalize_pending_page_creation_on_bound_owner_local_store(+ pending: RendererPendingPageCreation,+) -> RendererPageCreationCommit {+ with_bound_render_runtime_owner_local_store_session(|mut session| {+ session.finalize_pending_page_creation(pending)+ })+}++pub(in crate::runtime) fn resolve_pending_page_creation_on_bound_owner_local_store(+ pending: RendererPendingPageCreation,+ document: RendererDocumentLifecycleIdentity,+ target_stage: PageVmInitStage,+ navigation_reply_policy: NavigationReplyPolicy,+) -> RendererPageCreationResolution {+ // This operation runs inside one owner-lane task and contains no await+ // boundary. Before the task starts the entry remains resident; once it is+ // checked out, observation and the resulting page-state refresh,+ // restoration, or retirement run to completion without exposing the entry+ // to the outer owner loop.+ with_bound_render_runtime_owner_local_store_session(|session| {+ session.store.resolve_pending_page_creation(+ pending,+ document,+ target_stage,+ navigation_reply_policy,+ )+ })+}++pub(super) fn reserve_renderer_document_isolate_on_bound_owner_local_store(+ owner_local: &RendererOwnerLocalContext,+ page_id: PageId,+ page_runtime_task_source: crate::page_task_queue::PageRuntimeTaskSource,+) -> Result<(+ RendererDocumentIsolateBootstrap,+ RendererDocumentIsolateReservation,+)> {+ with_bound_render_runtime_owner_local_store_session(|mut session| {+ session.reserve_renderer_document_isolate(owner_local, page_id, page_runtime_task_source)+ })+}++pub(super) fn remove_reserved_renderer_document_isolate_on_bound_owner_local_store(+ token: RendererPageToken,+ reservation_id: u64,+) {+ with_bound_render_runtime_owner_local_store_session(|mut session| {+ session.remove_reserved_renderer_document_isolate(token, reservation_id)+ })+}++async fn run_on_bound_owner_local_store_local_task<R, F>(+ local_executor: JsLocalExecutor,+ future: F,+) -> Result<R>+where+ R: 'static,+ F: Future<Output = Result<R>> + 'static,+{+ run_named_owner_local_task(+ local_executor,+ "bound render-runtime owner-local local task was cancelled",+ future,+ )+ .await+}++pub(in crate::runtime) type EntryLocalTaskFuture<'a, R> =+ Pin<Box<dyn Future<Output = Result<R>> + 'a>>;++#[cfg(debug_assertions)]+const PANIC_WAIT_FOR_SELECTOR_FOR_TESTING: &str = "__moli_panic_wait_for_selector_for_testing__";+#[cfg(debug_assertions)]+const PANIC_WAIT_FOR_SCRIPT_TRUTHY_FOR_TESTING: &str =+ "__moli_panic_wait_for_script_truthy_for_testing__";++pub(super) struct EntryLocalTaskGuard<E, R> {+ entry: Option<E>,+ reply_tx: Option<oneshot::Sender<(E, Result<R>)>>,+}++impl<E, R> EntryLocalTaskGuard<E, R> {+ pub(super) fn new(entry: E, reply_tx: oneshot::Sender<(E, Result<R>)>) -> Self {+ Self {+ entry: Some(entry),+ reply_tx: Some(reply_tx),+ }+ }++ fn entry_mut(&mut self) -> &mut E {+ self.entry+ .as_mut()+ .expect("entry local task guard should retain its page entry")+ }++ fn complete(mut self, result: Result<R>) {+ let entry = self+ .entry+ .take()+ .expect("entry local task guard should retain its page entry on completion");+ let reply_tx = self+ .reply_tx+ .take()+ .expect("entry local task guard should retain its reply sender on completion");+ let _ = reply_tx.send((entry, result));+ }+}++impl<E, R> Drop for EntryLocalTaskGuard<E, R> {+ fn drop(&mut self) {+ if let (Some(entry), Some(reply_tx)) = (self.entry.take(), self.reply_tx.take()) {+ let _ = reply_tx.send((+ entry,+ Err(anyhow!(+ "bound render-runtime owner-local local task panicked before restoring its page entry"+ )),+ ));+ }+ }+}++pub(in crate::runtime) async fn run_entry_on_bound_owner_local_store_local_task<R, F>(+ local_executor: JsLocalExecutor,+ entry: LivePageEntry,+ operation: F,+) -> (LivePageEntry, Result<R>)+where+ R: 'static,+ F: for<'a> FnOnce(&'a mut LivePageEntry) -> EntryLocalTaskFuture<'a, R> + 'static,+{+ let (reply_tx, reply_rx) = oneshot::channel();+ // Construct the guard before spawning. If the local task is cancelled+ // before its first poll, dropping the future must still return the entry+ // and an inner error to the owner so command-specific cleanup can run.+ let guard = EntryLocalTaskGuard::new(entry, reply_tx);+ tokio::task::spawn_local(async move {+ let mut guard = guard;+ let result = local_executor+ .scope_on_current_thread(operation(guard.entry_mut()))+ .await;+ guard.complete(result);+ });+ reply_rx+ .await+ .expect("entry local task guard must return the page entry on task termination")+}++pub(in crate::runtime) fn take_entry_for_command_on_bound_owner_local_store(+ token: RendererPageToken,+) -> Result<LivePageEntry> {+ with_bound_render_runtime_owner_local_store_session(|mut session| {+ session.take_entry_for_command(token)+ })+}++pub(in crate::runtime) fn checkout_entry_for_owner_turn_on_bound_owner_local_store(+ token: RendererPageToken,+) -> LivePageEntryCheckout {+ with_bound_render_runtime_owner_local_store_session(|mut session| {+ session.checkout_entry_for_owner_turn(token)+ })+}++pub(in crate::runtime) fn schedule_page_turn_on_bound_owner_local_store(+ token: RendererPageToken,+ trigger: PageTurnTrigger,+) -> RendererPageTurnAdmission {+ with_bound_render_runtime_owner_local_store_session(|session| {+ session.store.schedule_page_turn(token, trigger)+ })+}++pub(in crate::runtime) fn release_post_response_document_lifecycle_on_bound_owner_local_store(+ token: RendererPageToken,+ document: RendererDocumentLifecycleIdentity,+) -> bool {+ with_bound_render_runtime_owner_local_store_session(|session| {+ session+ .store+ .release_post_response_document_lifecycle(token, document)+ })+}++pub(in crate::runtime) fn checkout_scheduled_page_turn_on_bound_owner_local_store(+ token: RendererPageToken,+) -> RendererPageTurnCheckout {+ with_bound_render_runtime_owner_local_store_session(|session| {+ session.store.checkout_scheduled_page_turn(token)+ })+}++pub(in crate::runtime) fn has_ready_page_networking_task_on_bound_owner_local_store(+ token: RendererPageToken,+ current_document: RendererDocumentToken,+) -> bool {+ with_bound_render_runtime_owner_local_store_session(|session| {+ session+ .store+ .has_ready_page_networking_task(token, current_document)+ })+}++/// Reconcile one restored phase-one residence against its stable+/// producer sources.+///+/// The residence must already be visible in the Page slot before this function+/// is called. A producer may have published its payload and spent its+/// empty-to-nonempty wake before restoration completed; current source+/// readiness is therefore authoritative, while the stored suspension reason+/// only selects the exact source to inspect. No task is dequeued here.+pub(in crate::runtime) fn pending_phase_one_admission_after_restore_on_bound_owner_local_store(+ token: RendererPageToken,+) -> PhaseOneResidenceAdmission {+ with_bound_render_runtime_owner_local_store_session(|session| {+ session+ .store+ .pending_phase_one_admission_after_restore(token)+ })+}++pub(in crate::runtime) fn page_turn_readiness_after_restore_on_bound_owner_local_store(+ token: RendererPageToken,+) -> Option<PageOwnerTurnReadiness> {+ with_bound_render_runtime_owner_local_store_session(|session| {+ session.store.page_turn_readiness_after_restore(token)+ })+}++pub(in crate::runtime) fn renderer_output_fence_for_tail_on_bound_owner_local_store(+ token: RendererPageToken,+) -> Option<RendererOutputFence> {+ with_bound_render_runtime_owner_local_store_session(|session| {+ session+ .store+ .page_hosts+ .get(&token.local_host_id)+ .and_then(|host| host.pages.get(&token.page_id))+ .and_then(|slot| {+ let journal = slot.script_environment_pin.environment.output_journal();+ journal+ .last_published_cursor()+ .map(|cursor| journal.declare_fence(cursor))+ })+ })+}++pub(in crate::runtime) fn restore_entry_after_command_on_bound_owner_local_store(+ token: RendererPageToken,+ entry: LivePageEntry,+) {+ with_bound_render_runtime_owner_local_store_session(|mut session| {+ session.restore_entry_after_command(token, entry);+ });+}++pub(in crate::runtime) fn restore_retiring_entry_after_command_on_bound_owner_local_store(+ token: RendererPageToken,+ entry: RetiringPageEntry,+) {+ with_bound_render_runtime_owner_local_store_session(|mut session| {+ session.restore_retiring_entry_after_command(token, entry);+ });+}++pub(in crate::runtime) fn restore_entry_after_document_lifecycle_on_bound_owner_local_store(+ token: RendererPageToken,+ entry: LivePageEntry,+ reconsider_displaced_ordinary: bool,+) {+ with_bound_render_runtime_owner_local_store_session(|mut session| {+ session.restore_entry_after_command(token, entry);+ if let Some(gate) = session+ .store+ .page_hosts+ .get_mut(&token.local_host_id)+ .and_then(|host| host.pages.get_mut(&token.page_id))+ .and_then(|slot| slot.lifecycle_gate.as_mut())+ {+ gate.settle_lifecycle_turn(reconsider_displaced_ordinary);+ }+ });+}++pub(in crate::runtime) fn release_lifecycle_gate_on_bound_owner_local_store(+ token: RendererPageToken,+) -> Result<ReleasedLifecycleGate> {+ with_bound_render_runtime_owner_local_store_session(|session| {+ session.store.release_lifecycle_gate(token)+ })+}++pub(in crate::runtime) fn renderer_page_token_for_owner_context(+ owner: &RendererOwnerLocalContext,+ page_id: PageId,+) -> RendererPageToken {+ RendererPageToken {+ local_host_id: owner.local_host_id,+ #[cfg(debug_assertions)]+ local_thread_id: owner.local_thread_id,+ page_id,+ }+}++pub(in crate::runtime) async fn dispatch_async_command_on_entry_via_local_task(+ local_executor: JsLocalExecutor,+ entry: LivePageEntry,+ command: RendererPageCommand,+) -> (LivePageEntry, Result<RendererPageCommandDispatch>) {+ run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {+ Box::pin(+ async move { RendererOwnerLocalStore::dispatch_async_on_entry(entry, command).await },+ )+ })+ .await+}++/// Command result plus any replacement lifecycle admission created while the+/// Page entry was checked out. The owner must restore stable residence before+/// publishing the admitted lifecycle turn.+pub(in crate::runtime) struct RendererPageCommandDispatch {+ pub(in crate::runtime) reply: RendererPageReply,+ pub(in crate::runtime) replacement_lifecycle: Option<DocumentLifecycleTurnOutcome>,+ pub(in crate::runtime) turn_records: Vec<PendingRendererOutputRecord>,+}++pub(in crate::runtime) async fn advance_runtime_command_lifecycle_on_entry_via_local_task(+ local_executor: JsLocalExecutor,+ entry: LivePageEntry,+ scope_id: PageVmRuntimeCommandOutputScopeId,+) -> (LivePageEntry, Result<PageVmRuntimeCommandLifecycleAdvance>) {+ run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {+ Box::pin(async move {+ entry+ .page_vm_mut()+ .advance_pending_runtime_command_lifecycle_one_turn(scope_id)+ .await+ })+ })+ .await+}++pub(in crate::runtime) async fn begin_post_parse_lifecycle_on_entry_via_local_task(+ local_executor: JsLocalExecutor,+ entry: LivePageEntry,+ work: Vec<PostParsePageOwnedWork>,+ stage: PageVmInitStage,+ started: std::time::Instant,+) -> (LivePageEntry, Result<DocumentLifecycleTurnOutcome>) {+ run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {+ Box::pin(async move {+ let (page_vm, pending_document_lifecycle_turn) =+ entry.page_vm_and_document_lifecycle_turn_mut();+ page_vm+ .begin_post_parse_lifecycle_on_named_owner_lane(+ pending_document_lifecycle_turn,+ work,+ stage,+ started,+ )+ .await+ })+ })+ .await+}++pub(in crate::runtime) async fn commit_page_state_on_entry_via_local_task(+ local_executor: JsLocalExecutor,+ entry: LivePageEntry,+) -> (LivePageEntry, Result<Arc<RendererPageState>>) {+ commit_page_state_on_entry_via_local_task_with_policy(+ local_executor,+ entry,+ super::RendererPageStateCapturePolicy::FullReport,+ )+ .await+}++pub(in crate::runtime) async fn commit_page_state_on_entry_via_local_task_with_policy(+ local_executor: JsLocalExecutor,+ entry: LivePageEntry,+ capture_policy: super::RendererPageStateCapturePolicy,+) -> (LivePageEntry, Result<Arc<RendererPageState>>) {+ run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {+ Box::pin(async move {+ RendererOwnerLocalStore::commit_current_vm_page_state_on_entry_with_policy(+ entry,+ capture_policy,+ )+ .map_err(|error| anyhow!("failed to refresh renderer owner page view: {error}"))+ })+ })+ .await+}++pub(in crate::runtime) async fn advance_network_idle_wait_turn_on_entry_via_local_task(+ local_executor: JsLocalExecutor,+ entry: LivePageEntry,+ state: PageVmNetworkIdleWaitState,+ remaining: std::time::Duration,+) -> (LivePageEntry, Result<PageVmNetworkIdleWaitAdvance>) {+ run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {+ Box::pin(async move {+ entry+ .page_vm_mut()+ .advance_network_idle_wait_turn(state, remaining)+ .await+ })+ })+ .await+}++pub(in crate::runtime) async fn advance_dom_stable_wait_turn_on_entry_via_local_task(+ local_executor: JsLocalExecutor,+ entry: LivePageEntry,+ state: PageVmDomStableWaitState,+ remaining: std::time::Duration,+) -> (LivePageEntry, Result<PageVmDomStableWaitAdvance>) {+ run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {+ Box::pin(async move {+ entry+ .page_vm_mut()+ .advance_dom_stable_wait_turn(state, remaining)+ .await+ })+ })+ .await+}++pub(in crate::runtime) async fn advance_selector_wait_turn_on_entry_via_local_task(+ local_executor: JsLocalExecutor,+ entry: LivePageEntry,+ selector: String,+ remaining: std::time::Duration,+) -> (LivePageEntry, Result<PageVmCommandWaitAdvance>) {+ run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {+ Box::pin(async move {+ #[cfg(debug_assertions)]+ if selector == PANIC_WAIT_FOR_SELECTOR_FOR_TESTING {+ panic!("wait-for-selector local task panicked for testing")+ }+ entry+ .page_vm_mut()+ .advance_selector_wait_turn(&selector, remaining)+ .await+ })+ })+ .await+}++pub(in crate::runtime) async fn advance_script_truthy_wait_turn_on_entry_via_local_task(+ local_executor: JsLocalExecutor,+ entry: LivePageEntry,+ expression: String,+ pending_call: Option<PendingRuntimeEvaluateCall>,+ remaining: std::time::Duration,+) -> (LivePageEntry, Result<PageVmScriptTruthyWaitAdvance>) {+ run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {+ Box::pin(async move {+ #[cfg(debug_assertions)]+ if expression == PANIC_WAIT_FOR_SCRIPT_TRUTHY_FOR_TESTING {+ panic!("wait-for-script-truthy local task panicked for testing")+ }+ entry+ .page_vm_mut()+ .advance_script_truthy_wait_turn(&expression, pending_call, remaining)+ .await+ })+ })+ .await+}++pub(in crate::runtime) async fn advance_runtime_expression_await_turn_on_entry_via_local_task(+ local_executor: JsLocalExecutor,+ entry: LivePageEntry,+ execution_context_id: Option<i64>,+ expression: String,+ pending_call: Option<PendingRuntimeEvaluateCall>,+ remaining: std::time::Duration,+) -> (LivePageEntry, Result<PageVmRuntimeExpressionAwaitAdvance>) {+ run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {+ Box::pin(async move {+ entry+ .page_vm_mut()+ .advance_runtime_expression_await_turn(+ execution_context_id,+ &expression,+ pending_call,+ remaining,+ )+ .await+ })+ })+ .await+}++pub(in crate::runtime) async fn advance_subresource_response_wait_turn_on_entry_via_local_task(+ local_executor: JsLocalExecutor,+ entry: LivePageEntry,+ criteria: SubresourceResponseWaitCriteria,+ remaining: std::time::Duration,+) -> (LivePageEntry, Result<PageVmSubresourceResponseWaitAdvance>) {+ run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {+ Box::pin(async move {+ entry+ .page_vm_mut()+ .advance_subresource_response_wait_turn(&criteria, remaining)+ .await+ })+ })+ .await+}++pub(in crate::runtime) async fn follow_pending_location_navigation_one_turn_on_entry_via_local_task(+ local_executor: JsLocalExecutor,+ entry: LivePageEntry,+ stage: PageVmInitStage,+) -> (LivePageEntry, Result<LivePageNavigationFollowTurn>) {+ run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {+ Box::pin(async move {+ let outcome = {+ let (page_vm, pending_document_lifecycle_turn) =+ entry.page_vm_and_document_lifecycle_turn_mut();+ page_vm+ .prepare_pending_location_navigation_document_commit_one_turn_async(+ pending_document_lifecycle_turn,+ stage,+ )+ .await+ };+ let outcome = match outcome? {+ PageVmFollowNavigationTurnOutcome::Completed => {+ LivePageNavigationFollowOutcome::Completed+ }+ PageVmFollowNavigationTurnOutcome::PostParseLifecycle {+ target_stage,+ outcome,+ } => LivePageNavigationFollowOutcome::PostParseLifecycle {+ target_stage,+ outcome,+ },+ PageVmFollowNavigationTurnOutcome::Download(download) => {+ LivePageNavigationFollowOutcome::Download(download)+ }+ PageVmFollowNavigationTurnOutcome::PendingPhaseOne(pending) => {+ let wake_token = entry.install_new_pending_phase_one_navigation(pending)?;+ LivePageNavigationFollowOutcome::PendingPhaseOne { wake_token }+ }+ PageVmFollowNavigationTurnOutcome::TriggeredNavigation { stage } => {+ LivePageNavigationFollowOutcome::TriggeredNavigation { stage }+ }+ };+ let document_commit = entry+ .has_uncommitted_page_vm()+ .then(|| entry.publish_replacement_document_commit())+ .transpose()?;+ Ok(LivePageNavigationFollowTurn {+ outcome,+ document_commit,+ })+ })+ })+ .await+}++pub(in crate::runtime) fn remove_page_on_bound_owner_local_store(token: RendererPageToken) {+ with_bound_render_runtime_owner_local_store_session(|mut session| session.remove_page(token))+}++pub(in crate::runtime) fn publish_page_navigation_failure_on_bound_owner_local_store(+ token: RendererPageToken,+ failure: PageNavigationOwnerFailure,+) -> Result<PageCreationNavigationFailurePublication> {+ with_bound_render_runtime_owner_local_store_session(|session| {+ session+ .store+ .publish_page_navigation_failure(token, failure)+ })+}++pub(in crate::runtime) async fn remove_page_on_bound_owner_local_store_via_local_task(+ local_executor: JsLocalExecutor,+ token: RendererPageToken,+) -> Result<()> {+ run_on_bound_owner_local_store_local_task(local_executor, async move {+ remove_page_on_bound_owner_local_store(token);+ Ok(())+ })+ .await+}++pub(in crate::runtime) fn next_page_task_deadline_on_bound_owner_local_store()+-> Option<std::time::Instant> {+ with_bound_render_runtime_owner_local_store_session(|session| {+ session.store.next_page_task_deadline()+ })+}++/// Snapshot Pages with any due owner-scheduled task from the derived deadline+/// index. Only resident entries are indexed because a checked-out PageVm may+/// change its timer heap or delayed typed-source state before restoration.+pub(in crate::runtime) fn snapshot_due_page_task_tokens_on_bound_owner_local_store(+ due_at_or_before: std::time::Instant,+) -> Vec<RendererPageToken> {+ with_bound_render_runtime_owner_local_store_session(|session| {+ session+ .store+ .snapshot_due_page_task_tokens(due_at_or_before)+ })+}++pub(in crate::runtime) fn next_owner_maintenance_deadline_on_bound_owner_local_store()+-> Option<std::time::Instant> {+ with_bound_render_runtime_owner_local_store_session(|session| {+ session.store.next_owner_maintenance_deadline()+ })+}++pub(in crate::runtime) fn claim_due_owner_maintenance_task_on_bound_owner_local_store(+ now: std::time::Instant,+) -> Option<RendererOwnerMaintenanceTask> {+ with_bound_render_runtime_owner_local_store_session(|session| {+ session.store.claim_due_owner_maintenance_task(now)+ })+}++pub(in crate::runtime) fn settle_owner_maintenance_task_on_bound_owner_local_store(+ task: RendererOwnerMaintenanceTask,+ now: std::time::Instant,+) -> Result<()> {+ with_bound_render_runtime_owner_local_store_session(|session| {+ session.store.settle_owner_maintenance_task(task, now)+ })+}++pub(super) struct PageReadyDescriptorSnapshot {+ pub(super) eligible: Vec<crate::page_task_queue::RendererPageReadyDescriptor>,+ pub(super) stable_source_was_ready: bool,+ due_timer_was_ready: bool,+}++impl PageReadyDescriptorSnapshot {+ pub(super) const fn has_ready_ordinary_source(&self) -> bool {+ self.stable_source_was_ready || self.due_timer_was_ready+ }+}++pub(super) fn page_ready_descriptor_snapshot(+ entry: &mut LivePageEntry,+ task_sources: &mut RendererPageOwnedTaskSources,+) -> PageReadyDescriptorSnapshot {+ let mut descriptors = task_sources.ready_descriptors();+ let stable_source_was_ready = !descriptors.is_empty();+ let mut due_timer_was_ready = false;+ if let Some(timer) = entry.page_vm().due_page_timer_ready_descriptor() {+ descriptors.push(timer);+ due_timer_was_ready = true;+ }+ descriptors.retain(|descriptor| {+ entry+ .page_vm_mut()+ .page_ready_descriptor_is_eligible(*descriptor)+ });+ PageReadyDescriptorSnapshot {+ eligible: descriptors,+ stable_source_was_ready,+ due_timer_was_ready,+ }+}++pub(super) fn select_page_scheduler_turn(+ scheduler: &mut PageTurnScheduler<LivePageEntry>,+ entry: &mut LivePageEntry,+ task_sources: &mut RendererPageOwnedTaskSources,+ lifecycle_gate: &mut Option<LifecycleGate>,+ trigger: PageTurnTrigger,+) -> RendererPageScheduledTurn {+ let snapshot = page_ready_descriptor_snapshot(entry, task_sources);+ // A lifecycle action can change an already-queued source's eligibility.+ // Preserve queue readiness, not only the pre-action eligible set, so a+ // blocked/idle lifecycle result can request exactly one fresh arbitration+ // without re-reading mutable source state after execution.+ let lifecycle_is_deferred = entry.document_lifecycle_is_deferred_until_response();+ let has_pending_document_lifecycle_turn =+ !lifecycle_is_deferred && entry.pending_document_lifecycle_identity().is_some();+ let document_lifecycle_owner_turn_is_runnable =+ !lifecycle_is_deferred && entry.document_lifecycle_owner_turn_is_runnable();+ let has_ready_main_parser_script_continuation =+ !lifecycle_is_deferred && entry.has_ready_main_parser_script_continuation();+ let document_lifecycle = DocumentLifecycleClassReadiness::from_resident_state(+ has_pending_document_lifecycle_turn,+ document_lifecycle_owner_turn_is_runnable,+ has_ready_main_parser_script_continuation,+ );+ let gate_policy = lifecycle_gate+ .as_mut()+ .map(|gate| gate.turn_policy(entry, !snapshot.eligible.is_empty()))+ .unwrap_or(LifecycleGateTurnPolicy::Normal);+ let selected_class = match gate_policy {+ LifecycleGateTurnPolicy::Normal => {+ scheduler.select_turn_class(trigger, !snapshot.eligible.is_empty(), document_lifecycle)+ }+ LifecycleGateTurnPolicy::Drive {+ reconsider_displaced_ordinary,+ } => scheduler.select_lifecycle_turn(+ reconsider_displaced_ordinary,+ !snapshot.eligible.is_empty(),+ document_lifecycle,+ ),+ LifecycleGateTurnPolicy::Park => {+ return RendererPageScheduledTurn::SpentWake;+ }+ };+ match selected_class {+ Some(PageTurnClass::DocumentLifecycle) => RendererPageScheduledTurn::DocumentLifecycle {+ displaced_ordinary: RendererDisplacedOrdinaryTurn::from_ready_source(+ snapshot.has_ready_ordinary_source(),+ ),+ },+ Some(PageTurnClass::Ordinary) => {+ let selected = scheduler+ .select_ready_descriptor(snapshot.eligible)+ .expect("selected ordinary Page-turn class must retain an eligible descriptor");+ let task = task_sources.take_task(selected);+ RendererPageScheduledTurn::Ordinary(Box::new(task))+ }+ None => RendererPageScheduledTurn::SpentWake,+ }+}++/// Run one ordinary page-owner turn already selected by the Page scheduler.+/// Every ordinary task is a concrete typed source payload or a due timer. The+/// caller must restore the returned entry before scheduling any continuation.+pub(in crate::runtime) async fn advance_page_owner_one_turn_via_local_task(+ local_executor: JsLocalExecutor,+ entry: LivePageEntry,+ task: RendererPageSchedulerTask,+ loader: ResourceRequestClient,+) -> (LivePageEntry, Result<()>) {+ run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {+ Box::pin(async move {+ let replacement_lifecycle_snapshot = entry+ .page_vm()+ .document_replacement_lifecycle_action_snapshot();+ // This scope belongs to the common Page owner, not the selected+ // task executor: command-local wait drivers reuse that executor+ // but retain their own typed navigation continuation.+ let _navigation_handoff_scope = entry+ .page_vm()+ .vm()+ .begin_ordinary_page_turn_navigation_handoff()?;+ let application = entry+ .page_vm_mut()+ .apply_selected_page_scheduler_task(task, &loader)+ .await;+ // Any JavaScript-capable Page action can synchronously replace the+ // main Document through document.open()/document.close(). Reconcile+ // the exact transition caused by this action at the common owner+ // boundary. Reconciliation must still run when the action reports+ // an error: JavaScript side effects are not rolled back by an+ // exception. A selected Page action cannot repair an older missed+ // transition.+ let reconciliation = {+ let (page_vm, pending_document_lifecycle_turn) =+ entry.page_vm_and_document_lifecycle_turn_mut();+ page_vm+ .reconcile_document_replacement_lifecycle_after_owner_action(+ replacement_lifecycle_snapshot,+ pending_document_lifecycle_turn,+ )+ .await+ };++ match (application, reconciliation) {+ (Ok(()), Ok(_)) => Ok(()),+ (Err(action_error), Ok(_)) => Err(action_error),+ (Ok(_), Err(reconciliation_error)) => Err(reconciliation_error),+ (Err(action_error), Err(reconciliation_error)) => Err(anyhow!(+ "page action failed ({action_error:#}) and its Document replacement lifecycle reconciliation also failed ({reconciliation_error:#})"+ )),+ }+ })+ })+ .await+}++/// Execute at most one action from the exact-Document lifecycle resident.+/// A missing resident is an idle stale-wake outcome; this helper never binds+/// a page wake to whichever Document happens to be current.+pub(in crate::runtime) async fn advance_document_lifecycle_one_page_turn_via_local_task(+ local_executor: JsLocalExecutor,+ entry: LivePageEntry,+) -> (LivePageEntry, Result<DocumentLifecycleTurnOutcome>) {+ run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {+ Box::pin(async move {+ let Some(document) = entry.pending_document_lifecycle_identity() else {+ return Ok(DocumentLifecycleTurnOutcome::idle(+ DocumentLifecycleTurnAction::None,+ ));+ };+ let (page_vm, pending_document_lifecycle_turn) =+ entry.page_vm_and_document_lifecycle_turn_mut();+ let outcome = page_vm+ .advance_post_parse_lifecycle_one_owner_turn(+ pending_document_lifecycle_turn,+ document,+ )+ .await?;+ if let Some(pending) = pending_document_lifecycle_turn.as_mut() {+ pending.owner_turn_is_runnable = matches!(+ outcome.readiness,+ DocumentLifecycleTurnReadiness::Runnable { .. }+ );+ }+ Ok(outcome)+ })+ })+ .await+}++pub(in crate::runtime) fn observe_document_lifecycle_on_entry(+ entry: &mut LivePageEntry,+ document: RendererDocumentLifecycleIdentity,+ target_stage: PageVmInitStage,+) -> DocumentLifecycleObserverOutcome {+ entry.observe_document_lifecycle(document, target_stage)+}++pub(super) fn reconcile_page_creation_lifecycle_observation(+ observation: DocumentLifecycleObserverOutcome,+ has_pending_location_navigation: bool,+) -> DocumentLifecycleObserverOutcome {+ match observation {+ DocumentLifecycleObserverOutcome::Reached if has_pending_location_navigation => {+ DocumentLifecycleObserverOutcome::NavigationPending+ }+ observation => observation,+ }+}++pub(in crate::runtime) fn has_pending_document_lifecycle_turn_on_entry(+ entry: &mut LivePageEntry,+) -> bool {+ entry.pending_document_lifecycle_identity().is_some()+}++impl Drop for RenderRuntimeOwnerLocalStoreBinding {+ fn drop(&mut self) {+ CURRENT_RENDER_RUNTIME_OWNER_LOCAL_STORE.with(|current_store| {+ // Cleanup must remain idempotent and non-asserting: this guard can+ // run during panic unwinding, where a second panic would abort the+ // process instead of preserving the original failure.+ current_store.borrow_mut().take();+ });+ }+}diff --git a/moli-renderer-v8/src/runtime/owner_local_store/entry.rs b/moli-renderer-v8/src/runtime/owner_local_store/entry.rsnew file mode 100644index 000000000..d7d628bfe--- /dev/null+++ b/moli-renderer-v8/src/runtime/owner_local_store/entry.rs@@ -0,0 +1,632 @@+use super::*;++#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]+pub(super) enum StandaloneNavigationFollowState {+ #[default]+ Idle,+ Following {+ handoff: crate::page_task_queue::RendererTopLevelNavigationHandoff,+ },+ FailedWithPendingNavigation {+ handoff: crate::page_task_queue::RendererTopLevelNavigationHandoff,+ },+}++#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub(in crate::runtime) struct PublishedReplacementDocument {+ pub(in crate::runtime) navigation_handoff:+ crate::page_task_queue::RendererTopLevelNavigationHandoff,+ pub(in crate::runtime) vm_creation_id: u64,+ pub(in crate::runtime) view_generation: u64,+}++impl StandaloneNavigationFollowState {+ pub(super) fn claim(+ &mut self,+ current: Option<crate::page_task_queue::RendererTopLevelNavigationHandoff>,+ requested: Option<crate::page_task_queue::RendererTopLevelNavigationHandoff>,+ ) -> bool {+ if matches!(+ *self,+ Self::FailedWithPendingNavigation { handoff } if Some(handoff) != current+ ) {+ *self = Self::Idle;+ }+ let Some(current) = current else {+ return false;+ };+ if requested.is_some_and(|requested| requested != current) {+ return false;+ }+ if !matches!(*self, Self::Idle) {+ return false;+ }+ *self = Self::Following { handoff: current };+ true+ }++ pub(super) fn settle(+ &mut self,+ current: Option<crate::page_task_queue::RendererTopLevelNavigationHandoff>,+ succeeded: bool,+ ) {+ *self = match *self {+ Self::Following { .. } if !succeeded => current+ .map(|handoff| Self::FailedWithPendingNavigation { handoff })+ .unwrap_or(Self::Idle),+ Self::Following { .. } => Self::Idle,+ Self::FailedWithPendingNavigation { handoff } if Some(handoff) != current => Self::Idle,+ state => state,+ };+ }+}++pub(in crate::runtime) struct LivePageEntry {+ pub(in crate::runtime) slot: RendererPageSlotHandle,+ pub(super) top_level_navigation_dispatch: RendererTopLevelNavigationDispatch,+ pub(super) standalone_navigation_follow: StandaloneNavigationFollowState,+ // Keep executable continuation state before `vm`: Rust drops fields in+ // declaration order, so an exceptional entry drop still releases any+ // ScriptVm-bound task before releasing the PageVm itself.+ pub(super) pending_document_lifecycle_turn: Option<PendingDocumentLifecycleTurn>,+ pub(super) post_response_document_lifecycle: Option<RendererDocumentLifecycleIdentity>,+ pub(in crate::runtime) vm: Option<PageVm>,+ pub(super) pending_phase_one_navigation: Option<PageVmPendingPhaseOneNavigation>,+ pub(super) last_published_replacement_document: Option<PublishedReplacementDocument>,+}++/// A checked-out Page entry whose final active `PageVm` has been consumed by+/// teardown and which can therefore only return through the retiring+/// residence boundary.+///+/// The wrapped entry is deliberately private: owner code cannot convert this+/// state back into [`LivePageEntry`] or accidentally pass it to a live-entry+/// restore path.+pub(in crate::runtime) struct RetiringPageEntry {+ pub(super) entry: LivePageEntry,+}++impl RetiringPageEntry {+ pub(super) fn new(entry: LivePageEntry) -> Self {+ assert!(+ entry.active_page_vm().is_none(),+ "a retiring Page entry must not retain an active PageVm"+ );+ Self { entry }+ }++ pub(in crate::runtime) fn settle_standalone_navigation_follow(&mut self, succeeded: bool) {+ self.entry.settle_standalone_navigation_follow(succeeded);+ }+}++impl std::fmt::Debug for LivePageEntry {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("LivePageEntry")+ .field("slot", &self.slot)+ .field(+ "top_level_navigation_dispatch",+ &self.top_level_navigation_dispatch,+ )+ .field(+ "standalone_navigation_follow",+ &self.standalone_navigation_follow,+ )+ .field("vm", &self.vm)+ .field(+ "pending_document_lifecycle_turn",+ &self+ .pending_document_lifecycle_turn+ .as_ref()+ .map(|pending| pending.document),+ )+ .field(+ "post_response_document_lifecycle",+ &self.post_response_document_lifecycle,+ )+ .field(+ "has_pending_phase_one_navigation",+ &self.pending_phase_one_navigation.is_some(),+ )+ .field(+ "last_published_replacement_document",+ &self.last_published_replacement_document,+ )+ .finish()+ }+}++impl LivePageEntry {+ pub(super) fn new(slot: RendererPageSlotHandle, mut vm: PageVm) -> Result<Self> {+ vm.bind_script_execution_control(slot.script_execution_control());+ Ok(Self {+ slot,+ top_level_navigation_dispatch:+ RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,+ standalone_navigation_follow: StandaloneNavigationFollowState::Idle,+ pending_document_lifecycle_turn: None,+ post_response_document_lifecycle: None,+ vm: Some(vm),+ pending_phase_one_navigation: None,+ last_published_replacement_document: None,+ })+ }++ pub(super) fn new_with_pending_phase_one_navigation(+ slot: RendererPageSlotHandle,+ mut pending: PageVmPendingPhaseOneNavigation,+ ) -> Result<Self> {+ pending+ .page_vm_mut()+ .bind_script_execution_control(slot.script_execution_control());+ let mut entry = Self {+ slot,+ top_level_navigation_dispatch:+ RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,+ standalone_navigation_follow: StandaloneNavigationFollowState::Idle,+ pending_document_lifecycle_turn: None,+ post_response_document_lifecycle: None,+ vm: None,+ pending_phase_one_navigation: None,+ last_published_replacement_document: None,+ };+ entry.prepare_pending_phase_one_navigation_install(&mut pending)?;+ entry.pending_phase_one_navigation = Some(pending);+ Ok(entry)+ }++ pub(in crate::runtime) fn page_vm(&self) -> &PageVm {+ self.active_page_vm()+ .expect("resident renderer page entry must retain an active PageVm")+ }++ pub(in crate::runtime) fn set_top_level_navigation_dispatch(+ &mut self,+ dispatch: RendererTopLevelNavigationDispatch,+ ) {+ self.top_level_navigation_dispatch = dispatch;+ }++ pub(in crate::runtime) fn top_level_navigation_dispatch(+ &self,+ ) -> RendererTopLevelNavigationDispatch {+ self.top_level_navigation_dispatch+ }++ /// Claim the single standalone owner chain for the current pending+ /// location navigation. A failed chain remains suppressed while that same+ /// descriptor is pending, so a duplicate producer handoff cannot restart+ /// the chain with a fresh limit.+ pub(in crate::runtime) fn begin_standalone_navigation_follow(&mut self) -> bool {+ self.begin_standalone_navigation_follow_for_handoff(None)+ }++ /// Claim a producer handoff only while the same request still occupies+ /// the ScriptVm's unique pending navigation slot. A delayed wake for an+ /// overwritten request therefore cannot start the replacement request.+ pub(in crate::runtime) fn begin_standalone_navigation_follow_from_handoff(+ &mut self,+ handoff: crate::page_task_queue::RendererTopLevelNavigationHandoff,+ ) -> bool {+ self.begin_standalone_navigation_follow_for_handoff(Some(handoff))+ }++ pub(super) fn begin_standalone_navigation_follow_for_handoff(+ &mut self,+ requested: Option<crate::page_task_queue::RendererTopLevelNavigationHandoff>,+ ) -> bool {+ if !matches!(+ self.top_level_navigation_dispatch,+ RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter+ ) {+ return false;+ }+ let current = self+ .active_page_vm()+ .and_then(|page_vm| page_vm.vm().pending_location_navigation_handoff());+ self.standalone_navigation_follow.claim(current, requested)+ }++ pub(in crate::runtime) fn settle_standalone_navigation_follow(&mut self, succeeded: bool) {+ let current = self+ .active_page_vm()+ .and_then(|page_vm| page_vm.vm().pending_location_navigation_handoff());+ self.standalone_navigation_follow.settle(current, succeeded);+ }++ /// A replacement PageVm becomes the active owner-local runtime before its+ /// view is committed to the stable cross-thread Page slot.+ pub(in crate::runtime) fn has_uncommitted_page_vm(&self) -> bool {+ self.uncommitted_page_vm_creation_id().is_some()+ }++ pub(in crate::runtime) fn uncommitted_page_vm_creation_id(&self) -> Option<u64> {+ let stable_entry = self.slot.entry();+ if !stable_entry.is_active() {+ return None;+ }+ self.active_page_vm().and_then(|page_vm| {+ (stable_entry.vm_creation_id() != page_vm.creation_id).then_some(page_vm.creation_id)+ })+ }++ pub(super) fn publish_replacement_document_commit(+ &mut self,+ ) -> Result<PublishedReplacementDocument> {+ let stable_before = self.slot.entry();+ ensure!(+ stable_before.is_active(),+ "replacement Document cannot commit into a retired Page slot"+ );+ let page_vm = self+ .active_page_vm()+ .ok_or_else(|| anyhow!("replacement Document commit lost its active PageVm"))?;+ let vm_creation_id = page_vm.creation_id;+ let navigation_handoff =+ page_vm+ .replacement_document_commit_handoff()+ .ok_or_else(|| {+ anyhow!("replacement PageVm is missing its navigation commit identity")+ })?;+ ensure!(+ stable_before.vm_creation_id() != vm_creation_id,+ "replacement Document commit attempted to republish stable PageVm {vm_creation_id}"+ );+ ensure!(+ self.last_published_replacement_document+ .is_none_or(|published| {+ published.vm_creation_id != vm_creation_id+ && published.navigation_handoff != navigation_handoff+ }),+ "replacement Document commit attempted to reuse a published navigation or PageVm identity"+ );++ self.page_vm_mut()+ .settle_replacement_document_commit(navigation_handoff)?;+ RendererOwnerLocalStore::commit_active_vm_page_state_on_entry(self)?;+ let stable_after = self.slot.entry();+ ensure!(+ stable_after.vm_creation_id() == vm_creation_id,+ "replacement Document publication did not install its PageVm identity"+ );+ ensure!(+ stable_after.view_generation > stable_before.view_generation,+ "replacement Document publication did not advance the stable view generation"+ );+ let published = PublishedReplacementDocument {+ navigation_handoff,+ vm_creation_id,+ view_generation: stable_after.view_generation,+ };+ self.last_published_replacement_document = Some(published);++ // Pending phase one owns the committed replacement. The old PageVm+ // was already terminated before the response commit and can no longer+ // be a rollback candidate.+ if self.pending_phase_one_navigation.is_some() {+ self.vm = None;+ }+ Ok(published)+ }++ pub(in crate::runtime) fn active_page_vm(&self) -> Option<&PageVm> {+ self.pending_phase_one_navigation+ .as_ref()+ .map(PageVmPendingPhaseOneNavigation::page_vm)+ .or(self.vm.as_ref())+ }++ pub(in crate::runtime) fn page_vm_mut(&mut self) -> &mut PageVm {+ let control = self.slot.script_execution_control();+ let page_vm = if let Some(pending) = self.pending_phase_one_navigation.as_mut() {+ pending.page_vm_mut()+ } else {+ self.vm+ .as_mut()+ .expect("resident renderer page entry must retain an active PageVm")+ };+ page_vm.bind_script_execution_control(control);+ page_vm+ }++ pub(in crate::runtime) fn pending_phase_one_navigation_has_ready_streaming_input(+ &mut self,+ ) -> bool {+ self.pending_phase_one_navigation+ .as_mut()+ .is_some_and(PageVmPendingPhaseOneNavigation::has_ready_streaming_input)+ }++ pub(super) fn page_vm_and_document_lifecycle_turn_mut(+ &mut self,+ ) -> (&mut PageVm, &mut Option<PendingDocumentLifecycleTurn>) {+ self.retire_stale_document_lifecycle_turn();+ let Self {+ vm,+ pending_document_lifecycle_turn,+ pending_phase_one_navigation,+ ..+ } = self;+ let page_vm = if let Some(pending) = pending_phase_one_navigation.as_mut() {+ pending.page_vm_mut()+ } else {+ vm.as_mut()+ .expect("resident renderer page entry must retain an active PageVm")+ };+ (page_vm, pending_document_lifecycle_turn)+ }++ pub(super) fn retire_document_lifecycle_turn(&mut self) {+ self.pending_document_lifecycle_turn = None;+ self.post_response_document_lifecycle = None;+ }++ pub(super) fn retire_stale_document_lifecycle_turn(&mut self) {+ let Some(pending_document) = self+ .pending_document_lifecycle_turn+ .as_ref()+ .map(|pending| pending.document)+ else {+ // A bounded lifecycle action may retire its resident before a+ // later operation in the same action fails. A post-response+ // continuation cannot survive without that exact resident.+ self.post_response_document_lifecycle = None;+ return;+ };+ let current_document = self.active_page_vm().map(|page_vm| {+ RendererDocumentLifecycleIdentity::from(page_vm.document_lifecycle.current_snapshot())+ });+ if current_document == Some(pending_document) {+ return;+ }+ tracing::debug!(+ ?pending_document,+ ?current_document,+ "retired stale lifecycle continuation at the stable page-residence boundary"+ );+ self.retire_document_lifecycle_turn();+ }++ pub(in crate::runtime) fn pending_document_lifecycle_identity(+ &mut self,+ ) -> Option<RendererDocumentLifecycleIdentity> {+ self.retire_stale_document_lifecycle_turn();+ self.pending_document_lifecycle_turn+ .as_ref()+ .map(|pending| pending.document)+ }++ pub(in crate::runtime) fn defer_document_lifecycle_until_response(+ &mut self,+ document: RendererDocumentLifecycleIdentity,+ ) -> Result<()> {+ anyhow::ensure!(+ self.pending_document_lifecycle_identity() == Some(document),+ "post-response lifecycle continuation does not match the resident Document"+ );+ self.post_response_document_lifecycle = Some(document);+ Ok(())+ }++ pub(super) fn document_lifecycle_is_deferred_until_response(&mut self) -> bool {+ let pending_document = self.pending_document_lifecycle_identity();+ if self.post_response_document_lifecycle == pending_document {+ return pending_document.is_some();+ }+ if self.post_response_document_lifecycle.is_some() {+ self.post_response_document_lifecycle = None;+ }+ false+ }++ pub(super) fn release_document_lifecycle_after_response(+ &mut self,+ document: RendererDocumentLifecycleIdentity,+ ) -> bool {+ if self.post_response_document_lifecycle != Some(document) {+ return false;+ }+ self.post_response_document_lifecycle = None;+ self.pending_document_lifecycle_identity() == Some(document)+ }++ pub(in crate::runtime) fn has_ready_main_parser_script_continuation(&mut self) -> bool {+ self.retire_stale_document_lifecycle_turn();+ let has_sealed_queue = self+ .pending_document_lifecycle_turn+ .as_ref()+ .is_some_and(|pending| pending.has_sealed_main_parser_script_queue);+ has_sealed_queue+ && self+ .page_vm_mut()+ .sealed_main_parser_script_continuation_is_ready()+ }++ pub(in crate::runtime) fn document_lifecycle_owner_turn_is_runnable(&mut self) -> bool {+ self.retire_stale_document_lifecycle_turn();+ self.pending_document_lifecycle_turn+ .as_ref()+ .is_some_and(|pending| pending.owner_turn_is_runnable)+ }++ pub(super) fn observe_document_lifecycle(+ &mut self,+ document: RendererDocumentLifecycleIdentity,+ target_stage: PageVmInitStage,+ ) -> DocumentLifecycleObserverOutcome {+ self.retire_stale_document_lifecycle_turn();+ let page_vm = self.page_vm();+ let current_document = page_vm.document_lifecycle.identity();+ if current_document != document {+ return DocumentLifecycleObserverOutcome::DocumentReplaced {+ document: current_document,+ };+ }++ match page_vm.document_lifecycle_wait_outcome(+ renderer_document_lifecycle_milestone_for_stage(target_stage),+ ) {+ RendererDocumentLifecycleWaitOutcome::Reached(_) => {+ DocumentLifecycleObserverOutcome::Reached+ }+ RendererDocumentLifecycleWaitOutcome::Interrupted(termination) => {+ DocumentLifecycleObserverOutcome::Interrupted(termination)+ }+ RendererDocumentLifecycleWaitOutcome::Pending => {+ classify_pending_document_lifecycle_residence(+ page_vm.vm().has_pending_location_navigation(),+ self.pending_phase_one_navigation.is_some(),+ self.pending_document_lifecycle_turn+ .as_ref()+ .is_some_and(|pending| pending.document == document),+ page_vm.has_blocked_document_replacement_lifecycle_admission(document),+ )+ }+ }+ }++ pub(super) fn prepare_pending_phase_one_navigation_install(+ &self,+ pending: &mut PageVmPendingPhaseOneNavigation,+ ) -> Result<RendererPageToken> {+ pending+ .page_vm_mut()+ .bind_script_execution_control(self.slot.script_execution_control());+ let validation = if self.pending_phase_one_navigation.is_some() {+ Err(anyhow!(+ "renderer page already owns a pending phase-one navigation"+ ))+ } else if self.vm.as_ref().is_some_and(PageVm::has_live_script_vm) {+ Err(anyhow!(+ "phase-one-blocked replacement must be installed after the old document context is detached"+ ))+ } else {+ Ok(())+ };+ if let Err(error) = validation {+ Self::reject_pending_phase_one_navigation_state(+ pending,+ format!("Cannot install navigation: {error}"),+ );+ return Err(error);+ }+ let Some(wake_token) = pending.owner_wake_token() else {+ let error = anyhow!("pending phase-one navigation requires an owner wake token");+ Self::reject_pending_phase_one_navigation_state(+ pending,+ format!("Cannot install navigation: {error}"),+ );+ return Err(error);+ };+ Ok(wake_token)+ }++ /// Install a newly created replacement Document while retaining the Page's+ /// stable typed resource source. The replacement PageVm must share the+ /// source carried by its Page runtime environment; no receiver transfer is+ /// part of Document installation.+ pub(in crate::runtime) fn install_new_pending_phase_one_navigation(+ &mut self,+ mut pending: PageVmPendingPhaseOneNavigation,+ ) -> Result<RendererPageToken> {+ let wake_token = self.prepare_pending_phase_one_navigation_install(&mut pending)?;+ pending.attach_committed_response();+ self.retire_document_lifecycle_turn();+ self.pending_phase_one_navigation = Some(pending);+ Ok(wake_token)+ }++ /// Re-park the same phase-one creation runtime after one bounded+ /// phase-one turn. Its typed resource source already lives in the stable+ /// Page runtime environment and must not be replaced.+ pub(super) fn restore_pending_phase_one_navigation(+ &mut self,+ mut pending: PageVmPendingPhaseOneNavigation,+ ) -> Result<RendererPageToken> {+ let wake_token = self.prepare_pending_phase_one_navigation_install(&mut pending)?;+ self.pending_phase_one_navigation = Some(pending);+ Ok(wake_token)+ }++ pub(super) fn install_resumed_phase_one_page_vm(&mut self, mut page_vm: PageVm) {+ debug_assert!(+ self.pending_phase_one_navigation.is_none(),+ "a resumed phase-one PageVm cannot coexist with its consumed residence"+ );+ self.retire_document_lifecycle_turn();+ page_vm.bind_script_execution_control(self.slot.script_execution_control());+ self.vm = Some(page_vm);+ }++ pub(super) fn reject_pending_phase_one_navigation_state(+ pending: &mut PageVmPendingPhaseOneNavigation,+ message: String,+ ) {+ let browser_context_runtime = pending+ .page_vm()+ .runtime_hooks+ .browser_context_runtime+ .clone();+ pending+ .metadata+ .reject(None, &browser_context_runtime, message);+ pending.page_vm_mut().close_for_context_teardown();+ }++ pub(in crate::runtime) fn take_pending_phase_one_navigation(+ &mut self,+ ) -> Result<PageVmPendingPhaseOneNavigation> {+ self.pending_phase_one_navigation+ .take()+ .ok_or_else(|| anyhow!("renderer page has no pending phase-one navigation to resume"))+ }++ pub(super) fn reject_pending_phase_one_navigation_in_place(&mut self, message: &str) {+ let Some(mut pending) = self.pending_phase_one_navigation.take() else {+ return;+ };+ Self::reject_pending_phase_one_navigation_state(&mut pending, message.to_owned());+ }++ /// Reject the committed phase-one navigation and irreversibly transition+ /// this checked-out entry out of the live state.+ pub(in crate::runtime) fn reject_pending_phase_one_navigation(+ mut self,+ message: &str,+ ) -> RetiringPageEntry {+ self.reject_pending_phase_one_navigation_in_place(message);+ RetiringPageEntry::new(self)+ }++ pub(super) fn close_for_context_teardown(&mut self) {+ self.retire_document_lifecycle_turn();+ self.reject_pending_phase_one_navigation_in_place(+ "Location navigation was cancelled because its page was retired.",+ );+ if let Some(vm) = self.vm.as_mut() {+ vm.close_for_context_teardown();+ }+ }++ pub(super) fn next_javascript_timer_deadline(&self) -> Option<std::time::Instant> {+ self.page_vm().vm().next_timeout_deadline()+ }+}++pub(super) fn classify_pending_document_lifecycle_residence(+ has_pending_location_navigation: bool,+ has_pending_phase_one_navigation: bool,+ has_exact_document_lifecycle_turn: bool,+ has_blocked_document_replacement_lifecycle_admission: bool,+) -> DocumentLifecycleObserverOutcome {+ if has_pending_location_navigation {+ DocumentLifecycleObserverOutcome::NavigationPending+ } else if has_pending_phase_one_navigation+ || has_exact_document_lifecycle_turn+ || has_blocked_document_replacement_lifecycle_admission+ {+ DocumentLifecycleObserverOutcome::Pending+ } else {+ DocumentLifecycleObserverOutcome::MissingResident+ }+}diff --git a/moli-renderer-v8/src/runtime/owner_local_store.rs b/moli-renderer-v8/src/runtime/owner_local_store/mod.rssimilarity index 58%rename from moli-renderer-v8/src/runtime/owner_local_store.rsrename to moli-renderer-v8/src/runtime/owner_local_store/mod.rsindex 95dfad3bd..1c31e7331 100644--- a/moli-renderer-v8/src/runtime/owner_local_store.rs+++ b/moli-renderer-v8/src/runtime/owner_local_store/mod.rs@@ -46,140 +46,22 @@ use crate::script_vm::{use crate::{RendererNavigationReplyPolicy, RendererTopLevelNavigationDispatch};use tokio::sync::oneshot;-#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]-enum StandaloneNavigationFollowState {- #[default]- Idle,- Following {- handoff: crate::page_task_queue::RendererTopLevelNavigationHandoff,- },- FailedWithPendingNavigation {- handoff: crate::page_task_queue::RendererTopLevelNavigationHandoff,- },-}--#[derive(Clone, Copy, Debug, Eq, PartialEq)]-pub(super) struct PublishedReplacementDocument {- pub(super) navigation_handoff: crate::page_task_queue::RendererTopLevelNavigationHandoff,- pub(super) vm_creation_id: u64,- pub(super) view_generation: u64,-}--impl StandaloneNavigationFollowState {- fn claim(- &mut self,- current: Option<crate::page_task_queue::RendererTopLevelNavigationHandoff>,- requested: Option<crate::page_task_queue::RendererTopLevelNavigationHandoff>,- ) -> bool {- if matches!(- *self,- Self::FailedWithPendingNavigation { handoff } if Some(handoff) != current- ) {- *self = Self::Idle;- }- let Some(current) = current else {- return false;- };- if requested.is_some_and(|requested| requested != current) {- return false;- }- if !matches!(*self, Self::Idle) {- return false;- }- *self = Self::Following { handoff: current };- true- }-- fn settle(- &mut self,- current: Option<crate::page_task_queue::RendererTopLevelNavigationHandoff>,- succeeded: bool,- ) {- *self = match *self {- Self::Following { .. } if !succeeded => current- .map(|handoff| Self::FailedWithPendingNavigation { handoff })- .unwrap_or(Self::Idle),- Self::Following { .. } => Self::Idle,- Self::FailedWithPendingNavigation { handoff } if Some(handoff) != current => Self::Idle,- state => state,- };- }-}--pub(super) struct LivePageEntry {- pub(super) slot: RendererPageSlotHandle,- top_level_navigation_dispatch: RendererTopLevelNavigationDispatch,- standalone_navigation_follow: StandaloneNavigationFollowState,- // Keep executable continuation state before `vm`: Rust drops fields in- // declaration order, so an exceptional entry drop still releases any- // ScriptVm-bound task before releasing the PageVm itself.- pending_document_lifecycle_turn: Option<PendingDocumentLifecycleTurn>,- post_response_document_lifecycle: Option<RendererDocumentLifecycleIdentity>,- pub(super) vm: Option<PageVm>,- pending_phase_one_navigation: Option<PageVmPendingPhaseOneNavigation>,- last_published_replacement_document: Option<PublishedReplacementDocument>,-}--/// A checked-out Page entry whose final active `PageVm` has been consumed by-/// teardown and which can therefore only return through the retiring-/// residence boundary.-///-/// The wrapped entry is deliberately private: owner code cannot convert this-/// state back into [`LivePageEntry`] or accidentally pass it to a live-entry-/// restore path.-pub(super) struct RetiringPageEntry {- entry: LivePageEntry,-}--impl RetiringPageEntry {- fn new(entry: LivePageEntry) -> Self {- assert!(- entry.active_page_vm().is_none(),- "a retiring Page entry must not retain an active PageVm"- );- Self { entry }- }-- pub(super) fn settle_standalone_navigation_follow(&mut self, succeeded: bool) {- self.entry.settle_standalone_navigation_follow(succeeded);- }-}+mod bound;+mod entry;+mod phase_one;+#[cfg(test)]+mod tests;-impl std::fmt::Debug for LivePageEntry {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- f.debug_struct("LivePageEntry")- .field("slot", &self.slot)- .field(- "top_level_navigation_dispatch",- &self.top_level_navigation_dispatch,- )- .field(- "standalone_navigation_follow",- &self.standalone_navigation_follow,- )- .field("vm", &self.vm)- .field(- "pending_document_lifecycle_turn",- &self- .pending_document_lifecycle_turn- .as_ref()- .map(|pending| pending.document),- )- .field(- "post_response_document_lifecycle",- &self.post_response_document_lifecycle,- )- .field(- "has_pending_phase_one_navigation",- &self.pending_phase_one_navigation.is_some(),- )- .field(- "last_published_replacement_document",- &self.last_published_replacement_document,- )- .finish()- }-}+pub(in crate::runtime) use bound::*;+#[cfg(test)]+use entry::StandaloneNavigationFollowState;+pub(in crate::runtime) use entry::{+ LivePageEntry, PublishedReplacementDocument, RetiringPageEntry,+};+pub(in crate::runtime) use phase_one::{+ LivePagePendingNavigationPhaseOneAdvance, PendingPhaseOneEntryAdvance,+ advance_pending_phase_one_navigation_on_entry_via_local_task,+};pub(super) type LivePageEntryCheckout =std::result::Result<LivePageEntry, LivePageEntryCheckoutError>;@@ -551,39 +433,6 @@ pub(super) struct LivePageNavigationFollowTurn {pub(super) document_commit: Option<PublishedReplacementDocument>,}-pub(super) enum LivePagePendingNavigationPhaseOneAdvance {- /// The resumed parser yielded again. The caller restores the entry before- /// deriving a one-shot admission wake from the stable Page slot.- Pending {- wake_token: RendererPageToken,- },- TriggeredNavigation {- stage: PageVmInitStage,- },- PostParseLifecycle {- target_stage: PageVmInitStage,- outcome: DocumentLifecycleTurnOutcome,- },-}--/// Result of advancing a checked-out phase-one navigation residence.-///-/// Resuming phase one temporarily consumes the Page's only active VM. Most-/// outcomes install that VM (or a new pending residence) back into the live-/// entry, but an unrecoverable resume failure leaves only a teardown shell.-/// Keeping those states in separate variants prevents the owner from passing-/// that shell to a live-entry restore API.-pub(super) enum PendingPhaseOneEntryAdvance {- Live {- entry: LivePageEntry,- result: Result<LivePagePendingNavigationPhaseOneAdvance>,- },- Retiring {- entry: RetiringPageEntry,- error: anyhow::Error,- },-}-pub(super) struct RendererOwnerLocalContext {pub(super) owner_state: Arc<RendererOwnerState>,pub(super) render_runtime: crate::render_runtime::RenderRuntimeHandle,@@ -744,1659 +593,134 @@ impl RendererOwnerLocalPageSlot {earliest_deadline(timer_deadline, internal_loading_deadline)}- #[cfg(debug_assertions)]- fn local_page_task_deadline(&self) -> Option<std::time::Instant> {- let entry = self.turn_scheduler.resident()?;- let timer_deadline = entry.next_javascript_timer_deadline();- let internal_loading_deadline = self- .task_sources- .local_internal_loading_deadline(entry.page_vm().current_page_internal_loading_owner());- earliest_deadline(timer_deadline, internal_loading_deadline)- }-}--fn earliest_deadline(- left: Option<std::time::Instant>,- right: Option<std::time::Instant>,-) -> Option<std::time::Instant> {- match (left, right) {- (Some(left), Some(right)) => Some(left.min(right)),- (Some(deadline), None) | (None, Some(deadline)) => Some(deadline),- (None, None) => None,- }-}--impl Drop for RendererOwnerLocalPageSlot {- fn drop(&mut self) {- // This is the stable Page lifetime boundary. A replacement PageVm- // drops only Document-owned queues; retiring the slot also discards- // V8 foreground work and typed Page source payloads.- self.task_sources.clear();- self.script_environment_pin- .environment- .retire_output_stream();- self.script_environment_pin.clear_page_runtime_tasks();- }-}--#[derive(Debug)]-struct RendererDocumentIsolateReservationEntry {- id: u64,- handle: RendererDocumentIsolateHandle,- /// The stream opens together with the isolate reservation, before that- /// isolate is attached to a stable Page slot. Until attachment transfers- /// lifetime ownership to `RendererPageScriptEnvironmentPin`, this entry- /// must close the stream on every cancellation/failure path.- output_journal: RendererTurnOutputJournal,- /// Initial page creation owns the not-yet-attached consumer set here.- /// A same-Page replacement reservation reuses the live slot's producer- /// routes and therefore must not manufacture a second consumer set.- initial_task_sources: Option<RendererPageOwnedTaskSources>,- _accounting: RendererDocumentIsolateReservationAccounting,-}--#[derive(Clone)]-pub(crate) struct RendererDocumentIsolateAllocator {- owner: RendererOwnerLocalContext,- page_id: PageId,-}--#[derive(Clone)]-pub(crate) struct RendererDocumentIsolateReservation {- inner: Rc<RendererDocumentIsolateReservationState>,-}--struct RendererDocumentIsolateReservationState {- token: RendererPageToken,- reservation_id: u64,- active: std::cell::Cell<bool>,-}--impl RendererDocumentIsolateAllocator {- pub(super) fn new(owner: RendererOwnerLocalContext, page_id: PageId) -> Self {- Self { owner, page_id }- }-- pub(crate) fn reserve_renderer_document_isolate(- &self,- page_runtime_task_source: crate::page_task_queue::PageRuntimeTaskSource,- ) -> Result<(- RendererDocumentIsolateBootstrap,- RendererDocumentIsolateReservation,- )> {- reserve_renderer_document_isolate_on_bound_owner_local_store(- &self.owner,- self.page_id,- page_runtime_task_source,- )- }-}--impl RendererDocumentIsolateReservation {- fn token(&self) -> RendererPageToken {- self.inner.token- }-- fn reservation_id(&self) -> u64 {- self.inner.reservation_id- }-- fn disarm_for_attach(&self) {- self.inner.active.set(false);- }-- pub(crate) fn is_active(&self) -> bool {- self.inner.active.get()- }-}--impl std::fmt::Debug for RendererDocumentIsolateReservation {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- f.debug_struct("RendererDocumentIsolateReservation")- .field("token", &self.inner.token)- .field("reservation_id", &self.inner.reservation_id)- .field("active", &self.inner.active.get())- .finish()- }-}--impl Drop for RendererDocumentIsolateReservationState {- fn drop(&mut self) {- if self.active.get() && has_current_render_runtime_owner_local_store() {- remove_reserved_renderer_document_isolate_on_bound_owner_local_store(- self.token,- self.reservation_id,- );- self.active.set(false);- }- }-}--impl LivePageEntry {- fn new(slot: RendererPageSlotHandle, mut vm: PageVm) -> Result<Self> {- vm.bind_script_execution_control(slot.script_execution_control());- Ok(Self {- slot,- top_level_navigation_dispatch:- RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,- standalone_navigation_follow: StandaloneNavigationFollowState::Idle,- pending_document_lifecycle_turn: None,- post_response_document_lifecycle: None,- vm: Some(vm),- pending_phase_one_navigation: None,- last_published_replacement_document: None,- })- }-- fn new_with_pending_phase_one_navigation(- slot: RendererPageSlotHandle,- mut pending: PageVmPendingPhaseOneNavigation,- ) -> Result<Self> {- pending- .page_vm_mut()- .bind_script_execution_control(slot.script_execution_control());- let mut entry = Self {- slot,- top_level_navigation_dispatch:- RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,- standalone_navigation_follow: StandaloneNavigationFollowState::Idle,- pending_document_lifecycle_turn: None,- post_response_document_lifecycle: None,- vm: None,- pending_phase_one_navigation: None,- last_published_replacement_document: None,- };- entry.prepare_pending_phase_one_navigation_install(&mut pending)?;- entry.pending_phase_one_navigation = Some(pending);- Ok(entry)- }-- pub(super) fn page_vm(&self) -> &PageVm {- self.active_page_vm()- .expect("resident renderer page entry must retain an active PageVm")- }-- pub(super) fn set_top_level_navigation_dispatch(- &mut self,- dispatch: RendererTopLevelNavigationDispatch,- ) {- self.top_level_navigation_dispatch = dispatch;- }-- pub(super) fn top_level_navigation_dispatch(&self) -> RendererTopLevelNavigationDispatch {- self.top_level_navigation_dispatch- }-- /// Claim the single standalone owner chain for the current pending- /// location navigation. A failed chain remains suppressed while that same- /// descriptor is pending, so a duplicate producer handoff cannot restart- /// the chain with a fresh limit.- pub(super) fn begin_standalone_navigation_follow(&mut self) -> bool {- self.begin_standalone_navigation_follow_for_handoff(None)- }-- /// Claim a producer handoff only while the same request still occupies- /// the ScriptVm's unique pending navigation slot. A delayed wake for an- /// overwritten request therefore cannot start the replacement request.- pub(super) fn begin_standalone_navigation_follow_from_handoff(- &mut self,- handoff: crate::page_task_queue::RendererTopLevelNavigationHandoff,- ) -> bool {- self.begin_standalone_navigation_follow_for_handoff(Some(handoff))- }-- fn begin_standalone_navigation_follow_for_handoff(- &mut self,- requested: Option<crate::page_task_queue::RendererTopLevelNavigationHandoff>,- ) -> bool {- if !matches!(- self.top_level_navigation_dispatch,- RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter- ) {- return false;- }- let current = self- .active_page_vm()- .and_then(|page_vm| page_vm.vm().pending_location_navigation_handoff());- self.standalone_navigation_follow.claim(current, requested)- }-- pub(super) fn settle_standalone_navigation_follow(&mut self, succeeded: bool) {- let current = self- .active_page_vm()- .and_then(|page_vm| page_vm.vm().pending_location_navigation_handoff());- self.standalone_navigation_follow.settle(current, succeeded);- }-- /// A replacement PageVm becomes the active owner-local runtime before its- /// view is committed to the stable cross-thread Page slot.- pub(super) fn has_uncommitted_page_vm(&self) -> bool {- self.uncommitted_page_vm_creation_id().is_some()- }-- pub(super) fn uncommitted_page_vm_creation_id(&self) -> Option<u64> {- let stable_entry = self.slot.entry();- if !stable_entry.is_active() {- return None;- }- self.active_page_vm().and_then(|page_vm| {- (stable_entry.vm_creation_id() != page_vm.creation_id).then_some(page_vm.creation_id)- })- }-- fn publish_replacement_document_commit(&mut self) -> Result<PublishedReplacementDocument> {- let stable_before = self.slot.entry();- ensure!(- stable_before.is_active(),- "replacement Document cannot commit into a retired Page slot"- );- let page_vm = self- .active_page_vm()- .ok_or_else(|| anyhow!("replacement Document commit lost its active PageVm"))?;- let vm_creation_id = page_vm.creation_id;- let navigation_handoff =- page_vm- .replacement_document_commit_handoff()- .ok_or_else(|| {- anyhow!("replacement PageVm is missing its navigation commit identity")- })?;- ensure!(- stable_before.vm_creation_id() != vm_creation_id,- "replacement Document commit attempted to republish stable PageVm {vm_creation_id}"- );- ensure!(- self.last_published_replacement_document- .is_none_or(|published| {- published.vm_creation_id != vm_creation_id- && published.navigation_handoff != navigation_handoff- }),- "replacement Document commit attempted to reuse a published navigation or PageVm identity"- );-- self.page_vm_mut()- .settle_replacement_document_commit(navigation_handoff)?;- RendererOwnerLocalStore::commit_active_vm_page_state_on_entry(self)?;- let stable_after = self.slot.entry();- ensure!(- stable_after.vm_creation_id() == vm_creation_id,- "replacement Document publication did not install its PageVm identity"- );- ensure!(- stable_after.view_generation > stable_before.view_generation,- "replacement Document publication did not advance the stable view generation"- );- let published = PublishedReplacementDocument {- navigation_handoff,- vm_creation_id,- view_generation: stable_after.view_generation,- };- self.last_published_replacement_document = Some(published);-- // Pending phase one owns the committed replacement. The old PageVm- // was already terminated before the response commit and can no longer- // be a rollback candidate.- if self.pending_phase_one_navigation.is_some() {- self.vm = None;- }- Ok(published)- }-- pub(super) fn active_page_vm(&self) -> Option<&PageVm> {- self.pending_phase_one_navigation- .as_ref()- .map(PageVmPendingPhaseOneNavigation::page_vm)- .or(self.vm.as_ref())- }-- pub(super) fn page_vm_mut(&mut self) -> &mut PageVm {- let control = self.slot.script_execution_control();- let page_vm = if let Some(pending) = self.pending_phase_one_navigation.as_mut() {- pending.page_vm_mut()- } else {- self.vm- .as_mut()- .expect("resident renderer page entry must retain an active PageVm")- };- page_vm.bind_script_execution_control(control);- page_vm- }-- pub(super) fn pending_phase_one_navigation_has_ready_streaming_input(&mut self) -> bool {- self.pending_phase_one_navigation- .as_mut()- .is_some_and(PageVmPendingPhaseOneNavigation::has_ready_streaming_input)- }-- fn page_vm_and_document_lifecycle_turn_mut(- &mut self,- ) -> (&mut PageVm, &mut Option<PendingDocumentLifecycleTurn>) {- self.retire_stale_document_lifecycle_turn();- let Self {- vm,- pending_document_lifecycle_turn,- pending_phase_one_navigation,- ..- } = self;- let page_vm = if let Some(pending) = pending_phase_one_navigation.as_mut() {- pending.page_vm_mut()- } else {- vm.as_mut()- .expect("resident renderer page entry must retain an active PageVm")- };- (page_vm, pending_document_lifecycle_turn)- }-- fn retire_document_lifecycle_turn(&mut self) {- self.pending_document_lifecycle_turn = None;- self.post_response_document_lifecycle = None;- }-- fn retire_stale_document_lifecycle_turn(&mut self) {- let Some(pending_document) = self- .pending_document_lifecycle_turn- .as_ref()- .map(|pending| pending.document)- else {- // A bounded lifecycle action may retire its resident before a- // later operation in the same action fails. A post-response- // continuation cannot survive without that exact resident.- self.post_response_document_lifecycle = None;- return;- };- let current_document = self.active_page_vm().map(|page_vm| {- RendererDocumentLifecycleIdentity::from(page_vm.document_lifecycle.current_snapshot())- });- if current_document == Some(pending_document) {- return;- }- tracing::debug!(- ?pending_document,- ?current_document,- "retired stale lifecycle continuation at the stable page-residence boundary"- );- self.retire_document_lifecycle_turn();- }-- pub(super) fn pending_document_lifecycle_identity(- &mut self,- ) -> Option<RendererDocumentLifecycleIdentity> {- self.retire_stale_document_lifecycle_turn();- self.pending_document_lifecycle_turn- .as_ref()- .map(|pending| pending.document)- }-- pub(super) fn defer_document_lifecycle_until_response(- &mut self,- document: RendererDocumentLifecycleIdentity,- ) -> Result<()> {- anyhow::ensure!(- self.pending_document_lifecycle_identity() == Some(document),- "post-response lifecycle continuation does not match the resident Document"- );- self.post_response_document_lifecycle = Some(document);- Ok(())- }-- fn document_lifecycle_is_deferred_until_response(&mut self) -> bool {- let pending_document = self.pending_document_lifecycle_identity();- if self.post_response_document_lifecycle == pending_document {- return pending_document.is_some();- }- if self.post_response_document_lifecycle.is_some() {- self.post_response_document_lifecycle = None;- }- false- }-- fn release_document_lifecycle_after_response(- &mut self,- document: RendererDocumentLifecycleIdentity,- ) -> bool {- if self.post_response_document_lifecycle != Some(document) {- return false;- }- self.post_response_document_lifecycle = None;- self.pending_document_lifecycle_identity() == Some(document)- }-- pub(super) fn has_ready_main_parser_script_continuation(&mut self) -> bool {- self.retire_stale_document_lifecycle_turn();- let has_sealed_queue = self- .pending_document_lifecycle_turn- .as_ref()- .is_some_and(|pending| pending.has_sealed_main_parser_script_queue);- has_sealed_queue- && self- .page_vm_mut()- .sealed_main_parser_script_continuation_is_ready()- }-- pub(super) fn document_lifecycle_owner_turn_is_runnable(&mut self) -> bool {- self.retire_stale_document_lifecycle_turn();- self.pending_document_lifecycle_turn- .as_ref()- .is_some_and(|pending| pending.owner_turn_is_runnable)- }-- fn observe_document_lifecycle(- &mut self,- document: RendererDocumentLifecycleIdentity,- target_stage: PageVmInitStage,- ) -> DocumentLifecycleObserverOutcome {- self.retire_stale_document_lifecycle_turn();- let page_vm = self.page_vm();- let current_document = page_vm.document_lifecycle.identity();- if current_document != document {- return DocumentLifecycleObserverOutcome::DocumentReplaced {- document: current_document,- };- }-- match page_vm.document_lifecycle_wait_outcome(- renderer_document_lifecycle_milestone_for_stage(target_stage),- ) {- RendererDocumentLifecycleWaitOutcome::Reached(_) => {- DocumentLifecycleObserverOutcome::Reached- }- RendererDocumentLifecycleWaitOutcome::Interrupted(termination) => {- DocumentLifecycleObserverOutcome::Interrupted(termination)- }- RendererDocumentLifecycleWaitOutcome::Pending => {- classify_pending_document_lifecycle_residence(- page_vm.vm().has_pending_location_navigation(),- self.pending_phase_one_navigation.is_some(),- self.pending_document_lifecycle_turn- .as_ref()- .is_some_and(|pending| pending.document == document),- page_vm.has_blocked_document_replacement_lifecycle_admission(document),- )- }- }- }-- fn prepare_pending_phase_one_navigation_install(- &self,- pending: &mut PageVmPendingPhaseOneNavigation,- ) -> Result<RendererPageToken> {- pending- .page_vm_mut()- .bind_script_execution_control(self.slot.script_execution_control());- let validation = if self.pending_phase_one_navigation.is_some() {- Err(anyhow!(- "renderer page already owns a pending phase-one navigation"- ))- } else if self.vm.as_ref().is_some_and(PageVm::has_live_script_vm) {- Err(anyhow!(- "phase-one-blocked replacement must be installed after the old document context is detached"- ))- } else {- Ok(())- };- if let Err(error) = validation {- Self::reject_pending_phase_one_navigation_state(- pending,- format!("Cannot install navigation: {error}"),- );- return Err(error);- }- let Some(wake_token) = pending.owner_wake_token() else {- let error = anyhow!("pending phase-one navigation requires an owner wake token");- Self::reject_pending_phase_one_navigation_state(- pending,- format!("Cannot install navigation: {error}"),- );- return Err(error);- };- Ok(wake_token)- }-- /// Install a newly created replacement Document while retaining the Page's- /// stable typed resource source. The replacement PageVm must share the- /// source carried by its Page runtime environment; no receiver transfer is- /// part of Document installation.- pub(super) fn install_new_pending_phase_one_navigation(- &mut self,- mut pending: PageVmPendingPhaseOneNavigation,- ) -> Result<RendererPageToken> {- let wake_token = self.prepare_pending_phase_one_navigation_install(&mut pending)?;- pending.attach_committed_response();- self.retire_document_lifecycle_turn();- self.pending_phase_one_navigation = Some(pending);- Ok(wake_token)- }-- /// Re-park the same phase-one creation runtime after one bounded- /// phase-one turn. Its typed resource source already lives in the stable- /// Page runtime environment and must not be replaced.- fn restore_pending_phase_one_navigation(- &mut self,- mut pending: PageVmPendingPhaseOneNavigation,- ) -> Result<RendererPageToken> {- let wake_token = self.prepare_pending_phase_one_navigation_install(&mut pending)?;- self.pending_phase_one_navigation = Some(pending);- Ok(wake_token)- }-- fn install_resumed_phase_one_page_vm(&mut self, mut page_vm: PageVm) {- debug_assert!(- self.pending_phase_one_navigation.is_none(),- "a resumed phase-one PageVm cannot coexist with its consumed residence"- );- self.retire_document_lifecycle_turn();- page_vm.bind_script_execution_control(self.slot.script_execution_control());- self.vm = Some(page_vm);- }-- fn reject_pending_phase_one_navigation_state(- pending: &mut PageVmPendingPhaseOneNavigation,- message: String,- ) {- let browser_context_runtime = pending- .page_vm()- .runtime_hooks- .browser_context_runtime- .clone();- pending- .metadata- .reject(None, &browser_context_runtime, message);- pending.page_vm_mut().close_for_context_teardown();- }-- pub(super) fn take_pending_phase_one_navigation(- &mut self,- ) -> Result<PageVmPendingPhaseOneNavigation> {- self.pending_phase_one_navigation- .take()- .ok_or_else(|| anyhow!("renderer page has no pending phase-one navigation to resume"))- }-- fn reject_pending_phase_one_navigation_in_place(&mut self, message: &str) {- let Some(mut pending) = self.pending_phase_one_navigation.take() else {- return;- };- Self::reject_pending_phase_one_navigation_state(&mut pending, message.to_owned());- }-- /// Reject the committed phase-one navigation and irreversibly transition- /// this checked-out entry out of the live state.- pub(super) fn reject_pending_phase_one_navigation(- mut self,- message: &str,- ) -> RetiringPageEntry {- self.reject_pending_phase_one_navigation_in_place(message);- RetiringPageEntry::new(self)- }-- fn close_for_context_teardown(&mut self) {- self.retire_document_lifecycle_turn();- self.reject_pending_phase_one_navigation_in_place(- "Location navigation was cancelled because its page was retired.",- );- if let Some(vm) = self.vm.as_mut() {- vm.close_for_context_teardown();- }- }-- fn next_javascript_timer_deadline(&self) -> Option<std::time::Instant> {- self.page_vm().vm().next_timeout_deadline()- }-}--fn classify_pending_document_lifecycle_residence(- has_pending_location_navigation: bool,- has_pending_phase_one_navigation: bool,- has_exact_document_lifecycle_turn: bool,- has_blocked_document_replacement_lifecycle_admission: bool,-) -> DocumentLifecycleObserverOutcome {- if has_pending_location_navigation {- DocumentLifecycleObserverOutcome::NavigationPending- } else if has_pending_phase_one_navigation- || has_exact_document_lifecycle_turn- || has_blocked_document_replacement_lifecycle_admission- {- DocumentLifecycleObserverOutcome::Pending- } else {- DocumentLifecycleObserverOutcome::MissingResident- }-}--pub(super) struct RenderRuntimeOwnerLocalStoreBinding;--fn with_bound_render_runtime_owner_local_store_session<R>(- f: impl FnOnce(RendererOwnerLocalStoreSession<'_>) -> R,-) -> R {- CURRENT_RENDER_RUNTIME_OWNER_LOCAL_STORE.with(|current_store| {- let mut store = current_store- .borrow()- .expect("bound render-runtime owner-local store should exist on current thread");- // Safety: the pointer is installed only for the lifetime of the- // render-runtime owner loop on the current thread.- unsafe {- f(RendererOwnerLocalStoreSession {- store: store.as_mut(),- })- }- })-}--pub(super) fn bind_render_runtime_owner_local_store(- store: &mut RendererOwnerLocalStore,-) -> RenderRuntimeOwnerLocalStoreBinding {- CURRENT_RENDER_RUNTIME_OWNER_LOCAL_STORE.with(|current_store| {- let mut current_store = current_store.borrow_mut();- assert!(- current_store.is_none(),- "render-runtime owner-local store must not be rebound while already active"- );- *current_store = Some(NonNull::from(store));- });- RenderRuntimeOwnerLocalStoreBinding-}--pub(super) fn has_current_render_runtime_owner_local_store() -> bool {- CURRENT_RENDER_RUNTIME_OWNER_LOCAL_STORE.with(|current_store| current_store.borrow().is_some())-}--pub(super) fn owner_local_store_session(- store: &mut RendererOwnerLocalStore,-) -> RendererOwnerLocalStoreSession<'_> {- RendererOwnerLocalStoreSession { store }-}--pub(super) fn install_page_vm_on_bound_owner_local_store(- owner_local: &RendererOwnerLocalContext,- requested_url: Url,- navigation_initiator_url: Option<Url>,- navigation_redirected: bool,- navigation_redirect_count: usize,- response_status: u16,- response_headers: Vec<(String, String)>,- vm: PageVm,- pending_download: Option<RendererPendingDownloadActivation>,- lifecycle_gate: Option<PageVmInitStage>,-) -> Result<RendererPendingPageCreation> {- with_bound_render_runtime_owner_local_store_session(|mut session| {- session.install_page_vm(- owner_local,- requested_url,- navigation_initiator_url,- navigation_redirected,- navigation_redirect_count,- response_status,- response_headers,- vm,- pending_download,- lifecycle_gate,- )- })-}--pub(super) fn install_phase_one_blocked_page_on_bound_owner_local_store(- owner_local: &RendererOwnerLocalContext,- requested_url: Url,- navigation_initiator_url: Option<Url>,- navigation_redirected: bool,- navigation_redirect_count: usize,- response_status: u16,- response_headers: Vec<(String, String)>,- pending_navigation: PageVmPendingPhaseOneNavigation,- lifecycle_gate: Option<PageVmInitStage>,-) -> Result<RendererPendingPageCreation> {- with_bound_render_runtime_owner_local_store_session(|mut session| {- session.install_phase_one_blocked_page_for_owner(- owner_local,- requested_url,- navigation_initiator_url,- navigation_redirected,- navigation_redirect_count,- response_status,- response_headers,- pending_navigation,- lifecycle_gate,- )- })-}--pub(super) fn finalize_pending_page_creation_on_bound_owner_local_store(- pending: RendererPendingPageCreation,-) -> RendererPageCreationCommit {- with_bound_render_runtime_owner_local_store_session(|mut session| {- session.finalize_pending_page_creation(pending)- })-}--pub(super) fn resolve_pending_page_creation_on_bound_owner_local_store(- pending: RendererPendingPageCreation,- document: RendererDocumentLifecycleIdentity,- target_stage: PageVmInitStage,- navigation_reply_policy: NavigationReplyPolicy,-) -> RendererPageCreationResolution {- // This operation runs inside one owner-lane task and contains no await- // boundary. Before the task starts the entry remains resident; once it is- // checked out, observation and the resulting page-state refresh,- // restoration, or retirement run to completion without exposing the entry- // to the outer owner loop.- with_bound_render_runtime_owner_local_store_session(|session| {- session.store.resolve_pending_page_creation(- pending,- document,- target_stage,- navigation_reply_policy,- )- })-}--fn reserve_renderer_document_isolate_on_bound_owner_local_store(- owner_local: &RendererOwnerLocalContext,- page_id: PageId,- page_runtime_task_source: crate::page_task_queue::PageRuntimeTaskSource,-) -> Result<(- RendererDocumentIsolateBootstrap,- RendererDocumentIsolateReservation,-)> {- with_bound_render_runtime_owner_local_store_session(|mut session| {- session.reserve_renderer_document_isolate(owner_local, page_id, page_runtime_task_source)- })-}--fn remove_reserved_renderer_document_isolate_on_bound_owner_local_store(- token: RendererPageToken,- reservation_id: u64,-) {- with_bound_render_runtime_owner_local_store_session(|mut session| {- session.remove_reserved_renderer_document_isolate(token, reservation_id)- })-}--async fn run_on_bound_owner_local_store_local_task<R, F>(- local_executor: JsLocalExecutor,- future: F,-) -> Result<R>-where- R: 'static,- F: Future<Output = Result<R>> + 'static,-{- run_named_owner_local_task(- local_executor,- "bound render-runtime owner-local local task was cancelled",- future,- )- .await-}--pub(super) type EntryLocalTaskFuture<'a, R> = Pin<Box<dyn Future<Output = Result<R>> + 'a>>;--#[cfg(debug_assertions)]-const PANIC_WAIT_FOR_SELECTOR_FOR_TESTING: &str = "__moli_panic_wait_for_selector_for_testing__";-#[cfg(debug_assertions)]-const PANIC_WAIT_FOR_SCRIPT_TRUTHY_FOR_TESTING: &str =- "__moli_panic_wait_for_script_truthy_for_testing__";--struct EntryLocalTaskGuard<E, R> {- entry: Option<E>,- reply_tx: Option<oneshot::Sender<(E, Result<R>)>>,-}--impl<E, R> EntryLocalTaskGuard<E, R> {- fn new(entry: E, reply_tx: oneshot::Sender<(E, Result<R>)>) -> Self {- Self {- entry: Some(entry),- reply_tx: Some(reply_tx),- }- }-- fn entry_mut(&mut self) -> &mut E {- self.entry- .as_mut()- .expect("entry local task guard should retain its page entry")- }-- fn complete(mut self, result: Result<R>) {- let entry = self- .entry- .take()- .expect("entry local task guard should retain its page entry on completion");- let reply_tx = self- .reply_tx- .take()- .expect("entry local task guard should retain its reply sender on completion");- let _ = reply_tx.send((entry, result));- }-}--impl<E, R> Drop for EntryLocalTaskGuard<E, R> {- fn drop(&mut self) {- if let (Some(entry), Some(reply_tx)) = (self.entry.take(), self.reply_tx.take()) {- let _ = reply_tx.send((- entry,- Err(anyhow!(- "bound render-runtime owner-local local task panicked before restoring its page entry"- )),- ));- }- }-}--pub(super) async fn run_entry_on_bound_owner_local_store_local_task<R, F>(- local_executor: JsLocalExecutor,- entry: LivePageEntry,- operation: F,-) -> (LivePageEntry, Result<R>)-where- R: 'static,- F: for<'a> FnOnce(&'a mut LivePageEntry) -> EntryLocalTaskFuture<'a, R> + 'static,-{- let (reply_tx, reply_rx) = oneshot::channel();- // Construct the guard before spawning. If the local task is cancelled- // before its first poll, dropping the future must still return the entry- // and an inner error to the owner so command-specific cleanup can run.- let guard = EntryLocalTaskGuard::new(entry, reply_tx);- tokio::task::spawn_local(async move {- let mut guard = guard;- let result = local_executor- .scope_on_current_thread(operation(guard.entry_mut()))- .await;- guard.complete(result);- });- reply_rx- .await- .expect("entry local task guard must return the page entry on task termination")-}--pub(super) fn take_entry_for_command_on_bound_owner_local_store(- token: RendererPageToken,-) -> Result<LivePageEntry> {- with_bound_render_runtime_owner_local_store_session(|mut session| {- session.take_entry_for_command(token)- })-}--pub(super) fn checkout_entry_for_owner_turn_on_bound_owner_local_store(- token: RendererPageToken,-) -> LivePageEntryCheckout {- with_bound_render_runtime_owner_local_store_session(|mut session| {- session.checkout_entry_for_owner_turn(token)- })-}--pub(super) fn schedule_page_turn_on_bound_owner_local_store(- token: RendererPageToken,- trigger: PageTurnTrigger,-) -> RendererPageTurnAdmission {- with_bound_render_runtime_owner_local_store_session(|session| {- session.store.schedule_page_turn(token, trigger)- })-}--pub(super) fn release_post_response_document_lifecycle_on_bound_owner_local_store(- token: RendererPageToken,- document: RendererDocumentLifecycleIdentity,-) -> bool {- with_bound_render_runtime_owner_local_store_session(|session| {- session- .store- .release_post_response_document_lifecycle(token, document)- })-}--pub(super) fn checkout_scheduled_page_turn_on_bound_owner_local_store(- token: RendererPageToken,-) -> RendererPageTurnCheckout {- with_bound_render_runtime_owner_local_store_session(|session| {- session.store.checkout_scheduled_page_turn(token)- })-}--pub(super) fn has_ready_page_networking_task_on_bound_owner_local_store(- token: RendererPageToken,- current_document: RendererDocumentToken,-) -> bool {- with_bound_render_runtime_owner_local_store_session(|session| {- session- .store- .has_ready_page_networking_task(token, current_document)- })-}--/// Reconcile one restored phase-one residence against its stable-/// producer sources.-///-/// The residence must already be visible in the Page slot before this function-/// is called. A producer may have published its payload and spent its-/// empty-to-nonempty wake before restoration completed; current source-/// readiness is therefore authoritative, while the stored suspension reason-/// only selects the exact source to inspect. No task is dequeued here.-pub(super) fn pending_phase_one_admission_after_restore_on_bound_owner_local_store(- token: RendererPageToken,-) -> PhaseOneResidenceAdmission {- with_bound_render_runtime_owner_local_store_session(|session| {- session- .store- .pending_phase_one_admission_after_restore(token)- })-}--pub(super) fn page_turn_readiness_after_restore_on_bound_owner_local_store(- token: RendererPageToken,-) -> Option<PageOwnerTurnReadiness> {- with_bound_render_runtime_owner_local_store_session(|session| {- session.store.page_turn_readiness_after_restore(token)- })-}--pub(super) fn renderer_output_fence_for_tail_on_bound_owner_local_store(- token: RendererPageToken,-) -> Option<RendererOutputFence> {- with_bound_render_runtime_owner_local_store_session(|session| {- session- .store- .page_hosts- .get(&token.local_host_id)- .and_then(|host| host.pages.get(&token.page_id))- .and_then(|slot| {- let journal = slot.script_environment_pin.environment.output_journal();- journal- .last_published_cursor()- .map(|cursor| journal.declare_fence(cursor))- })- })-}--pub(super) fn restore_entry_after_command_on_bound_owner_local_store(- token: RendererPageToken,- entry: LivePageEntry,-) {- with_bound_render_runtime_owner_local_store_session(|mut session| {- session.restore_entry_after_command(token, entry);- });-}--pub(super) fn restore_retiring_entry_after_command_on_bound_owner_local_store(- token: RendererPageToken,- entry: RetiringPageEntry,-) {- with_bound_render_runtime_owner_local_store_session(|mut session| {- session.restore_retiring_entry_after_command(token, entry);- });-}--pub(super) fn restore_entry_after_document_lifecycle_on_bound_owner_local_store(- token: RendererPageToken,- entry: LivePageEntry,- reconsider_displaced_ordinary: bool,-) {- with_bound_render_runtime_owner_local_store_session(|mut session| {- session.restore_entry_after_command(token, entry);- if let Some(gate) = session- .store- .page_hosts- .get_mut(&token.local_host_id)- .and_then(|host| host.pages.get_mut(&token.page_id))- .and_then(|slot| slot.lifecycle_gate.as_mut())- {- gate.settle_lifecycle_turn(reconsider_displaced_ordinary);- }- });-}--pub(super) fn release_lifecycle_gate_on_bound_owner_local_store(- token: RendererPageToken,-) -> Result<ReleasedLifecycleGate> {- with_bound_render_runtime_owner_local_store_session(|session| {- session.store.release_lifecycle_gate(token)- })-}--pub(super) fn renderer_page_token_for_owner_context(- owner: &RendererOwnerLocalContext,- page_id: PageId,-) -> RendererPageToken {- RendererPageToken {- local_host_id: owner.local_host_id,- #[cfg(debug_assertions)]- local_thread_id: owner.local_thread_id,- page_id,- }-}--pub(super) async fn dispatch_async_command_on_entry_via_local_task(- local_executor: JsLocalExecutor,- entry: LivePageEntry,- command: RendererPageCommand,-) -> (LivePageEntry, Result<RendererPageCommandDispatch>) {- run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {- Box::pin(- async move { RendererOwnerLocalStore::dispatch_async_on_entry(entry, command).await },- )- })- .await-}--/// Command result plus any replacement lifecycle admission created while the-/// Page entry was checked out. The owner must restore stable residence before-/// publishing the admitted lifecycle turn.-pub(super) struct RendererPageCommandDispatch {- pub(super) reply: RendererPageReply,- pub(super) replacement_lifecycle: Option<DocumentLifecycleTurnOutcome>,- pub(super) turn_records: Vec<PendingRendererOutputRecord>,-}--pub(super) async fn advance_runtime_command_lifecycle_on_entry_via_local_task(- local_executor: JsLocalExecutor,- entry: LivePageEntry,- scope_id: PageVmRuntimeCommandOutputScopeId,-) -> (LivePageEntry, Result<PageVmRuntimeCommandLifecycleAdvance>) {- run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {- Box::pin(async move {- entry- .page_vm_mut()- .advance_pending_runtime_command_lifecycle_one_turn(scope_id)- .await- })- })- .await-}--pub(super) async fn begin_post_parse_lifecycle_on_entry_via_local_task(- local_executor: JsLocalExecutor,- entry: LivePageEntry,- work: Vec<PostParsePageOwnedWork>,- stage: PageVmInitStage,- started: std::time::Instant,-) -> (LivePageEntry, Result<DocumentLifecycleTurnOutcome>) {- run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {- Box::pin(async move {- let (page_vm, pending_document_lifecycle_turn) =- entry.page_vm_and_document_lifecycle_turn_mut();- page_vm- .begin_post_parse_lifecycle_on_named_owner_lane(- pending_document_lifecycle_turn,- work,- stage,- started,- )- .await- })- })- .await-}--pub(super) async fn commit_page_state_on_entry_via_local_task(- local_executor: JsLocalExecutor,- entry: LivePageEntry,-) -> (LivePageEntry, Result<Arc<RendererPageState>>) {- commit_page_state_on_entry_via_local_task_with_policy(- local_executor,- entry,- super::RendererPageStateCapturePolicy::FullReport,- )- .await-}--pub(super) async fn commit_page_state_on_entry_via_local_task_with_policy(- local_executor: JsLocalExecutor,- entry: LivePageEntry,- capture_policy: super::RendererPageStateCapturePolicy,-) -> (LivePageEntry, Result<Arc<RendererPageState>>) {- run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {- Box::pin(async move {- RendererOwnerLocalStore::commit_current_vm_page_state_on_entry_with_policy(- entry,- capture_policy,- )- .map_err(|error| anyhow!("failed to refresh renderer owner page view: {error}"))- })- })- .await-}--pub(super) async fn advance_network_idle_wait_turn_on_entry_via_local_task(- local_executor: JsLocalExecutor,- entry: LivePageEntry,- state: PageVmNetworkIdleWaitState,- remaining: std::time::Duration,-) -> (LivePageEntry, Result<PageVmNetworkIdleWaitAdvance>) {- run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {- Box::pin(async move {- entry- .page_vm_mut()- .advance_network_idle_wait_turn(state, remaining)- .await- })- })- .await-}--pub(super) async fn advance_dom_stable_wait_turn_on_entry_via_local_task(- local_executor: JsLocalExecutor,- entry: LivePageEntry,- state: PageVmDomStableWaitState,- remaining: std::time::Duration,-) -> (LivePageEntry, Result<PageVmDomStableWaitAdvance>) {- run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {- Box::pin(async move {- entry- .page_vm_mut()- .advance_dom_stable_wait_turn(state, remaining)- .await- })- })- .await-}--pub(super) async fn advance_selector_wait_turn_on_entry_via_local_task(- local_executor: JsLocalExecutor,- entry: LivePageEntry,- selector: String,- remaining: std::time::Duration,-) -> (LivePageEntry, Result<PageVmCommandWaitAdvance>) {- run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {- Box::pin(async move {- #[cfg(debug_assertions)]- if selector == PANIC_WAIT_FOR_SELECTOR_FOR_TESTING {- panic!("wait-for-selector local task panicked for testing")- }- entry- .page_vm_mut()- .advance_selector_wait_turn(&selector, remaining)- .await- })- })- .await-}--pub(super) async fn advance_script_truthy_wait_turn_on_entry_via_local_task(- local_executor: JsLocalExecutor,- entry: LivePageEntry,- expression: String,- pending_call: Option<PendingRuntimeEvaluateCall>,- remaining: std::time::Duration,-) -> (LivePageEntry, Result<PageVmScriptTruthyWaitAdvance>) {- run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {- Box::pin(async move {- #[cfg(debug_assertions)]- if expression == PANIC_WAIT_FOR_SCRIPT_TRUTHY_FOR_TESTING {- panic!("wait-for-script-truthy local task panicked for testing")- }- entry- .page_vm_mut()- .advance_script_truthy_wait_turn(&expression, pending_call, remaining)- .await- })- })- .await-}--pub(super) async fn advance_runtime_expression_await_turn_on_entry_via_local_task(- local_executor: JsLocalExecutor,- entry: LivePageEntry,- execution_context_id: Option<i64>,- expression: String,- pending_call: Option<PendingRuntimeEvaluateCall>,- remaining: std::time::Duration,-) -> (LivePageEntry, Result<PageVmRuntimeExpressionAwaitAdvance>) {- run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {- Box::pin(async move {- entry- .page_vm_mut()- .advance_runtime_expression_await_turn(- execution_context_id,- &expression,- pending_call,- remaining,- )- .await- })- })- .await-}--pub(super) async fn advance_subresource_response_wait_turn_on_entry_via_local_task(- local_executor: JsLocalExecutor,- entry: LivePageEntry,- criteria: SubresourceResponseWaitCriteria,- remaining: std::time::Duration,-) -> (LivePageEntry, Result<PageVmSubresourceResponseWaitAdvance>) {- run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {- Box::pin(async move {- entry- .page_vm_mut()- .advance_subresource_response_wait_turn(&criteria, remaining)- .await- })- })- .await-}--pub(super) async fn follow_pending_location_navigation_one_turn_on_entry_via_local_task(- local_executor: JsLocalExecutor,- entry: LivePageEntry,- stage: PageVmInitStage,-) -> (LivePageEntry, Result<LivePageNavigationFollowTurn>) {- run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {- Box::pin(async move {- let outcome = {- let (page_vm, pending_document_lifecycle_turn) =- entry.page_vm_and_document_lifecycle_turn_mut();- page_vm- .prepare_pending_location_navigation_document_commit_one_turn_async(- pending_document_lifecycle_turn,- stage,- )- .await- };- let outcome = match outcome? {- PageVmFollowNavigationTurnOutcome::Completed => {- LivePageNavigationFollowOutcome::Completed- }- PageVmFollowNavigationTurnOutcome::PostParseLifecycle {- target_stage,- outcome,- } => LivePageNavigationFollowOutcome::PostParseLifecycle {- target_stage,- outcome,- },- PageVmFollowNavigationTurnOutcome::Download(download) => {- LivePageNavigationFollowOutcome::Download(download)- }- PageVmFollowNavigationTurnOutcome::PendingPhaseOne(pending) => {- let wake_token = entry.install_new_pending_phase_one_navigation(pending)?;- LivePageNavigationFollowOutcome::PendingPhaseOne { wake_token }- }- PageVmFollowNavigationTurnOutcome::TriggeredNavigation { stage } => {- LivePageNavigationFollowOutcome::TriggeredNavigation { stage }- }- };- let document_commit = entry- .has_uncommitted_page_vm()- .then(|| entry.publish_replacement_document_commit())- .transpose()?;- Ok(LivePageNavigationFollowTurn {- outcome,- document_commit,- })- })- })- .await-}--pub(super) async fn advance_pending_phase_one_navigation_on_entry_via_local_task(- local_executor: JsLocalExecutor,- entry: LivePageEntry,-) -> PendingPhaseOneEntryAdvance {- let (entry, result) =- run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {- Box::pin(async move {- let pending = entry.take_pending_phase_one_navigation()?;- let (residence, mut metadata) = pending.into_parts();- let browser_context_runtime = residence- .page_vm()- .runtime_hooks- .browser_context_runtime- .clone();- let phase_one_outcome = match residence.resume().await {- Ok(outcome) => outcome,- Err(error) => {- metadata.reject(- None,- &browser_context_runtime,- format!("Cannot navigate to URL: {error}"),- );- return Err(error);- }- };- let phase_one_outcome = match phase_one_outcome {- PendingPhaseOneResumeOutcome::Progress(outcome) => outcome,- PendingPhaseOneResumeOutcome::MainResourceLoadFailed { page_vm, error } => {- metadata.reject(- None,- &browser_context_runtime,- format!("Cannot navigate to URL: {error}"),- );- entry.install_resumed_phase_one_page_vm(page_vm);- return Err(error);- }- };- match phase_one_outcome {- ParseTimePageVmCreationOutcome::PendingPhaseOne(residence) => {- let pending = PageVmPendingPhaseOneNavigation::new(residence, metadata);- let wake_token = entry.restore_pending_phase_one_navigation(pending)?;- Ok(LivePagePendingNavigationPhaseOneAdvance::Pending { wake_token })- }- ParseTimePageVmCreationOutcome::TriggeredNavigation { mut page_vm, stage } => {- metadata.complete_service_worker_follow(&mut page_vm);- entry.install_resumed_phase_one_page_vm(page_vm);- Ok(LivePagePendingNavigationPhaseOneAdvance::TriggeredNavigation { stage })- }- ParseTimePageVmCreationOutcome::ContinuePhaseTwo {- mut page_vm,- page_tasks,- stage,- started,- } => {- metadata.complete_service_worker_follow(&mut page_vm);- entry.install_resumed_phase_one_page_vm(page_vm);- let (page_vm, pending_document_lifecycle_turn) =- entry.page_vm_and_document_lifecycle_turn_mut();- let outcome = page_vm- .begin_post_parse_lifecycle_on_named_owner_lane(- pending_document_lifecycle_turn,- page_tasks,- stage,- started,- )- .await?;- Ok(- LivePagePendingNavigationPhaseOneAdvance::PostParseLifecycle {- target_stage: stage,- outcome,- },- )- }- }- })- })- .await;-- classify_pending_phase_one_entry_advance(entry, result)-}--fn classify_pending_phase_one_entry_advance(- entry: LivePageEntry,- result: Result<LivePagePendingNavigationPhaseOneAdvance>,-) -> PendingPhaseOneEntryAdvance {- if entry.active_page_vm().is_some() {- PendingPhaseOneEntryAdvance::Live { entry, result }- } else {- let error = result.err().unwrap_or_else(|| {- anyhow!("phase-one navigation advance completed without restoring an active PageVm")- });- PendingPhaseOneEntryAdvance::Retiring {- entry: RetiringPageEntry::new(entry),- error,- }- }-}--pub(super) fn remove_page_on_bound_owner_local_store(token: RendererPageToken) {- with_bound_render_runtime_owner_local_store_session(|mut session| session.remove_page(token))-}--pub(super) fn publish_page_navigation_failure_on_bound_owner_local_store(- token: RendererPageToken,- failure: PageNavigationOwnerFailure,-) -> Result<PageCreationNavigationFailurePublication> {- with_bound_render_runtime_owner_local_store_session(|session| {- session- .store- .publish_page_navigation_failure(token, failure)- })-}--pub(super) async fn remove_page_on_bound_owner_local_store_via_local_task(- local_executor: JsLocalExecutor,- token: RendererPageToken,-) -> Result<()> {- run_on_bound_owner_local_store_local_task(local_executor, async move {- remove_page_on_bound_owner_local_store(token);- Ok(())- })- .await+ #[cfg(debug_assertions)]+ fn local_page_task_deadline(&self) -> Option<std::time::Instant> {+ let entry = self.turn_scheduler.resident()?;+ let timer_deadline = entry.next_javascript_timer_deadline();+ let internal_loading_deadline = self+ .task_sources+ .local_internal_loading_deadline(entry.page_vm().current_page_internal_loading_owner());+ earliest_deadline(timer_deadline, internal_loading_deadline)+ }}-pub(super) fn next_page_task_deadline_on_bound_owner_local_store() -> Option<std::time::Instant> {- with_bound_render_runtime_owner_local_store_session(|session| {- session.store.next_page_task_deadline()- })+fn earliest_deadline(+ left: Option<std::time::Instant>,+ right: Option<std::time::Instant>,+) -> Option<std::time::Instant> {+ match (left, right) {+ (Some(left), Some(right)) => Some(left.min(right)),+ (Some(deadline), None) | (None, Some(deadline)) => Some(deadline),+ (None, None) => None,+ }}-/// Snapshot Pages with any due owner-scheduled task from the derived deadline-/// index. Only resident entries are indexed because a checked-out PageVm may-/// change its timer heap or delayed typed-source state before restoration.-pub(super) fn snapshot_due_page_task_tokens_on_bound_owner_local_store(- due_at_or_before: std::time::Instant,-) -> Vec<RendererPageToken> {- with_bound_render_runtime_owner_local_store_session(|session| {- session- .store- .snapshot_due_page_task_tokens(due_at_or_before)- })+impl Drop for RendererOwnerLocalPageSlot {+ fn drop(&mut self) {+ // This is the stable Page lifetime boundary. A replacement PageVm+ // drops only Document-owned queues; retiring the slot also discards+ // V8 foreground work and typed Page source payloads.+ self.task_sources.clear();+ self.script_environment_pin+ .environment+ .retire_output_stream();+ self.script_environment_pin.clear_page_runtime_tasks();+ }}-pub(super) fn next_owner_maintenance_deadline_on_bound_owner_local_store()--> Option<std::time::Instant> {- with_bound_render_runtime_owner_local_store_session(|session| {- session.store.next_owner_maintenance_deadline()- })+#[derive(Debug)]+struct RendererDocumentIsolateReservationEntry {+ id: u64,+ handle: RendererDocumentIsolateHandle,+ /// The stream opens together with the isolate reservation, before that+ /// isolate is attached to a stable Page slot. Until attachment transfers+ /// lifetime ownership to `RendererPageScriptEnvironmentPin`, this entry+ /// must close the stream on every cancellation/failure path.+ output_journal: RendererTurnOutputJournal,+ /// Initial page creation owns the not-yet-attached consumer set here.+ /// A same-Page replacement reservation reuses the live slot's producer+ /// routes and therefore must not manufacture a second consumer set.+ initial_task_sources: Option<RendererPageOwnedTaskSources>,+ _accounting: RendererDocumentIsolateReservationAccounting,}-pub(super) fn claim_due_owner_maintenance_task_on_bound_owner_local_store(- now: std::time::Instant,-) -> Option<RendererOwnerMaintenanceTask> {- with_bound_render_runtime_owner_local_store_session(|session| {- session.store.claim_due_owner_maintenance_task(now)- })+#[derive(Clone)]+pub(crate) struct RendererDocumentIsolateAllocator {+ owner: RendererOwnerLocalContext,+ page_id: PageId,}-pub(super) fn settle_owner_maintenance_task_on_bound_owner_local_store(- task: RendererOwnerMaintenanceTask,- now: std::time::Instant,-) -> Result<()> {- with_bound_render_runtime_owner_local_store_session(|session| {- session.store.settle_owner_maintenance_task(task, now)- })+#[derive(Clone)]+pub(crate) struct RendererDocumentIsolateReservation {+ inner: Rc<RendererDocumentIsolateReservationState>,}-struct PageReadyDescriptorSnapshot {- eligible: Vec<crate::page_task_queue::RendererPageReadyDescriptor>,- stable_source_was_ready: bool,- due_timer_was_ready: bool,+struct RendererDocumentIsolateReservationState {+ token: RendererPageToken,+ reservation_id: u64,+ active: std::cell::Cell<bool>,}-impl PageReadyDescriptorSnapshot {- const fn has_ready_ordinary_source(&self) -> bool {- self.stable_source_was_ready || self.due_timer_was_ready+impl RendererDocumentIsolateAllocator {+ pub(super) fn new(owner: RendererOwnerLocalContext, page_id: PageId) -> Self {+ Self { owner, page_id }}-}-fn page_ready_descriptor_snapshot(- entry: &mut LivePageEntry,- task_sources: &mut RendererPageOwnedTaskSources,-) -> PageReadyDescriptorSnapshot {- let mut descriptors = task_sources.ready_descriptors();- let stable_source_was_ready = !descriptors.is_empty();- let mut due_timer_was_ready = false;- if let Some(timer) = entry.page_vm().due_page_timer_ready_descriptor() {- descriptors.push(timer);- due_timer_was_ready = true;- }- descriptors.retain(|descriptor| {- entry- .page_vm_mut()- .page_ready_descriptor_is_eligible(*descriptor)- });- PageReadyDescriptorSnapshot {- eligible: descriptors,- stable_source_was_ready,- due_timer_was_ready,+ pub(crate) fn reserve_renderer_document_isolate(+ &self,+ page_runtime_task_source: crate::page_task_queue::PageRuntimeTaskSource,+ ) -> Result<(+ RendererDocumentIsolateBootstrap,+ RendererDocumentIsolateReservation,+ )> {+ bound::reserve_renderer_document_isolate_on_bound_owner_local_store(+ &self.owner,+ self.page_id,+ page_runtime_task_source,+ )}}-fn select_page_scheduler_turn(- scheduler: &mut PageTurnScheduler<LivePageEntry>,- entry: &mut LivePageEntry,- task_sources: &mut RendererPageOwnedTaskSources,- lifecycle_gate: &mut Option<LifecycleGate>,- trigger: PageTurnTrigger,-) -> RendererPageScheduledTurn {- let snapshot = page_ready_descriptor_snapshot(entry, task_sources);- // A lifecycle action can change an already-queued source's eligibility.- // Preserve queue readiness, not only the pre-action eligible set, so a- // blocked/idle lifecycle result can request exactly one fresh arbitration- // without re-reading mutable source state after execution.- let lifecycle_is_deferred = entry.document_lifecycle_is_deferred_until_response();- let has_pending_document_lifecycle_turn =- !lifecycle_is_deferred && entry.pending_document_lifecycle_identity().is_some();- let document_lifecycle_owner_turn_is_runnable =- !lifecycle_is_deferred && entry.document_lifecycle_owner_turn_is_runnable();- let has_ready_main_parser_script_continuation =- !lifecycle_is_deferred && entry.has_ready_main_parser_script_continuation();- let document_lifecycle = DocumentLifecycleClassReadiness::from_resident_state(- has_pending_document_lifecycle_turn,- document_lifecycle_owner_turn_is_runnable,- has_ready_main_parser_script_continuation,- );- let gate_policy = lifecycle_gate- .as_mut()- .map(|gate| gate.turn_policy(entry, !snapshot.eligible.is_empty()))- .unwrap_or(LifecycleGateTurnPolicy::Normal);- let selected_class = match gate_policy {- LifecycleGateTurnPolicy::Normal => {- scheduler.select_turn_class(trigger, !snapshot.eligible.is_empty(), document_lifecycle)- }- LifecycleGateTurnPolicy::Drive {- reconsider_displaced_ordinary,- } => scheduler.select_lifecycle_turn(- reconsider_displaced_ordinary,- !snapshot.eligible.is_empty(),- document_lifecycle,- ),- LifecycleGateTurnPolicy::Park => {- return RendererPageScheduledTurn::SpentWake;- }- };- match selected_class {- Some(PageTurnClass::DocumentLifecycle) => RendererPageScheduledTurn::DocumentLifecycle {- displaced_ordinary: RendererDisplacedOrdinaryTurn::from_ready_source(- snapshot.has_ready_ordinary_source(),- ),- },- Some(PageTurnClass::Ordinary) => {- let selected = scheduler- .select_ready_descriptor(snapshot.eligible)- .expect("selected ordinary Page-turn class must retain an eligible descriptor");- let task = task_sources.take_task(selected);- RendererPageScheduledTurn::Ordinary(Box::new(task))- }- None => RendererPageScheduledTurn::SpentWake,+impl RendererDocumentIsolateReservation {+ fn token(&self) -> RendererPageToken {+ self.inner.token}-}-/// Run one ordinary page-owner turn already selected by the Page scheduler.-/// Every ordinary task is a concrete typed source payload or a due timer. The-/// caller must restore the returned entry before scheduling any continuation.-pub(super) async fn advance_page_owner_one_turn_via_local_task(- local_executor: JsLocalExecutor,- entry: LivePageEntry,- task: RendererPageSchedulerTask,- loader: ResourceRequestClient,-) -> (LivePageEntry, Result<()>) {- run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {- Box::pin(async move {- let replacement_lifecycle_snapshot = entry- .page_vm()- .document_replacement_lifecycle_action_snapshot();- // This scope belongs to the common Page owner, not the selected- // task executor: command-local wait drivers reuse that executor- // but retain their own typed navigation continuation.- let _navigation_handoff_scope = entry- .page_vm()- .vm()- .begin_ordinary_page_turn_navigation_handoff()?;- let application = entry- .page_vm_mut()- .apply_selected_page_scheduler_task(task, &loader)- .await;- // Any JavaScript-capable Page action can synchronously replace the- // main Document through document.open()/document.close(). Reconcile- // the exact transition caused by this action at the common owner- // boundary. Reconciliation must still run when the action reports- // an error: JavaScript side effects are not rolled back by an- // exception. A selected Page action cannot repair an older missed- // transition.- let reconciliation = {- let (page_vm, pending_document_lifecycle_turn) =- entry.page_vm_and_document_lifecycle_turn_mut();- page_vm- .reconcile_document_replacement_lifecycle_after_owner_action(- replacement_lifecycle_snapshot,- pending_document_lifecycle_turn,- )- .await- };+ fn reservation_id(&self) -> u64 {+ self.inner.reservation_id+ }- match (application, reconciliation) {- (Ok(()), Ok(_)) => Ok(()),- (Err(action_error), Ok(_)) => Err(action_error),- (Ok(_), Err(reconciliation_error)) => Err(reconciliation_error),- (Err(action_error), Err(reconciliation_error)) => Err(anyhow!(- "page action failed ({action_error:#}) and its Document replacement lifecycle reconciliation also failed ({reconciliation_error:#})"- )),- }- })- })- .await-}+ fn disarm_for_attach(&self) {+ self.inner.active.set(false);+ }-/// Execute at most one action from the exact-Document lifecycle resident.-/// A missing resident is an idle stale-wake outcome; this helper never binds-/// a page wake to whichever Document happens to be current.-pub(super) async fn advance_document_lifecycle_one_page_turn_via_local_task(- local_executor: JsLocalExecutor,- entry: LivePageEntry,-) -> (LivePageEntry, Result<DocumentLifecycleTurnOutcome>) {- run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {- Box::pin(async move {- let Some(document) = entry.pending_document_lifecycle_identity() else {- return Ok(DocumentLifecycleTurnOutcome::idle(- DocumentLifecycleTurnAction::None,- ));- };- let (page_vm, pending_document_lifecycle_turn) =- entry.page_vm_and_document_lifecycle_turn_mut();- let outcome = page_vm- .advance_post_parse_lifecycle_one_owner_turn(- pending_document_lifecycle_turn,- document,- )- .await?;- if let Some(pending) = pending_document_lifecycle_turn.as_mut() {- pending.owner_turn_is_runnable = matches!(- outcome.readiness,- DocumentLifecycleTurnReadiness::Runnable { .. }- );- }- Ok(outcome)- })- })- .await+ pub(crate) fn is_active(&self) -> bool {+ self.inner.active.get()+ }}-pub(super) fn observe_document_lifecycle_on_entry(- entry: &mut LivePageEntry,- document: RendererDocumentLifecycleIdentity,- target_stage: PageVmInitStage,-) -> DocumentLifecycleObserverOutcome {- entry.observe_document_lifecycle(document, target_stage)+impl std::fmt::Debug for RendererDocumentIsolateReservation {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("RendererDocumentIsolateReservation")+ .field("token", &self.inner.token)+ .field("reservation_id", &self.inner.reservation_id)+ .field("active", &self.inner.active.get())+ .finish()+ }}-fn reconcile_page_creation_lifecycle_observation(- observation: DocumentLifecycleObserverOutcome,- has_pending_location_navigation: bool,-) -> DocumentLifecycleObserverOutcome {- match observation {- DocumentLifecycleObserverOutcome::Reached if has_pending_location_navigation => {- DocumentLifecycleObserverOutcome::NavigationPending+impl Drop for RendererDocumentIsolateReservationState {+ fn drop(&mut self) {+ if self.active.get() && has_current_render_runtime_owner_local_store() {+ bound::remove_reserved_renderer_document_isolate_on_bound_owner_local_store(+ self.token,+ self.reservation_id,+ );+ self.active.set(false);}- observation => observation,}}-pub(super) fn has_pending_document_lifecycle_turn_on_entry(entry: &mut LivePageEntry) -> bool {- entry.pending_document_lifecycle_identity().is_some()-}-impl RendererOwnerLocalStoreSession<'_> {fn reserve_renderer_document_isolate(&mut self,@@ -2686,7 +1010,7 @@ impl RendererOwnerLocalStore {// `FollowBeforeReply` must observe that navigation before publishing// the old Document; generic lifecycle observers still treat the// milestone itself as reached.- let observation = reconcile_page_creation_lifecycle_observation(+ let observation = bound::reconcile_page_creation_lifecycle_observation(observation,entry.page_vm().vm().has_pending_location_navigation(),);@@ -3062,7 +1386,7 @@ impl RendererOwnerLocalStore {} = page_slot;match turn_scheduler.checkout_scheduled_turn() {ScheduledPageTurnCheckout::Turn { mut entry, trigger } => {- let scheduled_turn = select_page_scheduler_turn(+ let scheduled_turn = bound::select_page_scheduler_turn(turn_scheduler,&mut entry,task_sources,@@ -3154,7 +1478,7 @@ impl RendererOwnerLocalStore {pending.phase_one_restore_requirement()};let streaming_input_ready = entry.pending_phase_one_navigation_has_ready_streaming_input();- let page_turn_is_runnable = !page_ready_descriptor_snapshot(entry, task_sources)+ let page_turn_is_runnable = !bound::page_ready_descriptor_snapshot(entry, task_sources).eligible.is_empty();@@ -3189,7 +1513,7 @@ impl RendererOwnerLocalStore {..} = page_slot;let entry = turn_scheduler.resident_mut()?;- let snapshot = page_ready_descriptor_snapshot(entry, task_sources);+ let snapshot = bound::page_ready_descriptor_snapshot(entry, task_sources);if !snapshot.eligible.is_empty() {return Some(PageOwnerTurnReadiness::Runnable);}@@ -4505,349 +2829,3 @@ impl Drop for RendererOwnerLocalStore {}}}--impl Drop for RenderRuntimeOwnerLocalStoreBinding {- fn drop(&mut self) {- CURRENT_RENDER_RUNTIME_OWNER_LOCAL_STORE.with(|current_store| {- // Cleanup must remain idempotent and non-asserting: this guard can- // run during panic unwinding, where a second panic would abort the- // process instead of preserving the original failure.- current_store.borrow_mut().take();- });- }-}--#[cfg(test)]-mod entry_local_task_guard_tests {- use super::*;-- #[test]- fn owner_local_store_binding_rejects_rebinding_without_replacing_the_active_store() {- let mut active_store = RendererOwnerLocalStore::default();- let mut rejected_store = RendererOwnerLocalStore::default();- let binding = bind_render_runtime_owner_local_store(&mut active_store);-- let rebind = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {- let _rejected_binding = bind_render_runtime_owner_local_store(&mut rejected_store);- }));-- assert!(rebind.is_err(), "a nested owner-local binding must fail");- assert!(- has_current_render_runtime_owner_local_store(),- "rejecting a nested binding must preserve the active store"- );- drop(binding);- assert!(- !has_current_render_runtime_owner_local_store(),- "dropping the active binding must clear the thread-local store"- );- }-- #[test]- fn owner_local_store_binding_drop_does_not_double_panic_during_unwind() {- let unwind = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {- let mut store = RendererOwnerLocalStore::default();- let _binding = bind_render_runtime_owner_local_store(&mut store);- CURRENT_RENDER_RUNTIME_OWNER_LOCAL_STORE.with(|current_store| {- assert!(- current_store.borrow_mut().take().is_some(),- "the test must clear an active binding before unwinding"- );- });- panic!("primary owner-loop failure");- }));-- assert!(unwind.is_err(), "the primary panic must remain catchable");- assert!(- !has_current_render_runtime_owner_local_store(),- "unwinding must leave no thread-local owner store binding"- );- }-- #[test]- fn guard_returns_entry_when_task_future_is_dropped_before_first_poll() {- let (reply_tx, mut reply_rx) = oneshot::channel();- let guard = EntryLocalTaskGuard::<_, ()>::new(42_u8, reply_tx);- let never_polled_task = async move {- let _guard = guard;- std::future::pending::<()>().await;- };-- drop(never_polled_task);-- let (entry, result) = reply_rx- .try_recv()- .expect("dropping the unpolled task should return its guarded entry");- assert_eq!(entry, 42);- assert!(- result- .expect_err("an unpolled task must not report successful completion")- .to_string()- .contains("before restoring its page entry")- );- }-}--#[cfg(test)]-mod navigation_dispatch_tests {- use super::*;-- #[test]- fn runnable_page_creation_lifecycle_clears_displaced_ordinary_grant() {- let mut gate = LifecycleGate::new(PageVmInitStage::DomContentLoaded);-- gate.settle_lifecycle_turn(true);- assert!(gate.reconsider_ordinary_on_next_turn);-- gate.settle_lifecycle_turn(false);- assert!(!gate.reconsider_ordinary_on_next_turn);- }-- fn phase_one_entry_shell_without_active_page_vm(- standalone_navigation_follow: StandaloneNavigationFollowState,- ) -> LivePageEntry {- let page_id = PageId::new_for_testing(1);- let (page_context_cancel_tx, _page_context_cancel_rx) =- renderer_page_context_cancel_channel();- let slot = RendererPageSlotHandle::new(- std::sync::Weak::new(),- RendererPageEntry::removed(page_id),- page_context_cancel_tx,- Default::default(),- );- LivePageEntry {- slot,- top_level_navigation_dispatch:- RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,- standalone_navigation_follow,- pending_document_lifecycle_turn: None,- post_response_document_lifecycle: None,- vm: None,- pending_phase_one_navigation: None,- last_published_replacement_document: None,- }- }-- fn retiring_entry_without_active_page_vm(- standalone_navigation_follow: StandaloneNavigationFollowState,- ) -> RetiringPageEntry {- RetiringPageEntry::new(phase_one_entry_shell_without_active_page_vm(- standalone_navigation_follow,- ))- }-- #[test]- fn retiring_navigation_settlement_does_not_require_an_active_vm() {- let handoff = crate::page_task_queue::RendererTopLevelNavigationHandoff::new(1);- for succeeded in [false, true] {- for state in [- StandaloneNavigationFollowState::Idle,- StandaloneNavigationFollowState::Following { handoff },- StandaloneNavigationFollowState::FailedWithPendingNavigation { handoff },- ] {- let mut entry = retiring_entry_without_active_page_vm(state);-- entry.settle_standalone_navigation_follow(succeeded);-- assert_eq!(- entry.entry.standalone_navigation_follow,- StandaloneNavigationFollowState::Idle,- "an empty phase-one shell must settle {state:?} to Idle after succeeded={succeeded}"- );- }- }- }-- #[test]- fn failed_phase_one_advance_returns_a_retiring_entry() {- let advance = classify_pending_phase_one_entry_advance(- phase_one_entry_shell_without_active_page_vm(StandaloneNavigationFollowState::Idle),- Err(anyhow!("resume failed")),- );-- match advance {- PendingPhaseOneEntryAdvance::Retiring { entry, error } => {- assert!(entry.entry.active_page_vm().is_none());- assert_eq!(error.to_string(), "resume failed");- }- PendingPhaseOneEntryAdvance::Live { .. } => {- panic!("an empty phase-one shell must not escape as a LivePageEntry")- }- }- }-- #[test]- fn successful_phase_one_advance_without_a_vm_is_retired_as_an_invariant_error() {- let advance = classify_pending_phase_one_entry_advance(- phase_one_entry_shell_without_active_page_vm(StandaloneNavigationFollowState::Idle),- Ok(- LivePagePendingNavigationPhaseOneAdvance::TriggeredNavigation {- stage: PageVmInitStage::DomContentLoaded,- },- ),- );-- match advance {- PendingPhaseOneEntryAdvance::Retiring { entry, error } => {- assert!(entry.entry.active_page_vm().is_none());- assert!(- error- .to_string()- .contains("completed without restoring an active PageVm")- );- }- PendingPhaseOneEntryAdvance::Live { .. } => {- panic!("an empty phase-one shell must not escape as a LivePageEntry")- }- }- }-- #[test]- fn navigation_handoff_claim_rejects_stale_and_duplicate_requests() {- let first = crate::page_task_queue::RendererTopLevelNavigationHandoff::new(1);- let second = crate::page_task_queue::RendererTopLevelNavigationHandoff::new(2);- let mut state = StandaloneNavigationFollowState::Idle;-- assert!(!state.claim(Some(second), Some(first)));- assert_eq!(state, StandaloneNavigationFollowState::Idle);- assert!(state.claim(Some(second), Some(second)));- assert_eq!(- state,- StandaloneNavigationFollowState::Following { handoff: second }- );- assert!(!state.claim(Some(second), Some(second)));- }-- #[test]- fn failed_navigation_suppresses_only_the_same_request_identity() {- let first = crate::page_task_queue::RendererTopLevelNavigationHandoff::new(1);- let second = crate::page_task_queue::RendererTopLevelNavigationHandoff::new(2);- let mut state = StandaloneNavigationFollowState::Following { handoff: first };-- state.settle(Some(first), false);- assert_eq!(- state,- StandaloneNavigationFollowState::FailedWithPendingNavigation { handoff: first }- );- assert!(!state.claim(Some(first), Some(first)));- assert!(state.claim(Some(second), Some(second)));- assert_eq!(- state,- StandaloneNavigationFollowState::Following { handoff: second }- );- }-- #[test]- fn pending_document_lifecycle_classifies_each_stable_residence() {- let cases = [- (- (true, false, false, false),- DocumentLifecycleObserverOutcome::NavigationPending,- ),- (- (false, true, false, false),- DocumentLifecycleObserverOutcome::Pending,- ),- (- (false, false, true, false),- DocumentLifecycleObserverOutcome::Pending,- ),- (- (false, false, false, true),- DocumentLifecycleObserverOutcome::Pending,- ),- (- (false, false, false, false),- DocumentLifecycleObserverOutcome::MissingResident,- ),- ];-- for ((location, phase_one, lifecycle_turn, replacement), expected) in cases {- assert_eq!(- classify_pending_document_lifecycle_residence(- location,- phase_one,- lifecycle_turn,- replacement,- ),- expected- );- }- }-- #[test]- fn page_creation_prioritizes_navigation_enqueued_by_reached_milestone() {- assert_eq!(- reconcile_page_creation_lifecycle_observation(- DocumentLifecycleObserverOutcome::Reached,- true,- ),- DocumentLifecycleObserverOutcome::NavigationPending- );- }-- #[test]- fn page_creation_does_not_hide_an_interrupted_lifecycle() {- let termination = RendererLifecycleTerminationStamp {- sequence: 7,- timestamp_micros: 11,- reason: RendererDocumentTerminationReason::Detached,- };-- assert_eq!(- reconcile_page_creation_lifecycle_observation(- DocumentLifecycleObserverOutcome::Interrupted(termination),- true,- ),- DocumentLifecycleObserverOutcome::Interrupted(termination)- );- }-- #[test]- fn published_page_creation_discards_reply_policy_when_observer_detaches() {- let completion = LivePagePendingNavigationCompletion::PublishedPageCreation {- navigation_reply_policy: NavigationReplyPolicy::ReturnWithPendingNavigation,- };-- let (completion, detached) = completion.detach_command_observer();-- assert!(detached);- assert!(matches!(- completion,- LivePagePendingNavigationCompletion::Background- ));- }-- #[test]- fn detached_navigation_failure_routes_to_pending_page_creation() {- assert_eq!(- LivePagePendingNavigationCompletion::Background.failure_recipient(),- LivePageNavigationFailureRecipient::PageCreationObserver- );- }-- #[test]- fn already_published_page_creation_reports_later_navigation_failure_as_background() {- let completion = LivePagePendingNavigationCompletion::PublishedPageCreation {- navigation_reply_policy: NavigationReplyPolicy::FollowBeforeReply,- };-- assert_eq!(- completion.failure_recipient(),- LivePageNavigationFailureRecipient::Background- );- }-- #[test]- fn command_owned_navigation_failure_returns_to_its_initiator() {- let completion = LivePagePendingNavigationCompletion::ReplyWithSnapshot {- reply: Box::new(RendererPageReply::Unit),- capture_policy: super::RendererPageStateCapturePolicy::FullReport,- };-- assert_eq!(- completion.failure_recipient(),- LivePageNavigationFailureRecipient::Initiator- );- }-}diff --git a/moli-renderer-v8/src/runtime/owner_local_store/phase_one.rs b/moli-renderer-v8/src/runtime/owner_local_store/phase_one.rsnew file mode 100644index 000000000..89241e2f9--- /dev/null+++ b/moli-renderer-v8/src/runtime/owner_local_store/phase_one.rs@@ -0,0 +1,132 @@+use super::*;++pub(in crate::runtime) enum LivePagePendingNavigationPhaseOneAdvance {+ /// The resumed parser yielded again. The caller restores the entry before+ /// deriving a one-shot admission wake from the stable Page slot.+ Pending {+ wake_token: RendererPageToken,+ },+ TriggeredNavigation {+ stage: PageVmInitStage,+ },+ PostParseLifecycle {+ target_stage: PageVmInitStage,+ outcome: DocumentLifecycleTurnOutcome,+ },+}++/// Result of advancing a checked-out phase-one navigation residence.+///+/// Resuming phase one temporarily consumes the Page's only active VM. Most+/// outcomes install that VM (or a new pending residence) back into the live+/// entry, but an unrecoverable resume failure leaves only a teardown shell.+/// Keeping those states in separate variants prevents the owner from passing+/// that shell to a live-entry restore API.+pub(in crate::runtime) enum PendingPhaseOneEntryAdvance {+ Live {+ entry: LivePageEntry,+ result: Result<LivePagePendingNavigationPhaseOneAdvance>,+ },+ Retiring {+ entry: RetiringPageEntry,+ error: anyhow::Error,+ },+}++pub(in crate::runtime) async fn advance_pending_phase_one_navigation_on_entry_via_local_task(+ local_executor: JsLocalExecutor,+ entry: LivePageEntry,+) -> PendingPhaseOneEntryAdvance {+ let (entry, result) =+ run_entry_on_bound_owner_local_store_local_task(local_executor, entry, move |entry| {+ Box::pin(async move {+ let pending = entry.take_pending_phase_one_navigation()?;+ let (residence, mut metadata) = pending.into_parts();+ let browser_context_runtime = residence+ .page_vm()+ .runtime_hooks+ .browser_context_runtime+ .clone();+ let phase_one_outcome = match residence.resume().await {+ Ok(outcome) => outcome,+ Err(error) => {+ metadata.reject(+ None,+ &browser_context_runtime,+ format!("Cannot navigate to URL: {error}"),+ );+ return Err(error);+ }+ };+ let phase_one_outcome = match phase_one_outcome {+ PendingPhaseOneResumeOutcome::Progress(outcome) => outcome,+ PendingPhaseOneResumeOutcome::MainResourceLoadFailed { page_vm, error } => {+ metadata.reject(+ None,+ &browser_context_runtime,+ format!("Cannot navigate to URL: {error}"),+ );+ entry.install_resumed_phase_one_page_vm(page_vm);+ return Err(error);+ }+ };+ match phase_one_outcome {+ ParseTimePageVmCreationOutcome::PendingPhaseOne(residence) => {+ let pending = PageVmPendingPhaseOneNavigation::new(residence, metadata);+ let wake_token = entry.restore_pending_phase_one_navigation(pending)?;+ Ok(LivePagePendingNavigationPhaseOneAdvance::Pending { wake_token })+ }+ ParseTimePageVmCreationOutcome::TriggeredNavigation { mut page_vm, stage } => {+ metadata.complete_service_worker_follow(&mut page_vm);+ entry.install_resumed_phase_one_page_vm(page_vm);+ Ok(LivePagePendingNavigationPhaseOneAdvance::TriggeredNavigation { stage })+ }+ ParseTimePageVmCreationOutcome::ContinuePhaseTwo {+ mut page_vm,+ page_tasks,+ stage,+ started,+ } => {+ metadata.complete_service_worker_follow(&mut page_vm);+ entry.install_resumed_phase_one_page_vm(page_vm);+ let (page_vm, pending_document_lifecycle_turn) =+ entry.page_vm_and_document_lifecycle_turn_mut();+ let outcome = page_vm+ .begin_post_parse_lifecycle_on_named_owner_lane(+ pending_document_lifecycle_turn,+ page_tasks,+ stage,+ started,+ )+ .await?;+ Ok(+ LivePagePendingNavigationPhaseOneAdvance::PostParseLifecycle {+ target_stage: stage,+ outcome,+ },+ )+ }+ }+ })+ })+ .await;++ classify_pending_phase_one_entry_advance(entry, result)+}++pub(super) fn classify_pending_phase_one_entry_advance(+ entry: LivePageEntry,+ result: Result<LivePagePendingNavigationPhaseOneAdvance>,+) -> PendingPhaseOneEntryAdvance {+ if entry.active_page_vm().is_some() {+ PendingPhaseOneEntryAdvance::Live { entry, result }+ } else {+ let error = result.err().unwrap_or_else(|| {+ anyhow!("phase-one navigation advance completed without restoring an active PageVm")+ });+ PendingPhaseOneEntryAdvance::Retiring {+ entry: RetiringPageEntry::new(entry),+ error,+ }+ }+}diff --git a/moli-renderer-v8/src/runtime/owner_local_store/tests.rs b/moli-renderer-v8/src/runtime/owner_local_store/tests.rsnew file mode 100644index 000000000..d94c9583d--- /dev/null+++ b/moli-renderer-v8/src/runtime/owner_local_store/tests.rs@@ -0,0 +1,336 @@+use super::*;++#[cfg(test)]+mod entry_local_task_guard_tests {+ use super::*;++ #[test]+ fn owner_local_store_binding_rejects_rebinding_without_replacing_the_active_store() {+ let mut active_store = RendererOwnerLocalStore::default();+ let mut rejected_store = RendererOwnerLocalStore::default();+ let binding = bind_render_runtime_owner_local_store(&mut active_store);++ let rebind = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ let _rejected_binding = bind_render_runtime_owner_local_store(&mut rejected_store);+ }));++ assert!(rebind.is_err(), "a nested owner-local binding must fail");+ assert!(+ has_current_render_runtime_owner_local_store(),+ "rejecting a nested binding must preserve the active store"+ );+ drop(binding);+ assert!(+ !has_current_render_runtime_owner_local_store(),+ "dropping the active binding must clear the thread-local store"+ );+ }++ #[test]+ fn owner_local_store_binding_drop_does_not_double_panic_during_unwind() {+ let unwind = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ let mut store = RendererOwnerLocalStore::default();+ let _binding = bind_render_runtime_owner_local_store(&mut store);+ CURRENT_RENDER_RUNTIME_OWNER_LOCAL_STORE.with(|current_store| {+ assert!(+ current_store.borrow_mut().take().is_some(),+ "the test must clear an active binding before unwinding"+ );+ });+ panic!("primary owner-loop failure");+ }));++ assert!(unwind.is_err(), "the primary panic must remain catchable");+ assert!(+ !has_current_render_runtime_owner_local_store(),+ "unwinding must leave no thread-local owner store binding"+ );+ }++ #[test]+ fn guard_returns_entry_when_task_future_is_dropped_before_first_poll() {+ let (reply_tx, mut reply_rx) = oneshot::channel();+ let guard = bound::EntryLocalTaskGuard::<_, ()>::new(42_u8, reply_tx);+ let never_polled_task = async move {+ let _guard = guard;+ std::future::pending::<()>().await;+ };++ drop(never_polled_task);++ let (entry, result) = reply_rx+ .try_recv()+ .expect("dropping the unpolled task should return its guarded entry");+ assert_eq!(entry, 42);+ assert!(+ result+ .expect_err("an unpolled task must not report successful completion")+ .to_string()+ .contains("before restoring its page entry")+ );+ }+}++#[cfg(test)]+mod navigation_dispatch_tests {+ use super::*;++ #[test]+ fn runnable_page_creation_lifecycle_clears_displaced_ordinary_grant() {+ let mut gate = LifecycleGate::new(PageVmInitStage::DomContentLoaded);++ gate.settle_lifecycle_turn(true);+ assert!(gate.reconsider_ordinary_on_next_turn);++ gate.settle_lifecycle_turn(false);+ assert!(!gate.reconsider_ordinary_on_next_turn);+ }++ fn phase_one_entry_shell_without_active_page_vm(+ standalone_navigation_follow: StandaloneNavigationFollowState,+ ) -> LivePageEntry {+ let page_id = PageId::new_for_testing(1);+ let (page_context_cancel_tx, _page_context_cancel_rx) =+ renderer_page_context_cancel_channel();+ let slot = RendererPageSlotHandle::new(+ std::sync::Weak::new(),+ RendererPageEntry::removed(page_id),+ page_context_cancel_tx,+ Default::default(),+ );+ LivePageEntry {+ slot,+ top_level_navigation_dispatch:+ RendererTopLevelNavigationDispatch::FollowInStandaloneAdapter,+ standalone_navigation_follow,+ pending_document_lifecycle_turn: None,+ post_response_document_lifecycle: None,+ vm: None,+ pending_phase_one_navigation: None,+ last_published_replacement_document: None,+ }+ }++ fn retiring_entry_without_active_page_vm(+ standalone_navigation_follow: StandaloneNavigationFollowState,+ ) -> RetiringPageEntry {+ RetiringPageEntry::new(phase_one_entry_shell_without_active_page_vm(+ standalone_navigation_follow,+ ))+ }++ #[test]+ fn retiring_navigation_settlement_does_not_require_an_active_vm() {+ let handoff = crate::page_task_queue::RendererTopLevelNavigationHandoff::new(1);+ for succeeded in [false, true] {+ for state in [+ StandaloneNavigationFollowState::Idle,+ StandaloneNavigationFollowState::Following { handoff },+ StandaloneNavigationFollowState::FailedWithPendingNavigation { handoff },+ ] {+ let mut entry = retiring_entry_without_active_page_vm(state);++ entry.settle_standalone_navigation_follow(succeeded);++ assert_eq!(+ entry.entry.standalone_navigation_follow,+ StandaloneNavigationFollowState::Idle,+ "an empty phase-one shell must settle {state:?} to Idle after succeeded={succeeded}"+ );+ }+ }+ }++ #[test]+ fn failed_phase_one_advance_returns_a_retiring_entry() {+ let advance = phase_one::classify_pending_phase_one_entry_advance(+ phase_one_entry_shell_without_active_page_vm(StandaloneNavigationFollowState::Idle),+ Err(anyhow!("resume failed")),+ );++ match advance {+ PendingPhaseOneEntryAdvance::Retiring { entry, error } => {+ assert!(entry.entry.active_page_vm().is_none());+ assert_eq!(error.to_string(), "resume failed");+ }+ PendingPhaseOneEntryAdvance::Live { .. } => {+ panic!("an empty phase-one shell must not escape as a LivePageEntry")+ }+ }+ }++ #[test]+ fn successful_phase_one_advance_without_a_vm_is_retired_as_an_invariant_error() {+ let advance = phase_one::classify_pending_phase_one_entry_advance(+ phase_one_entry_shell_without_active_page_vm(StandaloneNavigationFollowState::Idle),+ Ok(+ LivePagePendingNavigationPhaseOneAdvance::TriggeredNavigation {+ stage: PageVmInitStage::DomContentLoaded,+ },+ ),+ );++ match advance {+ PendingPhaseOneEntryAdvance::Retiring { entry, error } => {+ assert!(entry.entry.active_page_vm().is_none());+ assert!(+ error+ .to_string()+ .contains("completed without restoring an active PageVm")+ );+ }+ PendingPhaseOneEntryAdvance::Live { .. } => {+ panic!("an empty phase-one shell must not escape as a LivePageEntry")+ }+ }+ }++ #[test]+ fn navigation_handoff_claim_rejects_stale_and_duplicate_requests() {+ let first = crate::page_task_queue::RendererTopLevelNavigationHandoff::new(1);+ let second = crate::page_task_queue::RendererTopLevelNavigationHandoff::new(2);+ let mut state = StandaloneNavigationFollowState::Idle;++ assert!(!state.claim(Some(second), Some(first)));+ assert_eq!(state, StandaloneNavigationFollowState::Idle);+ assert!(state.claim(Some(second), Some(second)));+ assert_eq!(+ state,+ StandaloneNavigationFollowState::Following { handoff: second }+ );+ assert!(!state.claim(Some(second), Some(second)));+ }++ #[test]+ fn failed_navigation_suppresses_only_the_same_request_identity() {+ let first = crate::page_task_queue::RendererTopLevelNavigationHandoff::new(1);+ let second = crate::page_task_queue::RendererTopLevelNavigationHandoff::new(2);+ let mut state = StandaloneNavigationFollowState::Following { handoff: first };++ state.settle(Some(first), false);+ assert_eq!(+ state,+ StandaloneNavigationFollowState::FailedWithPendingNavigation { handoff: first }+ );+ assert!(!state.claim(Some(first), Some(first)));+ assert!(state.claim(Some(second), Some(second)));+ assert_eq!(+ state,+ StandaloneNavigationFollowState::Following { handoff: second }+ );+ }++ #[test]+ fn pending_document_lifecycle_classifies_each_stable_residence() {+ let cases = [+ (+ (true, false, false, false),+ DocumentLifecycleObserverOutcome::NavigationPending,+ ),+ (+ (false, true, false, false),+ DocumentLifecycleObserverOutcome::Pending,+ ),+ (+ (false, false, true, false),+ DocumentLifecycleObserverOutcome::Pending,+ ),+ (+ (false, false, false, true),+ DocumentLifecycleObserverOutcome::Pending,+ ),+ (+ (false, false, false, false),+ DocumentLifecycleObserverOutcome::MissingResident,+ ),+ ];++ for ((location, phase_one, lifecycle_turn, replacement), expected) in cases {+ assert_eq!(+ entry::classify_pending_document_lifecycle_residence(+ location,+ phase_one,+ lifecycle_turn,+ replacement,+ ),+ expected+ );+ }+ }++ #[test]+ fn page_creation_prioritizes_navigation_enqueued_by_reached_milestone() {+ assert_eq!(+ reconcile_page_creation_lifecycle_observation(+ DocumentLifecycleObserverOutcome::Reached,+ true,+ ),+ DocumentLifecycleObserverOutcome::NavigationPending+ );+ }++ #[test]+ fn page_creation_does_not_hide_an_interrupted_lifecycle() {+ let termination = RendererLifecycleTerminationStamp {+ sequence: 7,+ timestamp_micros: 11,+ reason: RendererDocumentTerminationReason::Detached,+ };++ assert_eq!(+ reconcile_page_creation_lifecycle_observation(+ DocumentLifecycleObserverOutcome::Interrupted(termination),+ true,+ ),+ DocumentLifecycleObserverOutcome::Interrupted(termination)+ );+ }++ #[test]+ fn published_page_creation_discards_reply_policy_when_observer_detaches() {+ let completion = LivePagePendingNavigationCompletion::PublishedPageCreation {+ navigation_reply_policy: NavigationReplyPolicy::ReturnWithPendingNavigation,+ };++ let (completion, detached) = completion.detach_command_observer();++ assert!(detached);+ assert!(matches!(+ completion,+ LivePagePendingNavigationCompletion::Background+ ));+ }++ #[test]+ fn detached_navigation_failure_routes_to_pending_page_creation() {+ assert_eq!(+ LivePagePendingNavigationCompletion::Background.failure_recipient(),+ LivePageNavigationFailureRecipient::PageCreationObserver+ );+ }++ #[test]+ fn already_published_page_creation_reports_later_navigation_failure_as_background() {+ let completion = LivePagePendingNavigationCompletion::PublishedPageCreation {+ navigation_reply_policy: NavigationReplyPolicy::FollowBeforeReply,+ };++ assert_eq!(+ completion.failure_recipient(),+ LivePageNavigationFailureRecipient::Background+ );+ }++ #[test]+ fn command_owned_navigation_failure_returns_to_its_initiator() {+ let completion = LivePagePendingNavigationCompletion::ReplyWithSnapshot {+ reply: Box::new(RendererPageReply::Unit),+ capture_policy: super::RendererPageStateCapturePolicy::FullReport,+ };++ assert_eq!(+ completion.failure_recipient(),+ LivePageNavigationFailureRecipient::Initiator+ );+ }+}