1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
//! ยง23 Runtime traits โ RuntimeDriver and RuntimeControlPlane.
//!
//! These define the interface between surfaces and the runtime control-plane.
use meerkat_core::lifecycle::{InputId, RunId};
use serde::{Deserialize, Serialize};
use crate::accept::AcceptOutcome;
use crate::identifiers::LogicalRuntimeId;
use crate::input::Input;
use crate::input_state::{InputLifecycleState, InputState, StoredInputState};
use crate::runtime_event::RuntimeEventEnvelope;
use crate::runtime_state::RuntimeState;
/// Errors from RuntimeDriver operations.
#[derive(Debug, Clone, thiserror::Error)]
#[non_exhaustive]
pub enum RuntimeDriverError {
/// The runtime is not in a state that can accept this operation.
#[error("Runtime not ready: {state}")]
NotReady { state: RuntimeState },
/// The runtime was never registered / does not exist.
///
/// Distinct from [`RuntimeDriverError::Destroyed`] and
/// [`RuntimeDriverError::NotReady`] with a `Destroyed` state: absence means
/// the runtime id was never admitted, not that it once existed and was torn
/// down.
#[error("Runtime not found: {runtime_id}")]
NotFound { runtime_id: LogicalRuntimeId },
/// Input validation failed.
#[error("Input validation failed: {reason}")]
ValidationFailed { reason: String },
/// The runtime has been destroyed.
#[error("Runtime destroyed")]
Destroyed,
/// Durable recovery state could not be replayed through canonical runtime authority.
#[error("Recovery corruption: {reason}")]
RecoveryCorruption { reason: String },
/// Atomic unregister persistence may already be durable. The live retry
/// anchor is retained, but no compensating durable rollback may run.
#[error("Unregister finalization outcome is unknown: {reason}")]
UnregisterFinalizationOutcomeUnknown { reason: String },
/// The machine-owned unregister saga still owns this runtime epoch and is
/// continuing asynchronously. The caller may retry to join the same saga;
/// this is not permission to replace or abandon the owned executor.
#[error("Unregister teardown is still in progress for runtime {runtime_id}")]
UnregisterInProgress { runtime_id: LogicalRuntimeId },
/// The machine-owned ordinary-stop cleanup coordinator still owns this
/// runtime epoch. The caller may retry to join the same coordinator; this
/// is not permission to unregister, replace, or abandon the exact executor.
#[error("Runtime stop cleanup is still in progress for runtime {runtime_id}")]
RuntimeStopInProgress { runtime_id: LogicalRuntimeId },
/// The caller's exact durable ownership witness was superseded by another
/// runtime owner. Retrying from the same in-memory state is forbidden.
#[error("Stale runtime authority: {reason}")]
StaleAuthority { reason: String },
/// Internal error.
#[error("Internal error: {0}")]
Internal(String),
}
/// Errors from RuntimeControlPlane operations.
#[derive(Debug, Clone, thiserror::Error)]
#[non_exhaustive]
pub enum RuntimeControlPlaneError {
/// Runtime not found.
#[error("Runtime not found: {0}")]
NotFound(LogicalRuntimeId),
/// Invalid state for this operation.
#[error("Invalid state for operation: {state}")]
InvalidState { state: RuntimeState },
/// Store error.
#[error("Store error: {0}")]
StoreError(String),
/// Internal error.
#[error("Internal error: {0}")]
Internal(String),
}
/// Report from a recovery operation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecoveryReport {
/// How many inputs were recovered.
pub inputs_recovered: usize,
/// How many inputs were abandoned during recovery.
pub inputs_abandoned: usize,
/// How many inputs were re-queued.
pub inputs_requeued: usize,
/// Details of recovery actions.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub details: Vec<String>,
}
/// Report from a retire operation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RetireReport {
/// How many non-terminal inputs were abandoned.
pub inputs_abandoned: usize,
/// How many inputs are pending drain (will be processed before stopping).
#[serde(default)]
pub inputs_pending_drain: usize,
}
/// Report from a reset operation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResetReport {
/// How many non-terminal inputs were abandoned.
pub inputs_abandoned: usize,
}
/// Report from a recycle operation (reset driver and recover state).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecycleReport {
/// How many inputs were transferred to the new instance.
pub inputs_transferred: usize,
}
/// Report from a destroy operation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DestroyReport {
/// How many non-terminal inputs were abandoned.
pub inputs_abandoned: usize,
}
/// The runtime driver โ per-session interface for input acceptance and lifecycle.
///
/// Each session gets its own RuntimeDriver instance. The driver manages the
/// InputState ledger, policy resolution, and input queue for that session.
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
pub trait RuntimeDriver: Send + Sync {
/// Accept an input into the runtime.
async fn accept_input(&mut self, input: Input) -> Result<AcceptOutcome, RuntimeDriverError>;
/// Handle a runtime event (from the event bus).
async fn on_runtime_event(
&mut self,
event: RuntimeEventEnvelope,
) -> Result<(), RuntimeDriverError>;
/// Recover from a crash/restart.
async fn recover(&mut self) -> Result<RecoveryReport, RuntimeDriverError>;
/// Get the current runtime state.
fn runtime_state(&self) -> RuntimeState;
/// Get the state of a specific input.
fn input_state(&self, input_id: &InputId) -> Option<&InputState>;
/// Get the current DSL-owned lifecycle phase of a specific input.
fn input_phase(&self, input_id: &InputId) -> Option<InputLifecycleState>;
/// Get the current DSL-owned last run association for a specific input.
fn input_last_run_id(&self, input_id: &InputId) -> Option<RunId>;
/// Get the current DSL-owned last boundary sequence for a specific input.
fn input_last_boundary_sequence(&self, input_id: &InputId) -> Option<u64>;
/// Get the persisted shell+seed bundle for a specific input.
fn stored_input_state(&self, input_id: &InputId) -> Option<StoredInputState>;
/// Snapshot of every ledger entry paired with its DSL-owned seed.
///
/// The live-runtime witness set for terminal-status evaluation: the same
/// facts a persistent store commits at every lifecycle boundary, read
/// from the DSL authority instead of disk.
fn stored_input_states_snapshot(&self) -> Result<Vec<StoredInputState>, RuntimeDriverError>;
/// Resolve the machine-owned idempotency-key binding to its input id.
///
/// Read-only reconciliation mirror of the generated admission map โ it
/// decides nothing and never registers a binding (the accept-path
/// admission resolution stays the only mutator).
fn input_id_for_idempotency_key(&self, idempotency_key: &str) -> Option<InputId>;
/// List all non-terminal input IDs.
fn active_input_ids(&self) -> Vec<InputId>;
}
/// The runtime control plane โ manages multiple runtime instances.
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
pub trait RuntimeControlPlane: Send + Sync {
/// Ingest an input into a specific runtime.
async fn ingest(
&self,
runtime_id: &LogicalRuntimeId,
input: Input,
) -> Result<AcceptOutcome, RuntimeControlPlaneError>;
/// Publish an event to the logical runtime's current incarnation.
///
/// This command is session-scoped rather than attachment-originated: the
/// current session mutation gate is its linearization point, and the DSL
/// transition plus driver callback target that same guarded entry. An
/// attachment-originated producer that requires stale-incarnation fencing
/// needs an exact-identity API rather than inferring it from this envelope.
async fn publish_event(
&self,
event: RuntimeEventEnvelope,
) -> Result<(), RuntimeControlPlaneError>;
/// Retire a runtime (no new input, drain existing).
async fn retire(
&self,
runtime_id: &LogicalRuntimeId,
) -> Result<RetireReport, RuntimeControlPlaneError>;
/// Recycle a runtime (reset driver and recover state).
async fn recycle(
&self,
runtime_id: &LogicalRuntimeId,
) -> Result<RecycleReport, RuntimeControlPlaneError>;
/// Reset a runtime (abandon all pending input).
async fn reset(
&self,
runtime_id: &LogicalRuntimeId,
) -> Result<ResetReport, RuntimeControlPlaneError>;
/// Recover a runtime from crash.
async fn recover(
&self,
runtime_id: &LogicalRuntimeId,
) -> Result<RecoveryReport, RuntimeControlPlaneError>;
/// Get the state of a runtime.
async fn runtime_state(
&self,
runtime_id: &LogicalRuntimeId,
) -> Result<RuntimeState, RuntimeControlPlaneError>;
/// Destroy a runtime (terminal state, no recovery possible).
async fn destroy(
&self,
runtime_id: &LogicalRuntimeId,
) -> Result<DestroyReport, RuntimeControlPlaneError>;
/// Load a boundary receipt for verification.
async fn load_boundary_receipt(
&self,
runtime_id: &LogicalRuntimeId,
run_id: &RunId,
sequence: u64,
) -> Result<Option<meerkat_core::lifecycle::RunBoundaryReceipt>, RuntimeControlPlaneError>;
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
// Verify traits are object-safe
fn _assert_driver_object_safe(_: &dyn RuntimeDriver) {}
fn _assert_control_plane_object_safe(_: &dyn RuntimeControlPlane) {}
#[test]
fn runtime_driver_error_display() {
let err = RuntimeDriverError::NotReady {
state: RuntimeState::Initializing,
};
assert!(err.to_string().contains("initializing"));
let err = RuntimeDriverError::ValidationFailed {
reason: "bad input".into(),
};
assert!(err.to_string().contains("bad input"));
}
#[test]
fn runtime_control_plane_error_display() {
let err = RuntimeControlPlaneError::NotFound(LogicalRuntimeId::new("missing"));
assert!(err.to_string().contains("missing"));
}
#[test]
fn recovery_report_serde() {
let report = RecoveryReport {
inputs_recovered: 5,
inputs_abandoned: 1,
inputs_requeued: 3,
details: vec!["requeued 3 staged inputs".into()],
};
let json = serde_json::to_value(&report).unwrap();
let parsed: RecoveryReport = serde_json::from_value(json).unwrap();
assert_eq!(parsed.inputs_recovered, 5);
}
}