Skip to content

feat(wasm): coordinate epoch deadlines and cancellation through the caller runtime #43

Closed

Description

@zackees

Parent: #27. Depends on #41 and #42.

Scope

Enable Wasmtime 45 epoch interruption and add one compiler/Engine-global epoch clock with logical-execution-scoped registrations. Epoch is global to an Engine; it is not independently advanceable per sketch. Each root generation owns a bounded semantic registration containing its cancellation token, absolute wall-clock deadline, terminal winner, and root/child Store registrations.

The clock runs only through the caller-provided kernal_api::async_engine::RuntimeHandle. It never constructs/discovers another Tokio runtime or owns a Store. At a bounded cadence it marks expired/cancelled logical executions and calls Engine::increment_epoch() once. Every active root/child Store checks its own generation-scoped state in a Wasmtime epoch callback: unrelated executions continue for one tick; only the execution whose terminal cause won is interrupted.

The Wasmtime calls remain synchronous inside a native blocking task launched through that same RuntimeHandle; the facade execution entrypoint is async so a current-thread runtime can drive the epoch clock while Wasm runs outside its executor thread. The first implementation slice adds RuntimeHandle::launch_blocking as a facade-owned method; do not use the ambient global launch_blocking helper. The ticker task is always stopped and awaited. The blocking Wasm task is awaited after cooperative completion/fuel/epoch interruption. Aborting its task handle is never claimed to stop a native closure blocked in atomic.wait or a host call; those paths are characterized as ContainmentRequired and termination/reaping belongs to #28.

Facade contract

  • Add facade-owned SketchEpochLimits to SketchExecutionLimits: finite nonzero wall-clock deadline, finite nonzero bounded tick interval, and bounded active epoch registrations.
  • Accept the existing facade-owned CancellationToken on the controlled execution path. Cancellation is observed no later than the next epoch tick for running Wasm; it is not immediate force termination.
  • Return facade-owned DeadlineExceeded and Cancelled root/child outcomes, plus bounded scheduling observations. No Engine epoch, Store callback, Tokio task, or backend trap is public.
  • Preserve one convenient non-cancelled async execution path by supplying a never-cancelled token internally. Remove or privatize any public synchronous path that could bypass the epoch clock; private synchronous execution remains an implementation detail of the blocking task.

Wasmtime 45 implementation contract

  • Construct the private engine with Config::epoch_interruption(true).
  • Before instantiation (therefore covering the module start section), configure every root and child Store with set_epoch_deadline(1) and epoch_deadline_callback.
  • The callback reads only its Store-owned generation registration. It returns UpdateDeadline::Continue(1) while active and UpdateDeadline::Interrupt after that logical execution's cancellation/deadline terminal cause wins.
  • The compiler-global clock holds no Store/Instance/Caller/memory reference. It keeps only bounded weak logical-execution registrations plus the private Engine clone.
  • Fix runtime identity before enforcing it: derive a facade-private stable identity from the backend handle's runtime ID so Runtime::handle() clones and repeated RuntimeHandle::current() calls on the same live runtime compare equal. Remove the current fresh-Arc<()>-per-call behavior. The identity remains backend-private. The first supplied runtime establishes the clock identity; a genuinely different live runtime is rejected semantically rather than merely counted.

Wasmtime documents that Store objects belong to exactly one Store and wrong-Store use is a programmer error: https://github.com/bytecodealliance/wasmtime/blob/v45.0.0/crates/wasmtime/src/runtime/store.rs#L187-L197

Wasmtime documents relative epoch deadlines and the callback continuation/interrupt mechanism: https://github.com/bytecodealliance/wasmtime/blob/v45.0.0/crates/wasmtime/src/runtime/store.rs#L1050-L1142

Identity and lifecycle invariants

  • One Engine-global clock; generation-safe logical-sketch registrations; distinct root/child Store identities. An Engine tick may visit multiple Stores but must not cancel an unrelated logical execution.
  • Acquire a child epoch registration before guest-visible TID assignment/native spawn/Store creation; roll it back with feat(wasm): enforce bounded per-session fuel and execution permits #42 fuel/thread reservations on every rejection/failure.
  • One serialized terminal-winner state machine shared by the ticker and Store callbacks: Pending -> Cancelled | DeadlineExceeded | Completed. On each tick the ticker checks cancellation before deadline and commits at most one winner. Store callbacks only read the stored winner; root and child callbacks cannot independently choose different causes. An already-recorded terminal state is immutable. Fuel remains OutOfFuel when it is the actual trap.
  • Root outcome remains primary over ordered child outcomes and validation-report diagnostics.
  • Cooperative normal completion, proc-exit, trap, fuel exhaustion, epoch-check interruption, failed instantiate/start, panic, and cooperative cancellation remove registrations exactly once and leave counters at zero. Blocked atomic/host waits make no zero-cleanup claim until feat(wasm): add killable threaded-sketch worker containment #28 owns their process boundary.
  • No Store, Instance, Caller, guest pointer/reference, shared-memory borrow, mutex/DashMap guard, or resource borrow crosses runtime scheduling/cancellation handoff.
  • Cancellation/epoch interruption applies only at running Wasm epoch checks. atomic.wait, host-blocked calls, and hostile teardown remain containment-required by feat(wasm): add killable threaded-sketch worker containment #28.

RED -> GREEN

  • RED: root/child Stores have no finite epoch deadline, no caller-runtime clock, no logical cancellation token, and no typed interruption observations.
  • GREEN: a looping module start and looping root compute are interrupted after a finite configured deadline and mapped to typed DeadlineExceeded with all fuel/epoch/Store/Instance/root counters zero.
  • GREEN: child looping compute produces the exact ordered child DeadlineExceeded outcome and drains every registration/permit.
  • GREEN: caller cancellation closes new spawns/work and interrupts root plus children by the next clock tick; it uses exactly the supplied RuntimeHandle and creates no second runtime.
  • GREEN: two concurrent logical executions on the same Engine prove cancelling one does not interrupt the other; repeated RuntimeHandle::current() and cloned owned-runtime handles share the correct stable identity, while a genuinely foreign live runtime is rejected.
  • GREEN: cancellation/deadline/fuel races produce one deterministic semantic winner and do not leak a Wasmtime trap.
  • GREEN: normal, proc-exit, trap, fuel, failed-instantiation, and close paths return active scheduling registrations to zero.
  • GREEN: atomic-wait and host-blocked fixtures run only inside a killable test subprocess/harness, are explicitly classified ContainmentRequired for feat(wasm): add killable threaded-sketch worker containment #28, and are never reported as successfully interrupted or cleaned up by aborting a blocking-task handle. They must not strand an in-process test thread or hang the suite.
  • GREEN: current-thread and multi-thread caller runtimes both drive the async facade path without blocking their executor/event loop.
  • GREEN: focused Linux/macOS/Windows x86-64/ARM64 coverage and default-feature isolation remain intact.

Non-goals

No async Wasmtime Store/fiber execution, generated guest ABI/resources, worker process, forced native-thread termination, broad WASI, or claim that epoch can wake atomic.wait/host-blocked calls.

Closure

Deliver the private clock/registration state, async facade execution/control path, semantic observations, focused Soldr tests, and platform evidence. #44 characterizes the exact fuel/epoch boundaries; #28 supplies killable containment for blocked waits.

Activity

  1. added
    enhancement
    on Aug 27, 2026
  2. zackees commented on Aug 27, 2026

    @zackees
    CollaboratorAuthor

    Triage correction: Wasmtime epoch is Engine-global, so the prior wording could not safely promise a logical-sketch-owned broker. The accepted design is one Engine-global clock with generation-scoped Store callbacks; each tick continues unrelated executions and interrupts only the cancelled/expired logical execution. The facade call becomes async and runs synchronous Wasmtime on the supplied RuntimeHandle blocking lane so current-thread runtimes can still drive the clock.

  3. zackees commented on Aug 27, 2026

    @zackees
    CollaboratorAuthor

    Design audit follow-up: the issue now requires fixing RuntimeHandle identity using the backend handle's stable live-runtime ID, adding the missing caller-handle launch_blocking lane, retaining/cleaning both tasks, and serializing Pending -> Cancelled|DeadlineExceeded|Completed once per logical execution. This resolves the audit's HIGH and two MEDIUM findings before implementation.

  4. zackees commented on Aug 27, 2026

    @zackees
    CollaboratorAuthor

    Containment correction: #43 now guarantees ticker cleanup and blocking-task join only for cooperative terminal paths. It explicitly rejects the false claim that aborting a spawn_blocking JoinHandle terminates atomic.wait/host-blocked native execution; those fixtures are isolated in a killable test harness and final reaping belongs to #28.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions