alien-bindings 3.3.22

Alien direct in-process resource bindings
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
//! Speaking the sandbox agent protocol, once, for every backend that ships an agent.
//!
//! AWS and Kubernetes both talk to the same agent over HTTP and differ in exactly one thing:
//! how a request is authorized. AWS mints an endpoint token scoped to one MicroVM and an
//! explicit port set; Kubernetes claims a pod and presents a capability scoped to that sandbox. So
//! the transport is the trait and the protocol is written once over it.
//!
//! The decoding is the reason this is shared rather than copied. A body that ends without a
//! terminal frame is a **transport failure**, not a command that finished, and a stream that
//! quietly stopped would report a truncated response as a successful command.

use std::collections::BTreeMap;
use std::time::Duration;

use async_trait::async_trait;
use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine as _;
use futures::stream::BoxStream;
use futures::StreamExt;
use serde::Deserialize;
use serde_json::json;

use crate::error::{ErrorData, Result};
use crate::traits::{CommandOutput, JobError, JobExit, JobPoll, JobStart, RunCommandRequest};
use alien_error::{AlienError, Context, ContextError, IntoAlienError};

pub use alien_core::sandbox_process::AGENT_PORT;

/// Named once: `send` treats it as the one operation a 5xx must not be retried for.
const RUN_COMMAND: &str = "sandbox.runCommand";

const JOB_START: &str = "sandbox.jobStart";
const JOB_POLL: &str = "sandbox.jobPoll";
const JOB_CANCEL: &str = "sandbox.jobCancel";

/// How long a request to the agent may take to answer with its headers.
///
/// Bounds reaching the agent, not what it then streams: a command's own deadline governs its
/// output. Wrapped around `send()` alone rather than set as the request's timeout, which reqwest
/// runs until the whole body has arrived and so would cut off any command outliving it. A caller
/// cancelling a command waits for this request to settle before it can close the stream, so an
/// unbounded one would leave that cancel unable to complete.
#[cfg(not(test))]
const AGENT_RESPONSE_TIMEOUT: Duration = Duration::from_secs(60);
/// Short in tests so a stalled agent is exercised in milliseconds rather than waited out.
#[cfg(test)]
const AGENT_RESPONSE_TIMEOUT: Duration = Duration::from_millis(200);

/// How long past a command's own timeout the agent may still take to write a terminal frame.
///
/// A frozen guest — a paused sandbox, most of all — stops the agent's clock with it, so the
/// command deadline that would produce that frame never fires. Measured from the command's
/// declared timeout rather than from the last byte, because the agent sends no keepalive: silence
/// alone says nothing, while silence past the deadline the caller itself set says the sandbox
/// stopped running.
#[cfg(not(test))]
const TERMINAL_FRAME_GRACE: Duration = Duration::from_secs(60);
/// Short in tests so a frozen sandbox is exercised in milliseconds rather than waited out.
#[cfg(test)]
const TERMINAL_FRAME_GRACE: Duration = Duration::from_millis(200);

/// How a backend turns a sandbox id into an authorized request.
///
/// The only thing AWS and Kubernetes disagree on.
#[async_trait]
pub trait AgentTransport: Send + Sync + std::fmt::Debug {
    /// Builds a request to `path` on the sandbox's agent, carrying whatever authorizes it.
    async fn request(
        &self,
        sandbox_id: &str,
        method: reqwest::Method,
        path: &str,
    ) -> Result<reqwest::RequestBuilder>;

    /// Name used in errors, so a failure says which backend refused.
    fn provider(&self) -> &'static str;
}

/// A frame as the agent writes it.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase", tag = "t")]
enum AgentFrame {
    Stdout {
        seq: u64,
        data: String,
    },
    Stderr {
        seq: u64,
        data: String,
    },
    Exit {
        code: i32,
        #[serde(default)]
        truncated: bool,
    },
    Error {
        code: String,
        message: String,
    },
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ReadFileResponse {
    contents_base64: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct JobStartResponse {
    job_id: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct JobPollResponse {
    running: bool,
    #[serde(default)]
    frames: Vec<AgentFrame>,
    #[serde(default)]
    exit_code: Option<i32>,
    #[serde(default)]
    truncated: Option<bool>,
    #[serde(default)]
    error: Option<JobErrorResponse>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct JobErrorResponse {
    code: String,
    message: String,
}

/// Runs a command, streaming frames as the agent produces them.
pub async fn run_command<T: AgentTransport + ?Sized>(
    transport: &T,
    sandbox_id: &str,
    request: RunCommandRequest,
) -> Result<BoxStream<'static, Result<CommandOutput>>> {
    let body = exec_body(&request)?;

    let response = send(
        transport
            .request(sandbox_id, reqwest::Method::POST, "/v1/exec")
            .await?
            .json(&body),
        RUN_COMMAND,
    )
    .await?;

    Ok(frame_stream(
        response,
        transport.provider(),
        request.timeout,
    ))
}

/// Starts a command as a job the agent owns until it is polled to its end or cancelled.
pub async fn start_job<T: AgentTransport + ?Sized>(
    transport: &T,
    sandbox_id: &str,
    request: RunCommandRequest,
) -> Result<JobStart> {
    let body = exec_body(&request)?;

    let response = send(
        transport
            .request(sandbox_id, reqwest::Method::POST, "/v1/jobs/start")
            .await?
            .json(&body),
        JOB_START,
    )
    .await?;

    let started: JobStartResponse = response
        .json()
        .await
        .into_alien_error()
        .context(ErrorData::UnexpectedResponseFormat {
            provider: transport.provider().to_string(),
            binding_name: JOB_START.to_string(),
            field: "jobId".to_string(),
            response_json: "the agent returned a body this provider cannot parse".to_string(),
        })
        // The job is running and nothing can now poll or cancel it, so its end is unestablished
        // rather than merely unreadable.
        .context(unanswered(
            JOB_START,
            "the job started and its id could not be read",
        ))?;

    Ok(JobStart {
        job_id: started.job_id,
    })
}

/// Reads a job's output after `since_seq`, and its ending once it has one.
pub async fn poll_job<T: AgentTransport + ?Sized>(
    transport: &T,
    sandbox_id: &str,
    job_id: &str,
    since_seq: Option<u64>,
) -> Result<JobPoll> {
    let response = send(
        transport
            .request(sandbox_id, reqwest::Method::POST, "/v1/jobs/poll")
            .await?
            .json(&json!({ "jobId": job_id, "sinceSeq": since_seq })),
        JOB_POLL,
    )
    .await?;

    let JobPollResponse {
        running,
        frames,
        exit_code,
        truncated,
        error,
    } = response
        .json()
        .await
        .into_alien_error()
        .context(unanswered(JOB_POLL, "the poll's body could not be read"))?;

    Ok(JobPoll {
        running,
        frames: frames
            .into_iter()
            .map(|frame| frame.into_output(transport.provider()))
            .collect::<Result<Vec<_>>>()?,
        exit: exit_code.map(|code| JobExit {
            code,
            truncated: truncated.unwrap_or(false),
        }),
        error: error.map(|error| JobError {
            code: error.code,
            message: error.message,
        }),
    })
}

/// Cancels a job, stopping the command it runs.
pub async fn cancel_job<T: AgentTransport + ?Sized>(
    transport: &T,
    sandbox_id: &str,
    job_id: &str,
) -> Result<()> {
    send(
        transport
            .request(sandbox_id, reqwest::Method::POST, "/v1/jobs/cancel")
            .await?
            .json(&json!({ "jobId": job_id })),
        JOB_CANCEL,
    )
    .await?;

    Ok(())
}

/// The body `/v1/exec` and `/v1/jobs/start` both take.
fn exec_body(request: &RunCommandRequest) -> Result<serde_json::Value> {
    // Checked after conversion, not on the Duration: a sub-millisecond timeout is non-zero here
    // and floors to `timeoutMs: 0`, which the agent then refuses as invalid.
    if timeout_millis(request.timeout) == 0 {
        return Err(AlienError::new(ErrorData::SandboxCommandFailed {
            failure: "invalidRequest".to_string(),
            reason: "a command must carry a non-zero timeout".to_string(),
        }));
    }

    Ok(json!({
        "command": request.argv(),
        "timeoutMs": timeout_millis(request.timeout),
        "cwd": request.cwd,
        "env": request.env,
    }))
}

/// Reads a file out of the sandbox.
pub async fn read_file<T: AgentTransport + ?Sized>(
    transport: &T,
    sandbox_id: &str,
    path: &str,
) -> Result<Vec<u8>> {
    let response = send(
        transport
            .request(sandbox_id, reqwest::Method::GET, "/v1/files")
            .await?
            .query(&[("path", path)]),
        "sandbox.readFile",
    )
    .await?;

    let body: ReadFileResponse =
        response
            .json()
            .await
            .into_alien_error()
            .context(ErrorData::UnexpectedResponseFormat {
                provider: transport.provider().to_string(),
                binding_name: "sandbox.readFile".to_string(),
                field: "body".to_string(),
                response_json: "the agent returned a body this provider cannot parse".to_string(),
            })?;

    decode(
        &body.contents_base64,
        transport.provider(),
        "sandbox.readFile",
        "contentsBase64",
    )
}

/// Writes files into the sandbox, one request per path.
pub async fn write_files<T: AgentTransport + ?Sized>(
    transport: &T,
    sandbox_id: &str,
    files: BTreeMap<String, Vec<u8>>,
) -> Result<()> {
    for (path, contents) in files {
        send(
            transport
                .request(sandbox_id, reqwest::Method::PUT, "/v1/files")
                .await?
                .json(&json!({
                    "path": path,
                    "contentsBase64": BASE64.encode(contents),
                })),
            "sandbox.writeFiles",
        )
        .await?;
    }

    Ok(())
}

/// Milliseconds, saturated rather than wrapped.
///
/// A timeout long enough to overflow `u64` milliseconds is not a timeout anyone meant, and
/// wrapping it would turn "effectively forever" into "immediately".
fn timeout_millis(timeout: Duration) -> u64 {
    u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX)
}

/// What a request whose outcome is unknown becomes: no answer before its headers, or a body
/// that failed or ended short of its last frame.
///
/// For a file operation every one of those is safe to repeat. For `run_command` the agent may
/// have started the command — and past the headers it certainly did — so a repeat could run it
/// twice, and the refusal must not carry the retry signal.
fn unanswered(operation: &str, reason: &str) -> ErrorData {
    // Both take a command the agent may already be running, so an unanswered one leaves the
    // outcome unestablished. Every other operation is idempotent and safe to send again.
    if operation == RUN_COMMAND || operation == JOB_START {
        return ErrorData::SandboxOutcomeUnknown {
            operation: operation.to_string(),
            reason: reason.to_string(),
        };
    }
    ErrorData::SandboxUnreachable {
        operation: operation.to_string(),
        reason: reason.to_string(),
    }
}

/// Sends a request and turns a non-success into a typed error carrying the agent's own reason.
///
/// A transport failure here is marked retryable, which holds for the file operations but not for
/// `run_command` — that request may have already started the command. Nothing retries on this
/// path today; whoever adds a retry layer has to treat `run_command` as the exception.
pub async fn send(request: reqwest::RequestBuilder, operation: &str) -> Result<reqwest::Response> {
    let response = match tokio::time::timeout(AGENT_RESPONSE_TIMEOUT, request.send()).await {
        Ok(sent) => sent
            .into_alien_error()
            .context(unanswered(operation, "the request never reached the agent"))?,
        Err(_) => {
            return Err(AlienError::new(unanswered(
                operation,
                &format!(
                    "the agent did not answer within {}s",
                    AGENT_RESPONSE_TIMEOUT.as_secs()
                ),
            )));
        }
    };

    if response.status().is_success() {
        return Ok(response);
    }

    let status = response.status();
    // Read the body first: the agent puts the actual cause there, and a bare status turns a
    // specific refusal into a guess. A read that *fails* is not an empty body — collapsing the
    // two would let a dropped connection claim the request never arrived.
    let body = match response.text().await {
        Ok(body) => body,
        Err(error) => {
            return Err(error).into_alien_error().context(unanswered(
                operation,
                &format!("{operation} returned {status} and its body could not be read"),
            ))
        }
    };

    // A 5xx never proves the agent answered, with or without a body: the cloud's proxy emits them
    // too, and a 504 means the request reached the guest and no answer came back in time. A body
    // is no evidence either way — a proxy's error page is a body. So a 5xx is the unanswered case,
    // which for the idempotent file operations is still safe to repeat and for `run_command` is
    // not. A 4xx is the agent refusing before it does anything, which is an answer.
    if status.is_server_error() {
        return Err(AlienError::new(unanswered(
            operation,
            &format!("the sandbox host returned {status}: {body}"),
        )));
    }

    Err(AlienError::new(ErrorData::SandboxCommandFailed {
        // The cause, not the operation: `reason` already names the operation, and a caller
        // branching on `failure` gets an agent error code from every other construction site.
        failure: "agentRefused".to_string(),
        reason: format!("{operation} returned {status}: {body}"),
    }))
}

/// Turns the agent's NDJSON body into output frames.
///
/// `timeout` is the command's own, and the whole body is bounded by it plus
/// [`TERMINAL_FRAME_GRACE`]: a healthy agent ends every command at that deadline and writes a
/// terminal frame, so a body still open past it belongs to a sandbox that is no longer running.
fn frame_stream(
    response: reqwest::Response,
    provider: &'static str,
    timeout: Duration,
) -> BoxStream<'static, Result<CommandOutput>> {
    struct State {
        bytes: BoxStream<'static, reqwest::Result<bytes::Bytes>>,
        buffer: Vec<u8>,
        finished: bool,
        saw_terminal: bool,
        provider: &'static str,
        stall: std::pin::Pin<Box<tokio::time::Sleep>>,
    }

    let state = State {
        bytes: response.bytes_stream().boxed(),
        buffer: Vec::new(),
        finished: false,
        saw_terminal: false,
        provider,
        // `sleep` saturates a duration with no representable instant, so no timeout a caller can
        // name overflows this.
        stall: Box::pin(tokio::time::sleep(
            timeout.saturating_add(TERMINAL_FRAME_GRACE),
        )),
    };

    futures::stream::unfold(state, |mut state| async move {
        loop {
            if let Some(index) = state.buffer.iter().position(|byte| *byte == b'\n') {
                let line: Vec<u8> = state.buffer.drain(..=index).collect();
                let line = &line[..line.len() - 1];
                if line.is_empty() {
                    continue;
                }

                let frame = match serde_json::from_slice::<AgentFrame>(line) {
                    Ok(frame) => frame,
                    Err(error) => {
                        state.finished = true;
                        state.buffer.clear();
                        // Classified like the decode arms in `into_output`, and for the same
                        // reason: the frame arrived, so the command ran.
                        let failure = malformed(&error.to_string(), state.provider)
                            .context(unanswered(RUN_COMMAND, "an output frame did not parse"));
                        return Some((Err(failure), state));
                    }
                };

                if matches!(frame, AgentFrame::Exit { .. } | AgentFrame::Error { .. }) {
                    state.saw_terminal = true;
                }

                let output = frame.into_output(state.provider);
                // A failure here ends the stream. Yielding whatever the buffer still holds would
                // let a later exit frame answer the question this item just reported as
                // unanswerable, and which of the two a caller believes would depend only on
                // whether it stopped at the first error.
                if output.is_err() {
                    state.finished = true;
                    state.buffer.clear();
                }
                return Some((output, state));
            }

            if state.finished {
                return None;
            }

            // Biased so a chunk already in hand is read rather than discarded by a deadline
            // that came due in the same poll.
            let chunk = tokio::select! {
                biased;
                chunk = state.bytes.next() => chunk,
                () = &mut state.stall => {
                    state.finished = true;
                    // Dropping the body is the only signal that stops the command, and a caller
                    // that catches this error need never drop the stream it came from.
                    state.bytes = futures::stream::empty().boxed();
                    return Some((
                        Err(AlienError::new(unanswered(
                            RUN_COMMAND,
                            &format!(
                                "no terminal frame arrived within {}s of the command's timeout",
                                TERMINAL_FRAME_GRACE.as_secs()
                            ),
                        ))),
                        state,
                    ));
                }
            };

            match chunk {
                Some(Ok(chunk)) => state.buffer.extend_from_slice(&chunk),
                // The command has started — frames were arriving — and its end is now unknown.
                // That is the strongest case for not inviting a retry, so both a failing body and
                // one that ends short of its terminal frame refuse the same way a lost answer does.
                Some(Err(error)) => {
                    state.finished = true;
                    return Some((
                        Err(AlienError::new(unanswered(
                            RUN_COMMAND,
                            &format!("the output stream failed: {error}"),
                        ))),
                        state,
                    ));
                }
                None => {
                    state.finished = true;
                    if !state.saw_terminal {
                        return Some((
                            Err(AlienError::new(unanswered(
                                RUN_COMMAND,
                                "the output stream ended without a terminal frame",
                            ))),
                            state,
                        ));
                    }
                    return None;
                }
            }
        }
    })
    .boxed()
}

impl AgentFrame {
    fn into_output(self, provider: &'static str) -> Result<CommandOutput> {
        match self {
            // A frame that arrived is proof the command ran, so a payload that will not decode
            // leaves the outcome unestablished rather than merely malformed — reading it as a
            // format problem would let a caller repeat a command that already executed.
            Self::Stdout { seq, data } => Ok(CommandOutput::Stdout {
                seq,
                data: decode(&data, provider, RUN_COMMAND, "data")
                    .context(unanswered(RUN_COMMAND, "an output frame did not decode"))?,
            }),
            Self::Stderr { seq, data } => Ok(CommandOutput::Stderr {
                seq,
                data: decode(&data, provider, RUN_COMMAND, "data")
                    .context(unanswered(RUN_COMMAND, "an output frame did not decode"))?,
            }),
            Self::Exit { code, truncated } => Ok(CommandOutput::Exit { code, truncated }),
            // An error frame is the command's outcome, so it surfaces as an error rather than
            // as a stream that simply stopped.
            Self::Error { code, message } => {
                Err(AlienError::new(ErrorData::SandboxCommandFailed {
                    failure: code,
                    reason: message,
                }))
            }
        }
    }
}

/// `binding_name` and `field` are the caller's, not this function's: `read_file` decodes through
/// here too, and a corrupt file read reported as a runCommand output frame sends the reader to
/// the wrong place.
fn decode(data: &str, provider: &'static str, binding_name: &str, field: &str) -> Result<Vec<u8>> {
    BASE64
        .decode(data)
        .into_alien_error()
        .context(ErrorData::UnexpectedResponseFormat {
            provider: provider.to_string(),
            binding_name: binding_name.to_string(),
            field: field.to_string(),
            response_json: format!("{field} was not valid base64"),
        })
}

fn malformed(reason: &str, provider: &'static str) -> AlienError<ErrorData> {
    AlienError::new(ErrorData::UnexpectedResponseFormat {
        provider: provider.to_string(),
        binding_name: RUN_COMMAND.to_string(),
        field: "frame".to_string(),
        response_json: format!("an output frame did not parse: {reason}"),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::traits::CommandOutput;
    use axum::extract::State;
    use axum::http::StatusCode;
    use axum::response::IntoResponse;
    use axum::routing::post;
    use axum::{Json, Router};
    use std::net::SocketAddr;
    use std::sync::{Arc, Mutex};

    async fn serve_frames(chunks: Vec<&'static str>) -> String {
        let handler = move || {
            let chunks = chunks.clone();
            async move {
                let stream = futures::stream::iter(
                    chunks
                        .into_iter()
                        .map(|chunk| Ok::<_, std::io::Error>(bytes::Bytes::from(chunk))),
                );
                axum::body::Body::from_stream(stream).into_response()
            }
        };

        let router = Router::new().route("/v1/exec", post(handler));
        let listener = tokio::net::TcpListener::bind::<SocketAddr>("127.0.0.1:0".parse().unwrap())
            .await
            .expect("bind");
        let address = listener.local_addr().expect("address");
        tokio::spawn(async move {
            axum::serve(listener, router).await.expect("serve");
        });

        format!("http://{address}")
    }

    async fn frames_from(chunks: Vec<&'static str>) -> Vec<Result<CommandOutput>> {
        let base = serve_frames(chunks).await;
        let response = reqwest::Client::new()
            .post(format!("{base}/v1/exec"))
            .send()
            .await
            .expect("responds");

        frame_stream(response, "test-sandbox", Duration::from_secs(30))
            .collect::<Vec<_>>()
            .await
    }

    /// Serves `status` with `body` on /v1/exec and returns what `send` made of it.
    async fn send_status(status: StatusCode, body: &'static str) -> AlienError<ErrorData> {
        let handler = move || async move { (status, body).into_response() };
        let router = Router::new().route("/v1/exec", post(handler));
        let listener = tokio::net::TcpListener::bind::<SocketAddr>("127.0.0.1:0".parse().unwrap())
            .await
            .expect("bind");
        let address = listener.local_addr().expect("address");
        tokio::spawn(async move { axum::serve(listener, router).await.expect("serve") });

        send(
            reqwest::Client::new().post(format!("http://{address}/v1/exec")),
            RUN_COMMAND,
        )
        .await
        .expect_err("a non-success must be an error")
    }

    /// AWS answers 502 with an empty body while a MicroVM's snapshot is still restoring, so the
    /// request never reached the agent and the command never ran. Calling that `agentRefused`
    /// sends a reader into the agent for a fault that was never there.
    #[tokio::test]
    async fn a_bodyless_server_error_is_not_reported_as_the_agent_refusing() {
        let error = send_status(StatusCode::BAD_GATEWAY, "").await;
        let rendered = error.to_string();

        assert!(
            !rendered.contains("agentRefused"),
            "a proxy 502 is not the agent refusing: {rendered}"
        );
        assert_eq!(
            error.code, "SANDBOX_OUTCOME_UNKNOWN",
            "a proxy can synthesize a 502 after the agent accepted the request, so the caller has \
             to be told the outcome is unknown rather than that it is safe to repeat: {rendered}"
        );
    }

    /// A body is not evidence of who sent it: a proxy's error page is a body too, and a 504 in
    /// particular means the request reached the guest. The cause still has to survive for whoever
    /// reads the failure.
    #[tokio::test]
    async fn a_server_error_is_unknown_however_much_body_it_carries() {
        let error = send_status(StatusCode::INTERNAL_SERVER_ERROR, "spawn failed: ENOMEM").await;
        let rendered = error.to_string();

        assert!(
            rendered.contains("spawn failed: ENOMEM"),
            "the cause has to survive: {rendered}"
        );
        assert_eq!(error.code, "SANDBOX_OUTCOME_UNKNOWN", "got: {rendered}");
    }

    /// The scenario the rule above exists for: a gateway timing out on a command that is still
    /// running, and answering with its own HTML.
    #[tokio::test]
    async fn a_gateway_timeout_with_an_error_page_does_not_read_as_the_agent_refusing() {
        let error = send_status(
            StatusCode::GATEWAY_TIMEOUT,
            "<html><body>504 Gateway Time-out</body></html>",
        )
        .await;

        assert_eq!(error.code, "SANDBOX_OUTCOME_UNKNOWN", "got: {error}");
        assert!(
            !error.retryable,
            "the command may still be running behind the gateway: {error}"
        );
    }

    /// A 4xx is the agent refusing before it does anything, which is an answer.
    #[tokio::test]
    async fn a_client_error_is_the_agent_answering() {
        let error = send_status(StatusCode::BAD_REQUEST, "the command was empty").await;

        assert_ne!(
            error.code, "SANDBOX_OUTCOME_UNKNOWN",
            "a refusal before dispatch establishes that nothing ran: {error}"
        );
    }

    /// A cancel waits for this request before it can close the stream, so a request that never
    /// answers would leave the cancel unable to complete. Headers that never come are refused.
    #[tokio::test]
    async fn an_agent_that_never_answers_is_refused_within_the_bound() {
        let handler = || async {
            tokio::time::sleep(AGENT_RESPONSE_TIMEOUT * 20).await;
            "late".into_response()
        };
        let router = Router::new().route("/v1/exec", post(handler));
        let listener = tokio::net::TcpListener::bind::<SocketAddr>("127.0.0.1:0".parse().unwrap())
            .await
            .expect("bind");
        let address = listener.local_addr().expect("address");
        tokio::spawn(async move { axum::serve(listener, router).await.expect("serve") });

        let started = std::time::Instant::now();
        let error = send(
            reqwest::Client::new().post(format!("http://{address}/v1/exec")),
            RUN_COMMAND,
        )
        .await
        .expect_err("a stalled agent must be refused, not waited on");

        // The agent would answer at 20x the bound; refusing well before that is the property.
        // The margin is wide because setup shares a runtime with the rest of the suite.
        assert!(
            started.elapsed() < AGENT_RESPONSE_TIMEOUT * 10,
            "refused at the bound, not at the agent's leisure: {:?}",
            started.elapsed()
        );
        assert!(
            error.to_string().contains("did not answer"),
            "the refusal says the agent stalled: {error}"
        );
    }

    /// Output that arrives slowly, long after the headers, is the ordinary shape of a command
    /// that runs for a while. Each gap here is longer than `TERMINAL_FRAME_GRACE` and well inside
    /// the command's own timeout, which is what the body's bound is measured from.
    #[tokio::test]
    async fn a_slow_body_after_prompt_headers_is_not_cut_off() {
        let handler = || async {
            let frames = async_stream_frames(vec![
                "{\"t\":\"stdout\",\"seq\":0,\"data\":\"aGk=\"}\n",
                "{\"t\":\"exit\",\"code\":0,\"truncated\":false}\n",
            ]);
            axum::body::Body::from_stream(frames).into_response()
        };
        let router = Router::new().route("/v1/exec", post(handler));
        let listener = tokio::net::TcpListener::bind::<SocketAddr>("127.0.0.1:0".parse().unwrap())
            .await
            .expect("bind");
        let address = listener.local_addr().expect("address");
        tokio::spawn(async move { axum::serve(listener, router).await.expect("serve") });

        let response = send(
            reqwest::Client::new().post(format!("http://{address}/v1/exec")),
            RUN_COMMAND,
        )
        .await
        .expect("headers arrive at once");
        let outputs = frame_stream(response, "test-sandbox", Duration::from_secs(30))
            .collect::<Vec<_>>()
            .await;

        assert_eq!(outputs.len(), 2, "every frame arrived: {outputs:?}");
        assert_eq!(
            outputs[1].as_ref().expect("exit"),
            &CommandOutput::Exit {
                code: 0,
                truncated: false
            }
        );
    }

    /// An agent that writes one frame and then freezes with its guest: the body stays open and
    /// the command deadline that would have written the terminal frame never fires.
    async fn frozen_after_one_frame() -> TestTransport {
        let handler = || async {
            let frames = futures::stream::iter(vec![Ok::<bytes::Bytes, std::io::Error>(
                bytes::Bytes::from("{\"t\":\"stdout\",\"seq\":0,\"data\":\"aGk=\"}\n"),
            )])
            .chain(futures::stream::pending());
            axum::body::Body::from_stream(frames).into_response()
        };

        serve(Router::new().route("/v1/exec", post(handler))).await
    }

    /// Pausing a sandbox freezes the agent with it, so the command deadline that would end the
    /// stream never fires. A reader holding the stream is refused at the command's own deadline
    /// rather than held for as long as the pause lasts.
    #[tokio::test]
    async fn a_frozen_sandbox_refuses_an_open_stream_rather_than_parking_its_reader() {
        let transport = frozen_after_one_frame().await;

        let stream = run_command(
            &transport,
            "sandbox-1",
            RunCommandRequest {
                command: "sleep".to_string(),
                args: vec!["1".to_string()],
                cwd: None,
                env: BTreeMap::new(),
                timeout: TERMINAL_FRAME_GRACE,
            },
        )
        .await
        .expect("the agent answers with headers");

        // Scaffolding rather than the property: the bound under test is in `frame_stream`, and
        // without it this collect never resolves. The outer wait turns that hang into a failure.
        let outputs = tokio::time::timeout(TERMINAL_FRAME_GRACE * 20, stream.collect::<Vec<_>>())
            .await
            .expect("a frozen sandbox must end the stream, not park its reader");

        assert_eq!(
            outputs.len(),
            2,
            "the frame that did arrive is kept: {outputs:?}"
        );
        let error = outputs[1]
            .as_ref()
            .expect_err("a body that never ends is a failure, not an end");
        assert_eq!(error.code, "SANDBOX_OUTCOME_UNKNOWN", "got: {error}");
        assert!(
            !error.retryable,
            "the command may still be there when the sandbox resumes, so a repeat could run it \
             twice: {error}"
        );
        assert!(
            error.to_string().contains("no terminal frame"),
            "the refusal says what was missing: {error}"
        );
    }

    /// Reporting the stall is not enough: the body has to go with it. Dropping the stream is the
    /// only thing that stops the command, and a caller that catches this error still holds one,
    /// so a refusal that kept the transport would leave the command running past its own refusal.
    #[tokio::test]
    async fn a_refused_stream_releases_the_transport_when_it_reports() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let listener = tokio::net::TcpListener::bind::<SocketAddr>("127.0.0.1:0".parse().unwrap())
            .await
            .expect("bind");
        let address = listener.local_addr().expect("address");
        let (release, released) = tokio::sync::oneshot::channel::<()>();

        // Raw TCP rather than axum: the property is the socket closing, and a read that reaches
        // end-of-file is the only direct evidence of it.
        tokio::spawn(async move {
            let (mut socket, _) = listener.accept().await.expect("accept");
            let mut seen = Vec::new();
            let mut chunk = [0u8; 4096];
            while !seen.windows(4).any(|window| window == b"\r\n\r\n") {
                let read = socket.read(&mut chunk).await.expect("read the request");
                assert!(read > 0, "the client left before finishing its request");
                seen.extend_from_slice(&chunk[..read]);
            }

            let frame = "{\"t\":\"stdout\",\"seq\":0,\"data\":\"aGk=\"}\n";
            socket
                .write_all(
                    format!(
                        "HTTP/1.1 200 OK\r\nContent-Type: application/x-ndjson\r\n\
                         Transfer-Encoding: chunked\r\n\r\n{:x}\r\n{frame}\r\n",
                        frame.len()
                    )
                    .as_bytes(),
                )
                .await
                .expect("write one frame");
            socket.flush().await.expect("flush");

            // The chunked body is never terminated: this is the frozen agent. End-of-file here
            // is the client letting the connection go.
            while socket.read(&mut chunk).await.unwrap_or(0) > 0 {}
            release.send(()).expect("the test is still waiting");
        });

        // Held to the end of the test: a dropped client would close the connection by itself,
        // and the assertion below would then pass whether or not the refusal released anything.
        let client = reqwest::Client::new();
        let response = send(
            client.post(format!("http://{address}/v1/exec")),
            RUN_COMMAND,
        )
        .await
        .expect("headers arrive at once");
        let mut stream = frame_stream(response, "test-sandbox", TERMINAL_FRAME_GRACE);

        stream
            .next()
            .await
            .expect("the one frame the agent wrote")
            .expect("a stdout frame");
        let error = stream
            .next()
            .await
            .expect("the stall is reported rather than parking the reader")
            .expect_err("a body that never ends is a failure, not an end");
        assert_eq!(error.code, "SANDBOX_OUTCOME_UNKNOWN", "got: {error}");

        // `stream` stays alive across this wait on purpose: dropping it releases the body on its
        // own, which is the very thing the refusal is supposed to have already done.
        tokio::time::timeout(TERMINAL_FRAME_GRACE * 20, released)
            .await
            .expect("the refusal closes the connection to the agent")
            .expect("the agent reports the release");

        drop(stream);
        drop(client);
    }

    /// Frames emitted one at a time, each after a pause longer than the response bound, so the
    /// body as a whole takes several bounds to finish.
    fn async_stream_frames(
        chunks: Vec<&'static str>,
    ) -> impl futures::Stream<Item = std::result::Result<&'static str, std::io::Error>> {
        futures::stream::iter(chunks).then(|chunk| async move {
            tokio::time::sleep(AGENT_RESPONSE_TIMEOUT * 2).await;
            Ok(chunk)
        })
    }

    /// An agent that accepts any request and never sends its headers.
    /// The agent may have started the command before its headers stalled, so a retry could run
    /// A file operation is idempotent, so a stalled one is safe to repeat and says so.
    /// An agent that accepts any request and never sends its headers.
    /// A connection that drops before any headers is the same unknown as a stall: the agent may
    /// The agent may have started the command before its headers stalled, so a retry could run
    /// A file operation is idempotent, so a stalled one is safe to repeat and says so.
    /// An agent that accepts any request and never sends its headers.
    async fn stalled_agent() -> String {
        let handler = || async {
            tokio::time::sleep(AGENT_RESPONSE_TIMEOUT * 20).await;
            "late".into_response()
        };
        let router = Router::new().fallback(handler);
        let listener = tokio::net::TcpListener::bind::<SocketAddr>("127.0.0.1:0".parse().unwrap())
            .await
            .expect("bind");
        let address = listener.local_addr().expect("address");
        tokio::spawn(async move { axum::serve(listener, router).await.expect("serve") });

        format!("http://{address}")
    }

    /// A connection that drops before any headers is the same unknown as a stall: the agent may
    /// have taken the command before the socket went. It must not read as safe to repeat.
    #[tokio::test]
    async fn a_dropped_run_command_connection_is_not_retryable() {
        let listener = tokio::net::TcpListener::bind::<SocketAddr>("127.0.0.1:0".parse().unwrap())
            .await
            .expect("bind");
        let address = listener.local_addr().expect("address");
        // Accept and close at once: the request may have been read, no response ever comes.
        tokio::spawn(async move {
            loop {
                if let Ok((socket, _)) = listener.accept().await {
                    drop(socket);
                }
            }
        });

        let error = send(
            reqwest::Client::new().post(format!("http://{address}/v1/exec")),
            RUN_COMMAND,
        )
        .await
        .expect_err("a dropped connection is a refusal, not a response");

        assert_eq!(error.code, "SANDBOX_OUTCOME_UNKNOWN", "got: {error}");
        assert!(
            !error.retryable,
            "a command that may have started must not be retried: {error}"
        );
        assert!(
            error.to_string().contains("may have taken effect"),
            "the refusal says the outcome is unknown: {error}"
        );
    }

    /// The agent may have started the command before its headers stalled, so a retry could run
    /// it twice: the refusal must not invite one.
    #[tokio::test]
    async fn a_stalled_run_command_is_not_retryable() {
        let base = stalled_agent().await;

        let error = send(
            reqwest::Client::new().post(format!("{base}/v1/exec")),
            RUN_COMMAND,
        )
        .await
        .expect_err("a stalled agent must be refused, not waited on");

        assert_eq!(error.code, "SANDBOX_OUTCOME_UNKNOWN", "got: {error}");
        assert!(
            !error.retryable,
            "a command with an unknown outcome must not be retried: {error}"
        );
        assert!(
            error.to_string().contains("did not answer")
                && error.to_string().contains("may have taken effect"),
            "the refusal says the agent stalled and the outcome is unknown: {error}"
        );
    }

    /// A file operation is idempotent, so a stalled one is safe to repeat and says so.
    #[tokio::test]
    async fn a_stalled_file_operation_stays_retryable() {
        let base = stalled_agent().await;

        let error = send(
            reqwest::Client::new().get(format!("{base}/v1/files")),
            "sandbox.readFile",
        )
        .await
        .expect_err("a stalled agent must be refused, not waited on");

        assert_eq!(error.code, "SANDBOX_UNREACHABLE", "got: {error}");
        assert!(
            error.retryable,
            "a stalled file read is safe to repeat: {error}"
        );
        assert!(
            error.to_string().contains("did not answer"),
            "the refusal says the agent stalled: {error}"
        );
    }

    #[tokio::test]
    async fn frames_decode_in_order_with_a_real_exit_code() {
        let outputs = frames_from(vec![
            "{\"t\":\"stdout\",\"seq\":0,\"data\":\"aGk=\"}\n",
            "{\"t\":\"stderr\",\"seq\":1,\"data\":\"b29wcw==\"}\n",
            "{\"t\":\"exit\",\"code\":7,\"truncated\":false}\n",
        ])
        .await;

        assert_eq!(outputs.len(), 3);
        assert_eq!(
            outputs[0].as_ref().expect("stdout"),
            &CommandOutput::Stdout {
                seq: 0,
                data: b"hi".to_vec()
            }
        );
        assert_eq!(
            outputs[1].as_ref().expect("stderr"),
            &CommandOutput::Stderr {
                seq: 1,
                data: b"oops".to_vec()
            }
        );
        assert_eq!(
            outputs[2].as_ref().expect("exit"),
            &CommandOutput::Exit {
                code: 7,
                truncated: false
            }
        );
    }

    /// The protocol says a frame is never split across chunks; TCP makes no such promise. This
    /// is the case a naive per-chunk parser gets wrong, and it fails as a parse error on
    /// perfectly valid output.
    #[tokio::test]
    async fn a_frame_split_across_chunks_is_reassembled() {
        let outputs = frames_from(vec![
            "{\"t\":\"stdo",
            "ut\",\"seq\":0,\"data\":\"aGk=\"}\n{\"t\":\"ex",
            "it\",\"code\":0,\"truncated\":false}\n",
        ])
        .await;

        assert_eq!(
            outputs.len(),
            2,
            "a split frame must not become two frames or an error"
        );
        assert_eq!(
            outputs[0].as_ref().expect("stdout"),
            &CommandOutput::Stdout {
                seq: 0,
                data: b"hi".to_vec()
            }
        );
        assert_eq!(
            outputs[1].as_ref().expect("exit"),
            &CommandOutput::Exit {
                code: 0,
                truncated: false
            }
        );
    }

    /// A frame that arrived is proof the command ran, so a payload that will not decode leaves the
    /// outcome unestablished. Reported as a format problem it would read as safe to repeat, and the
    /// repeat would be a second execution.
    #[tokio::test]
    async fn a_frame_that_arrives_but_does_not_decode_leaves_the_outcome_unknown() {
        let outputs = frames_from(vec![
            "{\"t\":\"stdout\",\"seq\":0,\"data\":\"!!not base64!!\"}\n",
        ])
        .await;

        let error = outputs[0]
            .as_ref()
            .expect_err("a payload that does not decode is not output");
        assert_eq!(error.code, "SANDBOX_OUTCOME_UNKNOWN", "got: {error}");
        assert!(
            !error.retryable,
            "the command ran; a repeat would run it twice: {error}"
        );
        assert!(
            error.to_string().contains("base64"),
            "the decode failure must stay in the chain: {error}"
        );
    }

    /// A line that does not parse arrives the same way a decodable one does, so it carries the same
    /// proof that the command ran.
    #[tokio::test]
    async fn a_frame_that_does_not_parse_leaves_the_outcome_unknown() {
        let outputs = frames_from(vec!["{not json at all}\n"]).await;

        let error = outputs[0]
            .as_ref()
            .expect_err("a malformed frame is not output");
        assert_eq!(error.code, "SANDBOX_OUTCOME_UNKNOWN", "got: {error}");
        assert!(!error.retryable, "the command ran: {error}");
        assert!(
            error.to_string().contains("did not parse"),
            "the parse failure must stay in the chain: {error}"
        );
    }

    /// One chunk can hold both a frame that will not parse and the exit frame after it. The stream
    /// has to stop at the first: yielding the exit as well would answer the question the failure
    /// just reported as unanswerable, and a caller that reads to the end would believe the wrong
    /// one of the two.
    #[tokio::test]
    async fn an_unestablished_outcome_ends_the_stream_mid_chunk() {
        let outputs = frames_from(vec![
            "{not json at all}\n{\"t\":\"exit\",\"code\":0,\"truncated\":false}\n",
        ])
        .await;

        assert_eq!(
            outputs.len(),
            1,
            "the exit frame must not follow the failure"
        );
        let error = outputs[0]
            .as_ref()
            .expect_err("a malformed frame is not output");
        assert_eq!(error.code, "SANDBOX_OUTCOME_UNKNOWN", "got: {error}");
    }

    /// The same rule for a payload that arrives whole and will not decode.
    #[tokio::test]
    async fn a_decode_failure_ends_the_stream_mid_chunk() {
        let outputs = frames_from(vec![
            "{\"t\":\"stdout\",\"seq\":0,\"data\":\"!!\"}\n{\"t\":\"exit\",\"code\":0,\"truncated\":false}\n",
        ])
        .await;

        assert_eq!(
            outputs.len(),
            1,
            "the exit frame must not follow the failure"
        );
        assert_eq!(
            outputs[0]
                .as_ref()
                .expect_err("a bad payload is not output")
                .code,
            "SANDBOX_OUTCOME_UNKNOWN"
        );
    }

    /// A body that stops early looks exactly like a command that produced less output — the
    /// difference is only visible in the missing terminal frame. The command had started, so
    /// its end is unknown, and a retry could run it twice: the refusal must not invite one.
    #[tokio::test]
    async fn a_stream_without_a_terminal_frame_is_an_unknown_outcome() {
        let outputs = frames_from(vec!["{\"t\":\"stdout\",\"seq\":0,\"data\":\"aGk=\"}\n"]).await;

        assert_eq!(outputs.len(), 2);
        outputs[0].as_ref().expect("the stdout frame still arrives");
        let error = outputs[1]
            .as_ref()
            .expect_err("a truncated stream must not read as success");
        assert!(
            error.to_string().contains("without a terminal frame"),
            "the failure must name the cause: {error}"
        );
        assert_eq!(error.code, "SANDBOX_OUTCOME_UNKNOWN", "got: {error}");
        assert!(
            !error.retryable,
            "a command that started and whose end was lost must not be retried: {error}"
        );
    }

    #[tokio::test]
    async fn an_error_frame_surfaces_as_an_error_not_a_silent_end() {
        let outputs = frames_from(vec![
            "{\"t\":\"error\",\"code\":\"timeoutExceeded\",\"message\":\"exceeded its 300ms timeout\"}\n",
        ])
        .await;

        assert_eq!(outputs.len(), 1);
        let error = outputs[0]
            .as_ref()
            .expect_err("an error frame is a failure");
        assert!(error.to_string().contains("timeoutExceeded"), "{error}");
    }

    /// A transport that authorizes nothing, so the tests exercise the protocol rather than a
    /// backend's credentials.
    #[derive(Debug)]
    struct TestTransport(String);

    #[async_trait]
    impl AgentTransport for TestTransport {
        async fn request(
            &self,
            _sandbox_id: &str,
            method: reqwest::Method,
            path: &str,
        ) -> Result<reqwest::RequestBuilder> {
            Ok(reqwest::Client::new().request(method, format!("{}{path}", self.0)))
        }

        fn provider(&self) -> &'static str {
            "test-sandbox"
        }
    }

    async fn serve(router: Router) -> TestTransport {
        let listener = tokio::net::TcpListener::bind::<SocketAddr>("127.0.0.1:0".parse().unwrap())
            .await
            .expect("bind");
        let address = listener.local_addr().expect("address");
        tokio::spawn(async move { axum::serve(listener, router).await.expect("serve") });
        TestTransport(format!("http://{address}"))
    }

    /// What the agent was asked for, so a test can assert the cursor it received rather than only
    /// the frames it chose to send back.
    type Cursors = Arc<Mutex<Vec<Option<u64>>>>;

    /// An agent running one job: it reports a frame while running, then its exit.
    async fn job_agent(cursors: Cursors) -> TestTransport {
        async fn poll(
            State(cursors): State<Cursors>,
            Json(body): Json<serde_json::Value>,
        ) -> impl IntoResponse {
            let since = body.get("sinceSeq").and_then(serde_json::Value::as_u64);
            cursors.lock().expect("cursors").push(since);
            match since {
                None => Json(json!({
                    "running": true,
                    "frames": [{ "t": "stdout", "seq": 0, "data": "aGk=" }],
                })),
                Some(_) => Json(json!({
                    "running": false,
                    "frames": [],
                    "exitCode": 7,
                    "truncated": false,
                })),
            }
        }

        serve(
            Router::new()
                .route(
                    "/v1/jobs/start",
                    post(|| async { Json(json!({"jobId": "j1"})) }),
                )
                .route("/v1/jobs/poll", post(poll))
                .route("/v1/jobs/cancel", post(|| async { Json(json!({})) }))
                .with_state(cursors),
        )
        .await
    }

    /// The whole job round trip: a start that names the job, a first poll that reads from the
    /// beginning, a second that asks only for what is new, and a cancel the agent accepts.
    #[tokio::test]
    async fn a_job_starts_polls_from_its_cursor_and_cancels() {
        let cursors: Cursors = Arc::new(Mutex::new(Vec::new()));
        let transport = job_agent(Arc::clone(&cursors)).await;

        let started = start_job(&transport, "s1", command(Duration::from_secs(600)))
            .await
            .expect("the job starts");
        assert_eq!(started.job_id, "j1");

        let first = poll_job(&transport, "s1", &started.job_id, None)
            .await
            .expect("the first poll answers");
        assert!(first.running, "the job is still running: {first:?}");
        assert_eq!(
            first.frames,
            vec![CommandOutput::Stdout {
                seq: 0,
                data: b"hi".to_vec()
            }],
            "the agent's base64 frame is decoded"
        );
        assert!(first.exit.is_none() && first.error.is_none());

        let second = poll_job(&transport, "s1", &started.job_id, Some(0))
            .await
            .expect("the second poll answers");
        assert!(!second.running);
        assert!(second.frames.is_empty(), "nothing follows the last frame");
        assert_eq!(
            second.exit,
            Some(crate::traits::JobExit {
                code: 7,
                truncated: false
            }),
            "the ending is the envelope's, not a frame's"
        );

        cancel_job(&transport, "s1", &started.job_id)
            .await
            .expect("the cancel is accepted");

        assert_eq!(
            *cursors.lock().expect("cursors"),
            vec![None, Some(0)],
            "the cursor a caller passes has to reach the agent, or every poll replays the whole \
             output and a caller sees each frame twice"
        );
    }

    /// A start the agent may have taken is the one job call that must not invite a retry.
    #[tokio::test]
    async fn a_server_error_on_a_start_leaves_the_outcome_unknown() {
        let transport = serve(Router::new().route(
            "/v1/jobs/start",
            post(|| async { (StatusCode::INTERNAL_SERVER_ERROR, "spawn failed").into_response() }),
        ))
        .await;

        let error = start_job(&transport, "s1", command(Duration::from_secs(600)))
            .await
            .expect_err("a 5xx is not a job that started");

        assert_eq!(error.code, "SANDBOX_OUTCOME_UNKNOWN", "got: {error}");
        assert!(
            !error.retryable,
            "the agent may have taken the command, and a repeat would run it twice: {error}"
        );
        assert!(
            error.to_string().contains("sandbox.jobStart"),
            "the operation reaches callers and telemetry, so a failed start has to be tellable \
             apart from a failed streaming command: {error}"
        );
    }

    /// A poll changes nothing about the job, so a failed one is worth repeating — the opposite of
    /// the rule above, and the reason the two carry different operation names.
    #[tokio::test]
    async fn a_server_error_on_a_poll_stays_retryable() {
        let transport = serve(Router::new().route(
            "/v1/jobs/poll",
            post(|| async { (StatusCode::SERVICE_UNAVAILABLE, "").into_response() }),
        ))
        .await;

        let error = poll_job(&transport, "s1", "j1", Some(4))
            .await
            .expect_err("a 5xx is not a poll that answered");

        assert_eq!(error.code, "SANDBOX_UNREACHABLE", "got: {error}");
        assert!(error.retryable, "the job is untouched: {error}");
    }

    /// A body that stops half way is indistinguishable from a poll that never answered, and the
    /// job is still there to be polled again.
    #[tokio::test]
    async fn a_poll_body_that_ends_early_is_retryable() {
        let transport = serve(Router::new().route(
            "/v1/jobs/poll",
            post(|| async {
                axum::body::Body::from_stream(futures::stream::iter(vec![
                    Ok::<_, std::io::Error>(bytes::Bytes::from_static(b"{\"running\":tr")),
                    Err(std::io::Error::other("the connection went")),
                ]))
                .into_response()
            }),
        ))
        .await;

        let error = poll_job(&transport, "s1", "j1", None)
            .await
            .expect_err("a truncated body is not a poll");

        assert_eq!(error.code, "SANDBOX_UNREACHABLE", "got: {error}");
        assert!(error.retryable, "polling again costs nothing: {error}");
    }

    /// A cancel the agent refuses — an unknown job, say — is an answer, so it reaches the caller
    /// as the agent's refusal rather than as a sandbox that could not be reached.
    #[tokio::test]
    async fn a_refused_cancel_is_the_agent_answering() {
        let transport = serve(Router::new().route(
            "/v1/jobs/cancel",
            post(|| async { (StatusCode::NOT_FOUND, "JOB_NOT_FOUND").into_response() }),
        ))
        .await;

        let error = cancel_job(&transport, "s1", "j1")
            .await
            .expect_err("a 404 is not a cancel that landed");

        assert_eq!(error.code, "SANDBOX_COMMAND_FAILED", "got: {error}");
        assert!(
            error.to_string().contains("JOB_NOT_FOUND"),
            "the agent's own reason has to survive: {error}"
        );
    }

    /// The body AWS and Kubernetes both send: the program first, then its arguments in order.
    ///
    /// The agent takes one argv array, so the split has to be rejoined here, and a rejoin that
    /// dropped, reordered or duplicated an element would run something other than what was asked
    /// for. Two arguments rather than one: with a single argument an inverted or duplicated
    /// rejoin produces the same array as the correct one.
    #[test]
    fn the_program_leads_its_arguments_in_the_body_the_agent_receives() {
        let body = exec_body(&RunCommandRequest {
            command: "python".to_string(),
            args: vec!["-u".to_string(), "main.py".to_string()],
            cwd: Some("/work".to_string()),
            env: BTreeMap::from([("TOKEN".to_string(), "t".to_string())]),
            timeout: Duration::from_millis(5_000),
        })
        .expect("a command with a non-zero timeout builds a body");

        assert_eq!(
            body["command"],
            serde_json::json!(["python", "-u", "main.py"]),
            "the program leads, and its arguments follow in order"
        );
        assert_eq!(body["cwd"], serde_json::json!("/work"));
        assert_eq!(body["timeoutMs"], serde_json::json!(5_000));
        assert_eq!(body["env"], serde_json::json!({ "TOKEN": "t" }));
    }

    fn command(timeout: Duration) -> RunCommandRequest {
        RunCommandRequest {
            command: "/bin/sleep".to_string(),
            args: vec!["600".to_string()],
            cwd: None,
            env: BTreeMap::new(),
            timeout,
        }
    }
}