soma-som-ring 0.1.0

Standalone ring execution engine for soma(som): cycle lifecycle, extension registration, boundary mediation
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
// SPDX-License-Identifier: LGPL-3.0-only
#![allow(missing_docs, clippy::indexing_slicing)]

//! Protocol boundary: structural discontinuity at every ring crossing.
//!
//! Algorithm selection is application-tier:
//! `CrossingSigner` from [`soma_som_core`] abstracts signing; concrete
//! implementations live in the consuming application.
//!
//! ## Spec traceability
//! - Contracts §4: Boundary specification
//! - Contracts §4.1: 7 behavioural requirements
//! - SAD §4.3: Boundary orchestrator
//! - SAD §4.2: "The protocol adapter enforces envelope compliance and key stripping"
//! - Invariants 1, 9: No self-certification + Forward-only visibility

use std::time::{SystemTime, UNIX_EPOCH};

use soma_som_core::crossing::CrossingRecord;
use soma_som_core::envelope::Envelope;
use soma_som_core::signing_provider::{CrossingSigner, SigningProviderError};
use soma_som_core::timing::{CycleTimer, TimingConfig, TimingError};
use soma_som_core::types::{CrossingType, UnitId};
use tracing::instrument;

// ── BoundaryError ────────────────────────────────────────────────────────────

/// Errors produced by boundary operations.
#[derive(Debug, Clone, thiserror::Error)]
#[non_exhaustive]
pub enum BoundaryError {
    #[error(
        "Routing violation: {src_unit} is not the predecessor of {dst_unit} \
         (expected {expected})"
    )]
    RoutingViolation {
        src_unit: UnitId,
        dst_unit: UnitId,
        expected: UnitId,
    },

    #[error("Envelope validation failed: {reason}")]
    EnvelopeInvalid { reason: String },

    #[error("Source mismatch: envelope claims source={claimed}, expected={expected}")]
    SourceMismatch { claimed: UnitId, expected: UnitId },

    #[error(
        "Cycle index mismatch: envelope has {envelope_cycle}, boundary expects {boundary_cycle}"
    )]
    CycleIndexMismatch {
        envelope_cycle: u64,
        boundary_cycle: u64,
    },

    /// Wraps timing errors (unit/cycle timeout, protocol violation).
    #[error(transparent)]
    Timing(#[from] TimingError),

    #[error("Crossing record signature verification failed at sequence {sequence_number}")]
    SignatureVerificationFailed { sequence_number: u8 },

    #[error("Chain hash verification failed at sequence {sequence_number}")]
    ChainHashVerificationFailed { sequence_number: u8 },

    #[error("No cycle in progress — call begin_cycle first")]
    NoCycleInProgress,

    #[error("Cycle already in progress (cycle_index={cycle_index})")]
    CycleAlreadyInProgress { cycle_index: u64 },

    /// Signing provider returned an error.
    #[error(transparent)]
    Signing(#[from] SigningProviderError),
}

// ── Key stripping ────────────────────────────────────────────────────────────

/// Sentinel value used to replace the stripped Pointer (all-zero).
pub const STRIPPED_POINTER_SENTINEL: [u8; 32] = [0u8; 32];

/// The result of stripping the predecessor's Pointer.
#[derive(Debug, Clone)]
pub struct StrippedEnvelope {
    pub envelope: Envelope,
    pub stripped_pointer: [u8; 32],
}

/// Strip the predecessor's Pointer from an envelope before delivery.
///
/// Invariants 1 + 9: the consumer must not see the predecessor's Pointer.
pub fn strip_pointer(envelope: &Envelope) -> StrippedEnvelope {
    let stripped_pointer = envelope.quad.pointer;
    let mut env = envelope.clone();
    env.quad.pointer = STRIPPED_POINTER_SENTINEL;
    StrippedEnvelope {
        envelope: env,
        stripped_pointer,
    }
}

/// True if the envelope's Pointer has been stripped (is the sentinel).
pub fn is_stripped(envelope: &Envelope) -> bool {
    envelope.quad.pointer == STRIPPED_POINTER_SENTINEL
}

/// True if the envelope still has a live (non-sentinel) Pointer.
pub fn has_live_pointer(envelope: &Envelope) -> bool {
    !is_stripped(envelope)
}

// ── Routing + envelope validation ────────────────────────────────────────────

/// Validate vertical ring routing (Invariant 5 — no bypass).
pub fn validate_routing(src: UnitId, dst: UnitId) -> Result<(), BoundaryError> {
    let expected = src.successor();
    if expected != dst {
        return Err(BoundaryError::RoutingViolation {
            src_unit: src,
            dst_unit: dst,
            expected,
        });
    }
    Ok(())
}

/// Validate routing with crossing-type awareness (vertical vs horizontal).
pub fn validate_routing_for_crossing(
    src: UnitId,
    dst: UnitId,
    crossing_type: CrossingType,
) -> Result<(), BoundaryError> {
    match crossing_type {
        CrossingType::Vertical => validate_routing(src, dst),
        CrossingType::Horizontal => {
            if src != dst {
                return Err(BoundaryError::RoutingViolation {
                    src_unit: src,
                    dst_unit: dst,
                    expected: src,
                });
            }
            Ok(())
        }
    }
}

/// Validate an envelope at the protocol boundary (Contracts §4.1 Req. 3, 4).
pub fn validate_envelope(
    envelope: &Envelope,
    expected_source: UnitId,
    destination: UnitId,
    expected_cycle: u64,
) -> Result<(), BoundaryError> {
    if envelope.source_unit != expected_source {
        return Err(BoundaryError::SourceMismatch {
            claimed: envelope.source_unit,
            expected: expected_source,
        });
    }
    validate_routing_for_crossing(expected_source, destination, envelope.crossing_type)?;
    if envelope.cycle_index != expected_cycle {
        return Err(BoundaryError::CycleIndexMismatch {
            envelope_cycle: envelope.cycle_index,
            boundary_cycle: expected_cycle,
        });
    }
    if envelope.cycle_index > 0 && envelope.quad.is_empty() {
        return Err(BoundaryError::EnvelopeInvalid {
            reason: "empty Quad in active cycle".into(),
        });
    }
    Ok(())
}

// ── Boundary struct ──────────────────────────────────────────────────────────

/// The result of processing a crossing.
#[derive(Debug, Clone)]
pub struct CrossingResult {
    /// The envelope to deliver to the consumer (Pointer stripped, record attached).
    pub delivery_envelope: Envelope,
    /// The crossing record produced at this crossing.
    pub crossing_record: CrossingRecord,
    /// The stripped Pointer value (for orchestrator fingerprint use only).
    pub stripped_pointer: [u8; 32],
}

struct CycleState {
    cycle_index: u64,
    prev_hash: [u8; 32],
    next_sequence: u8,
    timer: CycleTimer,
    crossing_records: Vec<CrossingRecord>,
}

/// The protocol boundary: structural discontinuity at every crossing.
///
/// `Boundary` holds an abstract `CrossingSigner` (injected at construction).
/// Concrete signing implementations live in the consuming application.
/// For engine unit tests, use [`soma_som_core::NoopSigner`].
pub struct Boundary {
    signer: Box<dyn CrossingSigner>,
    timing_config: TimingConfig,
    cycle_state: Option<CycleState>,
}

impl std::fmt::Debug for Boundary {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Boundary")
            .field("timing_config", &self.timing_config)
            .field("cycle_active", &self.cycle_state.is_some())
            .finish()
    }
}

impl Boundary {
    /// Create a boundary with the given signer and timing config.
    pub fn new(signer: Box<dyn CrossingSigner>, timing_config: TimingConfig) -> Self {
        Self { signer, timing_config, cycle_state: None }
    }

    /// Return the verifying key bytes from the injected signer.
    pub fn verifying_key_bytes(&self) -> [u8; 32] {
        self.signer.verifying_key_bytes()
    }

    /// Begin a new cycle.
    #[instrument(skip(self, initial_prev_hash), name = "boundary.begin_cycle")]
    pub fn begin_cycle(
        &mut self,
        cycle_index: u64,
        initial_prev_hash: [u8; 32],
    ) -> Result<(), BoundaryError> {
        if let Some(state) = self.cycle_state.as_ref() {
            return Err(BoundaryError::CycleAlreadyInProgress {
                cycle_index: state.cycle_index,
            });
        }
        self.cycle_state = Some(CycleState {
            cycle_index,
            prev_hash: initial_prev_hash,
            next_sequence: 1,
            timer: CycleTimer::new(self.timing_config),
            crossing_records: Vec::with_capacity(12),
        });
        Ok(())
    }

    /// Process a boundary crossing.
    #[instrument(skip_all, fields(source = ?expected_source, dst = ?destination), name = "boundary.crossing")]
    pub fn process_crossing(
        &mut self,
        envelope: &Envelope,
        expected_source: UnitId,
        destination: UnitId,
    ) -> Result<CrossingResult, BoundaryError> {
        let crossing_type = envelope.crossing_type;
        let state = self.cycle_state.as_mut().ok_or(BoundaryError::NoCycleInProgress)?;

        validate_envelope(envelope, expected_source, destination, state.cycle_index)?;
        state.timer.check_cycle_timeout()?;

        let StrippedEnvelope { envelope: mut stripped_env, stripped_pointer } =
            strip_pointer(envelope);

        let timestamp_ns = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_nanos() as u64;

        let sequence_number = state.next_sequence;
        let chain_hash = CrossingRecord::compute_chain_hash(
            expected_source,
            destination,
            state.cycle_index,
            sequence_number,
            crossing_type,
            timestamp_ns,
            &state.prev_hash,
        );

        let mut record = CrossingRecord {
            source: expected_source,
            destination,
            cycle_index: state.cycle_index,
            sequence_number,
            crossing_type,
            timestamp_ns,
            prev_hash: state.prev_hash,
            chain_hash,
            signature: [0u8; 64],
        };

        record.signature = self.signer.sign(&record)?;
        stripped_env.crossing_record = Some(record.clone());

        state.prev_hash = record.chain_hash;
        state.next_sequence += 1;
        state.crossing_records.push(record.clone());

        Ok(CrossingResult {
            delivery_envelope: stripped_env,
            crossing_record: record,
            stripped_pointer,
        })
    }

    /// Record that a unit has started processing.
    pub fn start_unit_timer(&mut self, unit_id: UnitId) -> Result<(), BoundaryError> {
        let state = self.cycle_state.as_mut().ok_or(BoundaryError::NoCycleInProgress)?;
        state.timer.start_unit(unit_id);
        Ok(())
    }

    /// Record that a unit has finished processing and check its timeout.
    pub fn end_unit_timer(
        &mut self,
        unit_id: UnitId,
    ) -> Result<std::time::Duration, BoundaryError> {
        let state = self.cycle_state.as_mut().ok_or(BoundaryError::NoCycleInProgress)?;
        Ok(state.timer.end_unit(unit_id)?)
    }

    /// End the current cycle. Returns (final_chain_hash, crossing_records).
    pub fn end_cycle(&mut self) -> Result<([u8; 32], Vec<CrossingRecord>), BoundaryError> {
        let state = self.cycle_state.take().ok_or(BoundaryError::NoCycleInProgress)?;
        state.timer.check_cycle_timeout()?;
        Ok((state.prev_hash, state.crossing_records))
    }

    pub fn current_cycle_index(&self) -> Option<u64> {
        self.cycle_state.as_ref().map(|s| s.cycle_index)
    }

    pub fn current_sequence(&self) -> Option<u8> {
        self.cycle_state.as_ref().map(|s| s.next_sequence)
    }

    pub fn is_cycle_active(&self) -> bool {
        self.cycle_state.is_some()
    }

    pub fn cycle_elapsed_ms(&self) -> Option<u64> {
        self.cycle_state.as_ref().map(|s| s.timer.cycle_elapsed_ms())
    }
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use soma_som_core::quad::{Quad, Tree};
    use soma_som_core::NoopSigner;

    fn make_boundary() -> Boundary {
        Boundary::new(Box::new(NoopSigner), TimingConfig::default())
    }

    fn make_envelope(source: UnitId, cycle: u64) -> Envelope {
        let mut tree = Tree::new();
        tree.insert("test.key".into(), vec![1, 2, 3]);
        let quad = Quad::from_strings("root", "secret_pointer", tree);
        Envelope::new(cycle, source, quad)
    }

    #[test]
    fn begin_cycle_sets_state() {
        let mut b = make_boundary();
        assert!(!b.is_cycle_active());
        b.begin_cycle(1, [0u8; 32]).unwrap();
        assert!(b.is_cycle_active());
        assert_eq!(b.current_cycle_index(), Some(1));
    }

    #[test]
    fn double_begin_rejected() {
        let mut b = make_boundary();
        b.begin_cycle(1, [0u8; 32]).unwrap();
        assert!(matches!(
            b.begin_cycle(2, [0u8; 32]),
            Err(BoundaryError::CycleAlreadyInProgress { cycle_index: 1 })
        ));
    }

    #[test]
    fn end_cycle_clears_state() {
        let mut b = make_boundary();
        b.begin_cycle(1, [0u8; 32]).unwrap();
        let (_, records) = b.end_cycle().unwrap();
        assert!(records.is_empty());
        assert!(!b.is_cycle_active());
    }

    #[test]
    fn process_crossing_strips_pointer() {
        let mut b = make_boundary();
        b.begin_cycle(1, [0u8; 32]).unwrap();
        let env = make_envelope(UnitId::FU, 1);
        let orig_ptr = env.quad.pointer;
        let result = b.process_crossing(&env, UnitId::FU, UnitId::MU).unwrap();
        assert!(is_stripped(&result.delivery_envelope));
        assert_eq!(result.stripped_pointer, orig_ptr);
    }

    #[test]
    fn process_crossing_attaches_record() {
        let mut b = make_boundary();
        b.begin_cycle(1, [0u8; 32]).unwrap();
        let env = make_envelope(UnitId::FU, 1);
        let result = b.process_crossing(&env, UnitId::FU, UnitId::MU).unwrap();
        assert!(result.delivery_envelope.has_crossing_record());
        let rec = result.delivery_envelope.crossing_record.as_ref().unwrap();
        assert_eq!(rec.source, UnitId::FU);
        assert_eq!(rec.destination, UnitId::MU);
        assert!(rec.verify_chain_hash());
    }

    #[test]
    fn chain_hashes_link_correctly() {
        let mut b = make_boundary();
        let initial = [99u8; 32];
        b.begin_cycle(1, initial).unwrap();
        let r1 = b.process_crossing(&make_envelope(UnitId::FU, 1), UnitId::FU, UnitId::MU).unwrap();
        let r2 = b.process_crossing(&make_envelope(UnitId::MU, 1), UnitId::MU, UnitId::CU).unwrap();
        assert_eq!(r1.crossing_record.prev_hash, initial);
        assert_eq!(r2.crossing_record.prev_hash, r1.crossing_record.chain_hash);
    }

    #[test]
    fn routing_violation_detected() {
        let mut b = make_boundary();
        b.begin_cycle(1, [0u8; 32]).unwrap();
        let env = make_envelope(UnitId::FU, 1);
        assert!(matches!(
            b.process_crossing(&env, UnitId::FU, UnitId::CU),
            Err(BoundaryError::RoutingViolation { .. })
        ));
    }

    #[test]
    fn full_ring_cycle_six_records() {
        let mut b = make_boundary();
        b.begin_cycle(1, [0u8; 32]).unwrap();
        let transitions = [
            (UnitId::FU, UnitId::MU),
            (UnitId::MU, UnitId::CU),
            (UnitId::CU, UnitId::OU),
            (UnitId::OU, UnitId::SU),
            (UnitId::SU, UnitId::HU),
            (UnitId::HU, UnitId::FU),
        ];
        for (src, dst) in transitions {
            let env = make_envelope(src, 1);
            b.process_crossing(&env, src, dst).unwrap();
        }
        let (final_hash, records) = b.end_cycle().unwrap();
        assert_eq!(records.len(), 6);
        assert_eq!(final_hash, records[5].chain_hash);
    }
}