symbi-runtime 1.21.1

Agent Runtime System for the Symbi platform
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
//! Firecracker execution through an independently owned VMM and a versioned
//! guest command protocol. A VMM exit is never a substitute for a guest result.
use super::{
    supervisor::{Lease, SupervisorConfig},
    ExecutionResult, SandboxRunner,
};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    time::{Duration, Instant},
};
use symbi_sandbox_guest as guest;
use symbi_sandbox_supervisor::protocol::{CreateVm, IMPLEMENTATION, VERSION};
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;

#[cfg(unix)]
pub mod files;
pub mod services;
#[cfg(unix)]
pub mod snapshot;
#[cfg(unix)]
mod streaming;
#[cfg(unix)]
pub use streaming::{FirecrackerStdio, StdioGuard};

/// Operator-owned artifacts and VM limits. The root image is always read-only;
/// the guest init provisions temporary scratch space inside the VM.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct FirecrackerConfig {
    pub kernel_image_path: PathBuf,
    pub rootfs_path: PathBuf,
    pub rootfs_read_only: bool,
    pub boot_args: String,
    pub vcpus: u8,
    pub mem_mib: u32,
    pub firecracker_binary: String,
    pub max_execution_time: Duration,
    pub startup_timeout: Duration,
    pub max_output_bytes: usize,
    /// Legacy work-root setting. State now belongs to the private supervisor;
    /// set supervisor.state_dir instead. A nonempty legacy value is refused.
    pub work_dir: Option<PathBuf>,
    pub working_dir: String,
    /// Explicit host:virtual:ro ceilings for source queries and declared inputs. These are
    /// never mounted in, or automatically transferred to, the guest.
    pub source_roots: Vec<String>,
    /// Separate write-only host ceilings for new-file publication.
    pub output_roots: Vec<String>,
    /// One-use transport authority created by the file broker.
    #[cfg(unix)]
    #[serde(skip)]
    pub files: Option<std::sync::Arc<files::Transfer>>,
    #[cfg(unix)]
    #[serde(skip)]
    pub snapshot: Option<std::sync::Arc<snapshot::Transfer>>,
    pub supervisor: SupervisorConfig,
    /// Opaque runtime-issued broker capabilities, bound into managed admission.
    /// Project configuration cannot create or restore them.
    #[serde(skip_deserializing, skip_serializing_if = "Option::is_none")]
    pub services: Option<services::GuestServices>,
}
impl Default for FirecrackerConfig {
    fn default() -> Self {
        Self {
            kernel_image_path: PathBuf::new(),
            rootfs_path: PathBuf::new(),
            rootfs_read_only: true,
            boot_args: "console=ttyS0 reboot=k panic=1 pci=off ro init=/sbin/symbi-sandbox-guest"
                .into(),
            vcpus: 1,
            mem_mib: 512,
            firecracker_binary: "firecracker".into(),
            max_execution_time: Duration::from_secs(300),
            startup_timeout: Duration::from_secs(15),
            max_output_bytes: guest::MAX_OUTPUT,
            work_dir: None,
            working_dir: "/tmp".into(),
            source_roots: Vec::new(),
            output_roots: Vec::new(),
            #[cfg(unix)]
            files: None,
            #[cfg(unix)]
            snapshot: None,
            supervisor: SupervisorConfig::default(),
            services: None,
        }
    }
}
impl FirecrackerConfig {
    pub fn validate(&self) -> anyhow::Result<()> {
        if !cfg!(target_os = "linux") {
            anyhow::bail!("Firecracker requires Linux and KVM");
        }
        if self.kernel_image_path.as_os_str().is_empty() {
            anyhow::bail!("Firecracker sandbox is missing kernel_image_path");
        }
        if self.rootfs_path.as_os_str().is_empty() {
            anyhow::bail!("Firecracker sandbox is missing rootfs_path");
        }
        for path in [&self.kernel_image_path, &self.rootfs_path] {
            if !path.is_absolute() || !path.is_file() {
                anyhow::bail!(
                    "Firecracker artifact must be an existing absolute file: {}",
                    path.display()
                );
            }
        }
        if !self.rootfs_read_only {
            anyhow::bail!("Firecracker rootfs must be read-only; use guest scratch storage");
        }
        if self.work_dir.is_some() {
            anyhow::bail!("Firecracker work_dir is unsupported; configure supervisor.state_dir");
        }
        if !(1..=32).contains(&self.vcpus)
            || !(64..=16384).contains(&self.mem_mib)
            || self.max_execution_time.is_zero()
            || self.max_execution_time > Duration::from_secs(86400)
            || self.startup_timeout.is_zero()
            || self.startup_timeout > Duration::from_secs(60)
            || !(1..=guest::MAX_OUTPUT).contains(&self.max_output_bytes)
            || !self.working_dir.starts_with('/')
            || self.working_dir.contains('\0')
            || self.working_dir.len() > 4096
            || self.boot_args.is_empty()
            || self.boot_args.len() > 4096
            || self.boot_args.contains('\0')
        {
            anyhow::bail!("invalid Firecracker resource, startup or guest limits");
        }
        if self.firecracker_binary.is_empty() || self.firecracker_binary.contains('\0') {
            anyhow::bail!("invalid Firecracker executable");
        }
        self.supervisor.validate()?;
        let supervisor_root = self.supervisor.resolved_state_dir()?;
        for (roots, mode) in [(&self.source_roots, "ro"), (&self.output_roots, "rw")] {
            anyhow::ensure!(roots.len() <= 32, "too many Firecracker broker file roots");
            let mut destinations = std::collections::HashSet::new();
            for root in roots {
                super::docker::canonical_mount(root)?;
                let parts: Vec<_> = root.split(':').collect();
                anyhow::ensure!(parts.get(2).copied().unwrap_or("ro") == mode, "Firecracker source roots must be read-only and output roots explicitly writable");
                anyhow::ensure!(
                    destinations.insert(Path::new(parts[1]).components().collect::<PathBuf>()),
                    "duplicate Firecracker file destination"
                );
                let source = Path::new(parts[0]).canonicalize()?;
                anyhow::ensure!(
                    !source.starts_with(&supervisor_root) && !supervisor_root.starts_with(&source),
                    "file root exposes the protected sandbox supervisor state"
                );
            }
        }
        #[cfg(unix)]
        if let Some(snapshot) = &self.snapshot {
            snapshot.validate()?;
            anyhow::ensure!(
                self.files.is_none() && self.services.is_none(),
                "Git snapshot authority requires an exclusive worker"
            );
        }
        #[cfg(unix)]
        if let Some(files) = &self.files {
            files.validate()?;
        }

        if let Some(services) = &self.services {
            services.validate()?;
        }
        if self
            .supervisor
            .resolved_state_dir()?
            .join(format!("vm-{}", uuid::Uuid::nil()))
            .join("vsock")
            .as_os_str()
            .as_encoded_bytes()
            .len()
            >= if self.services.is_some() { 99 } else { 104 }
        {
            anyhow::bail!("Firecracker supervisor state path is too long for vsock");
        }
        Ok(())
    }
}

#[derive(Clone)]
pub struct FirecrackerRunner {
    config: FirecrackerConfig,
}
impl FirecrackerRunner {
    pub fn new(mut config: FirecrackerConfig) -> anyhow::Result<Self> {
        config.validate()?;
        config.kernel_image_path = config.kernel_image_path.canonicalize()?;
        config.rootfs_path = config.rootfs_path.canonicalize()?;
        config.firecracker_binary =
            super::supervisor::resolve_binary(Path::new(&config.firecracker_binary))?
                .to_str()
                .ok_or_else(|| anyhow::anyhow!("Firecracker executable must be UTF-8"))?
                .to_owned();
        config.supervisor.state_dir = config.supervisor.resolved_state_dir()?;
        // No unbounded --version subprocess. Existence is preflight evidence;
        // the actual VMM start and guest handshake establish execution readiness.
        Ok(Self { config })
    }
    fn specification(&self, id: uuid::Uuid, lifetime: Duration) -> CreateVm {
        CreateVm {
            origin: super::worker_origin::current(),
            version: VERSION,
            implementation: IMPLEMENTATION.into(),
            lease: id,
            binary: PathBuf::from(&self.config.firecracker_binary),
            kernel: self.config.kernel_image_path.clone(),
            rootfs: self.config.rootfs_path.clone(),
            boot_args: self.config.boot_args.clone(),
            vcpus: self.config.vcpus,
            memory_mib: self.config.mem_mib,
            lifetime_ms: lifetime.as_millis().min(u64::MAX as u128) as u64,
            startup_ms: self
                .config
                .startup_timeout
                .min(lifetime)
                .as_millis()
                .min(u64::MAX as u128) as u64,
        }
    }
    /// VM config contains a concrete vsock device and no network interface.
    pub fn build_vm_config_json(&self, vsock: &Path) -> serde_json::Value {
        self.specification(uuid::Uuid::nil(), self.config.max_execution_time)
            .vm_config(vsock)
    }

    pub async fn execute_command(
        &self,
        argv: &[String],
        environment: HashMap<String, String>,
        input: Option<Vec<u8>>,
        input_as_file: bool,
        budget: Duration,
    ) -> anyhow::Result<ExecutionResult> {
        let started = Instant::now();
        let lifetime = budget.min(self.config.max_execution_time);
        let id = uuid::Uuid::new_v4();
        let input = input.unwrap_or_default();
        let mut environment: std::collections::BTreeMap<String, String> =
            environment.into_iter().collect();
        for (name, value) in [
            ("PATH", "/usr/bin:/bin"),
            ("HOME", "/tmp"),
            ("LANG", "C.UTF-8"),
        ] {
            environment
                .entry(name.into())
                .or_insert_with(|| value.into());
        }
        let request = guest::Command {
            mode: guest::CommandMode::OneShot,
            version: guest::VERSION,
            id: id.to_string(),
            argv: argv.to_vec(),
            environment,
            working_dir: self.config.working_dir.clone(),
            input_length: input.len(),
            input_as_file,
            snapshot: {
                #[cfg(unix)]
                {
                    self.config
                        .snapshot
                        .as_ref()
                        .map(|s| s.begin())
                        .transpose()?
                }
                #[cfg(not(unix))]
                {
                    None
                }
            },
            files: {
                #[cfg(unix)]
                {
                    self.config
                        .files
                        .as_ref()
                        .map(|files| files.begin())
                        .transpose()?
                }
                #[cfg(not(unix))]
                {
                    None
                }
            },
            max_output_bytes: self.config.max_output_bytes,
            timeout_ms: lifetime.as_millis().min(u64::MAX as u128) as u64,
        };
        request.validate()?;
        guest::encode_header(&request)?;
        let specification = self.specification(id, lifetime);
        specification.validate()?;
        let registration = super::command_cleanup::register().map_err(anyhow::Error::msg)?;
        let run_stop = registration
            .as_ref()
            .map_or_else(CancellationToken::new, |r| r.stop.clone());
        let stop = CancellationToken::new();
        let guard = CancelOnDrop(stop.clone());
        let config = self.config.clone();
        let (send, receive) = oneshot::channel();
        tokio::spawn(async move {
            let deadline = started + lifetime;
            let startup = deadline.min(started + config.startup_timeout);
            let acquisition = Lease::register_vm(&config.supervisor, specification, startup).await;
            let (result, cleanup) = match acquisition {
                Ok(mut lease) => {
                    let work = async {
                        let (_, path) = lease.vm_created(startup).await?;
                        #[cfg(unix)]
                        {
                            transact(
                                &path,
                                request,
                                input,
                                startup,
                                config.files.as_deref(),
                                config.snapshot.as_deref(),
                            )
                            .await
                        }
                        #[cfg(not(unix))]
                        {
                            transact(&path, request, input, startup).await
                        }
                    };
                    let result = tokio::select! {
                        biased;
                        _=stop.cancelled()=>Err(anyhow::anyhow!("Firecracker execution cancelled")),
                        _=run_stop.cancelled()=>Err(anyhow::anyhow!("Firecracker execution run closed")),
                        result=tokio::time::timeout_at(deadline.into(),work)=>result.map_err(|_|anyhow::anyhow!("Firecracker execution deadline expired")).and_then(|r|r),
                    };
                    let outcome = lease.finish().await;
                    let cleanup = lease.finish_cleanup().await.map_err(|e| e.to_string());
                    let result = result.and_then(|result| outcome.map(|()| result));
                    (result, cleanup)
                }
                Err(error)
                    if error
                        .downcast_ref::<super::supervisor::CreationRefused>()
                        .is_some() =>
                {
                    (Err(error), Ok(()))
                }
                Err(error) => {
                    let message =
                        format!("VM registration failed without cleanup acknowledgement: {error}");
                    (Err(error), Err(message))
                }
            };
            if let Some(registration) = registration {
                registration.finish(cleanup.clone());
            }
            let result = match cleanup {
                Ok(()) => result,
                Err(error) => Err(anyhow::anyhow!("Firecracker cleanup failed: {error}")),
            };
            #[cfg(unix)]
            if result.is_ok() {
                if let Some(snapshot) = &config.snapshot {
                    snapshot.complete();
                }
            }
            #[cfg(unix)]
            if result.as_ref().is_ok_and(|result| result.success) {
                if let Some(files) = &config.files {
                    files.complete();
                }
            }
            let _ = send.send(result.map(|mut result| {
                result.execution_time_ms =
                    started.elapsed().as_millis().min(u64::MAX as u128) as u64;
                result
            }));
        });
        let result = receive
            .await
            .map_err(|_| anyhow::anyhow!("Firecracker execution owner ended"))?;
        drop(guard);
        result
    }
}
struct CancelOnDrop(CancellationToken);
impl Drop for CancelOnDrop {
    fn drop(&mut self) {
        self.0.cancel();
    }
}

#[cfg(unix)]
async fn read_header<T: serde::de::DeserializeOwned>(
    stream: &mut tokio::net::UnixStream,
) -> anyhow::Result<T> {
    use tokio::io::AsyncReadExt;
    let length = stream.read_u32().await? as usize;
    if length == 0 || length > guest::MAX_HEADER {
        anyhow::bail!("invalid guest header length");
    }
    let mut data = vec![0; length];
    stream.read_exact(&mut data).await?;
    Ok(serde_json::from_slice(&data)?)
}
#[cfg(unix)]
async fn connect_guest(path: &Path, startup: Instant) -> anyhow::Result<tokio::net::UnixStream> {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    let mut stream = loop {
        if Instant::now() >= startup {
            anyhow::bail!("Firecracker guest did not become ready before startup deadline");
        }
        let attempt = async {
            let mut stream = tokio::net::UnixStream::connect(path).await?;
            stream
                .write_all(format!("CONNECT {}\n", guest::PORT).as_bytes())
                .await?;
            let mut line = Vec::new();
            loop {
                let byte = stream.read_u8().await?;
                if byte == b'\n' {
                    break;
                }
                if line.len() >= 64 {
                    anyhow::bail!("invalid vsock acknowledgement");
                }
                line.push(byte);
            }
            let line = std::str::from_utf8(&line)?;
            line.strip_prefix("OK ")
                .ok_or_else(|| anyhow::anyhow!("vsock connection refused"))?
                .parse::<u32>()?;
            Ok::<_, anyhow::Error>(stream)
        };
        match tokio::time::timeout_at(
            startup
                .min(Instant::now() + Duration::from_millis(250))
                .into(),
            attempt,
        )
        .await
        {
            Ok(Ok(stream)) => break stream,
            _ => tokio::time::sleep(Duration::from_millis(10)).await,
        }
    };
    let hello: guest::Hello = tokio::time::timeout_at(startup.into(), read_header(&mut stream))
        .await
        .map_err(|_| anyhow::anyhow!("Firecracker guest handshake deadline expired"))??;
    if hello.version != guest::VERSION || hello.implementation != guest::IMPLEMENTATION {
        anyhow::bail!("Firecracker guest protocol mismatch");
    }
    Ok(stream)
}
#[cfg(unix)]
async fn transact(
    path: &Path,
    mut request: guest::Command,
    input: Vec<u8>,
    startup: Instant,
    files: Option<&files::Transfer>,
    snapshot: Option<&snapshot::Transfer>,
) -> anyhow::Result<ExecutionResult> {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    let connected = Instant::now();
    let mut stream = connect_guest(path, startup).await?;
    request.timeout_ms = request
        .timeout_ms
        .saturating_sub(connected.elapsed().as_millis().min(u64::MAX as u128) as u64);
    request.validate()?;
    let header = guest::encode_header(&request)?;
    stream.write_u32(header.len() as u32).await?;
    stream.write_all(&header).await?;
    if let Some(snapshot) = snapshot {
        snapshot.upload(&mut stream).await?;
    }
    if let Some(files) = files {
        files.upload(&mut stream).await?;
    }
    stream.write_all(&input).await?;
    let result: guest::Outcome = read_header(&mut stream).await?;
    result.validate(&request)?;
    let mut stdout = vec![0; result.stdout_length];
    let mut stderr = vec![0; result.stderr_length];
    stream.read_exact(&mut stdout).await?;
    stream.read_exact(&mut stderr).await?;
    if let Some(receipt) = &result.file_output {
        files
            .ok_or_else(|| anyhow::anyhow!("unsolicited guest file output"))?
            .receive(&mut stream, receipt)
            .await?;
    }
    if stream.read(&mut [0; 1]).await? != 0 {
        anyhow::bail!("unexpected bytes after guest outcome");
    }
    if let Some(receipt) = result.snapshot.clone() {
        snapshot
            .ok_or_else(|| anyhow::anyhow!("unexpected guest snapshot receipt"))?
            .observed(receipt)?;
    }
    let mut stderr = String::from_utf8_lossy(&stderr).into_owned();
    if let Some(error) = &result.error {
        stderr.push_str(&format!("\n{error}"));
    }
    if result.timed_out {
        stderr.push_str("\nguest command deadline expired");
    }
    Ok(ExecutionResult {
        exit_code: result.exit_code,
        stdout: String::from_utf8_lossy(&stdout).into_owned(),
        stderr,
        execution_time_ms: 0,
        success: result.success(),
        stdout_truncated: result.stdout_truncated,
        stderr_truncated: result.stderr_truncated,
    })
}
#[cfg(not(unix))]
async fn transact(
    _: &Path,
    _: guest::Command,
    _: Vec<u8>,
    _: Instant,
) -> anyhow::Result<ExecutionResult> {
    anyhow::bail!("Firecracker guest transport requires Linux")
}

#[async_trait]
impl SandboxRunner for FirecrackerRunner {
    async fn execute(
        &self,
        code: &str,
        environment: HashMap<String, String>,
    ) -> anyhow::Result<ExecutionResult> {
        self.execute_command(
            &["/bin/sh".into(), "-c".into(), code.into()],
            environment,
            None,
            false,
            self.config.max_execution_time,
        )
        .await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn missing_artifacts_and_unsafe_limits_are_refused() {
        assert!(FirecrackerConfig::default()
            .validate()
            .unwrap_err()
            .to_string()
            .contains("kernel_image_path"));
        let kernel = tempfile::NamedTempFile::new().unwrap();
        let rootfs = tempfile::NamedTempFile::new().unwrap();
        let mut config = FirecrackerConfig {
            kernel_image_path: kernel.path().into(),
            rootfs_path: rootfs.path().into(),
            ..Default::default()
        };
        config.validate().unwrap();
        config.rootfs_read_only = false;
        assert!(config.validate().is_err());
        config.rootfs_read_only = true;
        config.max_output_bytes = usize::MAX;
        assert!(config.validate().is_err());
        config.max_output_bytes = 1024;
        config.max_execution_time = Duration::ZERO;
        assert!(config.validate().is_err());
    }
    #[test]
    fn vm_configuration_has_a_real_guest_channel_without_network() {
        let runner = FirecrackerRunner {
            config: FirecrackerConfig::default(),
        };
        let value = runner.build_vm_config_json(Path::new("/private/vsock"));
        assert_eq!(value["vsock"]["uds_path"], "/private/vsock");
        assert_eq!(value["drives"][0]["is_read_only"], true);
        assert!(value.get("network-interfaces").is_none());
        assert!(value.get("logger").is_none());
    }
    #[cfg(unix)]
    #[tokio::test]
    async fn guest_response_must_be_complete_correlated_and_bounded() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        for mode in [
            "valid",
            "wrong_id",
            "wrong_version",
            "oversized_output",
            "oversized_header",
            "zero_header",
            "malformed_header",
            "unknown_field",
            "truncated_stream",
            "extra_stream",
            "stale_hello",
            "stalled_hello",
        ] {
            let directory = tempfile::tempdir().unwrap();
            let socket = directory.path().join("vsock");
            let listener = tokio::net::UnixListener::bind(&socket).unwrap();
            let request = guest::Command {
                mode: guest::CommandMode::OneShot,
                version: guest::VERSION,
                id: uuid::Uuid::new_v4().to_string(),
                argv: vec!["/bin/true".into()],
                environment: Default::default(),
                working_dir: "/tmp".into(),
                input_length: 0,
                input_as_file: false,
                files: None,
                snapshot: None,
                max_output_bytes: 4,
                timeout_ms: 1000,
            };
            let expected_id = request.id.clone();
            let server = tokio::spawn(async move {
                let (mut peer, _) = listener.accept().await.unwrap();
                let mut connect = Vec::new();
                loop {
                    let byte = peer.read_u8().await.unwrap();
                    connect.push(byte);
                    if byte == b'\n' {
                        break;
                    }
                }
                assert_eq!(connect, b"CONNECT 4050\n");
                peer.write_all(b"OK 12345\n").await.unwrap();
                if mode == "stalled_hello" {
                    let mut received = Vec::new();
                    peer.read_to_end(&mut received).await.unwrap();
                    assert!(received.is_empty(), "payload sent before handshake");
                    return;
                }
                let hello = guest::Hello {
                    version: guest::VERSION,
                    implementation: if mode == "stale_hello" {
                        "stale".into()
                    } else {
                        guest::IMPLEMENTATION.into()
                    },
                };
                let mut bytes = vec![];
                guest::write_header(&mut bytes, &hello).unwrap();
                peer.write_all(&bytes).await.unwrap();
                if mode == "stale_hello" {
                    let mut received = Vec::new();
                    peer.read_to_end(&mut received).await.unwrap();
                    assert!(received.is_empty(), "payload sent to a stale guest");
                    return;
                }
                let actual: guest::Command = read_header(&mut peer).await.unwrap();
                assert_eq!(actual.id, expected_id);
                let mut outcome = serde_json::json!({"version":guest::VERSION,"id":expected_id,
                    "exit_code":0,"stdout_length":2,"stderr_length":0,
                    "stdout_truncated":false,"stderr_truncated":false,"timed_out":false,"error":null,"file_output":null,"finalized":false});
                match mode {
                    "wrong_id" => outcome["id"] = uuid::Uuid::new_v4().to_string().into(),
                    "wrong_version" => outcome["version"] = 99.into(),
                    "oversized_output" => outcome["stdout_length"] = 5.into(),
                    "unknown_field" => outcome["invented_success"] = true.into(),
                    "oversized_header" => {
                        let _ = peer.write_u32(guest::MAX_HEADER as u32 + 1).await;
                        return;
                    }
                    "zero_header" => {
                        let _ = peer.write_u32(0).await;
                        return;
                    }
                    "malformed_header" => {
                        let _ = peer.write_all(b"\x00\x00\x00\x01{").await;
                        return;
                    }
                    _ => {}
                }
                bytes.clear();
                guest::write_header(&mut bytes, &outcome).unwrap();
                bytes.extend_from_slice(match mode {
                    "truncated_stream" => b"o",
                    "extra_stream" => b"ok!",
                    _ => b"ok",
                });
                let _ = peer.write_all(&bytes).await;
            });
            let result = tokio::time::timeout(
                Duration::from_secs(2),
                transact(
                    &socket,
                    request,
                    vec![],
                    Instant::now() + Duration::from_millis(200),
                    None,
                    None,
                ),
            )
            .await
            .expect("guest frame processing hung");
            if mode == "valid" {
                let result = result.unwrap();
                assert!(result.success);
                assert_eq!(result.stdout, "ok");
            } else {
                assert!(result.is_err(), "accepted invalid response: {mode}");
            }
            server.await.unwrap();
        }
    }
}