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
//! Versioned local engine protocol. Independent of the execution library.
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::io::{self, Read, Write};
/// Current wire generation. Mismatches are rejected before commands execute.
pub const VERSION: u32 = 1;
/// Maximum encoded JSON frame size (8 MiB).
pub const MAX_FRAME_BYTES: usize = 8 * 1024 * 1024;
/// Stable run identity: UTC nanosecond timestamp, with optional collision suffix.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct RunId(String);
impl RunId {
/// Returns the validated identifier.
pub fn as_str(&self) -> &str {
&self.0
}
}
impl TryFrom<String> for RunId {
type Error = &'static str;
fn try_from(value: String) -> Result<Self, Self::Error> {
let (base, suffix) = value
.split_once('-')
.map_or((value.as_str(), None), |(b, s)| (b, Some(s)));
let b = base.as_bytes();
if b.len() != 26
|| b[8] != b'T'
|| b[15] != b'.'
|| b[25] != b'Z'
|| !b
.iter()
.enumerate()
.all(|(i, c)| matches!(i, 8 | 15 | 25) || c.is_ascii_digit())
|| suffix.is_some_and(|s| s.is_empty() || !s.bytes().all(|c| c.is_ascii_digit()))
{
return Err("invalid UTC run identity");
}
let number = |range: std::ops::Range<usize>| base[range].parse::<u32>().unwrap();
let year = number(0..4);
let month = number(4..6);
let day = number(6..8);
let leap =
year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400));
let days = match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 => {
if leap {
29
} else {
28
}
}
_ => 0,
};
if year == 0
|| day == 0
|| day > days
|| number(9..11) > 23
|| number(11..13) > 59
|| number(13..15) > 59
{
return Err("invalid UTC calendar time");
}
Ok(Self(value))
}
}
impl From<RunId> for String {
fn from(id: RunId) -> Self {
id.0
}
}
/// A terminal outcome; liveness is a separate property.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Outcome {
/// Input capture or engine startup is still in progress.
Starting,
/// Execution is active or waiting for its final authoritative commit.
Running,
/// Execution and the final authoritative commit succeeded.
Completed,
/// Execution ended with a failure.
Failed,
/// Cooperative cancellation ended execution.
Cancelled,
}
impl Outcome {
/// Whether execution has ended.
pub fn terminal(self) -> bool {
matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
}
}
/// Canonical engine snapshot, also persisted for offline inspection.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Status {
/// Format generation.
pub version: u32,
/// Operational run identity.
pub run_id: String,
/// Last durable lifecycle sequence.
pub sequence: u64,
/// Last observation time (UTC).
pub updated_at: String,
/// Engine process identity; does not alone prove current liveness.
pub pid: u32,
/// Recorded lifecycle outcome.
pub outcome: Outcome,
/// Current pause reason.
pub pause_reason: Option<String>,
/// Cooperative control state, including whether active calls have parked.
pub control: String,
/// Scientific study currently active in a serial campaign.
pub study: Option<String>,
/// Last observed task facts, keyed by study/replicate/task identity.
pub tasks: std::collections::BTreeMap<String, Value>,
/// Current thread allocation facts.
pub allocations: Value,
/// Failure details or final explanation.
pub message: Option<String>,
/// Wall-clock elapsed milliseconds.
pub wall_ms: u64,
/// Active execution milliseconds, excluding pauses.
pub active_ms: u64,
}
/// A durable event with monotonically increasing sequence.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Event {
/// Sequence within this run.
pub sequence: u64,
/// UTC observation time.
pub at: String,
/// Stable event kind.
pub kind: String,
/// Structured runtime-owned facts.
pub data: Value,
}
/// One request on a framed connection.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Request {
/// Required wire version.
pub version: u32,
/// Client-generated id, echoed in the response.
pub id: String,
/// Requested operation.
pub command: Command,
}
/// Read, wait, replay and control operations.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum Command {
/// Negotiate version and inspect status.
Hello,
/// Fetch a current snapshot.
Status,
/// Return a bounded page of durable events after the cursor.
Events {
/// Exclusive sequence cursor.
after: u64,
},
/// Wait until the actual engine outcome is terminal.
Wait,
/// Cooperatively pause the active study.
Pause,
/// Explicitly resume after all safety gates recover.
Resume,
/// Cooperatively cancel execution.
Cancel,
}
/// Acknowledgement or structured error. Read-only requests do not mutate the run.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Response {
/// Server protocol version.
pub version: u32,
/// Original command id.
pub id: String,
/// Stable error code, absent for success.
pub error: Option<String>,
/// Human-readable details.
pub message: Option<String>,
/// Current canonical snapshot.
pub status: Status,
/// Bounded event replay page.
pub events: Vec<Event>,
}
/// Writes one length-prefixed JSON frame without allowing unbounded allocation.
pub fn write_frame(w: &mut impl Write, value: &impl Serialize) -> io::Result<()> {
let bytes = serde_json::to_vec(value).map_err(io::Error::other)?;
if bytes.len() > MAX_FRAME_BYTES {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"frame too large",
));
}
w.write_all(&(bytes.len() as u32).to_be_bytes())?;
w.write_all(&bytes)?;
w.flush()
}
/// Reads one frame, rejecting oversize and truncated messages.
pub fn read_frame<T: serde::de::DeserializeOwned>(r: &mut impl Read) -> io::Result<T> {
let mut len = [0; 4];
r.read_exact(&mut len)?;
let len = u32::from_be_bytes(len) as usize;
if len == 0 || len > MAX_FRAME_BYTES {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"invalid frame length",
));
}
let mut bytes = vec![0; len];
r.read_exact(&mut bytes)?;
serde_json::from_slice(&bytes).map_err(io::Error::other)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn utc_id_validates_calendar_and_collision_suffix() {
for id in [
"20261128T174205.123456789Z",
"20240229T235959.000000000Z-0001",
] {
assert!(RunId::try_from(id.to_owned()).is_ok());
}
for id in [
"20260229T174205.123456789Z",
"20261301T000000.000000000Z",
"20261128T240000.000000000Z",
"20261128T174205.123456789Z-",
"../run",
] {
assert!(RunId::try_from(id.to_owned()).is_err());
}
}
#[test]
fn frames_reject_limits_truncation_and_invalid_json() {
for bytes in [
vec![0, 0, 0, 0],
((MAX_FRAME_BYTES + 1) as u32).to_be_bytes().to_vec(),
vec![0, 0, 0, 2, b'{'],
vec![0, 0, 0, 1, b'?'],
] {
assert!(read_frame::<Value>(&mut bytes.as_slice()).is_err());
}
let mut bytes = Vec::new();
let request = Request {
version: VERSION,
id: "client-1".into(),
command: Command::Events { after: 42 },
};
write_frame(&mut bytes, &request).unwrap();
let decoded: Request = read_frame(&mut bytes.as_slice()).unwrap();
assert_eq!(decoded.id, "client-1");
}
}