multicast-codemode-local 2.0.0

Local QuickJS executor for multicast Code Mode
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
//! Real JavaScript acceptance for callable workflow composition.
#![cfg(all(feature = "quickjs", feature = "sqlite"))]
use multicast_codemode::{CodeMode, ExecutionStatus, MemoryStore};
use multicast_codemode_local::LocalExecutor;
use serde_json::json;
use std::sync::Arc;

#[tokio::test]
async fn define_compose_publish_delete_and_recurse_in_one_program() {
    let runtime = CodeMode::new(
        Arc::new(MemoryStore::default()),
        LocalExecutor::default(),
        vec![],
    );
    let state = runtime.execute(r#"async () => {
        const w = codemode.workflows;
        const inc = await w.define('async (input, bindings) => input + bindings.amount',
            {input:{type:'integer'}, output:{type:'integer'}}, {amount:2});
        const twice = await w.define('async input => input * 2',
            {input:{type:'integer'}, output:{type:'integer'}});
        const pipeline = await w.pipe([inc, twice]);
        const published = await w.publish(pipeline, 'pipeline');
        const pinned = await w.resolve('pipeline');
        await w.delete('pipeline', published.version);
        const values = await w.map(pinned, [1,2,3], 2);
        const factorial = await w.define('async (n, bindings, self) => n < 2 ? 1 : n * await self(n-1)',
            {input:{type:'integer',minimum:0}, output:{type:'integer'}});
        return {values, factorial:await factorial(5)};
    }"#).await.unwrap();
    assert_eq!(
        state.status,
        ExecutionStatus::Completed,
        "{:?} log={:?}",
        state.error,
        state.log
    );
    assert_eq!(
        state.result,
        Some(json!({"values":[6,8,10],"factorial":120}))
    );
}

#[tokio::test]
async fn hidden_lexical_capture_is_rejected_before_child_admission() {
    let runtime = CodeMode::new(
        Arc::new(MemoryStore::default()),
        LocalExecutor::default(),
        vec![],
    );
    let state = runtime
        .execute(
            r#"async () => {
        const secret = 41;
        return await codemode.workflows.define('async input => input + secret');
    }"#,
        )
        .await
        .unwrap();
    assert_eq!(state.status, ExecutionStatus::Error);
    assert!(state.error.unwrap().contains("WORKFLOW_CAPTURE"));
}

use async_trait::async_trait;
use multicast_codemode::{
    Connector, ConnectorDescription, ConnectorTool, RuntimeStore, ToolAnnotations, ToolContext,
    ToolPolicy, WorkflowLimits,
};
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::sync::Mutex;

#[derive(Default)]
struct Probe {
    active: AtomicUsize,
    maximum: AtomicUsize,
    events: Mutex<Vec<(bool, i64)>>,
    calls: AtomicUsize,
    approval: bool,
}
#[async_trait]
impl Connector for Probe {
    fn name(&self) -> &str {
        "probe"
    }
    async fn describe(&self) -> Result<ConnectorDescription, String> {
        Ok(ConnectorDescription {
            name: "probe".into(),
            instructions: None,
            tools: vec![ConnectorTool {
                name: "run".into(),
                description: None,
                input_schema: json!({"type":"object"}),
                output_schema: None,
                instructions: None,
                examples: vec![],
                annotations: ToolAnnotations::default(),
                policy: ToolPolicy {
                    requires_approval: self.approval,
                    ..Default::default()
                },
            }],
        })
    }
    async fn execute(
        &self,
        _method: &str,
        args: serde_json::Value,
        _context: &ToolContext,
    ) -> Result<serde_json::Value, String> {
        self.calls.fetch_add(1, Ordering::SeqCst);
        let id = args["id"].as_i64().unwrap_or(0);
        self.events.lock().await.push((true, id));
        let active = self.active.fetch_add(1, Ordering::SeqCst) + 1;
        self.maximum.fetch_max(active, Ordering::SeqCst);
        if args["block"] == true {
            return std::future::pending().await;
        }
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        self.events.lock().await.push((false, id));
        self.active.fetch_sub(1, Ordering::SeqCst);
        Ok(json!(id * 10))
    }
}
fn runtime_with(probe: Arc<Probe>, limits: WorkflowLimits) -> CodeMode {
    CodeMode::new(
        Arc::new(MemoryStore::default()),
        LocalExecutor::default(),
        vec![probe],
    )
    .with_workflow_limits(limits)
    .unwrap()
}

#[tokio::test]
async fn map_measures_overlapping_effects_with_two_slots_and_preserves_input_order() {
    let probe = Arc::new(Probe::default());
    let runtime = runtime_with(
        probe.clone(),
        WorkflowLimits {
            concurrency: 2,
            ..Default::default()
        },
    );
    let state = tokio::time::timeout(
        std::time::Duration::from_secs(10),
        runtime.execute(
            r#"async () =>{
        const w=codemode.workflows;
        const f=await w.define('async id => probe.run({id})');
        return await w.map(f,[3,1,4,2,5],2);
    }"#,
        ),
    )
    .await
    .expect("parallel scheduler stalled")
    .unwrap();
    assert_eq!(
        state.status,
        ExecutionStatus::Completed,
        "{:?}",
        state.error
    );
    assert_eq!(state.result, Some(json!([30, 10, 40, 20, 50])));
    assert_eq!(probe.maximum.load(Ordering::SeqCst), 2);
    let events = probe.events.lock().await;
    assert!(
        events[0].0 && events[1].0 && !events[2].0,
        "two independent starts must precede a finish: {events:?}"
    );
}

#[tokio::test]
async fn mutual_recursion_releases_the_only_execution_slot() {
    let runtime = runtime_with(
        Arc::new(Probe::default()),
        WorkflowLimits {
            concurrency: 1,
            ..Default::default()
        },
    );
    let state = runtime
        .execute(
            r#"async () =>{
        const pair=await codemode.workflows.bundle({
            even:{source:'async (n,b,self,peers)=>n===0?true:await peers.odd(n-1)'},
            odd:{source:'async (n,b,self,peers)=>n===0?false:await peers.even(n-1)'}
        });
        return await pair.even(8);
    }"#,
        )
        .await
        .unwrap();
    assert_eq!(
        state.status,
        ExecutionStatus::Completed,
        "{:?}",
        state.error
    );
    assert_eq!(state.result, Some(json!(true)));
}

#[tokio::test]
async fn root_depth_and_admission_budgets_do_not_reset_in_recursive_children() {
    for limits in [
        WorkflowLimits {
            depth: 3,
            ..Default::default()
        },
        WorkflowLimits {
            admissions: 3,
            ..Default::default()
        },
    ] {
        let runtime = runtime_with(Arc::new(Probe::default()), limits);
        let state=runtime.execute(r#"async () =>{const f=await codemode.workflows.define('async (n,b,self)=>n?await self(n-1):0');return await f(20);}"#).await.unwrap();
        assert_eq!(state.status, ExecutionStatus::Error);
        assert!(
            state
                .error
                .as_deref()
                .is_some_and(|s| s.contains("WORKFLOW_DEPTH") || s.contains("WORKFLOW_ADMISSIONS")),
            "{:?}",
            state.error
        );
    }
}

#[tokio::test]
async fn child_approval_is_visible_and_only_approval_continues_the_tree() {
    let probe = Arc::new(Probe {
        approval: true,
        ..Default::default()
    });
    let runtime = runtime_with(probe.clone(), WorkflowLimits::default());
    let root=runtime.execute(r#"async () =>{const f=await codemode.workflows.define('async id=>probe.run({id})');return (await f(7))+1;}"#).await.unwrap();
    assert_eq!(root.status, ExecutionStatus::Paused);
    assert!(root.workflow_wait.is_some());
    assert_eq!(probe.calls.load(Ordering::SeqCst), 0);
    assert!(runtime.resume(&root.id).await.is_err());
    let pending = runtime.runtime().pending(None).await.unwrap();
    assert_eq!(pending.len(), 1);
    assert_ne!(pending[0].execution_id, root.id);
    runtime
        .approve(&pending[0].execution_id, pending[0].seq)
        .await
        .unwrap();
    let completed = runtime.execution(&root.id).await.unwrap();
    assert_eq!(
        completed.status,
        ExecutionStatus::Completed,
        "{:?}",
        completed.error
    );
    assert_eq!(completed.result, Some(json!(71)));
    assert_eq!(probe.calls.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn invalid_output_stops_the_next_effect() {
    let probe = Arc::new(Probe::default());
    let runtime = runtime_with(probe.clone(), WorkflowLimits::default());
    let state = runtime
        .execute(
            r#"async () =>{const w=codemode.workflows;
        const bad=await w.define('async () =>"wrong"',{output:{type:'integer'}});
        const effect=await w.define('async id=>probe.run({id})');
        return await (await w.pipe([bad,effect]))(0);
    }"#,
        )
        .await
        .unwrap();
    assert_eq!(state.status, ExecutionStatus::Error);
    assert!(state.error.unwrap().contains("WORKFLOW_OUTPUT"));
    assert_eq!(probe.calls.load(Ordering::SeqCst), 0);
}

#[tokio::test]
async fn fail_fast_cancels_a_sibling_blocked_in_an_effect() {
    let probe = Arc::new(Probe::default());
    let runtime = runtime_with(probe.clone(), WorkflowLimits::default());
    let state=tokio::time::timeout(std::time::Duration::from_secs(5),runtime.execute(r#"async () =>{const w=codemode.workflows;
        const f=await w.define('async id=>{if(id===1)throw new Error("child failed");return await probe.run({id,block:true});}');
        return await w.map(f,[0,1],2);
    }"#)).await.expect("fail-fast left a blocked sibling").unwrap();
    assert_eq!(state.status, ExecutionStatus::Error);
    let children = runtime.runtime().executions().await.unwrap();
    assert!(
        children
            .iter()
            .any(|s| s.status == ExecutionStatus::Cancelled)
    );
    assert!(
        !children
            .iter()
            .any(|s| matches!(s.status, ExecutionStatus::Running | ExecutionStatus::Paused))
    );
}

#[tokio::test]
async fn settle_collects_outcomes_and_unawaited_children_are_joined() {
    let runtime = runtime_with(Arc::new(Probe::default()), WorkflowLimits::default());
    let state = runtime
        .execute(
            r#"async () =>{const w=codemode.workflows;
        const f=await w.define('async x=>{if(x<0)throw new Error("negative");return x*2;}');
        const a=await f.start(3), b=await f.start(-1);
        return await w.settle([a,b]);
    }"#,
        )
        .await
        .unwrap();
    assert_eq!(
        state.status,
        ExecutionStatus::Completed,
        "{:?}",
        state.error
    );
    assert_eq!(
        state.result,
        Some(json!([{"status":"fulfilled","value":6},{"status":"rejected","reason":"negative"}]))
    );
    let state=runtime.execute(r#"async () =>{const f=await codemode.workflows.define('async id=>probe.run({id})');await f.start(2);return 99;}"#).await.unwrap();
    assert_eq!(state.status, ExecutionStatus::Completed);
    assert!(
        runtime
            .runtime()
            .executions()
            .await
            .unwrap()
            .iter()
            .all(|s| !matches!(s.status, ExecutionStatus::Running | ExecutionStatus::Paused))
    );
}

#[tokio::test]
async fn scope_expiration_and_publication_retain_only_the_needed_graph() {
    let store = Arc::new(MemoryStore::default());
    let runtime = CodeMode::new(store.clone(), LocalExecutor::default(), vec![]);
    let state=runtime.execute(r#"async () =>{const w=codemode.workflows;
        const expired=await w.scope(async scope=>await scope.define('async x=>x+9'));
        let expiredCode;try {await expired(1);} catch(error) {expiredCode=error.message;}
        await w.scope(async scope=>{const a=await scope.define('async x=>x+1');const b=await scope.define('async x=>x*3');const p=await scope.pipe([a,b]);await scope.publish(p,'retained');});
        return expiredCode;
    }"#).await.unwrap();
    assert_eq!(
        state.status,
        ExecutionStatus::Completed,
        "{:?}",
        state.error
    );
    assert!(
        state
            .result
            .unwrap()
            .as_str()
            .unwrap()
            .contains("WORKFLOW_REFERENCE")
    );
    let state = runtime
        .execute(r#"async () =>await (await codemode.workflows.resolve('retained'))(4)"#)
        .await
        .unwrap();
    assert_eq!(state.result, Some(json!(15)), "{:?}", state.error);
    let catalog = store.get_workflows().await.unwrap().unwrap();
    assert_eq!(catalog["definitions"].as_object().unwrap().len(), 3);
}

#[tokio::test]
async fn publication_cas_permission_and_foreign_references_fail_closed() {
    let runtime = runtime_with(Arc::new(Probe::default()), WorkflowLimits::default());
    let state=runtime.execute(r#"async () =>{const w=codemode.workflows;
        const f=await w.define('async x=>x');const p=await w.publish(f,'p',null);
        const failures=[];
        try {await w.publish(f,'p',null);}catch(e){failures.push(e.message);}
        try {await w.delete('p','stale');}catch(e){failures.push(e.message);}
        try {await w.hydrate({__workflow_ref:{...f.__workflow_ref,store:'foreign'}})(1);}catch(e){failures.push(e.message);}
        return failures;
    }"#).await.unwrap();
    assert_eq!(state.status, ExecutionStatus::Completed);
    let messages = state.result.unwrap();
    assert_eq!(messages.as_array().unwrap().len(), 3);
    assert!(messages[0].as_str().unwrap().contains("WORKFLOW_VERSION"));
    assert!(messages[1].as_str().unwrap().contains("WORKFLOW_VERSION"));
    assert!(messages[2].as_str().unwrap().contains("WORKFLOW_REFERENCE"));
    let runtime = runtime_with(
        Arc::new(Probe::default()),
        WorkflowLimits {
            allow_publication: false,
            ..Default::default()
        },
    );
    let state=runtime.execute(r#"async () =>{const w=codemode.workflows;return await w.publish(await w.define('async x=>x'),'no');}"#).await.unwrap();
    assert_eq!(state.status, ExecutionStatus::Error);
    assert!(state.error.unwrap().contains("WORKFLOW_PERMISSION"));
}

#[tokio::test]
async fn publish_requires_the_latest_run_to_verify() {
    let gated = || {
        runtime_with(
            Arc::new(Probe::default()),
            WorkflowLimits {
                publish_requires: Some("/verified".into()),
                ..Default::default()
            },
        )
    };
    let refused = gated()
        .execute(
            r#"async () =>{const w=codemode.workflows;const failures=[];
        const f=await w.define('async x=>({verified:x})');
        try {await w.publish(f,'never_ran');}catch(e){failures.push(e.message);}
        await f(false);
        try {await w.publish(f,'ran_unverified');}catch(e){failures.push(e.message);}
        await f(true); await f(false);
        try {await w.publish(f,'verified_then_failed');}catch(e){failures.push(e.message);}
        return failures;
    }"#,
        )
        .await
        .unwrap();
    assert_eq!(
        refused.status,
        ExecutionStatus::Completed,
        "{:?}",
        refused.error
    );
    let messages = refused.result.unwrap();
    assert_eq!(messages.as_array().unwrap().len(), 3, "{messages}");
    for m in messages.as_array().unwrap() {
        assert!(m.as_str().unwrap().contains("WORKFLOW_UNVERIFIED"), "{m}");
    }
    let allowed = gated()
        .execute(
            r#"async () =>{const w=codemode.workflows;
        const f=await w.define('async x=>({verified:x})');
        await f(false); await f(true);
        return (await w.publish(f,'works')).name;
    }"#,
        )
        .await
        .unwrap();
    assert_eq!(
        allowed.status,
        ExecutionStatus::Completed,
        "{:?}",
        allowed.error
    );
    assert_eq!(allowed.result, Some(json!("works")));
}

#[tokio::test]
async fn saving_outside_a_program_cannot_skip_the_publish_check() {
    let runtime = runtime_with(
        Arc::new(Probe::default()),
        WorkflowLimits {
            publish_requires: Some("/verified".into()),
            ..Default::default()
        },
    );
    let unrun = runtime
        .publish_snippet("never_ran", "d", "async () => ({verified:true})", None)
        .await
        .unwrap_err();
    assert!(unrun.contains("WORKFLOW_UNVERIFIED"), "{unrun}");
    let failed = runtime
        .execute("async () => ({verified:false})")
        .await
        .unwrap();
    let refused = runtime
        .save_snippet("ran_unverified", "d", &failed.id, None)
        .await
        .unwrap_err();
    assert!(refused.contains("WORKFLOW_UNVERIFIED"), "{refused}");
    let passed = runtime
        .execute("async () => ({verified:true})")
        .await
        .unwrap();
    runtime
        .save_snippet("ran_verified", "d", &passed.id, None)
        .await
        .unwrap();
    let open = runtime_with(Arc::new(Probe::default()), WorkflowLimits::default());
    open.publish_snippet("ungated", "d", "async () => 1", None)
        .await
        .unwrap();
}

#[tokio::test]
async fn a_checked_publish_keeps_its_description_for_search() {
    let runtime = runtime_with(Arc::new(Probe::default()), WorkflowLimits::default());
    let out = runtime
        .execute(
            r#"async () =>{const w=codemode.workflows;
        const f=await w.define('async x=>x'); await f(1);
        await w.publish(f,'described_route',null,'walk to a named trader and greet them');
        const g=await w.define('async x=>x+1'); await g(1);
        await w.publish(g,'bare_route');
        return 1;
    }"#,
        )
        .await
        .unwrap();
    assert_eq!(out.status, ExecutionStatus::Completed, "{:?}", out.error);
    let found = runtime.search("route").await.unwrap();
    let describe = |name: &str| {
        found
            .results
            .iter()
            .find(|r| r.method == name)
            .and_then(|r| r.description.clone())
            .unwrap_or_default()
    };
    assert_eq!(
        describe("described_route"),
        "walk to a named trader and greet them",
        "{:?}",
        found.results
    );
    assert_eq!(describe("bare_route"), "Published callable workflow");
}

#[tokio::test]
async fn search_flags_a_published_workflow_that_keeps_failing() {
    let runtime = runtime_with(Arc::new(Probe::default()), WorkflowLimits::default());
    let out = runtime
        .execute(
            r#"async () =>{const w=codemode.workflows;
        const f=await w.define('async x=>{ if (x) throw new Error("boom"); return 1; }');
        await f(false);
        const g=await w.define('async x=>x');
        await g(1);
        await w.publish(f,'flaky_route'); await w.publish(g,'steady_route');
        for (const bad of [true,true,false,true]) { try { await f(bad); } catch (e) {} }
        await g(2);
        return 1;
    }"#,
        )
        .await
        .unwrap();
    assert_eq!(out.status, ExecutionStatus::Completed, "{:?}", out.error);
    let found = runtime.search("route").await.unwrap();
    let describe = |name: &str| {
        found
            .results
            .iter()
            .find(|r| r.method == name)
            .and_then(|r| r.description.clone())
            .unwrap_or_default()
    };
    assert!(
        describe("flaky_route").contains("UNRELIABLE: failed 3 of its last 5"),
        "{:?}",
        found.results
    );
    assert!(
        !describe("steady_route").contains("UNRELIABLE"),
        "{:?}",
        found.results
    );
}

#[tokio::test]
async fn partial_binding_validates_the_complete_original_contract_and_rejects_override() {
    let runtime = runtime_with(Arc::new(Probe::default()), WorkflowLimits::default());
    let state=runtime.execute(r#"async () =>{const w=codemode.workflows;
        const f=await w.define('async x=>x.a+x.b',{input:{type:'object',required:['a','b'],properties:{a:{type:'integer'},b:{type:'integer'}},additionalProperties:false},output:{type:'integer'}});
        const g=await w.bind(f,{a:5});const result=await g({b:2});let error;
        try {await g({a:99,b:2});}catch(e){error=e.message;}
        return {result,error};
    }"#).await.unwrap();
    assert_eq!(
        state.status,
        ExecutionStatus::Completed,
        "{:?}",
        state.error
    );
    assert_eq!(state.result.as_ref().unwrap()["result"], 7);
    assert!(
        state.result.unwrap()["error"]
            .as_str()
            .unwrap()
            .contains("WORKFLOW_BIND_OVERRIDE")
    );
}

#[tokio::test]
async fn sqlite_restart_reuses_child_ids_and_approval_checkpoint() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("fluency.sqlite");
    let probe = Arc::new(Probe {
        approval: true,
        ..Default::default()
    });
    let (root, child, seq) = {
        let store = Arc::new(multicast_codemode_local::DurableStore::open(&path).unwrap());
        let runtime = CodeMode::new(store, LocalExecutor::default(), vec![probe.clone()]);
        let state=runtime.execute(r#"async () =>{const f=await codemode.workflows.define('async id=>probe.run({id})');return await f(8);}"#).await.unwrap();
        let pending = runtime.runtime().pending(None).await.unwrap().remove(0);
        (state.id, pending.execution_id, pending.seq)
    };
    let store = Arc::new(multicast_codemode_local::DurableStore::open(&path).unwrap());
    let runtime = CodeMode::new(store, LocalExecutor::default(), vec![probe.clone()]);
    let before = runtime.runtime().executions().await.unwrap().len();
    runtime
        .drive_if_idle(&root, Default::default())
        .await
        .unwrap();
    assert_eq!(runtime.runtime().executions().await.unwrap().len(), before);
    runtime.approve(&child, seq).await.unwrap();
    assert_eq!(
        runtime.execution(&root).await.unwrap().result,
        Some(json!(80))
    );
    assert_eq!(probe.calls.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn root_attempts_and_metadata_limits_stop_descendant_effects() {
    let probe = Arc::new(Probe::default());
    let runtime = runtime_with(
        probe.clone(),
        WorkflowLimits {
            attempts: 2,
            ..Default::default()
        },
    );
    let state = runtime.execute(r#"async () => { const w=codemode.workflows; const f=await w.define('async id=>probe.run({id})'); return await w.map(f,[1,2,3],1); }"#).await.unwrap();
    assert_eq!(state.status, ExecutionStatus::Error);
    assert!(state.error.unwrap().contains("WORKFLOW_ATTEMPTS"));
    assert_eq!(probe.calls.load(Ordering::SeqCst), 2);
    let probe = Arc::new(Probe::default());
    let runtime = runtime_with(
        probe.clone(),
        WorkflowLimits {
            bytes: 1024,
            ..Default::default()
        },
    );
    let state = runtime.execute(r#"async () => { const w=codemode.workflows; const f=await w.define('async (id,b)=>probe.run({id})',{}, {large:'x'.repeat(2048)}); return await f(1); }"#).await.unwrap();
    assert_eq!(state.status, ExecutionStatus::Error);
    assert!(state.error.unwrap().contains("WORKFLOW_BYTES"));
    assert_eq!(probe.calls.load(Ordering::SeqCst), 0);
}

#[tokio::test]
async fn absolute_deadline_interrupts_a_blocked_effect_and_expires_pending_approval() {
    let probe = Arc::new(Probe::default());
    let runtime = runtime_with(
        probe.clone(),
        WorkflowLimits {
            lifetime_ms: 500,
            ..Default::default()
        },
    );
    let state = tokio::time::timeout(std::time::Duration::from_secs(3), runtime.execute(r#"async () => {const f=await codemode.workflows.define('async id=>probe.run({id,block:true})');return await f(1);}"#)).await.expect("deadline did not interrupt active effect").unwrap();
    assert_eq!(state.status, ExecutionStatus::Error);
    assert!(state.error.unwrap().contains("WORKFLOW_DEADLINE"));
    assert_eq!(probe.calls.load(Ordering::SeqCst), 1);
    assert!(
        runtime
            .runtime()
            .executions()
            .await
            .unwrap()
            .iter()
            .all(|s| !matches!(s.status, ExecutionStatus::Running | ExecutionStatus::Paused))
    );
    let probe = Arc::new(Probe {
        approval: true,
        ..Default::default()
    });
    let runtime = runtime_with(
        probe.clone(),
        WorkflowLimits {
            lifetime_ms: 200,
            ..Default::default()
        },
    );
    let state = runtime.execute(r#"async () => {const f=await codemode.workflows.define('async id=>probe.run({id})');return await f(1);}"#).await.unwrap();
    assert_eq!(state.status, ExecutionStatus::Paused);
    tokio::time::sleep(std::time::Duration::from_millis(220)).await;
    runtime
        .drive_if_idle(&state.id, Default::default())
        .await
        .unwrap();
    assert_eq!(
        runtime.execution(&state.id).await.unwrap().status,
        ExecutionStatus::Error
    );
    assert_eq!(probe.calls.load(Ordering::SeqCst), 0);
    assert!(runtime.runtime().pending(None).await.unwrap().is_empty());
}

#[tokio::test]
async fn child_rejection_and_parent_cancellation_stop_the_owned_tree() {
    let probe = Arc::new(Probe {
        approval: true,
        ..Default::default()
    });
    let runtime = runtime_with(probe.clone(), WorkflowLimits::default());
    let code = r#"async () => {const f=await codemode.workflows.define('async id=>probe.run({id})');return await f(7);}"#;
    let state = runtime.execute(code).await.unwrap();
    let pending = runtime
        .runtime()
        .pending(Some(&state.id))
        .await
        .unwrap()
        .remove(0);
    runtime
        .reject(&pending.execution_id, pending.seq)
        .await
        .unwrap();
    assert_eq!(
        runtime.execution(&state.id).await.unwrap().status,
        ExecutionStatus::Error
    );
    let state = runtime.execute(code).await.unwrap();
    runtime.cancel(&state.id).await.unwrap();
    assert_eq!(
        runtime.execution(&state.id).await.unwrap().status,
        ExecutionStatus::Cancelled
    );
    assert!(
        runtime
            .runtime()
            .pending(Some(&state.id))
            .await
            .unwrap()
            .is_empty()
    );
    assert_eq!(probe.calls.load(Ordering::SeqCst), 0);
}

#[tokio::test]
async fn pinned_versions_and_contract_discovery_survive_publication_replacement() {
    let runtime = runtime_with(Arc::new(Probe::default()), WorkflowLimits::default());
    let state=runtime.execute(r#"async () => {const w=codemode.workflows;
        const a=await w.define('async n=>n+1',{input:{type:'integer'},output:{type:'integer'}});
        const p=await w.publish(a,'replace');const old=await w.resolve('replace');
        const b=await w.define('async n=>n+100',{input:{type:'integer'},output:{type:'integer'}});
        await w.publish(b,'replace',p.version);
        const fresh=await w.resolve('replace');
        const same=await w.pipe([a,b]);const unknown=await w.pipe([a,await w.define('async n=>n',{input:{type:'number'}})]);
        let incompatible;try {await w.pipe([a,await w.define('async x=>x',{input:{type:'string'}})]);} catch(e){incompatible=e.message;}
        return {old:await old(1),fresh:await fresh(1),same:same.compatibility,unknown:unknown.compatibility,contract:await w.inspect(a),incompatible};
    }"#).await.unwrap();
    assert_eq!(
        state.status,
        ExecutionStatus::Completed,
        "{:?}",
        state.error
    );
    let value = state.result.unwrap();
    assert_eq!(value["old"], 2);
    assert_eq!(value["fresh"], 101);
    assert_eq!(value["same"], json!(["compatible"]));
    assert_eq!(value["unknown"], json!(["unknown"]));
    assert_eq!(value["contract"]["input"], json!({"type":"integer"}));
    assert!(
        value["contract"]["types"]
            .as_str()
            .unwrap()
            .contains("number")
    );
    assert!(
        value["incompatible"]
            .as_str()
            .unwrap()
            .contains("WORKFLOW_SCHEMA_INCOMPATIBLE")
    );
    let found = runtime.search("workflow define").await.unwrap();
    assert!(
        found
            .results
            .iter()
            .any(|r| r.path == "codemode.workflows.define")
    );
}

#[tokio::test]
async fn missing_bound_child_never_creates_a_replacement() {
    let store = Arc::new(MemoryStore::default());
    let probe = Arc::new(Probe {
        approval: true,
        ..Default::default()
    });
    let runtime = CodeMode::new(store.clone(), LocalExecutor::default(), vec![probe.clone()]);
    let root=runtime.execute(r#"async () => {const f=await codemode.workflows.define('async id=>probe.run({id})');return await f(7);}"#).await.unwrap();
    let pending = runtime
        .runtime()
        .pending(Some(&root.id))
        .await
        .unwrap()
        .remove(0);
    store.delete_execution(&pending.execution_id).await.unwrap();
    let before = store.list_executions().await.unwrap().len();
    let error = runtime
        .drive_if_idle(&root.id, Default::default())
        .await
        .unwrap_err();
    assert!(error.contains("WORKFLOW_BOUND_CHILD_MISSING"), "{error}");
    assert_eq!(store.list_executions().await.unwrap().len(), before);
    assert_eq!(probe.calls.load(Ordering::SeqCst), 0);
}

#[tokio::test]
async fn release_keeps_a_live_childs_definition_until_approval_and_retention_expire() {
    let store = Arc::new(MemoryStore::default());
    let probe = Arc::new(Probe {
        approval: true,
        ..Default::default()
    });
    let runtime = CodeMode::new(store.clone(), LocalExecutor::default(), vec![probe.clone()]);
    let root=runtime.execute(r#"async () => {const w=codemode.workflows;const f=await w.define('async id=>probe.run({id})');const run=await f.start(3);await w.release(f);return await run.result();}"#).await.unwrap();
    assert_eq!(root.status, ExecutionStatus::Paused);
    let pending = runtime
        .runtime()
        .pending(Some(&root.id))
        .await
        .unwrap()
        .remove(0);
    assert_eq!(
        store.get_workflows().await.unwrap().unwrap()["definitions"]
            .as_object()
            .unwrap()
            .len(),
        1
    );
    runtime
        .approve(&pending.execution_id, pending.seq)
        .await
        .unwrap();
    assert_eq!(
        runtime.execution(&root.id).await.unwrap().result,
        Some(json!(30))
    );
    assert_eq!(probe.calls.load(Ordering::SeqCst), 1);
    runtime.runtime().prune_at(0, u64::MAX).await.unwrap();
    // A new pass runs the same idempotent sweeper after execution retention is gone.
    runtime.execute("return 0;").await.unwrap();
    assert_eq!(
        store.get_workflows().await.unwrap().unwrap()["definitions"]
            .as_object()
            .unwrap()
            .len(),
        0
    );
}

#[tokio::test]
async fn heap_checkpoints_count_against_root_retained_storage() {
    let probe = Arc::new(Probe::default());
    let runtime = runtime_with(
        probe.clone(),
        WorkflowLimits {
            bytes: 16_384,
            ..Default::default()
        },
    );
    let state=runtime.execute("async () => { const payload='x'.repeat(50000); return await probe.run({id:payload.length}); } ").await.unwrap();
    assert_eq!(state.status, ExecutionStatus::Error, "{:?}", state.error);
    assert!(state.error.unwrap().contains("WORKFLOW_BYTES"));
    assert_eq!(probe.calls.load(Ordering::SeqCst), 0);
}

#[tokio::test]
async fn measure_direct_and_fluent_cold_and_warm_execution() {
    let mut measurements = Vec::new();
    for (mode, code) in [
        (
            "direct",
            "async () => { const values=[]; for (const id of [1,2,3,4,5]) values.push(await probe.run({id})); return values; }",
        ),
        (
            "fluent",
            "async () => { const f=await codemode.workflows.define('async id=>probe.run({id})'); return await codemode.workflows.map(f,[1,2,3,4,5],2); }",
        ),
    ] {
        let store = Arc::new(MemoryStore::default());
        let probe = Arc::new(Probe::default());
        let runtime = CodeMode::new(store.clone(), LocalExecutor::default(), vec![probe.clone()]);
        for temperature in ["cold", "warm"] {
            let before = probe.calls.load(Ordering::SeqCst);
            let start = std::time::Instant::now();
            let state = runtime.execute(code).await.unwrap();
            let elapsed_ms = start.elapsed().as_secs_f64() * 1000.0;
            assert_eq!(
                state.status,
                ExecutionStatus::Completed,
                "{:?}",
                state.error
            );
            assert_eq!(state.result, Some(json!([10, 20, 30, 40, 50])));
            let state = runtime
                .runtime()
                .execution_snapshot(&state.id)
                .await
                .unwrap()
                .unwrap();
            let children = state.workflow_children.len();
            let mut ids = vec![state.id.clone()];
            ids.extend(state.workflow_children.iter().map(|c| c.id.clone()));
            let mut checkpoint_bytes = 0;
            let mut execution_bytes = 0;
            let mut dispatches = 0;
            for id in ids {
                if let Some(checkpoint) = store.get_checkpoint(&id).await.unwrap() {
                    checkpoint_bytes += serde_json::to_vec(&checkpoint).unwrap().len();
                }
                let execution = store.get_execution(&id).await.unwrap().unwrap();
                dispatches += execution.log.len();
                execution_bytes += serde_json::to_vec(&execution).unwrap().len();
            }
            let catalog = store.get_workflows().await.unwrap().unwrap();
            // Measured five-effect fixture: gate retained size, not scheduler-sensitive time.
            assert!(
                checkpoint_bytes <= 131_072,
                "checkpoint bytes: {checkpoint_bytes}"
            );
            assert!(catalog["roots"][&state.id]["bytes"].as_u64().unwrap() <= 262_144);
            assert!(runtime.instructions().await.unwrap().len() <= 4096);
            if let Ok(path) = std::env::var("MULTICAST_WORKFLOW_TYPES_OUTPUT") {
                std::fs::write(path, runtime.instructions().await.unwrap()).unwrap();
            }
            measurements.push(json!({"mode":mode,"temperature":temperature,"elapsedMs":elapsed_ms,"effects":probe.calls.load(Ordering::SeqCst)-before,"children":children,"hostDispatches":dispatches,"checkpointBytes":checkpoint_bytes,"executionBytes":execution_bytes,"rootRetainedBytes":catalog["roots"][&state.id]["bytes"],"discoveryBytes":runtime.instructions().await.unwrap().len()}));
        }
    }
    println!(
        "WORKFLOW_MEASUREMENTS={}",
        serde_json::to_string(&measurements).unwrap()
    );
}