Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions docs/validation/terminal-navigation-task-boundary-20260920.md
Original file line number Diff line number Diff line change
@@ -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.
111 changes: 100 additions & 11 deletions experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<native_host_request> 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<v8::Context> local_context,
std::unique_ptr<native_host_request> 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<native_host_request> take_typed_host_request()
{
std::lock_guard lock(host_request_mutex);
Expand Down Expand Up @@ -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<native_host_request>();
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));
}

Expand All @@ -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<native_host_request>();
request->view.kind = WEBSCENE_HOST_REQUEST_WINDOW_NAVIGATE_V1;
request->view.flags = replace
Expand All @@ -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<v8::Value>& info)
Expand Down Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,14 @@
std::mutex host_request_mutex;
std::deque<std::string> host_requests;
std::deque<std::unique_ptr<native_host_request>> 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<std::unique_ptr<native_host_request>>
pending_terminal_host_requests;
std::optional<std::chrono::steady_clock::time_point>
terminal_host_request_timer_cutoff;
bool primary_selection_publication_dirty{};
std::deque<std::unique_ptr<native_download_request>> download_requests;
std::deque<std::unique_ptr<native_outbound_drag_request>>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2951,23 +2951,30 @@ 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");
const auto lifecycle = evaluate(engine,
"__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);
};
Expand Down Expand Up @@ -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<double>(
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)
Expand Down Expand Up @@ -3086,13 +3129,19 @@ 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");
require(evaluate(engine,
"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
Expand All @@ -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
Expand Down Expand Up @@ -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(
Expand Down
Loading