harn-vm 0.8.44

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
//! JSONL fixture format for the CLI LLM-mock surface.
//!
//! Same format consumed by `harn run --llm-mock <path>` and
//! `harn test-bench --llm-fixture <path>`. Centralized here so both the
//! CLI and the testbench composition primitive parse identically.

use std::path::Path;

use crate::llm::mock::{self, LlmMock, MockError};

/// Parse a JSONL fixture file into a vector of [`LlmMock`] entries.
/// Empty lines are skipped; every other line must be a JSON object.
pub fn load_llm_mocks_jsonl(path: &Path) -> Result<Vec<LlmMock>, String> {
    let content = std::fs::read_to_string(path)
        .map_err(|error| format!("failed to read {}: {error}", path.display()))?;
    let mut mocks = Vec::new();
    for (idx, raw_line) in content.lines().enumerate() {
        let line_no = idx + 1;
        let line = raw_line.trim();
        if line.is_empty() {
            continue;
        }
        let value: serde_json::Value = serde_json::from_str(line).map_err(|error| {
            format!(
                "invalid JSON in {} line {}: {error}",
                path.display(),
                line_no
            )
        })?;
        mocks.push(parse_llm_mock_value(&value).map_err(|error| {
            format!(
                "invalid LLM mock fixture in {} line {}: {error}",
                path.display(),
                line_no
            )
        })?);
    }
    Ok(mocks)
}

/// Parse a single JSON value into an [`LlmMock`]. Public so callers
/// that already have parsed JSON (e.g. inline test fixtures) can reuse
/// the same schema without re-encoding through a file.
pub fn parse_llm_mock_value(value: &serde_json::Value) -> Result<LlmMock, String> {
    let object = value
        .as_object()
        .ok_or_else(|| "fixture line must be a JSON object".to_string())?;

    let match_pattern = optional_string_field(object, "match")?;
    let consume_on_match = object
        .get("consume_match")
        .and_then(|value| value.as_bool())
        .unwrap_or(false);
    let text = optional_string_field(object, "text")?.unwrap_or_default();
    let input_tokens = optional_i64_field(object, "input_tokens")?;
    let output_tokens = optional_i64_field(object, "output_tokens")?;
    let cache_read_tokens = optional_i64_field(object, "cache_read_tokens")?;
    let cache_write_tokens = optional_i64_field(object, "cache_write_tokens")?
        .or(optional_i64_field(object, "cache_creation_input_tokens")?);
    let thinking = optional_string_field(object, "thinking")?;
    let thinking_summary = optional_string_field(object, "thinking_summary")?;
    let stop_reason = optional_string_field(object, "stop_reason")?;
    let model = optional_string_field(object, "model")?.unwrap_or_else(|| "mock".to_string());
    let provider = optional_string_field(object, "provider")?;
    let blocks = optional_vec_field(object, "blocks")?;
    let logprobs = optional_vec_field(object, "logprobs")?.unwrap_or_default();
    let tool_calls = parse_llm_tool_calls(object.get("tool_calls"))?;
    let error = parse_llm_mock_error(object.get("error"))?;

    Ok(LlmMock {
        text,
        tool_calls,
        match_pattern,
        consume_on_match,
        input_tokens,
        output_tokens,
        cache_read_tokens,
        cache_write_tokens,
        thinking,
        thinking_summary,
        stop_reason,
        model,
        provider,
        blocks,
        logprobs,
        error,
    })
}

/// Serialize a recorded [`LlmMock`] back into a JSON object suitable for
/// JSONL emission.
pub fn serialize_llm_mock(mock: LlmMock) -> Result<String, String> {
    let mut object = serde_json::Map::new();
    if let Some(match_pattern) = mock.match_pattern {
        object.insert(
            "match".to_string(),
            serde_json::Value::String(match_pattern),
        );
    }
    if !mock.text.is_empty() {
        object.insert("text".to_string(), serde_json::Value::String(mock.text));
    }
    if !mock.tool_calls.is_empty() {
        let tool_calls = mock
            .tool_calls
            .into_iter()
            .map(|tool_call| {
                let object = tool_call
                    .as_object()
                    .ok_or_else(|| "recorded tool call must be an object".to_string())?;
                let name = object
                    .get("name")
                    .and_then(|value| value.as_str())
                    .ok_or_else(|| "recorded tool call is missing `name`".to_string())?;
                Ok(serde_json::json!({
                    "name": name,
                    "args": object
                        .get("arguments")
                        .cloned()
                        .unwrap_or_else(|| serde_json::json!({})),
                }))
            })
            .collect::<Result<Vec<_>, String>>()?;
        object.insert(
            "tool_calls".to_string(),
            serde_json::Value::Array(tool_calls),
        );
    }
    if let Some(input_tokens) = mock.input_tokens {
        object.insert(
            "input_tokens".to_string(),
            serde_json::Value::Number(input_tokens.into()),
        );
    }
    if let Some(output_tokens) = mock.output_tokens {
        object.insert(
            "output_tokens".to_string(),
            serde_json::Value::Number(output_tokens.into()),
        );
    }
    if let Some(cache_read_tokens) = mock.cache_read_tokens {
        object.insert(
            "cache_read_tokens".to_string(),
            serde_json::Value::Number(cache_read_tokens.into()),
        );
    }
    if let Some(cache_write_tokens) = mock.cache_write_tokens {
        object.insert(
            "cache_write_tokens".to_string(),
            serde_json::Value::Number(cache_write_tokens.into()),
        );
        object.insert(
            "cache_creation_input_tokens".to_string(),
            serde_json::Value::Number(cache_write_tokens.into()),
        );
    }
    if let Some(thinking) = mock.thinking {
        object.insert("thinking".to_string(), serde_json::Value::String(thinking));
    }
    if let Some(thinking_summary) = mock.thinking_summary {
        object.insert(
            "thinking_summary".to_string(),
            serde_json::Value::String(thinking_summary),
        );
    }
    if let Some(stop_reason) = mock.stop_reason {
        object.insert(
            "stop_reason".to_string(),
            serde_json::Value::String(stop_reason),
        );
    }
    object.insert("model".to_string(), serde_json::Value::String(mock.model));
    if let Some(provider) = mock.provider {
        object.insert("provider".to_string(), serde_json::Value::String(provider));
    }
    if let Some(blocks) = mock.blocks {
        object.insert("blocks".to_string(), serde_json::Value::Array(blocks));
    }
    if !mock.logprobs.is_empty() {
        object.insert(
            "logprobs".to_string(),
            serde_json::Value::Array(mock.logprobs),
        );
    }
    if let Some(error) = mock.error {
        let mut error_object = serde_json::Map::new();
        error_object.insert(
            "category".to_string(),
            serde_json::Value::String(error.category.as_str().to_string()),
        );
        if !error.message.is_empty() {
            error_object.insert(
                "message".to_string(),
                serde_json::Value::String(error.message),
            );
        }
        if let Some(status) = error.status {
            error_object.insert(
                "status".to_string(),
                serde_json::Value::Number(status.into()),
            );
        }
        if let Some(kind) = error.kind {
            error_object.insert("kind".to_string(), serde_json::Value::String(kind));
        }
        if let Some(reason) = error.reason {
            error_object.insert("reason".to_string(), serde_json::Value::String(reason));
        }
        if let Some(retry_after_ms) = error.retry_after_ms {
            error_object.insert(
                "retry_after_ms".to_string(),
                serde_json::Value::Number(retry_after_ms.into()),
            );
        }
        object.insert("error".to_string(), serde_json::Value::Object(error_object));
    }
    serde_json::to_string(&serde_json::Value::Object(object))
        .map_err(|error| format!("failed to serialize recorded fixture: {error}"))
}

fn parse_llm_tool_calls(
    value: Option<&serde_json::Value>,
) -> Result<Vec<serde_json::Value>, String> {
    let Some(value) = value else {
        return Ok(Vec::new());
    };
    let items = value
        .as_array()
        .ok_or_else(|| "tool_calls must be an array".to_string())?;
    items
        .iter()
        .enumerate()
        .map(|(idx, item)| {
            normalize_llm_tool_call(item).map_err(|error| format!("tool_calls[{idx}] {error}"))
        })
        .collect()
}

fn normalize_llm_tool_call(value: &serde_json::Value) -> Result<serde_json::Value, String> {
    let object = value
        .as_object()
        .ok_or_else(|| "must be a JSON object".to_string())?;
    let name = object
        .get("name")
        .and_then(|value| value.as_str())
        .ok_or_else(|| "is missing string field `name`".to_string())?;
    let arguments = object
        .get("arguments")
        .cloned()
        .or_else(|| object.get("args").cloned())
        .unwrap_or_else(|| serde_json::json!({}));
    Ok(serde_json::json!({
        "name": name,
        "arguments": arguments,
    }))
}

fn parse_llm_mock_error(value: Option<&serde_json::Value>) -> Result<Option<MockError>, String> {
    let Some(value) = value else {
        return Ok(None);
    };
    if value.is_null() {
        return Ok(None);
    }
    let object = value.as_object().ok_or_else(|| {
        "error must be an object {category?, message?, status?, kind?, reason?, retry_after_ms?}"
            .to_string()
    })?;
    let category = object
        .get("category")
        .map(|value| {
            value
                .as_str()
                .map(str::to_string)
                .ok_or_else(|| "error.category must be a string".to_string())
        })
        .transpose()?;
    let message = object
        .get("message")
        .map(|value| {
            value
                .as_str()
                .map(str::to_string)
                .ok_or_else(|| "error.message must be a string".to_string())
        })
        .transpose()?;
    let status = match object.get("status") {
        None | Some(serde_json::Value::Null) => None,
        Some(serde_json::Value::Number(n)) => match n.as_i64() {
            Some(v) => Some(mock::validate_mock_error_status(v)?),
            None => return Err("error.status must be an HTTP status code".to_string()),
        },
        Some(_) => return Err("error.status must be an HTTP status code".to_string()),
    };
    let kind = object
        .get("kind")
        .map(|value| {
            value
                .as_str()
                .map(str::to_string)
                .ok_or_else(|| "error.kind must be a string".to_string())
        })
        .transpose()?;
    let reason = object
        .get("reason")
        .map(|value| {
            value
                .as_str()
                .map(str::to_string)
                .ok_or_else(|| "error.reason must be a string".to_string())
        })
        .transpose()?;
    let retry_after_ms = match object.get("retry_after_ms") {
        None | Some(serde_json::Value::Null) => None,
        Some(serde_json::Value::Number(n)) => match n.as_u64() {
            Some(v) => Some(v),
            None => return Err("error.retry_after_ms must be a non-negative integer".to_string()),
        },
        Some(_) => return Err("error.retry_after_ms must be a non-negative integer".to_string()),
    };
    mock::build_mock_error(category, message, status, kind, reason, retry_after_ms).map(Some)
}

fn optional_string_field(
    object: &serde_json::Map<String, serde_json::Value>,
    key: &str,
) -> Result<Option<String>, String> {
    match object.get(key) {
        None | Some(serde_json::Value::Null) => Ok(None),
        Some(serde_json::Value::String(value)) => Ok(Some(value.clone())),
        Some(_) => Err(format!("`{key}` must be a string")),
    }
}

fn optional_i64_field(
    object: &serde_json::Map<String, serde_json::Value>,
    key: &str,
) -> Result<Option<i64>, String> {
    match object.get(key) {
        None | Some(serde_json::Value::Null) => Ok(None),
        Some(value) => value
            .as_i64()
            .map(Some)
            .ok_or_else(|| format!("`{key}` must be an integer")),
    }
}

fn optional_vec_field(
    object: &serde_json::Map<String, serde_json::Value>,
    key: &str,
) -> Result<Option<Vec<serde_json::Value>>, String> {
    match object.get(key) {
        None | Some(serde_json::Value::Null) => Ok(None),
        Some(serde_json::Value::Array(items)) => Ok(Some(items.clone())),
        Some(_) => Err(format!("`{key}` must be an array")),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn roundtrip_preserves_text_and_tool_calls() {
        let mock = parse_llm_mock_value(&serde_json::json!({
            "text": "hello",
            "model": "mock",
            "tool_calls": [
                { "name": "search", "args": { "q": "harn" } }
            ]
        }))
        .expect("parse");
        let line = serialize_llm_mock(mock).expect("serialize");
        let value: serde_json::Value = serde_json::from_str(&line).expect("reparse");
        let reparsed = parse_llm_mock_value(&value).expect("reparse mock");
        assert_eq!(reparsed.text, "hello");
        assert_eq!(reparsed.tool_calls.len(), 1);
        assert_eq!(reparsed.tool_calls[0]["name"].as_str(), Some("search"));
    }

    #[test]
    fn parse_rejects_unknown_error_category() {
        let result = parse_llm_mock_value(&serde_json::json!({
            "error": { "category": "wibble", "message": "x" }
        }));
        match result {
            Err(err) => assert!(err.contains("unknown error category"), "{err}"),
            Ok(_) => panic!("expected parse failure for unknown error category"),
        }
    }

    #[test]
    fn parses_explicit_generic_error_category() {
        let mock = parse_llm_mock_value(&serde_json::json!({
            "error": { "category": "generic", "message": "x" }
        }))
        .expect("parse generic error");
        let error = mock.error.expect("error");
        assert_eq!(error.category.as_str(), "generic");
        assert_eq!(error.message, "x");
    }

    #[test]
    fn parses_provider_error_envelope() {
        let mock = parse_llm_mock_value(&serde_json::json!({
            "error": {
                "status": 503,
                "kind": "transient",
                "reason": "upstream_unavailable",
                "message": "upstream unavailable",
                "retry_after_ms": 250
            }
        }))
        .expect("parse provider envelope");
        let error = mock.error.expect("error");
        assert_eq!(error.category.as_str(), "overloaded");
        assert_eq!(error.status, Some(503));
        assert_eq!(error.kind.as_deref(), Some("transient"));
        assert_eq!(error.reason.as_deref(), Some("upstream_unavailable"));
        assert_eq!(error.retry_after_ms, Some(250));
    }

    #[test]
    fn roundtrip_preserves_provider_error_envelope() {
        let mock = parse_llm_mock_value(&serde_json::json!({
            "match": "*retry*",
            "error": {
                "status": 503,
                "kind": "transient",
                "reason": "upstream_unavailable",
                "retry_after_ms": 250
            }
        }))
        .expect("parse provider envelope");
        let line = serialize_llm_mock(mock).expect("serialize");
        let value: serde_json::Value = serde_json::from_str(&line).expect("reparse json");
        let reparsed = parse_llm_mock_value(&value).expect("reparse mock");
        let error = reparsed.error.expect("error");
        assert_eq!(reparsed.match_pattern.as_deref(), Some("*retry*"));
        assert_eq!(error.category.as_str(), "overloaded");
        assert_eq!(error.status, Some(503));
        assert_eq!(error.kind.as_deref(), Some("transient"));
        assert_eq!(error.reason.as_deref(), Some("upstream_unavailable"));
        assert_eq!(error.retry_after_ms, Some(250));
    }

    #[test]
    fn parse_rejects_unknown_error_kind() {
        let result = parse_llm_mock_value(&serde_json::json!({
            "error": { "status": 503, "kind": "maybe" }
        }));
        match result {
            Err(err) => assert!(err.contains("unknown error kind"), "{err}"),
            Ok(_) => panic!("expected parse failure for unknown error kind"),
        }
    }
}