runifold-effect 0.3.2

Write-ahead external-effect coordination for Runifold
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
use std::sync::Arc;

use futures_util::future::{Either, select};
use runifold_core::{
    EffectClass, EffectEvent, EffectId, EffectRequest, Instant, RetrySafety, RunContext, RunError,
    RunEventKind,
};
use serde_json::Value;

use crate::{
    EffectExecutionContext, EffectExecutorError, EffectExecutorErrorKind, EffectHandler,
    EffectReconciler, EffectReconciliation, EffectRecord, EffectStatus, EffectStore,
};

/// Recovery behavior for a record whose handler may have executed.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum EffectRecoveryPolicy {
    /// Never retry an ambiguous started effect automatically.
    #[default]
    RejectAmbiguous,
    /// Retry only effects whose class and idempotency contract make it safe.
    RetrySafe,
}

/// Controls whether effect outputs are copied into Journal events.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum EffectEventPayloadPolicy {
    /// Keep durable output only in the `EffectStore`.
    #[default]
    Redacted,
    /// Copy the complete output into `EffectEvent::Completed`.
    Full,
}

/// Successful coordinated effect result.
#[derive(Clone, Debug, PartialEq)]
pub struct EffectOutcome {
    /// Canonical logical effect identity.
    pub effect_id: EffectId,
    /// Canonical output.
    pub output: Value,
    /// Whether the output came from a completed durable record.
    pub replayed: bool,
    /// Durable record revision containing the output.
    pub revision: u64,
}

/// Capability-gated write-ahead external-effect coordinator.
#[derive(Clone)]
pub struct EffectExecutor {
    store: Arc<dyn EffectStore>,
    event_payload_policy: EffectEventPayloadPolicy,
}

impl EffectExecutor {
    /// Creates an executor using the given durable-state boundary.
    pub fn new(store: Arc<dyn EffectStore>) -> Self {
        Self {
            store,
            event_payload_policy: EffectEventPayloadPolicy::Redacted,
        }
    }

    /// Sets explicit Journal output-capture behavior.
    #[must_use]
    pub const fn with_event_payload_policy(mut self, policy: EffectEventPayloadPolicy) -> Self {
        self.event_payload_policy = policy;
        self
    }

    /// Executes or recovers one logical effect.
    ///
    /// # Errors
    ///
    /// Returns [`EffectExecutorError`] for authority, persistence, lifecycle,
    /// ambiguity, handler, or observability failures.
    pub async fn execute(
        &self,
        request: EffectRequest,
        run: &RunContext,
        handler: &dyn EffectHandler,
        recovery: EffectRecoveryPolicy,
    ) -> Result<EffectOutcome, EffectExecutorError> {
        self.execute_inner(request, run, handler, recovery, None)
            .await
    }

    /// Executes an effect and consults a remote-state reconciler before
    /// deciding whether an ambiguously started record may be retried.
    ///
    /// This closes the common crash window where the remote side committed but
    /// the local `Completed` record did not. It does not create a distributed
    /// transaction: unresolved remote state still returns `Ambiguous`.
    ///
    /// # Errors
    ///
    /// Returns [`EffectExecutorError`] for authority, persistence, lifecycle,
    /// reconciliation, ambiguity, handler, or observability failures.
    pub async fn execute_reconciled(
        &self,
        request: EffectRequest,
        run: &RunContext,
        handler: &dyn EffectHandler,
        reconciler: &dyn EffectReconciler,
        recovery: EffectRecoveryPolicy,
    ) -> Result<EffectOutcome, EffectExecutorError> {
        self.execute_inner(request, run, handler, recovery, Some(reconciler))
            .await
    }

    async fn execute_inner(
        &self,
        request: EffectRequest,
        run: &RunContext,
        handler: &dyn EffectHandler,
        recovery: EffectRecoveryPolicy,
        reconciler: Option<&dyn EffectReconciler>,
    ) -> Result<EffectOutcome, EffectExecutorError> {
        preflight(&request, run)?;
        let (record, created) = self.resolve(request)?;
        if created {
            record_event(
                run,
                RunEventKind::Effect(EffectEvent::Requested {
                    effect_id: record.request.effect_id,
                }),
            )?;
        }
        match &record.status {
            EffectStatus::Completed { output } => Ok(EffectOutcome {
                effect_id: record.request.effect_id,
                output: output.clone(),
                replayed: true,
                revision: record.revision,
            }),
            EffectStatus::Failed { error } => Err(EffectExecutorError::handler(error.clone())),
            EffectStatus::Prepared => self.start(record, run, handler).await,
            EffectStatus::Started => {
                if let Some(reconciler) = reconciler {
                    match self.reconcile(&record, run, reconciler).await? {
                        EffectReconciliation::Completed(output) => {
                            let mut outcome = self.complete(&record, output, run)?;
                            outcome.replayed = true;
                            return Ok(outcome);
                        }
                        EffectReconciliation::NotExecuted => {
                            return self.start(record, run, handler).await;
                        }
                        EffectReconciliation::Ambiguous => {}
                    }
                }
                if recovery != EffectRecoveryPolicy::RetrySafe || !retry_safe(&record.request) {
                    return Err(EffectExecutorError::new(
                        EffectExecutorErrorKind::Ambiguous,
                        format!(
                            "effect `{}` may already have executed",
                            record.request.effect_id
                        ),
                    ));
                }
                self.start(record, run, handler).await
            }
        }
    }

    async fn reconcile(
        &self,
        record: &EffectRecord,
        run: &RunContext,
        reconciler: &dyn EffectReconciler,
    ) -> Result<EffectReconciliation, EffectExecutorError> {
        let context = EffectExecutionContext::for_run(run);
        let cancellation = context.cancellation().clone();
        let reconciliation = reconciler.reconcile(&record.request, context);
        match select(Box::pin(cancellation.cancelled()), Box::pin(reconciliation)).await {
            Either::Left(_) => Err(EffectExecutorError::new(
                EffectExecutorErrorKind::Cancelled,
                "effect reconciliation was cancelled and remains ambiguous",
            )),
            Either::Right((result, _)) => result.map_err(EffectExecutorError::reconciliation),
        }
    }

    fn resolve(&self, request: EffectRequest) -> Result<(EffectRecord, bool), EffectExecutorError> {
        if let Some(record) = self.store.load(request.effect_id)? {
            validate_same_effect(&record.request, &request)?;
            return Ok((record, false));
        }
        if let Some(key) = &request.idempotency_key
            && let Some(record) = self.store.find_by_idempotency(request.capability_id, key)?
        {
            validate_same_effect(&record.request, &request)?;
            return Ok((record, false));
        }
        let record = EffectRecord::prepared(request);
        self.store.compare_and_swap(&record, None)?;
        Ok((record, true))
    }

    async fn start(
        &self,
        record: EffectRecord,
        run: &RunContext,
        handler: &dyn EffectHandler,
    ) -> Result<EffectOutcome, EffectExecutorError> {
        let started = record.next(EffectStatus::Started)?;
        self.store
            .compare_and_swap(&started, Some(record.revision))?;
        record_event(
            run,
            RunEventKind::Effect(EffectEvent::Started {
                effect_id: started.request.effect_id,
            }),
        )?;

        let context = EffectExecutionContext::for_run(run);
        let cancellation = context.cancellation().clone();
        let execution = handler.execute(&started.request, context);
        let result = match select(Box::pin(cancellation.cancelled()), Box::pin(execution)).await {
            Either::Left(_) => {
                return Err(EffectExecutorError::new(
                    EffectExecutorErrorKind::Cancelled,
                    "effect execution was cancelled and remains ambiguous",
                ));
            }
            Either::Right((result, _)) => result,
        };

        match result {
            Ok(output) => self.complete(&started, output, run),
            Err(error) if outcome_is_ambiguous(&error) => {
                Err(EffectExecutorError::ambiguous_handler(error))
            }
            Err(error) => self.fail(&started, error, run),
        }
    }

    fn complete(
        &self,
        started: &EffectRecord,
        output: Value,
        run: &RunContext,
    ) -> Result<EffectOutcome, EffectExecutorError> {
        let completed = started.next(EffectStatus::Completed {
            output: output.clone(),
        })?;
        self.store
            .compare_and_swap(&completed, Some(started.revision))?;
        record_event(
            run,
            RunEventKind::Effect(EffectEvent::Completed {
                effect_id: completed.request.effect_id,
                output: match self.event_payload_policy {
                    EffectEventPayloadPolicy::Redacted => {
                        serde_json::json!({"runifold": {"content_recorded": false}})
                    }
                    EffectEventPayloadPolicy::Full => output.clone(),
                },
            }),
        )?;
        Ok(EffectOutcome {
            effect_id: completed.request.effect_id,
            output,
            replayed: false,
            revision: completed.revision,
        })
    }

    fn fail(
        &self,
        started: &EffectRecord,
        error: RunError,
        run: &RunContext,
    ) -> Result<EffectOutcome, EffectExecutorError> {
        let failed = started.next(EffectStatus::Failed {
            error: error.clone(),
        })?;
        self.store
            .compare_and_swap(&failed, Some(started.revision))?;
        record_event(
            run,
            RunEventKind::Effect(EffectEvent::Failed {
                effect_id: failed.request.effect_id,
                error: error.clone(),
            }),
        )?;
        Err(EffectExecutorError::handler(error))
    }
}

impl std::fmt::Debug for EffectExecutor {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("EffectExecutor(..)")
    }
}

fn preflight(request: &EffectRequest, run: &RunContext) -> Result<(), EffectExecutorError> {
    if !run.capabilities().contains(request.capability_id) {
        return Err(EffectExecutorError::new(
            EffectExecutorErrorKind::CapabilityDenied,
            "Run is not granted the effect capability",
        ));
    }
    if run.cancellation().is_cancelled() {
        return Err(EffectExecutorError::new(
            EffectExecutorErrorKind::Cancelled,
            "effect was cancelled before preparation",
        ));
    }
    if run
        .deadline()
        .is_some_and(|deadline| deadline <= Instant::now())
    {
        return Err(EffectExecutorError::new(
            EffectExecutorErrorKind::DeadlineExceeded,
            "effect deadline elapsed before preparation",
        ));
    }
    Ok(())
}

fn validate_same_effect(
    existing: &EffectRequest,
    requested: &EffectRequest,
) -> Result<(), EffectExecutorError> {
    let same = existing.kind == requested.kind
        && existing.capability_id == requested.capability_id
        && existing.input == requested.input
        && existing.effect_class == requested.effect_class
        && existing.idempotency_key == requested.idempotency_key;
    if !same {
        return Err(EffectExecutorError::new(
            EffectExecutorErrorKind::IdempotencyConflict,
            "effect identity or idempotency key was reused for different work",
        ));
    }
    Ok(())
}

fn retry_safe(request: &EffectRequest) -> bool {
    matches!(
        request.effect_class,
        EffectClass::Pure | EffectClass::ReadOnly
    ) || matches!(request.effect_class, EffectClass::IdempotentWrite)
        && request.idempotency_key.is_some()
}

fn outcome_is_ambiguous(error: &RunError) -> bool {
    matches!(
        error.retry_safety,
        RetrySafety::RequiresIdempotency
            | RetrySafety::UnsafeAfterVisibleOutput
            | RetrySafety::UnsafeAfterSideEffect
            | RetrySafety::Unknown
    )
}

fn record_event(run: &RunContext, kind: RunEventKind) -> Result<(), EffectExecutorError> {
    run.record(kind, None)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::{
        collections::BTreeMap,
        sync::{
            Arc,
            atomic::{AtomicUsize, Ordering},
        },
    };

    use runifold_core::{
        Budget, BudgetTracker, CapabilityDescriptor, CapabilityId, CapabilityKind, CapabilitySet,
        EffectClass, EffectEvent, EffectId, EffectKind, EffectRequest, InMemoryJournal,
        InvocationId, RetrySafety, RiskLevel, RunContext, RunError, RunErrorKind, RunEventKind,
    };
    use serde_json::{Value, json};

    use crate::{
        EffectEventPayloadPolicy, EffectExecutionContext, EffectExecutor, EffectExecutorErrorKind,
        EffectFuture, EffectHandler, EffectReconciler, EffectReconciliation, EffectRecord,
        EffectRecoveryPolicy, EffectStatus, EffectStore, InMemoryEffectStore,
    };

    struct CountingHandler {
        calls: AtomicUsize,
    }

    impl CountingHandler {
        fn new() -> Self {
            Self {
                calls: AtomicUsize::new(0),
            }
        }
    }

    impl EffectHandler for CountingHandler {
        fn execute(
            &self,
            request: &EffectRequest,
            _context: EffectExecutionContext,
        ) -> EffectFuture<'_, Result<Value, RunError>> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            let input = request.input.clone();
            Box::pin(async move { Ok(json!({"echo": input})) })
        }
    }

    struct AmbiguousHandler;

    impl EffectHandler for AmbiguousHandler {
        fn execute(
            &self,
            _request: &EffectRequest,
            _context: EffectExecutionContext,
        ) -> EffectFuture<'_, Result<Value, RunError>> {
            Box::pin(async {
                Err(RunError {
                    kind: RunErrorKind::Transport,
                    message: "connection closed after request body was sent".into(),
                    retry_safety: RetrySafety::UnsafeAfterSideEffect,
                    metadata: BTreeMap::new(),
                })
            })
        }
    }

    struct CompletedReconciler;

    impl EffectReconciler for CompletedReconciler {
        fn reconcile(
            &self,
            _request: &EffectRequest,
            _context: EffectExecutionContext,
        ) -> EffectFuture<'_, Result<EffectReconciliation, RunError>> {
            Box::pin(async {
                Ok(EffectReconciliation::Completed(
                    json!({"remote": "committed"}),
                ))
            })
        }
    }

    struct FixedReconciler(EffectReconciliation);

    impl EffectReconciler for FixedReconciler {
        fn reconcile(
            &self,
            _request: &EffectRequest,
            _context: EffectExecutionContext,
        ) -> EffectFuture<'_, Result<EffectReconciliation, RunError>> {
            let outcome = self.0.clone();
            Box::pin(async move { Ok(outcome) })
        }
    }

    struct FailedReconciler;

    impl EffectReconciler for FailedReconciler {
        fn reconcile(
            &self,
            _request: &EffectRequest,
            _context: EffectExecutionContext,
        ) -> EffectFuture<'_, Result<EffectReconciliation, RunError>> {
            Box::pin(async {
                Err(RunError {
                    kind: RunErrorKind::Transport,
                    message: "remote lookup unavailable".into(),
                    retry_safety: RetrySafety::Unknown,
                    metadata: BTreeMap::new(),
                })
            })
        }
    }

    #[test]
    fn completed_idempotent_effect_is_replayed_without_handler_execution() {
        let capability = capability(EffectClass::IdempotentWrite);
        let journal = InMemoryJournal::new();
        let run = run_with(&capability, Some(journal.clone()));
        let store = Arc::new(InMemoryEffectStore::new());
        let executor = EffectExecutor::new(store);
        let handler = CountingHandler::new();
        let first_request = request(&capability, Some("order-7"), json!({"value": 7}));

        let first = futures_executor::block_on(executor.execute(
            first_request.clone(),
            &run,
            &handler,
            EffectRecoveryPolicy::RejectAmbiguous,
        ))
        .unwrap();
        let mut duplicate = first_request;
        duplicate.effect_id = EffectId::new();
        duplicate.invocation_id = InvocationId::new();
        let second = futures_executor::block_on(executor.execute(
            duplicate,
            &run,
            &handler,
            EffectRecoveryPolicy::RejectAmbiguous,
        ))
        .unwrap();

        assert!(!first.replayed);
        assert!(second.replayed);
        assert_eq!(second.effect_id, first.effect_id);
        assert_eq!(handler.calls.load(Ordering::SeqCst), 1);
        let events = journal.events();
        assert!(matches!(
            events[0].kind,
            RunEventKind::Effect(EffectEvent::Requested { .. })
        ));
        assert!(matches!(
            events.last().unwrap().kind,
            RunEventKind::Effect(EffectEvent::Completed { .. })
        ));
        assert!(matches!(
            &events.last().unwrap().kind,
            RunEventKind::Effect(EffectEvent::Completed { output, .. })
                if output == &json!({"runifold": {"content_recorded": false}})
        ));
    }

    #[test]
    fn full_event_payload_capture_requires_explicit_opt_in() {
        let capability = capability(EffectClass::Pure);
        let journal = InMemoryJournal::new();
        let run = run_with(&capability, Some(journal.clone()));
        let executor = EffectExecutor::new(Arc::new(InMemoryEffectStore::new()))
            .with_event_payload_policy(EffectEventPayloadPolicy::Full);
        let handler = CountingHandler::new();

        futures_executor::block_on(executor.execute(
            request(&capability, None, json!("secret")),
            &run,
            &handler,
            EffectRecoveryPolicy::RejectAmbiguous,
        ))
        .unwrap();

        assert!(matches!(
            &journal.events().last().unwrap().kind,
            RunEventKind::Effect(EffectEvent::Completed { output, .. })
                if output == &json!({"echo": "secret"})
        ));
    }

    #[test]
    fn idempotency_key_cannot_be_reused_for_different_input() {
        let capability = capability(EffectClass::IdempotentWrite);
        let run = run_with(&capability, None);
        let executor = EffectExecutor::new(Arc::new(InMemoryEffectStore::new()));
        let handler = CountingHandler::new();
        let first = request(&capability, Some("same-key"), json!({"value": 1}));
        futures_executor::block_on(executor.execute(
            first,
            &run,
            &handler,
            EffectRecoveryPolicy::RejectAmbiguous,
        ))
        .unwrap();
        let second = request(&capability, Some("same-key"), json!({"value": 2}));

        let error = futures_executor::block_on(executor.execute(
            second,
            &run,
            &handler,
            EffectRecoveryPolicy::RejectAmbiguous,
        ))
        .unwrap_err();

        assert_eq!(error.kind, EffectExecutorErrorKind::IdempotencyConflict);
        assert_eq!(handler.calls.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn ambiguous_non_idempotent_effect_is_never_retried() {
        let capability = capability(EffectClass::NonIdempotentWrite);
        let run = run_with(&capability, None);
        let store = Arc::new(InMemoryEffectStore::new());
        let request = request(&capability, None, json!({"charge": 10}));
        let prepared = EffectRecord::prepared(request.clone());
        store.compare_and_swap(&prepared, None).unwrap();
        let started = prepared.next(EffectStatus::Started).unwrap();
        store.compare_and_swap(&started, Some(0)).unwrap();
        let executor = EffectExecutor::new(store);
        let handler = CountingHandler::new();

        let error = futures_executor::block_on(executor.execute(
            request,
            &run,
            &handler,
            EffectRecoveryPolicy::RetrySafe,
        ))
        .unwrap_err();

        assert_eq!(error.kind, EffectExecutorErrorKind::Ambiguous);
        assert_eq!(handler.calls.load(Ordering::SeqCst), 0);
    }

    #[test]
    fn remote_reconciliation_closes_completed_but_unrecorded_crash_window() {
        let capability = capability(EffectClass::NonIdempotentWrite);
        let run = run_with(&capability, None);
        let store = Arc::new(InMemoryEffectStore::new());
        let request = request(
            &capability,
            Some("remote-operation-7"),
            json!({"charge": 10}),
        );
        let prepared = EffectRecord::prepared(request.clone());
        store.compare_and_swap(&prepared, None).unwrap();
        let started = prepared.next(EffectStatus::Started).unwrap();
        store.compare_and_swap(&started, Some(0)).unwrap();
        let executor = EffectExecutor::new(store.clone());
        let handler = CountingHandler::new();

        let outcome = futures_executor::block_on(executor.execute_reconciled(
            request,
            &run,
            &handler,
            &CompletedReconciler,
            EffectRecoveryPolicy::RejectAmbiguous,
        ))
        .unwrap();

        assert!(outcome.replayed);
        assert_eq!(outcome.output, json!({"remote": "committed"}));
        assert_eq!(handler.calls.load(Ordering::SeqCst), 0);
        assert!(matches!(
            store.load(outcome.effect_id).unwrap().unwrap().status,
            EffectStatus::Completed { .. }
        ));
    }

    #[test]
    fn uncertain_handler_failure_stays_started_until_remote_reconciliation() {
        let capability = capability(EffectClass::IdempotentWrite);
        let run = run_with(&capability, None);
        let store = Arc::new(InMemoryEffectStore::new());
        let executor = EffectExecutor::new(store.clone());
        let request = request(
            &capability,
            Some("remote-operation-response-loss"),
            json!({"charge": 10}),
        );

        let error = futures_executor::block_on(executor.execute(
            request.clone(),
            &run,
            &AmbiguousHandler,
            EffectRecoveryPolicy::RejectAmbiguous,
        ))
        .unwrap_err();
        assert_eq!(error.kind, EffectExecutorErrorKind::Ambiguous);
        assert!(matches!(
            store.load(request.effect_id).unwrap().unwrap().status,
            EffectStatus::Started
        ));

        let outcome = futures_executor::block_on(executor.execute_reconciled(
            request,
            &run,
            &CountingHandler::new(),
            &CompletedReconciler,
            EffectRecoveryPolicy::RejectAmbiguous,
        ))
        .unwrap();
        assert!(outcome.replayed);
        assert_eq!(outcome.output, json!({"remote": "committed"}));
    }

    #[test]
    fn reconciliation_reexecutes_only_after_remote_not_executed_proof() {
        let capability = capability(EffectClass::NonIdempotentWrite);
        let run = run_with(&capability, None);
        let store = Arc::new(InMemoryEffectStore::new());
        let request = request(
            &capability,
            Some("remote-operation-8"),
            json!({"charge": 11}),
        );
        let prepared = EffectRecord::prepared(request.clone());
        store.compare_and_swap(&prepared, None).unwrap();
        let started = prepared.next(EffectStatus::Started).unwrap();
        store.compare_and_swap(&started, Some(0)).unwrap();
        let executor = EffectExecutor::new(store);
        let handler = CountingHandler::new();

        let outcome = futures_executor::block_on(executor.execute_reconciled(
            request,
            &run,
            &handler,
            &FixedReconciler(EffectReconciliation::NotExecuted),
            EffectRecoveryPolicy::RejectAmbiguous,
        ))
        .unwrap();

        assert!(!outcome.replayed);
        assert_eq!(handler.calls.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn unresolved_or_failed_reconciliation_never_runs_the_handler() {
        let capability = capability(EffectClass::NonIdempotentWrite);
        let run = run_with(&capability, None);
        let store = Arc::new(InMemoryEffectStore::new());
        let request = request(
            &capability,
            Some("remote-operation-9"),
            json!({"charge": 12}),
        );
        let prepared = EffectRecord::prepared(request.clone());
        store.compare_and_swap(&prepared, None).unwrap();
        let started = prepared.next(EffectStatus::Started).unwrap();
        store.compare_and_swap(&started, Some(0)).unwrap();
        let executor = EffectExecutor::new(store);
        let handler = CountingHandler::new();

        let ambiguous = futures_executor::block_on(executor.execute_reconciled(
            request.clone(),
            &run,
            &handler,
            &FixedReconciler(EffectReconciliation::Ambiguous),
            EffectRecoveryPolicy::RejectAmbiguous,
        ))
        .unwrap_err();
        let failed = futures_executor::block_on(executor.execute_reconciled(
            request,
            &run,
            &handler,
            &FailedReconciler,
            EffectRecoveryPolicy::RejectAmbiguous,
        ))
        .unwrap_err();

        assert_eq!(ambiguous.kind, EffectExecutorErrorKind::Ambiguous);
        assert_eq!(failed.kind, EffectExecutorErrorKind::Reconciliation);
        assert_eq!(handler.calls.load(Ordering::SeqCst), 0);
    }

    #[test]
    fn started_idempotent_effect_can_be_explicitly_reconciled_by_retry() {
        let capability = capability(EffectClass::IdempotentWrite);
        let run = run_with(&capability, None);
        let store = Arc::new(InMemoryEffectStore::new());
        let request = request(&capability, Some("safe-key"), json!({"write": 1}));
        let prepared = EffectRecord::prepared(request.clone());
        store.compare_and_swap(&prepared, None).unwrap();
        let started = prepared.next(EffectStatus::Started).unwrap();
        store.compare_and_swap(&started, Some(0)).unwrap();
        let executor = EffectExecutor::new(store);
        let handler = CountingHandler::new();

        let outcome = futures_executor::block_on(executor.execute(
            request,
            &run,
            &handler,
            EffectRecoveryPolicy::RetrySafe,
        ))
        .unwrap();

        assert_eq!(outcome.revision, 3);
        assert_eq!(handler.calls.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn missing_capability_rejects_before_persistence_or_execution() {
        let capability = capability(EffectClass::Pure);
        let run = RunContext::root(BudgetTracker::new(Budget::default()), CapabilitySet::new());
        let store = Arc::new(InMemoryEffectStore::new());
        let effect = request(&capability, None, json!({}));
        let executor = EffectExecutor::new(store.clone());
        let handler = CountingHandler::new();

        let error = futures_executor::block_on(executor.execute(
            effect.clone(),
            &run,
            &handler,
            EffectRecoveryPolicy::RejectAmbiguous,
        ))
        .unwrap_err();

        assert_eq!(error.kind, EffectExecutorErrorKind::CapabilityDenied);
        assert!(store.load(effect.effect_id).unwrap().is_none());
        assert_eq!(handler.calls.load(Ordering::SeqCst), 0);
    }

    fn capability(effect: EffectClass) -> CapabilityDescriptor {
        CapabilityDescriptor {
            id: CapabilityId::new(),
            name: "test-effect".into(),
            version: "1".into(),
            kind: CapabilityKind::Resource,
            input_schema: json!({}),
            output_schema: json!({}),
            effect,
            risk: RiskLevel::Low,
            metadata: BTreeMap::new(),
        }
    }

    fn request(
        capability: &CapabilityDescriptor,
        key: Option<&str>,
        input: Value,
    ) -> EffectRequest {
        EffectRequest {
            effect_id: EffectId::new(),
            invocation_id: InvocationId::new(),
            kind: EffectKind::Extension("test".into()),
            capability_id: capability.id,
            input,
            effect_class: capability.effect,
            idempotency_key: key.map(str::to_owned),
        }
    }

    fn run_with(capability: &CapabilityDescriptor, journal: Option<InMemoryJournal>) -> RunContext {
        let mut capabilities = CapabilitySet::new();
        capabilities.grant(capability.clone());
        let run = RunContext::root(BudgetTracker::new(Budget::default()), capabilities);
        match journal {
            Some(journal) => run.with_journal(Arc::new(journal)),
            None => run,
        }
    }
}