harn-vm 0.10.140

Async bytecode virtual machine for the Harn programming language
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
//! Structured concurrency: starting work, and stopping it.
//!
//! `parallel` and `parallel each` blocks with their fail-fast, settle, and
//! stream-break semantics (including that a failing branch cancels its slow
//! siblings and that the lowest-index error wins), spawn/await/cancel, the LIFO
//! signal-handler stack and interrupt handlers, and deadlines — which must
//! interrupt an async sleep and kill a blocking subprocess.

use crate::compiler::Compiler;
use crate::stdlib::register_vm_stdlib;
use crate::VmValue;
use harn_lexer::Lexer;
use harn_parser::Parser;
use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Duration;

use super::harness::*;
use crate::vm::*;
#[test]
fn test_parallel_basic() {
    let out = run_output(
        "pipeline t(harness: Harness, task: unknown) { const results = parallel(3) { i -> i * 10 }\nharness.stdio.log(results) }",
    );
    assert_eq!(out, "[harn] [0, 10, 20]");
}

#[test]
fn test_parallel_no_variable() {
    let out = run_output(
        "pipeline t(harness: Harness, task: unknown) { const results = parallel(3) { 42 }\nharness.stdio.log(results) }",
    );
    assert_eq!(out, "[harn] [42, 42, 42]");
}

#[test]
fn test_parallel_each_basic() {
    let out = run_output(
        "pipeline t(harness: Harness, task: unknown) { const results = parallel each [1, 2, 3] { x -> x * x }\nharness.stdio.log(results) }",
    );
    assert_eq!(out, "[harn] [1, 4, 9]");
}

#[tokio::test(flavor = "current_thread", start_paused = true)]
async fn test_parallel_fail_fast_cancels_slow_sibling() {
    // A branch error aborts in-flight siblings: the slow branch is cancelled
    // mid-sleep and never reaches its atomic_set, even though the pipeline
    // keeps running well past the sibling's would-be completion time.
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let handle = tokio::task::spawn_local(async {
                run_harn_result_async(
                    r#"pipeline t(harness: Harness, task: unknown) {
const survived = harness.runtime.atomic(0)
const sibling_started = harness.runtime.atomic(0)
try {
  parallel 2 { i ->
    if i == 0 {
      while harness.runtime.atomic_get(sibling_started) == 0 {
        harness.runtime.yield_now()
      }
      throw "boom"
    }
    harness.runtime.atomic_set(sibling_started, 1)
    harness.clock.sleep_ms(5000)
    harness.runtime.atomic_set(survived, 1)
    i
  }
} catch (e) {
  harness.stdio.log("caught: " + e)
}
harness.clock.sleep_ms(20000)
harness.stdio.log(harness.runtime.atomic_get(survived))
}"#,
                )
                .await
            });
            let (output, _) = handle.await.expect("join VM task").expect("run Harn");
            assert_eq!(output.trim_end(), "[harn] caught: boom\n[harn] 0");
        })
        .await;
}

#[tokio::test(flavor = "current_thread", start_paused = true)]
async fn test_parallel_each_fail_fast_cancels_slow_sibling() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let handle = tokio::task::spawn_local(async {
                run_harn_result_async(
                    r#"pipeline t(harness: Harness, task: unknown) {
const survived = harness.runtime.atomic(0)
const sibling_started = harness.runtime.atomic(0)
try {
  parallel each ["fail", "slow"] { item ->
    if item == "fail" {
      while harness.runtime.atomic_get(sibling_started) == 0 {
        harness.runtime.yield_now()
      }
      throw "each boom"
    }
    harness.runtime.atomic_set(sibling_started, 1)
    harness.clock.sleep_ms(5000)
    harness.runtime.atomic_set(survived, 1)
    item
  }
} catch (e) {
  harness.stdio.log("caught: " + e)
}
harness.clock.sleep_ms(20000)
harness.stdio.log(harness.runtime.atomic_get(survived))
}"#,
                )
                .await
            });
            let (output, _) = handle.await.expect("join VM task").expect("run Harn");
            assert_eq!(output.trim_end(), "[harn] caught: each boom\n[harn] 0");
        })
        .await;
}

#[test]
fn test_parallel_fail_fast_skips_unstarted_branches() {
    // With max_concurrent: 1, the first branch's error means the queued
    // branches are never started at all — fully deterministic, no timing.
    let out = run_output(
        r#"pipeline t(harness: Harness, task: unknown) {
const started = harness.runtime.atomic(0)
try {
  parallel each [1, 2, 3] with { max_concurrent: 1 } { n ->
    if n == 1 {
      throw "stop"
    }
    harness.runtime.atomic_add(started, 1)
    n
  }
} catch (e) {
  harness.stdio.log(e)
}
harness.stdio.log(harness.runtime.atomic_get(started))
}"#,
    );
    assert_eq!(out, "[harn] stop\n[harn] 0");
}

#[test]
fn test_parallel_fail_fast_reports_lowest_index_error() {
    // Both branches throw on their first poll, so both errors have settled
    // by the time the abort lands; the reported error must deterministically
    // be the lowest-source-index one (the `scope { }` convention), not
    // whichever happened to join first.
    let out = run_output(
        r#"pipeline t(harness: Harness, task: unknown) {
try {
  parallel each ["first", "second"] { word ->
    throw word
  }
} catch (e) {
  harness.stdio.log(e)
}
}"#,
    );
    assert_eq!(out, "[harn] first");
}

#[tokio::test(flavor = "current_thread", start_paused = true)]
async fn test_parallel_settle_still_runs_all_branches() {
    // `parallel settle` keeps the draining semantics: a failing branch does
    // not cancel siblings, so both slow branches still complete.
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let handle = tokio::task::spawn_local(async {
                run_harn_result_async(
                    r#"pipeline t(harness: Harness, task: unknown) {
const completed = harness.runtime.atomic(0)
const outcome = parallel settle [1, 2, 3] { item ->
  if item == 1 {
    throw "early failure"
  }
  harness.clock.sleep_ms(5000)
  harness.runtime.atomic_add(completed, 1)
  item * 10
}
harness.stdio.log(outcome.succeeded)
harness.stdio.log(outcome.failed)
harness.stdio.log(harness.runtime.atomic_get(completed))
}"#,
                )
                .await
            });
            tokio::task::yield_now().await;
            tokio::time::advance(Duration::from_secs(30)).await;
            let (output, _) = handle.await.expect("join VM task").expect("run Harn");
            assert_eq!(output.trim_end(), "[harn] 2\n[harn] 1\n[harn] 2");
        })
        .await;
}

#[tokio::test(flavor = "current_thread", start_paused = true)]
async fn test_parallel_each_stream_break_cancels_remaining_work() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let handle = tokio::task::spawn_local(async {
                run_harn_result_async(
                    r"pipeline t(harness: Harness, task: unknown) {
const completed = harness.runtime.atomic(0)
const results = parallel each [1, 2, 3] with { max_concurrent: 1 } { item ->
  harness.clock.sleep_ms(1000)
  harness.runtime.atomic_add(completed, 1)
  return item
} as stream
for item in results {
  break
}
harness.clock.sleep_ms(3000)
harness.stdio.log(harness.runtime.atomic_get(completed))
}",
                )
                .await
            });
            tokio::task::yield_now().await;
            tokio::time::advance(Duration::from_secs(4)).await;
            let (output, _) = handle.await.expect("join VM task").expect("run Harn");
            assert_eq!(output.trim_end(), "[harn] 1");
        })
        .await;
}

#[test]
fn test_spawn_await() {
    let out = run_output(
        r#"pipeline t(harness: Harness, task: unknown) {
const handle = spawn { harness.stdio.log("spawned") }
const result = await(handle)
harness.stdio.log("done")
}"#,
    );
    assert_eq!(out, "[harn] spawned\n[harn] done");
}

#[test]
fn test_spawn_cancel() {
    let out = run_output(
        r#"pipeline t(harness: Harness, task: unknown) {
const handle = spawn { harness.stdio.log("should be cancelled") }
cancel(handle)
harness.stdio.log("cancelled")
}"#,
    );
    assert_eq!(out, "[harn] cancelled");
}

#[test]
fn test_cancel_graceful_propagates_to_cpu_bound_spawn() {
    let out = run_output(
        r#"pipeline t(harness: Harness, task: unknown) {
const handle = spawn {
  let i = 0
  while true {
    i = i + 1
  }
}
const result = cancel_graceful(handle, 100ms)
harness.stdio.log(is_err(result))
harness.stdio.log(contains(unwrap_err(result), "cancelled"))
}"#,
    );
    assert_eq!(out, "[harn] true\n[harn] true");
}

#[test]
fn test_std_signal_handlers_are_lifo_and_removable() {
    let out = run_output(
        r#"
import "std/signal"

pipeline t(harness: Harness) {
  const first = on_interrupt({ -> harness.stdio.log("a") }, {once: false})
  const second = on_interrupt({ -> harness.stdio.log("b") }, {once: false})
  __signal_raise("SIGINT")
  off_interrupt(second)
  __signal_raise("SIGINT")
  harness.stdio.log(interrupted())
  off_interrupt(first.handle)
}
"#,
    );
    assert_eq!(out, "[harn] b\n[harn] a\n[harn] a\n[harn] true");
}

#[test]
fn test_with_interrupt_unregisters_after_throw() {
    let out = run_output(
        r#"
import "std/signal"

pipeline t(harness: Harness) {
  try {
    with_interrupt({ -> harness.stdio.log("leaked") }, { -> throw "boom" }, {once: false})
  } catch (e) {
  }
  const raised = try {
    __signal_raise("SIGINT")
    "not interrupted"
  } catch (e) {
    "interrupted"
  }
  harness.stdio.log(raised)
}
"#,
    );
    assert_eq!(out, "[harn] interrupted");
}

#[test]
fn test_interrupt_handler_graceful_timeout_is_enforced() {
    let out = run_output(
        r#"
import "std/signal"

pipeline t(harness: Harness) {
  on_interrupt({ ->
    let spin = 0
    while true { spin = spin + 1 }
  }, {graceful_timeout_ms: 0})
  const result = try {
    __signal_raise("SIGINT")
    "missed timeout"
  } catch (e) {
    e
  }
  harness.stdio.log(result)
}
"#,
    );
    assert_eq!(out, "[harn] kind:interrupted:handler_timeout");
}

#[test]
fn test_host_signal_token_dispatches_matching_signal() {
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap();
    rt.block_on(async {
        let mut vm = Vm::new();
        vm.register_builtin("term_marker", |_, out| {
            out.push_str("[harn] term\n");
            Ok(VmValue::Nil)
        });
        vm.register_builtin("int_marker", |_, out| {
            out.push_str("[harn] int\n");
            Ok(VmValue::Nil)
        });
        let term_options = VmValue::dict(BTreeMap::from([(
            "signals".to_string(),
            VmValue::List(std::sync::Arc::new(vec![VmValue::String(
                arcstr::ArcStr::from("SIGTERM"),
            )])),
        )]));
        let int_options = VmValue::dict(BTreeMap::from([(
            "signals".to_string(),
            VmValue::List(std::sync::Arc::new(vec![VmValue::String(
                arcstr::ArcStr::from("SIGINT"),
            )])),
        )]));
        vm.register_interrupt_handler(
            VmValue::BuiltinRef(arcstr::ArcStr::from("term_marker")),
            Some(&term_options),
        )
        .unwrap();
        vm.register_interrupt_handler(
            VmValue::BuiltinRef(arcstr::ArcStr::from("int_marker")),
            Some(&int_options),
        )
        .unwrap();

        let cancel_token = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(true));
        let signal_token = std::sync::Arc::new(std::sync::Mutex::new(Some("SIGTERM".to_string())));
        vm.install_interrupt_signal_token(signal_token);
        vm.install_cancel_token(cancel_token);

        assert!(vm.pending_scope_interrupt().await.is_none());
        assert_eq!(vm.output().trim_end(), "[harn] term");
    });
}

/// A clock whose sleep makes a cancellation observable the moment the sleep
/// begins, and then never completes.
///
/// The tests below need the cancellation to be noticed by the blocking
/// operation itself rather than by the poll between operations, because those
/// are the two observers whose disagreement is the defect. Arranging that with
/// a timer would make the test a race, and a test written to remove a timing
/// dependency must not introduce one. Setting the flag from inside the sleep
/// puts the cancellation exactly where it is needed, with no duration to tune:
/// the sleep future never resolves, so the operation's own cancel poll is the
/// only thing that can end it.
#[derive(Debug)]
struct CancelWhenSleepStarts {
    cancel: Arc<std::sync::atomic::AtomicBool>,
    signal: Option<Arc<std::sync::Mutex<Option<String>>>>,
}

#[async_trait::async_trait]
impl harn_clock::Clock for CancelWhenSleepStarts {
    fn now_utc(&self) -> time::OffsetDateTime {
        time::OffsetDateTime::UNIX_EPOCH
    }

    fn monotonic_ms(&self) -> i64 {
        0
    }

    async fn sleep(&self, _duration: Duration) {
        if let Some(slot) = &self.signal {
            *slot.lock().unwrap() = Some("SIGTERM".to_string());
        }
        self.cancel.store(true, std::sync::atomic::Ordering::SeqCst);
        std::future::pending::<()>().await;
    }

    async fn sleep_until_utc(&self, _deadline: time::OffsetDateTime) {
        std::future::pending::<()>().await;
    }
}

// Which observer of a cancellation actually runs the interrupt handlers.
//
// A cancellation is noticed independently in several places. The between-ops
// poll dispatches handlers; so does the op wrapper's timed-out branch. The
// body of a blocking op does not: the harness clock's sleep runs its own 10ms
// poll and returns the cancelled error directly, reaching neither dispatch
// site. Whichever observer wins the race therefore decides whether a handler
// the program registered runs at all.
//
// This drives the shape the SIGTERM conformance case uses - a registered
// handler, then a blocking sleep cancelled part way through - and asserts the
// handler ran. It exists to pin that arrangement rather than leave it to the
// race, and to say which observer fired when it is the one that skips
// dispatch.
#[test]
fn test_handler_runs_when_a_blocking_op_observes_the_cancel_itself() {
    let cancel_token = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let signal_token = std::sync::Arc::new(std::sync::Mutex::new(None::<String>));
    let signal_writer = std::sync::Arc::clone(&signal_token);
    let cancel_writer = std::sync::Arc::clone(&cancel_token);

    let source = r#"
pipeline t(harness: Harness) {
  const outcome = try {
    harness.clock.sleep_ms(30000)
    "slept"
  } catch (e) {
    "caught"
  }
  harness.stdio.log(outcome)
}
"#;

    let (output, _) = run_harn_with_setup(source, move |vm| {
        vm.register_builtin("term_marker", |_, out| {
            out.push_str("[harn] term\n");
            Ok(VmValue::Nil)
        });
        let term_options = VmValue::dict(BTreeMap::from([(
            "signals".to_string(),
            VmValue::List(std::sync::Arc::new(vec![VmValue::String(
                arcstr::ArcStr::from("SIGTERM"),
            )])),
        )]));
        vm.register_interrupt_handler(
            VmValue::BuiltinRef(arcstr::ArcStr::from("term_marker")),
            Some(&term_options),
        )
        .unwrap();
        vm.install_interrupt_signal_token(signal_token);
        vm.install_cancel_token(cancel_token);
        vm.set_harness(crate::Harness::with_clock(Arc::new(
            CancelWhenSleepStarts {
                cancel: cancel_writer,
                signal: Some(signal_writer),
            },
        )));
    })
    .unwrap();

    assert!(
        output.contains("caught"),
        "the blocking sleep should have been interrupted, got: {output}"
    );
    assert!(
        output.contains("term"),
        "the registered SIGTERM handler never ran, so the observer that skips \
         dispatch won the race. Output: {output}"
    );
}

#[test]
fn test_handler_runs_when_the_cancelled_op_is_not_caught() {
    let cancel_token = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let signal_token = std::sync::Arc::new(std::sync::Mutex::new(None::<String>));
    let signal_writer = std::sync::Arc::clone(&signal_token);
    let cancel_writer = std::sync::Arc::clone(&cancel_token);
    let ran = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let ran_in_handler = std::sync::Arc::clone(&ran);

    // The same cancellation as the caught case, with the catch removed. The
    // handler dispatch that actually runs in the caught case happens on the
    // poll AFTER the op threw, so it depends on the program continuing to
    // execute. Nothing here continues.
    let source = r#"
pipeline t(harness: Harness) {
  harness.clock.sleep_ms(30000)
  harness.stdio.log("slept")
}
"#;

    let _ = run_harn_with_setup(source, move |vm| {
        vm.register_builtin("term_marker", move |_, out| {
            ran_in_handler.store(true, std::sync::atomic::Ordering::SeqCst);
            out.push_str("[harn] term\n");
            Ok(VmValue::Nil)
        });
        let term_options = VmValue::dict(BTreeMap::from([(
            "signals".to_string(),
            VmValue::List(std::sync::Arc::new(vec![VmValue::String(
                arcstr::ArcStr::from("SIGTERM"),
            )])),
        )]));
        vm.register_interrupt_handler(
            VmValue::BuiltinRef(arcstr::ArcStr::from("term_marker")),
            Some(&term_options),
        )
        .unwrap();
        vm.install_interrupt_signal_token(signal_token);
        vm.install_cancel_token(cancel_token);
        vm.set_harness(crate::Harness::with_clock(Arc::new(
            CancelWhenSleepStarts {
                cancel: cancel_writer,
                signal: Some(signal_writer),
            },
        )));
    });

    assert!(
        ran.load(std::sync::atomic::Ordering::SeqCst),
        "a registered SIGTERM handler did not run when the cancelled operation \
         was not caught: the only observer that dispatches runs after the \
         throw, so an uncaught cancel skips the handler entirely"
    );
}

#[test]
fn test_unfiltered_handler_runs_on_a_cancel_carrying_no_signal() {
    // A host stopping a session cancels without any signal. The common
    // registration - a cleanup hook with no options at all - is written for
    // that case, so it has to run on it. It used to default to SIGINT, which
    // made the default registration silently specific to a signal that a
    // session stop never carries.
    let cancel_token = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let cancel_writer = std::sync::Arc::clone(&cancel_token);
    let ran = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let ran_in_handler = std::sync::Arc::clone(&ran);

    let source = r#"
pipeline t(harness: Harness) {
  harness.clock.sleep_ms(30000)
  harness.stdio.log("slept")
}
"#;

    let _ = run_harn_with_setup(source, move |vm| {
        vm.register_builtin("cleanup_marker", move |_, out| {
            ran_in_handler.store(true, std::sync::atomic::Ordering::SeqCst);
            out.push_str("[harn] cleanup\n");
            Ok(VmValue::Nil)
        });
        // No options: no filter.
        vm.register_interrupt_handler(
            VmValue::BuiltinRef(arcstr::ArcStr::from("cleanup_marker")),
            None,
        )
        .unwrap();
        // A cancel token and no signal token at all: nothing can supply a name.
        vm.install_cancel_token(cancel_token);
        vm.set_harness(crate::Harness::with_clock(Arc::new(
            CancelWhenSleepStarts {
                cancel: cancel_writer,
                signal: None,
            },
        )));
    });

    assert!(
        ran.load(std::sync::atomic::Ordering::SeqCst),
        "an unfiltered on_interrupt handler did not run on a cancellation that \
         carried no signal, which is how a host stops a session"
    );
}

#[test]
fn test_filtered_handler_is_skipped_when_no_signal_was_delivered() {
    // The other side of the same rule, so that "runs on everything" cannot be
    // the accidental reading of the fix. A handler that named a signal has
    // nothing to match against here, and must not be run on a guess.
    let cancel_token = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let cancel_writer = std::sync::Arc::clone(&cancel_token);
    let ran = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let ran_in_handler = std::sync::Arc::clone(&ran);

    let source = r#"
pipeline t(harness: Harness) {
  harness.clock.sleep_ms(30000)
  harness.stdio.log("slept")
}
"#;

    let _ = run_harn_with_setup(source, move |vm| {
        vm.register_builtin("int_only_marker", move |_, out| {
            ran_in_handler.store(true, std::sync::atomic::Ordering::SeqCst);
            out.push_str("[harn] int\n");
            Ok(VmValue::Nil)
        });
        let int_options = VmValue::dict(BTreeMap::from([(
            "signals".to_string(),
            VmValue::List(std::sync::Arc::new(vec![VmValue::String(
                arcstr::ArcStr::from("SIGINT"),
            )])),
        )]));
        vm.register_interrupt_handler(
            VmValue::BuiltinRef(arcstr::ArcStr::from("int_only_marker")),
            Some(&int_options),
        )
        .unwrap();
        vm.install_cancel_token(cancel_token);
        vm.set_harness(crate::Harness::with_clock(Arc::new(
            CancelWhenSleepStarts {
                cancel: cancel_writer,
                signal: None,
            },
        )));
    });

    assert!(
        !ran.load(std::sync::atomic::Ordering::SeqCst),
        "a handler filtered to SIGINT ran on a cancellation that carried no \
         signal, so a name was invented for it"
    );
}

#[test]
fn test_spawn_returns_value() {
    let out = run_output(
        "pipeline t(harness: Harness, task: unknown) { const h = spawn { 42 }\nconst r = await(h)\nharness.stdio.log(r) }",
    );
    assert_eq!(out, "[harn] 42");
}

// --- Deadline tests ---

#[test]
fn test_deadline_success() {
    let out = run_output(
        r#"pipeline t(harness: Harness, task: unknown) {
const result = deadline 5s { harness.stdio.log("within deadline")
42 }
harness.stdio.log(result)
}"#,
    );
    assert_eq!(out, "[harn] within deadline\n[harn] 42");
}

#[test]
fn test_deadline_exceeded() {
    let result = run_harn_result(
        r"pipeline t(harness: Harness, task: unknown) {
deadline 1ms {
  let i = 0
  while i < 1000000 { i = i + 1 }
}
}",
    );
    assert!(result.is_err());
}

#[test]
fn test_deadline_caught_by_try() {
    let out = run_output(
        r#"pipeline t(harness: Harness, task: unknown) {
try {
  deadline 1ms {
    let i = 0
    while i < 1000000 { i = i + 1 }
  }
} catch(e) {
  harness.stdio.log("caught")
}
}"#,
    );
    assert_eq!(out, "[harn] caught");
}

#[cfg(unix)]
#[test]
fn test_deadline_kills_blocking_exec_subprocess() {
    // Regression for the subprocess-lifecycle gap: `exec` is a *sync*
    // builtin, so the deadline `tokio::select!` cannot preempt it while it
    // blocks on the child. The cooperative `op_interrupt` context must kill
    // the child (group) at the deadline instead of letting the 30s sleep
    // run to completion and orphaning it.
    let started = std::time::Instant::now();
    let result = run_harn_result(
        r#"pipeline t(harness: Harness, task: unknown) {
deadline 500ms {
  harness.process.exec("sh", "-c", "sleep 30")
}
}"#,
    );
    assert!(result.is_err(), "deadline must fire: {result:?}");
    assert!(
        started.elapsed() < std::time::Duration::from_secs(10),
        "deadline must preempt the blocking 30s exec, took {:?}",
        started.elapsed()
    );
}

#[tokio::test(flavor = "current_thread", start_paused = true)]
async fn test_deadline_interrupts_async_sleep_without_wall_clock() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let handle = tokio::task::spawn_local(async {
                run_harn_result_async(
                    r#"pipeline t(harness: Harness, task: unknown) {
try {
  deadline 50ms {
    harness.clock.sleep_ms(1000)
    harness.stdio.log("missed deadline")
  }
} catch(e) {
  harness.stdio.log("caught")
}
}"#,
                )
                .await
            });
            tokio::task::yield_now().await;
            tokio::time::advance(Duration::from_millis(50)).await;
            let (output, _) = handle.await.expect("join VM task").expect("run Harn");
            assert_eq!(output.trim_end(), "[harn] caught");
        })
        .await;
}

#[tokio::test(flavor = "current_thread", start_paused = true)]
async fn test_cancel_during_await_aborts_spawned_task() {
    let local = tokio::task::LocalSet::new();
    local
        .run_until(async {
            let source = r"pipeline t(harness: Harness, task: unknown) {
const handle = spawn {
  harness.clock.sleep_ms(1000)
  mark()
}
await(handle)
}";
            let mut lexer = Lexer::new(source);
            let tokens = lexer.tokenize().unwrap();
            let mut parser = Parser::new(tokens);
            let program = parser.parse().unwrap();
            let chunk = Compiler::new().compile(&program).unwrap();

            let marker = Arc::new(std::sync::atomic::AtomicBool::new(false));
            let marker_for_builtin = marker.clone();
            let cancel_token = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
            let vm_cancel_token = cancel_token.clone();
            let handle = tokio::task::spawn_local(async move {
                let mut vm = Vm::new();
                register_vm_stdlib(&mut vm);
                vm.register_builtin("mark", move |_, _| {
                    marker_for_builtin.store(true, std::sync::atomic::Ordering::SeqCst);
                    Ok(VmValue::Nil)
                });
                vm.install_cancel_token(vm_cancel_token);
                let result = vm.execute(&chunk).await;
                (vm.output().to_string(), result)
            });

            tokio::task::yield_now().await;
            cancel_token.store(true, std::sync::atomic::Ordering::SeqCst);
            tokio::time::advance(Duration::from_millis(300)).await;
            let (output, result) = handle.await.expect("join VM task");
            assert!(output.is_empty());
            let error = result.expect_err("parent await should be cancelled");
            assert!(error.to_string().contains("kind:cancelled"));

            tokio::time::advance(Duration::from_secs(1)).await;
            tokio::task::yield_now().await;
            assert!(
                !marker.load(std::sync::atomic::Ordering::SeqCst),
                "spawned task should be aborted when parent await is cancelled"
            );
        })
        .await;
}