telltale-machine 17.0.0

Protocol machine for choreographic session type protocols
Documentation
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
// Public accessors and validation queries for protocol machine state.
impl ProtocolMachine {
    /// Access the simulation clock.
    #[must_use]
    pub fn clock(&self) -> &SimClock {
        &self.clock
    }

    /// Whether all coroutines are terminal (done or faulted).
    #[must_use]
    pub fn all_done(&self) -> bool {
        self.sched.ready_count() == 0 && self.sched.blocked_count() == 0
    }

    /// Get a coroutine by ID.
    #[must_use]
    pub fn coroutine(&self, id: usize) -> Option<&Coroutine> {
        let idx = self.coro_index(id)?;
        self.coroutines.get(idx)
    }

    /// Program length for a coroutine by id.
    #[must_use]
    pub fn coroutine_program_len(&self, id: usize) -> Option<usize> {
        let coro = self.coroutine(id)?;
        self.programs
            .get(coro.program_id)
            .map(|program| program.len())
    }

    /// Number of unique immutable programs retained by the ProtocolMachine.
    #[must_use]
    pub fn unique_program_count(&self) -> usize {
        self.programs.len()
    }

    /// Get a mutable coroutine by ID.
    pub fn coroutine_mut(&mut self, id: usize) -> Option<&mut Coroutine> {
        let idx = self.coro_index(id)?;
        self.coroutines.get_mut(idx)
    }

    /// Get all coroutines for a session.
    #[must_use]
    pub fn session_coroutines(&self, sid: SessionId) -> Vec<&Coroutine> {
        self.coroutines
            .iter()
            .filter(|c| c.session_id == sid)
            .collect()
    }

    /// Access the session store.
    #[must_use]
    pub fn sessions(&self) -> &SessionStore {
        &self.sessions
    }

    /// Validate structural invariants after deserializing a persisted machine.
    ///
    /// This is intentionally conservative: it checks the decoded state against
    /// configuration limits and internal ID consistency before the machine is
    /// resumed.
    ///
    /// # Errors
    ///
    /// Returns a deterministic reason when decoded state violates runtime
    /// invariants.
    pub fn validate_post_decode(&self) -> Result<(), String> {
        self.config.validate_invariants()?;
        if self.coroutines.len() > self.config.max_coroutines {
            return Err(format!(
                "decoded coroutine count {} exceeds max_coroutines {}",
                self.coroutines.len(),
                self.config.max_coroutines
            ));
        }
        let session_count = self.sessions.iter().count();
        if session_count > self.config.max_sessions {
            return Err(format!(
                "decoded session count {session_count} exceeds max_sessions {}",
                self.config.max_sessions
            ));
        }

        let mut seen_coro_ids = BTreeSet::new();
        for coro in &self.coroutines {
            if !seen_coro_ids.insert(coro.id) {
                return Err(format!("decoded duplicate coroutine id {}", coro.id));
            }
            if coro.id >= self.next_coro_id {
                return Err(format!(
                    "decoded coroutine id {} is not below next_coro_id {}",
                    coro.id, self.next_coro_id
                ));
            }
            if self.sessions.get(coro.session_id).is_none() {
                return Err(format!(
                    "decoded coroutine {} references missing session {}",
                    coro.id, coro.session_id
                ));
            }
        }

        let mut seen_session_ids = BTreeSet::new();
        for session in self.sessions.iter() {
            if !seen_session_ids.insert(session.sid) {
                return Err(format!("decoded duplicate session id {}", session.sid));
            }
            if session.sid >= self.next_session_id {
                return Err(format!(
                    "decoded session id {} is not below next_session_id {}",
                    session.sid, self.next_session_id
                ));
            }
        }

        Ok(())
    }

    /// Access the session store mutably.
    ///
    /// Runtime internals and test support use this surface directly. Public host
    /// integrations use `OwnedSession` plus the ownership-gated session mutation
    /// APIs instead of mutating session-local host state through `sessions_mut()`.
    #[doc(hidden)]
    pub fn sessions_mut(&mut self) -> &mut SessionStore {
        &mut self.sessions
    }

    #[cfg(test)]
    fn replace_program_for_test(&mut self, program_id: usize, program: Vec<Instr>) {
        self.programs.replace_for_test(program_id, program);
    }

    /// Runtime well-formedness predicate used by debug assertions.
    ///
    /// # Errors
    ///
    /// Returns a description of the invariant violation if the ProtocolMachine state is invalid.
    #[allow(clippy::too_many_lines)]
    fn wf_coroutine_state(&self, coro: &Coroutine) -> Result<(), String> {
        if self.sessions.get(coro.session_id).is_none() {
            return Err(format!(
                "coroutine {} references missing session {}",
                coro.id, coro.session_id
            ));
        }
        let Some(program) = self.programs.get(coro.program_id) else {
            return Err(format!("missing program for coroutine {}", coro.id));
        };
        if coro.pc > program.len() {
            return Err(format!("pc out of bounds for coroutine {}", coro.id));
        }
        if coro.regs.len() != usize::from(self.config.num_registers) {
            return Err(format!("register width mismatch for coroutine {}", coro.id));
        }
        for ep in &coro.owned_endpoints {
            let Some(session) = self.sessions.get(ep.sid) else {
                return Err(format!(
                    "owned endpoint missing session {}:{}",
                    ep.sid, ep.role
                ));
            };
            if !session.roles.iter().any(|role| role == &ep.role) {
                return Err(format!(
                    "owned endpoint role not in session {}:{}",
                    ep.sid, ep.role
                ));
            }
        }
        for token in &coro.progress_tokens {
            let Some(session) = self.sessions.get(token.sid) else {
                return Err(format!(
                    "progress token missing session {} for coroutine {}",
                    token.sid, coro.id
                ));
            };
            if !session
                .roles
                .iter()
                .any(|role| role == &token.endpoint.role)
            {
                return Err(format!(
                    "progress token role not in session {}:{}",
                    token.sid, token.endpoint.role
                ));
            }
        }
        for fact in &coro.knowledge_set {
            let Some(session) = self.sessions.get(fact.endpoint.sid) else {
                return Err(format!(
                    "knowledge fact missing session {}:{}",
                    fact.endpoint.sid, fact.endpoint.role
                ));
            };
            if !session.roles.iter().any(|role| role == &fact.endpoint.role) {
                return Err(format!(
                    "knowledge fact role not in session {}:{}",
                    fact.endpoint.sid, fact.endpoint.role
                ));
            }
        }
        Ok(())
    }

    fn wf_collect_session_sets(
        &self,
    ) -> Result<(BTreeSet<SessionId>, BTreeSet<SessionId>), String> {
        let mut active_sids = BTreeSet::new();
        let mut monitor_required_sids = BTreeSet::new();
        for session in self.sessions.iter() {
            active_sids.insert(session.sid);
            if !matches!(
                session.status,
                SessionStatus::Closed | SessionStatus::Cancelled | SessionStatus::Faulted { .. }
            ) {
                monitor_required_sids.insert(session.sid);
            }
            for ep in session.local_types.keys() {
                if ep.sid != session.sid {
                    return Err(format!("local type sid mismatch for role {}", ep.role));
                }
            }
            for (edge, buffer) in &session.buffers {
                if edge.sid != session.sid {
                    return Err("buffer edge sid mismatch".to_string());
                }
                if buffer.len() > buffer.capacity() {
                    return Err("buffer length exceeds capacity".to_string());
                }
            }
        }
        Ok((active_sids, monitor_required_sids))
    }

    fn wf_monitor_state(
        &self,
        active_sids: &BTreeSet<SessionId>,
        monitor_required_sids: &BTreeSet<SessionId>,
    ) -> Result<(), String> {
        for sid in self.monitor.session_kinds.keys() {
            if !active_sids.contains(sid) {
                return Err(format!("monitor tracks unknown session {sid}"));
            }
        }
        for sid in monitor_required_sids {
            if !self.monitor.session_kinds.contains_key(sid) {
                return Err(format!("monitor missing kind for active session {sid}"));
            }
        }
        Ok(())
    }

    /// Runtime well-formedness predicate used by debug assertions.
    ///
    /// # Errors
    ///
    /// Returns a description of the invariant violation if the ProtocolMachine state is invalid.
    #[allow(clippy::too_many_lines)]
    pub fn wf_vm_state(&self) -> Result<(), String> {
        for coro in &self.coroutines {
            self.wf_coroutine_state(coro)?;
        }

        let (active_sids, monitor_required_sids) = self.wf_collect_session_sets()?;
        self.wf_monitor_state(&active_sids, &monitor_required_sids)?;

        if !self.arena.check_invariants() {
            return Err("arena invariant violation".to_string());
        }
        Ok(())
    }

    /// Inject a message directly into a session buffer.
    ///
    /// Used by simulation middleware (network/fault injection) to deliver
    /// in-flight messages without executing a ProtocolMachine send instruction.
    ///
    /// # Errors
    ///
    /// Returns an error if the session does not exist.
    pub fn inject_message(
        &mut self,
        sid: SessionId,
        from: &str,
        to: &str,
        value: Value,
    ) -> Result<EnqueueResult, ProtocolMachineError> {
        let session = self
            .sessions
            .get_mut(sid)
            .ok_or(ProtocolMachineError::SessionNotFound(sid))?;
        session
            .send(from, to, value)
            .map_err(|_| ProtocolMachineError::SessionNotFound(sid))
    }

    /// Access all coroutines.
    #[must_use]
    pub fn coroutines(&self) -> &[Coroutine] {
        &self.coroutines
    }

    /// Pause execution for all coroutines of a role.
    pub fn pause_role(&mut self, role: &str) {
        if !self.paused_roles.insert(role.to_string()) {
            return;
        }
        let coro_ids = self.role_coroutines.get(role).cloned().unwrap_or_default();
        for coro_id in coro_ids {
            self.paused_coro_ids.insert(coro_id);
            self.sync_ready_eligibility_for(coro_id);
        }
        #[cfg(debug_assertions)]
        self.debug_assert_paused_role_index();
    }

    /// Resume execution for all coroutines of a role.
    pub fn resume_role(&mut self, role: &str) {
        if !self.paused_roles.remove(role) {
            return;
        }
        let coro_ids = self.role_coroutines.get(role).cloned().unwrap_or_default();
        for coro_id in coro_ids {
            self.paused_coro_ids.remove(&coro_id);
            self.sync_ready_eligibility_for(coro_id);
        }
        #[cfg(debug_assertions)]
        self.debug_assert_paused_role_index();
    }

    /// Replace the paused role set.
    pub fn set_paused_roles(&mut self, roles: &BTreeSet<String>) {
        let to_pause: Vec<String> = roles.difference(&self.paused_roles).cloned().collect();
        let to_resume: Vec<String> = self.paused_roles.difference(roles).cloned().collect();
        for role in to_resume {
            self.resume_role(&role);
        }
        for role in to_pause {
            self.pause_role(&role);
        }
    }

    /// Access paused roles.
    #[must_use]
    pub fn paused_roles(&self) -> &BTreeSet<String> {
        &self.paused_roles
    }

    // ---- Private ----

    fn coro_index(&self, id: usize) -> Option<usize> {
        if let Some(idx) = self.coro_slots.get(&id).copied() {
            return Some(idx);
        }
        if self.coroutines.get(id).is_some_and(|coro| coro.id == id) {
            return Some(id);
        }
        self.coroutines.iter().position(|c| c.id == id)
    }

    fn rebuild_coroutine_indexes(&mut self) {
        self.coro_slots.clear();
        self.role_coroutines.clear();
        self.paused_coro_ids.clear();
        self.timed_out_coro_ids.clear();

        for (idx, coro) in self.coroutines.iter().enumerate() {
            self.coro_slots.insert(coro.id, idx);
            self.role_coroutines
                .entry(coro.role.clone())
                .or_default()
                .push(coro.id);
            if self.paused_roles.contains(&coro.role) {
                self.paused_coro_ids.insert(coro.id);
            }
            if self.timed_out_sites.contains_key(&coro.role) {
                self.timed_out_coro_ids.insert(coro.id);
            }
        }
    }

    #[cfg(debug_assertions)]
    fn debug_assert_paused_role_index(&self) {
        let expected: BTreeSet<usize> = self
            .coroutines
            .iter()
            .filter(|coro| self.paused_roles.contains(&coro.role))
            .map(|coro| coro.id)
            .collect();
        debug_assert_eq!(self.paused_coro_ids, expected);
    }

    pub(crate) fn read_reg(&self, coro_idx: usize, reg: u16) -> Result<Value, Fault> {
        self.read_reg_checked(coro_idx, reg)
    }

    pub(crate) fn write_coro_reg(
        coro: &mut Coroutine,
        reg: u16,
        value: Value,
    ) -> Result<(), Fault> {
        let slot = coro
            .regs
            .get_mut(usize::from(reg))
            .ok_or(Fault::OutOfRegisters)?;
        *slot = value;
        Ok(())
    }

    fn read_reg_checked(&self, coro_idx: usize, reg: u16) -> Result<Value, Fault> {
        self.coroutines[coro_idx]
            .regs
            .get(usize::from(reg))
            .cloned()
            .ok_or(Fault::OutOfRegisters)
    }

    fn endpoint_from_reg(&self, coro_idx: usize, reg: u16) -> Result<Endpoint, Fault> {
        decode_endpoint_from_reg(&self.coroutines[coro_idx], reg)
    }

    fn decode_fact(value: Value) -> Option<(Endpoint, String)> {
        decode_endpoint_fact(value)
    }

    fn validate_payload(
        &self,
        role: &str,
        context: &str,
        label: &str,
        expected_type: Option<&ValType>,
        value: &Value,
        strict_requires_annotation: bool,
    ) -> Result<(), Fault> {
        let mode = self.config.payload_validation_mode;
        if mode == PayloadValidationMode::Off {
            return Ok(());
        }

        let actual_type = runtime_value_val_type(value);
        let payload_bytes = runtime_value_wire_size_bytes(value);
        if payload_bytes > self.config.max_payload_bytes {
            return Err(Fault::TypeViolation {
                expected: expected_type.cloned().unwrap_or_else(|| actual_type.clone()),
                actual: actual_type,
                message: format!(
                    "{role}: {context} payload '{label}' exceeds max_payload_bytes={} (actual={payload_bytes})",
                    self.config.max_payload_bytes
                ),
            });
        }

        match expected_type {
            Some(expected) => {
                if runtime_value_matches_val_type(value, expected) {
                    Ok(())
                } else {
                    Err(Fault::TypeViolation {
                        expected: expected.clone(),
                        actual: actual_type,
                        message: format!(
                            "{role}: {context} payload '{label}' violated expected type {expected:?}"
                        ),
                    })
                }
            }
            None
                if mode == PayloadValidationMode::StrictSchema && strict_requires_annotation =>
            {
                Err(Fault::TypeViolation {
                    expected: ValType::Unit,
                    actual: actual_type,
                    message: format!(
                        "{role}: {context} payload '{label}' requires explicit ValType annotation in strict_schema mode"
                    ),
                })
            }
            None => Ok(()),
        }
    }

    /// Extract partner and branches from a Recv local type.
    fn expect_recv_type<'a>(
        local_type: &'a LocalTypeR,
        role: &str,
    ) -> Result<(&'a str, &'a BranchList), Fault> {
        match local_type {
            LocalTypeR::Recv {
                partner, branches, ..
            } => Ok((partner.as_str(), branches)),
            other => Err(Fault::TypeViolation {
                expected: telltale_types::ValType::Unit,
                actual: telltale_types::ValType::Unit,
                message: format!("{role}: Choose expects Recv, got {other:?}"),
            }),
        }
    }

    fn monitor_precheck(
        &mut self,
        ep: &Endpoint,
        role: &str,
        instr: &crate::instr::Instr,
    ) -> Result<(), Fault> {
        if self.config.monitor_mode == MonitorMode::Off {
            return Ok(());
        }
        match instr {
            crate::instr::Instr::Send { .. } | crate::instr::Instr::Offer { .. } => {
                let local_type =
                    self.sessions
                        .lookup_type(ep)
                        .ok_or_else(|| Fault::TypeViolation {
                            expected: telltale_types::ValType::Unit,
                            actual: telltale_types::ValType::Unit,
                            message: format!("[monitor] {role}: no type registered"),
                        })?;
                if matches!(local_type, LocalTypeR::Send { .. }) {
                    Ok(())
                } else {
                    Err(Fault::TypeViolation {
                        expected: telltale_types::ValType::Unit,
                        actual: telltale_types::ValType::Unit,
                        message: format!(
                            "[monitor] {role}: expected Send state, got {local_type:?}"
                        ),
                    })
                }
            }
            crate::instr::Instr::Receive { .. } => {
                let local_type =
                    self.sessions
                        .lookup_type(ep)
                        .ok_or_else(|| Fault::TypeViolation {
                            expected: telltale_types::ValType::Unit,
                            actual: telltale_types::ValType::Unit,
                            message: format!("[monitor] {role}: no type registered"),
                        })?;
                if matches!(local_type, LocalTypeR::Recv { .. }) {
                    Ok(())
                } else {
                    Err(Fault::TypeViolation {
                        expected: telltale_types::ValType::Unit,
                        actual: telltale_types::ValType::Unit,
                        message: format!(
                            "[monitor] {role}: expected Recv state, got {local_type:?}"
                        ),
                    })
                }
            }
            crate::instr::Instr::Choose { table, .. } => {
                let mut labels = BTreeSet::new();
                if !table
                    .iter()
                    .map(|(label, _)| label)
                    .all(|label| labels.insert(label.clone()))
                {
                    return Err(Fault::Speculation {
                        message: "[monitor] structural precheck failed: duplicate choose labels"
                            .to_string(),
                    });
                }
                let local_type =
                    self.sessions
                        .lookup_type(ep)
                        .ok_or_else(|| Fault::TypeViolation {
                            expected: telltale_types::ValType::Unit,
                            actual: telltale_types::ValType::Unit,
                            message: format!("[monitor] {role}: no type registered"),
                        })?;
                if matches!(local_type, LocalTypeR::Recv { .. }) {
                    Ok(())
                } else {
                    Err(Fault::TypeViolation {
                        expected: telltale_types::ValType::Unit,
                        actual: telltale_types::ValType::Unit,
                        message: format!(
                            "[monitor] {role}: expected Recv state, got {local_type:?}"
                        ),
                    })
                }
            }
            crate::instr::Instr::Open { roles, dsts, .. } => {
                if roles.len() == dsts.len() {
                    Ok(())
                } else {
                    Err(Fault::Speculation {
                        message: "[monitor] structural precheck failed: open arity mismatch"
                            .to_string(),
                    })
                }
            }
            _ => Ok(()),
        }?;
        self.monitor
            .record(ep, &format!("{instr:?}"), self.clock.tick);
        Ok(())
    }
}