From 1acef64a3d03a0c93a21e771351450b0c686cb71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wies=C5=82aw=20=C5=A0olt=C3=A9s?= Date: Mon, 21 Sep 2026 01:25:42 +0200 Subject: [PATCH] Promote in-flight IndexedDB work at terminal handoff --- .../indexeddb-terminal-promotion-20260921.md | 70 +++++++++++++++++++ .../native/webscene_indexeddb_compatibility.h | 23 +++--- .../native/webscene_v8_runtime.cpp | 16 +++++ .../webscene_v8_runtime_browser_apis.inc | 8 ++- .../native/webscene_v8_runtime_indexeddb.inc | 11 +++ .../webscene_v8_runtime_state_types.inc | 1 + .../native_v8_runtime_indexeddb_tests.inc | 37 ++++++++-- 7 files changed, 148 insertions(+), 18 deletions(-) create mode 100644 docs/validation/indexeddb-terminal-promotion-20260921.md diff --git a/docs/validation/indexeddb-terminal-promotion-20260921.md b/docs/validation/indexeddb-terminal-promotion-20260921.md new file mode 100644 index 00000000..40e5dd09 --- /dev/null +++ b/docs/validation/indexeddb-terminal-promotion-20260921.md @@ -0,0 +1,70 @@ +# IndexedDB terminal handoff promotion + +Tracking: #882, parent #269. + +## Exact product evidence + +The unchanged Code OSS Release package built from AppScene +`cd0a02ecd15f0a635bccc242cdd657888db39e25` and WebScene +`ba71aa1b4e832c521b81cb3c252c513412ca2c7f` intermittently loses the +workspace `mcpInputs` record across reload. An instrumented acceptance run +proved that the value exists in VS Code memory immediately before reload and +is absent in the replacement realm: + +```text +mcpStoredInputKeysBeforeReload = ["${input:sceneSecret}"] +mcpProfileInputKeysBeforeReload = [] +mcpStoredInputKeys = [] +mcpStoredInputPresent = false +``` + +The failure artifact is +`artifacts/smoke-cd0a02e-ba71aa1b-mcp-before-reload-probe-1` in the integration +repository. The exact executable SHA-256 is +`876d9eaf704655e0e6a9ee777501c4099cf03dbc9434fd7914bc7301ce3b2ecf`. + +## Root cause + +VS Code may start its idle storage flush before terminal navigation. That +flush can already have queued an IndexedDB compatibility transaction when +reload begins. The earlier terminal boundary retained work created by the +lifecycle listeners and their descendants, but it deliberately excluded +pre-existing work. JavaScript Promise dependency is not observable at the +host boundary, so the pending transaction could be retired during realm +teardown even though VS Code awaited it during shutdown. Whether the idle +transaction completed first made the product gate intermittent. + +## Runtime contract + +The IndexedDB compatibility layer schedules its zero-delay transaction work +through a private runtime task entry point. Those tasks are tagged as terminal +handoff candidates without changing the public timer contract. When terminal +navigation starts, WebScene promotes already queued candidate tasks and +already pending native IndexedDB operations into the existing bounded +persistence boundary. + +Only IndexedDB compatibility work receives the candidate tag. Intervals, +animation frames, delayed timers, and arbitrary application tasks remain +outside the boundary. Candidate timers consume the existing 1,024-task budget; +native operations retain their existing bounded pending-operation capacity. + +## Focused gate + +The terminal navigation fixture now queues a real read-write transaction +before `location.reload()`, queues another transaction from `beforeunload`, +and aborts any active pre-existing transaction from `pagehide`. It asserts +that both writes, the native commit, and the commit continuation finish before +handoff. It then restarts the engine and reads both durable values. The +self-refilling task fixture continues to prove that the terminal boundary is +bounded. + +```sh +cmake --build /private/tmp/webscene-882-build \ + --target webscene_native_engine_tests -j 3 +WEBSCENE_NATIVE_ENGINE_TEST_FILTER=terminal-indexeddb-navigation \ + /private/tmp/webscene-882-build/webscene_native_engine_tests +``` + +Result on macOS arm64 Release: pass. The durable transaction-to-handoff gate +completed in 0.0037 seconds. The next gate rebuilds the exact AppScene/WebScene +SDK and repeats the unchanged Code OSS two-realm MCP persistence smoke. diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_indexeddb_compatibility.h b/experiments/WebScene.NativeEngine.Probe/native/webscene_indexeddb_compatibility.h index c2f5ccbc..d8ccd242 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/webscene_indexeddb_compatibility.h +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_indexeddb_compatibility.h @@ -8,7 +8,8 @@ inline constexpr std::string_view indexeddb_compatibility_source = R"JS( (() => { 'use strict'; const nativeStorage = globalThis.__webSceneIndexedDBStorage; - if (typeof nativeStorage !== 'function') return; + const scheduleTask = globalThis.__webSceneIndexedDBTask; + if (typeof nativeStorage !== 'function' || typeof scheduleTask !== 'function') return; const openConnections = new Map(); const loadedDatabases = new Map(); const writeTails = new Map(); @@ -256,7 +257,7 @@ R"JS( class IDBTransaction extends EventTarget { this._requireActive(); const request = new IDBRequest(source, this); this._pending++; - setTimeout(() => { + scheduleTask(() => { if (!this._active) return; try { request._success(operation()); } catch (error) { @@ -265,31 +266,31 @@ R"JS( class IDBTransaction extends EventTarget { } this._pending--; this._scheduleFinish(); - }, 0); + }); return request; } _queueCursor(request, entries, index) { this._requireActive(); request.readyState = 'pending'; this._pending++; - setTimeout(() => { + scheduleTask(() => { if (!this._active) return; request.result = index < entries.length ? new IDBCursor(request, entries, index) : null; request.readyState = 'done'; request.dispatchEvent(event('success')); this._pending--; this._scheduleFinish(); - }, 0); + }); } _scheduleFinish() { if (!this._active || this._pending !== 0 || this._finishScheduled) return; this._finishScheduled = true; - setTimeout(() => { + scheduleTask(() => { this._finishScheduled = false; if (!this._active || this._pending !== 0) return; if (this.mode === 'readonly') this._complete(); else this._commit(); - }, 0); + }); } async _commit() { if (this._commitQueued) return; @@ -452,7 +453,7 @@ R"JS( class IDBTransaction extends EventTarget { } const requested = version === undefined ? undefined : Number(version); const request = new IDBOpenDBRequest(); - setTimeout(async () => { + scheduleTask(async () => { try { const loaded = await nativeStorage('load', name); const existing = loaded.data === null ? emptyState(0) : normalizeState(loaded.data); @@ -484,13 +485,13 @@ R"JS( class IDBTransaction extends EventTarget { request.transaction = null; request._success(database); } catch (error) { request._failure(error); } - }, 0); + }); return request; } deleteDatabase(name) { name = String(name); const request = new IDBOpenDBRequest(); - setTimeout(async () => { + scheduleTask(async () => { try { let oldVersion = 0; try { @@ -504,7 +505,7 @@ R"JS( class IDBTransaction extends EventTarget { loadedDatabases.delete(name); request._success(undefined); } catch (error) { request._failure(error); } - }, 0); + }); return request; } cmp(first, second) { diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime.cpp b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime.cpp index b9870b5e..16f4ec38 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime.cpp +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime.cpp @@ -7051,6 +7051,7 @@ struct v8_dom_runtime::implementation final { if (window_close_lifecycle_dispatching) return true; if (!reserve_typed_host_request_capacity()) return false; terminal_handoff_task_budget = maximum_terminal_handoff_tasks; + promote_terminal_handoff_persistence_work(); struct lifecycle_dispatch_guard final { bool& dispatching; explicit lifecycle_dispatch_guard(bool& value) : dispatching(value) @@ -7085,6 +7086,21 @@ struct v8_dom_runtime::implementation final { }); } + void promote_terminal_handoff_persistence_work() noexcept + { + for (auto& timer : timers) { + if (!timer.terminal_handoff_candidate + || timer.terminal_handoff_critical + || terminal_handoff_task_budget == 0U) continue; + timer.terminal_handoff_critical = true; + --terminal_handoff_task_budget; + } + for (auto& [id, pending] : pending_indexeddb_promises) { + static_cast(id); + pending.terminal_handoff_critical = true; + } + } + bool drain_terminal_host_request_task() { auto notify = false; diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_browser_apis.inc b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_browser_apis.inc index e4f03374..87239d22 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_browser_apis.inc +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_browser_apis.inc @@ -49,7 +49,10 @@ info.GetReturnValue().Set(v8::Integer::NewFromUnsigned(info.GetIsolate(), id)); } - static void schedule_timer(const v8::FunctionCallbackInfo& info, bool repeating) + static void schedule_timer( + const v8::FunctionCallbackInfo& info, + bool repeating, + bool terminal_handoff_candidate = false) { if (info.Length() < 1 || !info[0]->IsFunction()) return; auto* self = current(info.GetIsolate()); @@ -106,7 +109,8 @@ v8::Global(info.GetIsolate(), info[0].As()), std::move(arguments), -1, - terminal_handoff_critical}); + terminal_handoff_critical, + terminal_handoff_candidate}); #if defined(WEBSCENE_NATIVE_ENGINE_WITH_V8_INSPECTOR) self->inspector_async_task_scheduled( repeating ? "setInterval" : "setTimeout", diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_indexeddb.inc b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_indexeddb.inc index fc3de811..d10882b1 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_indexeddb.inc +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_indexeddb.inc @@ -597,6 +597,12 @@ info.GetReturnValue().Set(resolver->GetPromise()); } + static void indexeddb_schedule_task( + const v8::FunctionCallbackInfo& info) + { + schedule_timer(info, false, true); + } + void install_indexeddb(v8::Local realm) { if (indexeddb == nullptr) return; @@ -606,6 +612,11 @@ js_string(isolate, "__webSceneIndexedDBStorage"), v8::Function::New(realm, indexeddb_storage_operation).ToLocalChecked(), v8::PropertyAttribute::DontEnum).Check(); + global->DefineOwnProperty( + realm, + js_string(isolate, "__webSceneIndexedDBTask"), + v8::Function::New(realm, indexeddb_schedule_task).ToLocalChecked(), + v8::PropertyAttribute::DontEnum).Check(); auto script = v8::Script::Compile( realm, js_string(isolate, std::string(indexeddb_compatibility_source).c_str())) diff --git a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_state_types.inc b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_state_types.inc index 8e28d96a..168276e5 100644 --- a/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_state_types.inc +++ b/experiments/WebScene.NativeEngine.Probe/native/webscene_v8_runtime_state_types.inc @@ -72,6 +72,7 @@ std::vector> arguments; double animation_timestamp_ms{-1}; bool terminal_handoff_critical{false}; + bool terminal_handoff_candidate{false}; }; struct terminal_handoff_task_scope final { diff --git a/experiments/WebScene.NativeEngine.Probe/tests/native_v8_runtime_indexeddb_tests.inc b/experiments/WebScene.NativeEngine.Probe/tests/native_v8_runtime_indexeddb_tests.inc index ea24a90b..e2536b78 100644 --- a/experiments/WebScene.NativeEngine.Probe/tests/native_v8_runtime_indexeddb_tests.inc +++ b/experiments/WebScene.NativeEngine.Probe/tests/native_v8_runtime_indexeddb_tests.inc @@ -649,6 +649,7 @@ void test_terminal_navigation_waits_for_indexeddb_commit() request.onerror = () => reject(request.error); request.onsuccess = () => resolve(request.result); }); + globalThis.terminalIndexedDbDatabase = database; let pendingFlushTimer = 0; addEventListener('beforeunload', () => { terminalIndexedDb.order.push('beforeunload'); @@ -679,6 +680,9 @@ void test_terminal_navigation_waits_for_indexeddb_commit() terminalIndexedDb.order.push('pagehide'); // Model VS Code disposing its delayed storage flush during pagehide. clearTimeout(pendingFlushTimer); + if (globalThis.terminalIndexedDbPendingTransaction?._active) { + globalThis.terminalIndexedDbPendingTransaction.abort(); + } }); terminalIndexedDb.ready = true; })().catch(error => { @@ -688,7 +692,17 @@ void test_terminal_navigation_waits_for_indexeddb_commit() wait_for_indexeddb_flag(engine, "terminalIndexedDb.ready===true"); const auto started = std::chrono::steady_clock::now(); - require(evaluate(engine, "location.reload(); true", + require(evaluate(engine, R"JS( + globalThis.terminalIndexedDbPendingTransaction = + terminalIndexedDbDatabase.transaction('state', 'readwrite'); + terminalIndexedDbPendingTransaction.objectStore('state') + .put('already-pending', 'pendingBeforeReload'); + terminalIndexedDbPendingTransaction.oncomplete = () => { + terminalIndexedDb.order.push('preexisting-commit'); + }; + location.reload(); + true; + )JS", "terminal-indexeddb-reload.js") == "true", "terminal IndexedDB reload request failed"); typed_host_request_snapshot request; @@ -708,8 +722,17 @@ void test_terminal_navigation_waits_for_indexeddb_commit() "terminalIndexedDb.ready===true" "&&terminalIndexedDb.committed===true" "&&terminalIndexedDb.continuation===true" - "&&terminalIndexedDb.order.join(',')===" - "'beforeunload,flush-timer,commit,continuation,pagehide'" + "&&terminalIndexedDb.order[0]==='beforeunload'" + "&&terminalIndexedDb.order.indexOf('preexisting-commit')>0" + "&&terminalIndexedDb.order.indexOf('flush-timer')>0" + "&&terminalIndexedDb.order.indexOf('commit')>" + "terminalIndexedDb.order.indexOf('flush-timer')" + "&&terminalIndexedDb.order.indexOf('continuation')>" + "terminalIndexedDb.order.indexOf('commit')" + "&&terminalIndexedDb.order.indexOf('pagehide')>" + "terminalIndexedDb.order.indexOf('preexisting-commit')" + "&&terminalIndexedDb.order.indexOf('pagehide')>" + "terminalIndexedDb.order.indexOf('continuation')" "&&terminalIndexedDb.error===null", "terminal-indexeddb-before-handoff-result.js") == "true", "terminal reload preceded IndexedDB completion: " + terminal_state); @@ -724,7 +747,9 @@ void test_terminal_navigation_waits_for_indexeddb_commit() require(engine != nullptr, "terminal IndexedDB restart engine creation failed"); execute_and_wait(engine, R"JS( - globalThis.terminalIndexedDbRestart = { done: false, value: null, error: null }; + globalThis.terminalIndexedDbRestart = { + done: false, value: null, pendingValue: null, error: null + }; (async () => { const database = await new Promise((resolve, reject) => { const request = indexedDB.open('terminal-navigation'); @@ -733,12 +758,14 @@ void test_terminal_navigation_waits_for_indexeddb_commit() }); const transaction = database.transaction('state', 'readonly'); const request = transaction.objectStore('state').get('mcpInputs'); + const pendingRequest = transaction.objectStore('state').get('pendingBeforeReload'); transaction.onerror = transaction.onabort = () => { terminalIndexedDbRestart.error = String(transaction.error); terminalIndexedDbRestart.done = true; }; transaction.oncomplete = () => { terminalIndexedDbRestart.value = request.result; + terminalIndexedDbRestart.pendingValue = pendingRequest.result; terminalIndexedDbRestart.done = true; }; })().catch(error => { @@ -749,10 +776,10 @@ void test_terminal_navigation_waits_for_indexeddb_commit() wait_for_indexeddb_flag(engine, "terminalIndexedDbRestart.done===true"); require(evaluate(engine, "terminalIndexedDbRestart.value==='durable'" + "&&terminalIndexedDbRestart.pendingValue==='already-pending'" "&&!terminalIndexedDbRestart.error", "terminal-indexeddb-restart-result.js") == "true", "terminal IndexedDB value was not durable at host handoff"); - execute(engine, R"JS( globalThis.terminalRefillCount = 0; addEventListener('pagehide', () => {