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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
//! Coroutine: lightweight execution unit within the ProtocolMachine.
//!
//! Each role in a choreography runs as a coroutine with its own PC,
//! register file, and status. Matches the Lean `Coroutine` structure.
use serde::{Deserialize, Serialize};
use telltale_types::ValType;
use crate::instr::{Endpoint, PC};
use crate::session::{Edge, HandlerId, SessionId};
fn default_cost_budget() -> usize {
usize::MAX
}
/// Register-file representation aligned with the Lean ProtocolMachine model.
pub type RegFile = Vec<Value>;
/// Progress-token representation aligned with the Lean ProtocolMachine model.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProgressToken {
/// Session this token is scoped to.
pub sid: SessionId,
/// Endpoint this token authorizes progress for.
pub endpoint: Endpoint,
}
impl ProgressToken {
/// Construct a token from an endpoint.
#[must_use]
pub fn for_endpoint(endpoint: Endpoint) -> Self {
Self {
sid: endpoint.sid,
endpoint,
}
}
}
/// Effect context for coroutine execution, aligned with the Lean ProtocolMachine model.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EffectCtx<E = ()> {
/// Optional effect metadata captured for replay/introspection.
pub last_effect: Option<E>,
}
impl<E> Default for EffectCtx<E> {
fn default() -> Self {
Self { last_effect: None }
}
}
/// Runtime value stored in registers and buffers.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Value {
/// Unit / no value.
Unit,
/// Natural number (Lean-compatible).
Nat(u64),
/// Boolean.
Bool(bool),
/// String.
Str(String),
/// Product pair value (Lean-compatible).
Prod(Box<Value>, Box<Value>),
/// Endpoint reference for ownership and guard operations.
Endpoint(Endpoint),
}
/// Coroutine execution status.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum CoroStatus {
/// Ready to execute.
Ready,
/// Blocked waiting on something.
Blocked(BlockReason),
/// Completed normally.
Done,
/// Faulted with an error.
Faulted(Fault),
/// Running under speculative execution mode.
Speculating,
}
/// Why a coroutine is blocked.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BlockReason {
/// Waiting to receive on an edge.
Recv {
/// Edge scope for the receive wait.
edge: Edge,
/// Progress token associated with the blocked receive.
token: ProgressToken,
},
/// Waiting for buffer space to send.
Send {
/// Edge awaiting buffer space.
edge: Edge,
},
/// Waiting for an effect handler response.
Invoke {
/// Effect handler identifier.
handler: HandlerId,
},
/// Waiting for a guard layer to allow acquisition.
AcquireDenied {
/// Guard layer identifier.
layer: String,
},
/// Waiting for consensus-related condition to resolve.
Consensus {
/// Consensus wait tag.
tag: usize,
},
/// Waiting for spawn scheduling/activation.
Spawn,
/// Waiting for a session close to complete.
Close {
/// The session being closed.
sid: SessionId,
},
}
/// Runtime fault.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Fault {
/// Instruction violated the session type.
TypeViolation {
/// Expected runtime value type.
expected: ValType,
/// Actual runtime value type.
actual: ValType,
/// Description of the type violation.
message: String,
},
/// Unknown label in offer/choose.
UnknownLabel {
/// The unrecognized label.
label: String,
},
/// Channel/endpoint closed.
ChannelClosed {
/// The closed endpoint.
endpoint: Endpoint,
},
/// Signature evidence failed edge validation.
InvalidSignature {
/// Edge whose signature check failed.
edge: Edge,
},
/// Verification backend rejected a signed payload/proof.
VerificationFailed {
/// Edge whose verification failed.
edge: Edge,
/// Failure reason.
message: String,
},
/// Effect handler error.
Invoke {
/// Typed failure from the handler boundary.
failure: crate::effect::EffectFailure,
},
/// Guard layer failure.
Acquire {
/// Guard layer identifier.
layer: String,
/// Typed failure.
failure: crate::effect::EffectFailure,
},
/// Ownership transfer failure.
Transfer {
/// Error message.
message: String,
},
/// Speculation failure.
Speculation {
/// Error message.
message: String,
},
/// Session close error.
Close {
/// Error message from close.
message: String,
},
/// Protocol-level flow invariant violation.
FlowViolation {
/// Violation detail.
message: String,
},
/// Missing progress token for a required edge action.
NoProgressToken {
/// Edge missing a valid progress token.
edge: Edge,
},
/// Output-condition commit gate rejected emitted outputs.
OutputCondition {
/// Predicate reference that failed verification.
predicate_ref: String,
},
/// Register out of bounds.
OutOfRegisters,
/// PC out of bounds.
PcOutOfBounds,
/// Buffer full and backpressure policy is error.
BufferFull {
/// The full endpoint buffer.
endpoint: Endpoint,
},
/// Coroutine exhausted its deterministic execution budget.
OutOfCredits,
}
impl std::fmt::Display for Fault {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::TypeViolation {
expected,
actual,
message,
} => write!(
f,
"type violation (expected {expected:?}, actual {actual:?}): {message}"
),
Self::UnknownLabel { label } => write!(f, "unknown label: {label}"),
Self::ChannelClosed { endpoint } => {
write!(f, "channel closed: {}:{}", endpoint.sid, endpoint.role)
}
Self::InvalidSignature { edge } => write!(
f,
"invalid signature on edge {}:{}→{}",
edge.sid, edge.sender, edge.receiver
),
Self::VerificationFailed { edge, message } => write!(
f,
"verification failed on edge {}:{}→{}: {message}",
edge.sid, edge.sender, edge.receiver
),
Self::Invoke { failure } => write!(f, "invoke fault: {failure}"),
Self::Acquire { layer, failure } => {
write!(f, "acquire fault ({layer}): {failure}")
}
Self::Transfer { message } => write!(f, "transfer fault: {message}"),
Self::Speculation { message } => write!(f, "speculation fault: {message}"),
Self::Close { message } => write!(f, "close fault: {message}"),
Self::FlowViolation { message } => write!(f, "flow violation: {message}"),
Self::NoProgressToken { edge } => write!(
f,
"missing progress token for edge {}:{}→{}",
edge.sid, edge.sender, edge.receiver
),
Self::OutputCondition { predicate_ref } => {
write!(f, "output-condition rejected: {predicate_ref}")
}
Self::OutOfRegisters => write!(f, "out of registers"),
Self::PcOutOfBounds => write!(f, "PC out of bounds"),
Self::BufferFull { endpoint } => {
write!(f, "buffer full: {}:{}", endpoint.sid, endpoint.role)
}
Self::OutOfCredits => write!(f, "out of credits"),
}
}
}
/// A single coroutine executing a role's local protocol.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Coroutine<E = ()> {
/// Unique coroutine identifier.
pub id: usize,
/// Program table index for instruction fetch.
pub program_id: usize,
/// Program counter.
pub pc: PC,
/// Register file.
pub regs: RegFile,
/// Execution status.
pub status: CoroStatus,
/// Effect execution context.
#[serde(default)]
pub effect_ctx: EffectCtx<E>,
/// Endpoints owned by this coroutine.
pub owned_endpoints: Vec<Endpoint>,
/// Progress tokens for scheduling.
pub progress_tokens: Vec<ProgressToken>,
/// Knowledge facts owned by this coroutine.
pub knowledge_set: KnowledgeSet,
/// Speculation state, if any.
pub spec_state: Option<SpeculationState>,
/// Session this coroutine participates in.
pub session_id: SessionId,
/// Role name within the session.
pub role: String,
/// Remaining instruction budget for deterministic cost accounting.
#[serde(default = "default_cost_budget")]
pub cost_budget: usize,
}
/// Lean-aligned coroutine state alias.
pub type CoroutineState<E = ()> = Coroutine<E>;
/// Knowledge fact for ownership checks.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct KnowledgeFact {
/// Endpoint that the fact is about.
pub endpoint: Endpoint,
/// String fact payload.
pub fact: String,
}
/// Lean-aligned knowledge set type.
pub type KnowledgeSet = Vec<KnowledgeFact>;
/// Speculation state for a coroutine.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpeculationState {
/// Ghost session identifier.
pub ghost_sid: usize,
/// Speculation depth.
pub depth: usize,
}
impl Coroutine {
/// Create a new coroutine.
#[must_use]
pub fn new(
id: usize,
program_id: usize,
session_id: SessionId,
role: String,
num_regs: u16,
cost_budget: usize,
) -> Self {
Self {
id,
program_id,
pc: 0,
regs: vec![Value::Unit; usize::from(num_regs)],
status: CoroStatus::Ready,
effect_ctx: EffectCtx::default(),
owned_endpoints: Vec::with_capacity(1),
progress_tokens: Vec::with_capacity(1),
knowledge_set: Vec::with_capacity(1),
spec_state: None,
session_id,
role,
cost_budget,
}
}
/// Whether this coroutine is ready to execute.
#[must_use]
pub fn is_ready(&self) -> bool {
self.status == CoroStatus::Ready
}
/// Whether this coroutine has finished (done or faulted).
#[must_use]
pub fn is_terminal(&self) -> bool {
matches!(self.status, CoroStatus::Done | CoroStatus::Faulted(_))
}
}
impl Fault {
/// Build a type-violation fault when only a textual diagnostic is available.
#[must_use]
pub fn type_violation(message: impl Into<String>) -> Self {
Self::TypeViolation {
expected: ValType::Unit,
actual: ValType::Unit,
message: message.into(),
}
}
}