Skip to main content

kian_plugin/hooks/
failure.rs

1//! Failure classification and class defaults (PLUGIN-SPEC §11.1, §5.2).
2//!
3//! Two failure classes, disjoint by construction:
4//!
5//! - **Unreachability** — the handler cannot answer (deadline, crash,
6//!   quarantine, busy, handshake incomplete, EOF without a reply, or a
7//!   self-declared `err:deadline`/`err:crashed`). Resolves to the
8//!   **grant-keyed class default**.
9//! - **Speech defect** — the handler answered wrongly (out-of-grant,
10//!   wrong-mode, unparseable, or an `err` whose code is not a
11//!   self-declared unreachability). The reply is **discarded as an
12//!   opinion**: the outcome is exactly the as-if-absent one, never the
13//!   class default.
14//!
15//! [`resolve_outcome`] is the *only* place a reply becomes a verdict
16//! (K6): the bus and both tiers test through it, so the escalation bug of
17//! §5.2 (a draft resolving a defect to the fail-closed default) cannot
18//! reappear in a second code path.
19
20use super::grants::{Grant, GrantSet, ReplyShape, veto_grant_for_class};
21use super::ids::HookId;
22use super::registry::{HookReply, ReplyErrCode};
23use super::views::Origin;
24
25/// Why a handler could not answer (§11.1's unreachability members).
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Cause {
28    Deadline,
29    Crash,
30    Quarantine,
31    Busy,
32    HandshakeIncomplete,
33    EofWithoutReply,
34}
35
36impl Cause {
37    pub fn as_str(self) -> &'static str {
38        match self {
39            Cause::Deadline => "deadline",
40            Cause::Crash => "crash",
41            Cause::Quarantine => "quarantine",
42            Cause::Busy => "busy",
43            Cause::HandshakeIncomplete => "handshake_incomplete",
44            Cause::EofWithoutReply => "eof_without_reply",
45        }
46    }
47}
48
49/// Which speech defect a discarded reply committed. The first five are
50/// the ABI's non-unreachability `err` codes (§7.2); `Unparseable` arises
51/// only at the wire (the tier-0 carrier is typed, so it cannot occur
52/// in-process); `OriginObserveOnly` classifies the one in-process defect
53/// the wire never sees — a stop answered at an observe-only admission
54/// origin (§3.4.3).
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum SpeechCode {
57    Unauthorized,
58    Malformed,
59    UnsupportedHook,
60    ProtocolViolation,
61    Unparseable,
62    OriginObserveOnly,
63}
64
65impl SpeechCode {
66    pub fn as_str(self) -> &'static str {
67        match self {
68            SpeechCode::Unauthorized => "unauthorized",
69            SpeechCode::Malformed => "malformed",
70            SpeechCode::UnsupportedHook => "unsupported_hook",
71            SpeechCode::ProtocolViolation => "protocol_violation",
72            SpeechCode::Unparseable => "unparseable",
73            SpeechCode::OriginObserveOnly => "origin_observe_only",
74        }
75    }
76}
77
78/// The two failure classes (§11.1).
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub enum FailureClass {
81    Unreachable(Cause),
82    Speech(SpeechCode),
83}
84
85/// The class default an unreachability resolves to — **a property of a
86/// `veto:*` grant, not of a hook id** (§11.1):
87///
88/// - `Deny` — `veto:tool` holder at `tool/pre`: fail closed.
89/// - `RefuseAdmission` — `veto:admit` holder at a channel-borne
90///   `admit/pre`: fail closed for every target.
91/// - `Abstain` — `veto:settle` holder at `settle/pre`: fail open; a
92///   wedged quality gate must not hold a session hostage.
93/// - `Lapse` — an observe-only subscriber anywhere: the observation is
94///   lost and nothing else happens.
95#[derive(Debug, Clone, PartialEq, Eq)]
96pub enum ClassDefault {
97    Deny { cause: Cause },
98    RefuseAdmission { cause: Cause },
99    Abstain,
100    Lapse,
101}
102
103/// What one subscriber's reply resolves to.
104#[derive(Debug, Clone, PartialEq, Eq)]
105pub enum Outcome {
106    /// An observation (ack / next / abstain), or a defect whose reply was
107    /// discarded: this subscriber contributes no verdict, exactly as if
108    /// absent (§5.2).
109    AsIfAbsent,
110    /// A valid veto reply — the subscriber holds the grant and answered
111    /// in the hook's mode.
112    Denied { reason: String },
113    /// Unreachability resolved to the grant-keyed default (§11.1).
114    Default(ClassDefault),
115    /// A speech defect: discarded, but recorded for the `hook-discard`
116    /// audit line (§10.6) — audited as a defection, never as a lapse.
117    Discarded {
118        code: SpeechCode,
119        grant: Option<Grant>,
120    },
121}
122
123/// The one place a reply becomes a verdict (K6).
124///
125/// `hook` fixes the mode (wrong-mode check) and the class (grant-keyed
126/// default); `origin` carries §11.1's per-origin split for the admission
127/// port — the only veto-capable one is `channel`.
128pub fn resolve_outcome(
129    reply: &HookReply,
130    grants: &GrantSet,
131    hook: &HookId,
132    origin: Origin,
133) -> Outcome {
134    // Self-declared unreachability first (§11.1): an honest plugin that
135    // knows it cannot decide must not be mistaken for one speaking out of
136    // turn.
137    if let HookReply::Err { code, .. } = reply {
138        return match code {
139            ReplyErrCode::Deadline => {
140                Outcome::Default(grant_keyed_default(grants, hook, origin, Cause::Deadline))
141            }
142            ReplyErrCode::Crashed => {
143                Outcome::Default(grant_keyed_default(grants, hook, origin, Cause::Crash))
144            }
145            ReplyErrCode::Malformed => Outcome::Discarded {
146                code: SpeechCode::Malformed,
147                grant: None,
148            },
149            ReplyErrCode::Unauthorized => Outcome::Discarded {
150                code: SpeechCode::Unauthorized,
151                grant: None,
152            },
153            ReplyErrCode::UnsupportedHook => Outcome::Discarded {
154                code: SpeechCode::UnsupportedHook,
155                grant: None,
156            },
157            ReplyErrCode::ProtocolViolation => Outcome::Discarded {
158                code: SpeechCode::ProtocolViolation,
159                grant: None,
160            },
161        };
162    }
163
164    let shape = reply_shape(reply);
165    let mode = hook.mode();
166    if !shape.legal_at(mode) {
167        // Wrong-mode reply: `err:malformed`-shaped speech defect (§5.2).
168        return Outcome::Discarded {
169            code: SpeechCode::Malformed,
170            grant: None,
171        };
172    }
173    match shape {
174        ReplyShape::Ack | ReplyShape::FlowNext | ReplyShape::BailNone => Outcome::AsIfAbsent,
175        ReplyShape::FlowStop => {
176            // Only `admit/pre` is a flow hook (the mode check above has
177            // already refused a stop anywhere else).
178            match hook {
179                HookId::AdmitPre if origin != Origin::Channel => {
180                    // §3.4.3: the API-borne port is observe-only in v1 —
181                    // there is no verdict to fail closed and no wire to
182                    // express a refusal; the stop is discarded.
183                    Outcome::Discarded {
184                        code: SpeechCode::OriginObserveOnly,
185                        grant: Some(Grant::VetoAdmit),
186                    }
187                }
188                HookId::AdmitPre if !grants.contains(Grant::VetoAdmit) => Outcome::Discarded {
189                    code: SpeechCode::Unauthorized,
190                    grant: Some(Grant::VetoAdmit),
191                },
192                HookId::AdmitPre => Outcome::Denied {
193                    reason: match reply {
194                        HookReply::FlowStop { reason } => reason.clone(),
195                        _ => unreachable!("shape checked above"),
196                    },
197                },
198                _ => Outcome::Discarded {
199                    code: SpeechCode::Malformed,
200                    grant: None,
201                },
202            }
203        }
204        ReplyShape::BailDeny => {
205            let required = veto_grant_for_class(hook.class());
206            match required {
207                Some(grant) if grants.contains(grant) => Outcome::Denied {
208                    reason: match reply {
209                        HookReply::BailDeny { reason } => reason.clone(),
210                        _ => unreachable!("shape checked above"),
211                    },
212                },
213                Some(grant) => Outcome::Discarded {
214                    code: SpeechCode::Unauthorized,
215                    grant: Some(grant),
216                },
217                // A deny at a hook with no veto-capable class: malformed.
218                None => Outcome::Discarded {
219                    code: SpeechCode::Malformed,
220                    grant: None,
221                },
222            }
223        }
224    }
225}
226
227fn reply_shape(reply: &HookReply) -> ReplyShape {
228    match reply {
229        HookReply::Ack { .. } => ReplyShape::Ack,
230        HookReply::FlowNext => ReplyShape::FlowNext,
231        HookReply::FlowStop { .. } => ReplyShape::FlowStop,
232        HookReply::BailNone => ReplyShape::BailNone,
233        HookReply::BailDeny { .. } => ReplyShape::BailDeny,
234        HookReply::Err { .. } => unreachable!("err handled before shaping"),
235    }
236}
237
238/// The grant-keyed unreachability default (§11.1's table).
239/// `pub(crate)`: the bus's session-quarantine path (§9.3) synthesizes
240/// the default directly — a quarantined sidecar is unreachable, and
241/// the cause must read `quarantine`, not `crashed`.
242pub(crate) fn grant_keyed_default(
243    grants: &GrantSet,
244    hook: &HookId,
245    origin: Origin,
246    cause: Cause,
247) -> ClassDefault {
248    match hook {
249        HookId::ToolPre if grants.contains(Grant::VetoTool) => ClassDefault::Deny { cause },
250        HookId::AdmitPre if origin == Origin::Channel && grants.contains(Grant::VetoAdmit) => {
251            ClassDefault::RefuseAdmission { cause }
252        }
253        HookId::SettlePre if grants.contains(Grant::VetoSettle) => ClassDefault::Abstain,
254        // An observe-only subscriber — at any hook, including a
255        // veto-capable one, and at an observe-only port — lapses (§11.1
256        // row 4): an observer has no decision to lose.
257        _ => ClassDefault::Lapse,
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264
265    fn grants(names: &[&str]) -> GrantSet {
266        GrantSet::from_names(names).unwrap()
267    }
268
269    #[test]
270    fn class_default_is_keyed_by_grant() {
271        let tool_pre = HookId::parse("tool/pre").unwrap();
272        let admit_pre = HookId::parse("admit/pre").unwrap();
273        let settle_pre = HookId::parse("settle/pre").unwrap();
274
275        let unreachable = HookReply::Err {
276            code: ReplyErrCode::Crashed,
277            message: "gone".to_string(),
278        };
279
280        // Row 1: `veto:tool` at `tool/pre` fails CLOSED.
281        assert_eq!(
282            resolve_outcome(
283                &unreachable,
284                &grants(&["observe:tool", "veto:tool"]),
285                &tool_pre,
286                Origin::Api
287            ),
288            Outcome::Default(ClassDefault::Deny {
289                cause: Cause::Crash
290            })
291        );
292        // Row 2: `veto:admit` at a channel-borne `admit/pre` fails CLOSED.
293        assert_eq!(
294            resolve_outcome(
295                &unreachable,
296                &grants(&["observe:admit", "veto:admit"]),
297                &admit_pre,
298                Origin::Channel
299            ),
300            Outcome::Default(ClassDefault::RefuseAdmission {
301                cause: Cause::Crash
302            })
303        );
304        // The same holder at an API-borne origin lapses: the port is
305        // observe-only there, so there is no verdict to fail closed.
306        assert_eq!(
307            resolve_outcome(
308                &unreachable,
309                &grants(&["observe:admit", "veto:admit"]),
310                &admit_pre,
311                Origin::Api
312            ),
313            Outcome::Default(ClassDefault::Lapse)
314        );
315        // Row 3: `veto:settle` at `settle/pre` fails OPEN.
316        assert_eq!(
317            resolve_outcome(
318                &unreachable,
319                &grants(&["observe:settle", "veto:settle"]),
320                &settle_pre,
321                Origin::Api
322            ),
323            Outcome::Default(ClassDefault::Abstain)
324        );
325        // Row 4: observe-only lapses — even at a veto-capable hook.
326        assert_eq!(
327            resolve_outcome(
328                &unreachable,
329                &grants(&["observe:tool"]),
330                &tool_pre,
331                Origin::Api
332            ),
333            Outcome::Default(ClassDefault::Lapse)
334        );
335        // Deadline is the same default with a different cause.
336        let overdue = HookReply::Err {
337            code: ReplyErrCode::Deadline,
338            message: "slow".to_string(),
339        };
340        assert_eq!(
341            resolve_outcome(
342                &overdue,
343                &grants(&["observe:tool", "veto:tool"]),
344                &tool_pre,
345                Origin::Api
346            ),
347            Outcome::Default(ClassDefault::Deny {
348                cause: Cause::Deadline
349            })
350        );
351    }
352
353    #[test]
354    fn unreachable_veto_denies_at_any_order_position() {
355        // §11.1 consequence 1: "not reachable" cannot be read as
356        // "abstained". `resolve_outcome` is position-free — the ordering
357        // guarantee is exercised end-to-end in the bus tests, where the
358        // same reply placed *after* an abstaining subscriber still denies.
359        let tool_pre = HookId::parse("tool/pre").unwrap();
360        let abstain = HookReply::BailNone;
361        let unreachable = HookReply::Err {
362            code: ReplyErrCode::Deadline,
363            message: "over deadline".to_string(),
364        };
365        let veto_holder = grants(&["observe:tool", "veto:tool"]);
366
367        assert_eq!(
368            resolve_outcome(&abstain, &veto_holder, &tool_pre, Origin::Api),
369            Outcome::AsIfAbsent
370        );
371        assert_eq!(
372            resolve_outcome(&unreachable, &veto_holder, &tool_pre, Origin::Api),
373            Outcome::Default(ClassDefault::Deny {
374                cause: Cause::Deadline
375            })
376        );
377    }
378
379    #[test]
380    fn speech_defects_are_discarded_never_defaulted() {
381        // §5.2: an out-of-grant or wrong-mode reply is not the class
382        // default — the outcome is exactly as-if-absent.
383        let tool_pre = HookId::parse("tool/pre").unwrap();
384        let observe_only = grants(&["observe:tool"]);
385
386        // Out-of-grant deny from an observe-only subscriber.
387        assert_eq!(
388            resolve_outcome(
389                &HookReply::BailDeny {
390                    reason: "no".to_string()
391                },
392                &observe_only,
393                &tool_pre,
394                Origin::Api
395            ),
396            Outcome::Discarded {
397                code: SpeechCode::Unauthorized,
398                grant: Some(Grant::VetoTool)
399            }
400        );
401        // Wrong-mode: an `ack` at a bail hook.
402        assert_eq!(
403            resolve_outcome(
404                &HookReply::Ack { note: None },
405                &observe_only,
406                &tool_pre,
407                Origin::Api
408            ),
409            Outcome::Discarded {
410                code: SpeechCode::Malformed,
411                grant: None
412            }
413        );
414        // A flow stop at a bail hook is wrong-mode too.
415        assert_eq!(
416            resolve_outcome(
417                &HookReply::FlowStop {
418                    reason: "no".to_string()
419                },
420                &observe_only,
421                &tool_pre,
422                Origin::Api
423            ),
424            Outcome::Discarded {
425                code: SpeechCode::Malformed,
426                grant: None
427            }
428        );
429        // A stop at an API-borne admission is discarded (observe-only
430        // origin), even with the grant held.
431        let admit_pre = HookId::parse("admit/pre").unwrap();
432        assert_eq!(
433            resolve_outcome(
434                &HookReply::FlowStop {
435                    reason: "no".to_string()
436                },
437                &grants(&["observe:admit", "veto:admit"]),
438                &admit_pre,
439                Origin::Api
440            ),
441            Outcome::Discarded {
442                code: SpeechCode::OriginObserveOnly,
443                grant: Some(Grant::VetoAdmit)
444            }
445        );
446        // A valid stop at a channel-borne admission with the grant is a
447        // verdict, not a defect.
448        assert_eq!(
449            resolve_outcome(
450                &HookReply::FlowStop {
451                    reason: "off-hours".to_string()
452                },
453                &grants(&["observe:admit", "veto:admit"]),
454                &admit_pre,
455                Origin::Channel
456            ),
457            Outcome::Denied {
458                reason: "off-hours".to_string()
459            }
460        );
461        // Valid deny and abstain at bail hooks with the grant held.
462        assert_eq!(
463            resolve_outcome(
464                &HookReply::BailDeny {
465                    reason: "blocked".to_string()
466                },
467                &grants(&["observe:tool", "veto:tool"]),
468                &tool_pre,
469                Origin::Api
470            ),
471            Outcome::Denied {
472                reason: "blocked".to_string()
473            }
474        );
475        assert_eq!(
476            resolve_outcome(
477                &HookReply::BailNone,
478                &grants(&["observe:settle", "veto:settle"]),
479                &HookId::parse("settle/pre").unwrap(),
480                Origin::Api
481            ),
482            Outcome::AsIfAbsent
483        );
484    }
485}