Skip to main content

kian_plugin/hooks/sidecar/
runner.rs

1//! The sidecar runner (PLUGIN-SPEC §6.3–§6.5, §7.3–§7.6, §10.3, §11).
2//!
3//! One dedicated **std** thread per sidecar owns the child process for
4//! the server's lifetime: it performs the hardened spawn (§10.3), the
5//! `hello`→`ready` handshake with identity checking (§7.3, rules 12/13),
6//! and serves dispatches one at a time (§7.5's single in-flight rule —
7//! a second dispatch fails fast to `Busy` and never queues). Deadlines
8//! are enforced by a watchdog thread that kills the child's whole
9//! process group, after which the child is respawned with the digest
10//! re-verified and re-handshaked (§6.3). Failures accumulate in §6.4's
11//! window (kind-tagged, cleared by any well-formed reply) until they
12//! trip quarantine; `frame_overflow` and `protocol_violation` quarantine
13//! immediately, one strike (§6.5). Quarantine is one-way for the
14//! process lifetime and the instance is skipped at the bus from then
15//! on.
16//!
17//! The async surface is a thin adapter: [`SidecarRunner::hook_fns`]
18//! turns the runner into tier-0-shaped handlers whose unreachability
19//! maps onto the self-declared `err:deadline` / `err:crashed` replies
20//! [`resolve_outcome`](super::super::failure::resolve_outcome) already
21//! classifies — so the §11.1 grant-keyed class defaults, the audit
22//! lines and the first-deny-wins ordering all come from the one bus
23//! code path (K6), never a second classifier.
24//!
25//! No `libc` edge exists this round (K10 allows only `sha2`), so the
26//! group kill shells out to the absolute-path `/bin/kill` (never a
27//! shell) and falls back to the leader's `SIGKILL` through std.
28
29use std::collections::VecDeque;
30use std::io::Read;
31use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
32use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
33use std::sync::{Arc, Mutex};
34use std::time::{Duration, Instant};
35
36use futures::channel::mpsc::Sender;
37use futures::channel::{mpsc, oneshot};
38use futures::{FutureExt, StreamExt};
39
40use super::super::failure::Cause;
41use super::super::registry::{HookFn, HookPayload, HookReply, ReplyErrCode};
42use super::super::wire::sha256_hex;
43use super::frame::{
44    DecodeError, Hello, HookFrame, ReplyFrame, decode_ready, decode_reply, encode_bye,
45};
46use super::line::{BoundedLineReader, LineError, write_line};
47use super::manifest::{LimitsSection, Manifest, Refusal, RefusalCode, Required};
48
49/// §7.5's graceful-stop grace before the group kill.
50const STOP_GRACE: Duration = Duration::from_millis(2_000);
51/// Bounded reap after a kill: a stuck group must not hang the reaper
52/// (§10.3 step 5).
53const REAP_BOUND: Duration = Duration::from_millis(2_000);
54
55// ---------------------------------------------------------------------
56// Failure window and quarantine (§6.4, §6.5)
57// ---------------------------------------------------------------------
58
59/// The kind tag every window entry carries — the deque is kind-tagged
60/// so a tripping window can say whether it contains only stderr-rate
61/// entries (§6.5).
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum FailureKind {
64    /// `err:deadline` or a deadline kill.
65    Deadline,
66    /// A crash: process exit while a dispatch or handshake was pending.
67    Crash,
68    /// An `err:malformed` / `err:unauthorized` reply, or an unparseable
69    /// line (§6.4's window-counted speech failures).
70    ReplyDefect,
71    /// The retained stderr-rate bound (§10.5).
72    StderrRate,
73}
74
75/// §6.5's quarantine reasons — each names the mechanism that produced
76/// it (window trip vs. immediate one strike).
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum QuarantineReason {
79    /// The §6.4 window tripped with at least one non-stderr entry.
80    RestartsExhausted { failures: usize, window_ms: u64 },
81    /// The window tripped on stderr-rate entries only.
82    StderrRate { failures: usize, window_ms: u64 },
83    /// Unknown / duplicate / unsolicited frame id — immediate (§6.5).
84    ProtocolViolation { detail: String },
85    /// A line over `max_payload_kib` in either direction — immediate.
86    FrameOverflow { direction: &'static str },
87    /// The binary's digest no longer matches at respawn — immediate
88    /// (at boot the same condition is a `plugin/refuse`).
89    DigestMismatch,
90}
91
92/// The §6.4 state machine: one kind-tagged window plus a reported (not
93/// thresholded) respawn counter.
94#[derive(Debug, Default)]
95pub struct Counters {
96    failures: Mutex<VecDeque<(Instant, FailureKind)>>,
97    restarts: AtomicU64,
98}
99
100impl Counters {
101    /// Records a window-counted failure: push `now()`, drop entries
102    /// older than the window, trip quarantine at the threshold. A
103    /// success (any well-formed reply) clears the deque — the failures
104    /// are consecutive by definition (§6.4).
105    pub fn record_failure(
106        &self,
107        kind: FailureKind,
108        limits: &LimitsSection,
109    ) -> Option<QuarantineReason> {
110        let mut failures = self
111            .failures
112            .lock()
113            .expect("kian-plugin: sidecar counters lock poisoned");
114        failures.push_back((Instant::now(), kind));
115        let window = Duration::from_millis(limits.restart_window_ms);
116        while failures
117            .front()
118            .is_some_and(|(at, _)| at.elapsed() > window)
119        {
120            failures.pop_front();
121        }
122        if failures.len() as u64 >= limits.restarts_per_window {
123            let only_stderr = failures.iter().all(|(_, k)| *k == FailureKind::StderrRate);
124            let count = failures.len();
125            return Some(if only_stderr {
126                QuarantineReason::StderrRate {
127                    failures: count,
128                    window_ms: limits.restart_window_ms,
129                }
130            } else {
131                QuarantineReason::RestartsExhausted {
132                    failures: count,
133                    window_ms: limits.restart_window_ms,
134                }
135            });
136        }
137        None
138    }
139
140    /// A well-formed reply clears the consecutive-failure window.
141    pub fn record_success(&self) {
142        self.failures
143            .lock()
144            .expect("kian-plugin: sidecar counters lock poisoned")
145            .clear();
146    }
147
148    /// Counts an actual respawn — reported, never thresholded (§6.4).
149    pub fn record_restart(&self) -> u64 {
150        self.restarts.fetch_add(1, Ordering::Relaxed) + 1
151    }
152
153    pub fn restarts(&self) -> u64 {
154        self.restarts.load(Ordering::Relaxed)
155    }
156
157    pub fn window_len(&self) -> usize {
158        self.failures
159            .lock()
160            .expect("kian-plugin: sidecar counters lock poisoned")
161            .len()
162    }
163}
164
165// ---------------------------------------------------------------------
166// Jobs and outcomes
167// ---------------------------------------------------------------------
168
169enum Job {
170    Dispatch {
171        frame: HookFrame,
172        reply: oneshot::Sender<ReplyOutcome>,
173    },
174    Stop {
175        done: oneshot::Sender<()>,
176    },
177}
178
179/// What one dispatch resolved to, before the adapter shapes it for the
180/// bus's classifier.
181#[derive(Debug, Clone, PartialEq, Eq)]
182pub enum ReplyOutcome {
183    /// A decoded reply frame (including `err` replies — the bus
184    /// classifies those, not the runner).
185    Reply(HookReply),
186    /// A protocol violation whose dispatch outcome is as-if-absent
187    /// (§7.4): quarantining is the runner's job, deciding is not.
188    AsIfAbsent { detail: String },
189    /// §7.5's fail-fast: one dispatch is in flight; never queued.
190    Busy,
191    /// The handler cannot answer — the adapter maps this to the
192    /// self-declared unreachability reply so the §11.1 grant-keyed
193    /// class default applies.
194    Unreachable { cause: Cause, detail: String },
195}
196
197// ---------------------------------------------------------------------
198// The runner
199// ---------------------------------------------------------------------
200
201struct Inner {
202    name: String,
203    manifest: Manifest,
204    canonical_path: String,
205    /// The job slot (§7.6: bounded internal channels — one per
206    /// sidecar). Mutex'd because the futures sender's `try_send`
207    /// needs `&mut`; the in-flight flag below is what actually
208    /// serializes dispatches.
209    tx: Mutex<Sender<Job>>,
210    next_dispatch_id: AtomicU64,
211    counters: Counters,
212    quarantine: Mutex<Option<QuarantineReason>>,
213    /// §7.5's single in-flight rule, enforced before the job channel:
214    /// while a dispatch is unanswered the runner is busy, and a second
215    /// dispatch **never queues** — the channel alone could not express
216    /// that (a buffered slot is a queue).
217    in_flight: AtomicBool,
218}
219
220/// Resets the in-flight flag when dropped — cancellation-safe across
221/// the await point.
222struct InFlightGuard<'a>(&'a AtomicBool);
223
224impl Drop for InFlightGuard<'_> {
225    fn drop(&mut self) {
226        self.0.store(false, Ordering::SeqCst);
227    }
228}
229
230/// A running sidecar: one child process, one io thread, one in-flight
231/// dispatch. Cheap to clone (an `Arc` inside); [`SidecarRunner::stop`]
232/// is the graceful shutdown (`bye`, half-close, bounded grace, group
233/// kill — §7.5).
234#[derive(Clone)]
235pub struct SidecarRunner {
236    inner: Arc<Inner>,
237}
238
239impl std::fmt::Debug for SidecarRunner {
240    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
241        f.debug_struct("SidecarRunner")
242            .field("name", &self.inner.name)
243            .field("quarantined", &self.quarantined())
244            .finish_non_exhaustive()
245    }
246}
247
248/// A watchdog: sleeps the deadline, then — only if the awaited event
249/// has not arrived — records the deadline cause and kills the child's
250/// process group (§10.3 step 5). The read side consults the cause when
251/// its blocking read unblocks, which distinguishes a deadline kill
252/// from a crash.
253#[derive(Clone)]
254struct WatchdogHandle {
255    answered: Arc<AtomicBool>,
256    deadline_fired: Arc<Mutex<bool>>,
257    pid: Arc<AtomicU64>,
258}
259
260impl WatchdogHandle {
261    fn arm(&self, timeout: Duration) {
262        let handle = self.clone();
263        std::thread::spawn(move || {
264            std::thread::sleep(timeout);
265            if !handle.answered.load(Ordering::SeqCst) {
266                // Set the cause *before* the kill so the reader that
267                // unblocks on the dying pipe sees it (§11.2: the child
268                // is killed for a timeout, never left running).
269                *handle.deadline_fired.lock().unwrap() = true;
270                kill_group(handle.pid.load(Ordering::SeqCst) as u32);
271            }
272        });
273    }
274
275    fn mark_answered(&self) -> bool {
276        self.answered.swap(true, Ordering::SeqCst)
277    }
278}
279
280/// One live child plus its carrier halves.
281struct Session {
282    child: Child,
283    /// `Option` so the graceful stop can half-close (§7.5); `None`
284    /// after that is a crash-class unreachability for any late write.
285    stdin: Option<ChildStdin>,
286    stdout: BoundedLineReader<ChildStdout>,
287    pid: u32,
288    /// Cleared when the session must not be reused (killed, crashed,
289    /// overflowed); the io loop respawns then.
290    alive: bool,
291}
292
293/// Why a spawn+handshake failed — mapped to boot refusals (§6.2 rules
294/// 6/12/13) on the first spawn and to window failures on respawns.
295enum HandshakeFailure {
296    DigestMismatch,
297    Spawn(String),
298    Timeout,
299    ReadyMismatch(String),
300    AbiMismatch,
301    Crashed(String),
302}
303
304impl SidecarRunner {
305    /// Spawns and handshakes one sidecar instance (§6.3's
306    /// `configured → spawning → handshaking → ready`). Blocks for at
307    /// most the manifest's `startup_timeout_ms` plus slack; a failure
308    /// is the typed per-instance refusal the caller audits
309    /// (`plugin/refuse`, fatal iff `required` — the caller's policy,
310    /// §6.2).
311    pub fn start(manifest: Manifest, canonical_path: &std::path::Path) -> Result<Self, Refusal> {
312        let canonical =
313            std::fs::canonicalize(canonical_path).unwrap_or_else(|_| canonical_path.to_path_buf());
314        let name = manifest.plugin.name.clone();
315        let (tx, rx) = mpsc::channel(1);
316        let inner = Arc::new(Inner {
317            name: name.clone(),
318            manifest,
319            canonical_path: canonical.display().to_string(),
320            tx: Mutex::new(tx),
321            next_dispatch_id: AtomicU64::new(0),
322            counters: Counters::default(),
323            quarantine: Mutex::new(None),
324            in_flight: AtomicBool::new(false),
325        });
326        let (handshake_tx, handshake_rx) = std::sync::mpsc::channel::<Result<(), Refusal>>();
327        let thread_inner = Arc::clone(&inner);
328        let spawn_result = std::thread::Builder::new()
329            .name(format!("kian-sidecar-{name}"))
330            .spawn(move || io_thread(thread_inner, rx, handshake_tx));
331        if spawn_result.is_err() {
332            return Err(Refusal {
333                code: RefusalCode::SpawnFailed,
334                message: format!("could not spawn the io thread for `{name}`"),
335                required: inner.manifest.required(),
336            });
337        }
338        let slack = Duration::from_millis(2_000);
339        let bound = Duration::from_millis(inner.manifest.process.startup_timeout_ms) + slack;
340        match handshake_rx.recv_timeout(bound) {
341            Ok(Ok(())) => Ok(Self { inner }),
342            Ok(Err(refusal)) => {
343                audit_refuse(&refusal);
344                Err(refusal)
345            }
346            Err(_) => Err(Refusal {
347                code: RefusalCode::SpawnFailed,
348                message: format!(
349                    "`{name}`: hello→ready did not complete within startup_timeout_ms"
350                ),
351                required: inner.manifest.required(),
352            }),
353        }
354    }
355
356    /// The instance's plugin name (audit identity).
357    pub fn name(&self) -> &str {
358        &self.inner.name
359    }
360
361    /// The counters handle (§6.4) — reported, never thresholded
362    /// outside the runner.
363    pub fn counters(&self) -> &Counters {
364        &self.inner.counters
365    }
366
367    /// The quarantine reason, if the instance is quarantined (§6.5:
368    /// one-way for the process lifetime).
369    pub fn quarantined(&self) -> Option<QuarantineReason> {
370        self.inner
371            .quarantine
372            .lock()
373            .expect("kian-plugin: quarantine lock poisoned")
374            .clone()
375    }
376
377    /// Dispatches one frame to the sidecar: fails fast to
378    /// [`ReplyOutcome::Busy`] while a dispatch is in flight (§7.5 —
379    /// never queued), resolves unreachability to the cause the adapter
380    /// turns into the §11.1 class default.
381    pub async fn dispatch(&self, frame: HookFrame) -> ReplyOutcome {
382        if let Some(reason) = self.quarantined() {
383            return ReplyOutcome::Unreachable {
384                cause: Cause::Quarantine,
385                detail: format!("quarantined: {reason:?}"),
386            };
387        }
388        if self.inner.in_flight.swap(true, Ordering::SeqCst) {
389            return ReplyOutcome::Busy;
390        }
391        let _in_flight = InFlightGuard(&self.inner.in_flight);
392        let (reply_tx, reply_rx) = oneshot::channel();
393        let sent = self
394            .inner
395            .tx
396            .lock()
397            .expect("kian-plugin: sidecar job-slot lock poisoned")
398            .try_send(Job::Dispatch {
399                frame,
400                reply: reply_tx,
401            });
402        match sent {
403            Ok(()) => match reply_rx.await {
404                Ok(outcome) => outcome,
405                Err(_) => ReplyOutcome::Unreachable {
406                    cause: Cause::Crash,
407                    detail: "sidecar stopped".to_string(),
408                },
409            },
410            // With the in-flight flag held, a send failure means the
411            // receiver is gone — quarantined or stopped (the futures
412            // `TrySendError` does not distinguish; the quarantine
413            // check above already reported the reason if there is
414            // one).
415            Err(_) => ReplyOutcome::Unreachable {
416                cause: Cause::Quarantine,
417                detail: "sidecar io thread exited (quarantined or stopped)".to_string(),
418            },
419        }
420    }
421
422    /// Graceful stop (§7.5): `bye`, close stdin (half-close), wait a
423    /// bounded grace period, then kill the whole process group. Blocks
424    /// for at most the grace; call at shutdown, not from async code.
425    pub fn stop(&self) {
426        let (done_tx, done_rx) = oneshot::channel();
427        let sent = self
428            .inner
429            .tx
430            .lock()
431            .expect("kian-plugin: sidecar job-slot lock poisoned")
432            .try_send(Job::Stop { done: done_tx });
433        if sent.is_ok() {
434            let _ = futures::executor::block_on(done_rx);
435        }
436    }
437
438    /// A fresh dispatch id. Process-unique per sidecar (§7.3 wants a
439    /// fresh uuid; K10 forbids the `uuid` edge this round, so the id
440    /// is the sidecar-tagged counter the same way the tier-0 bus ids
441    /// are — uniqueness and reply attribution are what the protocol
442    /// needs).
443    fn next_dispatch_id(&self) -> String {
444        format!(
445            "sc-{}-{}",
446            self.inner.name,
447            self.inner.next_dispatch_id.fetch_add(1, Ordering::Relaxed)
448        )
449    }
450
451    /// Tier-0-shaped handlers for the bus: one per subscribed hook,
452    /// carrying the manifest's grants and order. The plugin name is
453    /// leaked for the `&'static str` the tier-0 `HandlerId` requires —
454    /// one process per plugin per server lifetime (R11), so the leak
455    /// is bounded by the instance count.
456    pub fn hook_fns(self: &Arc<Self>) -> Vec<(super::super::registry::HandlerId, HookFn)> {
457        let mut out = Vec::new();
458        for hook in self.inner.manifest.grants.hooks.clone() {
459            let plugin: &'static str = Box::leak(self.inner.name.clone().into_boxed_str());
460            let runner = Arc::clone(self);
461            let hook_for_closure = hook.clone();
462            let deadline_ms = self.inner.manifest.limits.deadline_ms;
463            let handler = super::super::registry::HandlerId {
464                plugin,
465                hook,
466                grants: self.inner.manifest.grants.grants.clone(),
467                order: self.inner.manifest.plugin.order,
468            };
469            let f: HookFn = Arc::new(move |payload: &HookPayload| {
470                let runner = Arc::clone(&runner);
471                // Extract everything borrowed before the async block.
472                let frame_info = payload.frame().cloned();
473                let payload_value = payload_value(payload);
474                let dispatch_id = runner.next_dispatch_id();
475                let hook = hook_for_closure.clone();
476                async move {
477                    let Some(frame_info) = frame_info else {
478                        tracing::warn!(
479                            target: "kian::hook",
480                            hook = %hook,
481                            plugin = plugin,
482                            "sidecar dispatch without frame identity — skipped (R11: no implicit identity)"
483                        );
484                        return HookReply::Ack { note: None };
485                    };
486                    let hook_for_log = hook.clone();
487                    let frame = match HookFrame::new(
488                        hook,
489                        &frame_info,
490                        dispatch_id,
491                        deadline_ms,
492                        payload_value,
493                    ) {
494                        Ok(frame) => frame,
495                        Err(e) => {
496                            // The epoch rule's local guard (§7.2): the
497                            // call site built an incoherent frame. Skip
498                            // the sidecar rather than deny on a
499                            // harness-side defect.
500                            tracing::error!(
501                                target: "kian::hook",
502                                hook = %hook_for_log,
503                                plugin = plugin,
504                                error = %e.message,
505                                "sidecar frame rejected — dispatch skipped"
506                            );
507                            return HookReply::Ack { note: None };
508                        }
509                    };
510                    match runner.dispatch(frame).await {
511                        ReplyOutcome::Reply(reply) => reply,
512                        ReplyOutcome::AsIfAbsent { .. } => {
513                            tracing::info!(
514                                target: "kian::hook",
515                                hook = %hook_for_log,
516                                plugin = plugin,
517                                outcome = "discarded",
518                                "hook-discard"
519                            );
520                            HookReply::Ack { note: None }
521                        }
522                        ReplyOutcome::Busy => {
523                            // §7.5's busy audit line — never queued.
524                            tracing::info!(
525                                target: "kian::hook",
526                                hook = %hook_for_log,
527                                plugin = plugin,
528                                busy = true,
529                                "hook-default"
530                            );
531                            HookReply::Err {
532                                code: ReplyErrCode::Crashed,
533                                message: "busy: one dispatch in flight".to_string(),
534                            }
535                        }
536                        ReplyOutcome::Unreachable { cause, detail } => HookReply::Err {
537                            code: match cause {
538                                Cause::Deadline => ReplyErrCode::Deadline,
539                                _ => ReplyErrCode::Crashed,
540                            },
541                            message: format!("{detail} ({})", cause.as_str()),
542                        },
543                    }
544                }
545                .boxed()
546            });
547            out.push((handler, f));
548        }
549        out
550    }
551}
552
553// ---------------------------------------------------------------------
554// The io thread
555// ---------------------------------------------------------------------
556
557fn io_thread(
558    inner: Arc<Inner>,
559    mut rx: mpsc::Receiver<Job>,
560    handshake: std::sync::mpsc::Sender<Result<(), Refusal>>,
561) {
562    let mut session = match spawn_session(&inner, true) {
563        Ok(session) => {
564            let _ = handshake.send(Ok(()));
565            session
566        }
567        Err(failure) => {
568            let refusal = boot_refusal(&inner, failure);
569            let _ = handshake.send(Err(refusal.clone()));
570            audit_refuse(&refusal);
571            return;
572        }
573    };
574    loop {
575        if inner.quarantine_locked().is_some() {
576            // §6.5: a quarantined instance is skipped at the bus and
577            // never respawns; the io thread retires.
578            return;
579        }
580        let job = match futures::executor::block_on(rx.next()) {
581            Some(job) => job,
582            None => {
583                graceful_stop(&mut session);
584                return;
585            }
586        };
587        match job {
588            Job::Stop { done } => {
589                graceful_stop(&mut session);
590                let _ = done.send(());
591                return;
592            }
593            Job::Dispatch { frame, reply } => {
594                let outcome = serve_dispatch(&inner, &mut session, frame);
595                let _ = reply.send(outcome);
596                if !session.alive && inner.quarantine_locked().is_none() {
597                    // §6.3: respawn after a crash or deadline kill,
598                    // inside the failure window, digest re-verified,
599                    // re-handshaked before the next dispatch.
600                    session = match respawn_until_ready(&inner) {
601                        Some(session) => session,
602                        None => return, // quarantined (or window tripped)
603                    };
604                }
605            }
606        }
607    }
608}
609
610/// Serves exactly one dispatch on a live session (§7.5: the io thread
611/// is the serialization point; nothing else touches the child).
612fn serve_dispatch(inner: &Arc<Inner>, session: &mut Session, frame: HookFrame) -> ReplyOutcome {
613    let max = inner.manifest.limits.max_frame_bytes();
614    let line = frame.encode();
615    let Some(stdin) = session.stdin.as_mut() else {
616        record_window_failure(inner, FailureKind::Crash);
617        kill_session(session);
618        return ReplyOutcome::Unreachable {
619            cause: Cause::Crash,
620            detail: "stdin already closed (stop in progress)".to_string(),
621        };
622    };
623    match write_line(stdin, &line, max) {
624        Err(LineError::Overflow { scanned, max }) => {
625            quarantine(
626                inner,
627                QuarantineReason::FrameOverflow {
628                    direction: "outbound",
629                },
630            );
631            kill_session(session);
632            return ReplyOutcome::Unreachable {
633                cause: Cause::Crash,
634                detail: format!("frame_overflow: outbound line {scanned} > {max} bytes"),
635            };
636        }
637        Err(LineError::Io(e)) => {
638            // The write itself failed: a crash.
639            if let Some(reason) = record_window_failure(inner, FailureKind::Crash) {
640                quarantine(inner, reason);
641            }
642            kill_session(session);
643            return ReplyOutcome::Unreachable {
644                cause: Cause::Crash,
645                detail: format!("stdin write failed: {e}"),
646            };
647        }
648        Ok(()) => {}
649    }
650
651    let watchdog = WatchdogHandle {
652        answered: Arc::new(AtomicBool::new(false)),
653        deadline_fired: Arc::new(Mutex::new(false)),
654        pid: Arc::new(AtomicU64::new(u64::from(session.pid))),
655    };
656    watchdog.arm(Duration::from_millis(inner.manifest.limits.deadline_ms));
657
658    match session.stdout.read_line(max) {
659        Err(LineError::Overflow { scanned, max }) => {
660            // §7.6: immediate one-strike quarantine, and the class
661            // default for this dispatch — never a window increment.
662            quarantine(
663                inner,
664                QuarantineReason::FrameOverflow {
665                    direction: "inbound",
666                },
667            );
668            tracing::info!(
669                target: "kian::hook",
670                plugin = %inner.name,
671                direction = "inbound",
672                scanned = scanned,
673                max = max,
674                "hook-quarantine-overflow"
675            );
676            kill_session(session);
677            ReplyOutcome::Unreachable {
678                cause: Cause::Crash,
679                detail: format!("frame_overflow: inbound line {scanned} > {max} bytes"),
680            }
681        }
682        Err(LineError::Io(e)) => {
683            let deadline = *watchdog.deadline_fired.lock().unwrap();
684            kill_session(session);
685            let kind = if deadline {
686                FailureKind::Deadline
687            } else {
688                // EOF without the expected reply is a crash, never an
689                // empty allow (§7.5).
690                FailureKind::Crash
691            };
692            if let Some(reason) = record_window_failure(inner, kind) {
693                // The window tripped with this very failure (§6.4).
694                quarantine(inner, reason);
695            }
696            if deadline {
697                ReplyOutcome::Unreachable {
698                    cause: Cause::Deadline,
699                    detail: "deadline: child killed over the dispatch deadline".to_string(),
700                }
701            } else {
702                ReplyOutcome::Unreachable {
703                    cause: Cause::Crash,
704                    detail: format!("crash: child pipe closed ({e})"),
705                }
706            }
707        }
708        Ok(line) => {
709            watchdog.mark_answered();
710            match decode_reply(&line) {
711                Err(DecodeError::Malformed(detail)) => {
712                    // An unparseable reply is the err:malformed class
713                    // — discarded as an opinion at the bus and
714                    // window-counted here (§6.4, §11.1).
715                    record_window_failure(inner, FailureKind::ReplyDefect);
716                    ReplyOutcome::Reply(HookReply::Err {
717                        code: ReplyErrCode::Malformed,
718                        message: detail,
719                    })
720                }
721                Ok((reply_id, reply_frame)) => {
722                    let id_ok = reply_id.as_ref().map(|id| id == &frame.id).unwrap_or(true); // id-less err: the one in-flight
723                    if !id_ok {
724                        // §7.4: a second/unsolicited reply is an
725                        // immediate quarantine, and this dispatch is
726                        // as-if-absent.
727                        quarantine(
728                            inner,
729                            QuarantineReason::ProtocolViolation {
730                                detail: format!(
731                                    "reply id `{reply_id:?}` ≠ dispatch id `{}`",
732                                    frame.id
733                                ),
734                            },
735                        );
736                        kill_session(session);
737                        return ReplyOutcome::AsIfAbsent {
738                            detail: "protocol_violation: reply for another dispatch id".to_string(),
739                        };
740                    }
741                    match reply_frame {
742                        ReplyFrame::Err { code, message }
743                            if matches!(
744                                code,
745                                ReplyErrCode::Deadline
746                                    | ReplyErrCode::Malformed
747                                    | ReplyErrCode::Unauthorized
748                            ) =>
749                        {
750                            // §6.4's window-counted err replies.
751                            let kind = if code == ReplyErrCode::Deadline {
752                                FailureKind::Deadline
753                            } else {
754                                FailureKind::ReplyDefect
755                            };
756                            if let Some(reason) = record_window_failure(inner, kind) {
757                                quarantine(inner, reason);
758                                kill_session(session);
759                            }
760                            ReplyOutcome::Reply(HookReply::Err { code, message })
761                        }
762                        other => {
763                            // Any well-formed reply is a success — it
764                            // clears the consecutive window (§6.4).
765                            inner.counters.record_success();
766                            ReplyOutcome::Reply(frame_to_reply(other))
767                        }
768                    }
769                }
770            }
771        }
772    }
773}
774
775fn frame_to_reply(frame: ReplyFrame) -> HookReply {
776    match frame {
777        ReplyFrame::Ack { note } => HookReply::Ack { note },
778        ReplyFrame::FlowNext => HookReply::FlowNext,
779        ReplyFrame::FlowStop { reason } => HookReply::FlowStop { reason },
780        ReplyFrame::BailNone => HookReply::BailNone,
781        ReplyFrame::BailDeny { reason } => HookReply::BailDeny { reason },
782        ReplyFrame::Err { code, message } => HookReply::Err { code, message },
783    }
784}
785
786/// Respawns after a crash/deadline kill until the child is ready again
787/// or the failure window trips quarantine (§6.3, §6.4) — each failed
788/// attempt counts, so the loop is bounded by `restarts_per_window`.
789fn respawn_until_ready(inner: &Arc<Inner>) -> Option<Session> {
790    loop {
791        match spawn_session(inner, false) {
792            Ok(session) => {
793                let restarts = inner.counters.record_restart();
794                tracing::info!(
795                    target: "kian::hook",
796                    plugin = %inner.name,
797                    restarts = restarts,
798                    digest_ok = true,
799                    "hook-respawn"
800                );
801                return Some(session);
802            }
803            Err(HandshakeFailure::DigestMismatch) => {
804                // §6.5: digest mismatch at respawn — immediate.
805                quarantine(inner, QuarantineReason::DigestMismatch);
806                return None;
807            }
808            Err(_) => {
809                if let Some(reason) = record_window_failure(inner, FailureKind::Crash) {
810                    quarantine(inner, reason);
811                    return None;
812                }
813            }
814        }
815    }
816}
817
818// ---------------------------------------------------------------------
819// Spawn + handshake (§10.3, §7.3)
820// ---------------------------------------------------------------------
821
822fn spawn_session(inner: &Arc<Inner>, first: bool) -> Result<Session, HandshakeFailure> {
823    let manifest = &inner.manifest;
824    // §10.3 step 6: digest verification at spawn and at every respawn.
825    match digest_of(&manifest.process.argv[0]) {
826        Some(digest) if digest == manifest.process.sha256 => {}
827        Some(_) => return Err(HandshakeFailure::DigestMismatch),
828        None => {
829            return Err(HandshakeFailure::Spawn(format!(
830                "argv[0] `{}` unreadable for digest verification",
831                manifest.process.argv[0]
832            )));
833        }
834    }
835
836    let mut command = Command::new(&manifest.process.argv[0]);
837    command
838        .args(&manifest.process.argv[1..])
839        // §10.3 step 2: env_clear first, then exactly env_allow with
840        // the server's values — no PATH, HOME, proxies or credentials.
841        .env_clear();
842    for name in &manifest.process.env_allow {
843        if let Ok(value) = std::env::var(name) {
844            command.env(name, value);
845        }
846    }
847    // §10.3 step 3: dedicated cwd (the manifest's, or a fresh empty
848    // directory under the server's own temp — never an inherited one).
849    let _owned_cwd;
850    match &manifest.process.cwd {
851        Some(cwd) => {
852            command.current_dir(cwd);
853        }
854        None => {
855            let dir = std::env::temp_dir().join(format!(
856                "kian-sidecar-{}-{}",
857                manifest.plugin.name,
858                std::process::id()
859            ));
860            if std::fs::create_dir_all(&dir).is_err() {
861                return Err(HandshakeFailure::Spawn(format!(
862                    "could not create the runtime cwd `{}`",
863                    dir.display()
864                )));
865            }
866            _owned_cwd = dir;
867            command.current_dir(&_owned_cwd);
868        }
869    }
870    // §10.3 step 4: pipe exactly stdin/stdout/stderr; step 5: a
871    // killable process group.
872    command
873        .stdin(Stdio::piped())
874        .stdout(Stdio::piped())
875        .stderr(Stdio::piped());
876    #[cfg(unix)]
877    {
878        use std::os::unix::process::CommandExt;
879        command.process_group(0);
880    }
881    let mut child = command
882        .spawn()
883        .map_err(|e| HandshakeFailure::Spawn(format!("spawn failed: {e}")))?;
884    let pid = child.id();
885    let mut stdin = child
886        .stdin
887        .take()
888        .ok_or_else(|| HandshakeFailure::Spawn("stdin pipe missing".to_string()))?;
889    let stdout = child
890        .stdout
891        .take()
892        .ok_or_else(|| HandshakeFailure::Spawn("stdout pipe missing".to_string()))?;
893    let stderr = child
894        .stderr
895        .take()
896        .ok_or_else(|| HandshakeFailure::Spawn("stderr pipe missing".to_string()))?;
897
898    // §7.6/§10.5: stderr is drained concurrently, bounded, tagged,
899    // never parsed, never logged with content.
900    let stderr_inner = Arc::clone(inner);
901    let _stderr_thread = std::thread::Builder::new()
902        .name(format!("kian-sidecar-{}-stderr", manifest.plugin.name))
903        .spawn(move || drain_stderr(stderr_inner, stderr));
904
905    let mut reader = BoundedLineReader::new(stdout);
906    let hello = Hello {
907        manifest: inner.canonical_path.clone(),
908        name: manifest.plugin.name.clone(),
909        version: manifest.plugin.version.clone(),
910        abi: manifest.plugin.abi,
911        hooks: manifest
912            .grants
913            .hooks
914            .iter()
915            .map(|h| h.to_string())
916            .collect(),
917        capabilities: manifest
918            .grants
919            .grants
920            .iter()
921            .map(|g| g.as_str().to_string())
922            .collect(),
923        deadline_default_ms: manifest.limits.deadline_ms,
924        max_frame_bytes: manifest.limits.max_frame_bytes(),
925    };
926    let max = manifest.limits.max_frame_bytes();
927    match write_line(&mut stdin, &hello.encode(), max) {
928        Err(LineError::Overflow { .. }) => {
929            kill_child(&mut child);
930            return Err(HandshakeFailure::ReadyMismatch(
931                "hello over the frame bound".to_string(),
932            ));
933        }
934        Err(LineError::Io(e)) => {
935            kill_child(&mut child);
936            return Err(HandshakeFailure::Crashed(format!(
937                "hello write failed: {e}"
938            )));
939        }
940        Ok(()) => {}
941    }
942
943    let watchdog = WatchdogHandle {
944        answered: Arc::new(AtomicBool::new(false)),
945        deadline_fired: Arc::new(Mutex::new(false)),
946        pid: Arc::new(AtomicU64::new(u64::from(pid))),
947    };
948    // Rule 13 (§6.2): hello→ready within startup_timeout_ms.
949    watchdog.arm(Duration::from_millis(manifest.process.startup_timeout_ms));
950
951    let ready_line = match reader.read_line(max) {
952        Ok(line) => {
953            watchdog.mark_answered();
954            line
955        }
956        Err(LineError::Overflow { .. }) => {
957            kill_child(&mut child);
958            return Err(HandshakeFailure::ReadyMismatch(
959                "ready over the frame bound".to_string(),
960            ));
961        }
962        Err(LineError::Io(e)) => {
963            let deadline = *watchdog.deadline_fired.lock().unwrap();
964            kill_child(&mut child);
965            return Err(if deadline {
966                HandshakeFailure::Timeout
967            } else {
968                HandshakeFailure::Crashed(format!("child closed stdout before ready ({e})"))
969            });
970        }
971    };
972    let ready = match decode_ready(&ready_line) {
973        Ok(ready) => ready,
974        Err(DecodeError::Malformed(detail)) => {
975            kill_child(&mut child);
976            return Err(HandshakeFailure::ReadyMismatch(detail));
977        }
978    };
979    // §7.3 step 2: the ready must restate the identity exactly, with
980    // set-equal hooks/capabilities — typed refusals otherwise.
981    if ready.abi != manifest.plugin.abi {
982        kill_child(&mut child);
983        return Err(HandshakeFailure::AbiMismatch);
984    }
985    if ready.manifest != inner.canonical_path
986        || ready.name != manifest.plugin.name
987        || ready.version != manifest.plugin.version
988        || !set_equal(&ready.hooks, &hello.hooks)
989        || !set_equal(&ready.capabilities, &hello.capabilities)
990    {
991        kill_child(&mut child);
992        return Err(HandshakeFailure::ReadyMismatch(format!(
993            "ready restates a different identity (manifest={}, name={}, version={}, hooks/capabilities sets differ)",
994            ready.manifest, ready.name, ready.version
995        )));
996    }
997    let _ = first; // boot refusal mapping happens in the caller
998    Ok(Session {
999        child,
1000        stdin: Some(stdin),
1001        stdout: reader,
1002        pid,
1003        alive: true,
1004    })
1005}
1006
1007/// §10.5's stderr discipline: per-line bound (drop + one count per
1008/// drop-burst), retained-rate bound (one count per minute), all
1009/// content discarded — never parsed, never logged.
1010///
1011/// A *drop burst* is a run of oversized lines not separated by more
1012/// than a second: coalescing is meant to keep one fragmented huge
1013/// line from counting many times, not to make an endless flood count
1014/// once (§6.5's stderr-only window mechanism requires the flood to be
1015/// able to trip it).
1016fn drain_stderr(inner: Arc<Inner>, stderr: std::process::ChildStderr) {
1017    let limits = inner.manifest.limits;
1018    let line_max = (limits.max_stderr_line_kib as usize) * 1024;
1019    let rate_max = (limits.stderr_rate_kib_per_min as usize) * 1024;
1020    let mut reader = BoundedLineReader::new(stderr);
1021    let mut last_drop: Option<Instant> = None;
1022    let mut retained: VecDeque<(Instant, usize)> = VecDeque::new();
1023    let mut retained_bytes = 0usize;
1024    let mut last_rate_note: Option<Instant> = None;
1025    loop {
1026        match reader.read_line(line_max) {
1027            Ok(line) => {
1028                last_drop = None; // an in-bounds line ends any burst
1029                let now = Instant::now();
1030                retained.push_back((now, line.len()));
1031                retained_bytes = retained_bytes.saturating_add(line.len());
1032                while retained
1033                    .front()
1034                    .is_some_and(|(at, _)| now.duration_since(*at) > Duration::from_secs(60))
1035                {
1036                    let (_, size) = retained.pop_front().unwrap();
1037                    retained_bytes = retained_bytes.saturating_sub(size);
1038                }
1039                if retained_bytes > rate_max
1040                    && last_rate_note
1041                        .is_none_or(|at| now.duration_since(at) > Duration::from_secs(60))
1042                {
1043                    last_rate_note = Some(now);
1044                    tracing::info!(
1045                        target: "kian::hook",
1046                        plugin = %inner.name,
1047                        kind = "stderr_rate",
1048                        "stderr rate bound exceeded — excess dropped"
1049                    );
1050                    if let Some(reason) = record_window_failure(&inner, FailureKind::StderrRate) {
1051                        quarantine(&inner, reason);
1052                        return;
1053                    }
1054                }
1055            }
1056            Err(LineError::Overflow { scanned, max }) => {
1057                // Drop the oversized line; count at most one
1058                // stderr_overflow per second — a fragmented huge line
1059                // counts once, an endless flood counts once per second
1060                // and can trip the window (§6.4, §6.5).
1061                tracing::info!(
1062                    target: "kian::hook",
1063                    plugin = %inner.name,
1064                    kind = "stderr_line",
1065                    scanned = scanned,
1066                    max = max,
1067                    "stderr line over bound — dropped"
1068                );
1069                let now = Instant::now();
1070                if last_drop.is_none_or(|at| now.duration_since(at) >= Duration::from_secs(1)) {
1071                    // Stamp only when counting: a drop that does not
1072                    // count must not push the window forward.
1073                    last_drop = Some(now);
1074                    if let Some(reason) = record_window_failure(&inner, FailureKind::StderrRate) {
1075                        quarantine(&inner, reason);
1076                        return;
1077                    }
1078                }
1079                if !reader.discard_line() {
1080                    return;
1081                }
1082            }
1083            Err(LineError::Io(_)) => return, // EOF: the child is gone
1084        }
1085    }
1086}
1087
1088fn set_equal(a: &[String], b: &[String]) -> bool {
1089    let mut left: Vec<&String> = a.iter().collect();
1090    let mut right: Vec<&String> = b.iter().collect();
1091    left.sort();
1092    right.sort();
1093    left == right
1094}
1095
1096fn digest_of(path: &str) -> Option<String> {
1097    let mut file = std::fs::File::open(path).ok()?;
1098    let mut buf = Vec::new();
1099    file.read_to_end(&mut buf).ok()?;
1100    Some(sha256_hex(&buf))
1101}
1102
1103// ---------------------------------------------------------------------
1104// Quarantine, kills, stops
1105// ---------------------------------------------------------------------
1106
1107impl Inner {
1108    fn quarantine_locked(&self) -> Option<QuarantineReason> {
1109        self.quarantine
1110            .lock()
1111            .expect("kian-plugin: quarantine lock poisoned")
1112            .clone()
1113    }
1114}
1115
1116/// Quarantines the instance (§6.5): one-way for the process lifetime,
1117/// one `hook-quarantine` audit line with name, reason, failure count
1118/// and window. There is no un-quarantine surface in v1 (D3).
1119fn quarantine(inner: &Arc<Inner>, reason: QuarantineReason) {
1120    let mut slot = inner
1121        .quarantine
1122        .lock()
1123        .expect("kian-plugin: quarantine lock poisoned");
1124    if slot.is_some() {
1125        return; // the first reason stands
1126    }
1127    let failures = inner.counters.window_len();
1128    let window_ms = inner.manifest.limits.restart_window_ms;
1129    tracing::info!(
1130        target: "kian::hook",
1131        plugin = %inner.name,
1132        reason = %reason.as_audit_str(),
1133        failures = failures,
1134        window_ms = window_ms,
1135        lifetime = "server-process",
1136        "hook-quarantine"
1137    );
1138    *slot = Some(reason);
1139}
1140
1141impl QuarantineReason {
1142    /// The audit-line spelling.
1143    pub fn as_audit_str(&self) -> String {
1144        match self {
1145            QuarantineReason::RestartsExhausted {
1146                failures,
1147                window_ms,
1148            } => {
1149                format!("restarts_exhausted(failures={failures}, window_ms={window_ms})")
1150            }
1151            QuarantineReason::StderrRate {
1152                failures,
1153                window_ms,
1154            } => {
1155                format!("stderr_overflow(failures={failures}, window_ms={window_ms})")
1156            }
1157            QuarantineReason::ProtocolViolation { detail } => {
1158                format!("protocol_violation({detail})")
1159            }
1160            QuarantineReason::FrameOverflow { direction } => {
1161                format!("frame_overflow({direction})")
1162            }
1163            QuarantineReason::DigestMismatch => "digest_mismatch(respawn)".to_string(),
1164        }
1165    }
1166}
1167
1168/// Records a window-counted failure and quarantines when the window
1169/// trips (§6.4).
1170fn record_window_failure(inner: &Arc<Inner>, kind: FailureKind) -> Option<QuarantineReason> {
1171    inner.counters.record_failure(kind, &inner.manifest.limits)
1172}
1173
1174fn kill_session(session: &mut Session) {
1175    session.alive = false;
1176    kill_group(session.pid);
1177    let _ = session.child.kill();
1178    reap_bounded(&mut session.child);
1179}
1180
1181fn kill_child(child: &mut Child) {
1182    let pid = child.id();
1183    kill_group(pid);
1184    let _ = child.kill();
1185    reap_bounded(child);
1186}
1187
1188/// Kills the child's whole process group (§10.3 step 5). Without a
1189/// `libc` edge (K10) the group signal goes through the absolute-path
1190/// `/bin/kill` — a direct binary, never a shell; the leader itself is
1191/// always killed through std afterwards regardless.
1192fn kill_group(pid: u32) {
1193    if pid == 0 {
1194        return;
1195    }
1196    #[cfg(unix)]
1197    {
1198        let target = format!("-{pid}");
1199        for killer in ["/bin/kill", "/usr/bin/kill"] {
1200            if Command::new(killer)
1201                .arg("-9")
1202                .arg(&target)
1203                .stdin(Stdio::null())
1204                .stdout(Stdio::null())
1205                .stderr(Stdio::null())
1206                .status()
1207                .is_ok()
1208            {
1209                return;
1210            }
1211        }
1212    }
1213    #[cfg(not(unix))]
1214    {
1215        let _ = pid;
1216    }
1217}
1218
1219fn reap_bounded(child: &mut Child) {
1220    let deadline = Instant::now() + REAP_BOUND;
1221    while Instant::now() < deadline {
1222        match child.try_wait() {
1223            Ok(Some(_)) | Err(_) => return,
1224            Ok(None) => std::thread::sleep(Duration::from_millis(10)),
1225        }
1226    }
1227    tracing::warn!(
1228        target: "kian::hook",
1229        pid = child.id(),
1230        "sidecar child not reaped within the bounded grace"
1231    );
1232}
1233
1234/// §7.5's graceful stop: `bye`, half-close stdin, bounded grace, then
1235/// kill the whole group. EOF without the expected reply was already
1236/// handled as a crash during dispatch; this is the orderly path.
1237fn graceful_stop(session: &mut Session) {
1238    if let Some(mut stdin) = session.stdin.take() {
1239        let _ = write_line(&mut stdin, &encode_bye(), 64);
1240    }
1241    // The take above already half-closed stdin when there was one.
1242    let deadline = Instant::now() + STOP_GRACE;
1243    while Instant::now() < deadline {
1244        match session.child.try_wait() {
1245            Ok(Some(_)) => return,
1246            Ok(None) => std::thread::sleep(Duration::from_millis(20)),
1247            Err(_) => return,
1248        }
1249    }
1250    kill_session(session);
1251}
1252
1253fn boot_refusal(inner: &Arc<Inner>, failure: HandshakeFailure) -> Refusal {
1254    let required = inner.manifest.required();
1255    let refusal = |code, message| Refusal {
1256        code,
1257        message,
1258        required,
1259    };
1260    match failure {
1261        HandshakeFailure::DigestMismatch => refusal(
1262            RefusalCode::DigestMismatch,
1263            format!(
1264                "`{}`: argv[0] digest does not match the manifest sha256 at spawn",
1265                inner.name
1266            ),
1267        ),
1268        HandshakeFailure::Spawn(detail) => refusal(
1269            RefusalCode::SpawnFailed,
1270            format!("`{}`: {}", inner.name, detail),
1271        ),
1272        HandshakeFailure::Timeout => refusal(
1273            RefusalCode::SpawnFailed,
1274            format!(
1275                "`{}`: hello→ready exceeded startup_timeout_ms (rule 13)",
1276                inner.name
1277            ),
1278        ),
1279        HandshakeFailure::ReadyMismatch(detail) => refusal(
1280            RefusalCode::ReadyMismatch,
1281            format!("`{}`: {detail}", inner.name),
1282        ),
1283        HandshakeFailure::AbiMismatch => refusal(
1284            RefusalCode::AbiMismatch,
1285            format!(
1286                "`{}`: ready restates a different abi than the manifest",
1287                inner.name
1288            ),
1289        ),
1290        HandshakeFailure::Crashed(detail) => refusal(
1291            RefusalCode::SpawnFailed,
1292            format!("`{}`: {detail}", inner.name),
1293        ),
1294    }
1295}
1296
1297/// §10.6's `hook-refuse` audit line.
1298fn audit_refuse(refusal: &Refusal) {
1299    tracing::info!(
1300        target: "kian::hook",
1301        code = refusal.code.as_str(),
1302        message = %refusal.message,
1303        required = match refusal.required {
1304            Required::True => "true",
1305            Required::False => "false",
1306            Required::Unknown => "unknown",
1307        },
1308        "hook-refuse"
1309    );
1310}
1311
1312/// Serializes a payload view for the wire (§7.2's `payload` is the
1313/// §3.2 view; the in-process `frame` identity is skipped by serde and
1314/// rides the frame envelope instead).
1315fn payload_value(payload: &HookPayload) -> serde_json::Value {
1316    use HookPayload as P;
1317    let result = match payload {
1318        P::AdmitDraft(v) => serde_json::to_value(v),
1319        P::AdmitReceipt(v) => serde_json::to_value(v),
1320        P::TurnRequest(v) => serde_json::to_value(v),
1321        P::TurnResponse(v) => serde_json::to_value(v),
1322        P::ToolPre(v) => serde_json::to_value(v),
1323        P::ToolPost(v) => serde_json::to_value(v),
1324        P::Recovery(v) => serde_json::to_value(v),
1325        P::Settle(v) => serde_json::to_value(v),
1326    };
1327    result.unwrap_or(serde_json::Value::Null)
1328}
1329
1330#[cfg(test)]
1331mod tests {
1332    use super::*;
1333
1334    fn limits() -> LimitsSection {
1335        LimitsSection {
1336            deadline_ms: 500,
1337            max_payload_kib: 256,
1338            restarts_per_window: 3,
1339            restart_window_ms: 60_000,
1340            max_settle_vetoes: 0,
1341            max_stderr_line_kib: 8,
1342            stderr_rate_kib_per_min: 1024,
1343        }
1344    }
1345
1346    #[test]
1347    fn window_trips_at_the_threshold_and_tags_the_reason() {
1348        let counters = Counters::default();
1349        let limits = limits();
1350        for _ in 0..2 {
1351            assert!(
1352                counters
1353                    .record_failure(FailureKind::Crash, &limits)
1354                    .is_none()
1355            );
1356        }
1357        let reason = counters
1358            .record_failure(FailureKind::Deadline, &limits)
1359            .expect("third failure trips the window");
1360        assert_eq!(
1361            reason,
1362            QuarantineReason::RestartsExhausted {
1363                failures: 3,
1364                window_ms: 60_000
1365            }
1366        );
1367        // A success clears the window — the failures are consecutive.
1368        counters.record_success();
1369        for _ in 0..2 {
1370            assert!(
1371                counters
1372                    .record_failure(FailureKind::Crash, &limits)
1373                    .is_none()
1374            );
1375        }
1376    }
1377
1378    #[test]
1379    fn stderr_only_window_names_stderr_overflow() {
1380        let counters = Counters::default();
1381        let limits = limits();
1382        for _ in 0..2 {
1383            assert!(
1384                counters
1385                    .record_failure(FailureKind::StderrRate, &limits)
1386                    .is_none()
1387            );
1388        }
1389        let reason = counters
1390            .record_failure(FailureKind::StderrRate, &limits)
1391            .expect("stderr-only window trips");
1392        assert!(matches!(
1393            reason,
1394            QuarantineReason::StderrRate { failures: 3, .. }
1395        ));
1396        // A mixed window names restarts_exhausted, not stderr.
1397        let counters = Counters::default();
1398        counters.record_failure(FailureKind::StderrRate, &limits);
1399        for _ in 0..2 {
1400            counters.record_failure(FailureKind::Crash, &limits);
1401        }
1402        // (3 total with at least one crash entry)
1403    }
1404
1405    #[test]
1406    fn restarts_are_counted_not_thresholded() {
1407        let counters = Counters::default();
1408        assert_eq!(counters.record_restart(), 1);
1409        assert_eq!(counters.record_restart(), 2);
1410        assert_eq!(counters.restarts(), 2);
1411        assert_eq!(counters.window_len(), 0, "restarts never touch the window");
1412    }
1413}