1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
// `doc_cfg` (nightly-only) auto-derives the "Available on crate feature" badges
// from `#[cfg]` gates; gated behind `docsrs` so stable/CI `cargo doc` ignores it.
//! `processkit` — async child-process management for Rust + [tokio]: whole-tree
//! kill-on-drop (no orphaned subprocesses), run-and-capture, streaming,
//! shell-free pipelines, timeouts & cancellation, and supervision.
//!
//! [tokio]: https://tokio.rs/
//!
//! Two layers:
//!
//! - **[`ProcessGroup`]** — a kill-on-drop container for a process *tree*. Every
//! child spawned into the group, and everything those children spawn, dies
//! with the group, so an exiting or panicking owner doesn't leak subprocesses.
//! Containment is a Windows [Job Object], a Linux [cgroup v2] (with a POSIX
//! process-group fallback), a FreeBSD `procctl(2)` process reaper, or a POSIX
//! process group on macOS/the other BSDs — observable via [`Mechanism`]. A
//! spawn-free [`host_containment`] reports
//! which [`Mechanism`] (and the reach of soft stop / abrupt-owner-death
//! cleanup) a group *would* get on this host, before any group exists. Two
//! caveats the [`ProcessGroup`] /
//! [`Mechanism`] docs spell out: the guarantee rides on `Drop` running (a
//! `panic = "abort"` process, or a `SIGKILL`/power-loss of the *owner*, skips
//! it — Windows still reaps through Job Object handle close, while Linux's
//! opt-in parent-death signal reaches only the direct child and macOS/BSD have
//! no equivalent), and on the process-group mechanism a child
//! that calls `setsid` escapes containment. The one *deliberate* way out is
//! [`Command::spawn_detached`] — an explicit, loudly-named opt-in that hands
//! back a [`DetachedChild`] for which the crate exposes no public lifetime,
//! kill, wait, timeout, capture, or control operations (Unix still reaps its
//! exit status through a private background owner), and never contains (it
//! inverts this guarantee on purpose; see its docs). The whole
//! tree can be
//! signalled (`ProcessGroup::signal`, see `Signal`), paused/resumed
//! (`ProcessGroup::suspend` / `ProcessGroup::resume`), and inspected
//! (`ProcessGroup::members`); [`wait_any`] races several running processes
//! and reports the first to exit.
//! - **runner** — async run-and-capture built on the group. Describe a run with
//! [`Command`], then drive it to completion ([`Command::output_string`],
//! [`Command::run`], …) or [`start`](Command::start) it for streaming and
//! interactive I/O. The [`ProcessRunner`] trait runs commands to completion
//! and is the mock seam (see [`ScriptedRunner`](testing::ScriptedRunner)). A
//! [`Supervisor`] keeps a command *alive* — restarting it per policy with
//! backoff — where [`Command::retry`] merely replays one run to success.
//! Readiness probes ([`RunningProcess::wait_for_line`] /
//! [`RunningProcess::wait_for_stderr_line`] /
//! [`wait_for_port`](RunningProcess::wait_for_port) /
//! [`wait_for`](RunningProcess::wait_for)) wait until a started child is
//! actually *ready* instead of sleeping. A [`Pipeline`]
//! ([`Command::pipe`]) chains commands stdout→stdin without a shell — each
//! stage spawns into its own kill-on-drop `ProcessGroup` sub-group, with
//! chain-wide teardown fanning the kill across every sub-group, pipefail
//! outcome. [`Command::cancel_on`] ties a run to a
//! [`CancellationToken`]: cancelling it kills the tree and every consuming
//! path resolves to [`ErrorReason::Cancelled`]. Spawn-time sandboxing knobs:
//! [`Command::inherit_env`] (env allow-list), [`Command::uid`] /
//! [`Command::gid`] (Unix privilege drop), [`Command::setsid`],
//! [`Command::create_no_window`], [`Command::priority`] (CPU-scheduling
//! priority, both platforms), [`Command::cpu_affinity`] (Linux/Windows CPU
//! placement), [`Command::io_priority`] (Linux I/O scheduling),
//! [`Command::umask`] (Unix file-creation mask).
//!
//! Async throughout (tokio). Errors are the structured [`Error`]; a non-zero
//! exit is reported in [`ProcessResult`], not raised, until you call
//! [`ProcessResult::ensure_success`].
//!
//! **Stability.** Since **1.0**, `processkit` follows [Semantic Versioning]: the
//! public API is stable, and any breaking change lands only in a new *major*
//! version, so `2.x` upgrades are backward-compatible (the last breaking release
//! was **2.1.0**). (The lone exception is the `mock` feature's `mockall`-generated
//! `expect_*` surface — see below.)
//!
//! [Semantic Versioning]: https://semver.org/spec/v2.0.0.html
//!
//! **Stable machine identifiers.** The reporting and configuration enums —
//! [`Mechanism`], [`Outcome`], [`ParentDeathCleanup`], [`StopReason`],
//! [`StdioMode`], [`LineTerminator`], [`OverflowMode`], [`Priority`],
//! [`RestartPolicy`], plus the feature-gated `LimitKind` / `LimitReason` /
//! `LimitVerdict`
//! (`limits`) and `Signal` / `SoftStopScope` / `SoftSignal`
//! (`process-control`), given as bare
//! names here since this crate-root doc also builds with those features off —
//! each
//! expose a `name()` that returns a short, lowercase `snake_case` identifier
//! for machine-readable output (a CLI's JSONL schema, a cross-language binding,
//! a structured log field), so a consumer publishing a contract over these
//! types has one canonical spelling per variant instead of a hand-maintained
//! table. These identifiers are a *diagnostic* surface — a stable **vocabulary**
//! rather than a frozen wire schema (see the `report-serde` feature below,
//! which puts exactly these identifiers on the wire) — and they carry the same
//! stability promise as the rest of the public API: a
//! new variant gets a new identifier, and an existing identifier is never
//! renamed without a major release. Every enum whose value can arrive from
//! outside (config, CLI, another language) also has a `from_name(&str)` inverse
//! that returns `None` — an honest miss, never a silent default — on an
//! unrecognized name. See the [Errors guide]'s "Stable machine identifiers"
//! section for the whole set.
//!
//! [Errors guide]: https://github.com/ZelAnton/ProcessKit-rs/blob/main/docs/errors.md
//!
//! Beyond this page, the repository ships a narrative [guide set] — a
//! task-oriented [cookbook] ("I want to …" → snippet), a deep guide per
//! capability, and every per-platform caveat collected in one place.
//!
//! [guide set]: https://github.com/ZelAnton/ProcessKit-rs/tree/main/docs#readme
//! [cookbook]: https://github.com/ZelAnton/ProcessKit-rs/blob/main/docs/cookbook.md
//!
//! **Run vocabulary** — one verb, one meaning, at every layer ([`Command`],
//! [`ProcessRunner`]/[`ProcessRunnerExt`], [`CliClient`]):
//!
//! - **`run`** — require an **accepted** exit (`0` by default, widened by
//! [`Command::ok_codes`]) and return stdout as a `String`, trailing whitespace
//! trimmed (`trim_end`: the final newline is noise, but leading whitespace can
//! be significant). **`run_unit`** — the same, discarding the output.
//! - **`output_string`** / **`output_bytes`** — return the full
//! [`ProcessResult`] (stdout as text / raw bytes); a non-zero exit is *not* an
//! error here. (`output_string`, not a bare `output`, since
//! `std::process::Command::output` yields *bytes* — the explicit name avoids
//! that footgun and is spelled the same on every layer.)
//! - **`exit_code`** — the exit code, with a missing code surfaced as an
//! error. (On a [`ProcessResult`], [`code`](ProcessResult::code) is the
//! plain `Option<i32>` accessor — `None` for a timeout/signal kill, never a
//! `-1` sentinel.)
//! - **`probe`** — run a predicate and read its exit code as a `bool`: `0` →
//! `true`, `1` → `false`, anything else is an error (`git diff --quiet`, …).
//! - **`parse`** / **`try_parse`** — run to a clean success and feed the
//! captured stdout to a closure: `parse` for an infallible closure,
//! `try_parse` for one returning [`Result`] (the JSON-deserialization
//! shape). **`Send`-contract exception:** [`Command::parse`] /
//! [`CliClient::parse`] require `F: Send` (and `T: Send`), so the returned
//! future is `Send` and movable into `tokio::spawn`; [`Pipeline::parse`]
//! deliberately does **not** require `Send` — its closure runs inline on
//! the awaiting task rather than across a `tokio::spawn` boundary, so it
//! accepts strictly more closures, but the resulting future is `Send` only
//! when `F`/`T` happen to be. If you need to move a `Pipeline::parse` /
//! `Pipeline::try_parse` call into `tokio::spawn`, make sure your closure
//! and its output are `Send` yourself; the compiler won't require it for
//! you the way it does for `Command`/`CliClient`.
//! - **`output_json`** *(feature `json`)* — the success-checking typed JSON
//! form of `try_parse`; `RunningProcess::stdout_json_lines` provides strict
//! line-wise NDJSON without buffering the complete stdout.
//!
//! # Features
//!
//! Every flag is *additive* and gates visibility only — the kill-on-drop tree
//! guarantee is unconditional in every configuration.
//!
//! - **`stats`** — resource measurement: `ProcessGroupStats`,
//! `ProcessGroup::stats` (plus the `sample_stats` time-series sampler and its
//! owning `'static` twin `OwnedStatsSampler`), the
//! per-process `RunningProcess::cpu_time`/`peak_memory_bytes` diagnostics,
//! and the `RunningProcess::profile` run summary. **Opt-in** for its
//! specialized purpose (on Windows it calls the system `ProcessStatus`/PSAPI
//! API — a link to an OS library, *not* an added crate dependency); enable with
//! `features = ["stats"]`, or `limits`, which implies it. (The features that do
//! pull an extra crate are `mock` → `mockall`, `tracing` → `tracing`, and
//! `record` / `json` → `serde`/`serde_json`.)
//! - **`process-control`** *(default)* — tree control beyond contain+kill:
//! `Signal` and `ProcessGroup::{signal, suspend, resume, members,
//! members_info, adopt, adopt_external}`, the enriched `MemberInfo` member
//! snapshot, and the free-standing `process_info` / `process_is_alive` queries
//! for a pid held *outside* any group (reuse-safe liveness by the
//! `(pid, start time)` pair).
//! - **`limits`** — whole-tree resource caps: `ResourceLimits`, the
//! `max_memory`/`max_processes`/`cpu_quota` builders on
//! [`ProcessGroupOptions`], `ErrorReason::ResourceLimit` (why a requested cap
//! could not be *applied*), and the post-run `ProcessGroup::limit_evidence`
//! report — `LimitEvidence` / `LimitVerdict` — saying whether a cap the group
//! carried then actually *fired*. Implies `stats`.
//! - **`mock`** — the `mockall`-generated `testing::MockRunner` for
//! consumers' tests. Its
//! `expect_*` surface is generated by `mockall` and is **exempt from this
//! crate's semver guarantees** — it tracks the `mockall` version (an
//! implementation detail) rather than a frozen API. The first-class doubles
//! ([`ScriptedRunner`](testing::ScriptedRunner) /
//! [`RecordingRunner`](testing::RecordingRunner)) are the stable, recommended
//! seam; reach for `mock` only if you specifically want expectation-style
//! mocking.
//! - **`tracing`** — `tracing` events on the `processkit` target: spawn and
//! exit (program/pid/mechanism), timeout and cancellation firing, group
//! terminate/shutdown, retry attempts, supervisor restarts and storm
//! pauses, and teardown anomalies (stdin-writer failures, pump overruns).
//! Never logs argv or environment values.
//! - **`metrics`** — [`metrics`](https://docs.rs/metrics) counters and histograms
//! over data the crate already computes: run/spawn counters, run-duration
//! histograms, an exit-code/timeout/cancel/signal tally, and retry / supervisor
//! restart / storm-pause events. A thin façade — the crate emits into whatever
//! global recorder (a Prometheus/OTel exporter) the consumer installs. Labels
//! carry only program name / mechanism / outcome / exit code — **never** argv or
//! environment values, and no unbounded-cardinality key like a pid. See the
//! `docs/observability.md` guide.
//! - **`record`** — record/replay cassettes over the [`ProcessRunner`] seam:
//! `RecordReplayRunner` records real `Invocation → ProcessResult` pairs to a
//! JSON fixture once, then replays them hermetically — no subprocess in CI.
//! Pulls in `serde` + `serde_json`.
//! - **`json`** — typed JSON capture through `Command::output_json`,
//! `ProcessRunnerExt::output_json`, and `CliClient::output_json`, plus
//! line-wise NDJSON through `RunningProcess::stdout_json_lines`. Parse
//! failures carry bounded raw fragments and exact decoded-output locations.
//! Pulls in `serde` + `serde_json`.
//! - **`report-serde`** — `serde::Serialize` for the crate's *report* types, so
//! a finished run, a graceful teardown, a stats tick or a supervision event
//! can be emitted as one JSONL line (or any other self-describing serde
//! format) without hand-copying fields and hand-calling `name()` per enum:
//! `ProcessResult`, `RunProfile`, `ProcessGroupStats`, `ShutdownReport`,
//! `MemberInfo`, `LimitEvidence`, `SupervisionEvent` / `SupervisionOutcome` /
//! `SupervisionStatus`, and the enums those carry. Reuses the optional
//! `serde` dependency `record` / `json` already pull, and pulls **no** codec
//! of its own — pick `serde_json`, `serde_yaml`, `ciborium`, … yourself. The
//! schema targets *self-describing* formats; rule 4 says why a
//! non-self-describing binary codec is out of scope. Four rules define the
//! shape:
//!
//! 1. **Every enum travels as its stable `name()` identifier**, never a
//! serde-derived variant tag: `{"kind": "exited", "code": 0,
//! "signal_number": null}`, not `{"Exited": 0}`. An enum carrying a
//! payload is an object tagged under `"kind"`; one without is the bare
//! identifier string (`"restarts_exhausted"`). The wire vocabulary is
//! therefore exactly the dictionary described under *Stable machine
//! identifiers* above — the same one `spec/identifiers.json` publishes —
//! never a second spelling. **`Signal` is the one named exception**, with
//! a third form: `Signal::Other(i32)` is a raw OS number that deliberately
//! has no curated identifier (`Signal::name()` answers `None` there rather
//! than minting a spelling no dictionary defines and no `from_name` parses
//! back), so a signal travels as its identifier string when curated
//! (`"term"`) and as that bare number when not (`37`). The union stops
//! there, because **a key names one domain**: `signal` is always a
//! `Signal` (a `ShutdownReport`'s soft tier), while the raw OS number an
//! `Outcome` carries is a different fact under its own key,
//! `signal_number` — always a number or `null`. Two keys, so a consumer
//! folding both into one JSONL table never reconciles a string with an
//! integer under one column.
//! 2. **`Serialize` only — deliberately no `Deserialize`.** These types are
//! *reported* by the crate and never supplied back to it: the same
//! asymmetry that leaves `Outcome` / `ErrorKind` / `SupervisionEvent`
//! without a `from_name` inverse. Enums a caller genuinely does supply
//! (`Signal`, `RestartPolicy`, `Priority`, …) keep their `from_name`, so
//! the missing direction leaves no gap.
//! 3. **Reports *about* processes — never what a process produced.** Nothing
//! here serializes captured stdout/stderr content, argv, or environment
//! values, the same secret hygiene the `tracing` and `metrics` seams keep
//! (a child's output routinely carries tokens, and a capture can be
//! multi-megabyte). `ProcessResult` reports the run — program name,
//! outcome, timings, truncation totals — and leaves the streams to the
//! caller, who already holds them. For the same reason `Error` /
//! `ErrorReason` (captured streams, the searched `PATH`), `ProcessEvent`
//! and `Finished` (captured output) deliberately have **no** impl: report
//! `ErrorKind` and attach whatever bounded, redacted detail your own
//! contract calls for.
//! 4. **The set of fields is not frozen; the spelling of each field is.**
//! Every one of these types is `#[non_exhaustive]`, keeps its fields
//! private, or both — they are grown, not frozen, and no downstream
//! struct literal pins today's set — and that stays true on the wire: a
//! future minor may add a key, so a consumer must ignore unknown ones (the
//! same discipline any JSONL reader already needs). That promise is also
//! why the schema targets **self-describing** formats: "ignore the keys
//! you don't know", and rule 1's identifier-or-number `Signal`, both need
//! an encoding that carries names and types, which `bincode` / `postcard`
//! deliberately do not — they will happily encode these values, but
//! nothing here pins their layout across a minor release. What *is* held
//! stable, like the rest of the public API, is everything already there —
//! an identifier or a key is never renamed or repurposed without a major
//! release. Time is always a number of seconds (`duration_secs`,
//! `elapsed_secs`, `delay_secs`, …), the unit the `metrics` histograms
//! record; a measurement a platform cannot report is `null`, never a
//! fabricated `0`.
//!
//! # Other languages
//!
//! Not on Rust? [`processkit-py`](https://pypi.org/project/processkit-py/) is a
//! Python wrapper (PyO3 bindings) over this crate's core, with an asyncio-facing
//! API. This crate remains the single source of truth for the containment/runner
//! logic underneath.
//!
//! [Job Object]: https://learn.microsoft.com/windows/win32/procthread/job-objects
//! [cgroup v2]: https://docs.kernel.org/admin-guide/cgroup-v2.html
// The one deliberate opt-in escape from kill-on-drop containment
// (`Command::spawn_detached` → `DetachedChild`).
// FNV-1a helper shared by the two cassette-key digests (`Stdin::content_digest`
// and `MatchPolicy::digest_of`), so their constants + mix loop have one home and
// can't drift apart. Both call sites live under `record`, so the helper does too.
// Compiles docs/*.md + README.md's fenced Rust blocks as doctests under
// `--all-features` (see the module's own doc comment). Under `cfg(test)`, the
// sanity test stays available to ordinary `cargo test` with any feature
// configuration, including default and `--no-default-features`.
// `process_info` / `process_is_alive` — the free-standing identity & reuse-safe
// liveness queries for an arbitrary pid held outside any group. Gated with the
// `MemberInfo` they return and the `process-control` readers they reuse.
// `MemberInfo` — the enriched member snapshot returned by
// `ProcessGroup::members_info` and the free-standing `process_info` query. Gated
// with the methods it exists for.
// Optional `metrics` counters/histograms over data the crate already computes
// (run/spawn counters, duration histograms, exit-code/timeout/cancel tally,
// retry/restart events). A thin, additive façade like the `tracing` seam, with the
// same secret-hygiene rule (never argv/env in labels). Gated on its feature.
// `ParentDeathCleanup` — the honest per-platform capability report for
// `Command::kill_on_parent_death`. Unconditional, like the knob it describes.
// Rules shared by the `report-serde` `Serialize` impls (the `"kind"` tag key,
// the seconds time unit) plus their schema tests; the impls themselves live
// beside the types they serialize.
// `ShutdownReport` / `SoftSignal` — the observed facts of a graceful
// `ProcessGroup::stop`. Gated with the method (and the `Signal` its `SoftSignal`
// carries).
// `SoftStopScope` — the runtime, per-group reach of a soft stop on the group
// axis, reported by `ProcessGroup::soft_stop_scope`. Gated with the `signal`
// verb it precedes.
// The `cfg(loom)`-swappable sync layer (std::sync in ordinary builds, loom models
// under `--cfg loom` test builds) that the PID-lifecycle lock-free protocols build
// on. See `sync.rs` for why it gates on `all(loom, test)`.
/// Clamp ceiling for `Instant + Duration` deadline math: a timeout, grace,
/// or `within` longer than this is treated as "effectively forever", so a
/// `Duration::MAX`-ish input can't overflow `Instant + Duration` and panic.
/// ~10 years — far beyond any real process deadline, with ample margin below
/// `Instant`'s representable range on every platform.
pub const MAX_DEADLINE: Duration =
from_secs;
pub use ;
pub use ;
pub use ;
pub use Command;
pub use DetachedChild;
pub use ;
pub use ;
pub use IoPriority;
pub use ;
pub use ;
pub use ;
pub use MemberInfo;
pub use ParentDeathCleanup;
pub use ;
pub use Priority;
// Fuzzing-only entry point for `fuzz/fuzz_targets/decode_pump_lines.rs` (see
// `src/pump.rs`). `cfg(fuzzing)` is set automatically by `cargo fuzz build`
// for the whole dependency graph, never in an ordinary build — so this
// never shows up in `cargo public-api`'s (`--all-features`, no `--cfg
// fuzzing`) surface, and thus never touches `public-api.txt`.
pub use ;
// Fuzzing-only cassette seams keep the ordinary API file-based while letting
// cargo-fuzz exercise parser and replay state directly from in-memory input.
pub use ;
pub use ;
pub use RetryPolicy;
pub use RlimitResource;
pub use ;
pub use JsonLines;
pub use ;
pub use ;
pub use Signal;
pub use SoftStopScope;
pub use ;
pub use ;
pub use ;
use OsStr;
/// Run `program` with `args` inside a private job and return trimmed stdout, or
/// an [`Error`] on a non-zero exit / spawn failure / timeout. A thin shim over
/// [`Command`]; use the builder for a working directory, env, stdin, timeout, or
/// the full verb vocabulary.
///
/// # Errors
///
/// The same surface as [`Command::run`]: a launch failure ([`ErrorReason::NotFound`] /
/// [`ErrorReason::Spawn`] / [`ErrorReason::Unsupported`] / [`ErrorReason::Io`]), a non-accepted
/// exit ([`ErrorReason::Exit`]), [`ErrorReason::Signalled`], [`ErrorReason::Timeout`], or
/// [`ErrorReason::OutputTooLarge`] on a fail-loud truncation.
pub async
/// Run `program` with `args` inside a private job and capture the result
/// without erroring on a non-zero exit — for commands whose exit code is meaningful.
///
/// # Errors
///
/// The same surface as [`Command::output_string`]: a non-zero exit, a timeout,
/// and a signal-kill are *captured* in the returned [`ProcessResult`], not
/// raised; beyond a launch failure, only [`ErrorReason::Cancelled`],
/// [`ErrorReason::OutputTooLarge`], [`ErrorReason::Stdin`], and [`ErrorReason::Io`] surface.
pub async
/// Resolve `program` to a concrete executable path **without launching it** — a
/// spawn-free preflight for a *doctor* / early-diagnosis check ("is `git`
/// installed?") that must have **no** side effects. A thin shim over
/// [`Command::new(program).resolve_program()`](Command::resolve_program); use the
/// builder form when you need `prefer_local` directories or a relocated `PATH`
/// honored (the client-level [`CliClient::resolve_program`] does the same for a
/// wrapped tool).
///
/// Resolution reuses the crate's *own* launch-path logic — a bare name is looked
/// up on `PATH` honoring PATHEXT on Windows and the execute bit on Unix; a
/// path-form `program` is probed directly — so a `which` hit is exactly what a
/// real run would spawn, at that same absolute path. On Windows this includes a
/// bare name reachable only through a non-`.exe` PATHEXT extension
/// (`yarn.cmd`/`npx.cmd` and similar shims): the launch substitutes the resolved
/// path, so such a hit spawns rather than failing. Synchronous and cheap (a few
/// `stat`s); no async runtime is required.
///
/// **The reverse holds on Unix, not fully on Windows.** A `which` miss is the
/// exact [`ErrorReason::NotFound`] a run would raise on Unix, where `execvp` searches
/// `PATH` only. On Windows the OS *also* locates a bare name through routes this
/// `PATH`-based preflight deliberately doesn't model — the application directory,
/// the current directory, and the system directories — so a Windows `which` miss
/// is not a guarantee a run couldn't still launch the program by one of those
/// routes.
///
/// # Errors
///
/// [`ErrorReason::NotFound`] when the program can't be located
/// — not installed, not on `PATH`, or a path that doesn't resolve to an
/// executable. Its `searched` field names the directories checked for a
/// bare-name lookup, and [`is_not_found`](crate::Error::is_not_found) classifies
/// it — the same error, with the same classification, a real run would give.
/// Report how process containment behaves on **this** host **without creating a
/// container or spawning anything** — a spawn-free preflight (a *doctor* /
/// host-check command that must have no side effects) that answers what a
/// [`ProcessGroup`] would otherwise only reveal *after* it exists: which
/// [`Mechanism`] a group created here and now would use, how far a soft stop
/// reaches, what the OS guarantees on abrupt owner death, and this crate's version.
///
/// See [`HostContainment`] for the full contract of each field. In particular the
/// [`mechanism`](HostContainment::mechanism) is determined by a read-only probe
/// (the shared `Mechanism::detect`) that is **best-effort** on two targets, both
/// because the query must create nothing: on **Linux** it inspects whether a cgroup
/// could be created rather than creating one, and on **FreeBSD** it reports the
/// process reaper without acquiring reaper status (acquiring it is a real,
/// permanent side effect). In either case a rare window can make it
/// differ from the mechanism a real [`ProcessGroup::new`](ProcessGroup::new) falls
/// back to. Like [`which`], no async runtime is required.
///
/// ```
/// let host = processkit::host_containment();
/// // e.g. log the containment story a run *would* get, before starting anything:
/// let _ = (host.mechanism(), host.parent_death_cleanup(), host.crate_version());
/// ```
/// Wait for whichever of several running processes exits **first**, returning
/// its index in `processes` and its [`Outcome`] (matching
/// [`RunningProcess::wait`]).
///
/// The processes are only *borrowed*: the race is cancel-safe, so the losers —
/// and the winner, whose exit status tokio caches — remain fully usable
/// afterwards ([`wait`](RunningProcess::wait), another `wait_any`, …).
///
/// Two deliberate non-features:
///
/// - **No per-process [`timeout`](Command::timeout)** — the configured deadline
/// is armed by the consuming wait paths, not here. Bound the whole race with
/// [`tokio::time::timeout`] when a deadline is wanted.
/// - **No output pumping** — a contender that fills its stdout/stderr pipe
/// blocks and never exits. Drain chatty children first (e.g. via
/// [`stdout_lines`](RunningProcess::stdout_lines)) or race low-output ones.
/// Note the interplay: a [`tokio::time::timeout`] bounding the race fires,
/// but leaves such pipe-blocked contenders alive and still wedged — kill or
/// drain them afterwards; the timeout alone is not the mitigation.
/// - **No stdin management** — symmetrically, a contender started with
/// [`keep_stdin_open`](Command::keep_stdin_open) and blocked reading stdin
/// never reaches EOF, so it never exits. The race does **not** close its
/// stdin for it (that would break the "losers remain usable" guarantee):
/// take its writer via [`take_stdin`](RunningProcess::take_stdin)
/// (or don't keep stdin open) before racing it.
///
/// An empty `processes` slice is an error ([`ErrorReason::Io`] with
/// [`InvalidInput`](std::io::ErrorKind::InvalidInput)) rather than a future
/// that never resolves.
///
/// The first finisher's result carries the same errors as a bulk verb:
/// `ErrorReason::Cancelled` for a cancelled run, or [`ErrorReason::Stdin`] when its stdin
/// source failed (non-broken-pipe) on an otherwise-successful exit. A non-zero
/// exit or signal is *not* an error here — it is returned as its [`Outcome`].
///
/// # Errors
///
/// [`ErrorReason::Io`] with [`InvalidInput`](std::io::ErrorKind::InvalidInput) when
/// `processes` is empty. Otherwise the first finisher's error surfaces:
/// [`ErrorReason::Cancelled`] (a cancelled run), [`ErrorReason::Stdin`] (a non-broken-pipe
/// stdin-source failure on an otherwise-successful exit), or [`ErrorReason::Io`] (a
/// failed reap). A non-zero exit or signal is returned as an [`Outcome`], not an
/// error.
pub async
/// Wait for **all** of several running processes to exit, returning their
/// [`Outcome`]s in the same order as `processes`. The processes are only
/// *borrowed* and stay usable afterwards (the exit status tokio caches remains
/// re-readable).
///
/// Same two non-features as [`wait_any`]: **no per-process
/// [`timeout`](Command::timeout)** (bound the whole batch with
/// [`tokio::time::timeout`]) and **no output pumping** (a contender that fills
/// its stdout/stderr pipe blocks forever — drain chatty children first). Unlike
/// `wait_any`, an empty slice resolves immediately to an empty `Vec`: collecting
/// zero outcomes is well-defined, where racing none is not.
///
/// If a contender fails to reap (an OS I/O error), that `Err` is returned and
/// the remaining processes stay waitable (cancel-safe). A contender's
/// `ErrorReason::Cancelled` (cancelled run) or [`ErrorReason::Stdin`] (a non-broken-pipe
/// stdin-source failure on its otherwise-successful exit) likewise short-circuits
/// the join — like the bulk verbs, these surface as an `Err`, not an `Outcome`.
///
/// # Errors
///
/// A contender's [`ErrorReason::Io`] (a failed reap), [`ErrorReason::Cancelled`] (a
/// cancelled run), or [`ErrorReason::Stdin`] (a non-broken-pipe stdin-source failure
/// on its otherwise-successful exit) short-circuits the join; the remaining
/// processes stay waitable (cancel-safe). A non-zero exit or signal is returned
/// as an [`Outcome`], not an error. An empty slice resolves to an empty `Vec`.
///
/// # Panics
///
/// Does not panic on any caller input: the final collection step carries an
/// internal consistency assertion (every outcome slot is filled once all
/// contenders have exited, an invariant the join loop maintains). It is
/// documented only because that assertion is a hard `expect`.
pub async
/// Test doubles for the [`ProcessRunner`] seam: a
/// [`ScriptedRunner`](testing::ScriptedRunner) that serves canned replies, a
/// [`RecordingRunner`](testing::RecordingRunner) that asserts on invocations,
/// the [`Invocation`](testing::Invocation) it captures, a
/// [`DryRunRunner`](testing::DryRunRunner) that renders and echoes commands
/// without spawning them, and (behind features) record/replay cassettes and a
/// `mockall` mock.
/// Re-exports of small vocabulary types from the crate's `0.x` dependencies,
/// kept out of the crate root so `use processkit::*` doesn't pull them in (and
/// so a future `0.x` major bump of either dependency stays contained to this
/// module rather than the whole crate surface).
///
/// ```
/// use processkit::prelude::StreamExt;
/// ```
/// Re-exported so callers can `use processkit::CancellationToken;` without a
/// direct `tokio-util` dependency. See [`Command::cancel_on`].
pub use CancellationToken;