Skip to main content

microvms_core/session/
exec.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The handle a caller holds for one running exec.
3//!
4//! The whole reason this module exists is [`ExecHandle::stream`]. Everything else here
5//! is a thin wrapper over one route.
6//!
7//! # The cursor is the contract
8//!
9//! A reconnect passes `?offset=<bytes consumed>`, and the daemon replays from there.
10//! Without it a dropped connection means either losing everything after the drop or
11//! replaying from zero, and neither is distinguishable from correct behaviour with
12//! nothing to check against — E2B's cursorless `connect(pid)` and their issue #1352 are
13//! exactly that.
14//!
15//! Two rules the cursor arithmetic has to obey, and both are properties of *what the
16//! caller has seen* rather than of what arrived:
17//!
18//! * Advance only past bytes actually handed to the caller, so a reconnect never
19//!   re-delivers and never skips.
20//! * Advance past a `gap` too. The daemon has already moved its own cursor past evicted
21//!   bytes; if ours did not follow, a reconnect would ask for them again and be told
22//!   about the same gap forever.
23//!
24//! # The reconnect condition is a typed event, not a byte count
25//!
26//! A stream that ended *without* an `exit` event was cut. A stream that ended *with* one
27//! is over. Those two are the identical byte sequence on a raw stream, which is the
28//! whole argument for SSE framing here and why this is not a byte stream. The
29//! reconnect decision reads that distinction and nothing else.
30
31use std::sync::Arc;
32use std::time::Duration;
33
34use base64::Engine as _;
35use futures_util::Stream;
36
37use super::sse::{ExecEvent, SseParser, decode};
38use super::{HttpRequest, Transport};
39use crate::error::{Error, ErrorKind, WireKind};
40
41/// Backoff between reconnect attempts. Short, because the offset makes a reconnect
42/// cheap — the daemon replays from the cursor, so nothing already delivered is refetched.
43const RECONNECT_BACKOFF: [Duration; 5] = [
44    Duration::from_millis(250),
45    Duration::from_millis(500),
46    Duration::from_secs(1),
47    Duration::from_secs(2),
48    Duration::from_secs(4),
49];
50
51/// How long an attached stream may be silent before it is treated as dead.
52///
53/// Four times the daemon's fifteen-second SSE keepalive, so three missed keepalives are
54/// tolerated before a reconnect. Tighter than that turns a slow proxy into a reconnect
55/// loop.
56pub const DEFAULT_STREAM_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
57
58/// How often to re-poll while waiting for an exec to finish.
59const POLL_INTERVAL: Duration = Duration::from_secs(1);
60
61/// An exec's phase and, once it has one, its outcome.
62///
63/// A thin wrapper over the daemon's [`protocol::exec::PollResponse`] rather than a
64/// re-modelling of it, so the two cannot disagree. What it adds is [`ExecResult::done`],
65/// which is the question every caller actually asks.
66#[derive(Debug)]
67pub struct ExecResult {
68    pub exec_id: String,
69    pub phase: protocol::exec::Phase,
70    /// `None` while running. Present once the child has exited.
71    pub outcome: Option<protocol::exec::Outcome>,
72}
73
74impl From<protocol::exec::PollResponse> for ExecResult {
75    fn from(response: protocol::exec::PollResponse) -> Self {
76        Self {
77            exec_id: response.exec_id,
78            phase: response.phase,
79            outcome: response.result,
80        }
81    }
82}
83
84impl ExecResult {
85    /// Whether the exec has finished, whichever way.
86    pub fn done(&self) -> bool {
87        matches!(
88            self.phase,
89            protocol::exec::Phase::Exited | protocol::exec::Phase::Acked
90        )
91    }
92
93    /// The exit code, when the child exited with one rather than dying to a signal.
94    pub fn exit_code(&self) -> Option<i32> {
95        self.outcome.as_ref().and_then(|outcome| outcome.exit_code)
96    }
97
98    /// Whether the command succeeded. `false` for a signal death and for a still-running
99    /// exec, since neither is a success.
100    pub fn succeeded(&self) -> bool {
101        self.exit_code() == Some(0)
102    }
103
104    pub fn stdout(&self) -> &str {
105        self.outcome
106            .as_ref()
107            .map_or("", |outcome| outcome.stdout.as_str())
108    }
109
110    pub fn stderr(&self) -> &str {
111        self.outcome
112            .as_ref()
113            .map_or("", |outcome| outcome.stderr.as_str())
114    }
115}
116
117/// What a stdin write accomplished.
118pub type StdinAck = protocol::exec::StdinResponse;
119
120/// Why a stream stopped, and where a resume would pick up.
121///
122/// Returned by [`ExecHandle::for_each_event`] and
123/// [`ExecHandle::for_each_event_async`] so the three endings are distinguishable
124/// *without* a caller having to reason about which event it last saw. That distinction is
125/// the whole point of this module — a body that ended without an `exit` event was cut, and
126/// the byte sequence alone cannot say so — and asking every caller to re-derive it from a
127/// tally is how one of them gets it wrong and reports a truncated stream as a clean pass.
128#[derive(Clone, Copy, Debug, Eq, PartialEq)]
129pub struct StreamEnd {
130    pub reason: EndReason,
131    /// The offset a resume would pass as [`StreamOptions::offset`].
132    ///
133    /// **Core's cursor, not a count of what the callback saw.** The two rules in this
134    /// module's docs (advance only past delivered bytes, and advance past a `gap`) are
135    /// obeyed by the state machine below; handing the number back means a caller resuming
136    /// does not maintain a second cursor that disagrees with this one exactly when a
137    /// reconnect happened.
138    pub cursor: u64,
139}
140
141/// The three ways a stream ends without an error.
142#[derive(Clone, Copy, Debug, Eq, PartialEq)]
143pub enum EndReason {
144    /// The terminal `exit` event arrived and was delivered. The command is over.
145    Exited,
146    /// The callback answered [`ControlFlow::Break`]. Nothing is wrong; the caller stopped
147    /// reading, and [`StreamEnd::cursor`] is where it stopped.
148    Stopped,
149    /// The body ended with **no** `exit` event and `reconnect` was off, so the connection
150    /// was cut and this client was told not to re-attach. The command's outcome is
151    /// unknown — not zero — and a caller reporting success here would pass a CI step on
152    /// evidence it never received.
153    Cut,
154}
155
156/// How a stream should behave. See [`ExecHandle::stream_with`].
157#[derive(Clone, Debug)]
158pub struct StreamOptions {
159    /// The byte to start at. Non-zero resumes a stream a previous process was reading.
160    pub offset: u64,
161    /// Whether to reconnect after a cut. `false` ends the stream at the cut instead,
162    /// which is what a caller doing its own reconnection wants.
163    pub reconnect: bool,
164    /// How many reconnects before giving up. A bound rather than forever, because a
165    /// stream that drops every time is a condition a caller needs reported.
166    pub max_reconnects: u32,
167    /// Turns a `gap` into an error instead of an event. What a caller that must have
168    /// complete output wants.
169    pub error_on_gap: bool,
170    /// How long the body may be silent before the connection is treated as dead.
171    pub idle_timeout: Duration,
172}
173
174impl Default for StreamOptions {
175    fn default() -> Self {
176        Self {
177            offset: 0,
178            reconnect: true,
179            max_reconnects: 20,
180            error_on_gap: false,
181            idle_timeout: DEFAULT_STREAM_IDLE_TIMEOUT,
182        }
183    }
184}
185
186/// A fresh exec id: `x-` plus 16 hex characters, the Python client's shape.
187///
188/// Here rather than in each binding, because both bindings carried a byte-identical
189/// copy of this function — and the id's shape is part of the session story ("the exec
190/// id is caller-minted"), so the crate that tells that story is the crate that mints.
191///
192/// Not a crate: the id needs to be distinct rather than unguessable — it is an
193/// idempotency key, not a credential, and the daemon rejects an unknown one — so the
194/// nanosecond clock mixed with a counter is enough, and a CSPRNG dependency for it
195/// would not be.
196pub fn mint_exec_id() -> String {
197    use std::sync::atomic::{AtomicU64, Ordering};
198    static SEQUENCE: AtomicU64 = AtomicU64::new(0);
199    let nanos = std::time::SystemTime::now()
200        .duration_since(std::time::UNIX_EPOCH)
201        .map(|since| since.as_nanos() as u64)
202        .unwrap_or_default();
203    let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed);
204    // The counter folds into the clock's high bits so two ids minted in the same
205    // nanosecond still differ.
206    format!("x-{:016x}", nanos ^ (sequence << 40))
207}
208
209/// One exec, addressed by its caller-minted id.
210///
211/// The id is the idempotency key, so a handle survives a process restart: rebuild it
212/// with the same id and every method still addresses the same server-side exec.
213pub struct ExecHandle {
214    transport: Arc<Transport>,
215    exec_id: String,
216}
217
218impl ExecHandle {
219    pub(crate) fn new(transport: Arc<Transport>, exec_id: String) -> Self {
220        Self { transport, exec_id }
221    }
222
223    pub fn exec_id(&self) -> &str {
224        &self.exec_id
225    }
226
227    /// Reads current status and output. Read-only server-side; safe to spin on.
228    pub async fn poll(&self) -> Result<ExecResult, Error> {
229        let response: protocol::exec::PollResponse = self
230            .transport
231            .send_json(HttpRequest::new(
232                "GET",
233                format!("/v1/exec/{}", self.exec_id),
234            ))
235            .await?;
236        Ok(response.into())
237    }
238
239    /// Polls until the exec is done, or fails with a client-side timeout.
240    ///
241    /// A timeout here has not touched the exec — polling is read-only and the output
242    /// lives until it is acked — so a caller that gives up can come back and poll again,
243    /// and the message says so.
244    ///
245    /// A retryable error mid-wait is swallowed rather than raised: a VM under load drops
246    /// a connection occasionally, and the whole point of a read-only poll is that
247    /// repeating it costs nothing. A fatal one ends the wait.
248    pub async fn wait(&self, timeout: Duration) -> Result<ExecResult, Error> {
249        let deadline = tokio::time::Instant::now() + timeout;
250        let mut last_phase: Option<protocol::exec::Phase> = None;
251        loop {
252            match self.poll().await {
253                Ok(result) => {
254                    if result.done() {
255                        return Ok(result);
256                    }
257                    last_phase = Some(result.phase);
258                }
259                Err(err) if err.retryable() => {}
260                Err(err) => return Err(err),
261            }
262            let now = tokio::time::Instant::now();
263            if now >= deadline {
264                let phase = match last_phase {
265                    Some(protocol::exec::Phase::Running) => "running",
266                    Some(protocol::exec::Phase::Exited) => "exited",
267                    Some(protocol::exec::Phase::Acked) => "acked",
268                    None => "unknown",
269                };
270                return Err(Error::wire(
271                    WireKind::ExecTimeout,
272                    format!(
273                        "exec {} was still {phase} after {}s; the record and its output \
274                         are untouched and can be re-polled",
275                        self.exec_id,
276                        timeout.as_secs()
277                    ),
278                ));
279            }
280            tokio::time::sleep(POLL_INTERVAL.min(deadline - now)).await;
281        }
282    }
283
284    /// Yields output as it arrives, reconnecting at the last good offset.
285    pub fn stream(&self) -> impl Stream<Item = Result<ExecEvent, Error>> + '_ {
286        self.stream_with(StreamOptions::default())
287    }
288
289    /// [`Self::stream`] with the knobs. See [`StreamOptions`].
290    ///
291    /// Written as a generator over an explicit state machine rather than as a hand-rolled
292    /// `Stream` impl: the reconnect logic is a loop with an `await` in the middle of it,
293    /// and expressing that as a `poll_next` would mean storing the in-flight attach as a
294    /// pinned field — which is where a self-referential-future bug lives.
295    pub fn stream_with(
296        &self,
297        options: StreamOptions,
298    ) -> impl Stream<Item = Result<ExecEvent, Error>> + '_ {
299        futures_util::stream::unfold(
300            StreamState::Reconnect {
301                cursor: options.offset,
302                attempts: 0,
303            },
304            move |state| {
305                let options = options.clone();
306                async move { self.advance(state, &options).await }
307            },
308        )
309    }
310
311    /// Drives a stream to its end, handing every event to `on_event`.
312    ///
313    /// The same state machine [`Self::stream_with`] runs, driven by an ordinary loop
314    /// instead of wrapped in a [`Stream`]. Everything about the wire behaviour is
315    /// identical — same reconnects, same cursor, same terminal-event rule — and both share
316    /// [`Self::advance`], so there is one implementation of the property and two ways to
317    /// consume it.
318    ///
319    /// # Why a callback exists beside the `Stream`
320    ///
321    /// Because `Stream` is not in `std`. A consumer of [`Self::stream_with`] has to name
322    /// the crate that defines the trait in order to call `poll_next`, so a client that
323    /// wants to print a line per event acquires a dependency to advance a loop —
324    /// `microvms-cli` carried `futures-util` for exactly that and nothing else, and
325    /// `tests/thinness.rs` (CLI-2) asserts that crate's dependency set exactly. This
326    /// method is that dependency's replacement: `ControlFlow` and `async fn` are both std,
327    /// so a caller needs nothing but this crate.
328    ///
329    /// A **synchronous** callback is the right shape for a caller whose per-event work is
330    /// synchronous — the CLI writes a line and returns. A caller whose per-event work is an
331    /// `await` (both bindings: a bounded-channel `send`) wants
332    /// [`Self::for_each_event_async`], which is the same loop with an awaited callback.
333    /// Using this one there would mean `blocking_send` on a runtime worker, which is why
334    /// the overload exists.
335    ///
336    /// # What the return value says that a tally cannot
337    ///
338    /// [`StreamEnd::reason`] distinguishes an `exit` event from a cut body from a caller
339    /// that stopped reading. A caller counting events cannot: a cut stream and a finished
340    /// one differ only in the terminal event, which is the argument for SSE framing here in
341    /// the first place. [`StreamEnd::cursor`] is the state machine's own offset, so a
342    /// caller resuming does not maintain a second one.
343    ///
344    /// An error ends the drive with `Err` and the events already handed over **stay handed
345    /// over**. That asymmetry is deliberate: the bytes a callback already wrote are real
346    /// output the caller received, and there is nothing to unwind them with.
347    pub async fn for_each_event<F>(
348        &self,
349        options: StreamOptions,
350        mut on_event: F,
351    ) -> Result<StreamEnd, Error>
352    where
353        F: FnMut(ExecEvent) -> std::ops::ControlFlow<()>,
354    {
355        // Delegated rather than a second copy of the loop. A synchronous callback *is* an
356        // async one whose future is already complete, and `std::future::ready` says exactly
357        // that — so the ordering, the cursor read, the `Break` arm, and the three endings
358        // have one implementation instead of two that agree until one is edited.
359        self.for_each_event_async(options, |event| std::future::ready(on_event(event)))
360            .await
361    }
362
363    /// [`Self::for_each_event`] for a callback that **awaits**.
364    ///
365    /// The same loop and the same [`Self::advance`] state machine; the only difference is
366    /// that the per-event callback answers a future, which is `.await`ed before the next
367    /// step is taken. So the events are still delivered strictly in order and still one at a
368    /// time — a callback that awaits between events holds the drive rather than racing it,
369    /// which is what makes this usable as backpressure.
370    ///
371    /// # Why the overload exists, and what it closed
372    ///
373    /// Both bindings consume a stream by pushing into a **capacity-1** `mpsc` channel that a
374    /// foreign-language iterator drains (`microvms-py/src/exec.rs`, `microvms-js/src/exec.rs`).
375    /// The channel bound is deliberate — the daemon's SSE body is the backpressure signal —
376    /// and it means the channel is full whenever the host-language consumer is even slightly
377    /// behind, i.e. normally. With [`Self::for_each_event`] the only available send is
378    /// `blocking_send`, which would block the very runtime worker the driver is running on;
379    /// so both bindings kept the `Stream` path, and `futures-util` with it, for a reason
380    /// about backpressure rather than about the trait. `send(..).await` inside an
381    /// `AsyncFnMut` yields the worker instead, and both bindings dropped the dependency on
382    /// 2026-08-09.
383    ///
384    /// # `FnMut(ExecEvent) -> Fut` rather than `AsyncFnMut`
385    ///
386    /// Measured, not stylistic, and the measurement is the reason the signature looks older
387    /// than the edition. `AsyncFnMut` is the obvious spelling and it compiles here — but a
388    /// caller cannot `tokio::spawn` a drive that uses it. Proving the returned future `Send`
389    /// requires naming `F::CallRefFuture<'a>` under a `for<'a>` bound, which is the unstable
390    /// `async_fn_traits` feature; without it the spawn fails with *"`Send` would have to be
391    /// implemented for the type `&ExecHandle`… but `Send` is actually implemented for
392    /// `&'0 ExecHandle`, for some specific lifetime"*. Both bindings spawn this drive onto a
393    /// runtime, so that is not a corner they can avoid, and the unstable bound additionally
394    /// forces the callback's captures to `'static`.
395    ///
396    /// So `Fut` is a plain type parameter. The cost is that the callback's future cannot
397    /// *borrow* from the closure's captures — it has no lifetime to name them with — so a
398    /// caller sending on a channel clones the sender per event rather than holding `&sender`.
399    /// For a `tokio::sync::mpsc::Sender` that is one atomic increment, which is the right
400    /// price for a signature that can cross a spawn.
401    ///
402    /// The return value and the error asymmetry are [`Self::for_each_event`]'s, unchanged.
403    pub async fn for_each_event_async<F, Fut>(
404        &self,
405        options: StreamOptions,
406        mut on_event: F,
407    ) -> Result<StreamEnd, Error>
408    where
409        F: FnMut(ExecEvent) -> Fut,
410        Fut: std::future::Future<Output = std::ops::ControlFlow<()>>,
411    {
412        let mut state = StreamState::Reconnect {
413            cursor: options.offset,
414            attempts: 0,
415        };
416        // Seeded from the caller's own starting offset, so a drive that ends before any
417        // event arrives reports where it began rather than zero.
418        let mut cursor = options.offset;
419        loop {
420            let Some((item, next)) = self.advance(state, &options).await else {
421                // `advance` yields nothing only when the body ended without an `exit`
422                // event and reconnecting was refused — the `exit` case returns below,
423                // before the machine is stepped again. So this is the cut.
424                return Ok(StreamEnd {
425                    reason: EndReason::Cut,
426                    cursor,
427                });
428            };
429            // Read off the machine rather than recomputed from the event: the two rules in
430            // this module's docs live in `advance`, and a second `cursor.max(end)` here
431            // would be a second implementation that agrees until a `gap` arrives.
432            if let Some(advanced) = next.cursor() {
433                cursor = advanced;
434            }
435            state = next;
436
437            let event = item?;
438            let terminal = matches!(event, ExecEvent::Exit(_));
439            // Awaited before the loop advances, which is the whole point: the next attach
440            // read does not start until the callback's own work is done, so a slow consumer
441            // slows the stream rather than buffering behind it.
442            if on_event(event).await.is_break() {
443                return Ok(StreamEnd {
444                    reason: EndReason::Stopped,
445                    cursor,
446                });
447            }
448            if terminal {
449                return Ok(StreamEnd {
450                    reason: EndReason::Exited,
451                    cursor,
452                });
453            }
454        }
455    }
456
457    /// One step of the stream state machine.
458    ///
459    /// Returns `None` to end the stream, or the next item plus the state after it.
460    async fn advance(
461        &self,
462        state: StreamState,
463        options: &StreamOptions,
464    ) -> Option<(Result<ExecEvent, Error>, StreamState)> {
465        let mut state = state;
466        loop {
467            match state {
468                StreamState::Done => return None,
469                StreamState::Reconnect { cursor, attempts } => {
470                    if attempts > 0 {
471                        if !options.reconnect {
472                            return None;
473                        }
474                        if attempts > options.max_reconnects {
475                            return Some((
476                                Err(Error::new(
477                                    ErrorKind::Retryable,
478                                    format!(
479                                        "the stream of {} dropped {attempts} times without \
480                                         an exit event; last good offset {cursor}",
481                                        self.exec_id
482                                    ),
483                                )),
484                                StreamState::Done,
485                            ));
486                        }
487                        let backoff = RECONNECT_BACKOFF
488                            [((attempts - 1) as usize).min(RECONNECT_BACKOFF.len() - 1)];
489                        tokio::time::sleep(backoff).await;
490                    }
491                    match self.attach(cursor, options.idle_timeout).await {
492                        Ok(attach) => {
493                            state = StreamState::Attached {
494                                attach: Box::new(attach),
495                                cursor,
496                                attempts,
497                            };
498                        }
499                        // A cut connection or a failed mint. Neither says anything
500                        // about the exec, which is still running server-side, so both
501                        // are reconnected through rather than surfaced.
502                        Err(err) if err.retryable() && options.reconnect => {
503                            state = StreamState::Reconnect {
504                                cursor,
505                                attempts: attempts + 1,
506                            };
507                        }
508                        // Anything fatal — a 404 on a collected entry above all, where
509                        // reconnecting can never succeed — ends the stream with the
510                        // error rather than looping on it.
511                        Err(err) => return Some((Err(err), StreamState::Done)),
512                    }
513                }
514                StreamState::Attached {
515                    mut attach,
516                    mut cursor,
517                    attempts,
518                } => match attach.next_event().await {
519                    Ok(Some(ExecEvent::Output {
520                        stream,
521                        offset,
522                        data,
523                    })) => {
524                        // Advance only past bytes actually handed over.
525                        let end = offset + data.len() as u64;
526                        cursor = cursor.max(end);
527                        return Some((
528                            Ok(ExecEvent::Output {
529                                stream,
530                                offset,
531                                data,
532                            }),
533                            StreamState::Attached {
534                                attach,
535                                cursor,
536                                attempts,
537                            },
538                        ));
539                    }
540                    Ok(Some(ExecEvent::Gap { from, to })) => {
541                        // Follow the daemon past the evicted range, or a reconnect asks
542                        // for it again and is told about the same gap forever.
543                        cursor = cursor.max(to);
544                        let item = if options.error_on_gap {
545                            Err(Error::wire(
546                                WireKind::OutputGap,
547                                format!("output bytes [{from}, {to}) are unrecoverable"),
548                            ))
549                        } else {
550                            Ok(ExecEvent::Gap { from, to })
551                        };
552                        let next = if options.error_on_gap {
553                            StreamState::Done
554                        } else {
555                            StreamState::Attached {
556                                attach,
557                                cursor,
558                                attempts,
559                            }
560                        };
561                        return Some((item, next));
562                    }
563                    // The terminal event. The stream is over, and this is the only thing
564                    // that says so.
565                    Ok(Some(ExecEvent::Exit(exit))) => {
566                        return Some((Ok(ExecEvent::Exit(exit)), StreamState::Done));
567                    }
568                    // The body ended with no exit event, so the connection was cut.
569                    Ok(None) => {
570                        if !options.reconnect {
571                            return None;
572                        }
573                        state = StreamState::Reconnect {
574                            cursor,
575                            attempts: attempts + 1,
576                        };
577                    }
578                    Err(err) if err.retryable() && options.reconnect => {
579                        state = StreamState::Reconnect {
580                            cursor,
581                            attempts: attempts + 1,
582                        };
583                    }
584                    Err(err) => return Some((Err(err), StreamState::Done)),
585                },
586            }
587        }
588    }
589
590    /// Opens one attach at `offset`.
591    async fn attach(&self, offset: u64, idle_timeout: Duration) -> Result<Attach, Error> {
592        let path = format!("/v1/exec/{}/stream?offset={offset}", self.exec_id);
593        let mut request = HttpRequest::new("GET", path.clone());
594        request
595            .headers
596            .push(("accept".into(), "text/event-stream".into()));
597        // Headers are built here rather than in `Transport::request`, because the
598        // streaming path does not go through it — and the mint has to happen anyway,
599        // which is what makes a mid-stream reconnect re-mint an expired token.
600        request.headers.extend(self.transport.headers(None).await?);
601        request.timeout = None;
602
603        let (head, chunks) = self
604            .transport
605            .backend
606            .open_stream(request, idle_timeout)
607            .await?;
608        // The status is checked before any body byte, so a 404 on an unknown exec id
609        // surfaces as NotFound rather than as an empty stream.
610        head.error_for_status("GET", &path)?;
611        Ok(Attach {
612            chunks,
613            parser: SseParser::new(),
614            frames: std::collections::VecDeque::new(),
615        })
616    }
617
618    /// Writes to the child's stdin.
619    ///
620    /// Requires the exec to have been started with `stdin: true`, or the daemon answers
621    /// 409. `eof` in the same call is the common case for feeding a prompt: two round
622    /// trips would leave a window where the child has the bytes but not the EOF that
623    /// tells it the input is complete.
624    pub async fn write_stdin(&self, data: &[u8], eof: bool) -> Result<StdinAck, Error> {
625        let body = protocol::exec::StdinRequest {
626            data_b64: (!data.is_empty())
627                .then(|| base64::engine::general_purpose::STANDARD.encode(data)),
628            signal: eof.then(|| "eof".to_string()),
629        };
630        let mut request = HttpRequest::new("POST", format!("/v1/exec/{}/stdin", self.exec_id));
631        request
632            .headers
633            .push(("content-type".into(), "application/json".into()));
634        request.body = serde_json::to_vec(&body).map_err(|err| {
635            Error::invalid_arg(format!("the stdin body will not serialize: {err}"))
636        })?;
637        self.transport.send_json(request).await
638    }
639
640    /// Sends EOF.
641    ///
642    /// Nothing else closes stdin: the daemon's copy of the pipe outlives `Child::wait()`,
643    /// so a child blocked reading stdin hangs until its timeout unless someone calls
644    /// this.
645    pub async fn close_stdin(&self) -> Result<StdinAck, Error> {
646        self.write_stdin(&[], true).await
647    }
648
649    /// Releases the buffered output and starts the TTL clock.
650    ///
651    /// 409 means either the exec has not exited — output is still being written — or an
652    /// earlier ack already took it. Both are real states, not the same state, and the
653    /// daemon's detail string distinguishes them.
654    pub async fn ack(&self) -> Result<ExecResult, Error> {
655        let response: protocol::exec::PollResponse = self
656            .transport
657            .send_json(HttpRequest::new(
658                "POST",
659                format!("/v1/exec/{}/ack", self.exec_id),
660            ))
661            .await?;
662        Ok(response.into())
663    }
664
665    /// Signals the whole process group, not just the direct child.
666    ///
667    /// Returns whether anything was signalled. `false` means no pgid was ever captured,
668    /// i.e. the child had already been reaped — which is the outcome a kill wanted, and
669    /// is why it is a 200 rather than an error.
670    pub async fn kill(&self) -> Result<bool, Error> {
671        let response: protocol::exec::KillResponse = self
672            .transport
673            .send_json(HttpRequest::new(
674                "POST",
675                format!("/v1/exec/{}/kill", self.exec_id),
676            ))
677            .await?;
678        Ok(response.killed)
679    }
680
681    /// Waits, then acks, returning the result that carries the output.
682    ///
683    /// Which result is returned matters: the ack response carries the released output,
684    /// and a poll issued after the ack reports `acked` with no output at all. Returning
685    /// the wrong one is a silent empty-output bug, so the sequencing lives here rather
686    /// than at every call site.
687    pub async fn wait_and_ack(&self, timeout: Duration) -> Result<ExecResult, Error> {
688        let done = self.wait(timeout).await?;
689        if done.phase == protocol::exec::Phase::Acked {
690            return Ok(done);
691        }
692        self.ack().await
693    }
694}
695
696impl std::fmt::Debug for ExecHandle {
697    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
698        f.debug_struct("ExecHandle")
699            .field("exec_id", &self.exec_id)
700            .finish()
701    }
702}
703
704/// One live attach: a chunk source plus the parser holding its partial frame.
705struct Attach {
706    chunks: Box<dyn super::ChunkSource>,
707    parser: SseParser,
708    frames: std::collections::VecDeque<super::Frame>,
709}
710
711impl Attach {
712    /// The next event this attach can produce, or `None` when its body ends.
713    ///
714    /// A frame that decodes to nothing is skipped rather than returned, so an unknown
715    /// event name does not surface as a spurious end-of-stream.
716    async fn next_event(&mut self) -> Result<Option<ExecEvent>, Error> {
717        loop {
718            while let Some(frame) = self.frames.pop_front() {
719                if let Some(event) = decode(&frame)? {
720                    return Ok(Some(event));
721                }
722            }
723            let Some(chunk) = self.chunks.next_chunk().await? else {
724                return Ok(None);
725            };
726            // A parse failure here is the undelimited-data ceiling, which is
727            // `ErrorKind::Protocol` and therefore not retryable — so `advance` ends the
728            // stream with it rather than reconnecting into the same non-SSE body. That is
729            // the point: a proxy answering an error page would otherwise be retried
730            // `max_reconnects` times, filling the buffer again each time.
731            self.frames.extend(self.parser.feed(&chunk)?);
732        }
733    }
734}
735
736/// Where the stream is. Boxed attach because the enum otherwise carries a trait object
737/// inline and every state pays its size.
738enum StreamState {
739    /// Needs an attach. `attempts` is zero for the first one, which is why the backoff
740    /// and the max-reconnect check are both skipped there.
741    Reconnect {
742        cursor: u64,
743        attempts: u32,
744    },
745    Attached {
746        attach: Box<Attach>,
747        cursor: u64,
748        attempts: u32,
749    },
750    Done,
751}
752
753impl StreamState {
754    /// The cursor this state carries, or `None` for [`StreamState::Done`].
755    ///
756    /// `Done` has none on purpose: it is reached from three different places and inventing
757    /// one there would mean picking a number, where the caller
758    /// ([`ExecHandle::for_each_event`]) already holds the last real one. `None` says "this
759    /// state advanced nothing" rather than "the cursor is zero".
760    fn cursor(&self) -> Option<u64> {
761        match self {
762            StreamState::Reconnect { cursor, .. } | StreamState::Attached { cursor, .. } => {
763                Some(*cursor)
764            }
765            StreamState::Done => None,
766        }
767    }
768}
769
770#[cfg(test)]
771mod tests {
772    use super::*;
773    use crate::session::testing::{Recorder, Reply, session_with};
774    use futures_util::StreamExt as _;
775
776    /// One SSE `output` frame on the wire.
777    fn output(offset: u64, bytes: &[u8]) -> Vec<u8> {
778        let encoded = base64::engine::general_purpose::STANDARD.encode(bytes);
779        format!(
780            "event: output\ndata: {{\"offset\":{offset},\"stream\":\"stdout\",\
781             \"output\":\"{encoded}\"}}\n\n"
782        )
783        .into_bytes()
784    }
785
786    fn exit(total: u64) -> Vec<u8> {
787        format!(
788            "event: exit\ndata: {{\"exit_code\":0,\"signal\":null,\"truncated\":false,\
789             \"writers_may_be_alive\":false,\"offset\":{total}}}\n\n"
790        )
791        .into_bytes()
792    }
793
794    fn gap(from: u64, to: u64) -> Vec<u8> {
795        format!("event: gap\ndata: {{\"from\":{from},\"to\":{to}}}\n\n").into_bytes()
796    }
797
798    /// Collects a stream's bytes and its events.
799    async fn collect(
800        handle: &ExecHandle,
801        options: StreamOptions,
802    ) -> (Vec<u8>, Vec<Result<ExecEvent, Error>>) {
803        let mut bytes = Vec::new();
804        let mut events = Vec::new();
805        let mut stream = std::pin::pin!(handle.stream_with(options));
806        while let Some(item) = stream.next().await {
807            if let Ok(ExecEvent::Output { data, .. }) = &item {
808                bytes.extend_from_slice(data);
809            }
810            events.push(item);
811        }
812        (bytes, events)
813    }
814
815    /// The offset a stream request asked for.
816    fn requested_offset(request: &HttpRequest) -> u64 {
817        request
818            .path
819            .split("offset=")
820            .nth(1)
821            .expect("a stream request always carries an offset")
822            .parse()
823            .expect("the offset is a number")
824    }
825
826    /// The reconnect property, asserted on the reassembled byte sequence.
827    ///
828    /// The verdict is the bytes, not the absence of an error: a client that reconnected
829    /// at zero would deliver every byte too, and only the seam shows the difference. So
830    /// this checks the join *and* the offset the second attach asked for.
831    #[tokio::test(start_paused = true)]
832    async fn a_cut_mid_stream_reconnects_at_the_cursor_losing_and_duplicating_nothing() {
833        let recorder = Recorder::with([
834            // First attach: two output frames, then the body ends with no exit event.
835            Reply::Chunks(200, vec![output(0, b"AAAA\n"), output(5, b"BBBB\n")]),
836            // Second attach: the daemon replays from the requested offset.
837            Reply::Chunks(200, vec![output(10, b"CCCC\n"), exit(15)]),
838        ]);
839        let (session, _, _) = session_with(Arc::clone(&recorder));
840        let handle = session.exec("resume");
841
842        let (bytes, events) = collect(&handle, StreamOptions::default()).await;
843
844        assert_eq!(
845            String::from_utf8_lossy(&bytes),
846            "AAAA\nBBBB\nCCCC\n",
847            "the two attaches did not reconstruct the output, so the resume \
848             duplicated or lost bytes at the seam"
849        );
850        assert!(
851            events.iter().all(Result::is_ok),
852            "a cut surfaced as an error rather than a reconnect: {events:#?}"
853        );
854        assert!(
855            matches!(events.last(), Some(Ok(ExecEvent::Exit(_)))),
856            "the stream did not end on the terminal event: {events:#?}"
857        );
858
859        let seen = recorder.requests();
860        assert_eq!(
861            seen.len(),
862            2,
863            "the cut did not produce exactly one reconnect"
864        );
865        assert_eq!(requested_offset(&seen[0]), 0);
866        assert_eq!(
867            requested_offset(&seen[1]),
868            10,
869            "the reconnect asked for the wrong byte, so the seam is wrong"
870        );
871    }
872
873    /// A stream that ends *with* an exit event does not reconnect.
874    ///
875    /// The mirror of the test above, and the reason the transport is framed: the two
876    /// cases are the same byte count and differ only in the terminal event.
877    #[tokio::test(start_paused = true)]
878    async fn a_stream_that_ended_with_an_exit_event_does_not_reconnect() {
879        let recorder = Recorder::with([Reply::Chunks(200, vec![output(0, b"hi\n"), exit(3)])]);
880        let (session, _, _) = session_with(Arc::clone(&recorder));
881        let handle = session.exec("finished");
882
883        let (bytes, _) = collect(&handle, StreamOptions::default()).await;
884        assert_eq!(bytes, b"hi\n");
885        assert_eq!(
886            recorder.requests().len(),
887            1,
888            "a finished stream was reattached, which would replay a completed exec \
889             forever"
890        );
891    }
892
893    /// A gap advances the cursor past the evicted range.
894    ///
895    /// Without this the reconnect asks for bytes the daemon has already dropped and is
896    /// told about the same gap forever — a livelock that looks like a slow stream.
897    #[tokio::test(start_paused = true)]
898    async fn a_gap_advances_the_cursor_so_a_reconnect_does_not_ask_for_evicted_bytes() {
899        let recorder = Recorder::with([
900            Reply::Chunks(200, vec![output(0, b"AA"), gap(2, 900)]),
901            Reply::Chunks(200, vec![output(900, b"ZZ"), exit(902)]),
902        ]);
903        let (session, _, _) = session_with(Arc::clone(&recorder));
904        let handle = session.exec("lagged");
905
906        let (bytes, events) = collect(&handle, StreamOptions::default()).await;
907        assert_eq!(bytes, b"AAZZ");
908        assert!(
909            events
910                .iter()
911                .any(|event| matches!(event, Ok(ExecEvent::Gap { from: 2, to: 900 }))),
912            "the gap was swallowed, so a truncated log reads as a complete one: \
913             {events:#?}"
914        );
915        assert_eq!(
916            requested_offset(&recorder.requests()[1]),
917            900,
918            "the reconnect asked for bytes the daemon had already evicted"
919        );
920    }
921
922    /// `error_on_gap` turns a gap into a typed error and ends the stream.
923    #[tokio::test(start_paused = true)]
924    async fn error_on_gap_surfaces_the_lost_range_as_an_error() {
925        let recorder = Recorder::with([Reply::Chunks(200, vec![output(0, b"AA"), gap(2, 900)])]);
926        let (session, _, _) = session_with(recorder);
927        let handle = session.exec("lagged");
928
929        let (_, events) = collect(
930            &handle,
931            StreamOptions {
932                error_on_gap: true,
933                ..StreamOptions::default()
934            },
935        )
936        .await;
937        let err = events
938            .last()
939            .expect("an event")
940            .as_ref()
941            .expect_err("the gap is an error");
942        assert_eq!(err.wire_kind(), Some(WireKind::OutputGap));
943        assert!(err.to_string().contains("[2, 900)"), "{err}");
944    }
945
946    /// A transport failure opening the attach is reconnected through, and the mint that
947    /// the reconnect performs is what carries a fresh token mid-stream (TRAP-9).
948    #[tokio::test(start_paused = true)]
949    async fn a_failed_attach_is_retried_and_the_reconnect_re_mints_an_expired_token() {
950        let recorder = Recorder::with([
951            Reply::Cut("connection reset"),
952            Reply::Chunks(200, vec![output(0, b"ok\n"), exit(3)]),
953        ]);
954        let (session, auth, clock) = session_with(Arc::clone(&recorder));
955        let handle = session.exec("retried");
956
957        // Age the cached token past the refresh window before the stream starts, so the
958        // attach has to mint. The reconnect then crosses the window again.
959        clock.advance(super::super::DEFAULT_REFRESH_AFTER + Duration::from_secs(1));
960
961        let (bytes, events) = collect(&handle, StreamOptions::default()).await;
962        assert_eq!(bytes, b"ok\n");
963        assert!(events.iter().all(Result::is_ok), "{events:#?}");
964        assert_eq!(
965            auth.mint_count(),
966            1,
967            "the attach did not mint inside the request path"
968        );
969        assert_eq!(recorder.requests().len(), 2);
970    }
971
972    /// A 404 is fatal even with reconnect on: the entry was collected, so reattaching
973    /// can never succeed.
974    #[tokio::test(start_paused = true)]
975    async fn a_collected_exec_ends_the_stream_rather_than_reconnecting_forever() {
976        let recorder = Recorder::with([Reply::Body(404, b"{\"error\":\"unknown_exec\"}".to_vec())]);
977        let (session, _, _) = session_with(Arc::clone(&recorder));
978        let handle = session.exec("gone");
979
980        let (_, events) = collect(&handle, StreamOptions::default()).await;
981        assert_eq!(events.len(), 1);
982        let err = events[0].as_ref().expect_err("404 is an error");
983        assert_eq!(err.wire_kind(), Some(WireKind::NotFound));
984        assert_eq!(
985            recorder.requests().len(),
986            1,
987            "a fatal status was reattached, which can never succeed"
988        );
989    }
990
991    /// The reconnect budget is bounded, and running out is reported with the last good
992    /// offset rather than as a silent end.
993    #[tokio::test(start_paused = true)]
994    async fn a_stream_that_never_completes_gives_up_naming_its_last_good_offset() {
995        let mut replies = vec![Reply::Chunks(200, vec![output(0, b"AA")])];
996        for _ in 0..3 {
997            replies.push(Reply::Chunks(200, vec![]));
998        }
999        let recorder = Recorder::with(replies);
1000        let (session, _, _) = session_with(Arc::clone(&recorder));
1001        let handle = session.exec("flaky");
1002
1003        let (bytes, events) = collect(
1004            &handle,
1005            StreamOptions {
1006                max_reconnects: 2,
1007                ..StreamOptions::default()
1008            },
1009        )
1010        .await;
1011        assert_eq!(bytes, b"AA");
1012        let err = events
1013            .last()
1014            .expect("an event")
1015            .as_ref()
1016            .expect_err("running out of reconnects is an error");
1017        assert!(err.retryable(), "the exec is still alive server-side");
1018        assert!(
1019            err.to_string().contains("last good offset 2"),
1020            "the give-up must name where to resume: {err}"
1021        );
1022        assert_eq!(recorder.requests().len(), 3, "the budget was not respected");
1023    }
1024
1025    /// `reconnect: false` ends the stream at the cut, for a caller doing its own.
1026    #[tokio::test(start_paused = true)]
1027    async fn reconnect_off_ends_the_stream_at_the_cut() {
1028        let recorder = Recorder::with([Reply::Chunks(200, vec![output(0, b"AA")])]);
1029        let (session, _, _) = session_with(Arc::clone(&recorder));
1030        let handle = session.exec("once");
1031
1032        let (bytes, events) = collect(
1033            &handle,
1034            StreamOptions {
1035                reconnect: false,
1036                ..StreamOptions::default()
1037            },
1038        )
1039        .await;
1040        assert_eq!(bytes, b"AA");
1041        assert!(events.iter().all(Result::is_ok));
1042        assert_eq!(recorder.requests().len(), 1);
1043    }
1044
1045    /// A non-zero starting offset is what a second process resuming a stream passes.
1046    #[tokio::test(start_paused = true)]
1047    async fn a_stream_can_start_at_an_offset_a_previous_process_left_off_at() {
1048        let recorder = Recorder::with([Reply::Chunks(200, vec![output(64, b"tail"), exit(68)])]);
1049        let (session, _, _) = session_with(Arc::clone(&recorder));
1050        let handle = session.exec("resumed");
1051
1052        let (bytes, _) = collect(
1053            &handle,
1054            StreamOptions {
1055                offset: 64,
1056                ..StreamOptions::default()
1057            },
1058        )
1059        .await;
1060        assert_eq!(bytes, b"tail");
1061        assert_eq!(requested_offset(&recorder.last()), 64);
1062    }
1063
1064    /// `wait_and_ack` returns the ack's result, which is the one carrying the output.
1065    ///
1066    /// Returning the poll's instead is a silent empty-output bug: a poll after the ack
1067    /// reports `acked` with nothing in it.
1068    #[tokio::test(start_paused = true)]
1069    async fn wait_and_ack_returns_the_ack_result_that_carries_the_output() {
1070        let recorder = Recorder::with([
1071            Reply::ok(serde_json::json!({"exec_id":"e1","phase":"running"})),
1072            Reply::ok(serde_json::json!({"exec_id":"e1","phase":"exited"})),
1073            Reply::ok(serde_json::json!({
1074                "exec_id":"e1","phase":"exited","exit_code":0,"signal":null,
1075                "stdout":"the output","stderr":"","truncated":false,
1076                "writers_may_be_alive":false
1077            })),
1078        ]);
1079        let (session, _, _) = session_with(Arc::clone(&recorder));
1080        let handle = session.exec("e1");
1081
1082        let result = handle
1083            .wait_and_ack(Duration::from_secs(30))
1084            .await
1085            .expect("waits then acks");
1086        assert_eq!(result.stdout(), "the output");
1087        assert!(result.succeeded());
1088
1089        let seen = recorder.requests();
1090        assert_eq!(seen.len(), 3);
1091        assert_eq!(seen[2].path, "/v1/exec/e1/ack");
1092        assert_eq!(seen[2].method, "POST");
1093    }
1094
1095    /// An already-acked exec is not acked twice: the second ack is a 409, and the phase
1096    /// is what tells the difference before the request goes out.
1097    #[tokio::test(start_paused = true)]
1098    async fn wait_and_ack_does_not_ack_an_already_acked_exec() {
1099        let recorder = Recorder::with([Reply::ok(serde_json::json!({
1100            "exec_id":"e1","phase":"acked","exit_code":0,"signal":null,
1101            "stdout":"","stderr":"","truncated":false,"writers_may_be_alive":false
1102        }))]);
1103        let (session, _, _) = session_with(Arc::clone(&recorder));
1104
1105        session
1106            .exec("e1")
1107            .wait_and_ack(Duration::from_secs(30))
1108            .await
1109            .expect("an acked exec is done");
1110        assert_eq!(
1111            recorder.requests().len(),
1112            1,
1113            "a second ack went out, which the daemon answers 409"
1114        );
1115    }
1116
1117    /// A retryable failure mid-wait is swallowed, because polling is read-only and
1118    /// repeating it costs nothing.
1119    #[tokio::test(start_paused = true)]
1120    async fn a_dropped_connection_mid_wait_is_retried_rather_than_raised() {
1121        let recorder = Recorder::with([
1122            Reply::Cut("connection reset"),
1123            Reply::ok(serde_json::json!({
1124                "exec_id":"e1","phase":"exited","exit_code":3,"signal":null,
1125                "stdout":"","stderr":"boom","truncated":false,"writers_may_be_alive":false
1126            })),
1127        ]);
1128        let (session, _, _) = session_with(recorder);
1129
1130        let result = session
1131            .exec("e1")
1132            .wait(Duration::from_secs(30))
1133            .await
1134            .expect("the retry lands");
1135        assert_eq!(result.exit_code(), Some(3));
1136        assert!(!result.succeeded());
1137        assert_eq!(result.stderr(), "boom");
1138    }
1139
1140    /// A wait that times out says the exec is untouched, because it is.
1141    #[tokio::test(start_paused = true)]
1142    async fn a_wait_timeout_says_the_record_can_be_re_polled() {
1143        let replies: Vec<Reply> = (0..10)
1144            .map(|_| Reply::ok(serde_json::json!({"exec_id":"e1","phase":"running"})))
1145            .collect();
1146        let recorder = Recorder::with(replies);
1147        let (session, _, _) = session_with(recorder);
1148
1149        let err = session
1150            .exec("e1")
1151            .wait(Duration::from_secs(3))
1152            .await
1153            .expect_err("the exec never finishes");
1154        assert_eq!(err.wire_kind(), Some(WireKind::ExecTimeout));
1155        assert_eq!(err.kind(), ErrorKind::Timeout);
1156        assert!(err.to_string().contains("still running"), "{err}");
1157        assert!(err.to_string().contains("re-polled"), "{err}");
1158    }
1159
1160    /// A stdin write base64s its data and names the eof signal, and an empty write with
1161    /// eof is a valid close.
1162    #[tokio::test]
1163    async fn a_stdin_write_carries_base64_and_the_eof_signal() {
1164        let recorder = Recorder::with([
1165            Reply::ok(serde_json::json!({"exec_id":"e1","written":3,"eof":true})),
1166            Reply::ok(serde_json::json!({"exec_id":"e1","written":0,"eof":true})),
1167        ]);
1168        let (session, _, _) = session_with(Arc::clone(&recorder));
1169        let handle = session.exec("e1");
1170
1171        let ack = handle.write_stdin(b"go\n", true).await.expect("writes");
1172        assert_eq!(ack.written, 3);
1173        assert!(ack.eof);
1174        let body: serde_json::Value =
1175            serde_json::from_slice(&recorder.last().body).expect("json body");
1176        assert_eq!(body["data_b64"], "Z28K");
1177        assert_eq!(body["signal"], "eof");
1178
1179        handle.close_stdin().await.expect("closes");
1180        let body: serde_json::Value =
1181            serde_json::from_slice(&recorder.last().body).expect("json body");
1182        assert!(
1183            body.get("data_b64").is_none_or(serde_json::Value::is_null),
1184            "a bare close must not send an empty data field: {body}"
1185        );
1186        assert_eq!(body["signal"], "eof");
1187    }
1188
1189    /// `kill` reports whether anything was signalled, and `false` with a 200 is a real
1190    /// answer rather than a failure.
1191    #[tokio::test]
1192    async fn kill_reports_false_for_a_group_that_had_already_exited() {
1193        let recorder = Recorder::with([
1194            Reply::ok(serde_json::json!({"exec_id":"e1","killed":true})),
1195            Reply::ok(serde_json::json!({"exec_id":"e1","killed":false})),
1196        ]);
1197        let (session, _, _) = session_with(Arc::clone(&recorder));
1198
1199        assert!(session.kill("e1").await.expect("kills"));
1200        assert!(!session.kill("e1").await.expect("already gone"));
1201        assert_eq!(recorder.last().path, "/v1/exec/e1/kill");
1202    }
1203
1204    /// A running poll has no outcome, and that absence is not an error — it is the shape
1205    /// of every poll before the last one.
1206    #[tokio::test]
1207    async fn a_running_poll_carries_no_outcome_and_is_not_an_error() {
1208        let recorder = Recorder::with([Reply::ok(
1209            serde_json::json!({"exec_id":"e1","phase":"running"}),
1210        )]);
1211        let (session, _, _) = session_with(recorder);
1212
1213        let result = session.exec("e1").poll().await.expect("polls");
1214        assert!(!result.done());
1215        assert!(result.outcome.is_none());
1216        assert_eq!(result.stdout(), "");
1217        assert_eq!(result.exit_code(), None);
1218        assert!(!result.succeeded());
1219    }
1220
1221    // ── the callback driver (`for_each_event`) ───────────────────────────────
1222    //
1223    // Four tests, mirroring the four `stream_with` properties that matter to a caller: the
1224    // events arrive in order, `Break` stops the drive, a reconnect still joins at the
1225    // cursor, and a cut without an exit event is *reported as a cut*. They are separate
1226    // tests rather than a re-run of the loop above on purpose — the driver is what the CLI
1227    // and (next) the bindings actually call, and "the `Stream` version works" is not a
1228    // statement about it.
1229
1230    /// Drives a stream with `for_each_event` and returns what the callback saw.
1231    async fn drive(
1232        handle: &ExecHandle,
1233        options: StreamOptions,
1234    ) -> (Vec<ExecEvent>, Result<StreamEnd, Error>) {
1235        let mut seen = Vec::new();
1236        let end = handle
1237            .for_each_event(options, |event| {
1238                seen.push(event);
1239                std::ops::ControlFlow::Continue(())
1240            })
1241            .await;
1242        (seen, end)
1243    }
1244
1245    /// **Events reach the callback in wire order, and the end names the terminal event.**
1246    ///
1247    /// Order is the property a callback API can silently break where a `Stream` cannot —
1248    /// buffering to hand over in a batch would reverse or coalesce, and the reader of a
1249    /// child's stdout would see the second chunk first. Asserted on the *offsets* rather
1250    /// than only on the reassembled bytes, because two chunks concatenated the wrong way
1251    /// round still yield the right total length.
1252    ///
1253    /// **Falsification** — push events onto a `Vec` inside `for_each_event` and call the
1254    /// callback after the loop, and the reason still reads `Exited` while the offsets come
1255    /// out of order only if the wire order was wrong; swap the two `Reply` chunks and this
1256    /// is red on `[0, 5]`. Verified: reversing the callback's argument order (delivering
1257    /// the second frame first) fails the offsets assertion.
1258    #[tokio::test(start_paused = true)]
1259    async fn the_driver_hands_every_event_to_the_callback_in_order() {
1260        let recorder = Recorder::with([Reply::Chunks(
1261            200,
1262            vec![output(0, b"AAAAA"), output(5, b"BBBBB"), exit(10)],
1263        )]);
1264        let (session, _, _) = session_with(Arc::clone(&recorder));
1265        let handle = session.exec("ordered");
1266
1267        let (seen, end) = drive(&handle, StreamOptions::default()).await;
1268        let end = end.expect("the stream completes");
1269
1270        let offsets: Vec<u64> = seen
1271            .iter()
1272            .filter_map(|event| match event {
1273                ExecEvent::Output { offset, .. } => Some(*offset),
1274                _ => None,
1275            })
1276            .collect();
1277        assert_eq!(offsets, [0, 5], "the callback saw the frames out of order");
1278        assert!(
1279            matches!(seen.last(), Some(ExecEvent::Exit(_))),
1280            "the terminal event has to be delivered, not merely observed: {seen:#?}"
1281        );
1282        assert_eq!(
1283            end,
1284            StreamEnd {
1285                reason: EndReason::Exited,
1286                cursor: 10,
1287            },
1288            "the end has to name the exit event and the total"
1289        );
1290        assert_eq!(recorder.requests().len(), 1);
1291    }
1292
1293    /// **`ControlFlow::Break` stops the drive, and says so rather than reporting a cut.**
1294    ///
1295    /// Two assertions and the second is the load-bearing one. Stopping has to be
1296    /// distinguishable from a truncated stream: both end without an exit event, and a
1297    /// caller that read `Cut` after its own `Break` would report "the command's outcome is
1298    /// unknown" about a command it chose not to watch. The cursor is where the callback
1299    /// stopped, so passing it back as `--from-offset` resumes exactly there.
1300    ///
1301    /// **Falsification** — return `EndReason::Cut` for the break arm and the reason
1302    /// assertion is red; drop the `is_break()` check and the drive runs to the exit event,
1303    /// so `seen.len()` reads 3 instead of 1. Verified: removing the early return makes the
1304    /// event-count assertion fail with 3.
1305    #[tokio::test(start_paused = true)]
1306    async fn control_flow_break_stops_the_stream_and_is_not_reported_as_a_cut() {
1307        let recorder = Recorder::with([Reply::Chunks(
1308            200,
1309            vec![output(0, b"first\n"), output(6, b"second\n"), exit(13)],
1310        )]);
1311        let (session, _, _) = session_with(Arc::clone(&recorder));
1312        let handle = session.exec("halted");
1313
1314        let mut seen = Vec::new();
1315        let end = handle
1316            .for_each_event(StreamOptions::default(), |event| {
1317                seen.push(event);
1318                // Stop on the first event, which is what a consumer with a `head -1` does.
1319                std::ops::ControlFlow::Break(())
1320            })
1321            .await
1322            .expect("stopping is not a failure");
1323
1324        assert_eq!(
1325            seen.len(),
1326            1,
1327            "the drive kept going after Break, so a caller that stopped reading is still \
1328             being read to: {seen:#?}"
1329        );
1330        assert_eq!(
1331            end,
1332            StreamEnd {
1333                reason: EndReason::Stopped,
1334                cursor: 6,
1335            },
1336            "a caller's own stop must not read as a cut stream, and the cursor is where it \
1337             stopped"
1338        );
1339    }
1340
1341    /// **A cut mid-drive still reconnects at the cursor, losing and duplicating nothing.**
1342    ///
1343    /// The same property as the `Stream` version's first test, asserted through the
1344    /// driver, because that is the path the CLI takes: if the driver dropped the cursor the
1345    /// reconnect would ask for byte zero and the caller would see `AAAA` twice, and the
1346    /// total byte count would look right. So the verdict is the reassembled bytes *and*
1347    /// the offset the second attach asked for.
1348    ///
1349    /// **Falsification** — seed the driver's `cursor` from zero instead of
1350    /// `options.offset`, or drop the `next.cursor()` read, and the reported end cursor is
1351    /// wrong while the bytes still join (the machine's own cursor is what drives the
1352    /// reconnect). Verified: replacing `next.cursor()` with `None` fails the `StreamEnd`
1353    /// assertion at cursor 0.
1354    #[tokio::test(start_paused = true)]
1355    async fn the_driver_reconnects_at_the_cursor_across_a_cut() {
1356        let recorder = Recorder::with([
1357            Reply::Chunks(200, vec![output(0, b"AAAA\n"), output(5, b"BBBB\n")]),
1358            Reply::Chunks(200, vec![output(10, b"CCCC\n"), exit(15)]),
1359        ]);
1360        let (session, _, _) = session_with(Arc::clone(&recorder));
1361        let handle = session.exec("resumed-driver");
1362
1363        let (seen, end) = drive(&handle, StreamOptions::default()).await;
1364        let end = end.expect("the reconnect lands");
1365
1366        let mut bytes = Vec::new();
1367        for event in &seen {
1368            if let ExecEvent::Output { data, .. } = event {
1369                bytes.extend_from_slice(data);
1370            }
1371        }
1372        assert_eq!(
1373            String::from_utf8_lossy(&bytes),
1374            "AAAA\nBBBB\nCCCC\n",
1375            "the two attaches did not reconstruct the output through the driver"
1376        );
1377        assert_eq!(end.reason, EndReason::Exited);
1378        assert_eq!(end.cursor, 15);
1379
1380        let seen_requests = recorder.requests();
1381        assert_eq!(seen_requests.len(), 2, "the cut produced no reconnect");
1382        assert_eq!(
1383            requested_offset(&seen_requests[1]),
1384            10,
1385            "the reconnect asked for the wrong byte, so the seam is wrong"
1386        );
1387    }
1388
1389    /// **A body that ended with no exit event and no reconnect is reported as `Cut`.**
1390    ///
1391    /// The one ending a byte count cannot detect, and the reason this returns a typed
1392    /// reason at all: `reconnect: false` is what a caller doing its own reconnection
1393    /// passes, and it must be able to tell "the command finished" from "the connection
1394    /// dropped and you told me not to retry". `cursor` is where its own reconnect starts.
1395    ///
1396    /// **Falsification** — report `EndReason::Exited` for the `advance` returned `None`
1397    /// arm and this is red on the reason; a caller acting on that would report exit code
1398    /// 0 for a command whose outcome nobody knows. Verified.
1399    #[tokio::test(start_paused = true)]
1400    async fn a_cut_with_reconnect_off_ends_the_drive_naming_the_cut() {
1401        let recorder = Recorder::with([Reply::Chunks(200, vec![output(0, b"partial")])]);
1402        let (session, _, _) = session_with(Arc::clone(&recorder));
1403        let handle = session.exec("truncated");
1404
1405        let (seen, end) = drive(
1406            &handle,
1407            StreamOptions {
1408                reconnect: false,
1409                ..StreamOptions::default()
1410            },
1411        )
1412        .await;
1413        let end = end.expect("a cut is not an error when reconnect is off");
1414
1415        assert_eq!(seen.len(), 1);
1416        assert!(
1417            !seen.iter().any(|event| matches!(event, ExecEvent::Exit(_))),
1418            "there was no terminal event to deliver"
1419        );
1420        assert_eq!(
1421            end,
1422            StreamEnd {
1423                reason: EndReason::Cut,
1424                cursor: 7,
1425            },
1426            "a stream with no exit event is a cut, and reporting anything else would let a \
1427             caller pass a CI step on output it never received"
1428        );
1429        assert_eq!(recorder.requests().len(), 1);
1430    }
1431
1432    /// A fatal error ends the drive with `Err`, and the events already delivered stay
1433    /// delivered.
1434    ///
1435    /// The asymmetry `for_each_event`'s docs state, asserted: a 404 mid-stream is fatal
1436    /// (the entry was collected, so reattaching can never succeed) and there is nothing to
1437    /// unwind the bytes a callback already wrote with.
1438    #[tokio::test(start_paused = true)]
1439    async fn a_fatal_status_ends_the_drive_with_an_error() {
1440        let recorder = Recorder::with([Reply::Body(404, b"{\"error\":\"unknown_exec\"}".to_vec())]);
1441        let (session, _, _) = session_with(Arc::clone(&recorder));
1442        let handle = session.exec("collected");
1443
1444        let (seen, end) = drive(&handle, StreamOptions::default()).await;
1445        assert!(seen.is_empty(), "nothing was delivered: {seen:#?}");
1446        let error = end.expect_err("a 404 on the attach is fatal");
1447        assert_eq!(error.wire_kind(), Some(WireKind::NotFound));
1448        assert_eq!(
1449            recorder.requests().len(),
1450            1,
1451            "a fatal status was reattached, which can never succeed"
1452        );
1453    }
1454
1455    // ── the async callback driver (`for_each_event_async`) ────────────────────
1456    //
1457    // Four tests. Three mirror `for_each_event`'s — order, `Break` stops, a reconnect joins at
1458    // the cursor — because "the sync driver works" is not a statement about this one even though
1459    // the sync driver is now written in terms of it: the delegation could be inverted tomorrow,
1460    // and the bindings call *this* method. The fourth is the property only an awaited callback
1461    // has, and it is the reason the overload exists at all: a callback that awaits between
1462    // events loses none of them.
1463
1464    /// Drives a stream with the async driver and returns what the callback saw.
1465    async fn drive_async(
1466        handle: &ExecHandle,
1467        options: StreamOptions,
1468    ) -> (Vec<ExecEvent>, Result<StreamEnd, Error>) {
1469        let mut seen = Vec::new();
1470        let end = handle
1471            .for_each_event_async(options, |event| {
1472                seen.push(event);
1473                std::future::ready(std::ops::ControlFlow::Continue(()))
1474            })
1475            .await;
1476        (seen, end)
1477    }
1478
1479    /// **Events reach an async callback in wire order, and the end names the terminal event.**
1480    ///
1481    /// Asserted on the *offsets* rather than only on the reassembled bytes, because two chunks
1482    /// concatenated the wrong way round still yield the right total length. Order is the
1483    /// property an awaited callback could break where the sync one cannot: a driver that
1484    /// launched each callback future without awaiting it, or awaited them out of order, would
1485    /// deliver a child's second stdout chunk before its first.
1486    ///
1487    /// **Falsification** — remove the `.await` on `on_event(event)` and the loop does not
1488    /// compile; replace it with a driver that collects the futures and joins them at the end
1489    /// and the offsets come out in completion order rather than wire order. Verified by
1490    /// reversing the `Reply::Chunks` frame order, which fails this assertion on `[5, 0]`.
1491    #[tokio::test(start_paused = true)]
1492    async fn the_async_driver_hands_every_event_to_the_callback_in_order() {
1493        let recorder = Recorder::with([Reply::Chunks(
1494            200,
1495            vec![output(0, b"AAAAA"), output(5, b"BBBBB"), exit(10)],
1496        )]);
1497        let (session, _, _) = session_with(Arc::clone(&recorder));
1498        let handle = session.exec("ordered-async");
1499
1500        let (seen, end) = drive_async(&handle, StreamOptions::default()).await;
1501        let end = end.expect("the stream completes");
1502
1503        let offsets: Vec<u64> = seen
1504            .iter()
1505            .filter_map(|event| match event {
1506                ExecEvent::Output { offset, .. } => Some(*offset),
1507                _ => None,
1508            })
1509            .collect();
1510        assert_eq!(offsets, [0, 5], "the callback saw the frames out of order");
1511        assert!(
1512            matches!(seen.last(), Some(ExecEvent::Exit(_))),
1513            "the terminal event has to be delivered, not merely observed: {seen:#?}"
1514        );
1515        assert_eq!(
1516            end,
1517            StreamEnd {
1518                reason: EndReason::Exited,
1519                cursor: 10,
1520            },
1521            "the end has to name the exit event and the total"
1522        );
1523        assert_eq!(recorder.requests().len(), 1);
1524    }
1525
1526    /// **`ControlFlow::Break` from an async callback stops the drive and is not a cut.**
1527    ///
1528    /// The load-bearing half is the reason: stopping has to be distinguishable from a truncated
1529    /// stream, because both end without an exit event. A binding whose host-language iterator
1530    /// was dropped answers `Break` here — a failed channel send — and it must not read as "the
1531    /// command's outcome is unknown".
1532    ///
1533    /// **Falsification** — return `EndReason::Cut` from the break arm and the reason assertion
1534    /// is red; drop the `is_break()` check and the drive runs to the exit event, so `seen.len()`
1535    /// reads 3 instead of 1. Verified: deleting the early return fails the event-count assertion
1536    /// with 3.
1537    #[tokio::test(start_paused = true)]
1538    async fn an_async_callback_breaking_stops_the_stream_and_is_not_reported_as_a_cut() {
1539        let recorder = Recorder::with([Reply::Chunks(
1540            200,
1541            vec![output(0, b"first\n"), output(6, b"second\n"), exit(13)],
1542        )]);
1543        let (session, _, _) = session_with(Arc::clone(&recorder));
1544        let handle = session.exec("halted-async");
1545
1546        let mut seen = Vec::new();
1547        let end = handle
1548            .for_each_event_async(StreamOptions::default(), |event| {
1549                seen.push(event);
1550                // Stop on the first event, which is what a dropped binding iterator does.
1551                std::future::ready(std::ops::ControlFlow::Break(()))
1552            })
1553            .await
1554            .expect("stopping is not a failure");
1555
1556        assert_eq!(
1557            seen.len(),
1558            1,
1559            "the drive kept going after Break, so a consumer that stopped reading is still \
1560             being read to: {seen:#?}"
1561        );
1562        assert_eq!(
1563            end,
1564            StreamEnd {
1565                reason: EndReason::Stopped,
1566                cursor: 6,
1567            },
1568            "a consumer's own stop must not read as a cut stream, and the cursor is where it \
1569             stopped"
1570        );
1571    }
1572
1573    /// **A cut mid-drive still reconnects at the cursor through the async driver.**
1574    ///
1575    /// The same seam property, asserted through the path the bindings take. If the driver lost
1576    /// the cursor the reconnect would ask for byte zero and the consumer would see `AAAA` twice
1577    /// while the total byte count still looked plausible — so the verdict is the reassembled
1578    /// bytes *and* the offset the second attach asked for.
1579    ///
1580    /// **Falsification** — seed `cursor` from zero instead of `options.offset`, or drop the
1581    /// `next.cursor()` read, and the reported end cursor is wrong while the bytes still join.
1582    /// Verified: replacing `next.cursor()` with `None` fails the end-cursor assertion at 0.
1583    #[tokio::test(start_paused = true)]
1584    async fn the_async_driver_reconnects_at_the_cursor_across_a_cut() {
1585        let recorder = Recorder::with([
1586            Reply::Chunks(200, vec![output(0, b"AAAA\n"), output(5, b"BBBB\n")]),
1587            Reply::Chunks(200, vec![output(10, b"CCCC\n"), exit(15)]),
1588        ]);
1589        let (session, _, _) = session_with(Arc::clone(&recorder));
1590        let handle = session.exec("resumed-async");
1591
1592        let (seen, end) = drive_async(&handle, StreamOptions::default()).await;
1593        let end = end.expect("the reconnect lands");
1594
1595        let mut bytes = Vec::new();
1596        for event in &seen {
1597            if let ExecEvent::Output { data, .. } = event {
1598                bytes.extend_from_slice(data);
1599            }
1600        }
1601        assert_eq!(
1602            String::from_utf8_lossy(&bytes),
1603            "AAAA\nBBBB\nCCCC\n",
1604            "the two attaches did not reconstruct the output through the async driver"
1605        );
1606        assert_eq!(end.reason, EndReason::Exited);
1607        assert_eq!(end.cursor, 15);
1608
1609        let seen_requests = recorder.requests();
1610        assert_eq!(seen_requests.len(), 2, "the cut produced no reconnect");
1611        assert_eq!(
1612            requested_offset(&seen_requests[1]),
1613            10,
1614            "the reconnect asked for the wrong byte, so the seam is wrong"
1615        );
1616    }
1617
1618    /// **A callback that awaits between events loses none of them.**
1619    ///
1620    /// The one property only this overload has, set up as the exact shape both bindings use: a
1621    /// **capacity-1** `mpsc` channel the callback `send`s into and a separate consumer drains,
1622    /// with the consumer deliberately slower than the producer so the channel is full for every
1623    /// event after the first. That is the configuration the sync driver could not serve — its
1624    /// only available send is `blocking_send`, which would park the runtime worker the driver
1625    /// itself is running on — and it is why `microvms-py` and `microvms-js` kept the `Stream`
1626    /// path until this method existed.
1627    ///
1628    /// Five events go in and five come out, in wire order, terminal event included. The
1629    /// verdict is the sequence and not a count: a driver that dropped an event under
1630    /// backpressure would still report `Exited` with the right cursor, because the cursor is the
1631    /// state machine's and not the callback's.
1632    ///
1633    /// **Falsification** — replace the awaited `send` with `try_send` and ignore the failure
1634    /// (the shape of a driver that does not respect backpressure) and this is red with three
1635    /// of five events delivered. Verified.
1636    #[tokio::test(start_paused = true)]
1637    async fn an_async_callback_that_awaits_between_events_loses_none_of_them() {
1638        let recorder = Recorder::with([Reply::Chunks(
1639            200,
1640            vec![
1641                output(0, b"AA"),
1642                output(2, b"BB"),
1643                output(4, b"CC"),
1644                output(6, b"DD"),
1645                exit(8),
1646            ],
1647        )]);
1648        let (session, _, _) = session_with(Arc::clone(&recorder));
1649        let handle = session.exec("backpressured");
1650
1651        // Capacity 1, the bindings' own bound: the SSE body is the backpressure signal, and
1652        // buffering here would defeat the cursor the core reconnects at.
1653        let (sender, mut receiver) = tokio::sync::mpsc::channel::<String>(1);
1654        let consumer = tokio::spawn(async move {
1655            let mut drained = Vec::new();
1656            while let Some(described) = receiver.recv().await {
1657                // Slower than the producer, so every send after the first waits.
1658                tokio::time::sleep(Duration::from_millis(50)).await;
1659                drained.push(described);
1660            }
1661            drained
1662        });
1663
1664        let end = handle
1665            .for_each_event_async(StreamOptions::default(), |event| {
1666                let described = match &event {
1667                    ExecEvent::Output { offset, data, .. } => {
1668                        format!("out@{offset}:{}", String::from_utf8_lossy(data))
1669                    }
1670                    ExecEvent::Gap { from, to } => format!("gap@{from}..{to}"),
1671                    ExecEvent::Exit(exit) => format!("exit:{:?}", exit.exit_code),
1672                };
1673                // Cloned per event rather than borrowed, which is what the plain-`Fut`
1674                // signature requires and what both bindings do. One atomic increment.
1675                let sender = sender.clone();
1676                async move {
1677                    match sender.send(described).await {
1678                        Ok(()) => std::ops::ControlFlow::Continue(()),
1679                        // A closed receiver is the dropped-iterator case, not this path.
1680                        Err(_) => std::ops::ControlFlow::Break(()),
1681                    }
1682                }
1683            })
1684            .await
1685            .expect("the stream completes even though the consumer lags");
1686        // Closing the sender is what ends the consumer's `recv` loop.
1687        drop(sender);
1688
1689        let drained = consumer.await.expect("the consumer task does not panic");
1690        assert_eq!(
1691            drained,
1692            [
1693                "out@0:AA",
1694                "out@2:BB",
1695                "out@4:CC",
1696                "out@6:DD",
1697                "exit:Some(0)",
1698            ],
1699            "a lagging capacity-1 consumer lost or reordered events, which is the failure the \
1700             awaited callback exists to prevent"
1701        );
1702        assert_eq!(
1703            end,
1704            StreamEnd {
1705                reason: EndReason::Exited,
1706                cursor: 8,
1707            },
1708            "the ending must still name the exit event and the total"
1709        );
1710    }
1711}