1use 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
49const STOP_GRACE: Duration = Duration::from_millis(2_000);
51const REAP_BOUND: Duration = Duration::from_millis(2_000);
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum FailureKind {
64 Deadline,
66 Crash,
68 ReplyDefect,
71 StderrRate,
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum QuarantineReason {
79 RestartsExhausted { failures: usize, window_ms: u64 },
81 StderrRate { failures: usize, window_ms: u64 },
83 ProtocolViolation { detail: String },
85 FrameOverflow { direction: &'static str },
87 DigestMismatch,
90}
91
92#[derive(Debug, Default)]
95pub struct Counters {
96 failures: Mutex<VecDeque<(Instant, FailureKind)>>,
97 restarts: AtomicU64,
98}
99
100impl Counters {
101 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 pub fn record_success(&self) {
142 self.failures
143 .lock()
144 .expect("kian-plugin: sidecar counters lock poisoned")
145 .clear();
146 }
147
148 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
165enum Job {
170 Dispatch {
171 frame: HookFrame,
172 reply: oneshot::Sender<ReplyOutcome>,
173 },
174 Stop {
175 done: oneshot::Sender<()>,
176 },
177}
178
179#[derive(Debug, Clone, PartialEq, Eq)]
182pub enum ReplyOutcome {
183 Reply(HookReply),
186 AsIfAbsent { detail: String },
189 Busy,
191 Unreachable { cause: Cause, detail: String },
195}
196
197struct Inner {
202 name: String,
203 manifest: Manifest,
204 canonical_path: String,
205 tx: Mutex<Sender<Job>>,
210 next_dispatch_id: AtomicU64,
211 counters: Counters,
212 quarantine: Mutex<Option<QuarantineReason>>,
213 in_flight: AtomicBool,
218}
219
220struct 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#[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#[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 *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
280struct Session {
282 child: Child,
283 stdin: Option<ChildStdin>,
286 stdout: BoundedLineReader<ChildStdout>,
287 pid: u32,
288 alive: bool,
291}
292
293enum HandshakeFailure {
296 DigestMismatch,
297 Spawn(String),
298 Timeout,
299 ReadyMismatch(String),
300 AbiMismatch,
301 Crashed(String),
302}
303
304impl SidecarRunner {
305 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 pub fn name(&self) -> &str {
358 &self.inner.name
359 }
360
361 pub fn counters(&self) -> &Counters {
364 &self.inner.counters
365 }
366
367 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 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 Err(_) => ReplyOutcome::Unreachable {
416 cause: Cause::Quarantine,
417 detail: "sidecar io thread exited (quarantined or stopped)".to_string(),
418 },
419 }
420 }
421
422 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 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 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 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 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 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
553fn 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 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 session = match respawn_until_ready(&inner) {
601 Some(session) => session,
602 None => return, };
604 }
605 }
606 }
607 }
608}
609
610fn 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 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 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 FailureKind::Crash
691 };
692 if let Some(reason) = record_window_failure(inner, kind) {
693 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 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); if !id_ok {
724 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 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 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
786fn 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 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
818fn spawn_session(inner: &Arc<Inner>, first: bool) -> Result<Session, HandshakeFailure> {
823 let manifest = &inner.manifest;
824 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 .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 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 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 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 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 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; Ok(Session {
999 child,
1000 stdin: Some(stdin),
1001 stdout: reader,
1002 pid,
1003 alive: true,
1004 })
1005}
1006
1007fn 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; 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 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 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, }
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
1103impl 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
1116fn 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; }
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 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
1168fn 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
1188fn 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
1234fn 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 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
1297fn 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
1312fn 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 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 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 }
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}