jspi: retire the asyncify pipeline — knob, post-link tail, binaryen hooks

Phase 8 in the parent repo. Deleted: asyncify-scheduler.js, apply-asyncify.sh,
apply-finalize.sh, inject-dyncall-shims.sh, asyncify-imports/removelist.txt,
the wasm-opt/finalize stub pair, scripts/binaryen-hoist-pass/ (the fork stays
a dormant submodule; removal is a follow-up), bench/wasm-opt-bench.sh (README
marked historical), wasm/shims/context_sleep.cpp, and the sched-context
harness app + Makefile targets.

PCBJAM_ASYNC_BACKEND is gone: build-wx-wasm.sh hardcodes the jspi stamp
(still force-cleans pre-migration trees), build-kicad-target.sh gives editors
the JSPI link surface and the CLIs nothing (they pin ASYNCIFY=0), the stub
dance is replaced by an unconditional .real-restore, build-wasm-test.sh lost
its whole post-link loop, docker/build.sh's postprocess is the ENV shim only,
and Makefile.wasm links every app JSPI with the scheduler shim as a tracked
prerequisite. pcbjam_async_policy.h keys on __EMSCRIPTEN__.

jspi-scheduler.js: wxWasmMainLoopPump dropped from the wrap census (the
export died with the D5 detach); inert [TRACE] instrumentation removed.

CI: wasm-build.yml rewritten for the single-cache pipeline (one output cache
keyed on compile inputs; post-processed bytes cached after the shim);
opt_level input removed from both callers. wasm-cache-hash.mjs inputs now
cover patch-env-shim.mjs + jspi-scheduler.js + jspi-exports.txt.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NDeBaKKhQztd8KiVtHuyXr
This commit is contained in:
Viktor Vaczi 2026-08-13 08:39:12 +02:00
commit e14faeca8b
36 changed files with 170 additions and 3348 deletions

View file

@ -3,21 +3,17 @@
* exports (the doc-18 "PARKER" class: kicadOpenFile / kicadOpenFiles /
* kicadLibsReload, whose bodies park on wx wait tokens mid-load).
*
* JSPI backend: they MUST be registered emscripten::async() so embind wraps
* the invoker in WebAssembly.promising — the call returns a real Promise and
* the suspension is legal. Without it the first park throws SuspendError
* ("trying to suspend without WebAssembly.promising").
*
* Asyncify backend: no policy — the legacy contract stands (placeholder
* return, callers gate on kicadOpenFileBusy; the scheduler shim owns the
* await surface).
* They MUST be registered emscripten::async() so embind wraps the invoker in
* WebAssembly.promising — the call returns a real Promise and the suspension
* is legal. Without it the first park throws SuspendError ("trying to
* suspend without WebAssembly.promising").
*
* Usage (note the macro carries its own leading comma):
* function( "kicadOpenFile", &kicadOpenFile PCBJAM_PARKER_POLICY );
*/
#pragma once
#ifdef PCBJAM_JSPI
#ifdef __EMSCRIPTEN__
#define PCBJAM_PARKER_POLICY , emscripten::async()
#else
#define PCBJAM_PARKER_POLICY

View file

@ -1,129 +0,0 @@
/*
* Main-thread sleep as a CONTEXT PARK (docs/features/async/22, Phase B).
*
* THE PROBLEM THIS SOLVES. `nanosleep` on the main thread yields via Asyncify
* (see nanosleep_yield.c): it parks THE STACK IT STANDS ON. Doc 21 filed that
* as K7, the "anywhere" class, and its worst caller is a loop inside a tool
* body — TOOL_MANAGER::RunSynchronousAction spins
*
* while( synchronousControl == STS_RUNNING ) { wxYield(); wxMilliSleep(1); }
*
* (kicad/common/tool/tool_manager.cpp:370-371). Every canvas edit/draw/move
* action goes through it. An in-place park there means a tool stack sits
* mid-Asyncify-suspension while a nested wxYield() dispatch runs on top of it,
* and once the scheduler owns dispatch (Phase D) a star transfer aimed at that
* stack rewinds a capture that is still in flight: `index out of bounds` in
* doRewind — the blue screen, measured on four canvas-tool specs 2026-08-07.
*
* THE FIX. When the sleeping frame stands on a scheduler context that OWNS
* that stack, the wait becomes what every other migrated wait already is: arm
* a timed wake, YIELD THE CONTEXT, and let the scheduler resume it. Nothing
* is suspended in place, so there is no in-flight capture for a transfer to
* land on, and the caller's `for(;;)`-shaped poll keeps its exact semantics —
* it just waits by yielding instead of by suspending.
*
* WHY HERE AND NOT IN KiCad. The loop is upstream KiCad code, and CLAUDE.md
* asks the fork to stay close to upstream. Routing this through the sleep
* primitive keeps KiCad and the wx core untouched AND fixes the whole K7 class
* at once (every main-thread sleep_for/wxMilliSleep reached on a context), not
* just the one caller that happened to be measured.
*
* WHY THE POLL DOESN'T NEED A SIGNAL. The waited-for state (an atomic set by a
* later dispatch) has no wake source of its own, so this keeps polling — the
* caller's contract. What changes is only which stack the wait suspends. The
* dispatch that eventually flips the atomic runs on a DIFFERENT context: the
* tick reuses an idle dispatch context or makes one when all are parked
* deeper (the idle-reuse set), which is exactly why that change had to land
* before this one.
*/
#include <wx/wasm/private/sched_context.h>
#include <emscripten/emscripten.h>
#include <cstdint>
// The scheduler mailbox (wx/wasm/private/mailbox.h). A timer message is the
// wake source: it is delivered from a fresh JS task on the main stack, which
// is where a resume is allowed to happen.
extern "C" void wxWasmMailboxEnqueueAfter( void ( *aFn )( void* ), void* aArg, int aMillisecs );
// Does some wx pump already own this context's wake (the main loop's rAF, a
// dispatch context's tick)? Parking such a context here would give it TWO
// owners, and the second wake resumes a capture the first already consumed —
// measured 2026-08-07 as a doRewind trap through wxWasmArmFrameWake. Those
// contexts keep the in-place yield; the tool coroutines this exists for have
// no other wake source, which is precisely why their wait must park.
extern "C" int wxWasmContextWakeIsPumpOwned( unsigned aId );
namespace
{
void wake_sleeper( void* aArg )
{
const pcbjam_sched::ContextId id =
static_cast<pcbjam_sched::ContextId>( reinterpret_cast<uintptr_t>( aArg ) );
// mark_ready never resumes inline (doc 13 §1.4). WHO performs the entry
// depends on where this delivery landed:
if( !pcbjam_sched::mark_ready( id, 0 ) )
return;
if( pcbjam_sched::current() == 0 )
{
// On the scheduler stack: drain here.
pcbjam_sched::drain_all();
return;
}
// Delivered ON a context — the mailbox tick itself now runs on a dispatch
// context (doc 22 §10). drain() would refuse re-entry, and it should: the
// outer drain_all that entered this context keeps pumping once it parks,
// and picks up the context we just marked ready. Arm a pump anyway so a
// delivery that reached here by some other route cannot strand it.
EM_ASM( {
setTimeout( function() {
if( Module["_wxWasmSchedPump"] ) Module["_wxWasmSchedPump"]();
}, 0 );
} );
}
} // namespace
extern "C" {
/**
* Park the running context for aMillisecs instead of suspending this stack.
*
* Returns 1 if the wait was taken as a context park, 0 if the caller must fall
* back to the in-place Asyncify yield — which is the right answer whenever no
* context owns this stack: the main loop itself, a bridge entered before the
* scheduler exists, or a libcontext fiber swapped in above a context (yielding
* there would save the WRONG stack — doc 22 §7 rule 4, enforced by
* can_yield_here()).
*/
int pcbjam_context_sleep_ms( double aMillisecs )
{
const pcbjam_sched::ContextId self = pcbjam_sched::current();
if( !self || !pcbjam_sched::can_yield_here() )
return 0;
if( wxWasmContextWakeIsPumpOwned( self ) )
return 0;
// Round up: a 0 ms mailbox delay would re-enter this poll in the same
// macrotask chain and spin the CPU exactly as the sleep exists to avoid.
int delay = static_cast<int>( aMillisecs );
if( delay < 1 )
delay = 1;
wxWasmMailboxEnqueueAfter( &wake_sleeper,
reinterpret_cast<void*>( static_cast<uintptr_t>( self ) ),
delay );
pcbjam_sched::yield_park( "main-thread-sleep" );
return 1;
}
} // extern "C"

View file

@ -1,34 +0,0 @@
#!/bin/bash
# Stub wasm-emscripten-finalize that just copies input to output
# The real finalize runs on the host where more RAM is available
# Handle --version query
if [[ "$1" == "--version" ]]; then
echo "wasm-emscripten-finalize version 121"
exit 0
fi
# Parse arguments to find input/output files
# wasm-emscripten-finalize <input.wasm> -o <output.wasm> [options]
INPUT=""
OUTPUT=""
PREV_ARG=""
for arg in "$@"; do
if [ "$PREV_ARG" = "-o" ]; then
OUTPUT="$arg"
elif [[ "$arg" != -* ]] && [[ "$arg" == *.wasm ]]; then
INPUT="$arg"
fi
PREV_ARG="$arg"
done
# Copy input to output (no transformation)
if [ -n "$INPUT" ] && [ -n "$OUTPUT" ]; then
cp "$INPUT" "$OUTPUT"
elif [ -n "$INPUT" ]; then
# In-place mode: nothing to do
:
fi
exit 0

View file

@ -1,32 +0,0 @@
#!/bin/bash
# Stub wasm-opt that does nothing
# This allows Emscripten to generate Asyncify JS runtime without running the actual transformation
# The real wasm-opt --asyncify is run on the host where more RAM is available
# Handle --version query from Emscripten
if [[ "$1" == "--version" ]]; then
echo "wasm-opt version 121 (version_121)"
exit 0
fi
# Find the output file argument (-o)
OUTPUT=""
INPUT=""
PREV_ARG=""
for arg in "$@"; do
if [ "$PREV_ARG" = "-o" ]; then
OUTPUT="$arg"
elif [[ "$arg" != -* ]] && [ -f "$arg" ]; then
INPUT="$arg"
fi
PREV_ARG="$arg"
done
# If we have both input and output, copy input to output
if [ -n "$INPUT" ] && [ -n "$OUTPUT" ] && [ "$INPUT" != "$OUTPUT" ]; then
cp "$INPUT" "$OUTPUT"
fi
# Exit successfully so Emscripten thinks wasm-opt ran
exit 0