kian_plugin/hooks/session.rs
1//! Session consistency (PLUGIN-SPEC §9): the same-process guard, the
2//! session-lifetime quarantine, and the two audit lines.
3//!
4//! What the guard is and is not (§9.1, stated honestly): the recorded
5//! digest lives in one **audit line**, not in the store — no table, no
6//! payload, no read API — so it is **not** a durable baseline. The
7//! guard compares only **within one process lifetime**: a cross-process
8//! restart re-resolves from the current config and v1 cannot detect
9//! that the config changed (§16.2 owns that gap; only durable pinning
10//! closes it). Inside one process the check fires only if resolution
11//! stops being a pure function of (config snapshot, durable binding) —
12//! a future reload path, or a scope read from mutable state — which is
13//! exactly the invariant it exists to guard, fail-closed.
14//!
15//! The runtime here is installed **once at boot** by the assembly
16//! ([`HookBus::install_sidecars`]) and never reloaded; the config
17//! snapshot is therefore fixed for the process lifetime (§13.1). With
18//! no runtime installed (the `sidecars:` section absent) every method
19//! is a no-op and dispatch is byte-identical to a build without the
20//! feature (§13.3).
21
22use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
23use std::sync::{Arc, Mutex, RwLock};
24
25use kian_core::model::SessionId;
26
27use super::digest;
28use super::resolve::{self, Resolution, SidecarConfig};
29use super::sidecar::manifest::Manifest;
30use super::views::FrameInfo;
31
32/// The per-session resolved set, memoized for the process lifetime:
33/// the digest, the member names, each member's per-plugin segment
34/// digest (the "changed" half of the mismatch line), and each member's
35/// effective settle-veto budget (§6.1 — the manifest limit after worker
36/// `limits:` narrowing, the input to the §4.6 decision).
37pub(crate) struct ResolvedSet {
38 pub digest: String,
39 pub names: BTreeSet<String>,
40 per_plugin: BTreeMap<String, String>,
41 settle_limits: BTreeMap<String, u64>,
42}
43
44impl ResolvedSet {
45 fn from(resolution: &Resolution) -> Self {
46 Self {
47 digest: digest::set_digest(&resolution.effective),
48 names: resolution
49 .effective
50 .iter()
51 .map(|p| p.name.clone())
52 .collect(),
53 per_plugin: resolution
54 .effective
55 .iter()
56 .map(|p| (p.name.clone(), digest::set_digest(std::slice::from_ref(p))))
57 .collect(),
58 settle_limits: resolution
59 .effective
60 .iter()
61 .map(|p| (p.name.clone(), p.limits.max_settle_vetoes))
62 .collect(),
63 }
64 }
65}
66
67/// The boot snapshot the guard recomputes against: the validated
68/// `sidecars:` config plus the successfully mounted manifests (a
69/// refused optional instance is absent, §6.2 — its refusal audit line
70/// is the record).
71pub struct SidecarRuntime {
72 /// The config snapshot. Behind a lock because the guard's whole
73 /// premise (§9.2 step 4) is that a **future reload path** could
74 /// break resolution's purity — production writes it exactly once,
75 /// at boot, and never again; only the in-crate mismatch tests use
76 /// [`SidecarRuntime::reconfigure`] to simulate that break.
77 cfg: RwLock<SidecarConfig>,
78 manifests: BTreeMap<String, Manifest>,
79 /// The declared instance names — the dispatch-time sidecar filter.
80 names: BTreeSet<String>,
81 /// Sessions this process has opened (session → recorded digest).
82 opened: Mutex<HashMap<SessionId, String>>,
83 /// Memoized per-session resolved sets (lazy, §8.4).
84 sets: Mutex<HashMap<SessionId, Arc<ResolvedSet>>>,
85 /// Session-lifetime quarantine (§9.3): that session, in this
86 /// process, for the rest of its drain lifetime.
87 quarantined: Mutex<HashSet<SessionId>>,
88}
89
90impl SidecarRuntime {
91 pub(crate) fn new(cfg: SidecarConfig, manifests: BTreeMap<String, Manifest>) -> Self {
92 let names = cfg.plugins.keys().cloned().collect();
93 Self {
94 cfg: RwLock::new(cfg),
95 manifests,
96 names,
97 opened: Mutex::new(HashMap::new()),
98 sets: Mutex::new(HashMap::new()),
99 quarantined: Mutex::new(HashSet::new()),
100 }
101 }
102
103 /// The reload path v1 does not have (§13.1: no live reload). Used
104 /// only by the in-crate mismatch tests to simulate §9.2 step 4's
105 /// premise — resolution stopped being a pure function of the
106 /// process-boot snapshot — and prove the guard fires. The declared
107 /// instance names stay fixed (the registry is not re-read; a reload
108 /// that added an instance would need handler registration too).
109 /// Production never calls it: `dead_code` is allowed because the
110 /// lib build (without tests) has no caller by design.
111 #[allow(dead_code)]
112 pub(crate) fn reconfigure(&self, cfg: SidecarConfig) {
113 *self
114 .cfg
115 .write()
116 .expect("kian-plugin: sidecar config lock poisoned") = cfg;
117 }
118
119 /// Whether a registered handler's plugin name is a declared
120 /// sidecar instance — the dispatch-time tier filter (tier-0
121 /// handlers are never affected by a mismatch, §9.2 step 6).
122 pub(crate) fn is_sidecar(&self, plugin: &str) -> bool {
123 self.names.contains(plugin)
124 }
125
126 /// Whether the session is under §9.3 quarantine (sidecar hooks of
127 /// that session take their class defaults; tier-0 unaffected).
128 pub(crate) fn is_quarantined(&self, session: &SessionId) -> bool {
129 self.quarantined
130 .lock()
131 .expect("kian-plugin: sidecar runtime lock poisoned")
132 .contains(session)
133 }
134
135 /// The session's resolved set, resolving lazily on first sight
136 /// (§8.4) and recording the §9.2 step-1 audit line then — a
137 /// session whose first bus contact is a dispatch (not a drain
138 /// begin) still opens honestly.
139 fn set_for(&self, frame: &FrameInfo) -> Arc<ResolvedSet> {
140 if let Some(set) = self
141 .sets
142 .lock()
143 .expect("kian-plugin: sidecar runtime lock poisoned")
144 .get(&frame.session)
145 {
146 return Arc::clone(set);
147 }
148 let resolution = self.resolve_for(frame);
149 let set = Arc::new(ResolvedSet::from(&resolution));
150 self.record_open(frame, &set, &resolution);
151 self.sets
152 .lock()
153 .expect("kian-plugin: sidecar runtime lock poisoned")
154 .insert(frame.session, Arc::clone(&set));
155 set
156 }
157
158 /// The dispatch-time session state: quarantined (sidecars take
159 /// their class defaults, §9.3) or the resolved member set (a name
160 /// outside it is skipped — the drop was audited at resolution).
161 pub(crate) fn state_for(&self, frame: Option<&FrameInfo>) -> SessionState {
162 let Some(frame) = frame else {
163 // No frame identity → no session to key resolution on; the
164 // contract forbids implicit identity (R11), so sidecar
165 // subscribers cannot participate in this dispatch. Their
166 // absence is the honest outcome (an unattributed hook
167 // consultation is not one).
168 return SessionState::NoIdentity;
169 };
170 if self.is_quarantined(&frame.session) {
171 return SessionState::Quarantined;
172 }
173 SessionState::Set(self.set_for(frame))
174 }
175
176 fn resolve_for(&self, frame: &FrameInfo) -> Resolution {
177 let binding = if frame.worker.is_empty() {
178 None
179 } else {
180 Some(frame.worker.as_str())
181 };
182 resolve::resolve(
183 &self
184 .cfg
185 .read()
186 .expect("kian-plugin: sidecar config lock poisoned"),
187 &self.manifests,
188 binding,
189 )
190 }
191
192 /// §9.2 step 1: record + the `hook-set` audit line, and §8.2's one
193 /// drop line when the worker layer narrowed names away.
194 fn record_open(&self, frame: &FrameInfo, set: &ResolvedSet, resolution: &Resolution) {
195 {
196 let mut opened = self
197 .opened
198 .lock()
199 .expect("kian-plugin: sidecar runtime lock poisoned");
200 if opened.contains_key(&frame.session) {
201 return;
202 }
203 opened.insert(frame.session, set.digest.clone());
204 }
205 let names: Vec<&str> = set.names.iter().map(|n| n.as_str()).collect();
206 tracing::info!(
207 target: "kian::hook",
208 session = %frame.session.0,
209 digest = %set.digest,
210 plugins = set.names.len(),
211 names = names.join(","),
212 "hook-set"
213 );
214 if !resolution.dropped.is_empty() {
215 // §8.2: a narrowed-away name is simply absent from this
216 // worker's set — one audit line, never an error.
217 tracing::info!(
218 target: "kian::hook",
219 session = %frame.session.0,
220 worker = %frame.worker,
221 dropped = resolution.dropped.join(","),
222 "hook-set-drop"
223 );
224 }
225 }
226
227 /// §9.2 steps 2–4: recompute the digest from the current config
228 /// snapshot and the durable binding, compare with what this
229 /// process recorded, and quarantine the session's sidecar hooks on
230 /// a mismatch (one `hook-set-mismatch` line naming the diff). The
231 /// caller is a drain/claim boundary that knows the session's
232 /// identity; nothing else participates (no harness, no profile,
233 /// §16.18).
234 pub(crate) fn drain_begin(&self, frame: &FrameInfo) {
235 // First sight doubles as step 1 (a drain is how most sessions
236 // first meet the bus).
237 let recorded = self.set_for(frame);
238 if self.is_quarantined(&frame.session) {
239 // §9.3: one mismatch line per session-lifetime break; the
240 // downgrade is already in force.
241 return;
242 }
243 let resolution = self.resolve_for(frame);
244 let current = digest::set_digest(&resolution.effective);
245 if current == recorded.digest {
246 return;
247 }
248 // The diff the audit line names: added/removed by name,
249 // changed by per-plugin segment digest.
250 let current_names: BTreeSet<String> = resolution
251 .effective
252 .iter()
253 .map(|p| p.name.clone())
254 .collect();
255 let added: Vec<&str> = current_names
256 .difference(&recorded.names)
257 .map(|n| n.as_str())
258 .collect();
259 let removed: Vec<&str> = recorded
260 .names
261 .difference(¤t_names)
262 .map(|n| n.as_str())
263 .collect();
264 let current_per_plugin: BTreeMap<String, String> = resolution
265 .effective
266 .iter()
267 .map(|p| (p.name.clone(), digest::set_digest(std::slice::from_ref(p))))
268 .collect();
269 let changed: Vec<&str> = recorded
270 .per_plugin
271 .iter()
272 .filter_map(|(name, token)| {
273 current_per_plugin
274 .get(name)
275 .is_some_and(|new_token| new_token != token)
276 .then_some(name.as_str())
277 })
278 .collect();
279 self.quarantined
280 .lock()
281 .expect("kian-plugin: sidecar runtime lock poisoned")
282 .insert(frame.session);
283 tracing::warn!(
284 target: "kian::hook",
285 session = %frame.session.0,
286 recorded = %recorded.digest,
287 current = %current,
288 added = added.join(","),
289 removed = removed.join(","),
290 changed = changed.join(","),
291 "hook-set-mismatch — session sidecar hooks quarantined for this drain lifetime (§9.3)"
292 );
293 // The stale memo is the mismatch's own cause; drop it so the
294 // quarantine flag is the single source of the downgrade.
295 self.sets
296 .lock()
297 .expect("kian-plugin: sidecar runtime lock poisoned")
298 .remove(&frame.session);
299 }
300
301 /// The digest this process recorded for `session` (§9.2's audit
302 /// record; `None` before the first open or without a runtime).
303 pub(crate) fn recorded_digest(&self, session: &SessionId) -> Option<String> {
304 self.opened
305 .lock()
306 .expect("kian-plugin: sidecar runtime lock poisoned")
307 .get(session)
308 .cloned()
309 }
310
311 /// The effective `max_settle_vetoes` for `plugin` in the session's
312 /// resolved set (§6.1/§4.6): the manifest limit after worker
313 /// `limits:` narrowing. A plugin outside the session's sidecar set
314 /// (a tier-0 handler, or a name this session's scope dropped) has
315 /// no manifest and must not invent one (K8) — the tier-0 default.
316 pub(crate) fn settle_veto_limit(&self, frame: Option<&FrameInfo>, plugin: &str) -> u64 {
317 match self.state_for(frame) {
318 SessionState::Set(set) => set
319 .settle_limits
320 .get(plugin)
321 .copied()
322 .unwrap_or(super::bus::DEFAULT_MAX_SETTLE_VETOS),
323 // No identity or quarantine: the tier-0 default. A
324 // quarantined sidecar is unreachable anyway (its denial is
325 // the class default), but the budget check still needs a
326 // bound — the manifest limit stays the honest one.
327 SessionState::NoIdentity | SessionState::Quarantined => {
328 super::bus::DEFAULT_MAX_SETTLE_VETOS
329 }
330 }
331 }
332}
333
334/// The dispatch-time session state (see [`SidecarRuntime::state_for`]).
335pub(crate) enum SessionState {
336 /// No frame identity: sidecar subscribers cannot participate (R11).
337 NoIdentity,
338 /// §9.3: sidecar hooks of this session take their class defaults.
339 Quarantined,
340 /// The session's resolved member set.
341 Set(Arc<ResolvedSet>),
342}
343
344/// The §9 guard surface a drain boundary calls: implemented by
345/// [`HookBus`](super::bus::HookBus) and injected where the loop drivers
346/// know the session's identity. This is **not** an eighth interception
347/// port (§4's seven are frozen); it is the consistency guard's own
348/// seam, called at drain/claim boundaries, never mid-turn.
349pub trait SessionSetGuard: Send + Sync {
350 /// §9.2 steps 1–4 for one drain begin: record at first sight,
351 /// recompute and compare after. (The method name avoids the
352 /// `drain_` prefix the superagent iron-rule grep forbids in bundle
353 /// sources.)
354 fn session_begin(&self, frame: FrameInfo);
355}
356
357/// The install-once holder the bus carries. `RwLock<Option<..>>`
358/// because the bus is constructed before the assembly mounts sidecars
359/// (which §13.1 orders after the inbox rebuild); production writes
360/// exactly once, at boot, and the §9.2 guard is honest that a second
361/// write is the purity break it exists to catch.
362pub(crate) type SharedRuntime = RwLock<Option<Arc<SidecarRuntime>>>;
363
364impl SessionSetGuard for super::bus::HookBus {
365 fn session_begin(&self, frame: FrameInfo) {
366 self.session_begin(frame)
367 }
368}
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373 use crate::hooks::resolve::validate;
374
375 fn manifest(name: &str) -> Manifest {
376 let text = format!(
377 "[plugin]\nname = \"{name}\"\nversion = \"0.1.0\"\nabi = 1\n\
378 [process]\nargv = [\"/bin/cat\"]\nsha256 = \"{}\"\n\
379 [grants]\nhooks = [\"tool/pre\"]\ncapabilities = [\"observe:tool\"]\n\
380 [limits]\ndeadline_ms = 500\n",
381 "a".repeat(64)
382 );
383 let ctx = crate::hooks::sidecar::ValidationCtx {
384 instance_key: name,
385 ..Default::default()
386 };
387 crate::hooks::sidecar::parse_manifest(&text, &ctx).expect("fixture manifest parses")
388 }
389
390 fn cfg(server: &[&str]) -> SidecarConfig {
391 serde_json::from_value(serde_json::json!({
392 "plugins": {"gate": {"manifest": "/etc/kian/plugins/gate.toml"}},
393 "scopes": {"server": server}
394 }))
395 .unwrap()
396 }
397
398 fn session(s: &str) -> SessionId {
399 // SessionId is Deserialize over its uuid string form, so tests
400 // pin exact uuids without a direct uuid dependency edge (only
401 // sha2 may be added this round, K10).
402 serde_json::from_str(&format!("\"{s}\"")).expect("valid uuid literal")
403 }
404
405 fn frame(worker: &str) -> FrameInfo {
406 FrameInfo {
407 session: session("0f9c2a11-3b4d-4e5f-8a6b-7c8d9e0f1a2b"),
408 worker: worker.to_string(),
409 seq: 0,
410 epoch: None,
411 }
412 }
413
414 fn runtime() -> SidecarRuntime {
415 let mut manifests = BTreeMap::new();
416 manifests.insert("gate".to_string(), manifest("gate"));
417 SidecarRuntime::new(cfg(&["gate"]), manifests)
418 }
419
420 #[test]
421 fn first_drain_records_the_digest_later_drains_recompute() {
422 let rt = runtime();
423 let frame = frame("");
424 rt.drain_begin(&frame);
425 let recorded = rt.recorded_digest(&frame.session).expect("recorded");
426 assert!(recorded.starts_with("sha256:"), "the §8.5 shape");
427 assert!(!rt.is_quarantined(&frame.session));
428 // §9.2 step 2: a recompute over the same immutable snapshot is
429 // equal — the guard stays silent, the session proceeds.
430 rt.drain_begin(&frame);
431 assert_eq!(
432 rt.recorded_digest(&frame.session).as_deref(),
433 Some(recorded.as_str())
434 );
435 assert!(!rt.is_quarantined(&frame.session));
436 }
437
438 #[test]
439 fn mismatch_quarantines_the_session_not_the_process() {
440 let rt = runtime();
441 let frame = frame("");
442 rt.drain_begin(&frame);
443 let recorded = rt.recorded_digest(&frame.session).expect("recorded");
444
445 // §9.2 step 4's premise: resolution stops being a pure function
446 // of the boot snapshot (the reload path v1 does not have —
447 // `reconfigure` simulates exactly that break).
448 rt.reconfigure(cfg(&[]));
449
450 rt.drain_begin(&frame);
451 assert!(rt.is_quarantined(&frame.session));
452 // The recorded digest is the operator's record of what was in
453 // force — the mismatch line's `recorded=` field.
454 assert_eq!(
455 rt.recorded_digest(&frame.session).as_deref(),
456 Some(recorded.as_str())
457 );
458 // Other sessions are unaffected (§9.3: not the process
459 // quarantine — no counter shared, nobody else downgraded).
460 let other = FrameInfo {
461 session: session("11111111-2222-3333-4444-555555555555"),
462 worker: String::new(),
463 seq: 0,
464 epoch: None,
465 };
466 rt.drain_begin(&other);
467 assert!(!rt.is_quarantined(&other.session));
468 // A repeat drain begin does not re-audit the same break.
469 rt.drain_begin(&frame);
470 assert!(rt.is_quarantined(&frame.session));
471 }
472
473 #[test]
474 fn lazy_resolution_uses_the_durable_binding() {
475 let mut cfg = cfg(&["gate"]);
476 cfg.scopes.worker.insert(
477 "node-zulu".to_string(),
478 super::super::resolve::WorkerScope {
479 use_: Some(vec![]),
480 limits: BTreeMap::new(),
481 },
482 );
483 let mut manifests = BTreeMap::new();
484 manifests.insert("gate".to_string(), manifest("gate"));
485 let rt = SidecarRuntime::new(cfg, manifests);
486
487 let zulu = FrameInfo {
488 session: session("0f9c2a11-3b4d-4e5f-8a6b-7c8d9e0f1a2b"),
489 worker: "node-zulu".to_string(),
490 seq: 0,
491 epoch: None,
492 };
493 let yankee = FrameInfo {
494 session: session("99999999-8888-7777-6666-555555555555"),
495 worker: "node-yankee".to_string(),
496 seq: 0,
497 epoch: None,
498 };
499 rt.drain_begin(&zulu);
500 rt.drain_begin(&yankee);
501 let zulu_digest = rt.recorded_digest(&zulu.session).unwrap();
502 let yankee_digest = rt.recorded_digest(&yankee.session).unwrap();
503 assert_ne!(
504 zulu_digest, yankee_digest,
505 "the empty-use worker resolves a different (empty) set than the server scope"
506 );
507 }
508
509 #[test]
510 fn boot_config_passes_the_full_validation() {
511 let mut cfg = cfg(&["gate"]);
512 cfg.scopes.worker.insert(
513 "node-zulu".to_string(),
514 super::super::resolve::WorkerScope {
515 use_: Some(vec!["gate".to_string()]),
516 limits: BTreeMap::new(),
517 },
518 );
519 let mut manifests = BTreeMap::new();
520 manifests.insert("gate".to_string(), manifest("gate"));
521 assert!(validate(&cfg, &manifests).is_ok());
522 }
523}