aver-cert 0.1.7

Independent artifact certificate engine and verifier for Aver WebAssembly
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
//! Hermetic subprocess boundary for the checker-owned Lean toolchain.
//!
//! Lake's `env` command prepends project/toolchain search paths to ambient
//! `LEAN_PATH` and `LEAN_SRC_PATH`; it does not replace them. Every verifier
//! subprocess therefore starts from an empty environment. The Elan home is the
//! explicit bootstrap trust anchor: its canonical `bin/elan` is selected once,
//! invoked by absolute path, and told to run the exact embedded toolchain.

use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Output, Stdio};
use std::time::{Duration, Instant};

/// Overrides the per-step wall-clock limit, in whole seconds, for every Lean
/// toolchain subprocess on the verify/check path.
const PHASE_TIMEOUT_ENV: &str = "AVER_CERT_PHASE_TIMEOUT_SECS";
/// Generous default: real certificate verifies take minutes per step, and the
/// first run on a machine may also install the pinned toolchain.
const DEFAULT_PHASE_TIMEOUT: Duration = Duration::from_secs(15 * 60);
/// Upper bound for the override: one day per step. Far beyond any real
/// verify, and it keeps every deadline computation trivially in range.
const MAX_PHASE_TIMEOUT_SECS: u64 = 24 * 60 * 60;
/// Overrides the per-worker Lean heap ceiling, in whole MiB, for every `lean`
/// the verify/check path spawns: injected as `--memory` on direct
/// `lake env lean` steps here, and via `moreLeanArgs` in the generated
/// checker lakefiles for `lake build` steps.
pub(crate) const MEMORY_LIMIT_ENV: &str = "AVER_CERT_MEMORY_LIMIT_MB";
/// Default heap ceiling: 16 GiB. This bounds the heap Lean itself accounts
/// for, which is what a runaway term-level elaboration grows, and an
/// over-budget step then fails with Lean's own memory diagnostic instead of
/// running until the step timeout.
///
/// It does NOT bound the process. Measured on a 32 GiB host (Lean 4.32): a
/// certificate module whose acceptance theorem walks the artifact bytes was
/// killed by the operating system (exit 137) under both a 16 GiB and an 8 GiB
/// ceiling, having driven the host into swap either way. That growth comes
/// from arbitrary-precision arithmetic, whose allocations sit outside the
/// accounted heap, so no value here catches it. The packages the producer
/// writes now keep every module small (see `WORKER_MEMORY_BUDGET_MB`), which
/// is what the worker count below is derived from; a hostile or unusual
/// package can still exceed it, so the wall-clock limit stays in place.
const DEFAULT_MEMORY_LIMIT_MB: u64 = 16 * 1024;
/// Overrides how many Lean workers `lake build` may run at once. Each worker
/// gets the full heap ceiling above, so the concurrency and the ceiling
/// multiply into the machine's real memory demand.
pub(crate) const BUILD_JOBS_ENV: &str = "AVER_CERT_BUILD_JOBS";
/// The worker count when the machine's available memory cannot be read.
const FALLBACK_BUILD_JOBS: u64 = 1;
/// The memory one Lean worker is budgeted when the worker count is derived
/// from the machine, in MiB. The packages the producer writes keep every
/// module of their build near 2 GiB at most (btc-listener, 1,093 certified
/// exports: 2.0 GiB), and the rest is margin for Lake and the operating
/// system. A package with larger modules can exceed it; a host that checks
/// such packages sets `AVER_CERT_BUILD_JOBS` itself.
const WORKER_MEMORY_BUDGET_MB: u64 = 4 * 1024;
/// Upper bound for the override: 1 TiB. Past that nothing legitimate is
/// being configured, and the bound keeps the flag rendering trivially sane.
const MAX_MEMORY_LIMIT_MB: u64 = 1024 * 1024;
/// How long cleanup after a kill may itself take (reaping the child, waiting
/// for the kill helper) before the cleanup is abandoned so the caller gets
/// its fail-closed error promptly.
const CLEANUP_LIMIT: Duration = Duration::from_secs(5);
const WAIT_POLL: Duration = Duration::from_millis(50);

/// Why a Lean toolchain step produced no usable output.
#[derive(Debug)]
pub(crate) enum LeanStepError {
    /// The step exceeded the per-step wall-clock limit and its process tree
    /// was stopped. Mandatory verifier steps fail closed on this; the prelude
    /// cache downgrades it to a loud cache miss.
    Timeout { phase: String, limit: Duration },
    /// The step could not be started, observed, or staged.
    Failed(String),
}

impl std::fmt::Display for LeanStepError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Timeout { phase, limit } => write!(
                formatter,
                "the {phase} step exceeded its {}-second time limit and was stopped; \
                 the certificate is not accepted (set {PHASE_TIMEOUT_ENV} to allow more time)",
                limit.as_secs()
            ),
            Self::Failed(reason) => formatter.write_str(reason),
        }
    }
}

pub(crate) struct LeanRunner {
    elan: PathBuf,
    elan_home: PathBuf,
    toolchain: String,
    system_environment: Vec<(&'static str, OsString)>,
    phase_timeout: Duration,
    memory_limit_mb: u64,
    build_jobs: u64,
}

impl LeanRunner {
    pub(crate) fn new(toolchain: &str) -> Result<Self, String> {
        Self::with_environment(toolchain, |name| std::env::var_os(name))
    }

    fn with_environment(
        toolchain: &str,
        environment: impl Fn(&str) -> Option<OsString>,
    ) -> Result<Self, String> {
        let toolchain = toolchain.trim();
        if toolchain.is_empty() || toolchain.chars().any(char::is_whitespace) {
            return Err("embedded Lean toolchain name is empty or malformed".to_string());
        }
        let phase_timeout = phase_timeout(&environment)?;
        let memory_limit_mb = memory_limit_mb(&environment)?;
        let build_jobs = build_jobs(&environment)?;

        #[cfg(windows)]
        let user_home =
            nonempty(environment("USERPROFILE")).or_else(|| nonempty(environment("HOME")));
        #[cfg(not(windows))]
        let user_home = nonempty(environment("HOME"));
        let elan_home = nonempty(environment("ELAN_HOME"))
            .map(PathBuf::from)
            .or_else(|| user_home.map(|home| PathBuf::from(home).join(".elan")))
            .ok_or_else(|| {
                "cannot resolve the pinned Lean toolchain: set ELAN_HOME or HOME".to_string()
            })?;
        let elan_home = std::fs::canonicalize(&elan_home).map_err(|error| {
            format!(
                "cannot resolve trusted Elan home {}: {error}",
                crate::verifier::shown_path(&elan_home)
            )
        })?;
        let elan_name = format!("elan{}", std::env::consts::EXE_SUFFIX);
        let elan = elan_home.join("bin").join(elan_name);
        let elan = std::fs::canonicalize(&elan).map_err(|error| {
            format!(
                "cannot resolve trusted Elan executable {}: {error}; install Elan there or set ELAN_HOME",
                crate::verifier::shown_path(&elan)
            )
        })?;
        if !elan.is_file() {
            return Err(format!(
                "trusted Elan executable is not a regular file: {}",
                crate::verifier::shown_path(&elan)
            ));
        }

        let system_environment = Vec::new();

        #[cfg(windows)]
        let mut system_environment = system_environment;
        #[cfg(windows)]
        {
            copy_if_present(&mut system_environment, "SYSTEMROOT", &environment);
            copy_if_present(&mut system_environment, "WINDIR", &environment);
        }

        Ok(Self {
            elan,
            elan_home,
            toolchain: toolchain.to_string(),
            system_environment,
            phase_timeout,
            memory_limit_mb,
            build_jobs,
        })
    }

    /// The Lean heap ceiling every worker runs under, in MiB. Exposed so the
    /// generated checker lakefiles can carry the same value into `lake build`
    /// workers via `moreLeanArgs` (Lake 4.32 ignores `LEAN_OPTS`, so the
    /// lakefile is the only channel that reaches build-spawned workers).
    pub(crate) fn memory_limit_mb(&self) -> u64 {
        self.memory_limit_mb
    }

    pub(crate) fn run_lake(
        &self,
        work_dir: &Path,
        phase: &str,
        arguments: &[&str],
    ) -> Result<Output, LeanStepError> {
        let work_dir = std::fs::canonicalize(work_dir).map_err(|error| {
            LeanStepError::Failed(format!(
                "cannot resolve checker-owned Lean work dir {}: {error}",
                crate::verifier::shown_path(work_dir)
            ))
        })?;
        let temp_dir = work_dir.join(format!(
            ".aver-cert-tmp-{}-{}",
            std::process::id(),
            unique_nanos()
        ));
        let mut builder = std::fs::DirBuilder::new();
        #[cfg(unix)]
        {
            use std::os::unix::fs::DirBuilderExt;
            builder.mode(0o700);
        }
        builder.create(&temp_dir).map_err(|error| {
            LeanStepError::Failed(format!(
                "cannot create checker-owned Lean temp dir {}: {error}",
                crate::verifier::shown_path(&temp_dir)
            ))
        })?;

        let output = run_with_timeout(
            self.lake_command(&work_dir, &temp_dir, arguments),
            self.phase_timeout,
            phase,
        );
        let _ = std::fs::remove_dir_all(&temp_dir);
        output
    }

    fn lake_command(&self, work_dir: &Path, temp_dir: &Path, arguments: &[&str]) -> Command {
        let mut command = Command::new(&self.elan);
        command.env_clear();
        command
            .env("ELAN_HOME", &self.elan_home)
            // Lake 4.32 reads its toolchain-local artifact cache by default.
            // Disable every implicit Lake cache; Aver caches are explicit,
            // content-addressed, and validated separately.
            .env("LAKE_ARTIFACT_CACHE", "0")
            .env("LAKE_RESTORE_ARTIFACTS", "0")
            .env("LAKE_NO_CACHE", "1")
            .env("LAKE_CACHE_DIR", "");
        for (name, value) in &self.system_environment {
            command.env(name, value);
        }

        // Never inherit an attacker-selected temp root. Both production callers
        // pass a newly created checker-owned project directory here.
        command
            .env("TMPDIR", temp_dir)
            .env("TMP", temp_dir)
            .env("TEMP", temp_dir)
            .current_dir(work_dir)
            .arg("run")
            .arg("--install")
            .arg(&self.toolchain)
            .arg("lake")
            .args(arguments.iter().take(DIRECT_LEAN_PREFIX.len()));
        // Direct `lake env lean` steps get the heap ceiling on the command
        // line; `lake build` workers get the same value through the generated
        // lakefile's `moreLeanArgs`. `lake env leanchecker` replays stored
        // oleans through the kernel and takes no `--memory` flag.
        if arguments.starts_with(&DIRECT_LEAN_PREFIX) {
            command.arg(format!("--memory={}", self.memory_limit_mb));
        }
        command.args(arguments.iter().skip(DIRECT_LEAN_PREFIX.len()));
        // The heap ceiling bounds ONE worker, and a build runs as many workers
        // as the machine has cores — Lake schedules module builds on Lean's
        // task pool, so the pool size is the worker count. The ceilings add up:
        // measured on a 32 GiB host, the certificate module for the checkers
        // board elaborates in 11.4 GiB when run alone under a 16 GiB ceiling,
        // while the same build through a parallel Lake was killed by the
        // operating system (exit 137) — the ceiling held per worker while the
        // machine ran out overall. Serialising keeps total demand at one
        // ceiling; the pristine wall is cached, so the cost lands once.
        if arguments.starts_with(&BUILD_PREFIX) {
            command.env("LEAN_NUM_THREADS", self.build_jobs.to_string());
        }
        command
    }
}

/// The argument shape of a direct Lean elaboration step (`lake env lean …`).
const DIRECT_LEAN_PREFIX: [&str; 2] = ["env", "lean"];
/// The argument shape of a Lake build step (`lake build …`).
const BUILD_PREFIX: [&str; 1] = ["build"];

fn build_jobs(environment: &impl Fn(&str) -> Option<OsString>) -> Result<u64, String> {
    let Some(value) = nonempty(environment(BUILD_JOBS_ENV)) else {
        let cores = std::thread::available_parallelism().map_or(1, |n| n.get() as u64);
        return Ok(default_build_jobs(cores, available_memory_mb()));
    };
    let text = value.to_string_lossy();
    text.trim()
        .parse::<u64>()
        .ok()
        .filter(|&jobs| jobs > 0)
        .ok_or_else(|| {
            format!(
                "{BUILD_JOBS_ENV} must be a positive whole number of workers, got `{}`",
                text.trim()
            )
        })
}

/// The worker count without an override: as many workers as the machine has
/// cores and as its available memory holds at [`WORKER_MEMORY_BUDGET_MB`]
/// each, and at least one; one when the available memory is unknown.
fn default_build_jobs(cores: u64, available_mb: Option<u64>) -> u64 {
    match available_mb {
        Some(mb) => (mb / WORKER_MEMORY_BUDGET_MB).min(cores).max(1),
        None => FALLBACK_BUILD_JOBS,
    }
}

/// The memory the operating system can give new processes now, in MiB:
/// `MemAvailable` on Linux; free, inactive and speculative pages on macOS.
/// `None` elsewhere, or when it cannot be read.
fn available_memory_mb() -> Option<u64> {
    #[cfg(target_os = "linux")]
    {
        let text = std::fs::read_to_string("/proc/meminfo").ok()?;
        parse_meminfo_available_mb(&text)
    }
    #[cfg(target_os = "macos")]
    {
        let output = Command::new("/usr/bin/vm_stat")
            .env_clear()
            .stdin(Stdio::null())
            .stderr(Stdio::null())
            .output()
            .ok()?;
        if !output.status.success() {
            return None;
        }
        parse_vm_stat_available_mb(&String::from_utf8_lossy(&output.stdout))
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos")))]
    {
        None
    }
}

#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
fn parse_meminfo_available_mb(text: &str) -> Option<u64> {
    let line = text
        .lines()
        .find(|line| line.starts_with("MemAvailable:"))?;
    let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?;
    Some(kib / 1024)
}

#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn parse_vm_stat_available_mb(text: &str) -> Option<u64> {
    let page: u64 = text
        .lines()
        .next()?
        .split("page size of ")
        .nth(1)?
        .split_whitespace()
        .next()?
        .parse()
        .ok()?;
    let pages = |label: &str| -> Option<u64> {
        let line = text.lines().find(|line| line.starts_with(label))?;
        line.split(':')
            .nth(1)?
            .trim()
            .trim_end_matches('.')
            .parse()
            .ok()
    };
    let free = pages("Pages free:")? + pages("Pages inactive:")? + pages("Pages speculative:")?;
    Some(free.checked_mul(page)? / (1024 * 1024))
}

fn memory_limit_mb(environment: &impl Fn(&str) -> Option<OsString>) -> Result<u64, String> {
    let Some(value) = nonempty(environment(MEMORY_LIMIT_ENV)) else {
        return Ok(DEFAULT_MEMORY_LIMIT_MB);
    };
    let text = value.to_string_lossy();
    let limit = text
        .trim()
        .parse::<u64>()
        .ok()
        .filter(|&limit| limit > 0)
        .ok_or_else(|| {
            format!(
                "{MEMORY_LIMIT_ENV} must be a positive whole number of MiB, got `{}`",
                text.trim()
            )
        })?;
    // Fail closed on absurd overrides, mirroring the phase-timeout knob.
    if limit > MAX_MEMORY_LIMIT_MB {
        return Err(format!(
            "{MEMORY_LIMIT_ENV} must be at most {MAX_MEMORY_LIMIT_MB} MiB (1 TiB), got `{}`",
            text.trim()
        ));
    }
    Ok(limit)
}

fn phase_timeout(environment: &impl Fn(&str) -> Option<OsString>) -> Result<Duration, String> {
    let Some(value) = nonempty(environment(PHASE_TIMEOUT_ENV)) else {
        return Ok(DEFAULT_PHASE_TIMEOUT);
    };
    let text = value.to_string_lossy();
    let seconds = text
        .trim()
        .parse::<u64>()
        .ok()
        .filter(|&seconds| seconds > 0)
        .ok_or_else(|| {
            format!(
                "{PHASE_TIMEOUT_ENV} must be a positive whole number of seconds, got `{}`",
                text.trim()
            )
        })?;
    // Fail closed on absurd overrides instead of carrying an unbounded value
    // into deadline arithmetic: past one day per step nothing legitimate is
    // being configured.
    if seconds > MAX_PHASE_TIMEOUT_SECS {
        return Err(format!(
            "{PHASE_TIMEOUT_ENV} must be at most {MAX_PHASE_TIMEOUT_SECS} seconds (one day), got `{}`",
            text.trim()
        ));
    }
    Ok(Duration::from_secs(seconds))
}

/// Run one verifier step to completion under a wall-clock limit. On expiry the
/// step's entire process tree is killed and a fail-closed error naming the
/// step is returned: a timed-out step can never contribute to a green verdict.
fn run_with_timeout(
    mut command: Command,
    limit: Duration,
    phase: &str,
) -> Result<Output, LeanStepError> {
    command
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        // A fresh process group lets the checker stop lake together with
        // every lean worker it spawned using one group-wide signal.
        command.process_group(0);
    }
    let mut child = command.spawn().map_err(|error| {
        LeanStepError::Failed(format!(
            "could not start the trusted Lean toolchain for the {phase} step: {error}"
        ))
    })?;
    let stdout = drain(child.stdout.take());
    let stderr = drain(child.stderr.take());

    // The limit covers both process exit and output drain: a runaway
    // descendant holding the output pipes open must not stall the verifier.
    // Compare elapsed time against the limit instead of precomputing a
    // deadline so no configured limit can overflow `Instant` arithmetic
    // after the child has already been spawned.
    let started = Instant::now();
    let mut status = None;
    let finished = loop {
        if status.is_none() {
            status = match child.try_wait() {
                Ok(exited) => exited,
                Err(error) => {
                    kill_process_tree(&mut child);
                    // Leave the drain threads detached: a survivor holding
                    // the pipes open must not delay this error.
                    drop(stdout);
                    drop(stderr);
                    return Err(LeanStepError::Failed(format!(
                        "could not observe the {phase} step: {error}"
                    )));
                }
            };
        }
        match status {
            Some(status) if stdout.is_finished() && stderr.is_finished() => break Some(status),
            _ if started.elapsed() >= limit => break None,
            _ => std::thread::sleep(WAIT_POLL),
        }
    };

    let Some(status) = finished else {
        kill_process_tree(&mut child);
        // Do not join the drain threads: if any process escaped the group
        // kill and still holds a pipe open, joining would hang the verifier.
        // The threads own nothing the caller needs, so leave them detached
        // and report the timeout promptly.
        drop(stdout);
        drop(stderr);
        return Err(LeanStepError::Timeout {
            phase: phase.to_string(),
            limit,
        });
    };
    Ok(Output {
        status,
        stdout: join_drain(stdout),
        stderr: join_drain(stderr),
    })
}

/// Stop the child and every process it spawned. On Unix the child leads its
/// own process group, so one group-wide SIGKILL reaches lake and its lean
/// workers; on Windows `taskkill /T` walks the process tree.
///
/// Cleanup is itself bounded: the kill helper and the reap of the child each
/// get [`CLEANUP_LIMIT`], and a cleanup that cannot finish in time is
/// abandoned so the caller's fail-closed error is reported promptly instead
/// of trading a hung step for a hung cleanup.
fn kill_process_tree(child: &mut Child) {
    #[cfg(unix)]
    let killer = Command::new("kill")
        .args(["-KILL", "--", &format!("-{}", child.id())])
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn();
    #[cfg(windows)]
    let killer = Command::new("taskkill")
        .args(["/T", "/F", "/PID", &child.id().to_string()])
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn();
    if let Ok(mut killer) = killer
        && reap_with_deadline(&mut killer, CLEANUP_LIMIT).is_none()
    {
        let _ = killer.kill();
        let _ = killer.try_wait();
    }
    let _ = child.kill();
    // Reap the child if it exits promptly; a child that ignores SIGKILL
    // (unkillable kernel state) is abandoned rather than waited on forever.
    let _ = reap_with_deadline(child, CLEANUP_LIMIT);
}

/// Poll `try_wait` until the process exits or the deadline passes. Returns
/// `None` when the process is still running (or cannot be observed) so the
/// caller can abandon it instead of blocking.
fn reap_with_deadline(child: &mut Child, limit: Duration) -> Option<std::process::ExitStatus> {
    let started = Instant::now();
    loop {
        match child.try_wait() {
            Ok(Some(status)) => return Some(status),
            Ok(None) if started.elapsed() < limit => std::thread::sleep(WAIT_POLL),
            Ok(None) | Err(_) => return None,
        }
    }
}

fn drain(pipe: Option<impl std::io::Read + Send + 'static>) -> std::thread::JoinHandle<Vec<u8>> {
    std::thread::spawn(move || {
        let mut buffer = Vec::new();
        if let Some(mut pipe) = pipe {
            let _ = pipe.read_to_end(&mut buffer);
        }
        buffer
    })
}

fn join_drain(reader: std::thread::JoinHandle<Vec<u8>>) -> Vec<u8> {
    reader.join().unwrap_or_default()
}

fn unique_nanos() -> u128 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|duration| duration.as_nanos())
        .unwrap_or(0)
}

#[cfg(windows)]
fn copy_if_present(
    destination: &mut Vec<(&'static str, OsString)>,
    name: &'static str,
    environment: &impl Fn(&str) -> Option<OsString>,
) {
    if let Some(value) = nonempty(environment(name)) {
        destination.push((name, value));
    }
}

fn nonempty(value: Option<OsString>) -> Option<OsString> {
    value.filter(|value| !value.is_empty())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::wall;
    use std::collections::BTreeMap;
    use std::path::PathBuf;
    use std::process::Command;

    fn command_environment(command: &Command) -> BTreeMap<String, OsString> {
        command
            .get_envs()
            .filter_map(|(name, value)| {
                value.map(|value| (name.to_string_lossy().into_owned(), value.to_os_string()))
            })
            .collect()
    }

    #[test]
    fn command_whitelists_only_toolchain_bootstrap_and_checker_temp() {
        let runner = LeanRunner {
            elan: PathBuf::from("/trusted/elan/bin/elan"),
            elan_home: PathBuf::from("/trusted/elan"),
            toolchain: wall::LEAN_TOOLCHAIN.trim().to_string(),
            system_environment: Vec::new(),
            phase_timeout: DEFAULT_PHASE_TIMEOUT,
            memory_limit_mb: DEFAULT_MEMORY_LIMIT_MB,
            build_jobs: FALLBACK_BUILD_JOBS,
        };
        let command = runner.lake_command(
            Path::new("/checker/build"),
            Path::new("/checker/temp"),
            &["env", "lean", "Probe.lean"],
        );

        assert_eq!(command.get_program(), "/trusted/elan/bin/elan");
        assert_eq!(
            command
                .get_args()
                .map(|argument| argument.to_string_lossy().into_owned())
                .collect::<Vec<_>>(),
            [
                "run",
                "--install",
                wall::LEAN_TOOLCHAIN.trim(),
                "lake",
                "env",
                "lean",
                "--memory=16384",
                "Probe.lean"
            ]
        );

        // The heap ceiling reaches only direct `lean` elaboration steps:
        // `lake build` carries it through the generated lakefile instead, and
        // `leanchecker` takes no such flag.
        for untouched in [
            &["build"] as &[&str],
            &["env", "leanchecker", "--fresh", "ArtifactCertificate"],
        ] {
            let command = runner.lake_command(
                Path::new("/checker/build"),
                Path::new("/checker/temp"),
                untouched,
            );
            let arguments = command
                .get_args()
                .map(|argument| argument.to_string_lossy().into_owned())
                .collect::<Vec<_>>();
            assert!(
                !arguments
                    .iter()
                    .any(|argument| argument.contains("--memory")),
                "{untouched:?} must not receive a lean flag: {arguments:?}"
            );
            assert_eq!(&arguments[4..], untouched, "arguments reordered");
        }

        // Build steps carry the worker count instead: Lake schedules module
        // builds on Lean's task pool, so the pool size caps how many heap
        // ceilings can be live at once. Lake 5.0 has no jobs flag, which makes
        // this environment variable the only channel.
        let build = runner.lake_command(
            Path::new("/checker/build"),
            Path::new("/checker/temp"),
            &["build"],
        );
        assert_eq!(
            command_environment(&build).get("LEAN_NUM_THREADS"),
            Some(&OsString::from("1")),
            "build step did not carry the worker count"
        );
        assert!(
            !command_environment(&command).contains_key("LEAN_NUM_THREADS"),
            "worker count leaked onto a direct elaboration step"
        );

        let environment = command_environment(&command);
        for forbidden in [
            "LEAN_PATH",
            "LEAN_SRC_PATH",
            "LEAN_SYSROOT",
            "ELAN_TOOLCHAIN",
            "PATH",
            "HOME",
            "LAKE_HOME",
            "LAKE_OVERRIDE_LEAN",
        ] {
            assert!(
                !environment.contains_key(forbidden),
                "forwarded {forbidden}"
            );
        }
        assert_eq!(environment.get("ELAN_HOME").unwrap(), "/trusted/elan");
        assert_eq!(environment.get("LAKE_ARTIFACT_CACHE").unwrap(), "0");
        assert_eq!(environment.get("LAKE_RESTORE_ARTIFACTS").unwrap(), "0");
        assert_eq!(environment.get("LAKE_NO_CACHE").unwrap(), "1");
        assert_eq!(environment.get("LAKE_CACHE_DIR").unwrap(), "");
        for temp in ["TMPDIR", "TMP", "TEMP"] {
            assert_eq!(environment.get(temp).unwrap(), "/checker/temp");
        }
    }

    struct TestTree(PathBuf);

    impl TestTree {
        fn new() -> Self {
            // The clock alone can collide across parallel test threads; the
            // counter keeps every tree in this process unique.
            static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
            let path = std::env::temp_dir().join(format!(
                "aver-cert-lean-env-{}-{}-{}",
                std::process::id(),
                NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|duration| duration.as_nanos())
                    .unwrap_or(0)
            ));
            std::fs::create_dir(&path).unwrap();
            Self(path)
        }
    }

    impl Drop for TestTree {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    fn report(output: &std::process::Output) -> String {
        format!(
            "{}{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        )
    }

    /// Lean 4.32's `lake env` keeps inherited LEAN_PATH entries live after its
    /// own package paths. Prove the baseline can import a valid ambient olean,
    /// then prove the production environment boundary makes it unreachable.
    #[test]
    fn hostile_lean_path_olean_is_not_visible() {
        let toolchain = wall::LEAN_TOOLCHAIN.trim();
        let available = Command::new("elan")
            .args(["run", "--install", toolchain, "lake", "--version"])
            .output();
        if !matches!(available, Ok(output) if output.status.success()) {
            assert!(
                std::env::var_os("AVER_CERT_REQUIRE_PINNED_LEAN").is_none(),
                "pinned Elan toolchain is required for this security gate"
            );
            eprintln!("skipping hostile LEAN_PATH test: pinned Elan toolchain unavailable");
            return;
        }

        let tree = TestTree::new();
        let ambient = tree.0.join("ambient");
        let consumer = tree.0.join("consumer");
        std::fs::create_dir(&ambient).unwrap();
        std::fs::create_dir(&consumer).unwrap();
        for directory in [&ambient, &consumer] {
            std::fs::write(directory.join("lean-toolchain"), wall::LEAN_TOOLCHAIN).unwrap();
            std::fs::write(
                directory.join("lakefile.lean"),
                "import Lake\nopen Lake DSL\npackage «envprobe» where\n",
            )
            .unwrap();
        }
        std::fs::write(
            ambient.join("CertPrelude.lean"),
            "def ambientMarker : Nat := 666\n",
        )
        .unwrap();

        let runner = LeanRunner::new(wall::LEAN_TOOLCHAIN).unwrap();
        let built = runner
            .run_lake(
                &ambient,
                "shadow olean build",
                &["env", "lean", "-o", "CertPrelude.olean", "CertPrelude.lean"],
            )
            .unwrap();
        assert!(
            built.status.success(),
            "shadow olean build failed:\n{}",
            report(&built)
        );
        std::fs::remove_file(ambient.join("CertPrelude.lean")).unwrap();
        assert!(ambient.join("CertPrelude.olean").is_file());

        std::fs::write(
            consumer.join("Probe.lean"),
            "import CertPrelude\n\ndef observed : Nat := ambientMarker\n",
        )
        .unwrap();

        let baseline = Command::new("elan")
            .current_dir(&consumer)
            .env("LEAN_PATH", &ambient)
            .args(["run", toolchain, "lake", "env", "lean", "Probe.lean"])
            .output()
            .unwrap();
        assert!(
            baseline.status.success(),
            "Lean 4.32 baseline did not retain ambient LEAN_PATH:\n{}",
            report(&baseline)
        );

        let hostile = |name: &str| match name {
            "LEAN_PATH" | "LEAN_SRC_PATH" => Some(ambient.as_os_str().to_os_string()),
            "ELAN_TOOLCHAIN" => Some(OsString::from("leanprover/lean4:v4.31.0")),
            _ => std::env::var_os(name),
        };
        let hardened = LeanRunner::with_environment(wall::LEAN_TOOLCHAIN, hostile)
            .unwrap()
            .run_lake(&consumer, "hostile probe", &["env", "lean", "Probe.lean"])
            .unwrap();
        let hardened_report = report(&hardened);
        assert!(
            !hardened.status.success(),
            "hostile ambient olean crossed the cleared environment:\n{hardened_report}"
        );
        assert!(
            hardened_report.contains("CertPrelude")
                && (hardened_report.contains("unknown module")
                    || hardened_report.contains("not found")),
            "hardened failure was not the missing hostile module:\n{hardened_report}"
        );
    }

    fn runner_with_setting(knob: &'static str, value: Option<&str>) -> Result<LeanRunner, String> {
        let tree = TestTree::new();
        let elan_home = tree.0.join("elan");
        std::fs::create_dir_all(elan_home.join("bin")).unwrap();
        std::fs::write(
            elan_home
                .join("bin")
                .join(format!("elan{}", std::env::consts::EXE_SUFFIX)),
            b"placeholder",
        )
        .unwrap();

        let elan_home = elan_home.into_os_string();
        let setting = value.map(OsString::from);
        LeanRunner::with_environment(wall::LEAN_TOOLCHAIN, move |name| {
            if name == "ELAN_HOME" {
                Some(elan_home.clone())
            } else if name == knob {
                setting.clone()
            } else {
                None
            }
        })
    }

    fn runner_with_timeout_setting(value: Option<&str>) -> Result<LeanRunner, String> {
        runner_with_setting(PHASE_TIMEOUT_ENV, value)
    }

    #[test]
    fn phase_timeout_defaults_generously_and_validates_the_override() {
        let default = runner_with_timeout_setting(None).unwrap();
        assert_eq!(default.phase_timeout, DEFAULT_PHASE_TIMEOUT);
        assert_eq!(default.phase_timeout, Duration::from_secs(900));

        let overridden = runner_with_timeout_setting(Some("120")).unwrap();
        assert_eq!(overridden.phase_timeout, Duration::from_secs(120));

        let at_cap = runner_with_timeout_setting(Some(&MAX_PHASE_TIMEOUT_SECS.to_string()))
            .expect("the cap itself is a valid override");
        assert_eq!(
            at_cap.phase_timeout,
            Duration::from_secs(MAX_PHASE_TIMEOUT_SECS)
        );

        for invalid in ["0", "-5", "soon", "1.5"] {
            let Err(error) = runner_with_timeout_setting(Some(invalid)) else {
                panic!("malformed timeout override `{invalid}` must fail closed");
            };
            assert!(error.contains(PHASE_TIMEOUT_ENV), "{error}");
        }

        let over_cap = (MAX_PHASE_TIMEOUT_SECS + 1).to_string();
        for oversized in [over_cap.as_str(), &u64::MAX.to_string()] {
            let Err(error) = runner_with_timeout_setting(Some(oversized)) else {
                panic!("oversized timeout override `{oversized}` must fail closed");
            };
            assert!(error.contains(PHASE_TIMEOUT_ENV), "{error}");
            assert!(error.contains("at most"), "{error}");
        }
    }

    #[test]
    fn build_jobs_default_follows_cores_and_available_memory() {
        // Four workers' budgets in 16 GiB, bounded by the cores.
        assert_eq!(default_build_jobs(12, Some(16 * 1024)), 4);
        assert_eq!(default_build_jobs(2, Some(64 * 1024)), 2);
        // Less than one budget still runs one worker.
        assert_eq!(default_build_jobs(8, Some(1000)), 1);
        assert_eq!(default_build_jobs(8, Some(0)), 1);
        // Unknown memory falls back to one worker.
        assert_eq!(default_build_jobs(8, None), 1);
        // An explicit override wins over the derived default and is validated.
        let overridden = runner_with_setting(BUILD_JOBS_ENV, Some("3")).unwrap();
        assert_eq!(overridden.build_jobs, 3);
        for invalid in ["0", "-1", "many"] {
            let Err(error) = runner_with_setting(BUILD_JOBS_ENV, Some(invalid)) else {
                panic!("malformed worker count `{invalid}` must fail closed");
            };
            assert!(error.contains(BUILD_JOBS_ENV), "{error}");
        }
        let derived = runner_with_setting(BUILD_JOBS_ENV, None).unwrap();
        assert!(derived.build_jobs >= 1);
    }

    #[test]
    fn available_memory_is_read_from_the_system_reports() {
        let meminfo =
            "MemTotal:       32768000 kB\nMemFree:  1000 kB\nMemAvailable:   16777216 kB\n";
        assert_eq!(parse_meminfo_available_mb(meminfo), Some(16384));
        assert_eq!(parse_meminfo_available_mb("MemTotal: 1 kB\n"), None);
        let vm_stat = "Mach Virtual Memory Statistics: (page size of 16384 bytes)\n\
                       Pages free:                               65536.\n\
                       Pages active:                            100000.\n\
                       Pages inactive:                           65536.\n\
                       Pages speculative:                            0.\n";
        assert_eq!(parse_vm_stat_available_mb(vm_stat), Some(2048));
        assert_eq!(parse_vm_stat_available_mb("garbage"), None);
    }

    #[test]
    fn memory_limit_defaults_and_validates_the_override() {
        let default = runner_with_setting(MEMORY_LIMIT_ENV, None).unwrap();
        assert_eq!(default.memory_limit_mb(), DEFAULT_MEMORY_LIMIT_MB);
        assert_eq!(default.memory_limit_mb(), 16384);

        let overridden = runner_with_setting(MEMORY_LIMIT_ENV, Some("256")).unwrap();
        assert_eq!(overridden.memory_limit_mb(), 256);
        // The override value is exactly what the lean worker will run under.
        let command = overridden.lake_command(
            Path::new("/checker/build"),
            Path::new("/checker/temp"),
            &["env", "lean", "Probe.lean"],
        );
        assert!(
            command
                .get_args()
                .any(|argument| argument.to_string_lossy() == "--memory=256"),
            "override did not reach the lean command line"
        );

        for invalid in ["0", "-5", "lots", "1.5"] {
            let Err(error) = runner_with_setting(MEMORY_LIMIT_ENV, Some(invalid)) else {
                panic!("malformed memory override `{invalid}` must fail closed");
            };
            assert!(error.contains(MEMORY_LIMIT_ENV), "{error}");
        }
        let over_cap = (MAX_MEMORY_LIMIT_MB + 1).to_string();
        let Err(error) = runner_with_setting(MEMORY_LIMIT_ENV, Some(&over_cap)) else {
            panic!("oversized memory override must fail closed");
        };
        assert!(error.contains("at most"), "{error}");
    }

    /// The hang guard must kill the whole process group: lake spawns lean
    /// workers, and killing only the direct child would leave them running.
    #[cfg(unix)]
    #[test]
    fn expired_phase_kills_the_whole_process_group() {
        let tree = TestTree::new();
        let pid_file = tree.0.join("grandchild.pid");
        let mut command = Command::new("sh");
        command.arg("-c").arg(format!(
            "tail -f /dev/null & echo $! > '{}'; wait",
            pid_file.display()
        ));

        let error = run_with_timeout(command, Duration::from_secs(1), "test probe")
            .expect_err("a hung step must fail closed")
            .to_string();
        assert!(error.contains("test probe"), "{error}");
        assert!(error.contains("time limit"), "{error}");
        assert!(error.contains(PHASE_TIMEOUT_ENV), "{error}");

        let grandchild =
            std::fs::read_to_string(&pid_file).expect("grandchild pid recorded before the timeout");
        let grandchild = grandchild.trim().to_string();
        assert!(!grandchild.is_empty(), "grandchild pid file was empty");

        let mut alive = true;
        for _ in 0..100 {
            let probe = Command::new("ps")
                .args(["-p", &grandchild, "-o", "pid="])
                .output()
                .expect("ps runs");
            if !probe.status.success() || String::from_utf8_lossy(&probe.stdout).trim().is_empty() {
                alive = false;
                break;
            }
            std::thread::sleep(Duration::from_millis(50));
        }
        assert!(
            !alive,
            "grandchild process {grandchild} survived the group kill"
        );
    }
}