aither-agent 0.27.0

AI agent framework with planning, memory, and tool execution for aither
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
//! The guard over scripted pressure, footprints and registry entries. The
//! jobs are `sleep` processes the tests start in their own process groups;
//! no test holds memory.

#![allow(clippy::assert_is_empty, clippy::significant_drop_tightening)]

use std::collections::HashMap;
use std::os::unix::process::CommandExt as _;
use std::process::{Child, Command};
use std::sync::{Arc, Mutex};

use aither_sandbox::{
    AnyContainerMemory, AnyFootprintReader, AnyFootprintRegistry, CgroupMemory, ContainerMemory,
    FootprintError, FootprintReader, FootprintRegistry, JobMemory, JobPlace, JobRegistry,
    JobStatus, KillCause, MemoryDomain, ResponseWindow, ScriptLanguage, TerminalMode,
    job_registry_channel,
};

use super::*;
use crate::clock::{AnyClock, ManualClock};

const GIB: u64 = 1024 * 1024 * 1024;
const WINDOW: Duration = Duration::from_secs(60);

/// The footprints the test says processes hold.
#[derive(Clone, Default)]
struct Footprints {
    by_pid: Arc<Mutex<HashMap<u32, u64>>>,
    physical: u64,
}

impl FootprintReader for Footprints {
    fn tree_footprints(&self, roots: &[u32]) -> Result<Vec<u64>, FootprintError> {
        let by_pid = self.by_pid.lock().unwrap();
        Ok(roots
            .iter()
            .map(|pid| by_pid.get(pid).copied().unwrap_or(0))
            .collect())
    }

    fn physical_memory(&self) -> Result<u64, FootprintError> {
        Ok(self.physical)
    }
}

/// What every agent of the machine has published.
#[derive(Clone, Default)]
struct Machine(Arc<Mutex<HashMap<&'static str, u64>>>);

struct Entry {
    machine: Machine,
    agent: &'static str,
}

impl FootprintRegistry for Entry {
    fn publish(&self, total_bytes: u64) -> Result<(), FootprintError> {
        let mut entries = self.machine.0.lock().unwrap();
        if total_bytes == 0 {
            entries.remove(self.agent);
        } else {
            entries.insert(self.agent, total_bytes);
        }
        Ok(())
    }

    fn others(&self) -> Result<Vec<u64>, FootprintError> {
        Ok(self
            .machine
            .0
            .lock()
            .unwrap()
            .iter()
            .filter(|(agent, _)| **agent != self.agent)
            .map(|(_, bytes)| *bytes)
            .collect())
    }
}

/// A harmless process standing for a job, in a group of its own.
struct Sleeper(Child);

impl Sleeper {
    fn start() -> Self {
        Self(
            Command::new("sleep")
                .arg("600")
                .process_group(0)
                .spawn()
                .unwrap(),
        )
    }

    fn pid(&self) -> u32 {
        self.0.id()
    }
}

impl Drop for Sleeper {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}

/// One agent: its jobs, and a guard over them.
struct Agent {
    registry: JobRegistry,
    footprints: Footprints,
    guard: RunawayGuard,
    sleepers: Vec<Sleeper>,
    window: ResponseWindow,
    /// The kill switches of the container jobs, by task.
    switches: Vec<(String, async_channel::Receiver<()>)>,
}

/// What the container's cgroup says, scripted.
#[derive(Clone)]
struct Cgroup(Arc<Mutex<CgroupState>>);

struct CgroupState {
    limit: Option<u64>,
    pressure: &'static str,
    jobs: HashMap<String, u64>,
}

const CALM: &str = "some avg10=0.00 avg60=0.00 avg300=0.00 total=0\nfull avg10=0.00 avg60=0.00 avg300=0.00 total=0";
const STALLED: &str = "some avg10=12.00 avg60=0.00 avg300=0.00 total=0\nfull avg10=0.00 avg60=0.00 avg300=0.00 total=0";
const THRASHING: &str = "some avg10=40.00 avg60=0.00 avg300=0.00 total=0\nfull avg10=15.00 avg60=0.00 avg300=0.00 total=0";

impl Cgroup {
    fn limited(limit: u64) -> Self {
        Self(Arc::new(Mutex::new(CgroupState {
            limit: Some(limit),
            pressure: CALM,
            jobs: HashMap::new(),
        })))
    }

    fn pressure(&self, pressure: &'static str) {
        self.0.lock().unwrap().pressure = pressure;
    }

    fn hold(&self, task_id: &str, bytes: u64) {
        self.0
            .lock()
            .unwrap()
            .jobs
            .insert(task_id.to_string(), bytes);
    }
}

impl ContainerMemory for Cgroup {
    fn cgroup(&self) -> impl Future<Output = Result<CgroupMemory, FootprintError>> + Send {
        let state = self.0.lock().unwrap();
        std::future::ready(Ok(CgroupMemory {
            current_bytes: state.jobs.values().sum(),
            limit_bytes: state.limit,
            pressure: state.pressure.to_string(),
        }))
    }

    fn job_footprints(
        &self,
        task_ids: &[String],
    ) -> impl Future<Output = Result<Vec<u64>, FootprintError>> + Send {
        let state = self.0.lock().unwrap();
        std::future::ready(Ok(task_ids
            .iter()
            .map(|id| state.jobs.get(id).copied().unwrap_or(0))
            .collect()))
    }
}

impl Agent {
    fn new(physical: u64, machine: Option<(&Machine, &'static str)>) -> Self {
        Self::build(physical, machine, None)
    }

    /// An agent that works in a container reading as `cgroup`.
    fn containerized(physical: u64, cgroup: &Cgroup) -> Self {
        Self::build(physical, None, Some(cgroup))
    }

    fn build(
        physical: u64,
        machine: Option<(&Machine, &'static str)>,
        cgroup: Option<&Cgroup>,
    ) -> Self {
        let (registry, service) = job_registry_channel();
        tokio::spawn(async move { service.serve().await });
        let footprints = Footprints {
            physical,
            ..Footprints::default()
        };
        let window = ResponseWindow::new(WINDOW);
        let memory = JobMemory::new(
            registry.clone(),
            AnyFootprintReader::new(footprints.clone()),
            machine.map(|(machine, agent)| {
                AnyFootprintRegistry::new(Entry {
                    machine: machine.clone(),
                    agent,
                })
            }),
            window.clone(),
        );
        let memory = match cgroup {
            Some(cgroup) => memory.with_container(AnyContainerMemory::new(cgroup.clone())),
            None => memory,
        };
        Self {
            registry,
            footprints,
            guard: RunawayGuard::new(memory),
            sleepers: Vec::new(),
            window,
            switches: Vec::new(),
        }
    }

    /// Starts a job inside the container holding `bytes`. A container job
    /// is killed through its kill switch, which the test keeps.
    async fn container_job(&mut self, cgroup: &Cgroup, task_id: &str, bytes: u64) {
        let pid = self.next_pid();
        self.registry
            .register_at(
                JobPlace::Container,
                pid,
                &aither_sandbox::test_ids::lease(task_id),
                "exec",
                task_id,
                ScriptLanguage::Shell,
                TerminalMode::Sandboxed,
            )
            .await;
        let (kill_tx, kill_rx) = async_channel::bounded::<()>(1);
        self.registry.attach_kill_switch(pid, kill_tx).await;
        self.switches.push((task_id.to_string(), kill_rx));
        cgroup
            .0
            .lock()
            .unwrap()
            .jobs
            .insert(task_id.to_string(), bytes);
        // The container's pid means nothing to the host: if it were read
        // there, this is what it would find.
        self.footprints
            .by_pid
            .lock()
            .unwrap()
            .insert(pid, 500 * GIB);
    }

    /// Starts a job on a remote host holding `bytes` there. Its local `ssh`
    /// stand-in is a real process, which must never be killed.
    async fn remote_job(&mut self, task_id: &str, bytes: u64) -> u32 {
        let sleeper = Sleeper::start();
        let pid = sleeper.pid();
        self.registry
            .register_at(
                JobPlace::Remote,
                pid,
                &aither_sandbox::test_ids::lease(task_id),
                "exec",
                task_id,
                ScriptLanguage::Shell,
                TerminalMode::Sandboxed,
            )
            .await;
        self.footprints.by_pid.lock().unwrap().insert(pid, bytes);
        self.sleepers.push(sleeper);
        pid
    }

    fn next_pid(&self) -> u32 {
        4_000_000 + u32::try_from(self.switches.len()).unwrap()
    }

    /// Whether the kill switch of the container job `task_id` was pulled.
    fn container_job_killed(&self, task_id: &str) -> bool {
        self.switches
            .iter()
            .find(|(id, _)| id == task_id)
            .is_some_and(|(_, rx)| rx.try_recv().is_ok())
    }

    /// Starts a job holding `bytes`.
    async fn job(&mut self, task_id: &str, bytes: u64) -> u32 {
        let sleeper = Sleeper::start();
        let pid = sleeper.pid();
        self.registry
            .register(
                pid,
                &aither_sandbox::test_ids::lease(task_id),
                "exec",
                task_id,
                TerminalMode::Sandboxed,
                None,
            )
            .await;
        self.footprints.by_pid.lock().unwrap().insert(pid, bytes);
        self.sleepers.push(sleeper);
        pid
    }

    async fn status(&self, task_id: &str) -> JobStatus {
        self.registry
            .get_by_task_id_settled(task_id)
            .await
            .expect("the job is registered")
            .status
    }
}

struct Clock {
    manual: ManualClock,
    any: AnyClock,
}

impl Clock {
    fn new() -> Self {
        let manual = ManualClock::new();
        Self {
            any: AnyClock::new(manual.clone()),
            manual,
        }
    }

    fn now(&self) -> Instant {
        self.any.now()
    }

    fn advance(&self, secs: u64) {
        self.manual.advance(Duration::from_secs(secs));
    }
}

fn task_ids(jobs: &[aither_sandbox::JobFootprint]) -> Vec<&str> {
    jobs.iter().map(|job| job.task_id.as_str()).collect()
}

#[tokio::test]
async fn yellow_red_and_dropped_back_alerts_fire_once_per_change_and_list_jobs_by_footprint() {
    let clock = Clock::new();
    let mut agent = Agent::new(64 * GIB, None);
    agent.job("small", GIB).await;
    agent.job("large", 4 * GIB).await;
    let mut observe = async |pressure| agent.guard.observe(clock.now(), Some(pressure)).await;

    assert!(observe(MemoryPressure::Normal).await.is_empty());
    let yellow = observe(MemoryPressure::Warning).await;
    let [HostLoadEvent::MemoryYellow { jobs, .. }] = yellow.as_slice() else {
        panic!("one yellow alert: {yellow:?}");
    };
    assert_eq!(task_ids(jobs), ["large", "small"]);
    assert!(observe(MemoryPressure::Warning).await.is_empty());

    let red = observe(MemoryPressure::Critical).await;
    let [HostLoadEvent::MemoryRed { jobs, .. }] = red.as_slice() else {
        panic!("one red alert: {red:?}");
    };
    assert_eq!(task_ids(jobs), ["large", "small"]);
    assert!(observe(MemoryPressure::Critical).await.is_empty());

    let dropped = observe(MemoryPressure::Warning).await;
    assert!(
        matches!(
            dropped.as_slice(),
            [HostLoadEvent::MemoryDroppedBack {
                level: MemoryPressure::Warning,
                ..
            }]
        ),
        "{dropped:?}"
    );
    let normal = observe(MemoryPressure::Normal).await;
    assert!(
        matches!(
            normal.as_slice(),
            [HostLoadEvent::MemoryDroppedBack {
                level: MemoryPressure::Normal,
                ..
            }]
        ),
        "{normal:?}"
    );
    assert!(observe(MemoryPressure::Normal).await.is_empty());
}

#[tokio::test]
async fn an_agent_over_physical_memory_loses_its_largest_job_when_the_window_ends_unanswered() {
    let clock = Clock::new();
    let mut agent = Agent::new(10 * GIB, None);
    agent.job("small", 3 * GIB).await;
    agent.job("large", 8 * GIB).await;

    let warned = agent
        .guard
        .observe(clock.now(), Some(MemoryPressure::Normal))
        .await;
    let [HostLoadEvent::MemoryFinalWarning { job, window, .. }] = warned.as_slice() else {
        panic!("the final warning: {warned:?}");
    };
    assert_eq!((job.task_id.as_str(), *window), ("large", WINDOW));

    clock.advance(59);
    assert!(
        agent
            .guard
            .observe(clock.now(), Some(MemoryPressure::Normal))
            .await
            .is_empty()
    );
    assert_eq!(agent.status("large").await, JobStatus::Running);

    clock.advance(1);
    let killed = agent
        .guard
        .observe(clock.now(), Some(MemoryPressure::Normal))
        .await;
    assert!(
        matches!(
            killed.as_slice(),
            [HostLoadEvent::JobKilledForMemory { task_id, .. }] if task_id == "large"
        ),
        "{killed:?}"
    );
    assert!(matches!(
        agent.status("large").await,
        JobStatus::Killed {
            cause: KillCause::MemoryRunaway {
                footprint_bytes,
                capacity_bytes,
                domain: MemoryDomain::Machine,
            },
            ..
        } if footprint_bytes == 8 * GIB && capacity_bytes == 10 * GIB
    ));
    assert_eq!(agent.status("small").await, JobStatus::Running);
}

#[tokio::test]
async fn a_job_the_agent_stopped_in_time_is_not_killed_and_reports_a_user_kill() {
    let clock = Clock::new();
    let mut agent = Agent::new(10 * GIB, None);
    agent.job("small", 3 * GIB).await;
    let large = agent.job("large", 8 * GIB).await;

    let warned = agent
        .guard
        .observe(clock.now(), Some(MemoryPressure::Normal))
        .await;
    assert_eq!(warned.len(), 1, "{warned:?}");
    clock.advance(30);
    assert!(agent.registry.kill(large).await);
    // The processes are gone, so the agent's jobs fit the machine again.
    agent.footprints.by_pid.lock().unwrap().insert(large, 0);

    clock.advance(120);
    let after = agent
        .guard
        .observe(clock.now(), Some(MemoryPressure::Normal))
        .await;
    assert!(after.is_empty(), "{after:?}");
    assert!(matches!(
        agent.status("large").await,
        JobStatus::Killed {
            cause: KillCause::User,
            ..
        }
    ));
    assert_eq!(agent.status("small").await, JobStatus::Running);
}

#[tokio::test]
async fn jobs_under_physical_memory_are_never_killed_whatever_the_pressure() {
    let clock = Clock::new();
    let mut agent = Agent::new(10 * GIB, None);
    agent.job("a", 4 * GIB).await;
    agent.job("b", 5 * GIB).await;
    for pressure in [
        MemoryPressure::Critical,
        MemoryPressure::Critical,
        MemoryPressure::Warning,
    ] {
        clock.advance(600);
        let events = agent.guard.observe(clock.now(), Some(pressure)).await;
        assert!(
            events.iter().all(|event| !matches!(
                event,
                HostLoadEvent::MemoryFinalWarning { .. } | HostLoadEvent::JobKilledForMemory { .. }
            )),
            "{events:?}"
        );
    }
    assert_eq!(agent.status("a").await, JobStatus::Running);
    assert_eq!(agent.status("b").await, JobStatus::Running);
}

#[tokio::test]
async fn the_machine_over_physical_memory_costs_the_largest_contributor_only_while_critical() {
    let clock = Clock::new();
    let machine = Machine::default();
    let mut big = Agent::new(50 * GIB, Some((&machine, "big")));
    let mut small = Agent::new(50 * GIB, Some((&machine, "small")));
    big.job("anchor", 25 * GIB).await;
    big.job("bridge", 10 * GIB).await;
    small.job("canyon", 20 * GIB).await;
    // Both publish; 55 GiB together on a machine of 50.
    for agent in [&mut big, &mut small] {
        agent
            .guard
            .observe(clock.now(), Some(MemoryPressure::Warning))
            .await;
    }

    // Below critical nothing is warned about, however long it lasts.
    clock.advance(600);
    for agent in [&mut big, &mut small] {
        let events = agent
            .guard
            .observe(clock.now(), Some(MemoryPressure::Warning))
            .await;
        assert!(events.is_empty(), "{events:?}");
    }

    // Critical: only the agent contributing the most is warned, about its
    // largest job.
    let small_events = small
        .guard
        .observe(clock.now(), Some(MemoryPressure::Critical))
        .await;
    assert!(
        small_events
            .iter()
            .all(|event| !matches!(event, HostLoadEvent::MemoryFinalWarning { .. })),
        "{small_events:?}"
    );
    let big_events = big
        .guard
        .observe(clock.now(), Some(MemoryPressure::Critical))
        .await;
    assert!(
        big_events.iter().any(|event| matches!(
            event,
            HostLoadEvent::MemoryFinalWarning { job, .. } if job.task_id == "anchor"
        )),
        "{big_events:?}"
    );

    clock.advance(60);
    let killed = big
        .guard
        .observe(clock.now(), Some(MemoryPressure::Critical))
        .await;
    assert!(
        matches!(
            killed.as_slice(),
            [HostLoadEvent::JobKilledForMemory { task_id, .. }] if task_id == "anchor"
        ),
        "{killed:?}"
    );
    assert!(matches!(
        big.status("anchor").await,
        JobStatus::Killed {
            cause: KillCause::MemoryRunaway { .. },
            ..
        }
    ));
    assert_eq!(big.status("bridge").await, JobStatus::Running);
    // The killed processes hold nothing now: 30 GiB together fits.
    let killed_pid = big.registry.get_by_task_id("anchor").await.unwrap().pid;
    big.footprints.by_pid.lock().unwrap().insert(killed_pid, 0);
    clock.advance(600);
    for agent in [&mut big, &mut small] {
        let events = agent
            .guard
            .observe(clock.now(), Some(MemoryPressure::Critical))
            .await;
        assert!(
            events
                .iter()
                .all(|event| !matches!(event, HostLoadEvent::MemoryFinalWarning { .. })),
            "the machine fits again: {events:?}"
        );
    }
    assert_eq!(small.status("canyon").await, JobStatus::Running);
}

#[tokio::test]
async fn kills_continue_down_the_contributors_while_both_conditions_hold() {
    let clock = Clock::new();
    let machine = Machine::default();
    let mut first = Agent::new(20 * GIB, Some((&machine, "first")));
    let mut second = Agent::new(20 * GIB, Some((&machine, "second")));
    let first_pid = first.job("first", 15 * GIB).await;
    second.job("second", 12 * GIB).await;
    let critical = Some(MemoryPressure::Critical);

    // 27 GiB together on 20: the first contributes the most.
    second.guard.observe(clock.now(), critical).await;
    let warned = first.guard.observe(clock.now(), critical).await;
    assert!(
        warned
            .iter()
            .any(|event| matches!(event, HostLoadEvent::MemoryFinalWarning { .. })),
        "{warned:?}"
    );
    let second_warned = second.guard.observe(clock.now(), critical).await;
    assert!(
        second_warned
            .iter()
            .all(|event| !matches!(event, HostLoadEvent::MemoryFinalWarning { .. })),
        "{second_warned:?}"
    );

    clock.advance(60);
    first.guard.observe(clock.now(), critical).await;
    first.footprints.by_pid.lock().unwrap().insert(first_pid, 0);
    assert!(matches!(
        first.status("first").await,
        JobStatus::Killed {
            cause: KillCause::MemoryRunaway { .. },
            ..
        }
    ));

    // 12 GiB is under 20: nothing more. Shrink the machine to keep both
    // conditions true, and the second contributor is next.
    let mut second_only = second;
    second_only.footprints.physical = 8 * GIB;
    second_only.guard = RunawayGuard::new(JobMemory::new(
        second_only.registry.clone(),
        AnyFootprintReader::new(second_only.footprints.clone()),
        Some(AnyFootprintRegistry::new(Entry {
            machine: machine.clone(),
            agent: "second",
        })),
        second_only.window.clone(),
    ));
    clock.advance(10);
    let next = second_only.guard.observe(clock.now(), critical).await;
    assert!(
        next.iter().any(|event| matches!(
            event,
            HostLoadEvent::MemoryFinalWarning { job, .. } if job.task_id == "second"
        )),
        "{next:?}"
    );
    clock.advance(60);
    second_only.guard.observe(clock.now(), critical).await;
    assert!(matches!(
        second_only.status("second").await,
        JobStatus::Killed {
            cause: KillCause::MemoryRunaway { .. },
            ..
        }
    ));
}

#[test]
fn the_alerts_read_as_plain_text() {
    let job = |task: &str, gib| aither_sandbox::JobFootprint {
        task_id: task.to_string(),
        command: format!("run {task}"),
        pid: 1,
        footprint_bytes: gib * GIB,
    };
    let red = HostLoadEvent::MemoryRed {
        domain: MemoryDomain::Machine,
        jobs: vec![job("big", 36), job("small", 1)],
    };
    assert_eq!(
        red.alert_text(),
        "The machine's memory is critically tight (pressure: critical). Stop the jobs you can do without now; a job that keeps growing may be killed. Your running jobs by memory, largest first:\n- 'big' (`run big`): 36.0 GiB\n- 'small' (`run small`): 1.0 GiB"
    );
    let killed = HostLoadEvent::JobKilledForMemory {
        domain: MemoryDomain::Machine,
        task_id: "big".to_string(),
        command: "run big".to_string(),
        footprint: MemorySize(36 * GIB),
        capacity: MemorySize(32 * GIB),
    };
    assert_eq!(
        killed.alert_text(),
        "Job 'big' (`run big`) was killed with everything it started: it held 36.0 GiB of the 32.0 GiB of memory the machine has, and the final warning went unanswered."
    );
    let container = HostLoadEvent::MemoryFinalWarning {
        domain: MemoryDomain::Container,
        job: job("big", 3),
        window: WINDOW,
        capacity: MemorySize(4 * GIB),
    };
    assert_eq!(
        container.alert_text(),
        "Final memory warning: job 'big' (`run big`) holds 3.0 GiB of memory and is killed in 60s, with everything it started, unless you stop it or free memory yourself. The container has 4.0 GiB of memory in all."
    );
}

const fn is_container(event: &HostLoadEvent) -> bool {
    matches!(
        event,
        HostLoadEvent::MemoryYellow {
            domain: MemoryDomain::Container,
            ..
        } | HostLoadEvent::MemoryRed {
            domain: MemoryDomain::Container,
            ..
        } | HostLoadEvent::MemoryDroppedBack {
            domain: MemoryDomain::Container,
            ..
        } | HostLoadEvent::MemoryFinalWarning {
            domain: MemoryDomain::Container,
            ..
        } | HostLoadEvent::JobKilledForMemory {
            domain: MemoryDomain::Container,
            ..
        }
    )
}

#[tokio::test]
async fn a_containers_own_pressure_raises_its_own_alerts_once_per_change() {
    let clock = Clock::new();
    let cgroup = Cgroup::limited(8 * GIB);
    let mut agent = Agent::containerized(64 * GIB, &cgroup);
    agent.container_job(&cgroup, "small", GIB).await;
    agent.container_job(&cgroup, "large", 3 * GIB).await;
    // The machine is calm throughout: only the container's pressure moves.
    let mut observe = async |pressure| {
        cgroup.pressure(pressure);
        agent
            .guard
            .observe(clock.now(), Some(MemoryPressure::Normal))
            .await
    };

    assert!(observe(CALM).await.is_empty());
    let yellow = observe(STALLED).await;
    let [HostLoadEvent::MemoryYellow { domain, jobs }] = yellow.as_slice() else {
        panic!("one yellow alert: {yellow:?}");
    };
    assert_eq!(*domain, MemoryDomain::Container);
    assert_eq!(task_ids(jobs), ["large", "small"]);
    assert!(observe(STALLED).await.is_empty());

    let red = observe(THRASHING).await;
    assert!(
        matches!(
            red.as_slice(),
            [HostLoadEvent::MemoryRed {
                domain: MemoryDomain::Container,
                ..
            }]
        ),
        "{red:?}"
    );
    assert!(observe(THRASHING).await.is_empty());

    let dropped = observe(STALLED).await;
    assert!(
        matches!(
            dropped.as_slice(),
            [HostLoadEvent::MemoryDroppedBack {
                domain: MemoryDomain::Container,
                level: MemoryPressure::Warning,
                ..
            }]
        ),
        "{dropped:?}"
    );
    let normal = observe(CALM).await;
    assert!(
        matches!(
            normal.as_slice(),
            [HostLoadEvent::MemoryDroppedBack {
                domain: MemoryDomain::Container,
                level: MemoryPressure::Normal,
                ..
            }]
        ),
        "{normal:?}"
    );
    assert!(observe(CALM).await.is_empty());
}

#[tokio::test]
async fn a_container_is_judged_against_its_own_limit_not_the_machines_memory() {
    let clock = Clock::new();
    let cgroup = Cgroup::limited(4 * GIB);
    // The machine has 64 GiB, so 4 GiB of jobs would be nothing to it.
    let mut agent = Agent::containerized(64 * GIB, &cgroup);
    agent.container_job(&cgroup, "small", GIB).await;
    agent.container_job(&cgroup, "large", 3 * GIB).await;
    let normal = Some(MemoryPressure::Normal);

    // Together the jobs fill the limit: the final warning names the largest.
    let warned = agent.guard.observe(clock.now(), normal).await;
    let [
        HostLoadEvent::MemoryFinalWarning {
            domain,
            job,
            window,
            capacity,
        },
    ] = warned.as_slice()
    else {
        panic!("the final warning: {warned:?}");
    };
    assert_eq!(*domain, MemoryDomain::Container);
    assert_eq!((job.task_id.as_str(), *window), ("large", WINDOW));
    assert_eq!(*capacity, MemorySize(4 * GIB));

    clock.advance(59);
    assert!(agent.guard.observe(clock.now(), normal).await.is_empty());
    assert!(!agent.container_job_killed("large"));

    clock.advance(1);
    let killed = agent.guard.observe(clock.now(), normal).await;
    assert!(
        matches!(
            killed.as_slice(),
            [HostLoadEvent::JobKilledForMemory {
                domain: MemoryDomain::Container,
                task_id,
                ..
            }] if task_id == "large"
        ),
        "{killed:?}"
    );
    assert!(agent.container_job_killed("large"));
    assert!(matches!(
        agent.status("large").await,
        JobStatus::Killed {
            cause: KillCause::MemoryRunaway {
                footprint_bytes,
                capacity_bytes,
                domain: MemoryDomain::Container,
            },
            ..
        } if footprint_bytes == 3 * GIB && capacity_bytes == 4 * GIB
    ));
    assert_eq!(agent.status("small").await, JobStatus::Running);
}

#[tokio::test]
async fn a_container_job_the_agent_stopped_in_time_is_not_killed() {
    let clock = Clock::new();
    let cgroup = Cgroup::limited(4 * GIB);
    let mut agent = Agent::containerized(64 * GIB, &cgroup);
    agent.container_job(&cgroup, "large", 4 * GIB).await;
    let normal = Some(MemoryPressure::Normal);

    assert_eq!(agent.guard.observe(clock.now(), normal).await.len(), 1);
    clock.advance(30);
    assert!(agent.registry.kill_by_task_id("large").await);
    cgroup.hold("large", 0);

    clock.advance(120);
    assert!(agent.guard.observe(clock.now(), normal).await.is_empty());
    assert!(matches!(
        agent.status("large").await,
        JobStatus::Killed {
            cause: KillCause::User,
            ..
        }
    ));
}

#[tokio::test]
async fn jobs_under_the_containers_limit_are_never_killed_whatever_the_pressure() {
    let clock = Clock::new();
    let cgroup = Cgroup::limited(8 * GIB);
    let mut agent = Agent::containerized(64 * GIB, &cgroup);
    agent.container_job(&cgroup, "a", 3 * GIB).await;
    agent.container_job(&cgroup, "b", 4 * GIB).await;
    for pressure in [THRASHING, THRASHING, STALLED] {
        clock.advance(600);
        cgroup.pressure(pressure);
        let events = agent
            .guard
            .observe(clock.now(), Some(MemoryPressure::Critical))
            .await;
        assert!(
            events.iter().all(|event| !matches!(
                event,
                HostLoadEvent::MemoryFinalWarning { .. } | HostLoadEvent::JobKilledForMemory { .. }
            )),
            "{events:?}"
        );
    }
    assert!(!agent.container_job_killed("a") && !agent.container_job_killed("b"));
}

#[tokio::test]
async fn a_container_without_a_memory_limit_adds_nothing_to_watch() {
    let clock = Clock::new();
    let cgroup = Cgroup::limited(4 * GIB);
    cgroup.0.lock().unwrap().limit = None;
    cgroup.pressure(THRASHING);
    let mut agent = Agent::containerized(64 * GIB, &cgroup);
    agent.container_job(&cgroup, "large", 100 * GIB).await;

    let events = agent
        .guard
        .observe(clock.now(), Some(MemoryPressure::Normal))
        .await;
    assert!(events.is_empty(), "{events:?}");
    clock.advance(600);
    assert!(
        agent
            .guard
            .observe(clock.now(), Some(MemoryPressure::Normal))
            .await
            .is_empty()
    );
    assert!(!agent.container_job_killed("large"));
}

#[tokio::test]
async fn the_machine_and_the_container_are_judged_apart() {
    let clock = Clock::new();
    let cgroup = Cgroup::limited(8 * GIB);
    let mut agent = Agent::containerized(10 * GIB, &cgroup);
    agent.container_job(&cgroup, "boxed", 2 * GIB).await;
    // A local job over the machine's memory is the machine's trouble alone.
    agent.job("local", 11 * GIB).await;

    let events = agent
        .guard
        .observe(clock.now(), Some(MemoryPressure::Normal))
        .await;
    let [
        HostLoadEvent::MemoryFinalWarning {
            domain: MemoryDomain::Machine,
            job,
            ..
        },
    ] = events.as_slice()
    else {
        panic!("only the machine warns: {events:?}");
    };
    assert_eq!(job.task_id, "local");
    assert!(!events.iter().any(is_container));
}

#[tokio::test]
async fn jobs_of_a_remote_environment_are_never_warned_about_or_killed() {
    let clock = Clock::new();
    let mut agent = Agent::new(10 * GIB, None);
    // The remote job's reading would be far past the machine's memory, if
    // anything ever read it.
    let remote = agent.remote_job("remote", 500 * GIB).await;
    agent.job("local", GIB).await;

    for pressure in [
        MemoryPressure::Warning,
        MemoryPressure::Critical,
        MemoryPressure::Critical,
    ] {
        clock.advance(600);
        let events = agent.guard.observe(clock.now(), Some(pressure)).await;
        assert!(
            events.iter().all(|event| !matches!(
                event,
                HostLoadEvent::MemoryFinalWarning { .. } | HostLoadEvent::JobKilledForMemory { .. }
            )),
            "{events:?}"
        );
        for event in &events {
            if let HostLoadEvent::MemoryYellow { jobs, .. }
            | HostLoadEvent::MemoryRed { jobs, .. } = event
            {
                assert_eq!(task_ids(jobs), ["local"], "the remote job is not listed");
            }
        }
    }
    assert_eq!(agent.status("remote").await, JobStatus::Running);
    // Its stand-in process is still alive.
    assert!(
        agent.sleepers.iter().any(|sleeper| sleeper.pid() == remote),
        "the remote job's process was left alone"
    );
    assert_eq!(agent.registry.kill_running().await, 2);
}

#[tokio::test]
async fn a_remote_job_in_a_container_terminal_is_still_never_judged() {
    let clock = Clock::new();
    let cgroup = Cgroup::limited(4 * GIB);
    let mut agent = Agent::containerized(10 * GIB, &cgroup);
    agent.remote_job("remote", 500 * GIB).await;
    // The container's cgroup knows nothing of the remote job either.
    cgroup.hold("remote", 500 * GIB);
    cgroup.pressure(THRASHING);

    let events = agent
        .guard
        .observe(clock.now(), Some(MemoryPressure::Critical))
        .await;
    assert!(
        events.iter().all(|event| !matches!(
            event,
            HostLoadEvent::MemoryFinalWarning { .. } | HostLoadEvent::JobKilledForMemory { .. }
        )),
        "{events:?}"
    );
    clock.advance(600);
    assert!(
        agent
            .guard
            .observe(clock.now(), Some(MemoryPressure::Critical))
            .await
            .iter()
            .all(|event| !matches!(event, HostLoadEvent::JobKilledForMemory { .. }))
    );
    assert_eq!(agent.status("remote").await, JobStatus::Running);
}