From 853f532a9d48d17ce37c99406ba184959fea2fac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wies=C5=82aw=20=C5=A0olt=C3=A9s?= Date: Sun, 20 Sep 2026 23:39:11 +0200 Subject: [PATCH] Defer terminal navigation until lifecycle tasks run --- ...minal-navigation-task-boundary-20260920.md | 56 +++++++++ .../native/webscene_v8_runtime.cpp | 111 ++++++++++++++++-- .../native/webscene_v8_runtime_lifecycle.inc | 1 + .../native/webscene_v8_runtime_navigation.inc | 1 + .../native/webscene_v8_runtime_state.inc | 8 ++ .../native/webscene_v8_runtime_tasks.inc | 7 ++ .../tests/native_v8_runtime_input_tests.inc | 59 +++++++++- 7 files changed, 230 insertions(+), 13 deletions(-) create mode 100644 docs/validation/terminal-navigation-task-boundary-20260920.md diff --git a/docs/validation/terminal-navigation-task-boundary-20260920.md b/docs/validation/terminal-navigation-task-boundary-20260920.md new file mode 100644 index 00000000..2f7f962c --- /dev/null +++ b/docs/validation/terminal-navigation-task-boundary-20260920.md @@ -0,0 +1,56 @@ +# Terminal navigation task boundary + +Tracking: #876, parent #269. + +## Reproduction + +The exact unchanged Code OSS package built from AppScene +`cd0a02ecd15f0a635bccc242cdd657888db39e25` and WebScene +`f5df884af35cf0d05eb4864f507ee3e468360e4e` dispatches `beforeunload` and +`pagehide`, but the native reload request is visible to AppScene in the same +JavaScript turn. VS Code's `onWillSaveState` listener queues its IndexedDB +commit with a zero-delay timer. AppScene can therefore retire the realm before +that timer runs. The reopened MCP editor finds its durable encrypted secret but +no workspace-scoped `mcpInputs` record. + +#874 supplied the missing lifecycle events and #875 removed same-runtime +IndexedDB commit conflicts. The exact package no longer reports the conflict, +which isolates this remaining task-ordering boundary. + +## Runtime contract + +Reload and same-origin navigation reserve bounded host-request capacity before +dispatching lifecycle. Approved requests remain in one bounded terminal queue +until every non-animation timer queued no later than the end of lifecycle has +run. WebScene then publishes the terminal requests as one browser task and +notifies the host. + +The cutoff is captured after both lifecycle event microtask checkpoints. A +timer queued from either listener, including one queued by a Promise microtask, +therefore precedes handoff. A timer created later by one of those tasks has a +newer deadline and cannot indefinitely delay navigation. Navigation teardown +and runtime shutdown release pending requests and their reservations. + +Recursive navigation from a lifecycle listener is coalesced into the outer +request. Reload/navigation veto and error paths release their reservation. +Focus, external URL, window close, nested-document, and same-document behavior +retain their existing task and host contracts. + +## Focused gate + +The focused Release V8 regression covers reload, same-origin navigation, +listener and Promise-microtask zero-delay work, veto behavior, request order, +one lifecycle dispatch for 1,000 queued terminal requests, and a two-second +performance bound. + +```sh +cmake --build /private/tmp/webscene-876-build \ + --target webscene_native_engine_tests -j 3 +WEBSCENE_NATIVE_ENGINE_TEST_FILTER=top-level-navigation-lifecycle \ + /private/tmp/webscene-876-build/webscene_native_engine_tests +``` + +Result on macOS arm64: pass. The 1,000-request gate completed in 0.0058 seconds. +The next acceptance step is rebuilding the exact AppScene/WebScene SDK and +unchanged Code OSS release package, then repeating the two-navigation MCP +persistence smoke. diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime.cpp b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime.cpp index 3dc81dcf..b7e63b2e 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime.cpp +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime.cpp @@ -7021,6 +7021,100 @@ struct v8_dom_runtime::implementation final { return true; } + void cancel_pending_terminal_host_requests() + { + std::lock_guard lock(host_request_mutex); + const auto count = pending_terminal_host_requests.size(); + pending_terminal_host_requests.clear(); + terminal_host_request_timer_cutoff.reset(); + reserved_host_request_count = count > reserved_host_request_count + ? 0U : reserved_host_request_count - count; + } + + bool defer_reserved_terminal_host_request( + std::unique_ptr request) + { + if (!request) return false; + std::lock_guard lock(host_request_mutex); + if (reserved_host_request_count == 0U) return false; + if (pending_terminal_host_requests.empty()) { + // Every zero-delay timer scheduled by beforeunload/pagehide or by + // their microtasks has an earlier deadline. Timers created by one + // of those tasks receive a later deadline and cannot indefinitely + // postpone a terminal navigation. + terminal_host_request_timer_cutoff = + std::chrono::steady_clock::now(); + } + pending_terminal_host_requests.push_back(std::move(request)); + return true; + } + + bool queue_terminal_host_request( + v8::Local local_context, + std::unique_ptr request) + { + // A navigation requested recursively by its own lifecycle listener is + // coalesced into the outer handoff. + if (window_close_lifecycle_dispatching) return true; + if (!reserve_typed_host_request_capacity()) return false; + struct lifecycle_dispatch_guard final { + bool& dispatching; + explicit lifecycle_dispatch_guard(bool& value) : dispatching(value) + { + dispatching = true; + } + ~lifecycle_dispatch_guard() { dispatching = false; } + } dispatch_guard(window_close_lifecycle_dispatching); + const auto disposition = + request_window_close_in_current_realm(local_context); + if (disposition != WEBSCENE_WINDOW_CLOSE_ALLOW_V1) { + release_typed_host_request_capacity(); + return disposition == WEBSCENE_WINDOW_CLOSE_VETO_V1; + } + if (defer_reserved_terminal_host_request(std::move(request))) return true; + release_typed_host_request_capacity(); + return false; + } + + bool has_lifecycle_timer_before_terminal_handoff() const noexcept + { + if (pending_terminal_host_requests.empty() + || !terminal_host_request_timer_cutoff.has_value()) return false; + const auto cutoff = *terminal_host_request_timer_cutoff; + return std::any_of(timers.begin(), timers.end(), [&](const auto& timer) { + return !timer.animation_frame && timer.deadline <= cutoff; + }); + } + + bool drain_terminal_host_request_task() + { + auto notify = false; + { + std::lock_guard lock(host_request_mutex); + if (pending_terminal_host_requests.empty()) { + terminal_host_request_timer_cutoff.reset(); + return true; + } + while (!pending_terminal_host_requests.empty()) { + if (reserved_host_request_count == 0U) { + last_error = + "Deferred terminal navigation lost its host-request reservation"; + pending_terminal_host_requests.clear(); + terminal_host_request_timer_cutoff.reset(); + return false; + } + --reserved_host_request_count; + typed_host_requests.push_back( + std::move(pending_terminal_host_requests.front())); + pending_terminal_host_requests.pop_front(); + notify = true; + } + terminal_host_request_timer_cutoff.reset(); + } + if (notify && host_request_available) host_request_available(); + return true; + } + std::unique_ptr take_typed_host_request() { std::lock_guard lock(host_request_mutex); @@ -7368,14 +7462,12 @@ struct v8_dom_runtime::implementation final { uint32_t kind) { if (local_context != context.Get(isolate)) return true; - if (kind == WEBSCENE_HOST_REQUEST_WINDOW_RELOAD_V1) { - const auto disposition = - request_window_close_in_current_realm(local_context); - if (disposition == WEBSCENE_WINDOW_CLOSE_ERROR_V1) return false; - if (disposition == WEBSCENE_WINDOW_CLOSE_VETO_V1) return true; - } auto request = std::make_unique(); request->view.kind = kind; + if (kind == WEBSCENE_HOST_REQUEST_WINDOW_RELOAD_V1) { + return queue_terminal_host_request( + local_context, std::move(request)); + } return enqueue_typed_host_request(std::move(request)); } @@ -7398,10 +7490,6 @@ struct v8_dom_runtime::implementation final { } const auto scheme = resource_scheme(resolved); if (scheme != "http" && scheme != "https") return false; - const auto disposition = - request_window_close_in_current_realm(local_context); - if (disposition == WEBSCENE_WINDOW_CLOSE_ERROR_V1) return false; - if (disposition == WEBSCENE_WINDOW_CLOSE_VETO_V1) return true; auto request = std::make_unique(); request->view.kind = WEBSCENE_HOST_REQUEST_WINDOW_NAVIGATE_V1; request->view.flags = replace @@ -7413,7 +7501,7 @@ struct v8_dom_runtime::implementation final { "supported", "same-origin top-level navigation through the bounded native host request queue", "web-api-binding"); - return enqueue_typed_host_request(std::move(request)); + return queue_terminal_host_request(local_context, std::move(request)); } static void window_close(const v8::FunctionCallbackInfo& info) @@ -8393,6 +8481,7 @@ bool v8_dom_runtime::has_pending_tasks() const noexcept #endif #endif return impl_->has_pending_detached_dom_collection() + || !impl_->pending_terminal_host_requests.empty() || impl_->indexeddb_work_ready.load(std::memory_order_acquire) || impl_->websocket_transport.has_pending_events() || !impl_->pending_file_reading_tasks.empty() diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_lifecycle.inc b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_lifecycle.inc index 66dd6691..25b3da63 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_lifecycle.inc +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_lifecycle.inc @@ -289,6 +289,7 @@ resize_listeners.clear(); media_query_lists.clear(); timers.clear(); + cancel_pending_terminal_host_requests(); pending_file_reading_tasks.clear(); pending_window_messages.clear(); pending_window_message_bytes = 0U; diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_navigation.inc b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_navigation.inc index b6ff2a7e..d3e56394 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_navigation.inc +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_navigation.inc @@ -163,6 +163,7 @@ fullscreen_element = nullptr; document_fullscreen = false; { std::lock_guard lock(host_request_mutex); host_requests.clear(); } + cancel_pending_terminal_host_requests(); { std::lock_guard lock(host_request_mutex); typed_host_requests.clear(); diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_state.inc b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_state.inc index cf0af0ad..85548a66 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_state.inc +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_state.inc @@ -346,6 +346,14 @@ std::mutex host_request_mutex; std::deque host_requests; std::deque> typed_host_requests; + // Top-level reload/navigation is published from a later browser task so + // lifecycle listeners can finish zero-delay persistence work before the + // host retires this realm. Entries consume reserved host-request capacity + // while they wait, keeping the combined queue bounded. + std::deque> + pending_terminal_host_requests; + std::optional + terminal_host_request_timer_cutoff; bool primary_selection_publication_dirty{}; std::deque> download_requests; std::deque> diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_tasks.inc b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_tasks.inc index 5c221efb..25f6cf55 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_tasks.inc +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_tasks.inc @@ -827,6 +827,13 @@ // compilation and optimization work. An embedder must service that // queue; otherwise hot application code remains on its initial tier. pump_v8_platform_tasks(); + // A top-level navigation is a browser task, not a synchronous tail of + // beforeunload/pagehide. Preserve timer-source order for zero-delay + // lifecycle work, then expose every bounded terminal request together. + if (!pending_terminal_host_requests.empty() + && !has_lifecycle_timer_before_terminal_handoff()) { + return drain_terminal_host_request_task(); + } const auto timer_due = has_due_timer(); // Browser task-source selection is implementation-defined, but it // cannot permanently strand one ready source. Alternate a due timer diff --git a/experiments/WebScene.NativeEngine.Probe/tests/native_v8_runtime_input_tests.inc b/experiments/WebScene.NativeEngine.Probe/tests/native_v8_runtime_input_tests.inc index 141e0033..28ada9ae 100644 --- a/experiments/WebScene.NativeEngine.Probe/tests/native_v8_runtime_input_tests.inc +++ b/experiments/WebScene.NativeEngine.Probe/tests/native_v8_runtime_input_tests.inc @@ -2951,14 +2951,21 @@ void test_top_level_navigation_lifecycle() addEventListener('beforeunload', event => { __topLevelNavigationLifecycle.push( [event.type, event.bubbles, event.cancelable]); + Promise.resolve().then(() => setTimeout(() => + __topLevelNavigationLifecycle.push(['beforeunload-task']), 0)); }); addEventListener('pagehide', event => { __topLevelNavigationLifecycle.push( [event.type, event.bubbles, event.cancelable, event.persisted]); + setTimeout(() => + __topLevelNavigationLifecycle.push(['pagehide-task']), 0); }); )JS", "top-level-navigation-lifecycle-setup.js"); require(evaluate(engine, script, fixture_name) == "true", "top-level navigation request did not drain through the engine worker"); + require(evaluate(engine, "true", + "top-level-navigation-task-boundary.js") == "true", + "top-level navigation task boundary did not drain"); const auto request = take_typed_host_request(engine); require(request.kind == expected_kind, "top-level navigation did not emit the expected host request"); @@ -2966,8 +2973,8 @@ void test_top_level_navigation_lifecycle() "__topLevelNavigationLifecycle", "top-level-navigation-lifecycle-result.js"); require(lifecycle - == R"([["beforeunload",false,true],["pagehide",false,false,false]])", - "top-level navigation did not publish the terminal document lifecycle: " + == R"([["beforeunload",false,true],["pagehide",false,false,false],["beforeunload-task"],["pagehide-task"]])", + "top-level navigation reached the host before lifecycle tasks: " + lifecycle); webscene_engine_destroy(engine); }; @@ -2997,6 +3004,42 @@ void test_top_level_navigation_lifecycle() && !take_typed_host_request(veto_engine), "a canceled top-level reload reached the host or dispatched pagehide"); webscene_engine_destroy(veto_engine); + + auto* bounded_engine = webscene_engine_create(0); + require(bounded_engine != nullptr, + "bounded terminal navigation engine creation failed"); + const auto started = std::chrono::steady_clock::now(); + require(evaluate(bounded_engine, R"JS( + globalThis.__boundedNavigationLifecycle = 0; + addEventListener('pagehide', () => ++__boundedNavigationLifecycle); + for (let index = 0; index < 1000; ++index) { + location.assign('/?lifecycle-task-boundary=' + index); + } + true + )JS", "top-level-navigation-task-boundary-performance.js") == "true", + "bounded terminal navigation batch did not execute"); + require(evaluate(bounded_engine, "true", + "top-level-navigation-task-boundary-performance-barrier.js") == "true", + "bounded terminal navigation batch did not reach its task boundary"); + for (unsigned index = 0; index < 1000U; ++index) { + const auto request = take_typed_host_request(bounded_engine); + require(request.kind == WEBSCENE_HOST_REQUEST_WINDOW_NAVIGATE_V1 + && request.url + == "http://127.0.0.1/?lifecycle-task-boundary=" + + std::to_string(index), + "bounded terminal navigation queue changed request order"); + } + require(!take_typed_host_request(bounded_engine) + && evaluate(bounded_engine, "__boundedNavigationLifecycle", + "top-level-navigation-task-boundary-lifecycle-count.js") == "1", + "bounded terminal navigation queue duplicated lifecycle or host requests"); + const auto elapsed = std::chrono::duration( + std::chrono::steady_clock::now() - started).count(); + require(elapsed < 2.0, + "1,000 deferred terminal navigation requests exceeded two seconds"); + std::cout << "Terminal navigation task boundary gate: operations=1000 elapsed=" + << elapsed << "s\n"; + webscene_engine_destroy(bounded_engine); } void test_pointer_cursor_and_external_anchor_host_handoff(webscene_engine* engine) @@ -3086,6 +3129,9 @@ void test_pointer_cursor_and_external_anchor_host_handoff(webscene_engine* engin require(evaluate(engine, "location.reload(); true", "native-window-reload.js") == "true", "Location.reload script did not drain through the engine worker"); + require(evaluate(engine, "true", "native-window-reload-task-boundary.js") + == "true", + "Location.reload task boundary did not drain"); const auto reload_request = take_typed_host_request(engine); require(reload_request.kind == WEBSCENE_HOST_REQUEST_WINDOW_RELOAD_V1, "Location.reload did not emit a typed native reload request"); @@ -3093,6 +3139,9 @@ void test_pointer_cursor_and_external_anchor_host_handoff(webscene_engine* engin "location.href='?folder=/private/tmp/webscene-247-fixture/beta'; true", "native-window-navigate-href.js") == "true", "Location.href assignment did not drain through the engine worker"); + require(evaluate(engine, "true", "native-window-href-task-boundary.js") + == "true", + "Location.href task boundary did not drain"); const auto href_navigation = take_typed_host_request(engine); require( href_navigation.kind == WEBSCENE_HOST_REQUEST_WINDOW_NAVIGATE_V1 @@ -3109,6 +3158,9 @@ void test_pointer_cursor_and_external_anchor_host_handoff(webscene_engine* engin "location.replace('/replacement?workspace=one'); true", "native-window-navigate-replace.js") == "true", "Location.replace did not drain through the engine worker"); + require(evaluate(engine, "true", "native-window-replace-task-boundary.js") + == "true", + "Location.replace task boundary did not drain"); const auto replace_navigation = take_typed_host_request(engine); require( replace_navigation.kind == WEBSCENE_HOST_REQUEST_WINDOW_NAVIGATE_V1 @@ -3428,6 +3480,9 @@ void test_typed_window_host_request_performance(webscene_engine* engine) true )JS", "native-window-navigation-performance.js") == "true", "typed navigation batch did not drain through the engine worker"); + require(evaluate(engine, "true", + "native-window-navigation-performance-boundary.js") == "true", + "typed navigation batch task boundary did not drain"); for (unsigned index = 0; index < batch_size; ++index) { const auto request = take_typed_host_request(engine); require(