arkhe_kernel/runtime/event.rs
1//! `KernelEvent` and supporting enums.
2//!
3//! `#[non_exhaustive]` everywhere: external matchers cannot wildcard-match,
4//! so adding a variant is not breaking for external consumers. The
5//! `clippy::wildcard_enum_match_arm = deny` lint enforces this within
6//! the crate as well.
7
8use bitflags::bitflags;
9use bytes::Bytes;
10use serde::{Deserialize, Serialize};
11
12use crate::abi::{EntityId, InstanceId, RouteId, Tick, TypeCode};
13use crate::state::ScheduledActionId;
14
15/// Top-level kernel-emitted event. Routed through observer filters and
16/// recorded in WAL (chunks 3b/c+).
17#[derive(Debug, Clone, Serialize, Deserialize)]
18#[non_exhaustive]
19pub enum KernelEvent {
20 /// An action completed dispatch successfully.
21 ActionExecuted {
22 /// Instance where the action ran.
23 instance: InstanceId,
24 /// Type code of the executed action.
25 action_type: TypeCode,
26 /// Tick at which `step()` processed the action.
27 at: Tick,
28 },
29 /// Action `compute()` failed (panic or error). `reason` is opaque bytes.
30 ActionFailed {
31 /// Instance where the action was attempted.
32 instance: InstanceId,
33 /// Type code of the failing action.
34 action_type: TypeCode,
35 /// Opaque failure reason — kernel does not interpret.
36 reason: Bytes,
37 },
38 /// Effect application failed during dispatcher.
39 EffectFailed {
40 /// Instance where the effect was being applied.
41 instance: InstanceId,
42 /// Opaque failure reason (e.g. `b"budget_exceeded"` from
43 /// memory-budget enforcement).
44 reason: Bytes,
45 },
46 /// Observer panicked during `on_event`. Bounded payload —
47 /// `observer_index` only, no panic message (covert channel closed).
48 ObserverPanic {
49 /// Index of the panicking observer in the registry.
50 observer_index: u16,
51 },
52 /// First-panic eviction (A22).
53 ObserverEvicted {
54 /// Index of the evicted observer.
55 observer_index: u16,
56 /// Sequence number of the event that triggered the panic.
57 panic_at_seq: u64,
58 /// Panic count before eviction (always `1` under the
59 /// first-panic policy).
60 panic_count_before_eviction: u32,
61 },
62 /// Cross-instance signal dropped (reserved variant for the
63 /// `SendSignal` rate-limit (deferred); constructible today for tests).
64 SignalDropped {
65 /// Target instance the signal was destined for.
66 target: InstanceId,
67 /// Route discriminant.
68 route: RouteId,
69 /// Why the kernel dropped the signal.
70 reason: SignalDropReason,
71 },
72 /// Module force-unloaded via `force_unload` cap path.
73 ModuleForceUnloaded {
74 /// Route id whose `inflight_refs` were drained.
75 route_id: RouteId,
76 /// Sum of live refs that were dropped across instances.
77 live_refs_at_unload: u32,
78 },
79 /// Action deferred to the next tick (reserved variant).
80 ActionDeferredToNextTick {
81 /// Id of the deferred scheduled action.
82 action_id: ScheduledActionId,
83 /// Why the action was deferred.
84 reason: DeferReason,
85 },
86 /// `BestEffort` durability barrier flushed pending observer events.
87 ObserversFlushed {
88 /// Caller-supplied barrier ticket.
89 barrier_ticket: u64,
90 /// Number of events drained at this barrier.
91 event_count: u32,
92 },
93 /// Domain `Op::EmitEvent` produced an event payload.
94 DomainEventEmitted {
95 /// Instance that emitted the event.
96 instance: InstanceId,
97 /// Optional originating entity.
98 actor: Option<EntityId>,
99 /// Event type discriminant.
100 event_type_code: TypeCode,
101 /// Canonical bytes of the event payload.
102 bytes: Bytes,
103 },
104}
105
106/// Why a `SendSignal` op was dropped before delivery.
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
108#[non_exhaustive]
109pub enum SignalDropReason {
110 /// Target instance's IPC queue was full.
111 QueueFull,
112 /// Target instance does not exist (or has been despawned).
113 TargetNotFound,
114 /// Sender cancelled the signal before delivery.
115 Cancelled,
116}
117
118/// Why a scheduled action was deferred to the next tick.
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
120#[non_exhaustive]
121pub enum DeferReason {
122 /// Per-step scheduler dispatch budget was reached.
123 SchedulerBusy,
124 /// Per-instance resource budget would be exceeded by running this
125 /// action now.
126 BudgetExceeded,
127}
128
129/// Stable observer registration handle returned by `Kernel::register_observer`.
130#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
131#[serde(transparent)]
132pub struct ObserverHandle(
133 /// Monotonic registry index assigned at registration. A `u64` (not
134 /// `u16`) so the monotonic counter cannot realistically saturate and
135 /// alias a live handle (the registry has no unregister, so handles
136 /// only ever grow).
137 pub u64,
138);
139
140bitflags! {
141 /// Event-class filter for observer registration. One bit per
142 /// `KernelEvent` variant; an observer registered with a mask only
143 /// receives events whose variant bit is set. `EventMask::ALL`
144 /// (the `Default`) matches every variant — backward-compatible with
145 /// the unfiltered `Kernel::register_observer` path.
146 ///
147 /// Bit assignments are part of the public surface; new variants
148 /// must take the next free bit (no repurposing).
149 #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, serde::Serialize, serde::Deserialize)]
150 pub struct EventMask: u32 {
151 /// Match [`KernelEvent::ActionExecuted`].
152 const ACTION_EXECUTED = 1 << 0;
153 /// Match [`KernelEvent::ActionFailed`].
154 const ACTION_FAILED = 1 << 1;
155 /// Match [`KernelEvent::EffectFailed`].
156 const EFFECT_FAILED = 1 << 2;
157 /// Match [`KernelEvent::ObserverPanic`].
158 const OBSERVER_PANIC = 1 << 3;
159 /// Match [`KernelEvent::ObserverEvicted`].
160 const OBSERVER_EVICTED = 1 << 4;
161 /// Match [`KernelEvent::SignalDropped`].
162 const SIGNAL_DROPPED = 1 << 5;
163 /// Match [`KernelEvent::ModuleForceUnloaded`].
164 const MODULE_FORCE_UNLOADED = 1 << 6;
165 /// Match [`KernelEvent::ActionDeferredToNextTick`].
166 const ACTION_DEFERRED = 1 << 7;
167 /// Match [`KernelEvent::ObserversFlushed`].
168 const OBSERVERS_FLUSHED = 1 << 8;
169 /// Match [`KernelEvent::DomainEventEmitted`].
170 const DOMAIN_EVENT_EMITTED = 1 << 9;
171 /// Match every variant — equivalent to `Default`.
172 const ALL = 0x3FF;
173 }
174}
175
176impl Default for EventMask {
177 fn default() -> Self {
178 Self::ALL
179 }
180}
181
182impl EventMask {
183 /// Whether this mask wants to be notified of `event`.
184 pub(crate) fn matches(&self, event: &KernelEvent) -> bool {
185 match event {
186 KernelEvent::ActionExecuted { .. } => self.contains(Self::ACTION_EXECUTED),
187 KernelEvent::ActionFailed { .. } => self.contains(Self::ACTION_FAILED),
188 KernelEvent::EffectFailed { .. } => self.contains(Self::EFFECT_FAILED),
189 KernelEvent::ObserverPanic { .. } => self.contains(Self::OBSERVER_PANIC),
190 KernelEvent::ObserverEvicted { .. } => self.contains(Self::OBSERVER_EVICTED),
191 KernelEvent::SignalDropped { .. } => self.contains(Self::SIGNAL_DROPPED),
192 KernelEvent::ModuleForceUnloaded { .. } => self.contains(Self::MODULE_FORCE_UNLOADED),
193 KernelEvent::ActionDeferredToNextTick { .. } => self.contains(Self::ACTION_DEFERRED),
194 KernelEvent::ObserversFlushed { .. } => self.contains(Self::OBSERVERS_FLUSHED),
195 KernelEvent::DomainEventEmitted { .. } => self.contains(Self::DOMAIN_EVENT_EMITTED),
196 }
197 }
198}
199
200#[cfg(test)]
201mod tests {
202 use super::*;
203
204 #[test]
205 fn kernel_event_all_variants_constructible() {
206 let inst = InstanceId::new(1).unwrap();
207 let route = RouteId(1);
208 let _ = KernelEvent::ActionExecuted {
209 instance: inst,
210 action_type: TypeCode(1),
211 at: Tick(0),
212 };
213 let _ = KernelEvent::ActionFailed {
214 instance: inst,
215 action_type: TypeCode(1),
216 reason: Bytes::from_static(b"r"),
217 };
218 let _ = KernelEvent::EffectFailed {
219 instance: inst,
220 reason: Bytes::new(),
221 };
222 let _ = KernelEvent::ObserverPanic { observer_index: 0 };
223 let _ = KernelEvent::ObserverEvicted {
224 observer_index: 0,
225 panic_at_seq: 1,
226 panic_count_before_eviction: 1,
227 };
228 let _ = KernelEvent::SignalDropped {
229 target: inst,
230 route,
231 reason: SignalDropReason::QueueFull,
232 };
233 let _ = KernelEvent::ModuleForceUnloaded {
234 route_id: route,
235 live_refs_at_unload: 0,
236 };
237 let _ = KernelEvent::ActionDeferredToNextTick {
238 action_id: ScheduledActionId::new(1).unwrap(),
239 reason: DeferReason::SchedulerBusy,
240 };
241 let _ = KernelEvent::ObserversFlushed {
242 barrier_ticket: 0,
243 event_count: 0,
244 };
245 }
246
247 #[test]
248 fn signal_drop_reason_copy_eq() {
249 let r1 = SignalDropReason::QueueFull;
250 let r2 = r1;
251 assert_eq!(r1, r2);
252 assert_ne!(r1, SignalDropReason::TargetNotFound);
253 }
254
255 #[test]
256 fn defer_reason_copy_distinct() {
257 let r1 = DeferReason::SchedulerBusy;
258 let r2 = DeferReason::BudgetExceeded;
259 assert_ne!(r1, r2);
260 }
261
262 #[test]
263 fn observer_handle_total_order() {
264 let h1 = ObserverHandle(1);
265 let h2 = ObserverHandle(2);
266 assert!(h1 < h2);
267 assert_eq!(h1, ObserverHandle(1));
268 }
269}