obzenflow_runtime 0.2.5

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
// SPDX-License-Identifier: MIT OR Apache-2.0
// SPDX-FileCopyrightText: 2025-2026 ObzenFlow Contributors
// https://obzenflow.dev

use super::binding::EffectPortSlotLabel;
use super::*;

#[derive(Debug, Clone, Error)]
pub enum EffectError {
    #[error("{fault}")]
    BindingAuthority { fault: BindingAuthorityFault },

    #[error("effect serialization failed: {0}")]
    Serialization(String),

    #[error("effect journal write failed: {0}")]
    Journal(String),

    #[error("missing recorded effect for cursor {cursor:?}")]
    MissingRecordedEffect { cursor: EffectCursor },

    #[error(
        "effect cursor {cursor:?} is in doubt after durable attempt {highest_started_attempt}"
    )]
    EffectInDoubt {
        cursor: EffectCursor,
        highest_started_attempt: EffectAttemptOrdinal,
    },

    #[error("duplicate recorded effect for cursor {cursor:?}")]
    DuplicateRecordedEffect { cursor: EffectCursor },

    #[error("effect descriptor mismatch for cursor {cursor:?}: expected {expected}, recorded {recorded}")]
    DescriptorMismatch {
        cursor: EffectCursor,
        expected: EffectDescriptorHash,
        recorded: EffectDescriptorHash,
    },

    #[error("recorded effect failure: {error_type}: {error_message}")]
    RecordedFailure {
        error_type: EffectFailureKind,
        error_message: String,
        retry: RetryDisposition,
        cause: Option<EffectFailureCause>,
        detail: Option<Box<EffectFailureDetail>>,
    },

    #[error("effect rejected at boundary by {rejected_by}: {code}: {message}")]
    BoundaryRejected {
        rejected_by: EffectFailureSource,
        code: EffectFailureCode,
        message: String,
        retry: RetryDisposition,
    },

    #[error("effect provenance mismatch: {0}")]
    EffectProvenanceMismatch(String),

    #[error(
        "incomplete effect outcome group for cursor {cursor:?}: {present} of {expected} facts present"
    )]
    IncompleteOutcomeGroup {
        cursor: EffectCursor,
        expected: usize,
        present: usize,
    },

    #[error("non-idempotent effect '{effect_type}' has no idempotency key")]
    MissingIdempotencyKey { effect_type: String },

    #[error("effectful stage '{stage_key}' performed undeclared effect '{effect_type}'")]
    UndeclaredEffect {
        stage_key: String,
        effect_type: String,
    },

    #[error("effectful stage '{stage_key}' emitted undeclared output fact '{event_type}'")]
    UndeclaredOutput {
        stage_key: String,
        event_type: String,
    },

    #[error("effectful stage '{stage_key}' cannot emit output facts from this handler context")]
    EmitUnsupported { stage_key: String },

    #[error("effectful stage '{stage_key}' completed without authoring an output fact")]
    CompletedWithoutOutput { stage_key: String },

    #[error(
        "effectful stage '{stage_key}' used complete_empty after committing {committed} output facts"
    )]
    CompletedEmptyWithOutput { stage_key: String, committed: usize },

    #[error("effect target invariant failed for slot '{slot}'")]
    EffectTargetInvariantViolation { slot: EffectPortSlotLabel },

    #[error("effect dependency '{failure_source}' failed ({code}): {message}")]
    DependencyFailed {
        failure_source: EffectFailureSource,
        code: EffectFailureCode,
        message: String,
        retry: RetryDisposition,
    },

    #[error(
        "effect recovery abandoned after attempt {last_started_attempt} by {failure_source} ({code}): {message}"
    )]
    RecoveryAbandoned {
        last_started_attempt: EffectAttemptOrdinal,
        failure_source: EffectFailureSource,
        code: EffectFailureCode,
        message: String,
        boundary_retry: RetryDisposition,
    },

    #[error(
        "transactional effect '{effect_type}' using executor '{executor}' returned without committing an effect result"
    )]
    TransactionalCommitMissing {
        effect_type: String,
        executor: String,
    },

    /// Legacy opaque call failure. Circuit-breaker recovery treats it as
    /// permanent and ineligible; effect ports should author a typed variant.
    #[error("effect execution failed: {0}")]
    Execution(String),

    /// The physical call exceeded its operation timeout.
    #[error("effect call timed out: {0}")]
    Timeout(String),

    /// The physical call failed at the transport boundary.
    #[error("effect call transport failed: {0}")]
    Transport(String),

    /// The dependency refused the call and supplied a minimum retry delay.
    #[error("effect call was rate limited: {message}")]
    RateLimited {
        message: String,
        retry_after: Duration,
    },

    /// The physical call failed in a way another call cannot repair.
    #[error("effect call failed permanently: {0}")]
    Permanent(String),

    /// The dependency rejected invalid call input.
    #[error("effect call validation failed: {0}")]
    Validation(String),

    /// The dependency returned a domain-level failure.
    #[error("effect call domain failure: {0}")]
    Domain(String),

    #[error("effect replay archive failed: {0}")]
    ReplayArchive(String),
}

impl EffectError {
    /// Construct a target-invariant failure from a validated typed slot.
    pub fn target_invariant_violation<P, M>(slot: EffectPortSlot<P, M>) -> Self
    where
        P: ?Sized + Send + Sync + 'static,
        M: Send + Sync + 'static,
    {
        Self::EffectTargetInvariantViolation {
            slot: slot.diagnostic_label(),
        }
    }

    fn recovery_eligible_by_default(&self) -> bool {
        match self {
            EffectError::BindingAuthority { .. } => false,
            EffectError::RecordedFailure { retry, .. }
            | EffectError::BoundaryRejected { retry, .. }
            | EffectError::DependencyFailed { retry, .. } => retry.is_retryable(),
            EffectError::RecoveryAbandoned { .. }
            | EffectError::EffectTargetInvariantViolation { .. } => false,
            EffectError::EffectProvenanceMismatch(_) => false,
            EffectError::IncompleteOutcomeGroup { .. } => false,
            EffectError::MissingRecordedEffect { .. }
            | EffectError::EffectInDoubt { .. }
            | EffectError::DuplicateRecordedEffect { .. }
            | EffectError::DescriptorMismatch { .. }
            | EffectError::MissingIdempotencyKey { .. }
            | EffectError::UndeclaredEffect { .. }
            | EffectError::UndeclaredOutput { .. }
            | EffectError::EmitUnsupported { .. }
            | EffectError::CompletedWithoutOutput { .. }
            | EffectError::CompletedEmptyWithOutput { .. }
            | EffectError::TransactionalCommitMissing { .. } => false,
            EffectError::Timeout(_)
            | EffectError::Transport(_)
            | EffectError::RateLimited { .. }
            | EffectError::Serialization(_)
            | EffectError::Journal(_)
            | EffectError::Execution(_)
            | EffectError::ReplayArchive(_) => true,
            EffectError::Permanent(_) | EffectError::Validation(_) | EffectError::Domain(_) => {
                false
            }
        }
    }

    pub(super) fn retry_disposition(&self) -> RetryDisposition {
        RetryDisposition::from_bool(self.recovery_eligible_by_default())
    }

    pub(super) fn error_type(&self) -> EffectFailureKind {
        match self {
            EffectError::BindingAuthority { .. } => "binding_authority_fault",
            EffectError::Serialization(_) => "serialization",
            EffectError::Journal(_) => "journal",
            EffectError::MissingRecordedEffect { .. } => "missing_recorded_effect",
            EffectError::EffectInDoubt { .. } => "effect_in_doubt",
            EffectError::DuplicateRecordedEffect { .. } => "duplicate_recorded_effect",
            EffectError::DescriptorMismatch { .. } => "descriptor_mismatch",
            EffectError::RecordedFailure { error_type, .. } => return error_type.clone(),
            EffectError::BoundaryRejected { .. } => "boundary_rejected",
            EffectError::EffectProvenanceMismatch(_) => "effect_provenance_mismatch",
            EffectError::IncompleteOutcomeGroup { .. } => "incomplete_outcome_group",
            EffectError::MissingIdempotencyKey { .. } => "missing_idempotency_key",
            EffectError::UndeclaredEffect { .. } => "undeclared_effect",
            EffectError::UndeclaredOutput { .. } => "undeclared_output",
            EffectError::EmitUnsupported { .. } => "emit_unsupported",
            EffectError::CompletedWithoutOutput { .. } => "completed_without_output",
            EffectError::CompletedEmptyWithOutput { .. } => "completed_empty_with_output",
            EffectError::EffectTargetInvariantViolation { .. } => "target_invariant_violation",
            EffectError::DependencyFailed { code, .. } => return code.as_str().into(),
            EffectError::RecoveryAbandoned { .. } => "recovery_abandoned",
            EffectError::TransactionalCommitMissing { .. } => "transactional_commit_missing",
            EffectError::Execution(_) => "execution",
            EffectError::Timeout(_) => "timeout",
            EffectError::Transport(_) => "transport",
            EffectError::RateLimited { .. } => "rate_limited",
            EffectError::Permanent(_) => "permanent",
            EffectError::Validation(_) => "validation",
            EffectError::Domain(_) => "domain",
            EffectError::ReplayArchive(_) => "replay_archive",
        }
        .into()
    }

    /// The business-facing failure reason, identical live and replayed
    /// (FLOWIP-120i).
    ///
    /// A live `Execution("gateway_timeout_simulated")` and the
    /// `RecordedFailure` its journaled outcome rehydrates to on replay both
    /// project to `"gateway_timeout_simulated"`, so failure-mapping code has
    /// one path and never parses Display wrappers. Variants carrying a
    /// semantic message borrow it; infrastructure variants with structured
    /// fields fall back to their Display rendering.
    pub fn semantic_reason(&self) -> std::borrow::Cow<'_, str> {
        match self {
            EffectError::Execution(message)
            | EffectError::Timeout(message)
            | EffectError::Transport(message)
            | EffectError::Permanent(message)
            | EffectError::Validation(message)
            | EffectError::Domain(message)
            | EffectError::Serialization(message)
            | EffectError::Journal(message)
            | EffectError::ReplayArchive(message)
            | EffectError::EffectProvenanceMismatch(message) => std::borrow::Cow::Borrowed(message),
            EffectError::RecordedFailure { error_message, .. } => {
                std::borrow::Cow::Borrowed(error_message)
            }
            EffectError::RateLimited { message, .. } => std::borrow::Cow::Borrowed(message),
            EffectError::BoundaryRejected { message, .. } => std::borrow::Cow::Borrowed(message),
            EffectError::DependencyFailed { message, .. }
            | EffectError::RecoveryAbandoned { message, .. } => std::borrow::Cow::Borrowed(message),
            EffectError::BindingAuthority { .. }
            | EffectError::MissingRecordedEffect { .. }
            | EffectError::EffectInDoubt { .. }
            | EffectError::DuplicateRecordedEffect { .. }
            | EffectError::DescriptorMismatch { .. }
            | EffectError::IncompleteOutcomeGroup { .. }
            | EffectError::MissingIdempotencyKey { .. }
            | EffectError::UndeclaredEffect { .. }
            | EffectError::UndeclaredOutput { .. }
            | EffectError::EmitUnsupported { .. }
            | EffectError::CompletedWithoutOutput { .. }
            | EffectError::CompletedEmptyWithOutput { .. }
            | EffectError::EffectTargetInvariantViolation { .. }
            | EffectError::TransactionalCommitMissing { .. } => {
                std::borrow::Cow::Owned(self.to_string())
            }
        }
    }

    /// The message recorded into a `Failed` outcome payload. The semantic
    /// reason, never the Display wrapper: recording `self.to_string()` here
    /// baked "effect execution failed: " into journaled facts, which replay
    /// then surfaced to user code as a different business payload than the
    /// live run produced (the FLOWIP-120i wrapper leak).
    pub(super) fn error_message(&self) -> String {
        self.semantic_reason().into_owned()
    }

    /// Structured cause carried into a recorded `Failed` outcome, present when
    /// execution was rejected by a named component such as boundary middleware.
    /// Live `BoundaryRejected` errors and replayed `RecordedFailure` errors
    /// return the same source/code pair.
    pub fn failure_cause(&self) -> Option<EffectFailureCause> {
        match self {
            EffectError::BoundaryRejected {
                rejected_by, code, ..
            } => Some(EffectFailureCause {
                source: rejected_by.clone(),
                code: code.clone(),
            }),
            EffectError::RecordedFailure { cause, .. } => cause.clone(),
            EffectError::DependencyFailed {
                failure_source,
                code,
                ..
            }
            | EffectError::RecoveryAbandoned {
                failure_source,
                code,
                ..
            } => Some(EffectFailureCause {
                source: failure_source.clone(),
                code: code.clone(),
            }),
            _ => None,
        }
    }

    pub fn failure_detail(&self) -> Option<EffectFailureDetail> {
        match self {
            Self::EffectTargetInvariantViolation { slot } => {
                Some(EffectFailureDetail::PortBindingInvariantViolation {
                    port: slot.as_str().to_string(),
                    expected: "<not disclosed>".to_string(),
                    observed: "<not disclosed>".to_string(),
                })
            }
            Self::RecordedFailure { detail, .. } => detail.as_deref().cloned(),
            _ => None,
        }
    }
}

impl From<ReplayError> for EffectError {
    fn from(value: ReplayError) -> Self {
        Self::ReplayArchive(value.to_string())
    }
}

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

    /// FLOWIP-120i: the semantic reason is identical across the live error,
    /// what gets recorded, and the replay-side rehydration, with no Display
    /// wrapper anywhere in the chain.
    #[test]
    fn semantic_reason_is_stable_across_live_recording_and_replay() {
        let live = EffectError::Execution("gateway_timeout_simulated".to_string());
        assert_eq!(live.semantic_reason(), "gateway_timeout_simulated");
        assert_eq!(live.error_message(), "gateway_timeout_simulated");

        // What replay rehydrates from the recorded Failed payload.
        let replayed = EffectError::RecordedFailure {
            error_type: live.error_type(),
            error_message: live.error_message(),
            retry: live.retry_disposition(),
            cause: live.failure_cause(),
            detail: live.failure_detail().map(Box::new),
        };
        assert_eq!(replayed.semantic_reason(), live.semantic_reason());
        assert_eq!(
            replayed.error_message(),
            "gateway_timeout_simulated",
            "re-recording a recorded failure must not wrap again"
        );
        assert!(
            !replayed
                .semantic_reason()
                .contains("effect execution failed"),
            "no Display wrapper may leak into the semantic reason"
        );
    }

    #[test]
    fn semantic_reason_projects_boundary_rejections_to_their_message() {
        let rejected = EffectError::BoundaryRejected {
            rejected_by: EffectFailureSource::new("effect_boundary"),
            code: EffectFailureCode::new("breaker_open"),
            message: "circuit breaker open".to_string(),
            retry: RetryDisposition::from_bool(true),
        };
        assert_eq!(rejected.semantic_reason(), "circuit breaker open");
        assert_eq!(
            rejected.error_message(),
            "circuit breaker open",
            "structured source and code live in the recorded cause, never the message"
        );
        assert!(rejected.failure_cause().is_some());
    }

    #[test]
    fn semantic_reason_falls_back_to_display_for_infrastructure_variants() {
        let infra = EffectError::MissingIdempotencyKey {
            effect_type: "demo.effect".to_string(),
        };
        assert_eq!(infra.semantic_reason(), infra.to_string());
    }
}