Cooperative cancellation of an in-progress compilation

Abierto
#15,466 1 comentario 0 reacciones 0 asignados Ver en GitHub

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

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 async embedders 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:

Shape of the prototype:

  • wasmtime::CompileCancel — a cloneable handle (an Arc<AtomicBool>) with cancel() and is_cancelled(); CodeBuilder::cancel_handle(&CompileCancel); a typed error wasmtime::CompileCancelled (error.is::<CompileCancelled>()), so that "cancelled" can never be mistaken for "this module does not compile". Module::new, Engine::precompile_module etc. pass no handle and are unchanged.
  • The flag is passed down by reference (no thread-local): Compiler::compile_function / append_code in wasmtime-environ, Context::compile_cancellable etc. in cranelift-codegen (the existing names call them with a never-set flag), regalloc2::run_with_ctx_cancellable and RegAllocError::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 one br_table with 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
  1. Is this something Wasmtime would want at all?
  2. 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.
  3. Where should it live: CodeBuilder only (as in the prototype), or also something for Module::new / the C API?
  4. 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.
  5. 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 Engine lose 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

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de bytecodealliance/wasmtime

Todos los issues de bytecodealliance/wasmtime

Issues similares

Más issues de Rust

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.