1
//! Codex adversarial review, fourth pass on this slice: five findings. `n`
2
//! stands for `(rpc-protocol-version)`, which is 1. (Every repro was first
3
//! verified against a bare `nms` sandbox using `primary-entity-idx` — the
4
//! non-foldable runtime call available there — while developing the fix,
5
//! then ported to `rpc-protocol-version` for this harness.)
6

            
7
use super::*;
8

            
9
// --- item 1: eval-only comparisons (num_cmp/num_neq/eql/equal) applied
10
// operand effects to the caller's table only when folding to a constant;
11
// their RUNTIME-result branches discarded them entirely, and — since EQ?'s
12
// own two-operand probe threads the SAME clone through both operands in
13
// sequence — a nested comparison's dropped effect left the SECOND operand's
14
// classification stale relative to what real emission does, producing an
15
// invalid wasm module (mismatched predicted vs. emitted type). Fixed by
16
// evaluating every operand exactly once, in source order, directly on the
17
// caller's table — no separate disposable-probe-then-apply step at all in
18
// these eval-only paths (unlike the codegen paths, which keep it). ---
19

            
20
#[tokio::test]
21
1
async fn eval_only_comparison_runtime_branch_still_applies_a_nested_definition() {
22
1
    let form = "(let ((v (progn (= (progn (defvar codex-r6-z 7) (rpc-protocol-version)) 1) codex-r6-z))) v)";
23
1
    assert_values(&[(form, "7")]).await;
24
1
}
25

            
26
#[tokio::test]
27
1
async fn eval_only_eq_runtime_branch_still_applies_a_nested_definition() {
28
1
    let form = "(let ((v (progn (eq? (progn (defvar codex-r6-z2 7) (rpc-protocol-version)) 1) codex-r6-z2))) v)";
29
1
    assert_values(&[(form, "7")]).await;
30
1
}
31

            
32
#[tokio::test]
33
1
async fn eq_outer_probe_sees_the_first_operands_effect_and_compiles_valid_wasm() {
34
    // Previously failed wasm-engine compilation: the outer `eq?` probe
35
    // predicted an integer second operand from STALE `x` (the nested `=`'s
36
    // `setf` never reached the probe), while real emission — which DOES
37
    // apply the `setf` before compiling the second operand — produced a
38
    // string, a type mismatch invalid wasm can't represent.
39
1
    let form = r#"(progn (defparameter x t)
40
1
                   (eq? (= (progn (setf x nil) (rpc-protocol-version)) 1) (if x (rpc-protocol-version) "s")))"#;
41
1
    assert_values(&[(form, "nil")]).await;
42
1
}
43

            
44
// --- item 2: DEFPARAMETER/DEFVAR's own initializer was evaluated for its
45
// compile-time effects via `eval_value` AND compiled again for real by
46
// `promote_def_binding` — a nested `setf` on a plain (non-wasm-backed)
47
// place ran twice even with NO guard at all, and — because that second
48
// application has no corresponding runtime-conditional bytecode — ran
49
// UNCONDITIONALLY even when a surrounding AND/OR guard was false. Fixed at
50
// two levels: (a) the initializer's real effects now apply exactly once
51
// (probed on a clone for classification, applied for real only via
52
// `promote_def_binding`'s later compile when the result is runtime); (b) a
53
// SETF on a compile-time-only place under ANY runtime guard (AND/OR or
54
// COND) is now a structured error, since such a store has no way to be
55
// made conditional at all. ---
56

            
57
#[tokio::test]
58
1
async fn defparameter_initializer_effect_applies_exactly_once_unguarded() {
59
1
    let form = "(progn (defparameter x 0) \
60
1
                 (defparameter codex-r6-fresh (progn (setf x (+ x 1)) (rpc-protocol-version))) \
61
1
                 x)";
62
1
    assert_values(&[(form, "1")]).await;
63
1
}
64

            
65
#[tokio::test]
66
1
async fn defparameter_initializer_compile_time_setf_under_a_runtime_guard_is_rejected() {
67
1
    let form = "(progn (defparameter x 0) \
68
1
                 (and (> (rpc-protocol-version) 5) (defparameter codex-r6-fresh2 (progn (setf x (+ x 1)) (rpc-protocol-version)))) \
69
1
                 x)";
70
1
    assert_error_code(form, "compile").await;
71
1
}
72

            
73
#[tokio::test]
74
1
async fn defvar_initializer_effect_applies_exactly_once_unguarded() {
75
1
    let form = "(progn (defparameter y 0) \
76
1
                 (defvar codex-r6-fresh3 (progn (setf y (+ y 1)) (rpc-protocol-version))) \
77
1
                 y)";
78
1
    assert_values(&[(form, "1")]).await;
79
1
}
80

            
81
// --- item 3: the bodyless COND path leaked the shared recursion counter —
82
// `enter_cond_chain` succeeded, then the test's `eval_value(symbols,
83
// &elems[0])?` could fail and `?` past `exit_cond_chain`, leaving BOTH
84
// `cond_depth` and the shared budget incremented forever on the
85
// (session-persistent) SymbolTable. Fixed by evaluating the bodyless
86
// test BEFORE `enter_cond_chain`, matching what codegen already does. ---
87

            
88
#[tokio::test]
89
1
async fn a_cond_chain_failure_does_not_leak_the_guard_counter_across_forms() {
90
    // First form: a bodyless COND whose test fails to compile (an
91
    // undefined symbol) — this must fail WITHOUT leaking `cond_depth`.
92
1
    let mut session = Session::new(ScriptCtx::new(uuid::Uuid::nil())).expect("Session::new");
93
1
    let failing = session
94
1
        .handle_form("(:id 1 :form (cond (codex-r6-undefined-symbol) (t 1)))")
95
1
        .await;
96
1
    assert!(
97
1
        failing.contains(":code"),
98
        "expected the undefined symbol to fail: {failing}"
99
    );
100
    // Second form, same session/SymbolTable: an ORDINARY COND must still
101
    // compile and run correctly — a leaked counter would make this (and
102
    // eventually every later form) spuriously fail once the shared/cond
103
    // ceiling is reached.
104
1
    let recovered = session
105
1
        .handle_form("(:id 2 :form (cond ((> (rpc-protocol-version) 5) 1) (t 2)))")
106
1
        .await;
107
1
    assert_eq!(
108
1
        recovered, "(:id 2 :value 2)",
109
1
        "session did not recover: {recovered}"
110
1
    );
111
1
}
112

            
113
// --- item 4: the `>`/`<=` scalar and commodity paths compiled args[1]
114
// before args[0] (needed for the `a > b ≡ b < a` / `a <= b ≡ !(b < a)`
115
// reversed-comparator trick), so a `setf` in args[0] ran AFTER args[1] had
116
// already read the pre-setf value — both wrong evaluation order AND (via
117
// the disposable `resolve_all` probe) a definition in args[0] invisible to
118
// args[1]. Fixed by evaluating both operands into locals in SOURCE order,
119
// then loading them in comparator order. ---
120

            
121
#[tokio::test]
122
1
async fn gt_scalar_evaluates_operands_in_source_order() {
123
1
    let form = "(let ((x (rpc-protocol-version))) \
124
1
                 (> (progn (setf x (+ x 1)) (index->scalar x)) \
125
1
                    (progn (setf x (* x 10)) (index->scalar x))) \
126
1
                 x)";
127
1
    assert_values(&[(form, "20")]).await;
128
1
}
129

            
130
#[tokio::test]
131
1
async fn gt_scalar_first_operands_definition_is_visible_to_the_second() {
132
    let form =
133
1
        "(> (progn (defvar codex-r6-z3 2/1) (index->scalar (rpc-protocol-version))) codex-r6-z3)";
134
1
    assert_values(&[(form, "nil")]).await;
135
1
}
136

            
137
#[tokio::test]
138
1
async fn le_scalar_evaluates_operands_in_source_order() {
139
1
    let form = "(let ((x (rpc-protocol-version))) \
140
1
                 (<= (progn (setf x (+ x 1)) (index->scalar x)) \
141
1
                     (progn (setf x (* x 10)) (index->scalar x))) \
142
1
                 x)";
143
1
    assert_values(&[(form, "20")]).await;
144
1
}
145

            
146
// --- item 5: the both-nil cross-type shortcut assumed every pair of
147
// distinct static wasm types is disjoint — false for `AnyRef` (the
148
// ADR-0025 widen target), which can box a value of ANY other type. A
149
// concrete-typed operand equal in VALUE to what an AnyRef actually boxes
150
// (an Index, or a pair by reference identity) must compare `t`, not `nil`.
151
// Fixed via runtime type discrimination (`ref.test` + type-specific value
152
// comparison) whenever exactly one side is `AnyRef`. ---
153

            
154
#[tokio::test]
155
1
async fn index_equals_an_anyref_boxing_the_same_index_value() {
156
1
    let form = "(eq? (rpc-protocol-version) (if (= (rpc-protocol-version) 1) (rpc-protocol-version) \"x\"))";
157
1
    assert_values(&[(form, "t")]).await;
158
1
}
159

            
160
#[tokio::test]
161
1
async fn anyref_boxing_the_same_index_value_equals_index_reversed_operand_order() {
162
1
    let form = "(eq? (if (= (rpc-protocol-version) 1) (rpc-protocol-version) \"x\") (rpc-protocol-version))";
163
1
    assert_values(&[(form, "t")]).await;
164
1
}
165

            
166
#[tokio::test]
167
1
async fn index_does_not_equal_an_anyref_boxing_a_different_value() {
168
1
    let form = "(eq? (+ (rpc-protocol-version) 1) (if (= (rpc-protocol-version) 1) (rpc-protocol-version) \"x\"))";
169
1
    assert_values(&[(form, "nil")]).await;
170
1
}
171

            
172
#[tokio::test]
173
1
async fn pair_equals_an_anyref_boxing_the_same_pair_by_identity() {
174
1
    let form = "(let ((p (list (rpc-protocol-version)))) (eq? p (if (= (rpc-protocol-version) 1) p (rpc-protocol-version))))";
175
1
    assert_values(&[(form, "t")]).await;
176
1
}