artifactize-core 0.33.0

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
//! Single-owner Verify engine daemon: owns scheduling, the global eval queue, cross-Run
//! deduplication, and SQLite state writes for one state directory.

mod client;
mod coordinator;
mod transport;

pub(crate) use client::{cancel_run, submit_run};
pub(crate) use coordinator::{Coordinator, EngineClaim, ExecutionLease};

use std::{path::Path, sync::Arc, time::Duration};

use tokio::task::JoinSet;
use tokio_util::sync::CancellationToken;

use crate::{
    platform, process,
    runs::{CancelAcknowledgement, Control, observe, worker},
    store::{self, Receipts},
    types::{FailureCode, RunId},
};

use transport::{
    ClientFrame, EngineEndpoint, ServerFrame, Stream, VERSION, read_frame, validate_peer,
    write_frame,
};

/// Brief drain window after the last active Run settles before stopping the idle engine:
/// keeps the engine warm across back-to-back submissions while exiting promptly when idle.
const IDLE_DRAIN: Duration = Duration::from_millis(150);
/// Bound one client's handshake so an abandoned connection cannot occupy an engine slot.
const HELLO_TIMEOUT: Duration = Duration::from_secs(5);
/// Bound reading one client RPC request frame after `Hello` so a hung client cannot wedge shutdown.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
/// Bound writing one server RPC reply frame so a stalled peer cannot hold client tasks open.
const WRITE_TIMEOUT: Duration = Duration::from_secs(10);
/// Cap simultaneous client IPC connections accepted by one Verify engine process.
const MAX_CLIENTS: usize = 64;
/// Short backoff after a transient `listener.accept()` error (e.g. temporary fd exhaustion).
const ACCEPT_ERROR_BACKOFF: Duration = Duration::from_millis(50);
/// Check periodically whether the state directory or `state.sqlite` was removed/replaced.
const STATE_CHECK: Duration = Duration::from_millis(500);

/// Run the single-owner Verify engine daemon for `state`. Exits `Ok(())` cleanly if another
/// engine already owns `state` or once all submitted Runs have settled and the engine drains.
pub async fn serve(state: &Path) -> Result<(), String> {
    serve_with_hook(state, None).await
}

/// Optional test hook invoked inside the engine right before executing a newly submitted Run
/// (allows deterministic admission-gate tests without shipping test logic in production CLI).
#[doc(hidden)]
pub type BeforeRunHook = Arc<
    dyn Fn(
            &Path,
            &RunId,
        )
            -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>> + Send>>
        + Send
        + Sync,
>;

/// How long a newly spawned Verify engine retries taking `engine.lock` when a previous
/// engine is mid-shutdown (unlinked its socket but still flushing its final WAL checkpoint).
const TAKEOVER_WAIT: Duration = Duration::from_secs(2);
/// Retry interval while waiting for a draining Verify engine to release `engine.lock`.
const TAKEOVER_POLL: Duration = Duration::from_millis(20);

fn state_identities(state: &Path) -> Option<(platform::FileIdentity, platform::FileIdentity)> {
    let dir = platform::open_directory(state).ok()?;
    let db = platform::open_regular(&state.join(store::DATABASE)).ok()?;
    Some((
        platform::file_identity(&dir).ok()?,
        platform::file_identity(&db).ok()?,
    ))
}

#[doc(hidden)]
pub async fn serve_with_hook(
    state: &Path,
    before_run: Option<BeforeRunHook>,
) -> Result<(), String> {
    let state = crate::workspace::canonical_target(&store::state_dir(Some(state))?)
        .map_err(|error| error.to_string())?;
    platform::create_private_dir_all(&state).map_err(|error| error.to_string())?;
    let endpoint = EngineEndpoint::new(&state).map_err(|error| error.to_string())?;
    let takeover_deadline = tokio::time::Instant::now() + TAKEOVER_WAIT;
    let _owner_lock = loop {
        if let Some(lock) = endpoint.take_owner().map_err(|error| error.to_string())? {
            break lock;
        }
        // If another Verify engine is already actively accepting connections, exit cleanly;
        // otherwise it may be mid-shutdown flushing its final checkpoint, so retry briefly.
        if endpoint.connect().await.is_ok() || tokio::time::Instant::now() >= takeover_deadline {
            return Ok(());
        }
        tokio::time::sleep(TAKEOVER_POLL).await;
    };
    let owner = process::child_identity(std::process::id()).map_err(|error| error.to_string())?;

    // Recover any Runs left open by a previously crashed engine before accepting new work.
    if platform::paths::target_is_file(&state.join(store::DATABASE)) {
        crate::runs::reconcile_open(&state).await;
    }

    let receipts = Receipts::open_state(&state).await?;
    let baseline_identities = state_identities(&state);
    let listener = endpoint.listen().map_err(|error| error.to_string())?;
    let coordinator = Coordinator::new(state.clone(), owner, receipts.clone());
    let shutdown = CancellationToken::new();

    let result = run_server(
        listener,
        endpoint,
        coordinator.clone(),
        baseline_identities,
        before_run,
        shutdown.clone(),
    )
    .await;

    // Best-effort clean WAL truncation on idle exit before closing SQLite handles.
    let _ = receipts.checkpoint_truncate().await;
    let closed = receipts.close().await;
    result.and(closed)
}

async fn run_server(
    mut listener: transport::Listener,
    endpoint: EngineEndpoint,
    coordinator: Arc<Coordinator>,
    baseline_identities: Option<(platform::FileIdentity, platform::FileIdentity)>,
    before_run: Option<BeforeRunHook>,
    shutdown: CancellationToken,
) -> Result<(), String> {
    let mut clients = JoinSet::new();
    let mut run_tasks = JoinSet::new();
    let (run_tx, mut run_rx) = tokio::sync::mpsc::unbounded_channel::<SpawnedRun>();
    let client_shutdown = CancellationToken::new();
    let mut state_check = tokio::time::interval(STATE_CHECK);
    state_check.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
    state_check.tick().await;

    let mut idle_since: Option<tokio::time::Instant> = Some(tokio::time::Instant::now());

    loop {
        // Register the activity waiter BEFORE checking `is_idle()` so a concurrent wakeup
        // between `is_idle()` and `select!` is never lost.
        let activity = coordinator.activity_notified();
        tokio::pin!(activity);
        activity.as_mut().enable();

        if coordinator.is_idle() {
            if idle_since.is_none() {
                idle_since = Some(tokio::time::Instant::now());
            }
        } else {
            idle_since = None;
        }
        let idle_deadline = idle_since.map(|since| since + IDLE_DRAIN);
        if let Some(deadline) = idle_deadline
            && tokio::time::Instant::now() >= deadline
            && coordinator.try_begin_shutdown()
        {
            break;
        }

        tokio::select! {
            _ = shutdown.cancelled() => {
                coordinator.begin_draining();
                break;
            }
            Some(spawned) = run_rx.recv() => {
                idle_since = None;
                let coord = coordinator.clone();
                let hook = before_run.clone();
                run_tasks.spawn(async move {
                    execute_managed_run(coord, spawned, hook).await;
                });
            }
            Some(joined) = run_tasks.join_next(), if !run_tasks.is_empty() => {
                let _ = crate::task::joined(joined);
            }
            Some(joined) = clients.join_next(), if !clients.is_empty() => {
                let _ = crate::task::joined(joined);
            }
            accepted = listener.accept(), if clients.len() < MAX_CLIENTS => {
                match accepted {
                    Ok(stream) => {
                        let coord = coordinator.clone();
                        let id = endpoint.identity.clone();
                        let tx = run_tx.clone();
                        let stop = shutdown.clone();
                        let client_stop = client_shutdown.clone();
                        clients.spawn(async move {
                            let _ = handle_client(stream, id, coord, tx, stop, client_stop).await;
                        });
                    }
                    Err(error) => {
                        use std::io::Write;
                        let _ = writeln!(
                            std::io::stderr().lock(),
                            "Verify engine transient accept error: {error}"
                        );
                        tokio::time::sleep(ACCEPT_ERROR_BACKOFF).await;
                    }
                }
            }
            _ = &mut activity => {}
            _ = tokio::time::sleep_until(idle_deadline.unwrap_or_else(tokio::time::Instant::now)),
                if idle_deadline.is_some() => {}
            _ = state_check.tick() => {
                let missing_or_replaced = !platform::paths::target_is_dir(coordinator.state_dir())
                    || baseline_identities
                        .is_some_and(|expected| state_identities(coordinator.state_dir()) != Some(expected));
                if missing_or_replaced {
                    coordinator.begin_draining();
                    coordinator.cancel_all_active();
                    break;
                }
            }
        }
    }

    drop(listener);
    // Cancel any idle post-Hello clients that have not started an RPC so shutdown cannot
    // wedge while holding `engine.lock`, while allowing in-flight submissions to finish.
    client_shutdown.cancel();
    while let Some(joined) = clients.join_next().await {
        let _ = crate::task::joined(joined);
    }
    // Drain any Run queued just before shutdown began so an accepted Run is never dropped.
    drop(run_tx);
    run_rx.close();
    while let Some(spawned) = run_rx.recv().await {
        let coord = coordinator.clone();
        let hook = before_run.clone();
        run_tasks.spawn(async move {
            execute_managed_run(coord, spawned, hook).await;
        });
    }
    while let Some(joined) = run_tasks.join_next().await {
        let _ = crate::task::joined(joined);
    }
    Ok(())
}

struct SpawnedRun {
    run: store::Run,
    caller_env: Arc<std::collections::BTreeMap<std::ffi::OsString, std::ffi::OsString>>,
    cancellation: CancellationToken,
}

async fn write_bounded(stream: &mut Stream, frame: &ServerFrame) -> std::io::Result<()> {
    tokio::time::timeout(WRITE_TIMEOUT, write_frame(stream, frame))
        .await
        .map_err(|_| std::io::ErrorKind::TimedOut)?
}

async fn handle_client(
    mut stream: Stream,
    expected_identity: crate::config::EndpointId,
    coordinator: Arc<Coordinator>,
    run_tx: tokio::sync::mpsc::UnboundedSender<SpawnedRun>,
    shutdown: CancellationToken,
    client_shutdown: CancellationToken,
) -> std::io::Result<()> {
    validate_peer(&stream)?;
    let hello: ClientFrame = tokio::select! {
        _ = client_shutdown.cancelled() => return Ok(()),
        result = tokio::time::timeout(HELLO_TIMEOUT, read_frame(&mut stream)) => result??,
    };
    let ClientFrame::Hello { version, identity } = hello else {
        return Err(std::io::ErrorKind::InvalidData.into());
    };
    if identity != expected_identity {
        return Err(std::io::ErrorKind::PermissionDenied.into());
    }
    if version != VERSION {
        write_bounded(
            &mut stream,
            &ServerFrame::Incompatible {
                server_version: VERSION,
            },
        )
        .await?;
        // Keep the connection open briefly so a newer client can request an idle shutdown
        // on the same stream during a binary upgrade.
        let follow = tokio::select! {
            _ = client_shutdown.cancelled() => return Ok(()),
            result = tokio::time::timeout(HELLO_TIMEOUT, read_frame::<_, ClientFrame>(&mut stream)) => result,
        };
        if let Ok(Ok(ClientFrame::ShutdownIfIdle)) = follow {
            let reply = if coordinator.try_begin_shutdown() {
                shutdown.cancel();
                ServerFrame::Ack
            } else {
                ServerFrame::Busy
            };
            let _ = write_bounded(&mut stream, &reply).await;
        }
        return Ok(());
    }
    if coordinator.is_shutting_down() {
        write_bounded(&mut stream, &ServerFrame::ShuttingDown).await?;
        return Ok(());
    }
    write_bounded(
        &mut stream,
        &ServerFrame::Welcome {
            version: VERSION,
            owner: coordinator.owner(),
        },
    )
    .await?;

    let request: ClientFrame = tokio::select! {
        _ = client_shutdown.cancelled() => return Ok(()),
        result = tokio::time::timeout(REQUEST_TIMEOUT, read_frame(&mut stream)) => result??,
    };
    let response = match request {
        ClientFrame::SubmitRun {
            repo,
            selection,
            options,
            env,
            request_key,
            request_args_hash,
            origin,
        } => {
            let Some(_guard) = coordinator.begin_submission() else {
                write_bounded(&mut stream, &ServerFrame::ShuttingDown).await?;
                return Ok(());
            };
            let caller_env = Arc::new(platform::environment::from_text(&env));
            match handle_submit(
                &coordinator,
                &run_tx,
                &repo,
                &selection,
                &options,
                caller_env,
                request_key.as_ref(),
                request_args_hash.as_deref(),
                &origin,
            )
            .await
            {
                Ok((run, accepted)) => ServerFrame::Submitted {
                    run,
                    accepted,
                    owner: coordinator.owner(),
                },
                Err(message) => ServerFrame::Error(message),
            }
        }
        ClientFrame::CancelRun { repo, run_id } => {
            match handle_cancel(&coordinator, &repo, &run_id).await {
                Ok(ack) => ServerFrame::Cancelled(ack),
                Err(message) => ServerFrame::Error(message),
            }
        }
        ClientFrame::ShutdownIfIdle => {
            if coordinator.try_begin_shutdown() {
                shutdown.cancel();
                ServerFrame::Ack
            } else {
                ServerFrame::Busy
            }
        }
        ClientFrame::Hello { .. } => ServerFrame::Error("Unexpected duplicate Hello.".into()),
    };
    write_bounded(&mut stream, &response).await
}

#[expect(
    clippy::too_many_arguments,
    reason = "forwarding all SubmitRun RPC fields into reservation"
)]
async fn handle_submit(
    coordinator: &Arc<Coordinator>,
    run_tx: &tokio::sync::mpsc::UnboundedSender<SpawnedRun>,
    repo: &Path,
    selection: &crate::project::selection::Selection,
    options: &crate::project::VerifyOptions,
    caller_env: Arc<std::collections::BTreeMap<std::ffi::OsString, std::ffi::OsString>>,
    request_key: Option<&crate::types::RequestKey>,
    request_args_hash: Option<&str>,
    origin: &crate::runs::Origin,
) -> Result<(RunId, bool), String> {
    if let Some(key) = request_key
        && let Some(existing) = coordinator
            .receipts()
            .keyed_run(repo, key, request_args_hash)
            .await?
    {
        return Ok((existing, false));
    }
    let reserved = crate::project::verify::reserve_in(
        repo,
        coordinator.state_dir(),
        coordinator.receipts(),
        selection,
        options,
        request_key,
        request_args_hash,
        origin,
        Some(caller_env.as_ref()),
        Some(coordinator.owner()),
    )
    .await?;
    let (run, accepted) = match reserved {
        crate::project::verify::Reserved::Accepted(run) => (*run, true),
        crate::project::verify::Reserved::Existing(id) => return Ok((id, false)),
    };
    let id = run.id.clone();
    if let Err(error) = process::ensure_worker_stderr(coordinator.state_dir(), &id) {
        let message = error.to_string();
        let _ = coordinator
            .receipts()
            .retire_worker(&id, FailureCode::PreparationFailed)
            .await;
        let _ = worker::fail(
            coordinator.receipts(),
            &id,
            FailureCode::PreparationFailed,
            message.clone(),
        )
        .await;
        return Err(message);
    }
    let cancellation = CancellationToken::new();
    coordinator.register_run(id.clone(), cancellation.clone());
    // Catch any direct-DB cancellation written between `reserve_in` and `register_run`.
    if let Ok(saved) = store::run_control::observe(coordinator.state_dir(), &id).await
        && saved.control.as_ref().is_some_and(Control::is_cancelling)
    {
        cancellation.cancel();
    }
    if run_tx
        .send(SpawnedRun {
            run,
            caller_env,
            cancellation,
        })
        .is_err()
    {
        coordinator.finish_run(&id);
        let message = "Verify engine stopped before accepting Run.".to_owned();
        let _ = coordinator
            .receipts()
            .retire_worker(&id, FailureCode::OwnerDied)
            .await;
        let _ = worker::fail(
            coordinator.receipts(),
            &id,
            FailureCode::OwnerDied,
            message.clone(),
        )
        .await;
        return Err(message);
    }
    Ok((id, accepted))
}

async fn handle_cancel(
    coordinator: &Arc<Coordinator>,
    repo: &Path,
    id: &RunId,
) -> Result<CancelAcknowledgement, String> {
    let saved = store::run_control::observe(coordinator.state_dir(), id).await?;
    if !platform::paths_equal(&saved.repo, repo) {
        return Err("Run not found in this repository.".into());
    }
    // If an open Run belongs to a dead external owner (not managed by this engine), reconcile
    // it immediately instead of leaving it stuck in `Cancelling`.
    if super::owner_died(saved.status, saved.control.as_ref())? {
        let view = store::read_run(coordinator.state_dir(), id).await?;
        worker::recover_in(coordinator.receipts(), coordinator.state_dir(), &view).await?;
        let reconciled = store::run_control::observe(coordinator.state_dir(), id).await?;
        let counts = observe::counts(reconciled.counts);
        return Ok(CancelAcknowledgement {
            run: id.clone(),
            state: observe::state_for(reconciled.status, reconciled.control.as_ref(), &counts),
            cancellation_requested: reconciled
                .control
                .as_ref()
                .is_some_and(Control::is_cancelling),
        });
    }
    // Persist `Activity::Cancelling` BEFORE firing the in-memory cancellation token so
    // `request_cancel` observes the Run as open and returns `cancellation_requested: true`.
    let (status, control) = coordinator.receipts().request_cancel(id).await?;
    coordinator.cancel_active(id);
    let counts = observe::counts(saved.counts);
    Ok(CancelAcknowledgement {
        run: id.clone(),
        state: observe::state_for(status, control.as_ref(), &counts),
        cancellation_requested: control.as_ref().is_some_and(Control::is_cancelling),
    })
}

/// Mirror external SQLite-level cancellations (`runs::cancel` fallback) into the Run's
/// in-memory `CancellationToken` so direct DB cancellations always stop live Runs promptly.
async fn watch_db_cancellation(state: &Path, id: &RunId, cancellation: CancellationToken) {
    let mut changes = crate::changes::Subscription::new(state).await;
    loop {
        if let Ok(saved) = store::run_control::observe(state, id).await
            && (!saved.status.is_open()
                || saved.control.as_ref().is_some_and(Control::is_cancelling))
        {
            cancellation.cancel();
            break;
        }
        tokio::select! {
            _ = cancellation.cancelled() => break,
            _ = changes.next_state() => {}
        }
    }
    let _ = changes.close().await;
}

async fn execute_managed_run(
    coordinator: Arc<Coordinator>,
    spawned: SpawnedRun,
    before_run: Option<BeforeRunHook>,
) {
    let id = spawned.run.id.clone();
    let watcher_stop = spawned.cancellation.child_token();
    let db_watch_state = coordinator.state_dir().to_path_buf();
    let db_watch_id = id.clone();
    let db_watch_cancel = spawned.cancellation.clone();
    let watcher = tokio::spawn(async move {
        tokio::select! {
            _ = watcher_stop.cancelled() => {}
            _ = watch_db_cancellation(&db_watch_state, &db_watch_id, db_watch_cancel) => {}
        }
    });
    let result = async {
        if let Some(hook) = before_run {
            hook(coordinator.state_dir(), &id).await?;
        }
        if spawned.cancellation.is_cancelled() {
            return Err(crate::project::verify::Error::Preparation(
                "Run was cancelled.".into(),
            ));
        }
        crate::project::verify::execute_in(
            spawned.run,
            coordinator.receipts(),
            spawned.cancellation.clone(),
            Some(spawned.caller_env),
            Some(coordinator.clone()),
        )
        .await
    }
    .await;
    watcher.abort();
    let _ = watcher.await;
    if let Err(error) = result {
        let code = if spawned.cancellation.is_cancelled() {
            FailureCode::Cancelled
        } else {
            error.code()
        };
        let message = error.to_string();
        process::append_worker_diagnostic(coordinator.state_dir(), &id, &message);
        // Retire any active SQLite execution owned by this Run before marking it failed so
        // no `RUNNING` / `WAITING_HUMAN` execution leaks while the shared engine stays alive.
        let _ = coordinator.receipts().retire_worker(&id, code).await;
        let _ = worker::fail(coordinator.receipts(), &id, code, message).await;
    }
    coordinator.finish_run(&id);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::project::selection::Selection;
    use crate::project::verify::VerifyOptions;

    /// Bound engine startup, RPC round-trips, and clean idle exit in unit tests.
    const TEST_TIMEOUT: Duration = Duration::from_secs(10);

    async fn connect_when_ready(endpoint: &EngineEndpoint) -> Stream {
        let deadline = tokio::time::Instant::now() + TEST_TIMEOUT;
        loop {
            match endpoint.connect().await {
                Ok(stream) => return stream,
                Err(_) if tokio::time::Instant::now() < deadline => {
                    tokio::time::sleep(Duration::from_millis(20)).await;
                }
                Err(error) => panic!("engine failed to listen: {error}"),
            }
        }
    }

    #[tokio::test]
    async fn incompatible_hello_accepts_shutdown_if_idle_and_exits_cleanly() {
        let dir = crate::test_os::tempdir();
        let state = dir.path().join("state");
        std::fs::create_dir_all(&state).unwrap();
        let engine_state = state.clone();
        let server = tokio::spawn(async move { serve(&engine_state).await });

        let endpoint = EngineEndpoint::new(&state).unwrap();
        let mut stream = connect_when_ready(&endpoint).await;
        write_frame(
            &mut stream,
            &ClientFrame::Hello {
                version: VERSION + 1,
                identity: endpoint.identity.clone(),
            },
        )
        .await
        .unwrap();
        let reply: ServerFrame = read_frame(&mut stream).await.unwrap();
        assert!(
            matches!(
                reply,
                ServerFrame::Incompatible { server_version } if server_version == VERSION
            ),
            "expected Incompatible, got {reply:?}"
        );
        // Same open stream must still accept ShutdownIfIdle so a newer CLI can drain an idle engine.
        write_frame(&mut stream, &ClientFrame::ShutdownIfIdle)
            .await
            .unwrap();
        let ack: ServerFrame = read_frame(&mut stream).await.unwrap();
        assert!(
            matches!(ack, ServerFrame::Ack),
            "expected Ack on idle engine, got {ack:?}"
        );
        drop(stream);

        tokio::time::timeout(TEST_TIMEOUT, server)
            .await
            .expect("engine exits promptly after ShutdownIfIdle")
            .unwrap()
            .unwrap();
    }

    #[tokio::test]
    async fn hung_post_hello_client_does_not_wedge_idle_shutdown() {
        let dir = crate::test_os::tempdir();
        let state = dir.path().join("state");
        std::fs::create_dir_all(&state).unwrap();
        let engine_state = state.clone();
        let server = tokio::spawn(async move { serve(&engine_state).await });

        let endpoint = EngineEndpoint::new(&state).unwrap();
        let mut hung = connect_when_ready(&endpoint).await;
        write_frame(
            &mut hung,
            &ClientFrame::Hello {
                version: VERSION,
                identity: endpoint.identity.clone(),
            },
        )
        .await
        .unwrap();
        let reply: ServerFrame = read_frame(&mut hung).await.unwrap();
        assert!(matches!(reply, ServerFrame::Welcome { .. }));

        // Leave `hung` open without sending any request; ask the engine to shut down via a
        // second client and verify it still drains and exits cleanly.
        let mut control = endpoint.connect().await.unwrap();
        write_frame(
            &mut control,
            &ClientFrame::Hello {
                version: VERSION,
                identity: endpoint.identity.clone(),
            },
        )
        .await
        .unwrap();
        let ready: ServerFrame = read_frame(&mut control).await.unwrap();
        assert!(matches!(ready, ServerFrame::Welcome { .. }));
        write_frame(&mut control, &ClientFrame::ShutdownIfIdle)
            .await
            .unwrap();
        let ack: ServerFrame = read_frame(&mut control).await.unwrap();
        assert!(matches!(ack, ServerFrame::Ack));
        drop(control);

        tokio::time::timeout(TEST_TIMEOUT, server)
            .await
            .expect("hung client must not block engine shutdown")
            .unwrap()
            .unwrap();
        drop(hung);
    }

    #[tokio::test]
    async fn direct_db_cancellation_cancels_live_engine_run_and_incompatible_reports_busy() {
        let dir = crate::test_os::tempdir();
        let state = dir.path().join("state");
        let repo = dir.path().join("repo");
        std::fs::create_dir_all(&state).unwrap();
        std::fs::create_dir_all(repo.join(".artifactize")).unwrap();
        std::fs::write(repo.join("content.txt"), "hello").unwrap();
        std::fs::write(
            repo.join(".artifactize/index.artf"),
            "artf app : files = {\n  path = \"content.txt\"\n  eval check : runtime(command = \"true\", args = []) = { title = \"Check\" }\n}\n",
        )
        .unwrap();

        let (entered_tx, entered_rx) = tokio::sync::oneshot::channel::<RunId>();
        let entered_tx = Arc::new(std::sync::Mutex::new(Some(entered_tx)));
        let gate = Arc::new(tokio::sync::Notify::new());
        let gate_hook = gate.clone();
        let hook: BeforeRunHook = Arc::new(move |_state, id| {
            let id = id.clone();
            let entered_tx = entered_tx.clone();
            let gate = gate_hook.clone();
            Box::pin(async move {
                if let Some(tx) = entered_tx.lock().unwrap().take() {
                    let _ = tx.send(id);
                }
                gate.notified().await;
                Ok(())
            })
        });

        let engine_state = state.clone();
        let server = tokio::spawn(async move { serve_with_hook(&engine_state, Some(hook)).await });

        let endpoint = EngineEndpoint::new(&state).unwrap();
        let mut client = connect_when_ready(&endpoint).await;
        write_frame(
            &mut client,
            &ClientFrame::Hello {
                version: VERSION,
                identity: endpoint.identity.clone(),
            },
        )
        .await
        .unwrap();
        assert!(matches!(
            read_frame(&mut client).await.unwrap(),
            ServerFrame::Welcome { .. }
        ));
        write_frame(
            &mut client,
            &ClientFrame::SubmitRun {
                repo: repo.clone(),
                selection: Selection::All,
                options: Box::new(VerifyOptions::default()),
                request_key: None,
                request_args_hash: None,
                env: platform::environment::snapshot_text(),
                origin: crate::runs::Origin::Cli,
            },
        )
        .await
        .unwrap();
        let run_id = match read_frame(&mut client).await.unwrap() {
            ServerFrame::Submitted { run, .. } => run,
            other => panic!("expected Submitted, got {other:?}"),
        };
        drop(client);

        let started_id = tokio::time::timeout(TEST_TIMEOUT, entered_rx)
            .await
            .expect("before_run hook fires")
            .unwrap();
        assert_eq!(started_id, run_id);

        // While the Run is active, an incompatible peer requesting ShutdownIfIdle gets Busy.
        let mut peer = endpoint.connect().await.unwrap();
        write_frame(
            &mut peer,
            &ClientFrame::Hello {
                version: VERSION + 1,
                identity: endpoint.identity.clone(),
            },
        )
        .await
        .unwrap();
        assert!(matches!(
            read_frame(&mut peer).await.unwrap(),
            ServerFrame::Incompatible { .. }
        ));
        write_frame(&mut peer, &ClientFrame::ShutdownIfIdle)
            .await
            .unwrap();
        assert!(
            matches!(read_frame(&mut peer).await.unwrap(), ServerFrame::Busy),
            "active engine must refuse ShutdownIfIdle with Busy"
        );
        drop(peer);

        // Request cancellation directly via SQLite (bypassing engine IPC).
        let receipts = Receipts::open(&state, &repo).await.unwrap();
        receipts.request_cancel(&run_id).await.unwrap();
        receipts.close().await.unwrap();

        // Wait until `watch_db_cancellation` observes the SQLite flag, then release the hook.
        tokio::time::sleep(Duration::from_millis(80)).await;
        gate.notify_waiters();

        // Engine should settle the Run as cancelled and then drain cleanly.
        tokio::time::timeout(TEST_TIMEOUT, server)
            .await
            .expect("engine drains after cancelled Run settles")
            .unwrap()
            .unwrap();
        let view = store::read_run(&state, &run_id).await.unwrap();
        assert_eq!(view.run.status(), crate::types::RunStatus::Error);
    }
}