use assay_core::model::SequenceRule;
use serde_yaml::{Mapping, Value};
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::process::Command;
const PAGES: &[&str] = &[
"docs/reference/config/sequences.md",
"docs/metrics/sequence-valid.md",
];
const POLICY_FILE_PAGES: &[&str] = &["docs/reference/config/sequences.md"];
const POLICY_FILE_NAME: &str = "sequences.yaml";
const NOT_A_CONFIG_MARKER: &str = "<!-- docs-example: not-a-config";
const EXPECTED_EXEMPTIONS: &[(&str, &str)] = &[
(
"docs/reference/config/sequences.md",
"a v0 format that no version reads",
),
("docs/reference/config/sequences.md", "shows test ids only"),
];
struct Block {
page: &'static str,
line: usize,
yaml: String,
exemption: Option<String>,
}
fn workspace_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../..")
}
fn blocks(page: &'static str) -> Vec<Block> {
let text = std::fs::read_to_string(workspace_root().join(page))
.unwrap_or_else(|e| panic!("read {page}: {e}"));
let lines: Vec<&str> = text.lines().collect();
let mut out = Vec::new();
let mut i = 0;
while i < lines.len() {
if lines[i].trim_end() == "```yaml" {
let previous = lines[..i]
.iter()
.rev()
.find(|l| !l.trim().is_empty())
.map(|l| l.trim());
let exemption = previous
.filter(|l| l.starts_with(NOT_A_CONFIG_MARKER))
.map(|l| {
let inner = l
.trim_start_matches(NOT_A_CONFIG_MARKER)
.trim_end_matches("-->")
.trim();
inner
.strip_prefix('(')
.and_then(|s| s.strip_suffix(')'))
.unwrap_or_else(|| panic!("{page}:{}: marker needs a (reason)", i + 1))
.to_string()
});
let start = i + 1;
let end = lines[start..]
.iter()
.position(|l| l.trim_end() == "```")
.map(|p| start + p)
.unwrap_or_else(|| panic!("{page}:{}: unterminated yaml block", i + 1));
out.push(Block {
page,
line: i + 1,
yaml: lines[start..end].join("\n"),
exemption,
});
i = end + 1;
} else {
i += 1;
}
}
out
}
fn mapping(pairs: Vec<(&str, Value)>) -> Value {
let mut m = Mapping::new();
for (k, v) in pairs {
m.insert(Value::String(k.to_string()), v);
}
Value::Mapping(m)
}
fn config_around(expected: Value) -> Value {
mapping(vec![
("configVersion", Value::Number(1.into())),
("suite", Value::String("docs_example".into())),
("model", Value::String("trace".into())),
(
"tests",
Value::Sequence(vec![mapping(vec![
("id", Value::String("docs_example".into())),
(
"input",
mapping(vec![("prompt", Value::String("docs".into()))]),
),
("expected", expected),
])]),
),
])
}
fn as_config(block: &Block, doc: &Value) -> Value {
let where_ = format!("{}:{}", block.page, block.line);
let Value::Mapping(top) = doc else {
panic!("{where_}: example is not a mapping; mark it not-a-config with a reason");
};
let keys: BTreeSet<&str> = top.keys().filter_map(Value::as_str).collect();
if keys.contains("tests") {
for test in doc["tests"].as_sequence().into_iter().flatten() {
let expected = &test["expected"];
assert!(
expected["type"].as_str() == Some("sequence_valid")
&& (expected["rules"].is_sequence() || expected["policy"].is_string()),
"{where_}: example test {:?} has no `expected: {{ type: sequence_valid, rules | policy }}`",
test["id"]
);
}
return doc.clone();
}
if keys == BTreeSet::from(["rules"]) {
return config_around(mapping(vec![
("type", Value::String("sequence_valid".into())),
("rules", top[&Value::String("rules".into())].clone()),
]));
}
if keys == BTreeSet::from(["expected"]) {
return config_around(top[&Value::String("expected".into())].clone());
}
panic!(
"{where_}: example has top-level keys {keys:?}; it is neither a configuration, a `rules:` \
list nor an `expected:` block. Fix it, or mark it not-a-config with a reason."
);
}
fn rules_in(config: &Value) -> Vec<Value> {
let mut out = Vec::new();
for test in config["tests"].as_sequence().into_iter().flatten() {
if let Some(rules) = test["expected"]["rules"].as_sequence() {
out.extend(rules.iter().cloned());
}
}
out
}
fn assert_rule_fields_known(where_: &str, rule: &Value) {
let parsed: SequenceRule = serde_yaml::from_value(rule.clone())
.unwrap_or_else(|e| panic!("{where_}: rule does not parse: {e}\n{rule:?}"));
let known = serde_yaml::to_value(&parsed).expect("serialize rule");
assert!(
rule.is_mapping(),
"{where_}: rule is not a mapping: {rule:?}"
);
assert_keys_known(where_, "rule", rule, &known);
}
fn assert_keys_known(where_: &str, path: &str, written: &Value, known: &Value) {
match (written, known) {
(Value::Mapping(w), Value::Mapping(k)) => {
for (key, value) in w {
let name = key.as_str().unwrap_or("<non-string key>");
let Some(known_value) = k.get(key) else {
panic!("{where_}: {path} has a field its type does not read: `{name}`");
};
assert_keys_known(where_, &format!("{path}.{name}"), value, known_value);
}
}
(Value::Sequence(w), Value::Sequence(k)) => {
assert_eq!(w.len(), k.len(), "{where_}: {path} changed length on parse");
for (i, (wv, kv)) in w.iter().zip(k).enumerate() {
assert_keys_known(where_, &format!("{path}[{i}]"), wv, kv);
}
}
(Value::Mapping(_), other) => {
panic!("{where_}: {path} is written as a mapping but parses as {other:?}")
}
_ => {}
}
}
fn validate(where_: &str, config: &Value) {
let dir = tempfile::tempdir().expect("tempdir");
for test in config["tests"].as_sequence().into_iter().flatten() {
if let Some(policy) = test["expected"]["policy"].as_str() {
std::fs::write(dir.path().join(policy), "- { type: require, tool: A }\n")
.expect("policy file");
}
}
let text = serde_yaml::to_string(config).expect("serialize config");
std::fs::write(dir.path().join("eval.yaml"), &text).expect("eval.yaml");
let out = Command::new(env!("CARGO_BIN_EXE_assay"))
.current_dir(dir.path())
.env("ASSAY_EXIT_CODES", "v2")
.args(["validate", "--config", "eval.yaml"])
.output()
.expect("run assay validate");
assert_eq!(
out.status.code(),
Some(0),
"{where_}: assay validate refused the example\n--- config ---\n{text}\n--- stderr ---\n{}",
String::from_utf8_lossy(&out.stderr)
);
}
fn run_policy_file(where_: &str, yaml: &str) {
let dir = tempfile::tempdir().expect("tempdir");
std::fs::write(dir.path().join(POLICY_FILE_NAME), yaml).expect("policy file");
let config = config_around(mapping(vec![
("type", Value::String("sequence_valid".into())),
("policy", Value::String(POLICY_FILE_NAME.into())),
]));
let text = serde_yaml::to_string(&config).expect("serialize config");
std::fs::write(dir.path().join("eval.yaml"), &text).expect("eval.yaml");
let trace = [
serde_json::json!({"type": "episode_start", "episode_id": "e1", "timestamp": 1000,
"input": {"prompt": "docs"}}),
serde_json::json!({"type": "episode_end", "episode_id": "e1", "timestamp": 2000,
"final_output": "done"}),
]
.iter()
.map(|l| format!("{l}\n"))
.collect::<String>();
std::fs::write(dir.path().join("trace.jsonl"), trace).expect("trace.jsonl");
let out = Command::new(env!("CARGO_BIN_EXE_assay"))
.current_dir(dir.path())
.env("ASSAY_EXIT_CODES", "v2")
.env("ASSAY_VCR_MODE", "off")
.args([
"run",
"--config",
"eval.yaml",
"--trace-file",
"trace.jsonl",
"--db",
":memory:",
])
.output()
.expect("run assay run");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
matches!(out.status.code(), Some(0) | Some(1)) && !stderr.contains("E_CFG_PARSE"),
"{where_}: assay run did not load the policy file example (exit {:?}; 2 is a \
configuration error)\n--- {POLICY_FILE_NAME} ---\n{yaml}\n--- stderr ---\n{stderr}",
out.status.code()
);
}
#[test]
fn every_sequence_rule_docs_example_validates() {
let mut exemptions = Vec::new();
for &page in PAGES {
let found = blocks(page);
let fences = std::fs::read_to_string(workspace_root().join(page))
.expect("read page")
.lines()
.filter(|l| l.trim_end() == "```yaml")
.count();
assert_eq!(found.len(), fences, "{page}: extractor missed a yaml block");
let mut full_configs = 0;
let mut policy_files = 0;
for block in &found {
let where_ = format!("{}:{}", block.page, block.line);
if let Some(reason) = &block.exemption {
exemptions.push((block.page, reason.clone()));
continue;
}
let doc: Value = serde_yaml::from_str(&block.yaml)
.unwrap_or_else(|e| panic!("{where_}: not YAML: {e}"));
let top_keys: BTreeSet<&str> = doc
.as_mapping()
.map(|m| m.keys().filter_map(Value::as_str).collect())
.unwrap_or_default();
if top_keys.contains("sequences") {
policy_files += 1;
for rule in doc["sequences"].as_sequence().into_iter().flatten() {
assert_rule_fields_known(&where_, rule);
}
run_policy_file(&where_, &block.yaml);
continue;
}
if doc.get("tests").is_some() {
full_configs += 1;
}
let config = as_config(block, &doc);
for rule in rules_in(&config) {
assert_rule_fields_known(&where_, &rule);
}
validate(&where_, &config);
}
assert!(
full_configs > 0,
"{page}: no complete configuration example was checked"
);
if POLICY_FILE_PAGES.contains(&page) {
assert!(
policy_files > 0,
"{page}: describes the `policy:` file form but shows no policy file that \
`assay run` loads"
);
}
}
let expected: Vec<(&str, String)> = EXPECTED_EXEMPTIONS
.iter()
.map(|(p, r)| (*p, (*r).to_string()))
.collect();
assert_eq!(exemptions, expected, "not-a-config markers changed");
}