app-kit 0.0.2

Application and durable workflow composition for ai-kit
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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
//! Serial halt contracts through public execution methods and real LanceDB state.
//!
//! Source-derived oracle from rurr commit 005bfe3ece631e64b06dac2d42ef84235f727a4f,
//! archive SHA-256 5b5f20eb1d233467c600dc9dd249feaaa9046c5a303ae4e937040be5b6ecf25e:
//! application/session.rs:169–210,335–374,489–514; streaming/step_lifecycle.rs:
//! 237–251,441–448; tests/contract/application_run_contract.rs:428–465,546–583;
//! tests/contract/application_streaming_contract/resumed_halts.rs:11–115.
//! App's mixed-method mapping and retained status tuple follow SPECIFICATIONS
//! and WORKFLOW. These are source-derived cases, not executed-rurr evidence.
//! Multiple matching BSP siblings and fresh-process recovery are separate cases.

use std::mem;
use std::panic::AssertUnwindSafe;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use std::time::Duration;

use agents_kit::Agent;
use app_kit::workflow::{
    ActionBackend, ActionDeclaration, ActionEvent, ActionMode, ActionRequest, Execution,
    ExecutionEvent, ExecutionOptions, JsonState, LifecycleEvent, LifecycleHooks, NoConditions,
    RunSelector, RunSnapshot, RunStatus, StateChange, SyncExecution, Workflow, WorkflowDefinition,
    WorkflowRun, WorkflowState,
};
use app_kit::{App, AppConfig, AppError, Shutdown, WorkspaceConfig};
use futures_util::{FutureExt, Stream};
use serde_json::{Map, Value, json};
use storage_kit::StateStore;
use storage_kit::state::config::{LanceStateStoreConfig, StateStoreConfig};
use tokio::sync::futures::OwnedNotified;
use tokio::sync::{Notify, oneshot};

#[derive(Clone, Copy)]
enum Output {
    Counter,
    Empty,
    EofOnce,
    Pending,
}

#[derive(Clone, Copy)]
enum Advance {
    Streaming,
    Ordinary,
}

#[derive(Clone, Copy, Debug)]
enum BlockingMethod {
    Next,
    Step,
    Finish,
    Abort,
}

#[derive(Clone, Debug, PartialEq)]
struct Invocation {
    node: String,
    ordinal: u64,
    mode: ActionMode,
    thread: std::thread::ThreadId,
}

struct CounterAction {
    declaration: ActionDeclaration,
    calls: Arc<Mutex<Vec<Invocation>>>,
    output: Output,
    evidence: Arc<ControlEvidence>,
}

struct CounterSource {
    progress: Progress,
    calls: Arc<Mutex<Vec<Invocation>>>,
    output: Output,
    owner_thread: Rc<std::thread::ThreadId>,
    evidence: Arc<ControlEvidence>,
    pending: Option<Pin<Box<OwnedNotified>>>,
}

enum Progress {
    Ready(Box<ActionRequest>),
    Terminal {
        result: Map<String, Value>,
        writes: Vec<StateChange>,
    },
    Eof,
    Done,
}

struct Controls {
    app: App<StateStore, Agent, CounterAction, NoConditions, JsonState, ControlHooks>,
    workflow: Workflow<StateStore, Agent, CounterAction, NoConditions, JsonState, ControlHooks>,
    calls: Arc<Mutex<Vec<Invocation>>>,
    hooks: Arc<AtomicUsize>,
    async_hooks: Arc<AtomicUsize>,
    evidence: Arc<ControlEvidence>,
}

#[derive(Default)]
struct ControlEvidence {
    sources: Mutex<Vec<(&'static str, std::thread::ThreadId)>>,
    hook_modes: Mutex<Vec<ActionMode>>,
    steps: Mutex<Vec<(String, u64)>>,
    pending: Notify,
    release: Arc<Notify>,
}

impl ControlEvidence {
    fn constructions(&self) -> usize {
        self.sources
            .lock()
            .unwrap()
            .iter()
            .filter(|(event, _)| *event == "construct")
            .count()
    }

    fn source(&self, event: &'static str) {
        self.sources
            .lock()
            .unwrap()
            .push((event, std::thread::current().id()));
    }
}

struct ControlHooks {
    calls: Arc<AtomicUsize>,
    async_calls: Arc<AtomicUsize>,
    evidence: Arc<ControlEvidence>,
}

impl LifecycleHooks for ControlHooks {
    fn observe(&self, event: &LifecycleEvent<'_>) -> Result<(), AppError> {
        self.calls.fetch_add(1, Ordering::SeqCst);
        if let LifecycleEvent::StepStarted { context, .. }
        | LifecycleEvent::StepFinished { context, .. } = event
        {
            self.evidence.hook_modes.lock().unwrap().push(context.mode);
        }
        if let LifecycleEvent::StepStarted { context, .. } = event {
            self.evidence
                .steps
                .lock()
                .unwrap()
                .push((context.node.clone(), context.action_ordinal));
        }
        Ok(())
    }

    async fn observe_async<'a>(&'a self, _event: &'a LifecycleEvent<'a>) -> Result<(), AppError> {
        self.calls.fetch_add(1, Ordering::SeqCst);
        self.async_calls.fetch_add(1, Ordering::SeqCst);
        Ok(())
    }
}

impl CounterAction {
    fn new(
        calls: &Arc<Mutex<Vec<Invocation>>>,
        output: Output,
        evidence: &Arc<ControlEvidence>,
    ) -> Self {
        Self {
            declaration: ActionDeclaration {
                key: "counter".into(),
                revision: "r1".into(),
                reads: vec!["count".into()],
                writes: vec!["count".into()],
                required_inputs: Vec::new(),
                optional_inputs: Vec::new(),
                bound_inputs: Map::new(),
                default_inputs: Map::new(),
                tags: Vec::new(),
                source: None,
                mode: ActionMode::Both,
            },
            calls: Arc::clone(calls),
            output,
            evidence: Arc::clone(evidence),
        }
    }
}

impl ActionBackend for CounterAction {
    type Stream = CounterSource;

    fn declaration(&self) -> &ActionDeclaration {
        &self.declaration
    }

    fn start(&self, request: ActionRequest) -> Self::Stream {
        self.evidence.source("construct");
        CounterSource {
            progress: Progress::Ready(Box::new(request)),
            calls: Arc::clone(&self.calls),
            output: self.output,
            owner_thread: Rc::new(std::thread::current().id()),
            evidence: Arc::clone(&self.evidence),
            pending: matches!(self.output, Output::Pending)
                .then(|| Box::pin(Arc::clone(&self.evidence.release).notified_owned())),
        }
    }
}

impl Stream for CounterSource {
    type Item = Result<ActionEvent, AppError>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        assert_eq!(*self.owner_thread, std::thread::current().id());
        self.evidence.source("poll");
        match mem::replace(&mut self.progress, Progress::Done) {
            Progress::Ready(request) => {
                let first = {
                    let mut calls = self.calls.lock().expect("invocation observations");
                    let first = calls.is_empty();
                    calls.push(Invocation {
                        node: request.context.node.clone(),
                        ordinal: request.context.action_ordinal,
                        mode: request.context.mode,
                        thread: *self.owner_thread,
                    });
                    first
                };
                let count = request.state.values()["count"]
                    .as_u64()
                    .expect("counter state")
                    + 1;
                self.progress = if matches!(self.output, Output::EofOnce) && first {
                    Progress::Eof
                } else {
                    Progress::Terminal {
                        result: if matches!(self.output, Output::Empty) {
                            Map::new()
                        } else {
                            Controls::result(&request.context.node, count)
                        },
                        writes: vec![StateChange::Assign {
                            values: Map::from_iter([("count".into(), json!(count))]),
                        }],
                    }
                };
                self.evidence.source("partial");
                Poll::Ready(Some(Ok(ActionEvent::Partial {
                    result: Map::from_iter([("node".into(), json!(request.context.node))]),
                })))
            }
            Progress::Terminal { result, writes } => {
                if let Some(pending) = self.pending.as_mut() {
                    if pending.as_mut().poll(cx).is_pending() {
                        self.progress = Progress::Terminal { result, writes };
                        self.evidence.source("pending");
                        self.evidence.pending.notify_one();
                        return Poll::Pending;
                    }
                    self.pending = None;
                }
                self.evidence.source("complete");
                Poll::Ready(Some(Ok(ActionEvent::Completed { result, writes })))
            }
            Progress::Eof => Poll::Ready(None),
            Progress::Done => panic!("a closed source must never be polled again"),
        }
    }
}

impl Drop for CounterSource {
    fn drop(&mut self) {
        self.evidence.source("drop");
        assert_eq!(*self.owner_thread, std::thread::current().id());
    }
}

impl Advance {
    async fn commit(
        self,
        execution: &mut Execution<
            '_,
            StateStore,
            Agent,
            CounterAction,
            NoConditions,
            JsonState,
            ControlHooks,
        >,
        node: &str,
        ordinal: u64,
    ) {
        let event = match self {
            Self::Streaming => {
                Controls::partial(execution.next().await.expect("partial event"), node);
                execution.next().await.expect("commit event")
            }
            Self::Ordinary => execution.step().await.expect("drained commit event"),
        };
        Controls::committed(event, node, ordinal);
    }

    fn expected(self) -> (&'static str, Option<Map<String, Value>>) {
        match self {
            Self::Streaming => ("a", Some(Controls::result("a", 1))),
            Self::Ordinary => ("b", None),
        }
    }
}

impl Controls {
    async fn new(nodes: &[&str], cycle: bool, output: Output) -> Self {
        Self::open(Self::definition(nodes, cycle), output).await
    }

    async fn open(definition: WorkflowDefinition, output: Output) -> Self {
        let calls = Arc::new(Mutex::new(Vec::new()));
        let hooks = Arc::new(AtomicUsize::new(0));
        let async_hooks = Arc::new(AtomicUsize::new(0));
        let evidence = Arc::new(ControlEvidence::default());
        let store = StateStore::connect(StateStoreConfig::Lance(LanceStateStoreConfig::memory()))
            .await
            .expect("real memory transactions");
        let config: AppConfig<StateStore, Agent> =
            AppConfig::new(store, Vec::new(), vec![definition]);
        let app = App::open(
            config
                .with_actions(vec![CounterAction::new(&calls, output, &evidence)])
                .with_hooks(ControlHooks {
                    calls: Arc::clone(&hooks),
                    async_calls: Arc::clone(&async_hooks),
                    evidence: Arc::clone(&evidence),
                }),
        )
        .await
        .expect("bind the caller-owned counter without constructing an Agent");
        let workspace = app
            .create_workspace(WorkspaceConfig {
                name: None,
                root: std::env::current_dir().expect("workspace root"),
            })
            .await
            .expect("App workspace");
        let workflow = workspace
            .workflow("controls".parse().expect("workflow identity"))
            .await
            .expect("configured workflow");
        Self {
            app,
            workflow,
            calls,
            hooks,
            async_hooks,
            evidence,
        }
    }

    fn definition(nodes: &[&str], cycle: bool) -> WorkflowDefinition {
        let routes = nodes
            .iter()
            .enumerate()
            .filter_map(|(index, node)| {
                let target = nodes
                    .get(index + 1)
                    .copied()
                    .or_else(|| cycle.then_some(nodes[0]))?;
                Some((
                    (*node).to_owned(),
                    json!({
                        "mode":"first", "branches":[{"target":{"kind":"node","id":target}}]
                    }),
                ))
            })
            .collect::<Map<_, _>>();
        let nodes = nodes.iter().enumerate().map(|(index, node)| json!({
            "id":node, "tags": if index == 0 { vec!["all", "first"] } else { vec!["all", "later"] },
            "step":{"kind":"action", "action":"counter", "revision":"r1"}
        })).collect::<Vec<_>>();
        WorkflowDefinition::parse(
            &json!({
                "schema":"app-kit.workflow/v2", "id":"controls", "revision":"r1",
                "state":{"count":0}, "required":["count"], "reducers":{"count":"reject_concurrent"},
                "entry":"a", "nodes":nodes, "routes":routes
            })
            .to_string(),
        )
        .expect("serial action graph")
    }

    fn options(before: &[&str], after: &[&str]) -> ExecutionOptions {
        ExecutionOptions {
            state: WorkflowState::default(),
            inputs: Map::new(),
            halt_before: before.iter().map(|value| (*value).into()).collect(),
            halt_after: after.iter().map(|value| (*value).into()).collect(),
            max_steps: None,
        }
    }

    async fn native_halt(maximum: bool) {
        let nodes = ["a", "b", "c"].map(|id| {
            json!({
                "id":id, "step":{"kind":"state", "mutations":[
                    {"kind":"increment", "target":"count", "value":{"kind":"literal", "value":1}}
                ]}
            })
        });
        let definition = WorkflowDefinition::parse(
            &json!({
                "schema":"app-kit.workflow/v2", "id":"controls", "revision":"r1",
                "state":{"count":0}, "required":["count"],
                "reducers":{"count":"reject_concurrent"}, "entry":"a",
                "nodes":nodes,
                "routes":{
                    "a":{"mode":"first", "branches":[{"target":{"kind":"node", "id":"b"}}]},
                    "b":{"mode":"first", "branches":[{"target":{"kind":"node", "id":"c"}}]}
                }
            })
            .to_string(),
        )
        .expect("native serial state graph");
        let mut fixture = Self::open(definition, Output::Counter).await;
        let observed = AssertUnwindSafe(tokio::time::timeout(Duration::from_secs(12), async {
            let mut options = Self::options(if maximum { &[] } else { &["b"] }, &[]);
            if maximum {
                options.max_steps = Some(std::num::NonZeroUsize::MIN);
            }
            let run = fixture
                .workflow
                .start(options)
                .await
                .expect("native background admission");
            let halted = tokio::time::timeout(Duration::from_secs(3), run.wait())
                .await
                .expect("native background halt is bounded")
                .expect("native halt snapshot");
            let result = maximum.then(Map::new);
            let node = if maximum { "a" } else { "b" };
            Self::halted_snapshot(&halted, node, &result, 1);
            assert_eq!(halted.outcomes[0].node, "a");
            assert!(halted.outcomes[0].result.is_empty());
            let steps = fixture.evidence.steps.lock().unwrap().clone();
            assert_eq!(steps, vec![("a".into(), 0)]);
            assert_eq!(fixture.evidence.constructions(), 0);
            fixture.calls(&[]);

            // Completion may still own its final receipt when wait exposes the
            // durable halt. Busy cannot alter it or admit another native step.
            let finished = tokio::time::timeout(Duration::from_secs(3), async {
                loop {
                    let mut resumed = fixture
                        .workflow
                        .open_run(RunSelector::Latest(run.id().clone()))
                        .await
                        .unwrap();
                    let acquisition = resumed.execution(Self::options(&[], &[])).await;
                    match acquisition {
                        Ok(execution) => {
                            break execution
                                .finish()
                                .await
                                .expect("explicit native continuation");
                        }
                        Err(AppError::Busy(_)) => {
                            Self::unchanged(&run.snapshot().await.unwrap(), &halted);
                            let steps = fixture.evidence.steps.lock().unwrap().clone();
                            assert_eq!(steps, vec![("a".into(), 0)]);
                            assert_eq!(fixture.evidence.constructions(), 0);
                            tokio::task::yield_now().await;
                        }
                        Err(error) => panic!("unexpected native continuation error: {error}"),
                    }
                }
            })
            .await
            .expect("native ownership handoff and continuation stay bounded");
            assert!(matches!(finished.status, RunStatus::Succeeded));
            assert_eq!(finished.state.values()["count"], 3);
            assert_eq!(finished.last_action_ordinal, Some(2));
            assert_eq!(finished.outcomes.len(), 1);
            assert_eq!(finished.outcomes[0].node, "c");
            assert_eq!(finished.outcomes[0].ordinal, 2);
            assert!(finished.outcomes[0].result.is_empty());
            let steps = fixture.evidence.steps.lock().unwrap().clone();
            assert_eq!(
                steps,
                vec![("a".into(), 0), ("b".into(), 1), ("c".into(), 2)]
            );
            assert_eq!(fixture.evidence.constructions(), 0);
            fixture.calls(&[]);
        }))
        .catch_unwind()
        .await;
        let closed = AssertUnwindSafe(fixture.close()).catch_unwind().await;
        match observed {
            Ok(result) => result.expect("native state halt journey stays bounded"),
            Err(failure) => std::panic::resume_unwind(failure),
        }
        if let Err(failure) = closed {
            std::panic::resume_unwind(failure);
        }
    }

    async fn prepare(
        &self,
    ) -> WorkflowRun<StateStore, Agent, CounterAction, NoConditions, JsonState, ControlHooks> {
        self.workflow
            .prepare(WorkflowState::default())
            .await
            .expect("checkpoint zero")
    }

    async fn seed_a(
        &self,
        run: &mut WorkflowRun<
            StateStore,
            Agent,
            CounterAction,
            NoConditions,
            JsonState,
            ControlHooks,
        >,
    ) {
        let execution = run
            .execution(Self::options(&[], &["a"]))
            .await
            .expect("seed session");
        let snapshot = tokio::time::timeout(Duration::from_secs(3), execution.finish())
            .await
            .expect("bounded first action")
            .expect("seed commit");
        Self::halted_snapshot(&snapshot, "a", &Some(Self::result("a", 1)), 1);
    }

    fn result(node: &str, count: u64) -> Map<String, Value> {
        Map::from_iter([("node".into(), json!(node)), ("count".into(), json!(count))])
    }

    fn partial(event: Option<ExecutionEvent>, expected: &str) {
        assert!(
            matches!(event, Some(ExecutionEvent::Partial { node, result })
            if node == expected && result["node"] == expected)
        );
    }

    fn committed(event: Option<ExecutionEvent>, expected: &str, ordinal: u64) {
        assert!(
            matches!(event, Some(ExecutionEvent::Committed { outcomes, .. })
            if outcomes.len() == 1 && outcomes[0].node == expected && outcomes[0].ordinal == ordinal)
        );
    }

    fn halted_event(
        event: Option<ExecutionEvent>,
        expected: &str,
        result: &Option<Map<String, Value>>,
    ) {
        assert!(
            matches!(event, Some(ExecutionEvent::Halted { node, result: actual })
            if node == expected && &actual == result)
        );
    }

    fn halted_snapshot(
        snapshot: &RunSnapshot,
        expected: &str,
        result: &Option<Map<String, Value>>,
        count: u64,
    ) {
        assert!(
            matches!(&snapshot.status, RunStatus::Halted { node, result: actual }
            if node == expected && actual == result)
        );
        assert_eq!(snapshot.state.values()["count"], count);
        assert_eq!(snapshot.last_action_ordinal, Some(count - 1));
        assert_eq!(
            snapshot.outcomes.len(),
            1,
            "halt cannot fabricate a pending action outcome"
        );
        assert_eq!(snapshot.outcomes[0].ordinal, count - 1);
        assert!(
            snapshot.interactions.is_empty(),
            "halt is not an Input or Unknown interaction"
        );
    }

    fn calls(&self, expected: &[(&str, u64)]) {
        let calls = self.calls.lock().expect("calls").clone();
        assert_eq!(
            calls
                .iter()
                .map(|call| (call.node.as_str(), call.ordinal))
                .collect::<Vec<_>>(),
            expected
        );
    }

    fn unchanged(actual: &RunSnapshot, before: &RunSnapshot) {
        assert_eq!(actual.checkpoint, before.checkpoint);
        assert_eq!(actual.state.values(), before.state.values());
        assert_eq!(actual.last_action_ordinal, before.last_action_ordinal);
        assert_eq!(actual.interactions.len(), before.interactions.len());
        assert_eq!(actual.outcomes.len(), before.outcomes.len());
        for (actual, expected) in actual.outcomes.iter().zip(&before.outcomes) {
            assert_eq!(actual.node, expected.node);
            assert_eq!(actual.ordinal, expected.ordinal);
            assert_eq!(actual.result, expected.result);
        }
        match (&actual.status, &before.status) {
            (RunStatus::Paused, RunStatus::Paused) => {}
            (
                RunStatus::Halted { node, result },
                RunStatus::Halted {
                    node: prior,
                    result: prior_result,
                },
            ) => {
                assert_eq!(node, prior);
                assert_eq!(result, prior_result);
            }
            _ => panic!("rejected initial state changed the saved execution boundary"),
        }
    }

    async fn close(&mut self) {
        tokio::time::timeout(
            Duration::from_secs(5),
            self.app.shutdown(Shutdown::CancelAndDrain {
                timeout: Duration::from_secs(3),
            }),
        )
        .await
        .expect("cleanup observation remains bounded")
        .expect("owned work drains");
    }
}

#[tokio::test]
async fn native_background_halt_before_stops_before_the_next_state_activation() {
    Controls::native_halt(false).await;
}

#[tokio::test]
async fn native_background_max_steps_counts_committed_state_activations() {
    Controls::native_halt(true).await;
}

#[tokio::test]
async fn existing_async_run_rejects_initial_state_before_hooks_source_or_generation_changes() {
    for historical in [false, true] {
        let mut fixture = Controls::new(&["a", "b"], false, Output::Counter).await;
        let observed = AssertUnwindSafe(async {
            let mut run = fixture.prepare().await;
            if historical {
                fixture.seed_a(&mut run).await;
            }
            let before = run.snapshot().await.expect("saved committed boundary");
            let constructions = fixture.evidence.constructions();
            let hooks = fixture.hooks.load(Ordering::SeqCst);
            for values in [
                before.state.values().clone(),
                Map::from_iter([("count".into(), json!(99))]),
                Map::from_iter([("new_key".into(), Value::Null)]),
            ] {
                let mut options = Controls::options(&[], &[]);
                options.state = WorkflowState::new(values).expect("valid nonempty initial state");
                assert!(matches!(
                    run.execution(options).await,
                    Err(AppError::InvalidInput(_))
                ));
                Controls::unchanged(&run.snapshot().await.expect("unchanged saved run"), &before);
                assert_eq!(fixture.evidence.constructions(), constructions);
                assert_eq!(fixture.hooks.load(Ordering::SeqCst), hooks);
            }
            let mut resumed = fixture
                .workflow
                .open_run(RunSelector::Latest(run.id().clone()))
                .await
                .expect("another handle remains usable");
            let execution = resumed
                .execution(Controls::options(&[], &[]))
                .await
                .expect("rejection must not strand an exclusive generation");
            let snapshot = tokio::time::timeout(Duration::from_secs(3), execution.finish())
                .await
                .expect("subsequent empty-state execution stays bounded")
                .expect("complete from the saved position");
            assert!(matches!(snapshot.status, RunStatus::Succeeded));
            assert_eq!(snapshot.state.values()["count"], 2);
            assert_eq!(snapshot.last_action_ordinal, Some(1));
            fixture.calls(&[("a", 0), ("b", 1)]);
            assert_eq!(fixture.evidence.constructions(), 2);
            assert!(fixture.hooks.load(Ordering::SeqCst) > hooks);
        })
        .catch_unwind()
        .await;
        let closed = AssertUnwindSafe(fixture.close()).catch_unwind().await;
        for result in [observed, closed] {
            if let Err(failure) = result {
                std::panic::resume_unwind(failure);
            }
        }
    }
}

#[test]
fn existing_sync_run_rejects_initial_state_before_hooks_source_or_generation_changes() {
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .worker_threads(2)
        .enable_all()
        .build()
        .expect("caller lower runtime remains driven");
    for historical in [false, true] {
        let mut fixture = runtime.block_on(Controls::new(&["a", "b"], false, Output::Counter));
        let observed = std::panic::catch_unwind(AssertUnwindSafe(|| {
            let mut run = runtime.block_on(fixture.prepare());
            if historical {
                runtime.block_on(fixture.seed_a(&mut run));
            }
            let before = runtime
                .block_on(run.snapshot())
                .expect("saved committed boundary");
            let constructions = fixture.evidence.constructions();
            let hooks = fixture.hooks.load(Ordering::SeqCst);
            for values in [
                before.state.values().clone(),
                Map::from_iter([("count".into(), json!(99))]),
                Map::from_iter([("new_key".into(), Value::Null)]),
            ] {
                let mut options = Controls::options(&[], &[]);
                options.state = WorkflowState::new(values).expect("valid nonempty initial state");
                assert!(matches!(
                    SyncExecution::open(&mut run, options),
                    Err(AppError::InvalidInput(_))
                ));
                Controls::unchanged(
                    &runtime
                        .block_on(run.snapshot())
                        .expect("unchanged saved run"),
                    &before,
                );
                assert_eq!(fixture.evidence.constructions(), constructions);
                assert_eq!(fixture.hooks.load(Ordering::SeqCst), hooks);
            }
            let mut resumed = runtime
                .block_on(
                    fixture
                        .workflow
                        .open_run(RunSelector::Latest(run.id().clone())),
                )
                .expect("another handle remains usable");
            let execution = SyncExecution::open(&mut resumed, Controls::options(&[], &[]))
                .expect("rejection must not strand an exclusive generation");
            let snapshot = execution
                .finish()
                .expect("complete from the saved position");
            assert!(matches!(snapshot.status, RunStatus::Succeeded));
            assert_eq!(snapshot.state.values()["count"], 2);
            assert_eq!(snapshot.last_action_ordinal, Some(1));
            fixture.calls(&[("a", 0), ("b", 1)]);
            let calls = fixture.calls.lock().unwrap().clone();
            assert_eq!(
                calls[0].mode,
                if historical {
                    ActionMode::Asynchronous
                } else {
                    ActionMode::Synchronous
                }
            );
            assert_eq!(calls[1].mode, ActionMode::Synchronous);
            assert_eq!(fixture.evidence.constructions(), 2);
            assert!(fixture.hooks.load(Ordering::SeqCst) > hooks);
        }));
        let closed =
            std::panic::catch_unwind(AssertUnwindSafe(|| runtime.block_on(fixture.close())));
        for result in [observed, closed] {
            if let Err(failure) = result {
                std::panic::resume_unwind(failure);
            }
        }
    }
}

#[tokio::test]
async fn next_and_step_keep_the_two_pinned_halt_orders_and_exact_reopened_status() {
    for advance in [Advance::Streaming, Advance::Ordinary] {
        let mut fixture = Controls::new(&["a", "b"], false, Output::Counter).await;
        let mut run = fixture.prepare().await;
        let mut execution = run
            .execution(Controls::options(&["b"], &["a"]))
            .await
            .expect("execution");
        advance.commit(&mut execution, "a", 0).await;
        let (node, result) = advance.expected();
        Controls::halted_event(
            execution.next().await.expect("retained halt"),
            node,
            &result,
        );
        assert!(
            execution
                .next()
                .await
                .expect("halt event is emitted once")
                .is_none()
        );
        assert!(
            execution
                .step()
                .await
                .expect("changing methods cannot unhalt")
                .is_none()
        );
        let snapshot = execution.finish().await.expect("finish the retained halt");
        Controls::halted_snapshot(&snapshot, node, &result, 1);
        assert_eq!(snapshot.outcomes[0].node, "a");
        assert_eq!(snapshot.outcomes[0].result, Controls::result("a", 1));
        let reopened = fixture
            .workflow
            .open_run(RunSelector::Latest(run.id().clone()))
            .await
            .expect("new run handle");
        let readback = reopened.snapshot().await.expect("checkpoint readback");
        Controls::halted_snapshot(&readback, node, &result, 1);
        assert_eq!(readback.checkpoint, snapshot.checkpoint);
        fixture.calls(&[("a", 0)]);
        fixture.close().await;
    }
}

#[tokio::test]
async fn finish_and_background_wait_return_the_pending_halt_tuple_without_fabricating_an_outcome() {
    for background in [false, true] {
        let mut fixture = Controls::new(&["a", "b"], false, Output::Counter).await;
        let snapshot = if background {
            let run = fixture
                .workflow
                .start(Controls::options(&["b"], &["a"]))
                .await
                .expect("background admission");
            tokio::time::timeout(Duration::from_secs(3), run.wait())
                .await
                .expect("bounded halt")
                .expect("background snapshot")
        } else {
            let mut run = fixture.prepare().await;
            let execution = run
                .execution(Controls::options(&["b"], &["a"]))
                .await
                .expect("foreground admission");
            tokio::time::timeout(Duration::from_secs(3), execution.finish())
                .await
                .expect("bounded halt")
                .expect("finish snapshot")
        };
        Controls::halted_snapshot(&snapshot, "b", &None, 1);
        assert_eq!(snapshot.outcomes[0].node, "a");
        fixture.calls(&[("a", 0)]);
        fixture.close().await;
    }
}

#[tokio::test]
async fn historical_halts_do_not_suppress_the_first_current_session_action() {
    for advance in [Advance::Streaming, Advance::Ordinary] {
        for (before, after) in [
            (vec!["b"], vec![]),
            (vec![], vec!["a"]),
            (vec!["b"], vec!["a"]),
        ] {
            let mut fixture = Controls::new(&["a", "b"], false, Output::Counter).await;
            let mut run = fixture.prepare().await;
            fixture.seed_a(&mut run).await;
            let mut resumed = run
                .execution(Controls::options(&before, &after))
                .await
                .expect("new execution session");
            advance.commit(&mut resumed, "b", 1).await;
            assert!(resumed.next().await.expect("terminal frontier").is_none());
            let snapshot = resumed.finish().await.expect("resumed completion");
            assert!(matches!(snapshot.status, RunStatus::Succeeded));
            assert_eq!(snapshot.state.values()["count"], 2);
            assert_eq!(snapshot.last_action_ordinal, Some(1));
            fixture.calls(&[("a", 0), ("b", 1)]);
            fixture.close().await;
        }
    }
}

#[tokio::test]
async fn resumed_halts_become_active_after_the_first_current_session_commit() {
    for advance in [Advance::Streaming, Advance::Ordinary] {
        let mut fixture = Controls::new(&["a", "b", "c"], false, Output::Counter).await;
        let mut run = fixture.prepare().await;
        fixture.seed_a(&mut run).await;
        let mut resumed = run
            .execution(Controls::options(&["c"], &["b"]))
            .await
            .expect("resumed session");
        advance.commit(&mut resumed, "b", 1).await;
        let (node, result) = match advance {
            Advance::Streaming => ("b", Some(Controls::result("b", 2))),
            Advance::Ordinary => ("c", None),
        };
        Controls::halted_event(
            resumed
                .next()
                .await
                .expect("halt after this session's commit"),
            node,
            &result,
        );
        let snapshot = resumed.finish().await.expect("retained halt");
        Controls::halted_snapshot(&snapshot, node, &result, 2);
        fixture.calls(&[("a", 0), ("b", 1)]);
        fixture.close().await;
    }
}

#[tokio::test]
async fn the_method_committing_a_partially_observed_action_selects_and_then_retains_halt_order() {
    for ordinary_finish in [false, true] {
        let mut fixture = Controls::new(&["a", "b"], false, Output::Counter).await;
        let mut run = fixture.prepare().await;
        let mut execution = run
            .execution(Controls::options(&["b"], &["a"]))
            .await
            .expect("execution");
        Controls::partial(
            execution.next().await.expect("initial streaming partial"),
            "a",
        );
        let snapshot = if ordinary_finish {
            execution
                .finish()
                .await
                .expect("ordinary finish commits the boundary")
        } else {
            Controls::committed(
                execution
                    .step()
                    .await
                    .expect("ordinary step commits the boundary"),
                "a",
                0,
            );
            Controls::halted_event(
                execution
                    .next()
                    .await
                    .expect("streaming next cannot reclassify it"),
                "b",
                &None,
            );
            execution
                .finish()
                .await
                .expect("finish keeps pending-node halt")
        };
        Controls::halted_snapshot(&snapshot, "b", &None, 1);
        fixture.calls(&[("a", 0)]);
        fixture.close().await;
    }

    let mut fixture = Controls::new(&["a", "b"], false, Output::Counter).await;
    let mut run = fixture.prepare().await;
    let mut execution = run
        .execution(Controls::options(&["b"], &["a"]))
        .await
        .expect("execution");
    Advance::Streaming.commit(&mut execution, "a", 0).await;
    let result = Some(Controls::result("a", 1));
    Controls::halted_event(
        execution
            .step()
            .await
            .expect("ordinary step cannot reclassify retained streaming halt"),
        "a",
        &result,
    );
    Controls::halted_snapshot(
        &execution.finish().await.expect("retained decision"),
        "a",
        &result,
        1,
    );
    fixture.calls(&[("a", 0)]);
    fixture.close().await;
}

#[tokio::test]
async fn tag_expansion_and_duplicate_selectors_preserve_the_same_serial_boundaries() {
    for advance in [Advance::Streaming, Advance::Ordinary] {
        let mut fixture = Controls::new(&["a", "b", "c"], false, Output::Counter).await;
        let mut run = fixture.prepare().await;
        let mut execution = run
            .execution(Controls::options(
                &["@later", "b", "@later"],
                &["@first", "a", "@first"],
            ))
            .await
            .expect("ordered tag selectors");
        advance.commit(&mut execution, "a", 0).await;
        let (node, result) = advance.expected();
        Controls::halted_event(
            execution.next().await.expect("selected tagged boundary"),
            node,
            &result,
        );
        Controls::halted_snapshot(
            &execution.finish().await.expect("tagged halt"),
            node,
            &result,
            1,
        );
        fixture.calls(&[("a", 0)]);
        fixture.close().await;
    }
}

#[tokio::test]
async fn unknown_explicit_and_tag_selectors_fail_before_any_action_is_polled() {
    for selector in ["missing", "@missing"] {
        for before in [false, true] {
            let mut fixture = Controls::new(&["a", "b"], false, Output::Counter).await;
            let mut run = fixture.prepare().await;
            let options = if before {
                Controls::options(&[selector], &[])
            } else {
                Controls::options(&[], &[selector])
            };
            match run.execution(options).await {
                Err(error) => assert!(matches!(error, AppError::InvalidInput(_))),
                Ok(mut execution) => assert!(matches!(
                    execution.next().await,
                    Err(AppError::InvalidInput(_))
                )),
            }
            let snapshot = run.snapshot().await.expect("no-effect state");
            assert_eq!(snapshot.state.values()["count"], 0);
            assert!(snapshot.last_action_ordinal.is_none());
            assert!(snapshot.outcomes.is_empty());
            fixture.calls(&[]);
            fixture.close().await;
        }
    }
}

#[tokio::test]
async fn first_entry_bypass_distinguishes_a_self_loop_from_an_exhausted_frontier() {
    for advance in [Advance::Streaming, Advance::Ordinary] {
        for cycle in [false, true] {
            let mut fixture = Controls::new(&["a"], cycle, Output::Counter).await;
            let mut run = fixture.prepare().await;
            let mut execution = run
                .execution(Controls::options(&["a"], &[]))
                .await
                .expect("first-entry selector");
            advance.commit(&mut execution, "a", 0).await;
            if cycle {
                Controls::halted_event(
                    execution.next().await.expect("halt before repeated action"),
                    "a",
                    &None,
                );
                Controls::halted_snapshot(
                    &execution.finish().await.expect("retained loop halt"),
                    "a",
                    &None,
                    1,
                );
            } else {
                assert!(
                    execution
                        .next()
                        .await
                        .expect("no next action exists")
                        .is_none()
                );
                let snapshot = execution.finish().await.expect("terminal completion");
                assert!(matches!(snapshot.status, RunStatus::Succeeded));
                assert_eq!(snapshot.state.values()["count"], 1);
                assert_eq!(snapshot.last_action_ordinal, Some(0));
            }
            fixture.calls(&[("a", 0)]);
            fixture.close().await;
        }
    }
}

#[tokio::test]
async fn halt_after_an_exhausted_action_preserves_some_empty_result() {
    for advance in [Advance::Streaming, Advance::Ordinary] {
        let mut fixture = Controls::new(&["a"], false, Output::Empty).await;
        let mut run = fixture.prepare().await;
        let mut execution = run
            .execution(Controls::options(&["a"], &["a"]))
            .await
            .expect("terminal halt selectors");
        advance.commit(&mut execution, "a", 0).await;
        let result = Some(Map::new());
        Controls::halted_event(
            execution
                .next()
                .await
                .expect("after wins when no pending action exists"),
            "a",
            &result,
        );
        Controls::halted_snapshot(
            &execution
                .finish()
                .await
                .expect("empty result is not absent"),
            "a",
            &result,
            1,
        );
        fixture.calls(&[("a", 0)]);
        fixture.close().await;
    }
}

#[tokio::test]
async fn partial_then_eof_does_not_enable_historical_halts_or_advance_position() {
    let mut fixture = Controls::new(&["a", "b"], false, Output::EofOnce).await;
    let mut run = fixture.prepare().await;
    let observer = fixture
        .workflow
        .open_run(RunSelector::Latest(run.id().clone()))
        .await
        .expect("read-only observer handle");
    let mut execution = run
        .execution(Controls::options(&["a"], &[]))
        .await
        .expect("session with first-action halt-before");
    Controls::partial(execution.next().await.expect("uncommitted partial"), "a");
    assert!(
        execution
            .next()
            .await
            .expect("successful no-output EOF")
            .is_none()
    );
    let snapshot = observer.snapshot().await.expect("EOF rollback readback");
    assert_eq!(snapshot.state.values()["count"], 0);
    assert!(snapshot.last_action_ordinal.is_none());
    assert!(snapshot.outcomes.is_empty());
    assert!(!matches!(
        snapshot.status,
        RunStatus::Halted { .. } | RunStatus::Failed(_)
    ));
    // This explicit advancement retries the saved position; no hidden drain
    // after EOF is allowed to construct or commit that second source for us.
    fixture.calls(&[("a", 0)]);
    Advance::Streaming.commit(&mut execution, "a", 0).await;
    Advance::Streaming.commit(&mut execution, "b", 1).await;
    let snapshot = execution
        .finish()
        .await
        .expect("explicit retry and remaining action complete");
    assert!(matches!(snapshot.status, RunStatus::Succeeded));
    fixture.calls(&[("a", 0), ("a", 0), ("b", 1)]);
    fixture.close().await;
}

#[test]
fn synchronous_next_and_step_use_the_same_two_halt_orders_outside_a_tokio_task() {
    // The multi-thread runtime remains driven while this ordinary test thread
    // invokes the sync facade. No sync operation runs inside Runtime::block_on.
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .worker_threads(2)
        .enable_all()
        .build()
        .expect("still-driven runtime");
    for advance in [Advance::Streaming, Advance::Ordinary] {
        let mut fixture = runtime.block_on(Controls::new(&["a", "b"], false, Output::Counter));
        let observed = std::panic::catch_unwind(AssertUnwindSafe(|| {
            let mut run = runtime.block_on(fixture.prepare());
            let asynchronous = fixture.async_hooks.load(Ordering::SeqCst);
            let hooks = fixture.hooks.load(Ordering::SeqCst);
            let mut execution = SyncExecution::open(&mut run, Controls::options(&["b"], &["a"]))
                .expect("sync execution outside runtime task");
            assert_eq!(fixture.evidence.constructions(), 0);
            let event = match advance {
                Advance::Streaming => {
                    Controls::partial(execution.try_next().expect("sync partial"), "a");
                    execution.try_next().expect("sync commit")
                }
                Advance::Ordinary => execution.step().expect("sync drained commit"),
            };
            Controls::committed(event, "a", 0);
            let (node, result) = advance.expected();
            Controls::halted_event(
                execution.try_next().expect("sync retained halt"),
                node,
                &result,
            );
            assert!(execution.step().expect("sync halt is fused").is_none());
            Controls::halted_snapshot(
                &execution.finish().expect("sync finalization"),
                node,
                &result,
                1,
            );
            fixture.calls(&[("a", 0)]);
            let calls = fixture.calls.lock().unwrap().clone();
            assert!(calls.iter().all(|call| call.mode == ActionMode::Synchronous
                && call.thread == std::thread::current().id()));
            assert!(fixture.hooks.load(Ordering::SeqCst) > hooks);
            assert_eq!(fixture.async_hooks.load(Ordering::SeqCst), asynchronous);
        }));
        let closed = runtime.block_on(AssertUnwindSafe(fixture.close()).catch_unwind());
        if let Err(panic) = observed {
            std::panic::resume_unwind(panic);
        }
        closed.expect("sync cleanup does not panic");
    }
}

#[test]
fn synchronous_resumption_and_partial_to_finish_preserve_first_session_and_ordinary_rules() {
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .worker_threads(2)
        .enable_all()
        .build()
        .expect("still-driven runtime");
    let mut fixture = runtime.block_on(Controls::new(&["a", "b", "c"], false, Output::Counter));
    let observed = std::panic::catch_unwind(AssertUnwindSafe(|| {
        let mut run = runtime.block_on(fixture.prepare());
        let asynchronous = fixture.async_hooks.load(Ordering::SeqCst);
        let mut initial =
            SyncExecution::open(&mut run, Controls::options(&["@later"], &["@first"]))
                .expect("sync execution");
        Controls::partial(initial.try_next().expect("sync partial"), "a");
        Controls::halted_snapshot(
            &initial.finish().expect("finish selects ordinary order"),
            "b",
            &None,
            1,
        );
        let mut resumed =
            SyncExecution::open(&mut run, Controls::options(&["b", "c"], &["a", "b"]))
                .expect("new sync session");
        Controls::partial(
            resumed
                .try_next()
                .expect("historical halt cannot suppress B"),
            "b",
        );
        Controls::committed(
            resumed.try_next().expect("first current-session commit"),
            "b",
            1,
        );
        let result = Some(Controls::result("b", 2));
        Controls::halted_event(
            resumed
                .step()
                .expect("retained streaming choice cannot be reclassified"),
            "b",
            &result,
        );
        Controls::halted_snapshot(
            &resumed.finish().expect("sync retained output"),
            "b",
            &result,
            2,
        );
        fixture.calls(&[("a", 0), ("b", 1)]);
        let calls = fixture.calls.lock().unwrap().clone();
        assert!(calls.iter().all(|call| call.mode == ActionMode::Synchronous
            && call.thread == std::thread::current().id()));
        assert_eq!(fixture.async_hooks.load(Ordering::SeqCst), asynchronous);
    }));
    let closed = runtime.block_on(AssertUnwindSafe(fixture.close()).catch_unwind());
    if let Err(panic) = observed {
        std::panic::resume_unwind(panic);
    }
    closed.expect("sync cleanup does not panic");
}

#[test]
fn every_sync_method_rejects_entered_context_without_polling_or_committing() {
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .worker_threads(2)
        .enable_all()
        .build()
        .unwrap();
    for method in [
        BlockingMethod::Next,
        BlockingMethod::Step,
        BlockingMethod::Finish,
        BlockingMethod::Abort,
    ] {
        let mut fixture = runtime.block_on(Controls::new(&["a"], false, Output::Counter));
        let observed = std::panic::catch_unwind(AssertUnwindSafe(|| {
            let mut run = runtime.block_on(fixture.prepare());
            let id = run.id().clone();
            let observer = runtime
                .block_on(fixture.workflow.open_run(RunSelector::Latest(id.clone())))
                .unwrap();
            let mut execution = SyncExecution::open(&mut run, Controls::options(&[], &[])).unwrap();
            Controls::partial(execution.try_next().unwrap(), "a");
            let before = runtime.block_on(observer.snapshot()).unwrap();
            let sources = fixture.evidence.sources.lock().unwrap().clone();
            let hooks = fixture.hooks.load(Ordering::SeqCst);
            let asynchronous = fixture.async_hooks.load(Ordering::SeqCst);
            assert_eq!(fixture.evidence.constructions(), 1);
            assert_eq!(before.state.values()["count"], 0);
            assert!(before.last_action_ordinal.is_none() && before.outcomes.is_empty());

            let snapshot = match method {
                BlockingMethod::Next | BlockingMethod::Step => {
                    let rejected = {
                        // Merely entering a runtime is enough: this is not
                        // limited to calls currently polled by a Tokio task.
                        let _entered = runtime.enter();
                        match method {
                            BlockingMethod::Next => execution.try_next(),
                            BlockingMethod::Step => execution.step(),
                            _ => unreachable!(),
                        }
                    };
                    assert!(
                        matches!(rejected, Err(AppError::InvalidInput(_))),
                        "{method:?}"
                    );
                    let after_sources = fixture.evidence.sources.lock().unwrap().clone();
                    assert_eq!(
                        after_sources, sources,
                        "rejection cannot poll or drop the retained source"
                    );
                    assert_eq!(fixture.hooks.load(Ordering::SeqCst), hooks);
                    Controls::unchanged(&runtime.block_on(observer.snapshot()).unwrap(), &before);
                    // A borrowed rejection keeps the exact existing source.
                    execution
                        .finish()
                        .expect("same owning session remains usable")
                }
                BlockingMethod::Finish | BlockingMethod::Abort => {
                    let rejected = {
                        let _entered = runtime.enter();
                        match method {
                            BlockingMethod::Finish => execution.finish(),
                            BlockingMethod::Abort => execution.abort(),
                            _ => unreachable!(),
                        }
                    };
                    assert!(
                        matches!(rejected, Err(AppError::InvalidInput(_))),
                        "{method:?}"
                    );
                    let after_sources = fixture.evidence.sources.lock().unwrap().clone();
                    let mut dropped = sources.clone();
                    dropped.push(("drop", std::thread::current().id()));
                    assert_eq!(
                        after_sources, dropped,
                        "consuming rejection only drops the uncommitted source"
                    );
                    assert_eq!(fixture.async_hooks.load(Ordering::SeqCst), asynchronous);
                    // Consuming rejection may revoke the generation. The
                    // original App cleanup may briefly retain its reservation.
                    let deadline = std::time::Instant::now() + Duration::from_secs(3);
                    loop {
                        let saved = runtime.block_on(observer.snapshot()).unwrap();
                        assert_eq!(saved.state.values(), before.state.values());
                        assert!(saved.last_action_ordinal.is_none() && saved.outcomes.is_empty());
                        assert_eq!(fixture.evidence.constructions(), 1);
                        let mut resumed = runtime
                            .block_on(fixture.workflow.open_run(RunSelector::Latest(id.clone())))
                            .unwrap();
                        match SyncExecution::open(&mut resumed, Controls::options(&[], &[])) {
                            Ok(execution) => {
                                break execution
                                    .finish()
                                    .expect("a fresh session uses the unchanged saved position");
                            }
                            Err(AppError::Busy(_)) => {
                                assert!(
                                    std::time::Instant::now() < deadline,
                                    "consumed rejection retains ownership past bounded cleanup"
                                );
                                let current = fixture.evidence.sources.lock().unwrap().clone();
                                assert_eq!(
                                    current, dropped,
                                    "handoff cannot replay the abandoned source"
                                );
                                std::thread::yield_now();
                            }
                            Err(error) => {
                                panic!("unexpected post-rejection acquisition failure: {error}")
                            }
                        }
                    }
                }
            };
            assert!(matches!(snapshot.status, RunStatus::Succeeded));
            assert_eq!(snapshot.state.values()["count"], 1);
            assert_eq!(snapshot.last_action_ordinal, Some(0));
            assert_eq!(snapshot.outcomes.len(), 1);
            let attempts = if matches!(method, BlockingMethod::Finish | BlockingMethod::Abort) {
                2
            } else {
                1
            };
            assert_eq!(fixture.evidence.constructions(), attempts);
            let calls = fixture.calls.lock().unwrap().clone();
            assert_eq!(calls.len(), attempts);
            assert!(calls.iter().all(|call| call.node == "a"
                && call.ordinal == 0
                && call.mode == ActionMode::Synchronous
                && call.thread == std::thread::current().id()));
            let modes = fixture.evidence.hook_modes.lock().unwrap().clone();
            assert!(!modes.is_empty() && modes.iter().all(|mode| *mode == ActionMode::Synchronous));
            assert_eq!(fixture.async_hooks.load(Ordering::SeqCst), asynchronous);
        }));
        let closed = runtime.block_on(AssertUnwindSafe(fixture.close()).catch_unwind());
        if let Err(panic) = observed {
            std::panic::resume_unwind(panic);
        }
        closed.expect("rejection cleanup does not panic");
    }
}

#[test]
fn synchronous_abort_discards_partial_work_and_releases_the_run_for_explicit_resumption() {
    let runtime = tokio::runtime::Builder::new_multi_thread()
        .worker_threads(2)
        .enable_all()
        .build()
        .expect("caller lower runtime remains driven");
    for committed_prefix in [false, true] {
        let mut fixture = runtime.block_on(Controls::new(&["a", "b"], false, Output::Counter));
        let observed = std::panic::catch_unwind(AssertUnwindSafe(|| {
            let caller = std::thread::current().id();
            let mut run = runtime.block_on(fixture.prepare());
            let observer = runtime
                .block_on(
                    fixture
                        .workflow
                        .open_run(RunSelector::Latest(run.id().clone())),
                )
                .unwrap();
            let asynchronous = fixture.async_hooks.load(Ordering::SeqCst);
            let mut execution = SyncExecution::open(&mut run, Controls::options(&[], &[])).unwrap();
            assert_eq!(fixture.evidence.constructions(), 0);
            if committed_prefix {
                Controls::committed(execution.step().unwrap(), "a", 0);
            }
            let node = if committed_prefix { "b" } else { "a" };
            Controls::partial(execution.try_next().unwrap(), node);
            let before = runtime.block_on(observer.snapshot()).unwrap();
            let sources = fixture.evidence.sources.lock().unwrap().clone();
            let hooks = fixture.hooks.load(Ordering::SeqCst);
            assert_eq!(before.state.values()["count"], u64::from(committed_prefix));
            assert_eq!(before.last_action_ordinal, committed_prefix.then_some(0));
            assert_eq!(before.outcomes.len(), usize::from(committed_prefix));

            // Abort returns on this ordinary thread. It must drop the retained
            // partial source without polling its ready terminal writes.
            let paused = execution.abort().expect("successful synchronous abort");
            assert!(matches!(paused.status, RunStatus::Paused));
            assert_eq!(paused.state, before.state);
            assert_eq!(paused.last_action_ordinal, before.last_action_ordinal);
            assert!(paused.outcomes == before.outcomes);
            assert!(paused.interactions.is_empty());
            let mut dropped = sources;
            dropped.push(("drop", caller));
            assert_eq!(fixture.evidence.sources.lock().unwrap().as_slice(), dropped);
            assert_eq!(fixture.hooks.load(Ordering::SeqCst), hooks + 3);
            assert_eq!(fixture.async_hooks.load(Ordering::SeqCst), asynchronous);
            let modes = fixture.evidence.hook_modes.lock().unwrap().clone();
            assert_eq!(
                modes,
                vec![ActionMode::Synchronous; 2 + 2 * usize::from(committed_prefix)]
            );
            // The consumed owner releases the original mutable run borrow.
            Controls::unchanged(&runtime.block_on(run.snapshot()).unwrap(), &paused);

            let complete = SyncExecution::open(&mut run, Controls::options(&[], &[]))
                .expect("abort releases the original execution ownership")
                .finish()
                .expect("explicit continuation completes from the saved boundary");
            assert!(matches!(complete.status, RunStatus::Succeeded));
            assert_eq!(complete.state.values()["count"], 2);
            assert_eq!(complete.last_action_ordinal, Some(1));
            assert_eq!(fixture.async_hooks.load(Ordering::SeqCst), asynchronous);
        }));
        let closed = runtime.block_on(AssertUnwindSafe(fixture.close()).catch_unwind());
        if let Err(panic) = observed {
            std::panic::resume_unwind(panic);
        }
        closed.expect("synchronous abort cleanup joins");
    }
}

#[test]
fn synchronous_pending_source_stays_on_caller_with_driven_current_thread_runtime() {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap();
    let handle = runtime.handle().clone();
    let mut fixture = runtime.block_on(Controls::new(&["a"], false, Output::Pending));
    let caller = std::thread::current().id();
    // This is the caller's lower runtime, not a SyncExecution-created thread.
    // Its real LanceDB/App operations stay on this same captured runtime.
    std::thread::scope(|scope| {
        let (stop, stopped) = oneshot::channel();
        let driver = scope.spawn(|| {
            runtime.block_on(async {
                let _ = stopped.await;
            })
        });
        let evidence = Arc::clone(&fixture.evidence);
        let mut release = handle.spawn(async move {
            let pending =
                tokio::time::timeout(Duration::from_secs(3), evidence.pending.notified()).await;
            evidence.release.notify_one();
            pending.expect("real source must return Pending before it is released");
        });
        let observed = std::panic::catch_unwind(AssertUnwindSafe(|| {
            let mut run = handle.block_on(fixture.prepare());
            let observer = handle
                .block_on(
                    fixture
                        .workflow
                        .open_run(RunSelector::Latest(run.id().clone())),
                )
                .unwrap();
            let asynchronous = fixture.async_hooks.load(Ordering::SeqCst);
            let mut execution = SyncExecution::open(&mut run, Controls::options(&[], &[])).unwrap();
            Controls::partial(execution.try_next().unwrap(), "a");
            let partial = handle.block_on(observer.snapshot()).unwrap();
            assert_eq!(partial.state.values()["count"], 0);
            assert!(partial.last_action_ordinal.is_none() && partial.outcomes.is_empty());
            Controls::committed(
                execution
                    .step()
                    .expect("pending local source wakes on the captured runtime"),
                "a",
                0,
            );
            let snapshot = execution.finish().unwrap();
            assert!(matches!(snapshot.status, RunStatus::Succeeded));
            assert_eq!(snapshot.state.values()["count"], 1);
            assert_eq!(snapshot.last_action_ordinal, Some(0));
            assert_eq!(snapshot.outcomes.len(), 1);
            fixture.calls(&[("a", 0)]);
            let sources = fixture.evidence.sources.lock().unwrap().clone();
            assert!(sources.iter().all(|(_, thread)| *thread == caller));
            assert_eq!(sources.first().unwrap().0, "construct");
            assert_eq!(sources.last().unwrap().0, "drop");
            for event in ["construct", "partial", "complete", "drop"] {
                assert_eq!(
                    sources.iter().filter(|(name, _)| *name == event).count(),
                    1,
                    "{event}"
                );
            }
            let pending = sources
                .iter()
                .position(|(event, _)| *event == "pending")
                .expect("a real Pending poll");
            let complete = sources
                .iter()
                .position(|(event, _)| *event == "complete")
                .unwrap();
            assert!(pending < complete);
            let calls = fixture.calls.lock().unwrap().clone();
            assert_eq!(calls[0].mode, ActionMode::Synchronous);
            let modes = fixture.evidence.hook_modes.lock().unwrap().clone();
            assert_eq!(modes, [ActionMode::Synchronous, ActionMode::Synchronous]);
            assert_eq!(fixture.async_hooks.load(Ordering::SeqCst), asynchronous);
        }));
        fixture.evidence.release.notify_one();
        let released = handle.block_on(async {
            match tokio::time::timeout(Duration::from_secs(4), &mut release).await {
                Ok(result) => result,
                Err(_) => {
                    release.abort();
                    release.await
                }
            }
        });
        let closed = handle.block_on(AssertUnwindSafe(fixture.close()).catch_unwind());
        // Keep the runtime driven until both the App and test-owned wake task
        // have joined, even when a body assertion or cleanup fails.
        let _ = stop.send(());
        let joined = driver.join();
        if let Err(panic) = observed {
            std::panic::resume_unwind(panic);
        }
        released.expect("source release task joins without panic or cancellation");
        closed.expect("current-thread App cleanup does not panic");
        joined.expect("caller-owned runtime driver joins");
    });
}

#[tokio::test]
async fn synchronous_execution_inside_a_tokio_task_rejects_before_admission() {
    let mut case = Controls::new(&["a"], false, Output::Counter).await;
    let mut run = case.prepare().await;
    let observed = AssertUnwindSafe(tokio::time::timeout(Duration::from_secs(5), async {
        let before = run.snapshot().await.unwrap();
        let hooks = case.hooks.load(Ordering::SeqCst);
        assert!(SyncExecution::open(&mut run, Controls::options(&[], &[])).is_err());
        Controls::unchanged(&run.snapshot().await.unwrap(), &before);
        assert_eq!(case.hooks.load(Ordering::SeqCst), hooks);
        assert_eq!(case.evidence.constructions(), 0);
        let completed = run
            .execution(Controls::options(&[], &[]))
            .await
            .unwrap()
            .finish()
            .await
            .unwrap();
        assert!(matches!(completed.status, RunStatus::Succeeded));
        case.calls(&[("a", 0)]);
        let calls = case.calls.lock().unwrap().clone();
        assert_eq!(calls[0].mode, ActionMode::Asynchronous);
    }))
    .catch_unwind()
    .await;
    let closed = AssertUnwindSafe(case.close()).catch_unwind().await;
    drop(case);
    match observed {
        Ok(result) => result.expect("rejected sync acquisition and async continuation are bounded"),
        Err(panic) => std::panic::resume_unwind(panic),
    }
    closed.expect("rejected sync acquisition leaves cleanup usable");
}