obzenflow_runtime 0.2.4

Runtime services for ObzenFlow - execution and coordination business logic
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
// SPDX-License-Identifier: MIT OR Apache-2.0
// SPDX-FileCopyrightText: 2025-2026 ObzenFlow Contributors
// https://obzenflow.dev

//! Materialisation, committed readiness evidence and authorised source startup.

use crate::bootstrap::{
    bootstrap_test_lock_async, install_bootstrap_config, BootstrapConfig, StartupMode,
};
use crate::pipeline::fsm::{PipelineAction, PipelineFsmEvent, PipelineFsmState};
use crate::pipeline::tests::support::new_system_journal;
use crate::pipeline::tests::support::{
    empty_system_subscription, empty_topology, ready_stage, source_sink_topology,
    source_sink_topology_with_source, spawn_supervisor_loop, stop_and_join, test_context,
    test_supervisor, wait_for_state, TestPipelineStageHandle,
};
use crate::pipeline::PipelineState;
use crate::supervised_base::ChannelBuilder;
use obzenflow_core::event::context::StageType;
use obzenflow_core::event::SystemEvent;
use obzenflow_core::journal::factory::FlowJournalFactory;
use obzenflow_core::SystemId;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use tokio::sync::oneshot;

pub async fn manual_ready_for_run_publishes_state_and_waits_for_external_run(
    make_journals: fn() -> Box<dyn FlowJournalFactory>,
) {
    let _lock = bootstrap_test_lock_async().await;
    let _guard = install_bootstrap_config(BootstrapConfig {
        startup_mode: StartupMode::Manual,
        ..BootstrapConfig::default()
    });
    let system_id = SystemId::new();
    let mut journals = make_journals();
    let system_journal = new_system_journal(&mut *journals, system_id);
    let (topology, sink_stage_id) = source_sink_topology();
    let subscription = empty_system_subscription(&system_journal).await;
    let mut context = test_context(
        topology,
        system_id,
        system_journal.clone(),
        Some(subscription),
    );
    ready_stage(&mut context, sink_stage_id).await;

    let (sender, receiver, watcher) =
        ChannelBuilder::<PipelineFsmEvent, PipelineState>::new().build(PipelineState::Materialized);
    let mut state_rx = watcher.subscribe();
    let task = spawn_supervisor_loop(
        PipelineState::Materialized,
        test_supervisor(system_id, system_journal.clone()),
        context,
        receiver,
        watcher,
    );

    wait_for_state(&mut state_rx, "ReadyForRun", |state| {
        matches!(state, PipelineState::ReadyForRun)
    })
    .await;

    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    assert!(
        matches!(*state_rx.borrow(), PipelineState::ReadyForRun),
        "manual startup should wait in ReadyForRun until Play/Run arrives"
    );

    stop_and_join(&sender, task).await;
}

pub async fn auto_ready_for_run_emits_run_and_reaches_running(
    make_journals: fn() -> Box<dyn FlowJournalFactory>,
) {
    let _lock = bootstrap_test_lock_async().await;
    let _guard = install_bootstrap_config(BootstrapConfig {
        startup_mode: StartupMode::Auto,
        ..BootstrapConfig::default()
    });
    let system_id = SystemId::new();
    let mut journals = make_journals();
    let system_journal = new_system_journal(&mut *journals, system_id);
    let (topology, sink_stage_id) = source_sink_topology();
    let subscription = empty_system_subscription(&system_journal).await;
    let mut context = test_context(
        topology,
        system_id,
        system_journal.clone(),
        Some(subscription),
    );
    ready_stage(&mut context, sink_stage_id).await;

    let (sender, receiver, watcher) =
        ChannelBuilder::<PipelineFsmEvent, PipelineState>::new().build(PipelineState::Materialized);
    let mut state_rx = watcher.subscribe();
    let task = spawn_supervisor_loop(
        PipelineState::Materialized,
        test_supervisor(system_id, system_journal.clone()),
        context,
        receiver,
        watcher,
    );

    wait_for_state(&mut state_rx, "Running", |state| {
        matches!(state, PipelineState::Running)
    })
    .await;

    stop_and_join(&sender, task).await;
}

pub async fn materializing_stage_count_mismatch_transitions_to_failed_without_panic(
    make_journals: fn() -> Box<dyn FlowJournalFactory>,
) {
    let system_id = SystemId::new();
    let mut journals = make_journals();
    let system_journal = new_system_journal(&mut *journals, system_id);
    let (topology, sink_stage_id) = source_sink_topology();
    let mut context = test_context(topology, system_id, system_journal.clone(), None);
    context.stage_supervisors.insert(
        sink_stage_id,
        TestPipelineStageHandle::boxed(sink_stage_id, "sink", StageType::Sink),
    );

    let (_sender, receiver, watcher) = ChannelBuilder::<PipelineFsmEvent, PipelineState>::new()
        .build(PipelineState::Materializing);
    let mut state_rx = watcher.subscribe();
    let task = spawn_supervisor_loop(
        PipelineState::Materializing,
        test_supervisor(system_id, system_journal.clone()),
        context,
        receiver,
        watcher,
    );

    wait_for_state(&mut state_rx, "Failed", |state| {
        matches!(
            state,
            PipelineState::Failed { reason, .. } if reason.contains("Stage count mismatch")
        )
    })
    .await;

    tokio::time::timeout(std::time::Duration::from_secs(2), task)
        .await
        .expect("supervisor should terminate after materialization failure")
        .expect("supervisor task should join")
        .expect("supervisor should return ok after failure transition");
}

pub async fn materialized_to_ready_for_run_publishes_post_transition_state(
    make_journals: fn() -> Box<dyn FlowJournalFactory>,
) {
    let _lock = bootstrap_test_lock_async().await;
    let _guard = install_bootstrap_config(BootstrapConfig {
        startup_mode: StartupMode::Manual,
        ..BootstrapConfig::default()
    });
    let system_id = SystemId::new();
    let mut journals = make_journals();
    let system_journal = new_system_journal(&mut *journals, system_id);
    let (topology, sink_stage_id) = source_sink_topology();
    let subscription = empty_system_subscription(&system_journal).await;
    let mut context = test_context(
        topology,
        system_id,
        system_journal.clone(),
        Some(subscription),
    );
    ready_stage(&mut context, sink_stage_id).await;

    let (sender, receiver, watcher) =
        ChannelBuilder::<PipelineFsmEvent, PipelineState>::new().build(PipelineState::Materialized);
    let watcher_for_assertion = watcher.clone();
    let mut state_rx = watcher.subscribe();
    let task = spawn_supervisor_loop(
        PipelineState::Materialized,
        test_supervisor(system_id, system_journal.clone()),
        context,
        receiver,
        watcher,
    );

    wait_for_state(&mut state_rx, "ReadyForRun", |state| {
        matches!(state, PipelineState::ReadyForRun)
    })
    .await;

    assert!(
        matches!(watcher_for_assertion.current(), PipelineState::ReadyForRun),
        "observer state should publish ReadyForRun immediately after the readiness transition"
    );

    stop_and_join(&sender, task).await;
}

pub async fn running_state_requires_committed_source_running_after_start(
    make_journals: fn() -> Box<dyn FlowJournalFactory>,
) {
    let _lock = bootstrap_test_lock_async().await;
    let _guard = install_bootstrap_config(BootstrapConfig {
        startup_mode: StartupMode::Manual,
        ..BootstrapConfig::default()
    });
    let system_id = SystemId::new();
    let mut journals = make_journals();
    let system_journal = new_system_journal(&mut *journals, system_id);
    let (topology, source_stage_id, sink_stage_id) = source_sink_topology_with_source();
    let subscription = empty_system_subscription(&system_journal).await;
    let mut context = test_context(
        topology,
        system_id,
        system_journal.clone(),
        Some(subscription),
    );
    ready_stage(&mut context, sink_stage_id).await;
    context.stage_supervisors.insert(
        sink_stage_id,
        TestPipelineStageHandle::boxed(sink_stage_id, "sink", StageType::Sink),
    );

    let (entered_tx, entered_rx) = oneshot::channel();
    let (release_tx, release_rx) = oneshot::channel();
    let source_start_count = Arc::new(AtomicUsize::new(0));
    context.source_supervisors.insert(
        source_stage_id,
        TestPipelineStageHandle::with_start_gate(
            source_stage_id,
            "source",
            StageType::FiniteSource,
            entered_tx,
            release_rx,
            source_start_count.clone(),
        ),
    );

    let (sender, receiver, watcher) =
        ChannelBuilder::<PipelineFsmEvent, PipelineState>::new().build(PipelineState::ReadyForRun);
    let watcher_for_assertion = watcher.clone();
    let mut state_rx = watcher.subscribe();
    let task = spawn_supervisor_loop(
        PipelineState::ReadyForRun,
        test_supervisor(system_id, system_journal.clone()),
        context,
        receiver,
        watcher,
    );

    sender
        .send(PipelineFsmEvent::Start)
        .await
        .expect("Run should send");
    tokio::time::timeout(std::time::Duration::from_secs(2), entered_rx)
        .await
        .expect("source start action should begin")
        .expect("source start gate should be signalled");

    assert!(
        matches!(watcher_for_assertion.current(), PipelineState::ReadyForRun),
        "a pending source command is not running evidence"
    );

    release_tx
        .send(())
        .expect("source start action should still be waiting");
    system_journal
        .append(
            SystemEvent::stage_running(source_stage_id),
            Default::default(),
        )
        .await
        .unwrap();
    wait_for_state(&mut state_rx, "Running", |state| {
        matches!(state, PipelineState::Running)
    })
    .await;
    assert_eq!(source_start_count.load(Ordering::Relaxed), 1);

    stop_and_join(&sender, task).await;
}

pub async fn early_run_queued_in_materialized_is_consumed_before_ready_for_run(
    make_journals: fn() -> Box<dyn FlowJournalFactory>,
) {
    let _lock = bootstrap_test_lock_async().await;
    let _guard = install_bootstrap_config(BootstrapConfig {
        startup_mode: StartupMode::Manual,
        ..BootstrapConfig::default()
    });
    let system_id = SystemId::new();
    let mut journals = make_journals();
    let system_journal = new_system_journal(&mut *journals, system_id);
    let (topology, sink_stage_id) = source_sink_topology();
    let subscription = empty_system_subscription(&system_journal).await;
    let mut context = test_context(
        topology,
        system_id,
        system_journal.clone(),
        Some(subscription),
    );
    ready_stage(&mut context, sink_stage_id).await;

    let (sender, receiver, watcher) =
        ChannelBuilder::<PipelineFsmEvent, PipelineState>::new().build(PipelineState::Materialized);
    sender
        .send(PipelineFsmEvent::Start)
        .await
        .expect("early Run should queue");

    let mut state_rx = watcher.subscribe();
    let task = spawn_supervisor_loop(
        PipelineState::Materialized,
        test_supervisor(system_id, system_journal.clone()),
        context,
        receiver,
        watcher,
    );

    wait_for_state(&mut state_rx, "ReadyForRun", |state| {
        matches!(state, PipelineState::ReadyForRun)
    })
    .await;
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    assert!(
        matches!(*state_rx.borrow(), PipelineState::ReadyForRun),
        "queued pre-ready Run must not be deferred and replayed after readiness"
    );

    stop_and_join(&sender, task).await;
}

pub async fn empty_topology_fails_through_the_canonical_fsm(
    make_journals: fn() -> Box<dyn FlowJournalFactory>,
) {
    let system_id = SystemId::new();
    let mut journals = make_journals();
    let journal = new_system_journal(&mut *journals, system_id);
    let mut context = test_context(empty_topology(), system_id, journal, None);
    let mut machine =
        crate::pipeline::fsm::build_pipeline_fsm_with_initial(PipelineFsmState::Created);
    machine
        .handle(PipelineFsmEvent::Bootstrap, &mut context)
        .await
        .unwrap();
    assert!(matches!(machine.state(), PipelineFsmState::SettlingStages));
    assert!(context
        .termination
        .failure
        .as_ref()
        .unwrap()
        .reason
        .contains("Stage count mismatch"));
}

pub async fn stage_failures_and_cancellations_before_readiness_use_journal_evidence(
    make_journals: fn() -> Box<dyn FlowJournalFactory>,
) {
    for state in [
        PipelineFsmState::AwaitingStageReadiness,
        PipelineFsmState::ReadyForRun,
    ] {
        for cancelled in [false, true] {
            let system_id = SystemId::new();
            let mut journals = make_journals();
            let journal = new_system_journal(&mut *journals, system_id);
            let (topology, sink) = source_sink_topology();
            let event = if cancelled {
                SystemEvent::stage_cancelled(sink, "cancelled".into())
            } else {
                SystemEvent::stage_failed(sink, "ready fault".into(), false)
            };
            let envelope = journal.append(event, Default::default()).await.unwrap();
            let mut context = test_context(topology, system_id, journal, None);
            let mut machine = crate::pipeline::fsm::build_pipeline_fsm_with_initial(state.clone());
            machine
                .handle(PipelineFsmEvent::Journal(Box::new(envelope)), &mut context)
                .await
                .unwrap();
            assert!(matches!(machine.state(), PipelineFsmState::SettlingStages));
            assert!(context.termination.failure.is_some());
        }
    }
}

pub async fn materialisation_reconsiders_readiness_facts_already_consumed(
    make_journals: fn() -> Box<dyn FlowJournalFactory>,
) {
    let system_id = SystemId::new();
    let mut journals = make_journals();
    let journal = new_system_journal(&mut *journals, system_id);
    let (topology, sink) = source_sink_topology();
    let mut context = test_context(topology, system_id, journal.clone(), None);
    context.stage_supervisors.insert(
        sink,
        TestPipelineStageHandle::boxed(sink, "sink", StageType::Sink),
    );
    let mut machine =
        crate::pipeline::fsm::build_pipeline_fsm_with_initial(PipelineFsmState::Materializing);
    let envelope = journal
        .append(SystemEvent::stage_running(sink), Default::default())
        .await
        .unwrap();
    assert!(machine
        .handle(PipelineFsmEvent::Journal(Box::new(envelope)), &mut context)
        .await
        .unwrap()
        .is_empty());
    let actions = machine
        .handle(PipelineFsmEvent::PhysicalSettlementSatisfied, &mut context)
        .await
        .unwrap();
    assert!(matches!(
        machine.state(),
        PipelineFsmState::AwaitingStageReadiness
    ));
    let readiness = actions
        .into_iter()
        .find_map(|action| match action {
            PipelineAction::Publish { event, .. } => Some(*event),
            _ => None,
        })
        .expect("previously consumed Running fact must authorise readiness publication");
    let envelope = journal.append(readiness, Default::default()).await.unwrap();
    machine
        .handle(PipelineFsmEvent::Journal(Box::new(envelope)), &mut context)
        .await
        .unwrap();
    assert!(matches!(machine.state(), PipelineFsmState::ReadyForRun));
}