1
//! Symbol completion and the interrupt latch across forms.
2

            
3
use super::*;
4
use crate::ctx::ScriptLimits;
5

            
6
#[test]
7
1
fn completions_match_case_insensitively_and_skip_internal() {
8
1
    let session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
9
    // Lower-case input matches the upper-case folded symbol; the canonical
10
    // upper-case name is returned.
11
1
    let defuns = session.completions("def");
12
1
    assert!(defuns.contains(&"DEFUN".to_string()), "got: {defuns:?}");
13
1
    assert!(
14
7
        defuns.iter().all(|n| n.starts_with("DEF")),
15
        "got: {defuns:?}"
16
    );
17
    // Sorted; no internal `$`/`__` or `(SETF …)` place names.
18
1
    let all = session.completions("");
19
243
    assert!(all.windows(2).all(|w| w[0] <= w[1]), "must be sorted");
20
1
    assert!(
21
1
        all.iter()
22
244
            .all(|n| !n.starts_with('$') && !n.starts_with("__") && !n.starts_with("(SETF")),
23
        "internal/setf symbols must be filtered: {all:?}"
24
    );
25
1
}
26

            
27
#[tokio::test]
28
1
async fn completions_include_a_user_defined_symbol() {
29
1
    let mut session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
30
1
    let _ = session
31
1
        .handle_form("(:id 1 :form (defun my-helper (x) x))")
32
1
        .await;
33
    // The defun's name is folded to upper-case; a lower-case prefix finds it.
34
1
    let hits = session.completions("my-");
35
1
    assert!(hits.contains(&"MY-HELPER".to_string()), "got: {hits:?}");
36
1
}
37

            
38
#[test]
39
1
fn completions_unknown_prefix_is_empty() {
40
1
    let session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
41
1
    assert!(session.completions("zzz-no-such-symbol-").is_empty());
42
1
}
43

            
44
#[tokio::test]
45
1
async fn interrupt_before_form_short_circuits_with_interrupted() {
46
1
    let mut session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
47
1
    let handle = session.interrupt_handle();
48
1
    handle.interrupt();
49
1
    let response = session.handle_form("(:id 11 :form (+ 1 2))").await;
50
1
    assert!(response.contains(":id 11"));
51
1
    assert!(response.contains(":code interrupted"));
52
1
}
53

            
54
#[tokio::test]
55
1
async fn coalesced_interrupts_abort_one_form_each_in_order() {
56
    // Two `C-g`s observed together before a form cancel THAT form and are
57
    // coalesced (they do not pre-arm cancellation of a later one); a fresh,
58
    // distinct `C-g` later still cancels the next form. This pins the REPL
59
    // contract against both a "lost interrupt" and an "over-eager next-form
60
    // abort" regression.
61
1
    let mut session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
62
1
    let handle = session.interrupt_handle();
63
1
    handle.interrupt();
64
1
    handle.interrupt(); // two presses before the form
65
1
    let first = session.handle_form("(:id 60 :form (+ 1 2))").await;
66
1
    assert!(
67
1
        first.contains(":code interrupted"),
68
        "first form must abort: {first}"
69
    );
70
    // Both presses were coalesced into the one abort — the next form is clean.
71
1
    let second = session.handle_form("(:id 61 :form (+ 1 2))").await;
72
1
    assert_eq!(
73
1
        second, "(:id 61 :value 3)",
74
        "next form coalesced-poisoned: {second}"
75
    );
76
    // A fresh, distinct press still aborts the following form.
77
1
    handle.interrupt();
78
1
    let third = session.handle_form("(:id 62 :form (+ 1 2))").await;
79
1
    assert!(
80
1
        third.contains(":code interrupted"),
81
1
        "a distinct later interrupt must still abort: {third}"
82
1
    );
83
1
}
84

            
85
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
86
1
async fn inflight_interrupt_does_not_poison_next_form() {
87
    // The SLYNK reader arms the interrupt signal and then the epoch bump on
88
    // `(:emacs-interrupt)` (mod.rs); that order is required. When it lands
89
    // mid-eval the epoch trap cancels the running call; that interrupt
90
    // generation must then be acked so the SAME `C-g` can't also abort the
91
    // next request.
92
    //
93
    // The interrupt is sent only once the form's own PRINT is visible in the
94
    // shared output, so it provably lands while Wasm is running; unbounded
95
    // fuel and a huge loop keep the form from finishing or failing first.
96
1
    let ctx = ScriptCtx::new(uuid::Uuid::nil()).with_limits(ScriptLimits {
97
1
        fuel: u64::MAX,
98
1
        ..ScriptLimits::default()
99
1
    });
100
1
    let mut session = Session::new(ctx).expect("Session::new");
101
1
    let bumper = session.epoch_bumper();
102
1
    let interrupt = session.interrupt_handle();
103
1
    let output = Arc::clone(&session.output);
104
1
    let cancel_task = tokio::spawn(async move {
105
1
        let started = Instant::now();
106
46
        while output.lock().map(|out| out.is_empty()).unwrap_or(true)
107
45
            && started.elapsed() < Duration::from_secs(60)
108
        {
109
45
            tokio::time::sleep(Duration::from_millis(1)).await;
110
        }
111
1
        interrupt.interrupt();
112
1
        bumper.bump();
113
1
    });
114
1
    let cancelled = tokio::time::timeout(
115
1
        std::time::Duration::from_secs(60),
116
1
        session.handle_form(
117
1
            "(:id 30 :form (let ((n 1073741823)) (print \"go\") (do ((i 0 (+ i 1))) ((>= i n) i))))",
118
1
        ),
119
1
    )
120
1
    .await
121
1
    .expect("epoch bump did not cancel the eval within 60s");
122
1
    cancel_task.await.expect("cancel task");
123
1
    assert!(
124
1
        cancelled.contains(":code interrupted") && !cancelled.contains("before start"),
125
        "in-flight eval should have been cancelled by the epoch trap: {cancelled}"
126
    );
127
1
    let next = session.handle_form("(:id 31 :form (+ 1 2))").await;
128
1
    assert_eq!(next, "(:id 31 :value 3)", "next form was poisoned: {next}");
129
1
}
130

            
131
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
132
1
async fn non_interrupt_failure_still_consumes_a_concurrent_interrupt() {
133
    // Race: an interrupt is signalled WHILE a form is in flight, but the
134
    // form loses to its own terminal error (out-of-fuel) before any epoch
135
    // bump could win. The in-flight form is finished, so the interrupt must
136
    // be acked on the error path too — otherwise it poisons the next form.
137
    // Enough fuel to run ~0.5s after its PRINT, so the latch provably
138
    // lands mid-flight, yet the loop still ends in out-of-fuel.
139
1
    let ctx = ScriptCtx::new(uuid::Uuid::nil()).with_limits(ScriptLimits {
140
1
        fuel: 4_000_000_000,
141
1
        ..ScriptLimits::default()
142
1
    });
143
1
    let mut session = Session::new(ctx).expect("Session::new");
144
1
    let interrupt = session.interrupt_handle();
145
1
    let output = Arc::clone(&session.output);
146
1
    let latch_task = tokio::spawn(async move {
147
        // Latch only (no epoch bump), once the form is in flight: it trips
148
        // out-of-fuel on its own.
149
1
        let started = Instant::now();
150
34
        while output.lock().map(|out| out.is_empty()).unwrap_or(true)
151
33
            && started.elapsed() < Duration::from_secs(60)
152
        {
153
33
            tokio::time::sleep(Duration::from_millis(1)).await;
154
        }
155
1
        interrupt.interrupt();
156
1
    });
157
1
    let failed = session
158
1
        .handle_form(
159
1
            "(:id 50 :form (let ((n 1073741823)) (print \"go\") (do ((i 0 (+ i 1))) ((>= i n) i))))",
160
1
        )
161
1
        .await;
162
1
    latch_task.await.unwrap();
163
1
    assert!(
164
1
        failed.contains(":code runtime") || failed.contains(":code interrupted"),
165
        "in-flight form should fail terminally: {failed}"
166
    );
167
1
    let next = session.handle_form("(:id 51 :form (+ 1 2))").await;
168
1
    assert_eq!(next, "(:id 51 :value 3)", "next form was poisoned: {next}");
169
1
}
170

            
171
#[tokio::test]
172
1
async fn interrupt_after_clean_eval_aborts_next_form() {
173
    // The mirror of the above: after a form completes NORMALLY, an interrupt
174
    // armed before the next form must still abort it. The in-flight cleanup
175
    // only consumes the latch on an actual epoch-interrupt trap, so a `C-g`
176
    // that lands post-completion is NOT swallowed.
177
1
    let mut session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
178
1
    let clean = session.handle_form("(:id 40 :form (+ 1 2))").await;
179
1
    assert_eq!(clean, "(:id 40 :value 3)");
180
1
    session.interrupt_handle().interrupt();
181
1
    let interrupted = session.handle_form("(:id 41 :form (+ 4 5))").await;
182
1
    assert!(
183
1
        interrupted.contains(":code interrupted"),
184
1
        "post-completion interrupt must abort the next form: {interrupted}"
185
1
    );
186
1
}
187

            
188
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
189
1
async fn epoch_bumper_cancels_inflight_long_eval() {
190
    // The one test that pins the EPOCH-TRAP cancel path specifically.
191
    //
192
    // Two things can end an in-flight eval with `:code interrupted`: the
193
    // pre-start `check_interrupt` latch, and the epoch trap inside Wasm.
194
    // They are easy to confuse, and a test that accepts either silently
195
    // stops covering the trap the moment timing drifts — which is exactly
196
    // what a coverage-instrumented build does to it.
197
    //
198
    // This isolates the trap structurally rather than by timing:
199
    //   - the interrupt handle is never touched, so `check_interrupt` can
200
    //     not fire at all and the pre-start path is unreachable;
201
    //   - fuel is effectively unbounded and the loop bound is just under
202
    //     i32::MAX, so the form can neither finish nor exhaust fuel, ruling
203
    //     out `:code runtime`;
204
    //   - the bumper runs in a loop rather than after a fixed sleep, so a
205
    //     slow host widens the window instead of missing it.
206
    // The assertions then pin the trap by its wire signature: EpochInterrupt
207
    // carries a `:detail`, whereas the pre-start latch reports
208
    // "evaluation interrupted before start" with none.
209
1
    let ctx = ScriptCtx::new(uuid::Uuid::nil()).with_limits(ScriptLimits {
210
1
        fuel: u64::MAX,
211
1
        ..ScriptLimits::default()
212
1
    });
213
1
    let mut session = Session::new(ctx).expect("Session::new");
214
1
    let bumper = session.epoch_bumper();
215
1
    let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
216
1
    let bump_until_done = done.clone();
217
1
    let bump_task = tokio::spawn(async move {
218
15
        while !bump_until_done.load(std::sync::atomic::Ordering::Relaxed) {
219
14
            bumper.bump();
220
14
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
221
        }
222
1
    });
223
    // Bounded: if epoch interruption regresses, the form runs to a bound just
224
    // under i32::MAX with unbounded fuel and never returns. Without this the
225
    // test would stop being a test and become a job that burns until the k8s
226
    // deadline kills it — silently, since it produces no output meanwhile.
227
1
    let response = tokio::time::timeout(
228
1
        std::time::Duration::from_secs(60),
229
1
        session.handle_form("(:id 22 :form (do ((i 0 (+ i 1))) ((>= i 1073741823) i)))"),
230
1
    )
231
1
    .await
232
1
    .expect("epoch bump did not cancel the eval within 60s — interruption has regressed");
233
1
    done.store(true, std::sync::atomic::Ordering::Relaxed);
234
1
    bump_task.await.unwrap();
235

            
236
1
    assert!(response.contains(":id 22"), "{response}");
237
1
    assert!(
238
1
        response.contains(":code interrupted"),
239
        "epoch bump must cancel the in-flight eval: {response}"
240
    );
241
1
    assert!(
242
1
        !response.contains("evaluation interrupted before start"),
243
        "took the pre-start latch path, so the epoch trap went untested: {response}"
244
    );
245
1
    assert!(
246
1
        response.contains(":detail"),
247
1
        "EpochInterrupt must surface its detail; got: {response}"
248
1
    );
249
1
}