lashlang 0.1.0-alpha.95

Lashlang: compact CodeAct language for model-authored REPL blocks in the lash agent runtime.
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
fn continuation_test_vm<'a>(program: &'a CompiledProgram, host: &'a Host) -> Vm<'a, Host> {
    let slots = SlotState::from_globals(
        Record::new(),
        &program.chunk.slot_names,
        &ProjectedBindings::new(),
    );
    Vm::new_with_mode(&program.chunk, slots, host, ExecutionMode::Foreground)
}

async fn uninterrupted_continuation_result(program: &CompiledProgram) -> ExecutionOutcome {
    execute_compiled(program, &mut State::new(), &Host)
        .await
        .expect("uninterrupted execution should succeed")
}

async fn suspend_after_instruction_budget(
    program: &CompiledProgram,
    budget: usize,
) -> VmContinuation {
    let host = Host;
    let mut vm = continuation_test_vm(program, &host);
    vm.suspend_after_instructions(budget);
    assert_eq!(
        vm.run_for_mode().await.expect("execution should suspend"),
        ExecutionOutcome::Continued
    );
    vm.suspend().expect("VM state should be capturable")
}

async fn round_trip_and_resume(
    program: &CompiledProgram,
    continuation: VmContinuation,
) -> ExecutionOutcome {
    let bytes = serde_json::to_vec(&continuation).expect("continuation should serialize");
    let restored = serde_json::from_slice(&bytes).expect("continuation should deserialize");
    let host = Host;
    let mut vm = Vm::resume_from(restored, program, &host).expect("continuation should resume");
    vm.run_for_mode().await.expect("resumed VM should finish")
}

async fn find_instruction_continuation(
    program: &CompiledProgram,
    predicate: impl Fn(&VmContinuation) -> bool,
) -> VmContinuation {
    for budget in 1..=program.chunk.code.len() * 20 {
        let continuation = suspend_after_instruction_budget(program, budget).await;
        if predicate(&continuation) {
            return continuation;
        }
    }
    panic!("no instruction boundary matched the requested live state")
}

fn slot_number(program: &CompiledProgram, continuation: &VmContinuation, name: &str) -> Option<f64> {
    let index = program
        .chunk
        .slot_names
        .iter()
        .position(|slot| slot.text.as_ref() == name)?;
    match continuation.slots.get(index)?.as_ref()? {
        Value::Number(value) => Some(*value),
        _ => None,
    }
}

#[tokio::test(flavor = "current_thread")]
async fn continuation_resumes_jump_based_while_with_accumulator() {
    let program = compile_source(
        r#"
        n = 0
        total = 0
        while n < 6 {
          total = total + n
          n = n + 1
        }
        finish { n: n, total: total }
        "#,
    )
    .expect("program should compile");
    let expected = uninterrupted_continuation_result(&program).await;
    let continuation = find_instruction_continuation(&program, |continuation| {
        let Some(n @ 2.0..=4.0) = slot_number(&program, continuation, "n") else {
            return false;
        };
        slot_number(&program, continuation, "total") == Some(n * (n + 1.0) / 2.0)
    })
    .await;

    assert_eq!(round_trip_and_resume(&program, continuation).await, expected);
}

#[tokio::test(flavor = "current_thread")]
async fn continuation_resumes_for_iterator_at_saved_cursor() {
    let program = compile_source(
        r#"
        seen = []
        for item in [2, 4, 6, 8] {
          seen = seen + [item]
        }
        finish seen
        "#,
    )
    .expect("program should compile");
    let expected = uninterrupted_continuation_result(&program).await;
    let continuation = find_instruction_continuation(&program, |continuation| {
        matches!(
            continuation.iterator_stack.as_slice(),
            [VmIteratorContinuation {
                cursor: VmIteratorCursor::List { next_index: 2, .. },
                ..
            }]
        )
    })
    .await;

    assert_eq!(round_trip_and_resume(&program, continuation).await, expected);
}

#[tokio::test(flavor = "current_thread")]
async fn continuation_resumes_nested_inner_iterator() {
    let program = compile_source(
        r#"
        total = 0
        for outer in [1, 2, 3] {
          for inner in [10, 20, 30] {
            total = total + outer + inner
          }
        }
        finish total
        "#,
    )
    .expect("program should compile");
    let expected = uninterrupted_continuation_result(&program).await;
    let continuation = find_instruction_continuation(&program, |continuation| {
        continuation.iterator_stack.len() == 2
            && matches!(
                &continuation.iterator_stack[1].cursor,
                VmIteratorCursor::List { next_index: 2, .. }
            )
    })
    .await;

    assert_eq!(round_trip_and_resume(&program, continuation).await, expected);
}

#[tokio::test(flavor = "current_thread")]
async fn continuation_suspends_at_quiescent_post_effect_point() {
    let program = compile_source(
        r#"
        value = await tools.echo({ value: 7 })?
        finish value + 1
        "#,
    )
    .expect("program should compile");
    let expected = uninterrupted_continuation_result(&program).await;
    let host = Host;
    let mut vm = continuation_test_vm(&program, &host);
    vm.suspend_after_effects(1);
    assert_eq!(
        vm.run_for_mode().await.expect("execution should suspend"),
        ExecutionOutcome::Continued
    );
    let continuation = vm.suspend().expect("post-effect state should capture");

    assert_eq!(round_trip_and_resume(&program, continuation).await, expected);
}

#[tokio::test(flavor = "current_thread")]
async fn continuation_distinguishes_present_null_from_unset_slot() {
    let program = compile_source(
        r#"
        value = null
        ignored = await tools.echo({ value: 7 })?
        finish value
        "#,
    )
    .expect("program should compile");
    let expected = uninterrupted_continuation_result(&program).await;
    let host = Host;
    let mut vm = continuation_test_vm(&program, &host);
    vm.suspend_after_effects(1);
    assert_eq!(
        vm.run_for_mode().await.expect("execution should suspend"),
        ExecutionOutcome::Continued
    );
    let continuation = vm.suspend().expect("post-effect state should capture");
    let value_slot = program
        .chunk
        .slot_names
        .iter()
        .position(|name| name.text.as_ref() == "value")
        .expect("value slot");
    assert_eq!(continuation.slots[value_slot], Some(Value::Null));

    let bytes = serde_json::to_vec(&continuation).expect("continuation should serialize");
    let restored: VmContinuation =
        serde_json::from_slice(&bytes).expect("continuation should deserialize");
    assert_eq!(restored.slots[value_slot], Some(Value::Null));
    assert_eq!(round_trip_and_resume(&program, restored).await, expected);
}

#[tokio::test(flavor = "current_thread")]
async fn continuation_preserves_record_insertion_order() {
    let program = compile_source(
        r#"
        ordered = { zebra: 1, alpha: 2, middle: 3 }
        ignored = await tools.echo({ value: 7 })?
        finish ordered
        "#,
    )
    .expect("program should compile");
    let host = Host;
    let mut vm = continuation_test_vm(&program, &host);
    vm.suspend_after_effects(1);
    assert_eq!(
        vm.run_for_mode().await.expect("execution should suspend"),
        ExecutionOutcome::Continued
    );
    let continuation = vm.suspend().expect("post-effect state should capture");
    let bytes = serde_json::to_vec(&continuation).expect("continuation should serialize");
    let restored: VmContinuation =
        serde_json::from_slice(&bytes).expect("continuation should deserialize");
    let ordered_slot = program
        .chunk
        .slot_names
        .iter()
        .position(|name| name.text.as_ref() == "ordered")
        .expect("ordered slot");
    let Value::Record(record) = restored.slots[ordered_slot]
        .as_ref()
        .expect("ordered value")
    else {
        panic!("ordered slot must contain a record");
    };
    assert_eq!(record.keys().collect::<Vec<_>>(), ["zebra", "alpha", "middle"]);
}

#[test]
fn resume_rejects_invalid_iterator_binding_and_zero_range_step() {
    let program = compile_source("value = null\nfinish value").expect("program should compile");
    let slot_count = program.chunk.slot_names.len();
    let base = VmContinuation {
        instruction_pointer: 0,
        operand_stack: Vec::new(),
        last_value: None,
        slots: vec![None; slot_count],
        projected_slots: vec![false; slot_count],
        globals: Record::new(),
        iterator_stack: Vec::new(),
        occurrence_counters: Default::default(),
        mode: ExecutionMode::Process,
        profile: None,
        pending_error_span: None,
    };
    let host = Host;
    let mut invalid_binding = base.clone();
    invalid_binding.iterator_stack.push(VmIteratorContinuation {
        cursor: VmIteratorCursor::List {
            values: Vec::new(),
            next_index: 0,
        },
        binding_slot: slot_count,
        restore_value: None,
    });
    assert!(matches!(
        Vm::resume_from(invalid_binding, &program, &host),
        Err(ContinuationError::IteratorBindingOutOfBounds { .. })
    ));

    let mut zero_step = base;
    zero_step.iterator_stack.push(VmIteratorContinuation {
        cursor: VmIteratorCursor::Range {
            next: 0,
            end: 10,
            step: 0,
        },
        binding_slot: 0,
        restore_value: None,
    });
    assert!(matches!(
        Vm::resume_from(zero_step, &program, &host),
        Err(ContinuationError::ZeroRangeStep { iterator: 0 })
    ));
}

#[tokio::test(flavor = "current_thread")]
async fn continuation_multi_effect_determinism_sweep() {
    let program = compile_source(
        r#"
        a = await tools.echo({ value: 2 })?
        b = await tools.echo({ value: a + 3 })?
        c = await tools.echo({ value: b * 4 })?
        finish [a, b, c]
        "#,
    )
    .expect("program should compile");
    let expected = uninterrupted_continuation_result(&program).await;

    for effect_count in 1..=3 {
        let host = Host;
        let mut vm = continuation_test_vm(&program, &host);
        vm.suspend_after_effects(effect_count);
        assert_eq!(
            vm.run_for_mode().await.expect("execution should suspend"),
            ExecutionOutcome::Continued
        );
        let continuation = vm.suspend().expect("post-effect state should capture");
        assert_eq!(
            round_trip_and_resume(&program, continuation).await,
            expected,
            "resume after effect {effect_count} diverged"
        );
    }
}

#[test]
fn continuation_declines_projected_host_state_with_typed_error() {
    let program = compile_source("finish input").expect("program should compile");
    let mut projected = ProjectedBindings::new();
    projected.insert("input", ProjectedValue::scalar("input", Value::Number(3.0)));
    let slots = SlotState::from_globals(Record::new(), &program.chunk.slot_names, &projected);
    let host = Host;
    let vm = Vm::new_with_mode(
        &program.chunk,
        slots,
        &host,
        ExecutionMode::Foreground,
    );

    assert_eq!(
        vm.suspend(),
        Err(ContinuationError::UnserializableValue {
            location: "slot 0".to_string(),
            variant: "Projected",
        })
    );
}

#[derive(Default)]
struct SegmentRecordingHost {
    effects: Mutex<Vec<Value>>,
}

impl ExecutionHost for SegmentRecordingHost {
    async fn perform(&self, op: AbilityOp) -> Result<AbilityResult, ExecutionHostError> {
        match op {
            AbilityOp::ResourceOperation(operation) => {
                let value = Host::perform_resource_operation(operation)?;
                self.effects.lock().expect("effects lock").push(value.clone());
                Ok(AbilityResult::Value(value))
            }
            other => Host.perform(other).await,
        }
    }
}

async fn run_with_segment_budget(
    program: &CompiledProgram,
    every: Option<usize>,
) -> (ExecutionOutcome, Vec<Value>, usize) {
    let host = SegmentRecordingHost::default();
    let mut state = State::new();
    let mut vm = Vm::from_state(program, &mut state, &host);
    let mut effects_in_segment = 0;
    let mut boundaries = 0;
    loop {
        match vm
            .run_process_until_effect()
            .await
            .expect("segmented execution should succeed")
        {
            VmRunOutcome::Complete(output) => {
                return (
                    output,
                    host.effects.lock().expect("effects lock").clone(),
                    boundaries,
                );
            }
            VmRunOutcome::EffectCompleted => {
                effects_in_segment += 1;
                if every.is_some_and(|budget| effects_in_segment == budget) {
                    let continuation = vm.suspend().expect("post-effect state should capture");
                    let bytes = serde_json::to_vec(&continuation)
                        .expect("segment continuation should serialize");
                    let restored = serde_json::from_slice(&bytes)
                        .expect("segment continuation should deserialize");
                    vm = Vm::resume_from(restored, program, &host)
                        .expect("segment continuation should resume");
                    effects_in_segment = 0;
                    boundaries += 1;
                }
            }
        }
    }
}

#[tokio::test(flavor = "current_thread")]
async fn segmented_multi_effect_run_preserves_result_and_observable_effects() {
    let program = compile_source(
        r#"
        a = await tools.echo({ value: 2 })?
        b = await tools.echo({ value: a + 3 })?
        c = await tools.echo({ value: b * 4 })?
        finish [a, b, c]
        "#,
    )
    .expect("program should compile");
    let unsegmented = run_with_segment_budget(&program, None).await;
    let segmented = run_with_segment_budget(&program, Some(1)).await;

    assert_eq!(segmented.0, unsegmented.0);
    assert_eq!(segmented.1, unsegmented.1);
    assert!(segmented.2 >= 1, "the run must cross a non-terminal boundary");
    assert_eq!(unsegmented.2, 0, "the default path must not segment");
}

#[tokio::test(flavor = "current_thread")]
async fn requested_boundary_at_non_capturable_point_is_safely_skipped() {
    let program = compile_source(
        r#"
        value = await tools.echo({ value: 7 })?
        finish input
        "#,
    )
    .expect("program should compile");
    let mut projected = ProjectedBindings::new();
    projected.insert("input", ProjectedValue::scalar("input", Value::Number(3.0)));
    let slots = SlotState::from_globals(Record::new(), &program.chunk.slot_names, &projected);
    let host = Host;
    let mut vm = Vm::new_with_mode(&program.chunk, slots, &host, ExecutionMode::Process);

    assert_eq!(
        vm.run_process_until_effect().await.expect("effect should succeed"),
        VmRunOutcome::EffectCompleted
    );
    assert!(matches!(
        vm.suspend(),
        Err(ContinuationError::UnserializableValue { variant: "Projected", .. })
    ));
    assert_eq!(
        vm.run_process_until_effect().await.expect("skip should continue"),
        VmRunOutcome::Complete(ExecutionOutcome::Finished(Value::Number(3.0)))
    );
}