pcbjam/wasm/shims/context_sleep.cpp

129 lines
5.4 KiB
C++
Raw Normal View History

Phase B: main-thread sleep parks its context; the real D blocker is DOM entries wasm/shims/context_sleep.cpp: a main-thread nanosleep whose frame stands on a scheduler context that OWNS the stack arms a mailbox wake and yield_parks that context instead of suspending the stack in place. It lives in the sleep primitive rather than in tool_manager.cpp on purpose - KiCad and the wx core stay untouched (CLAUDE.md's fork rule) and the whole K7 class moves at once, not just TOOL_MANAGER::RunSynchronousAction's spin loop. MEASURED AT D-ON, and it is NOT what unblocks Phase D. The four canvas-tool specs still fail, but the trace now names a different cause: the fatal swap is old=<libcontext ROOT> new=<tool coroutine> with mouseEventHandlerFunc above it - a DOM mouse handler entering wasm DIRECTLY on the main stack, bypassing the tick. So one coroutine is entered two ways: by the tick through the dispatch context as a STAR TRANSFER, and by DOM handlers as a DIRECT SYMMETRIC SWAP. A capture written by one path cannot be rewound by the other -> index out of bounds in doRewind. That is section 7 rule 5 (partial migration is worse than none) in its purest measured form, and it is why the harness stays green: its coroutines are only ever entered from one place. So the next increment is the DOM event entries (mouse/key/wheel/resize must hand their events to the dispatch context as the tick does), not another park site. It subsumes the one-root work too: with no dispatch on the main stack, resolve_root_identity() always answers "the running context". Landing state: STAR_DISPATCH=0, kicad 139 passed / 1 (pre-existing occ-probe) = baseline, with the sleep shim in and inert. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LBjomQfKyRa3jBdeAKpmTw
2026-08-07 20:48:35 +02:00
/*
* 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>
docs 22 + wx bump: DOM entries on the dispatch context; canvas tools green at D-on The increment doc 22 ordered last round. Every entry that can reach a tool coroutine - the four DOM callbacks and the mailbox tick - now goes through the scheduler, so a coroutine is never entered by a star transfer from one path and a direct symmetric swap from another. At D-on all four canvas-tool specs are GREEN and the KiCad suite is 136/3 (was 135/5 before the sleep work, with the tools red throughout). context_sleep's wake learned the mirror lesson: now that the mailbox runs ON a context, it must NOT call drain_all from there (drain refuses re-entry, and should) - it marks ready and lets the outer drain_all perform the entry, with an armed pump as a backstop. Recorded honestly, not papered over: two of the three remaining D-on failures are the timer-park and quasimodal-strand levers, each failing ONE assertion - "scheduler shim observed the concurrent-park window", expected >0, got 0 - while fired/done/parked/errors all pass. That counter needs TWO concurrent in-place Asyncify parks, and the lever stages "timer park x MAIN-LOOP YIELD PARK"; D5 removed the main loop's Asyncify park, so the overlap cannot occur. Re-pinning those levers to the post-migration invariant is a Phase F decision alongside fiber-resume-park's red->green flip, NOT an assert to relax now. Landing state: STAR_DISPATCH=0, kicad 139 passed / 1 (pre-existing occ-probe). Next: Phase E - the K1-K7 bridges are the only in-place parks left under a context, and are exactly what the current()!=0 fallback still tolerates. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LBjomQfKyRa3jBdeAKpmTw
2026-08-07 22:33:41 +02:00
#include <emscripten/emscripten.h>
Phase B: main-thread sleep parks its context; the real D blocker is DOM entries wasm/shims/context_sleep.cpp: a main-thread nanosleep whose frame stands on a scheduler context that OWNS the stack arms a mailbox wake and yield_parks that context instead of suspending the stack in place. It lives in the sleep primitive rather than in tool_manager.cpp on purpose - KiCad and the wx core stay untouched (CLAUDE.md's fork rule) and the whole K7 class moves at once, not just TOOL_MANAGER::RunSynchronousAction's spin loop. MEASURED AT D-ON, and it is NOT what unblocks Phase D. The four canvas-tool specs still fail, but the trace now names a different cause: the fatal swap is old=<libcontext ROOT> new=<tool coroutine> with mouseEventHandlerFunc above it - a DOM mouse handler entering wasm DIRECTLY on the main stack, bypassing the tick. So one coroutine is entered two ways: by the tick through the dispatch context as a STAR TRANSFER, and by DOM handlers as a DIRECT SYMMETRIC SWAP. A capture written by one path cannot be rewound by the other -> index out of bounds in doRewind. That is section 7 rule 5 (partial migration is worse than none) in its purest measured form, and it is why the harness stays green: its coroutines are only ever entered from one place. So the next increment is the DOM event entries (mouse/key/wheel/resize must hand their events to the dispatch context as the tick does), not another park site. It subsumes the one-root work too: with no dispatch on the main stack, resolve_root_identity() always answers "the running context". Landing state: STAR_DISPATCH=0, kicad 139 passed / 1 (pre-existing occ-probe) = baseline, with the sleep shim in and inert. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LBjomQfKyRa3jBdeAKpmTw
2026-08-07 20:48:35 +02:00
#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 ) );
docs 22 + wx bump: DOM entries on the dispatch context; canvas tools green at D-on The increment doc 22 ordered last round. Every entry that can reach a tool coroutine - the four DOM callbacks and the mailbox tick - now goes through the scheduler, so a coroutine is never entered by a star transfer from one path and a direct symmetric swap from another. At D-on all four canvas-tool specs are GREEN and the KiCad suite is 136/3 (was 135/5 before the sleep work, with the tools red throughout). context_sleep's wake learned the mirror lesson: now that the mailbox runs ON a context, it must NOT call drain_all from there (drain refuses re-entry, and should) - it marks ready and lets the outer drain_all perform the entry, with an armed pump as a backstop. Recorded honestly, not papered over: two of the three remaining D-on failures are the timer-park and quasimodal-strand levers, each failing ONE assertion - "scheduler shim observed the concurrent-park window", expected >0, got 0 - while fired/done/parked/errors all pass. That counter needs TWO concurrent in-place Asyncify parks, and the lever stages "timer park x MAIN-LOOP YIELD PARK"; D5 removed the main loop's Asyncify park, so the overlap cannot occur. Re-pinning those levers to the post-migration invariant is a Phase F decision alongside fiber-resume-park's red->green flip, NOT an assert to relax now. Landing state: STAR_DISPATCH=0, kicad 139 passed / 1 (pre-existing occ-probe). Next: Phase E - the K1-K7 bridges are the only in-place parks left under a context, and are exactly what the current()!=0 fallback still tolerates. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LBjomQfKyRa3jBdeAKpmTw
2026-08-07 22:33:41 +02:00
// 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.
Phase B: main-thread sleep parks its context; the real D blocker is DOM entries wasm/shims/context_sleep.cpp: a main-thread nanosleep whose frame stands on a scheduler context that OWNS the stack arms a mailbox wake and yield_parks that context instead of suspending the stack in place. It lives in the sleep primitive rather than in tool_manager.cpp on purpose - KiCad and the wx core stay untouched (CLAUDE.md's fork rule) and the whole K7 class moves at once, not just TOOL_MANAGER::RunSynchronousAction's spin loop. MEASURED AT D-ON, and it is NOT what unblocks Phase D. The four canvas-tool specs still fail, but the trace now names a different cause: the fatal swap is old=<libcontext ROOT> new=<tool coroutine> with mouseEventHandlerFunc above it - a DOM mouse handler entering wasm DIRECTLY on the main stack, bypassing the tick. So one coroutine is entered two ways: by the tick through the dispatch context as a STAR TRANSFER, and by DOM handlers as a DIRECT SYMMETRIC SWAP. A capture written by one path cannot be rewound by the other -> index out of bounds in doRewind. That is section 7 rule 5 (partial migration is worse than none) in its purest measured form, and it is why the harness stays green: its coroutines are only ever entered from one place. So the next increment is the DOM event entries (mouse/key/wheel/resize must hand their events to the dispatch context as the tick does), not another park site. It subsumes the one-root work too: with no dispatch on the main stack, resolve_root_identity() always answers "the running context". Landing state: STAR_DISPATCH=0, kicad 139 passed / 1 (pre-existing occ-probe) = baseline, with the sleep shim in and inert. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LBjomQfKyRa3jBdeAKpmTw
2026-08-07 20:48:35 +02:00
pcbjam_sched::drain_all();
docs 22 + wx bump: DOM entries on the dispatch context; canvas tools green at D-on The increment doc 22 ordered last round. Every entry that can reach a tool coroutine - the four DOM callbacks and the mailbox tick - now goes through the scheduler, so a coroutine is never entered by a star transfer from one path and a direct symmetric swap from another. At D-on all four canvas-tool specs are GREEN and the KiCad suite is 136/3 (was 135/5 before the sleep work, with the tools red throughout). context_sleep's wake learned the mirror lesson: now that the mailbox runs ON a context, it must NOT call drain_all from there (drain refuses re-entry, and should) - it marks ready and lets the outer drain_all perform the entry, with an armed pump as a backstop. Recorded honestly, not papered over: two of the three remaining D-on failures are the timer-park and quasimodal-strand levers, each failing ONE assertion - "scheduler shim observed the concurrent-park window", expected >0, got 0 - while fired/done/parked/errors all pass. That counter needs TWO concurrent in-place Asyncify parks, and the lever stages "timer park x MAIN-LOOP YIELD PARK"; D5 removed the main loop's Asyncify park, so the overlap cannot occur. Re-pinning those levers to the post-migration invariant is a Phase F decision alongside fiber-resume-park's red->green flip, NOT an assert to relax now. Landing state: STAR_DISPATCH=0, kicad 139 passed / 1 (pre-existing occ-probe). Next: Phase E - the K1-K7 bridges are the only in-place parks left under a context, and are exactly what the current()!=0 fallback still tolerates. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LBjomQfKyRa3jBdeAKpmTw
2026-08-07 22:33:41 +02:00
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 );
} );
Phase B: main-thread sleep parks its context; the real D blocker is DOM entries wasm/shims/context_sleep.cpp: a main-thread nanosleep whose frame stands on a scheduler context that OWNS the stack arms a mailbox wake and yield_parks that context instead of suspending the stack in place. It lives in the sleep primitive rather than in tool_manager.cpp on purpose - KiCad and the wx core stay untouched (CLAUDE.md's fork rule) and the whole K7 class moves at once, not just TOOL_MANAGER::RunSynchronousAction's spin loop. MEASURED AT D-ON, and it is NOT what unblocks Phase D. The four canvas-tool specs still fail, but the trace now names a different cause: the fatal swap is old=<libcontext ROOT> new=<tool coroutine> with mouseEventHandlerFunc above it - a DOM mouse handler entering wasm DIRECTLY on the main stack, bypassing the tick. So one coroutine is entered two ways: by the tick through the dispatch context as a STAR TRANSFER, and by DOM handlers as a DIRECT SYMMETRIC SWAP. A capture written by one path cannot be rewound by the other -> index out of bounds in doRewind. That is section 7 rule 5 (partial migration is worse than none) in its purest measured form, and it is why the harness stays green: its coroutines are only ever entered from one place. So the next increment is the DOM event entries (mouse/key/wheel/resize must hand their events to the dispatch context as the tick does), not another park site. It subsumes the one-root work too: with no dispatch on the main stack, resolve_root_identity() always answers "the running context". Landing state: STAR_DISPATCH=0, kicad 139 passed / 1 (pre-existing occ-probe) = baseline, with the sleep shim in and inert. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LBjomQfKyRa3jBdeAKpmTw
2026-08-07 20:48:35 +02:00
}
} // 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"