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
70 changes: 70 additions & 0 deletions docs/validation/indexeddb-terminal-promotion-20260921.md
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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) {
Expand All @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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 {
Expand All @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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<void>(id);
pending.terminal_handoff_critical = true;
}
}

bool drain_terminal_host_request_task()
{
auto notify = false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,10 @@
info.GetReturnValue().Set(v8::Integer::NewFromUnsigned(info.GetIsolate(), id));
}

static void schedule_timer(const v8::FunctionCallbackInfo<v8::Value>& info, bool repeating)
static void schedule_timer(
const v8::FunctionCallbackInfo<v8::Value>& info,
bool repeating,
bool terminal_handoff_candidate = false)
{
if (info.Length() < 1 || !info[0]->IsFunction()) return;
auto* self = current(info.GetIsolate());
Expand Down Expand Up @@ -106,7 +109,8 @@
v8::Global<v8::Function>(info.GetIsolate(), info[0].As<v8::Function>()),
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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -597,6 +597,12 @@
info.GetReturnValue().Set(resolver->GetPromise());
}

static void indexeddb_schedule_task(
const v8::FunctionCallbackInfo<v8::Value>& info)
{
schedule_timer(info, false, true);
}

void install_indexeddb(v8::Local<v8::Context> realm)
{
if (indexeddb == nullptr) return;
Expand All @@ -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()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
std::vector<v8::Global<v8::Value>> arguments;
double animation_timestamp_ms{-1};
bool terminal_handoff_critical{false};
bool terminal_handoff_candidate{false};
};

struct terminal_handoff_task_scope final {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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 => {
Expand All @@ -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;
Expand All @@ -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);
Expand All @@ -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');
Expand All @@ -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 => {
Expand All @@ -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', () => {
Expand Down
Loading