Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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
78 changes: 72 additions & 6 deletions crates/js-component-bindgen/runtime/runtime-all.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// @bytecodealliance/jco-cm-runtime@0.1.0
// generated from commit 9e941c33a4d13e04bd3c5098567e37852ed73f6e
// generated from commit 25ddf8a96ffd052a3262cdcc6c658bd6a23fa3ef
//#region runtime/runtime.js
/** Experimental JavaScript Component Model runtime contract, independent of package version. */
const CM_RUNTIME_API_VERSION = 1;
Expand Down Expand Up @@ -602,7 +602,8 @@ const initializeStoreAsyncState = () => ({
deadlockCheck: null,
pendingHostOperations: 0,
hostWakeupScheduled: false,
idleWaiters: /* @__PURE__ */ new Set()
idleWaiters: /* @__PURE__ */ new Set(),
syncCalls: []
});
const initializeComponentAsyncStates = () => /* @__PURE__ */ new Map();
const initializeCoreTrapMessages = (messages) => new Map(Object.entries(messages));
Expand Down Expand Up @@ -637,8 +638,10 @@ function checkForDeadlock(context) {
exitedTasks.add(task);
unresolvedRoots.add(task.getRootTask());
}
const syncCall = storeAsyncState.syncCalls.at(-1);
if (syncCall !== void 0 && !syncCall.task.isResolvedState()) unresolvedRoots.add(syncCall.task.getRootTask());
if (unresolvedRoots.size === 0) return;
const err = new RuntimeError("wasm trap: deadlock detected: event loop cannot make further progress");
const err = new RuntimeError(syncCall === void 0 ? "wasm trap: deadlock detected: event loop cannot make further progress" : "cannot block a synchronous task before returning");
err.deadlockDetail = {
pendingHostOperations: storeAsyncState.pendingHostOperations,
suspendedTasks: [...suspendedTasks].map((task) => ({
Expand Down Expand Up @@ -1181,14 +1184,15 @@ function defineComponentAsyncState() {
}
isThreadReady(thread) {
const meta = this.#suspendedThreadsByRef.get(thread);
return !!meta && !meta.suspended && (meta.thread.isRejected() || meta.readyFn());
return !!meta && !meta.suspended && this.suspendedThreadReady(thread);
}
suspendedThreadReady(thread) {
const meta = this.#suspendedThreadsByRef.get(thread);
if (!meta) return false;
if (!meta.readyFn) throw new Error(`suspended thread [${thread.id()}] is missing a readiness function`);
if (this.isTrapped() || meta.thread.isRejected()) return true;
if (!meta.readyFn()) return false;
if (!meta.thread.isImplicit()) return true;
const task = meta.thread.task();
return !task.needsExclusiveLock() || !this.isExclusivelyLocked() || this.exclusivelyLockedBy(task.id());
}
Expand All @@ -1201,9 +1205,27 @@ function defineComponentAsyncState() {
hasPendingSchedulerWork() {
if (this.#pendingTaskStarts > 0) return true;
if (this.#lockHandoffScheduled) return true;
if (this.#heldBySyncCall()) return false;
for (const meta of this.#suspendedThreadsByRef.values()) if (this.suspendedThreadReady(meta.thread)) return true;
return false;
}
beginSyncCall(task) {
this.#context.deadlock.storeAsyncState.syncCalls.push({
componentIdx: this.#componentIdx,
task
});
}
endSyncCall(task) {
const syncCalls = this.#context.deadlock.storeAsyncState.syncCalls;
const idx = syncCalls.findIndex((call) => call.task === task);
if (idx === -1) return;
syncCalls.splice(idx, 1);
for (const state of this.#context.deadlock.asyncState.values()) if (state.hasPendingSchedulerWork()) state.runTickLoop();
}
#heldBySyncCall() {
const top = this.#context.deadlock.storeAsyncState.syncCalls.at(-1);
return top !== void 0 && top.componentIdx !== this.#componentIdx;
}
stop() {
this.#tickLoop?.();
this.#tickLoop = null;
Expand All @@ -1229,14 +1251,15 @@ function defineComponentAsyncState() {
this.#tickLoop = onNextMacrotask(run);
}
tick() {
const held = this.#heldBySyncCall();
for (const [thread, meta] of this.#suspendedThreadsByRef) {
if (!meta || !meta.readyFn) throw new Error(`missing/invalid thread meta despite thread [${thread.id()}] being present`);
if (this.isTrapped() || meta.thread.isRejected()) {
DEBUG: debugLog("[ComponentAsyncState#tick()] detected thread rejection, leaving early", { meta });
this.resumeThread(thread);
return TICK_RESUMED;
}
if (!this.suspendedThreadReady(thread)) continue;
if (held || !this.suspendedThreadReady(thread)) continue;
DEBUG: debugLog("[ComponentAsyncState#tick()] resuming thread via tick", {
threadID: thread.id(),
componentIdx: this.#componentIdx
Expand Down Expand Up @@ -2902,7 +2925,15 @@ const suspendingImport = (context, componentIdx, fn, syncOnly = false, switchesT
}
return result;
}
const settled = (async () => fn.apply(null, args))();
let started;
try {
started = fn.apply(null, args);
} catch (error) {
currentTaskMeta[componentIdx] = saved;
if (!switchesTask) currentTaskMeta.current = saved;
throw recordTrap(context.traps, componentIdx, error, convertsRangeErrors);
}
const settled = (async () => started)();
const resumption = promiseWithResolvers();
/** Restore this stack's task, then let the stack resume. */
const resume = (deliver) => resumeInTurn(currentTaskMeta, () => {
Expand Down Expand Up @@ -4942,6 +4973,7 @@ function defineAsyncTask() {
#calleeIsAsync = null;
#admissionTicket = null;
#funcTypeIsAsync = false;
#syncCall = false;
#returnResultTypeIdx = null;
#parentSubtask = null;
#errHandling;
Expand Down Expand Up @@ -5193,6 +5225,25 @@ function defineAsyncTask() {
setFuncTypeIsAsync(v) {
this.#funcTypeIsAsync = v;
}
/**
* Record that this task is a call of a non-async-typed guest function,
* in progress until the task resolves. Until then, only threads of its
* instance are scheduled, and a block with none of them ready traps
* (Canonical ABI `canon_lift`).
*/
beginSyncCall() {
if (this.#syncCall || this.#funcTypeIsAsync || this.#componentIdx === -1 || this.isResolvedState()) return;
this.#syncCall = true;
getOrCreateAsyncState(this.#context.lookup, this.#componentIdx).beginSyncCall(this);
}
#beginGuestSyncCall() {
if (this.#callingWasmExport) this.beginSyncCall();
}
#endSyncCall() {
if (!this.#syncCall) return;
this.#syncCall = false;
getOrCreateAsyncState(this.#context.lookup, this.#componentIdx).endSyncCall(this);
}
setReturnResultTypeIdx(v) {
this.#returnResultTypeIdx = v;
}
Expand Down Expand Up @@ -5227,6 +5278,7 @@ function defineAsyncTask() {
});
}
}
this.#beginGuestSyncCall();
return true;
}
tryEnter() {
Expand All @@ -5238,6 +5290,7 @@ function defineAsyncTask() {
const cstate = getOrCreateAsyncState(this.#context.lookup, this.#componentIdx);
if (this.isSync()) {
this.#entered = true;
this.#beginGuestSyncCall();
return true;
}
if (cstate.hasBackpressure()) return null;
Expand All @@ -5252,6 +5305,7 @@ function defineAsyncTask() {
return false;
}
this.#entered = true;
this.#beginGuestSyncCall();
return true;
}
async enter(opts) {
Expand All @@ -5271,6 +5325,7 @@ function defineAsyncTask() {
const cstate = getOrCreateAsyncState(this.#context.lookup, this.#componentIdx);
if (this.isSync()) {
this.#entered = true;
this.#beginGuestSyncCall();
if (this.#isManualAsync) {
if (this.needsExclusiveLock()) await cstate.acquireExclusiveLock(this.#id);
}
Expand Down Expand Up @@ -5336,6 +5391,7 @@ function defineAsyncTask() {
return false;
}
this.#entered = true;
this.#beginGuestSyncCall();
return this.#entered;
}
isRunningState() {
Expand Down Expand Up @@ -5484,6 +5540,7 @@ function defineAsyncTask() {
this.cancelled = true;
this.onResolve(args?.error ?? null);
this.#state = TASK_RESOLVED;
this.#endSyncCall();
if (!this.#entered) this.notifyProgress();
}
onResolve(taskValue) {
Expand Down Expand Up @@ -5595,6 +5652,7 @@ function defineAsyncTask() {
}
this.validateResourceBorrowScope();
this.#state = TASK_RESOLVED;
this.#endSyncCall();
switch (results.length) {
case 0:
this.onResolve(void 0);
Expand All @@ -5620,6 +5678,7 @@ function defineAsyncTask() {
taskID: this.#id
});
this.endFirstSlice();
this.#endSyncCall();
if (this.#exited) throw new Error("task has already exited");
this.validateResourceBorrowScope();
const state = this.#componentIdx === -1 ? null : getOrCreateAsyncState(this.#context.lookup, this.#componentIdx);
Expand Down Expand Up @@ -6565,6 +6624,7 @@ function symmetricSyncGuestCallEnter(_context, callerComponentIdx, calleeIsAsync
previousTaskMayBlock: _context.mayBlock.value
});
_context.mayBlock.value = newTask.mayBlock() ? 1 : 0;
newTask.beginSyncCall();
DEBUG: debugLog("[_symmetricSyncGuestCallEnter()] finished preparing", {
callerComponentIdx,
calleeComponentIdx,
Expand Down Expand Up @@ -6629,6 +6689,7 @@ function defineAsyncThread() {
#task;
#state;
#startFn = null;
#implicit;
storage = [0, 0];
constructor(context, opts) {
this.#context = context;
Expand All @@ -6640,6 +6701,11 @@ function defineAsyncThread() {
this.#startFn = opts.startFn;
this.#state = THREAD_NOT_STARTED;
} else this.#state = THREAD_RUNNING;
this.#implicit = !opts.startFn;
}
/** Whether this is its task's implicit thread (not made by `thread.new-indirect`). */
isImplicit() {
return this.#implicit;
}
id() {
return this.#id;
Expand Down
66 changes: 62 additions & 4 deletions crates/js-component-bindgen/src/intrinsics/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,11 @@ impl ComponentIntrinsic {
"_checkIdle",
"_isIdle",
"CALL_TRACKING",
// Reserved so that an export named e.g. `backpressure-inc` is not
// bound as a local that shadows the intrinsic its trampolines call.
Self::GetOrCreateAsyncState.name(),
Self::BackpressureInc.name(),
Self::BackpressureDec.name(),
]
}

Expand Down Expand Up @@ -350,7 +355,7 @@ impl ComponentIntrinsic {
let var_name = render_args.require_intrinsic(Self::GlobalStoreAsyncState);
uwriteln!(
output,
r#"const {var_name} = {{ deadlockCheck: null, pendingHostOperations: 0, idleWaiters: new Set() }};"#
r#"const {var_name} = {{ deadlockCheck: null, pendingHostOperations: 0, idleWaiters: new Set(), syncCalls: [] }};"#
);
}

Expand Down Expand Up @@ -394,9 +399,22 @@ impl ComponentIntrinsic {
unresolvedRoots.add(task.getRootTask());
}}
}}

// With a call of a non-async-typed function in progress, nothing but
// its instance's threads may run until it returns, so running out of
// ready threads is that call blocking with none to switch to (Canonical
// ABI `canon_lift`), rather than a deadlock of the event loop.
const syncCall = {store_async_state}.syncCalls.at(-1);
if (syncCall !== undefined && !syncCall.task.isResolvedState()) {{
unresolvedRoots.add(syncCall.task.getRootTask());
}}
if (unresolvedRoots.size === 0) {{ return; }}

const err = new {runtime_error_class}('wasm trap: deadlock detected: event loop cannot make further progress');
const err = new {runtime_error_class}(
syncCall === undefined
? 'wasm trap: deadlock detected: event loop cannot make further progress'
: 'cannot block a synchronous task before returning'
);
// Which tasks were waiting, and on whose behalf. The message stays
// exactly what the Canonical ABI calls for, so this rides alongside
// it: a deadlock reported from a real program is otherwise a bare
Expand Down Expand Up @@ -698,6 +716,8 @@ impl ComponentIntrinsic {
let cannot_enter_component = Trap::CannotEnterComponent.to_string();
let report_trap_fn = render_args.require_intrinsic(Self::ReportTrap);
let check_idle_fn = render_args.require_intrinsic(Self::CheckIdle);
let store_async_state = render_args.require_intrinsic(Self::GlobalStoreAsyncState);
let async_state_map = render_args.require_intrinsic(Self::GlobalAsyncStateMap);

output.push_str(&format!(
r#"
Expand Down Expand Up @@ -1252,9 +1272,12 @@ impl ComponentIntrinsic {
return this.#suspendedThreadsByRef.get(thread)?.suspended ?? false;
}}

// Readiness as `thread.{{suspend,yield}}-then-promote` sees it: the same
// condition the scheduler uses, including the exclusive lock (Canonical
// ABI `Thread.ready`, whose callback readiness waits for the lock).
isThreadReady(thread) {{
const meta = this.#suspendedThreadsByRef.get(thread);
return !!meta && !meta.suspended && (meta.thread.isRejected() || meta.readyFn());
return !!meta && !meta.suspended && this.suspendedThreadReady(thread);
}}

suspendedThreadReady(thread) {{
Expand All @@ -1265,6 +1288,9 @@ impl ComponentIntrinsic {
}}
if (this.isTrapped() || meta.thread.isRejected()) {{ return true; }}
if (!meta.readyFn()) {{ return false; }}
// Only the implicit thread of a task that takes the exclusive lock
// waits for it; threads made by `thread.new-indirect` never do.
if (!meta.thread.isImplicit()) {{ return true; }}
const task = meta.thread.task();
return !task.needsExclusiveLock()
|| !this.isExclusivelyLocked()
Expand All @@ -1277,12 +1303,39 @@ impl ComponentIntrinsic {
hasPendingSchedulerWork() {{
if (this.#pendingTaskStarts > 0) {{ return true; }}
if (this.#lockHandoffScheduled) {{ return true; }}
if (this.#heldBySyncCall()) {{ return false; }}
for (const meta of this.#suspendedThreadsByRef.values()) {{
if (this.suspendedThreadReady(meta.thread)) {{ return true; }}
}}
return false;
}}

// Calls of non-async-typed functions (Canonical ABI `canon_lift` with
// `not ft.async_`) are tracked store-wide, innermost last. Until such a
// call's task resolves, the spec resumes only ready threads of the
// callee's instance, and traps if there are none; nothing else in the
// store runs.
beginSyncCall(task) {{
{store_async_state}.syncCalls.push({{ componentIdx: this.#componentIdx, task }});
}}

endSyncCall(task) {{
const idx = {store_async_state}.syncCalls.findIndex((call) => call.task === task);
if (idx === -1) {{ return; }}
{store_async_state}.syncCalls.splice(idx, 1);
// Instances held back by the call may run again.
for (const state of {async_state_map}.values()) {{
if (state.hasPendingSchedulerWork()) {{ state.runTickLoop(); }}
}}
}}

// Whether a call of a non-async-typed function into another instance
// is in progress, so that this instance's threads may not be resumed.
#heldBySyncCall() {{
const top = {store_async_state}.syncCalls.at(-1);
return top !== undefined && top.componentIdx !== this.#componentIdx;
}}

stop() {{
this.#tickLoop?.();
this.#tickLoop = null;
Expand All @@ -1303,6 +1356,10 @@ impl ComponentIntrinsic {
return;
}}
if (result === {component_async_state_class}.TickResult.IDLE) {{
// This also runs while a synchronous call into another
// instance holds this one back: the loop keeps polling, so
// that it notices readiness and takes part in the store-wide
// idle check both during the call and after it ends.
{check_for_deadlock_fn}();
}}
// Let resumed microtasks drain before the next slice;
Expand All @@ -1317,6 +1374,7 @@ impl ComponentIntrinsic {
tick() {{
// (resuming returns immediately below, so the map is never
// mutated while this loop is still iterating it)
const held = this.#heldBySyncCall();
for (const [thread, meta] of this.#suspendedThreadsByRef) {{
if (!meta || !meta.readyFn) {{
throw new Error(`missing/invalid thread meta despite thread [${{thread.id()}}] being present`);
Expand All @@ -1328,7 +1386,7 @@ impl ComponentIntrinsic {
return {component_async_state_class}.TickResult.RESUMED;
}}

if (!this.suspendedThreadReady(thread)) {{ continue; }}
if (held || !this.suspendedThreadReady(thread)) {{ continue; }}

{debug_log_fn}('[{component_async_state_class}#tick()] resuming thread via tick', {{
threadID: thread.id(),
Expand Down
Loading
Loading