use std::collections::VecDeque;
use std::io::Read;
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use futures::channel::mpsc::Sender;
use futures::channel::{mpsc, oneshot};
use futures::{FutureExt, StreamExt};
use super::super::failure::Cause;
use super::super::registry::{HookFn, HookPayload, HookReply, ReplyErrCode};
use super::super::wire::sha256_hex;
use super::frame::{
DecodeError, Hello, HookFrame, ReplyFrame, decode_ready, decode_reply, encode_bye,
};
use super::line::{BoundedLineReader, LineError, write_line};
use super::manifest::{LimitsSection, Manifest, Refusal, RefusalCode, Required};
const STOP_GRACE: Duration = Duration::from_millis(2_000);
const REAP_BOUND: Duration = Duration::from_millis(2_000);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FailureKind {
Deadline,
Crash,
ReplyDefect,
StderrRate,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum QuarantineReason {
RestartsExhausted { failures: usize, window_ms: u64 },
StderrRate { failures: usize, window_ms: u64 },
ProtocolViolation { detail: String },
FrameOverflow { direction: &'static str },
DigestMismatch,
}
#[derive(Debug, Default)]
pub struct Counters {
failures: Mutex<VecDeque<(Instant, FailureKind)>>,
restarts: AtomicU64,
}
impl Counters {
pub fn record_failure(
&self,
kind: FailureKind,
limits: &LimitsSection,
) -> Option<QuarantineReason> {
let mut failures = self
.failures
.lock()
.expect("kian-plugin: sidecar counters lock poisoned");
failures.push_back((Instant::now(), kind));
let window = Duration::from_millis(limits.restart_window_ms);
while failures
.front()
.is_some_and(|(at, _)| at.elapsed() > window)
{
failures.pop_front();
}
if failures.len() as u64 >= limits.restarts_per_window {
let only_stderr = failures.iter().all(|(_, k)| *k == FailureKind::StderrRate);
let count = failures.len();
return Some(if only_stderr {
QuarantineReason::StderrRate {
failures: count,
window_ms: limits.restart_window_ms,
}
} else {
QuarantineReason::RestartsExhausted {
failures: count,
window_ms: limits.restart_window_ms,
}
});
}
None
}
pub fn record_success(&self) {
self.failures
.lock()
.expect("kian-plugin: sidecar counters lock poisoned")
.clear();
}
pub fn record_restart(&self) -> u64 {
self.restarts.fetch_add(1, Ordering::Relaxed) + 1
}
pub fn restarts(&self) -> u64 {
self.restarts.load(Ordering::Relaxed)
}
pub fn window_len(&self) -> usize {
self.failures
.lock()
.expect("kian-plugin: sidecar counters lock poisoned")
.len()
}
}
enum Job {
Dispatch {
frame: HookFrame,
reply: oneshot::Sender<ReplyOutcome>,
},
Stop {
done: oneshot::Sender<()>,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReplyOutcome {
Reply(HookReply),
AsIfAbsent { detail: String },
Busy,
Unreachable { cause: Cause, detail: String },
}
struct Inner {
name: String,
manifest: Manifest,
canonical_path: String,
tx: Mutex<Sender<Job>>,
next_dispatch_id: AtomicU64,
counters: Counters,
quarantine: Mutex<Option<QuarantineReason>>,
in_flight: AtomicBool,
}
struct InFlightGuard<'a>(&'a AtomicBool);
impl Drop for InFlightGuard<'_> {
fn drop(&mut self) {
self.0.store(false, Ordering::SeqCst);
}
}
#[derive(Clone)]
pub struct SidecarRunner {
inner: Arc<Inner>,
}
impl std::fmt::Debug for SidecarRunner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SidecarRunner")
.field("name", &self.inner.name)
.field("quarantined", &self.quarantined())
.finish_non_exhaustive()
}
}
#[derive(Clone)]
struct WatchdogHandle {
answered: Arc<AtomicBool>,
deadline_fired: Arc<Mutex<bool>>,
pid: Arc<AtomicU64>,
}
impl WatchdogHandle {
fn arm(&self, timeout: Duration) {
let handle = self.clone();
std::thread::spawn(move || {
std::thread::sleep(timeout);
if !handle.answered.load(Ordering::SeqCst) {
*handle.deadline_fired.lock().unwrap() = true;
kill_group(handle.pid.load(Ordering::SeqCst) as u32);
}
});
}
fn mark_answered(&self) -> bool {
self.answered.swap(true, Ordering::SeqCst)
}
}
struct Session {
child: Child,
stdin: Option<ChildStdin>,
stdout: BoundedLineReader<ChildStdout>,
pid: u32,
alive: bool,
}
enum HandshakeFailure {
DigestMismatch,
Spawn(String),
Timeout,
ReadyMismatch(String),
AbiMismatch,
Crashed(String),
}
impl SidecarRunner {
pub fn start(manifest: Manifest, canonical_path: &std::path::Path) -> Result<Self, Refusal> {
let canonical =
std::fs::canonicalize(canonical_path).unwrap_or_else(|_| canonical_path.to_path_buf());
let name = manifest.plugin.name.clone();
let (tx, rx) = mpsc::channel(1);
let inner = Arc::new(Inner {
name: name.clone(),
manifest,
canonical_path: canonical.display().to_string(),
tx: Mutex::new(tx),
next_dispatch_id: AtomicU64::new(0),
counters: Counters::default(),
quarantine: Mutex::new(None),
in_flight: AtomicBool::new(false),
});
let (handshake_tx, handshake_rx) = std::sync::mpsc::channel::<Result<(), Refusal>>();
let thread_inner = Arc::clone(&inner);
let spawn_result = std::thread::Builder::new()
.name(format!("kian-sidecar-{name}"))
.spawn(move || io_thread(thread_inner, rx, handshake_tx));
if spawn_result.is_err() {
return Err(Refusal {
code: RefusalCode::SpawnFailed,
message: format!("could not spawn the io thread for `{name}`"),
required: inner.manifest.required(),
});
}
let slack = Duration::from_millis(2_000);
let bound = Duration::from_millis(inner.manifest.process.startup_timeout_ms) + slack;
match handshake_rx.recv_timeout(bound) {
Ok(Ok(())) => Ok(Self { inner }),
Ok(Err(refusal)) => {
audit_refuse(&refusal);
Err(refusal)
}
Err(_) => Err(Refusal {
code: RefusalCode::SpawnFailed,
message: format!(
"`{name}`: hello→ready did not complete within startup_timeout_ms"
),
required: inner.manifest.required(),
}),
}
}
pub fn name(&self) -> &str {
&self.inner.name
}
pub fn counters(&self) -> &Counters {
&self.inner.counters
}
pub fn quarantined(&self) -> Option<QuarantineReason> {
self.inner
.quarantine
.lock()
.expect("kian-plugin: quarantine lock poisoned")
.clone()
}
pub async fn dispatch(&self, frame: HookFrame) -> ReplyOutcome {
if let Some(reason) = self.quarantined() {
return ReplyOutcome::Unreachable {
cause: Cause::Quarantine,
detail: format!("quarantined: {reason:?}"),
};
}
if self.inner.in_flight.swap(true, Ordering::SeqCst) {
return ReplyOutcome::Busy;
}
let _in_flight = InFlightGuard(&self.inner.in_flight);
let (reply_tx, reply_rx) = oneshot::channel();
let sent = self
.inner
.tx
.lock()
.expect("kian-plugin: sidecar job-slot lock poisoned")
.try_send(Job::Dispatch {
frame,
reply: reply_tx,
});
match sent {
Ok(()) => match reply_rx.await {
Ok(outcome) => outcome,
Err(_) => ReplyOutcome::Unreachable {
cause: Cause::Crash,
detail: "sidecar stopped".to_string(),
},
},
Err(_) => ReplyOutcome::Unreachable {
cause: Cause::Quarantine,
detail: "sidecar io thread exited (quarantined or stopped)".to_string(),
},
}
}
pub fn stop(&self) {
let (done_tx, done_rx) = oneshot::channel();
let sent = self
.inner
.tx
.lock()
.expect("kian-plugin: sidecar job-slot lock poisoned")
.try_send(Job::Stop { done: done_tx });
if sent.is_ok() {
let _ = futures::executor::block_on(done_rx);
}
}
fn next_dispatch_id(&self) -> String {
format!(
"sc-{}-{}",
self.inner.name,
self.inner.next_dispatch_id.fetch_add(1, Ordering::Relaxed)
)
}
pub fn hook_fns(self: &Arc<Self>) -> Vec<(super::super::registry::HandlerId, HookFn)> {
let mut out = Vec::new();
for hook in self.inner.manifest.grants.hooks.clone() {
let plugin: &'static str = Box::leak(self.inner.name.clone().into_boxed_str());
let runner = Arc::clone(self);
let hook_for_closure = hook.clone();
let deadline_ms = self.inner.manifest.limits.deadline_ms;
let handler = super::super::registry::HandlerId {
plugin,
hook,
grants: self.inner.manifest.grants.grants.clone(),
order: self.inner.manifest.plugin.order,
};
let f: HookFn = Arc::new(move |payload: &HookPayload| {
let runner = Arc::clone(&runner);
let frame_info = payload.frame().cloned();
let payload_value = payload_value(payload);
let dispatch_id = runner.next_dispatch_id();
let hook = hook_for_closure.clone();
async move {
let Some(frame_info) = frame_info else {
tracing::warn!(
target: "kian::hook",
hook = %hook,
plugin = plugin,
"sidecar dispatch without frame identity — skipped (R11: no implicit identity)"
);
return HookReply::Ack { note: None };
};
let hook_for_log = hook.clone();
let frame = match HookFrame::new(
hook,
&frame_info,
dispatch_id,
deadline_ms,
payload_value,
) {
Ok(frame) => frame,
Err(e) => {
tracing::error!(
target: "kian::hook",
hook = %hook_for_log,
plugin = plugin,
error = %e.message,
"sidecar frame rejected — dispatch skipped"
);
return HookReply::Ack { note: None };
}
};
match runner.dispatch(frame).await {
ReplyOutcome::Reply(reply) => reply,
ReplyOutcome::AsIfAbsent { .. } => {
tracing::info!(
target: "kian::hook",
hook = %hook_for_log,
plugin = plugin,
outcome = "discarded",
"hook-discard"
);
HookReply::Ack { note: None }
}
ReplyOutcome::Busy => {
tracing::info!(
target: "kian::hook",
hook = %hook_for_log,
plugin = plugin,
busy = true,
"hook-default"
);
HookReply::Err {
code: ReplyErrCode::Crashed,
message: "busy: one dispatch in flight".to_string(),
}
}
ReplyOutcome::Unreachable { cause, detail } => HookReply::Err {
code: match cause {
Cause::Deadline => ReplyErrCode::Deadline,
_ => ReplyErrCode::Crashed,
},
message: format!("{detail} ({})", cause.as_str()),
},
}
}
.boxed()
});
out.push((handler, f));
}
out
}
}
fn io_thread(
inner: Arc<Inner>,
mut rx: mpsc::Receiver<Job>,
handshake: std::sync::mpsc::Sender<Result<(), Refusal>>,
) {
let mut session = match spawn_session(&inner, true) {
Ok(session) => {
let _ = handshake.send(Ok(()));
session
}
Err(failure) => {
let refusal = boot_refusal(&inner, failure);
let _ = handshake.send(Err(refusal.clone()));
audit_refuse(&refusal);
return;
}
};
loop {
if inner.quarantine_locked().is_some() {
return;
}
let job = match futures::executor::block_on(rx.next()) {
Some(job) => job,
None => {
graceful_stop(&mut session);
return;
}
};
match job {
Job::Stop { done } => {
graceful_stop(&mut session);
let _ = done.send(());
return;
}
Job::Dispatch { frame, reply } => {
let outcome = serve_dispatch(&inner, &mut session, frame);
let _ = reply.send(outcome);
if !session.alive && inner.quarantine_locked().is_none() {
session = match respawn_until_ready(&inner) {
Some(session) => session,
None => return, };
}
}
}
}
}
fn serve_dispatch(inner: &Arc<Inner>, session: &mut Session, frame: HookFrame) -> ReplyOutcome {
let max = inner.manifest.limits.max_frame_bytes();
let line = frame.encode();
let Some(stdin) = session.stdin.as_mut() else {
record_window_failure(inner, FailureKind::Crash);
kill_session(session);
return ReplyOutcome::Unreachable {
cause: Cause::Crash,
detail: "stdin already closed (stop in progress)".to_string(),
};
};
match write_line(stdin, &line, max) {
Err(LineError::Overflow { scanned, max }) => {
quarantine(
inner,
QuarantineReason::FrameOverflow {
direction: "outbound",
},
);
kill_session(session);
return ReplyOutcome::Unreachable {
cause: Cause::Crash,
detail: format!("frame_overflow: outbound line {scanned} > {max} bytes"),
};
}
Err(LineError::Io(e)) => {
if let Some(reason) = record_window_failure(inner, FailureKind::Crash) {
quarantine(inner, reason);
}
kill_session(session);
return ReplyOutcome::Unreachable {
cause: Cause::Crash,
detail: format!("stdin write failed: {e}"),
};
}
Ok(()) => {}
}
let watchdog = WatchdogHandle {
answered: Arc::new(AtomicBool::new(false)),
deadline_fired: Arc::new(Mutex::new(false)),
pid: Arc::new(AtomicU64::new(u64::from(session.pid))),
};
watchdog.arm(Duration::from_millis(inner.manifest.limits.deadline_ms));
match session.stdout.read_line(max) {
Err(LineError::Overflow { scanned, max }) => {
quarantine(
inner,
QuarantineReason::FrameOverflow {
direction: "inbound",
},
);
tracing::info!(
target: "kian::hook",
plugin = %inner.name,
direction = "inbound",
scanned = scanned,
max = max,
"hook-quarantine-overflow"
);
kill_session(session);
ReplyOutcome::Unreachable {
cause: Cause::Crash,
detail: format!("frame_overflow: inbound line {scanned} > {max} bytes"),
}
}
Err(LineError::Io(e)) => {
let deadline = *watchdog.deadline_fired.lock().unwrap();
kill_session(session);
let kind = if deadline {
FailureKind::Deadline
} else {
FailureKind::Crash
};
if let Some(reason) = record_window_failure(inner, kind) {
quarantine(inner, reason);
}
if deadline {
ReplyOutcome::Unreachable {
cause: Cause::Deadline,
detail: "deadline: child killed over the dispatch deadline".to_string(),
}
} else {
ReplyOutcome::Unreachable {
cause: Cause::Crash,
detail: format!("crash: child pipe closed ({e})"),
}
}
}
Ok(line) => {
watchdog.mark_answered();
match decode_reply(&line) {
Err(DecodeError::Malformed(detail)) => {
record_window_failure(inner, FailureKind::ReplyDefect);
ReplyOutcome::Reply(HookReply::Err {
code: ReplyErrCode::Malformed,
message: detail,
})
}
Ok((reply_id, reply_frame)) => {
let id_ok = reply_id.as_ref().map(|id| id == &frame.id).unwrap_or(true); if !id_ok {
quarantine(
inner,
QuarantineReason::ProtocolViolation {
detail: format!(
"reply id `{reply_id:?}` ≠ dispatch id `{}`",
frame.id
),
},
);
kill_session(session);
return ReplyOutcome::AsIfAbsent {
detail: "protocol_violation: reply for another dispatch id".to_string(),
};
}
match reply_frame {
ReplyFrame::Err { code, message }
if matches!(
code,
ReplyErrCode::Deadline
| ReplyErrCode::Malformed
| ReplyErrCode::Unauthorized
) =>
{
let kind = if code == ReplyErrCode::Deadline {
FailureKind::Deadline
} else {
FailureKind::ReplyDefect
};
if let Some(reason) = record_window_failure(inner, kind) {
quarantine(inner, reason);
kill_session(session);
}
ReplyOutcome::Reply(HookReply::Err { code, message })
}
other => {
inner.counters.record_success();
ReplyOutcome::Reply(frame_to_reply(other))
}
}
}
}
}
}
}
fn frame_to_reply(frame: ReplyFrame) -> HookReply {
match frame {
ReplyFrame::Ack { note } => HookReply::Ack { note },
ReplyFrame::FlowNext => HookReply::FlowNext,
ReplyFrame::FlowStop { reason } => HookReply::FlowStop { reason },
ReplyFrame::BailNone => HookReply::BailNone,
ReplyFrame::BailDeny { reason } => HookReply::BailDeny { reason },
ReplyFrame::Err { code, message } => HookReply::Err { code, message },
}
}
fn respawn_until_ready(inner: &Arc<Inner>) -> Option<Session> {
loop {
match spawn_session(inner, false) {
Ok(session) => {
let restarts = inner.counters.record_restart();
tracing::info!(
target: "kian::hook",
plugin = %inner.name,
restarts = restarts,
digest_ok = true,
"hook-respawn"
);
return Some(session);
}
Err(HandshakeFailure::DigestMismatch) => {
quarantine(inner, QuarantineReason::DigestMismatch);
return None;
}
Err(_) => {
if let Some(reason) = record_window_failure(inner, FailureKind::Crash) {
quarantine(inner, reason);
return None;
}
}
}
}
}
fn spawn_session(inner: &Arc<Inner>, first: bool) -> Result<Session, HandshakeFailure> {
let manifest = &inner.manifest;
match digest_of(&manifest.process.argv[0]) {
Some(digest) if digest == manifest.process.sha256 => {}
Some(_) => return Err(HandshakeFailure::DigestMismatch),
None => {
return Err(HandshakeFailure::Spawn(format!(
"argv[0] `{}` unreadable for digest verification",
manifest.process.argv[0]
)));
}
}
let mut command = Command::new(&manifest.process.argv[0]);
command
.args(&manifest.process.argv[1..])
.env_clear();
for name in &manifest.process.env_allow {
if let Ok(value) = std::env::var(name) {
command.env(name, value);
}
}
let _owned_cwd;
match &manifest.process.cwd {
Some(cwd) => {
command.current_dir(cwd);
}
None => {
let dir = std::env::temp_dir().join(format!(
"kian-sidecar-{}-{}",
manifest.plugin.name,
std::process::id()
));
if std::fs::create_dir_all(&dir).is_err() {
return Err(HandshakeFailure::Spawn(format!(
"could not create the runtime cwd `{}`",
dir.display()
)));
}
_owned_cwd = dir;
command.current_dir(&_owned_cwd);
}
}
command
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
let mut child = command
.spawn()
.map_err(|e| HandshakeFailure::Spawn(format!("spawn failed: {e}")))?;
let pid = child.id();
let mut stdin = child
.stdin
.take()
.ok_or_else(|| HandshakeFailure::Spawn("stdin pipe missing".to_string()))?;
let stdout = child
.stdout
.take()
.ok_or_else(|| HandshakeFailure::Spawn("stdout pipe missing".to_string()))?;
let stderr = child
.stderr
.take()
.ok_or_else(|| HandshakeFailure::Spawn("stderr pipe missing".to_string()))?;
let stderr_inner = Arc::clone(inner);
let _stderr_thread = std::thread::Builder::new()
.name(format!("kian-sidecar-{}-stderr", manifest.plugin.name))
.spawn(move || drain_stderr(stderr_inner, stderr));
let mut reader = BoundedLineReader::new(stdout);
let hello = Hello {
manifest: inner.canonical_path.clone(),
name: manifest.plugin.name.clone(),
version: manifest.plugin.version.clone(),
abi: manifest.plugin.abi,
hooks: manifest
.grants
.hooks
.iter()
.map(|h| h.to_string())
.collect(),
capabilities: manifest
.grants
.grants
.iter()
.map(|g| g.as_str().to_string())
.collect(),
deadline_default_ms: manifest.limits.deadline_ms,
max_frame_bytes: manifest.limits.max_frame_bytes(),
};
let max = manifest.limits.max_frame_bytes();
match write_line(&mut stdin, &hello.encode(), max) {
Err(LineError::Overflow { .. }) => {
kill_child(&mut child);
return Err(HandshakeFailure::ReadyMismatch(
"hello over the frame bound".to_string(),
));
}
Err(LineError::Io(e)) => {
kill_child(&mut child);
return Err(HandshakeFailure::Crashed(format!(
"hello write failed: {e}"
)));
}
Ok(()) => {}
}
let watchdog = WatchdogHandle {
answered: Arc::new(AtomicBool::new(false)),
deadline_fired: Arc::new(Mutex::new(false)),
pid: Arc::new(AtomicU64::new(u64::from(pid))),
};
watchdog.arm(Duration::from_millis(manifest.process.startup_timeout_ms));
let ready_line = match reader.read_line(max) {
Ok(line) => {
watchdog.mark_answered();
line
}
Err(LineError::Overflow { .. }) => {
kill_child(&mut child);
return Err(HandshakeFailure::ReadyMismatch(
"ready over the frame bound".to_string(),
));
}
Err(LineError::Io(e)) => {
let deadline = *watchdog.deadline_fired.lock().unwrap();
kill_child(&mut child);
return Err(if deadline {
HandshakeFailure::Timeout
} else {
HandshakeFailure::Crashed(format!("child closed stdout before ready ({e})"))
});
}
};
let ready = match decode_ready(&ready_line) {
Ok(ready) => ready,
Err(DecodeError::Malformed(detail)) => {
kill_child(&mut child);
return Err(HandshakeFailure::ReadyMismatch(detail));
}
};
if ready.abi != manifest.plugin.abi {
kill_child(&mut child);
return Err(HandshakeFailure::AbiMismatch);
}
if ready.manifest != inner.canonical_path
|| ready.name != manifest.plugin.name
|| ready.version != manifest.plugin.version
|| !set_equal(&ready.hooks, &hello.hooks)
|| !set_equal(&ready.capabilities, &hello.capabilities)
{
kill_child(&mut child);
return Err(HandshakeFailure::ReadyMismatch(format!(
"ready restates a different identity (manifest={}, name={}, version={}, hooks/capabilities sets differ)",
ready.manifest, ready.name, ready.version
)));
}
let _ = first; Ok(Session {
child,
stdin: Some(stdin),
stdout: reader,
pid,
alive: true,
})
}
fn drain_stderr(inner: Arc<Inner>, stderr: std::process::ChildStderr) {
let limits = inner.manifest.limits;
let line_max = (limits.max_stderr_line_kib as usize) * 1024;
let rate_max = (limits.stderr_rate_kib_per_min as usize) * 1024;
let mut reader = BoundedLineReader::new(stderr);
let mut last_drop: Option<Instant> = None;
let mut retained: VecDeque<(Instant, usize)> = VecDeque::new();
let mut retained_bytes = 0usize;
let mut last_rate_note: Option<Instant> = None;
loop {
match reader.read_line(line_max) {
Ok(line) => {
last_drop = None; let now = Instant::now();
retained.push_back((now, line.len()));
retained_bytes = retained_bytes.saturating_add(line.len());
while retained
.front()
.is_some_and(|(at, _)| now.duration_since(*at) > Duration::from_secs(60))
{
let (_, size) = retained.pop_front().unwrap();
retained_bytes = retained_bytes.saturating_sub(size);
}
if retained_bytes > rate_max
&& last_rate_note
.is_none_or(|at| now.duration_since(at) > Duration::from_secs(60))
{
last_rate_note = Some(now);
tracing::info!(
target: "kian::hook",
plugin = %inner.name,
kind = "stderr_rate",
"stderr rate bound exceeded — excess dropped"
);
if let Some(reason) = record_window_failure(&inner, FailureKind::StderrRate) {
quarantine(&inner, reason);
return;
}
}
}
Err(LineError::Overflow { scanned, max }) => {
tracing::info!(
target: "kian::hook",
plugin = %inner.name,
kind = "stderr_line",
scanned = scanned,
max = max,
"stderr line over bound — dropped"
);
let now = Instant::now();
if last_drop.is_none_or(|at| now.duration_since(at) >= Duration::from_secs(1)) {
last_drop = Some(now);
if let Some(reason) = record_window_failure(&inner, FailureKind::StderrRate) {
quarantine(&inner, reason);
return;
}
}
if !reader.discard_line() {
return;
}
}
Err(LineError::Io(_)) => return, }
}
}
fn set_equal(a: &[String], b: &[String]) -> bool {
let mut left: Vec<&String> = a.iter().collect();
let mut right: Vec<&String> = b.iter().collect();
left.sort();
right.sort();
left == right
}
fn digest_of(path: &str) -> Option<String> {
let mut file = std::fs::File::open(path).ok()?;
let mut buf = Vec::new();
file.read_to_end(&mut buf).ok()?;
Some(sha256_hex(&buf))
}
impl Inner {
fn quarantine_locked(&self) -> Option<QuarantineReason> {
self.quarantine
.lock()
.expect("kian-plugin: quarantine lock poisoned")
.clone()
}
}
fn quarantine(inner: &Arc<Inner>, reason: QuarantineReason) {
let mut slot = inner
.quarantine
.lock()
.expect("kian-plugin: quarantine lock poisoned");
if slot.is_some() {
return; }
let failures = inner.counters.window_len();
let window_ms = inner.manifest.limits.restart_window_ms;
tracing::info!(
target: "kian::hook",
plugin = %inner.name,
reason = %reason.as_audit_str(),
failures = failures,
window_ms = window_ms,
lifetime = "server-process",
"hook-quarantine"
);
*slot = Some(reason);
}
impl QuarantineReason {
pub fn as_audit_str(&self) -> String {
match self {
QuarantineReason::RestartsExhausted {
failures,
window_ms,
} => {
format!("restarts_exhausted(failures={failures}, window_ms={window_ms})")
}
QuarantineReason::StderrRate {
failures,
window_ms,
} => {
format!("stderr_overflow(failures={failures}, window_ms={window_ms})")
}
QuarantineReason::ProtocolViolation { detail } => {
format!("protocol_violation({detail})")
}
QuarantineReason::FrameOverflow { direction } => {
format!("frame_overflow({direction})")
}
QuarantineReason::DigestMismatch => "digest_mismatch(respawn)".to_string(),
}
}
}
fn record_window_failure(inner: &Arc<Inner>, kind: FailureKind) -> Option<QuarantineReason> {
inner.counters.record_failure(kind, &inner.manifest.limits)
}
fn kill_session(session: &mut Session) {
session.alive = false;
kill_group(session.pid);
let _ = session.child.kill();
reap_bounded(&mut session.child);
}
fn kill_child(child: &mut Child) {
let pid = child.id();
kill_group(pid);
let _ = child.kill();
reap_bounded(child);
}
fn kill_group(pid: u32) {
if pid == 0 {
return;
}
#[cfg(unix)]
{
let target = format!("-{pid}");
for killer in ["/bin/kill", "/usr/bin/kill"] {
if Command::new(killer)
.arg("-9")
.arg(&target)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.is_ok()
{
return;
}
}
}
#[cfg(not(unix))]
{
let _ = pid;
}
}
fn reap_bounded(child: &mut Child) {
let deadline = Instant::now() + REAP_BOUND;
while Instant::now() < deadline {
match child.try_wait() {
Ok(Some(_)) | Err(_) => return,
Ok(None) => std::thread::sleep(Duration::from_millis(10)),
}
}
tracing::warn!(
target: "kian::hook",
pid = child.id(),
"sidecar child not reaped within the bounded grace"
);
}
fn graceful_stop(session: &mut Session) {
if let Some(mut stdin) = session.stdin.take() {
let _ = write_line(&mut stdin, &encode_bye(), 64);
}
let deadline = Instant::now() + STOP_GRACE;
while Instant::now() < deadline {
match session.child.try_wait() {
Ok(Some(_)) => return,
Ok(None) => std::thread::sleep(Duration::from_millis(20)),
Err(_) => return,
}
}
kill_session(session);
}
fn boot_refusal(inner: &Arc<Inner>, failure: HandshakeFailure) -> Refusal {
let required = inner.manifest.required();
let refusal = |code, message| Refusal {
code,
message,
required,
};
match failure {
HandshakeFailure::DigestMismatch => refusal(
RefusalCode::DigestMismatch,
format!(
"`{}`: argv[0] digest does not match the manifest sha256 at spawn",
inner.name
),
),
HandshakeFailure::Spawn(detail) => refusal(
RefusalCode::SpawnFailed,
format!("`{}`: {}", inner.name, detail),
),
HandshakeFailure::Timeout => refusal(
RefusalCode::SpawnFailed,
format!(
"`{}`: hello→ready exceeded startup_timeout_ms (rule 13)",
inner.name
),
),
HandshakeFailure::ReadyMismatch(detail) => refusal(
RefusalCode::ReadyMismatch,
format!("`{}`: {detail}", inner.name),
),
HandshakeFailure::AbiMismatch => refusal(
RefusalCode::AbiMismatch,
format!(
"`{}`: ready restates a different abi than the manifest",
inner.name
),
),
HandshakeFailure::Crashed(detail) => refusal(
RefusalCode::SpawnFailed,
format!("`{}`: {detail}", inner.name),
),
}
}
fn audit_refuse(refusal: &Refusal) {
tracing::info!(
target: "kian::hook",
code = refusal.code.as_str(),
message = %refusal.message,
required = match refusal.required {
Required::True => "true",
Required::False => "false",
Required::Unknown => "unknown",
},
"hook-refuse"
);
}
fn payload_value(payload: &HookPayload) -> serde_json::Value {
use HookPayload as P;
let result = match payload {
P::AdmitDraft(v) => serde_json::to_value(v),
P::AdmitReceipt(v) => serde_json::to_value(v),
P::TurnRequest(v) => serde_json::to_value(v),
P::TurnResponse(v) => serde_json::to_value(v),
P::ToolPre(v) => serde_json::to_value(v),
P::ToolPost(v) => serde_json::to_value(v),
P::Recovery(v) => serde_json::to_value(v),
P::Settle(v) => serde_json::to_value(v),
};
result.unwrap_or(serde_json::Value::Null)
}
#[cfg(test)]
mod tests {
use super::*;
fn limits() -> LimitsSection {
LimitsSection {
deadline_ms: 500,
max_payload_kib: 256,
restarts_per_window: 3,
restart_window_ms: 60_000,
max_settle_vetoes: 0,
max_stderr_line_kib: 8,
stderr_rate_kib_per_min: 1024,
}
}
#[test]
fn window_trips_at_the_threshold_and_tags_the_reason() {
let counters = Counters::default();
let limits = limits();
for _ in 0..2 {
assert!(
counters
.record_failure(FailureKind::Crash, &limits)
.is_none()
);
}
let reason = counters
.record_failure(FailureKind::Deadline, &limits)
.expect("third failure trips the window");
assert_eq!(
reason,
QuarantineReason::RestartsExhausted {
failures: 3,
window_ms: 60_000
}
);
counters.record_success();
for _ in 0..2 {
assert!(
counters
.record_failure(FailureKind::Crash, &limits)
.is_none()
);
}
}
#[test]
fn stderr_only_window_names_stderr_overflow() {
let counters = Counters::default();
let limits = limits();
for _ in 0..2 {
assert!(
counters
.record_failure(FailureKind::StderrRate, &limits)
.is_none()
);
}
let reason = counters
.record_failure(FailureKind::StderrRate, &limits)
.expect("stderr-only window trips");
assert!(matches!(
reason,
QuarantineReason::StderrRate { failures: 3, .. }
));
let counters = Counters::default();
counters.record_failure(FailureKind::StderrRate, &limits);
for _ in 0..2 {
counters.record_failure(FailureKind::Crash, &limits);
}
}
#[test]
fn restarts_are_counted_not_thresholded() {
let counters = Counters::default();
assert_eq!(counters.record_restart(), 1);
assert_eq!(counters.record_restart(), 2);
assert_eq!(counters.restarts(), 2);
assert_eq!(counters.window_len(), 0, "restarts never touch the window");
}
}