q2 preview: a re-execute still writing its capture to samod blocks runtime shutdown forever

Abierto
#1,341 0 comentarios 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
4/5
Tiempo estimado
1-2 días
Aptitud para principiantes
22/100
Tipo de issue
Error
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
rust
Área
devtools

Línea de trabajo

Start with crates/quarto-preview/src/re_execute.rs, where perform_re_execute runs on spawn_blocking and calls samod's Repo::create, then read the flaky test live_reexecute::auto_re_runs_after_a_stale_copy_was_served_at_startup in crates/quarto-preview/tests/integration/live_reexecute.rs. Reproduce with the diagnostic test from the issue, then move the samod write onto the runtime so shutdown drops it. Done when the hang no longer occurs and the tests wait for the worker and check the final sidecar.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug testing

A re-execute worker that is still writing its capture to samod when the tokio runtime shuts down never returns, and the runtime's shutdown waits for it forever. This is what hangs live_reexecute::auto_re_runs_after_a_stale_copy_was_served_at_startup on macOS until the job is cancelled, on main in https://github.com/quarto-dev/q2/actions/runs/45260078239/job/137992188063 and in https://github.com/quarto-dev/q2/actions/runs/45432297037/job/138580999778 (still SLOW after more than 18,000 s).

The worker runs perform_re_execute with pollster::block_on on a spawn_blocking thread:

https://github.com/quarto-dev/q2/blob/db699aedb701af9b7c60fb6a840ab0e2b9044af4/crates/quarto-preview/src/re_execute.rs#L282-L288

and stores the capture through samod's Repo::create:

https://github.com/quarto-dev/q2/blob/db699aedb701af9b7c60fb6a840ab0e2b9044af4/crates/quarto-preview/src/re_execute.rs#L405-L408

In samod 0.16, create waits on a oneshot whose sender is kept in the repo's own pending_commands. The io loop task resolves it once the document is persisted (source):

pub async fn create(&self, initial_content: Automerge) -> Result<DocHandle, Stopped> {
    let (tx, rx) = oneshot::channel();
    {
        let DispatchedCommand { command_id, event } =
            HubEvent::create_document(initial_content);
        let mut inner = self.inner.lock().unwrap();
        inner.handle_event(event);
        inner.pending_commands.insert(command_id, tx);
        drop(inner);
    }
    let inner = self.inner.clone();
    match rx.await {
        // ...
        Err(_) => Err(Stopped),
    }
}

When the runtime shuts down, the io loop task is dropped, but the sender is not: the worker's own context clone keeps the repo alive. rx.await never resolves, so the blocking thread never exits, and Runtime::drop waits on the blocking pool forever.

How the test gets there

The test returns as soon as the engine has run twice and the .quarto copy holds three:

https://github.com/quarto-dev/q2/blob/db699aedb701af9b7c60fb6a840ab0e2b9044af4/crates/quarto-preview/tests/integration/live_reexecute.rs#L673-L676

The engine stage writes that copy before the run publishes its capture, so the test often returns while the worker is still running. With temporary logging, 23 of 40 local runs on Windows returned with the worker still in flight, 21 of them before the sidecar was updated. The test still passed 40 of 40 times: samod's write usually completes about 1 ms before the shutdown drops the io loop. On macOS CI it lost that race.

I can reproduce the hang deterministically on Windows. A test that returns while the worker is held in the stub engine, with the gate opened 500 ms later from another thread, logs the start of the samod write and never its end. nextest has to kill it.

Experiment (not meant to land)
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn return_while_a_worker_runs() {
    let dir = tempfile::TempDir::with_prefix("q2-live-diag-").unwrap();
    let root = dir.path().canonicalize().unwrap();
    let doc = root.join("doc.qmd");
    std::fs::write(&doc, recording_doc("ok1")).unwrap();
    let probe = Probe::default();
    let reg = registry(&probe);
    let c = cfg(EnginePolicy::Auto, &root.join("cache"), vec![RecordSource::Engine]);
    let (ctx, _data) = hub_ctx(&root).await;
    capture_driver::record_eager_captures(ctx.clone(), plain_runtime(), Some(reg.clone()), &c)
        .await
        .unwrap();
    std::fs::write(&doc, recording_doc("BLOCK")).unwrap();
    capture_driver::recompute_staleness(ctx.clone(), plain_runtime(), "doc.qmd", Some(reg), &c)
        .await
        .unwrap();
    wait_for("the blocked run to start", 30, || runs(&probe) == 2).await;
    let gate = probe.gate.clone();
    std::thread::spawn(move || {
        std::thread::sleep(Duration::from_millis(500));
        gate.release();
    });
    std::mem::forget(dir);
}
worker: start
perform: compute_source_inputs done
test: body RETURNS
diag: releasing the gate (runtime is tearing down)
perform: engine run done (copy written)
perform: store_run done
perform: write_capture_doc_gated (samod create) BEGIN
        SLOW [> 30.000s] live_reexecute::zz_diag_return_while_a_worker_runs
        SLOW [> 60.000s] live_reexecute::zz_diag_return_while_a_worker_runs
 TERMINATING [> 90.000s] live_reexecute::zz_diag_return_while_a_worker_runs

In q2 preview

q2 preview drops its runtime after block_on(run(args)) returns:

https://github.com/quarto-dev/q2/blob/db699aedb701af9b7c60fb6a840ab0e2b9044af4/crates/quarto/src/commands/preview.rs#L209-L218

So I think a Ctrl-C during an auto re-execute could hang the exit the same way. I haven't verified this end to end.

Possible fix

We could run the worker as a tokio task and keep only the engine part (source inputs, engine run, cache store) on spawn_blocking. The samod write, the sidecar update and the end-of-run re-check would then run on the runtime, and a shutdown drops them instead of waiting on them. Separately, the tests could wait for the worker to finish and check the final sidecar state, not only the .quarto copy.

The tests were added in #1196. #1200 is an earlier samod lifecycle fix (flushing storage before dropping the hub context), for a different test. The Ubuntu timeout of the sibling test in the same file has a separate cause, filed as #1340.

Lenguaje dominante
Rust
Estrellas
316
Forks
23
Merge medio
11 h 49 min
PR fusionados (30 d)
245

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 quarto-dev/q2

Todos los issues de quarto-dev/q2

Issues similares

Más issues de Rust

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.