obzenflow_core 0.2.5

Core domain layer for ObzenFlow - pure abstractions with minimal dependencies
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
// SPDX-License-Identifier: MIT OR Apache-2.0
// SPDX-FileCopyrightText: 2025-2026 ObzenFlow Contributors
// https://obzenflow.dev

//! Combines member-stage lifecycle events into each composite's current status.

use crate::event::StageLifecycleEvent;
use crate::id::{CompositeId, RoleId, StageId};
use std::collections::{BTreeMap, BTreeSet};

/// The stages that form a composite and the role each stage plays in the group.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompositeDefinition {
    composite_id: CompositeId,
    members: Vec<(StageId, RoleId)>,
}

impl CompositeDefinition {
    /// Name the composite and pair each member stage with its role, such as `map`.
    pub fn new(composite_id: CompositeId, members: Vec<(StageId, RoleId)>) -> Self {
        Self {
            composite_id,
            members,
        }
    }

    /// The composite ID used to look up this group's status.
    pub fn composite_id(&self) -> &CompositeId {
        &self.composite_id
    }
}

/// The group's status based on the member events read so far.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CompositeStatus {
    Waiting,
    Running,
    Completed,
    Cancelled {
        reason: String,
    },
    Failed {
        at: RoleId,
        error: String,
    },
    /// A member reported conflicting outcomes, such as completed then cancelled.
    Invalid {
        error: String,
    },
}

/// Invalid group membership or conflicting outcomes reported by a member, such
/// as the same stage reporting both successful completion and cancellation.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum CompositeProjectionError {
    #[error("composite {composite} has no lifecycle members")]
    EmptyComposite { composite: CompositeId },

    #[error("composite {composite} declares member {stage} more than once")]
    DuplicateMember {
        composite: CompositeId,
        stage: StageId,
    },

    #[error("composite {composite} declares role {role} more than once")]
    DuplicateRole {
        composite: CompositeId,
        role: RoleId,
    },

    #[error("composite {composite} is defined more than once")]
    DuplicateComposite { composite: CompositeId },

    #[error("stage {stage} belongs to both composite {first} and composite {second}")]
    StageInMultipleComposites {
        stage: StageId,
        first: CompositeId,
        second: CompositeId,
    },

    #[error(
        "composite {composite} member {stage} reported conflicting terminal states: {previous} then {incoming}"
    )]
    ConflictingTerminal {
        composite: CompositeId,
        stage: StageId,
        previous: &'static str,
        incoming: &'static str,
    },
}

impl CompositeProjectionError {
    /// Composite whose definition or history is invalid, when one is known.
    pub fn composite_id(&self) -> Option<&CompositeId> {
        match self {
            Self::EmptyComposite { composite }
            | Self::DuplicateMember { composite, .. }
            | Self::DuplicateRole { composite, .. }
            | Self::DuplicateComposite { composite }
            | Self::ConflictingTerminal { composite, .. } => Some(composite),
            Self::StageInMultipleComposites { .. } => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct AttributedFailure {
    at: RoleId,
    error: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum MemberTerminal {
    Completed,
    Cancelled { reason: String },
    Failed { error: String },
}

impl MemberTerminal {
    const fn name(&self) -> &'static str {
        match self {
            Self::Completed => "completed",
            Self::Cancelled { .. } => "cancelled",
            Self::Failed { .. } => "failed",
        }
    }

    fn semantically_matches(&self, other: &Self) -> bool {
        self == other
    }
}

#[derive(Debug, Clone)]
struct CompositeState {
    composite_id: CompositeId,
    members: BTreeSet<StageId>,
    role_of: BTreeMap<StageId, RoleId>,
    terminal_of: BTreeMap<StageId, MemberTerminal>,
    first_failure: Option<AttributedFailure>,
    first_cancellation: Option<String>,
    started: bool,
    integrity_error: Option<CompositeProjectionError>,
}

impl CompositeState {
    fn from_definition(definition: CompositeDefinition) -> Result<Self, CompositeProjectionError> {
        let CompositeDefinition {
            composite_id,
            members,
        } = definition;

        if members.is_empty() {
            return Err(CompositeProjectionError::EmptyComposite {
                composite: composite_id,
            });
        }

        let mut member_set = BTreeSet::new();
        let mut role_set = BTreeSet::new();
        let mut role_of = BTreeMap::new();
        for (stage, role) in members {
            if !member_set.insert(stage) {
                return Err(CompositeProjectionError::DuplicateMember {
                    composite: composite_id,
                    stage,
                });
            }
            if !role_set.insert(role.clone()) {
                return Err(CompositeProjectionError::DuplicateRole {
                    composite: composite_id,
                    role,
                });
            }
            role_of.insert(stage, role);
        }

        Ok(Self {
            composite_id,
            members: member_set,
            role_of,
            terminal_of: BTreeMap::new(),
            first_failure: None,
            first_cancellation: None,
            started: false,
            integrity_error: None,
        })
    }

    fn status(&self) -> CompositeStatus {
        if let Some(error) = &self.integrity_error {
            return CompositeStatus::Invalid {
                error: error.to_string(),
            };
        }

        if let Some(failure) = &self.first_failure {
            return CompositeStatus::Failed {
                at: failure.at.clone(),
                error: failure.error.clone(),
            };
        }

        if self.terminal_of.len() == self.members.len() {
            if let Some(reason) = &self.first_cancellation {
                return CompositeStatus::Cancelled {
                    reason: reason.clone(),
                };
            }
            return CompositeStatus::Completed;
        }

        if self.started {
            CompositeStatus::Running
        } else {
            CompositeStatus::Waiting
        }
    }

    fn apply(
        &mut self,
        stage: StageId,
        event: &StageLifecycleEvent,
    ) -> Result<(), CompositeProjectionError> {
        if self.integrity_error.is_some() || !self.members.contains(&stage) {
            return Ok(());
        }

        match event {
            StageLifecycleEvent::Running => {
                self.started = true;
                Ok(())
            }
            StageLifecycleEvent::Draining { .. } => Ok(()),
            StageLifecycleEvent::Drained | StageLifecycleEvent::Completed { .. } => {
                self.record_terminal(stage, MemberTerminal::Completed)
            }
            StageLifecycleEvent::Cancelled { reason, .. } => {
                let terminal = MemberTerminal::Cancelled {
                    reason: reason.clone(),
                };
                let was_new = !self.terminal_of.contains_key(&stage);
                self.record_terminal(stage, terminal)?;
                if was_new && self.first_cancellation.is_none() {
                    self.first_cancellation = Some(reason.clone());
                }
                Ok(())
            }
            StageLifecycleEvent::Failed { error, .. } => {
                let terminal = MemberTerminal::Failed {
                    error: error.clone(),
                };
                let was_new = !self.terminal_of.contains_key(&stage);
                self.record_terminal(stage, terminal)?;
                if was_new && self.first_failure.is_none() {
                    let at = self
                        .role_of
                        .get(&stage)
                        .expect("validated composite member always has a role")
                        .clone();
                    self.first_failure = Some(AttributedFailure {
                        at,
                        error: error.clone(),
                    });
                }
                Ok(())
            }
        }
    }

    fn record_terminal(
        &mut self,
        stage: StageId,
        incoming: MemberTerminal,
    ) -> Result<(), CompositeProjectionError> {
        if let Some(previous) = self.terminal_of.get(&stage) {
            if previous.semantically_matches(&incoming) {
                return Ok(());
            }

            let error = CompositeProjectionError::ConflictingTerminal {
                composite: self.composite_id.clone(),
                stage,
                previous: previous.name(),
                incoming: incoming.name(),
            };
            self.integrity_error = Some(error.clone());
            return Err(error);
        }

        self.terminal_of.insert(stage, incoming);
        Ok(())
    }
}

/// Tracks member outcomes and calculates each composite's status.
#[derive(Debug, Clone)]
pub struct CompositeLifecycleProjection {
    states: BTreeMap<CompositeId, CompositeState>,
    composite_by_stage: BTreeMap<StageId, CompositeId>,
}

impl CompositeLifecycleProjection {
    /// Validate group membership and start each group in the waiting state.
    pub fn new(
        definitions: impl IntoIterator<Item = CompositeDefinition>,
    ) -> Result<Self, CompositeProjectionError> {
        let mut states = BTreeMap::new();
        let mut composite_by_stage = BTreeMap::new();

        for definition in definitions {
            let state = CompositeState::from_definition(definition)?;
            let composite_id = state.composite_id.clone();
            if states.contains_key(&composite_id) {
                return Err(CompositeProjectionError::DuplicateComposite {
                    composite: composite_id,
                });
            }

            for stage in &state.members {
                if let Some(first) = composite_by_stage.insert(*stage, composite_id.clone()) {
                    return Err(CompositeProjectionError::StageInMultipleComposites {
                        stage: *stage,
                        first,
                        second: composite_id,
                    });
                }
            }

            states.insert(composite_id, state);
        }

        Ok(Self {
            states,
            composite_by_stage,
        })
    }

    /// Composite containing `stage`, if the topology declares one.
    pub fn composite_for_stage(&self, stage: StageId) -> Option<&CompositeId> {
        self.composite_by_stage.get(&stage)
    }

    /// Apply events in journal order: the first recorded failure supplies the cause.
    pub fn apply(
        &mut self,
        stage: StageId,
        event: &StageLifecycleEvent,
    ) -> Result<(), CompositeProjectionError> {
        let Some(composite_id) = self.composite_by_stage.get(&stage).cloned() else {
            return Ok(());
        };
        self.states
            .get_mut(&composite_id)
            .expect("validated stage index references an existing composite")
            .apply(stage, event)
    }

    /// The group's status after all events applied so far.
    pub fn status(&self, composite_id: &CompositeId) -> Option<CompositeStatus> {
        self.states.get(composite_id).map(CompositeState::status)
    }

    /// Current statuses of all groups, sorted by composite ID.
    pub fn statuses(&self) -> Vec<(CompositeId, CompositeStatus)> {
        self.states
            .iter()
            .map(|(id, state)| (id.clone(), state.status()))
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn definition(composite: &str, members: &[(StageId, &str)]) -> CompositeDefinition {
        CompositeDefinition::new(
            CompositeId::new(composite),
            members
                .iter()
                .map(|(stage, role)| (*stage, RoleId::new(*role)))
                .collect(),
        )
    }

    fn projection() -> (CompositeLifecycleProjection, StageId, StageId) {
        let map = StageId::new();
        let finish = StageId::new();
        let projection = CompositeLifecycleProjection::new([definition(
            "ai_map_reduce:digest",
            &[(map, "map"), (finish, "finalize")],
        )])
        .unwrap();
        (projection, map, finish)
    }

    fn completed() -> StageLifecycleEvent {
        StageLifecycleEvent::Completed { accounting: None }
    }

    fn cancelled(reason: &str) -> StageLifecycleEvent {
        StageLifecycleEvent::Cancelled {
            reason: reason.to_string(),
            accounting: None,
        }
    }

    fn failed(error: &str) -> StageLifecycleEvent {
        StageLifecycleEvent::Failed {
            error: error.to_string(),
            recoverable: None,
            accounting: None,
            causal_event_id: None,
        }
    }

    fn id() -> CompositeId {
        CompositeId::new("ai_map_reduce:digest")
    }

    #[test]
    fn waiting_running_and_all_completed_are_state_derived() {
        let (mut projection, map, finish) = projection();
        assert_eq!(projection.status(&id()), Some(CompositeStatus::Waiting));

        projection
            .apply(map, &StageLifecycleEvent::Running)
            .unwrap();
        assert_eq!(projection.status(&id()), Some(CompositeStatus::Running));

        projection.apply(map, &completed()).unwrap();
        assert_eq!(projection.status(&id()), Some(CompositeStatus::Running));
        projection
            .apply(finish, &StageLifecycleEvent::Drained)
            .unwrap();
        assert_eq!(projection.status(&id()), Some(CompositeStatus::Completed));
    }

    #[test]
    fn first_failure_is_fail_fast_and_append_order_attributed() {
        let (mut first_map, map, finish) = projection();
        first_map.apply(map, &failed("map failed")).unwrap();
        first_map.apply(finish, &failed("finalize failed")).unwrap();
        assert_eq!(
            first_map.status(&id()),
            Some(CompositeStatus::Failed {
                at: RoleId::new("map"),
                error: "map failed".to_string(),
            })
        );

        let (mut first_finish, map, finish) = projection();
        first_finish
            .apply(finish, &failed("finalize failed"))
            .unwrap();
        first_finish.apply(map, &failed("map failed")).unwrap();
        assert_eq!(
            first_finish.status(&id()),
            Some(CompositeStatus::Failed {
                at: RoleId::new("finalize"),
                error: "finalize failed".to_string(),
            })
        );
    }

    #[test]
    fn cancellation_waits_for_all_members_and_keeps_first_reason() {
        let (mut projection, map, finish) = projection();
        projection.apply(map, &cancelled("operator stop")).unwrap();
        assert_eq!(projection.status(&id()), Some(CompositeStatus::Waiting));
        projection.apply(finish, &cancelled("timeout")).unwrap();
        assert_eq!(
            projection.status(&id()),
            Some(CompositeStatus::Cancelled {
                reason: "operator stop".to_string(),
            })
        );
    }

    #[test]
    fn failure_overrides_an_unresolved_cancellation() {
        let (mut projection, map, finish) = projection();
        projection.apply(map, &cancelled("operator stop")).unwrap();
        projection.apply(finish, &failed("boom")).unwrap();
        assert!(matches!(
            projection.status(&id()),
            Some(CompositeStatus::Failed { at, error })
                if at.as_str() == "finalize" && error == "boom"
        ));
    }

    #[test]
    fn exact_duplicate_terminal_is_idempotent() {
        let (mut projection, map, _finish) = projection();
        projection.apply(map, &completed()).unwrap();
        projection.apply(map, &completed()).unwrap();
        assert_eq!(projection.status(&id()), Some(CompositeStatus::Waiting));
    }

    #[test]
    fn conflicting_terminal_makes_the_view_invalid() {
        let (mut projection, map, _finish) = projection();
        projection.apply(map, &completed()).unwrap();
        let error = projection
            .apply(map, &cancelled("late stop"))
            .expect_err("contradictory tape must fail integrity");
        assert!(matches!(
            error,
            CompositeProjectionError::ConflictingTerminal {
                previous: "completed",
                incoming: "cancelled",
                ..
            }
        ));
        assert!(matches!(
            projection.status(&id()),
            Some(CompositeStatus::Invalid { error })
                if error.contains("conflicting terminal states")
        ));
    }

    #[test]
    fn same_ordered_history_rebuilds_identical_statuses() {
        let (first, map, finish) = projection();
        let history = [
            (map, StageLifecycleEvent::Running),
            (finish, StageLifecycleEvent::Running),
            (map, cancelled("operator stop")),
            (finish, completed()),
        ];

        let replay = |mut projection: CompositeLifecycleProjection| {
            for (stage, event) in &history {
                projection.apply(*stage, event).unwrap();
            }
            projection.statuses()
        };

        assert_eq!(replay(first.clone()), replay(first));
    }

    #[test]
    fn non_member_lifecycle_is_ignored() {
        let (mut projection, _map, _finish) = projection();
        projection
            .apply(StageId::new(), &StageLifecycleEvent::Running)
            .unwrap();
        assert_eq!(projection.status(&id()), Some(CompositeStatus::Waiting));
    }

    #[test]
    fn one_stage_cannot_belong_to_two_composites() {
        let stage = StageId::new();
        let error = CompositeLifecycleProjection::new([
            definition("first", &[(stage, "member")]),
            definition("second", &[(stage, "member")]),
        ])
        .expect_err("ambiguous membership must fail");
        assert!(matches!(
            error,
            CompositeProjectionError::StageInMultipleComposites { .. }
        ));
    }
}