Cooperative cancellation of an in-progress compilation
Los mantenedores suelen responder en 1 día
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Aptitud para principiantes
- 25/100
- Tipo de issue
- Nueva funcionalidad
- Claridad
- Bien especificado
- Estado de actividad
- Activo
- Stack tecnológico
- rust, wasm
- Área
- backend, performance
Línea de trabajo
Read the proposed API and cancellation check locations in the issue, then review the linked Wasmtime/Cranelift prototype and its regalloc2 commit to understand the cross-project changes. The issue asks maintainers to decide whether cancellation is wanted and which API shape and coverage to use. Done means a direction is agreed; implementation scope depends on that decision.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Feature
A way for an embedder to cancel a module compilation that is in progress, from another thread: a handle given to CodeBuilder, which the compilation checks cooperatively, returning a typed "cancelled" error and leaving nothing behind.
Today a compilation, once started, runs to the end. The only ways to stop one are to abandon its thread (it keeps a core and its memory until it finishes) or to compile in a separate process and kill it.
Use cases
- Speculative compilation with a budget. A service that accepts modules from users compiles each one ahead of time, when it is submitted, to decide whether to accept it and to have the code ready. It wants to give that a wall-clock budget and refuse the submission when the budget runs out. Limits on the module (size, functions, locals) bound compile time only loosely, because the time depends on the shape of the code: a 280 KB module with one function of 2,047 locals and two
br_tables of 4,096 targets took over a minute before the recent regalloc2 fixes and still takes seconds and gigabytes after them. A deadline is the robust bound, and it needs a way to stop the work. - The module stops being wanted. The client that submitted it disconnects, a newer version of the same module arrives, the request that needed it is cancelled or times out. With
asyncembedders the natural expectation is that dropping the work stops the work. - Different patience in different places. The same module may be compiled where someone will wait as long as it takes (it has already been accepted) and where nobody should wait long (it is being tried out). The limit is the caller's, not the engine's, so it does not fit in
Config; it is a property of one compilation. - Shutdown and reconfiguration. A process that is asked to exit, or to drop an engine, while background compilations are running currently has to wait for them or leak the threads.
- Bounding memory indirectly. Compile memory grows with time for the pathological shapes; an embedder watching its own memory use can cancel a compilation that passes a threshold.
Epoch interruption and fuel give this for running wasm; there is no counterpart for compiling it. I understand compile-time resource use is deliberately outside the security policy; this is asked for as a resource-management tool for embedders, not as a security boundary.
A prototype, to make the discussion concrete
I have a working prototype and would be glad to turn it into PRs in whatever shape is preferred:
- wasmtime, cranelift: https://github.com/gofractally/wasmtime/tree/claude/compile-cancel-2 (the first and third commit)
- regalloc2: https://github.com/gofractally/regalloc2/commit/bfce51e3d3293eca7626b210e141c7e80d8c07ca
Shape of the prototype:
wasmtime::CompileCancel— a cloneable handle (anArc<AtomicBool>) withcancel()andis_cancelled();CodeBuilder::cancel_handle(&CompileCancel); a typed errorwasmtime::CompileCancelled(error.is::<CompileCancelled>()), so that "cancelled" can never be mistaken for "this module does not compile".Module::new,Engine::precompile_moduleetc. pass no handle and are unchanged.- The flag is passed down by reference (no thread-local):
Compiler::compile_function/append_codein wasmtime-environ,Context::compile_cancellableetc. in cranelift-codegen (the existing names call them with a never-set flag),regalloc2::run_with_ctx_cancellableandRegAllocError::Cancelled. - Checks are one relaxed atomic load: before each function and between compile phases in wasmtime; between the passes of
optimize, per block in lowering and emission in Cranelift; per block / vreg / bundle / spillset and per few thousand moves in regalloc2's loops; per 1,024 functions while linking. - Nothing partial is kept: function outputs are assembled only if every function returned
Ok; nothing is published to the engine, written to the module cache (the handle is not part of the cache key) or returned to the compiler-context pool from a cancelled compilation. A handle that is set after the artifact is complete has no effect. The same engine compiles the same module to the same bytes afterwards.
Measured (aarch64 macOS, release build):
- Cost when the handle is never set: not measurable. 450 real modules (531 MB of wasm), five interleaved rounds per variant: 247.7 CPU-s without the change, 247.8 with it and no handle, 247.4 with a never-set handle; rounds of one variant differ by up to 1 %. Serialized modules are byte-identical with and without a handle for these and for ~28,000 further compilations of generated modules (aarch64 and x86-64 targets).
- Latency from
cancel()to the compile call returning: median under 1 ms inside the register allocator's loops. Worst seen on a single function of 2,047 locals × 4,096 branch edges (8.4 million block-parameter moves, 2.3 s to compile): about 0.21 s. With many small functions on 8 threads: 6 ms median, 47 ms worst at 20,000 functions. - Longest stretches without a check at that extreme function, which I left alone because each needs a check in an inner loop or a restructured sort: the three large sorts in regalloc2 (
blockparam_ins,blockparam_outs, inserted moves; 120–220 ms), the egraph pass (130 ms), translating onebr_tablewith SSA construction (55 ms),remove_constant_phis(53 ms). All are linear in edges × locals.
Tests in the prototype: cancelled before start; a long register allocation interrupted part-way and the module compiling to the same bytes afterwards; many functions cancelled midway, serial and parallel; a never-set handle changes nothing; a cancelled compilation is not cached; in regalloc2, cancelling at every check site in turn and reusing the Ctx.
Questions
- Is this something Wasmtime would want at all?
- If so, which shape: a shared flag as above, a callback (
FnMut() -> bool, which would also allow fuel-like budgets or a deadline check without a second thread), or a deadline passed in directly? A flag is the cheapest to check in inner loops; a callback could be checked at the coarser sites only. - Where should it live:
CodeBuilderonly (as in the prototype), or also something forModule::new/ the C API? - For regalloc2: an extra entry point, or a field on
RegallocOptions? I can open the regalloc2 part as its own issue/PR once the direction is clear; it is independent of the Cranelift API but only useful with it. - Winch only checks between functions in the prototype; is finer-grained checking wanted there?
Alternatives
- Compile in a child process and kill it: works, but costs process start-up and transferring the artifact, and embedders that use the in-process module cache or share an
Enginelose that. - Abandon the thread: the work continues, holding a core and (for the shapes above) gigabytes, and several abandoned compilations accumulate.
- Stricter limits on what is accepted: helps, but bounds compile time only through a model of the compiler that has to be kept in step with it.
- Lenguaje dominante
- Rust
- Estrellas
- 18.9k
- Forks
- 2k
- Merge medio
- 1 d 6 h
- PR fusionados (30 d)
- 238
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de bytecodealliance/wasmtime
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
bytecodealliance/wasmtime#15536 ·
Los mantenedores suelen responder en 1 día
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
bytecodealliance/wasmtime#15455 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
wasi-preview1-component-adapter: fd_write does not invalidate cached InputStream, causing stale readsPosiblemente ocupada @dpfens la tomó hace 13 días. Abiertowasi
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
bytecodealliance/wasmtime#15296 ·
Los mantenedores suelen responder en 1 día
-
bug wasm-proposal:exceptions wasmtime:debugging
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
bytecodealliance/wasmtime#14102 ·
Los mantenedores suelen responder en 1 día
-
wasm-proposal:gc
Dificultad 2/5 1-3 horas Aptitud para principiantes 62/100
bytecodealliance/wasmtime#13808 · 2 comentarios ·
Los mantenedores suelen responder en 1 día
Todos los issues de bytecodealliance/wasmtime
Issues similares
-
Android: a long press's `contextmenu` event carries no point (`clientX` and `clientY` are 0)Abierto
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día
-
Test connection's password prompt says the password is never saved, also for a keychain profileAbiertobug
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
Los mantenedores suelen responder en 1 día
-
area: settings bug Haiku review: no-score ui
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
MMFoundation/WallpaperMachine#346 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
rubys/roundhouse#2473 ·
-
bug mod: quantum info
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Qiskit/qiskit#17699 · 2 comentarios ·
Los mantenedores suelen responder en 1 día