harn-vm 0.8.24

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
use std::collections::BTreeSet;
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;

const FLOAT_TOLERANCE: f64 = 1e-6;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ToolCallEvalCase {
    pub id: String,
    pub prompt: String,
    #[serde(default)]
    pub tools: Vec<ToolDef>,
    pub expected: ExpectedToolCall,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub baseline_pass_rate: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tags: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ToolDef {
    pub name: String,
    #[serde(default)]
    pub description: String,
    /// Harn tool parameter schema: a map of parameter name to JSON Schema
    /// fragments. `llm_call` wraps this into provider-native function schemas.
    #[serde(default)]
    pub parameters: JsonValue,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "outputSchema"
    )]
    pub output_schema: Option<JsonValue>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub defer_loading: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ExpectedToolCall {
    Exact {
        name: String,
        args: JsonValue,
    },
    Predicate {
        description: String,
        judge_prompt: String,
    },
    Refusal {
        reason_must_match: String,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ObservedToolCall {
    pub name: String,
    #[serde(default)]
    pub args: JsonValue,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ObservedToolCallOutcome {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_call: Option<ObservedToolCall>,
    #[serde(default)]
    pub final_text: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PredicateJudgeVerdict {
    pub passed: bool,
    #[serde(default)]
    pub reason: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ToolCallScore {
    pub passed: bool,
    pub reason: String,
}

#[derive(Debug)]
pub enum ToolCallEvalDatasetError {
    Io { path: PathBuf, message: String },
    Json { path: PathBuf, message: String },
    Validation { path: PathBuf, message: String },
}

impl fmt::Display for ToolCallEvalDatasetError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io { path, message } => write!(f, "{}: {message}", path.display()),
            Self::Json { path, message } => write!(f, "{}: {message}", path.display()),
            Self::Validation { path, message } => write!(f, "{}: {message}", path.display()),
        }
    }
}

impl std::error::Error for ToolCallEvalDatasetError {}

pub fn load_tool_call_eval_dataset(
    path: &Path,
) -> Result<Vec<ToolCallEvalCase>, ToolCallEvalDatasetError> {
    let mut cases = Vec::new();
    for file in tool_call_eval_case_files(path)? {
        let raw = fs::read_to_string(&file).map_err(|error| ToolCallEvalDatasetError::Io {
            path: file.clone(),
            message: error.to_string(),
        })?;
        let value: JsonValue =
            serde_json::from_str(&raw).map_err(|error| ToolCallEvalDatasetError::Json {
                path: file.clone(),
                message: error.to_string(),
            })?;
        let mut loaded = if value.is_array() {
            serde_json::from_value::<Vec<ToolCallEvalCase>>(value).map_err(|error| {
                ToolCallEvalDatasetError::Json {
                    path: file.clone(),
                    message: error.to_string(),
                }
            })?
        } else {
            vec![
                serde_json::from_value::<ToolCallEvalCase>(value).map_err(|error| {
                    ToolCallEvalDatasetError::Json {
                        path: file.clone(),
                        message: error.to_string(),
                    }
                })?,
            ]
        };
        for case in &loaded {
            validate_case(case, &file)?;
        }
        cases.append(&mut loaded);
    }
    cases.sort_by(|left, right| left.id.cmp(&right.id));
    validate_unique_case_ids(&cases, path)?;
    Ok(cases)
}

fn tool_call_eval_case_files(path: &Path) -> Result<Vec<PathBuf>, ToolCallEvalDatasetError> {
    if path.is_file() {
        return Ok(vec![path.to_path_buf()]);
    }
    let cases_dir = path.join("cases");
    let root = if cases_dir.is_dir() {
        cases_dir
    } else {
        path.to_path_buf()
    };
    let mut files = Vec::new();
    collect_json_files(&root, &mut files)?;
    files.sort();
    Ok(files)
}

fn collect_json_files(dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), ToolCallEvalDatasetError> {
    let entries = fs::read_dir(dir).map_err(|error| ToolCallEvalDatasetError::Io {
        path: dir.to_path_buf(),
        message: error.to_string(),
    })?;
    for entry in entries {
        let entry = entry.map_err(|error| ToolCallEvalDatasetError::Io {
            path: dir.to_path_buf(),
            message: error.to_string(),
        })?;
        let path = entry.path();
        if path.is_dir() {
            collect_json_files(&path, out)?;
        } else if path.extension().is_some_and(|ext| ext == "json") {
            out.push(path);
        }
    }
    Ok(())
}

fn validate_case(case: &ToolCallEvalCase, path: &Path) -> Result<(), ToolCallEvalDatasetError> {
    if case.id.trim().is_empty() {
        return validation_error(path, "case id must not be empty");
    }
    if case.prompt.trim().is_empty() {
        return validation_error(path, format!("{}: prompt must not be empty", case.id));
    }
    let mut names = BTreeSet::new();
    for tool in &case.tools {
        if tool.name.trim().is_empty() {
            return validation_error(path, format!("{}: tool name must not be empty", case.id));
        }
        if !names.insert(tool.name.as_str()) {
            return validation_error(
                path,
                format!("{}: duplicate tool name `{}`", case.id, tool.name),
            );
        }
        if !tool.parameters.is_object() {
            return validation_error(
                path,
                format!(
                    "{}: tool `{}` parameters must be an object",
                    case.id, tool.name
                ),
            );
        }
    }
    if let ExpectedToolCall::Exact { name, .. } = &case.expected {
        if !names.contains(name.as_str()) {
            return validation_error(
                path,
                format!("{}: expected tool `{name}` is not declared", case.id),
            );
        }
    }
    if let Some(rate) = case.baseline_pass_rate {
        if !(0.0..=1.0).contains(&rate) {
            return validation_error(
                path,
                format!("{}: baseline_pass_rate must be in [0, 1]", case.id),
            );
        }
    }
    Ok(())
}

fn validation_error<T>(
    path: &Path,
    message: impl Into<String>,
) -> Result<T, ToolCallEvalDatasetError> {
    Err(ToolCallEvalDatasetError::Validation {
        path: path.to_path_buf(),
        message: message.into(),
    })
}

fn validate_unique_case_ids(
    cases: &[ToolCallEvalCase],
    path: &Path,
) -> Result<(), ToolCallEvalDatasetError> {
    let mut seen = BTreeSet::new();
    for case in cases {
        if !seen.insert(case.id.as_str()) {
            return validation_error(path, format!("duplicate case id `{}`", case.id));
        }
    }
    Ok(())
}

pub fn score_tool_call_case(
    case: &ToolCallEvalCase,
    observed: &ObservedToolCallOutcome,
    predicate_verdict: Option<&PredicateJudgeVerdict>,
) -> ToolCallScore {
    match &case.expected {
        ExpectedToolCall::Exact { name, args } => score_exact(name, args, observed),
        ExpectedToolCall::Predicate { .. } => match predicate_verdict {
            Some(verdict) => ToolCallScore {
                passed: verdict.passed,
                reason: if verdict.reason.is_empty() {
                    "predicate judge returned no reason".to_string()
                } else {
                    verdict.reason.clone()
                },
            },
            None => ToolCallScore {
                passed: false,
                reason: "predicate case was not judged".to_string(),
            },
        },
        ExpectedToolCall::Refusal { reason_must_match } => {
            score_refusal(reason_must_match, observed)
        }
    }
}

fn score_exact(name: &str, args: &JsonValue, observed: &ObservedToolCallOutcome) -> ToolCallScore {
    let Some(call) = observed.tool_call.as_ref() else {
        return ToolCallScore {
            passed: false,
            reason: format!("expected `{name}` tool call, observed no tool call"),
        };
    };
    if call.name != name {
        return ToolCallScore {
            passed: false,
            reason: format!("expected tool `{name}`, observed `{}`", call.name),
        };
    }
    if !json_deep_equal_with_numeric_tolerance(args, &call.args) {
        return ToolCallScore {
            passed: false,
            reason: format!("expected args {args}, observed {}", call.args),
        };
    }
    ToolCallScore {
        passed: true,
        reason: format!("matched `{name}` and canonical arguments"),
    }
}

fn score_refusal(pattern: &str, observed: &ObservedToolCallOutcome) -> ToolCallScore {
    if let Some(call) = observed.tool_call.as_ref() {
        return ToolCallScore {
            passed: false,
            reason: format!("expected refusal, observed tool `{}`", call.name),
        };
    }
    match regex::Regex::new(pattern) {
        Ok(regex) if regex.is_match(&observed.final_text) => ToolCallScore {
            passed: true,
            reason: "refusal text matched expected reason pattern".to_string(),
        },
        Ok(_) => ToolCallScore {
            passed: false,
            reason: format!(
                "refusal text did not match `{pattern}`: {}",
                observed.final_text
            ),
        },
        Err(error) => ToolCallScore {
            passed: false,
            reason: format!("invalid refusal regex `{pattern}`: {error}"),
        },
    }
}

pub fn json_deep_equal_with_numeric_tolerance(left: &JsonValue, right: &JsonValue) -> bool {
    match (left, right) {
        (JsonValue::Null, JsonValue::Null) => true,
        (JsonValue::Bool(left), JsonValue::Bool(right)) => left == right,
        (JsonValue::String(left), JsonValue::String(right)) => left == right,
        (JsonValue::Number(left), JsonValue::Number(right)) => {
            match (left.as_f64(), right.as_f64()) {
                (Some(left), Some(right)) => (left - right).abs() <= FLOAT_TOLERANCE,
                _ => left == right,
            }
        }
        (JsonValue::Array(left), JsonValue::Array(right)) => {
            left.len() == right.len()
                && left
                    .iter()
                    .zip(right)
                    .all(|(l, r)| json_deep_equal_with_numeric_tolerance(l, r))
        }
        (JsonValue::Object(left), JsonValue::Object(right)) => {
            left.len() == right.len()
                && left.iter().all(|(key, left_value)| {
                    right.get(key).is_some_and(|right_value| {
                        json_deep_equal_with_numeric_tolerance(left_value, right_value)
                    })
                })
        }
        _ => false,
    }
}

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

    fn exact_case() -> ToolCallEvalCase {
        ToolCallEvalCase {
            id: "exact".to_string(),
            prompt: "Add two numbers".to_string(),
            tools: vec![ToolDef {
                name: "add".to_string(),
                description: String::new(),
                parameters: json!({
                    "left": {"type": "integer"},
                    "right": {"type": "integer"}
                }),
                output_schema: None,
                namespace: None,
                defer_loading: None,
            }],
            expected: ExpectedToolCall::Exact {
                name: "add".to_string(),
                args: json!({"left": 2, "right": 3.0}),
            },
            baseline_pass_rate: None,
            source: None,
            tags: Vec::new(),
        }
    }

    #[test]
    fn exact_scoring_accepts_numeric_tolerance() {
        let score = score_tool_call_case(
            &exact_case(),
            &ObservedToolCallOutcome {
                tool_call: Some(ObservedToolCall {
                    name: "add".to_string(),
                    args: json!({"right": 3.0000001, "left": 2}),
                }),
                final_text: String::new(),
            },
            None,
        );
        assert!(score.passed, "{score:?}");
    }

    #[test]
    fn exact_scoring_rejects_extra_args() {
        let score = score_tool_call_case(
            &exact_case(),
            &ObservedToolCallOutcome {
                tool_call: Some(ObservedToolCall {
                    name: "add".to_string(),
                    args: json!({"left": 2, "right": 3, "extra": true}),
                }),
                final_text: String::new(),
            },
            None,
        );
        assert!(!score.passed);
        assert!(score.reason.contains("expected args"));
    }

    #[test]
    fn refusal_requires_no_tool_and_matching_text() {
        let case = ToolCallEvalCase {
            id: "refusal".to_string(),
            prompt: "Tell a joke".to_string(),
            tools: Vec::new(),
            expected: ExpectedToolCall::Refusal {
                reason_must_match: "(?i)not.*available".to_string(),
            },
            baseline_pass_rate: None,
            source: None,
            tags: Vec::new(),
        };
        let score = score_tool_call_case(
            &case,
            &ObservedToolCallOutcome {
                tool_call: None,
                final_text: "That tool is not available for this request.".to_string(),
            },
            None,
        );
        assert!(score.passed, "{score:?}");
    }

    #[test]
    fn dataset_loader_accepts_arrays() {
        let tmp = tempfile::tempdir().unwrap();
        let cases_dir = tmp.path().join("cases");
        fs::create_dir(&cases_dir).unwrap();
        fs::write(
            cases_dir.join("cases.json"),
            serde_json::to_string(&vec![exact_case()]).unwrap(),
        )
        .unwrap();
        let loaded = load_tool_call_eval_dataset(tmp.path()).unwrap();
        assert_eq!(loaded.len(), 1);
        assert_eq!(loaded[0].id, "exact");
    }
}