Skip to main content

datadog_agent_config_corpus/
reader.rs

1//! Validates saved Agent configuration records and builds the typed model used by Rust tests.
2//!
3//! [`read`] takes the bytes of `config-recorder/corpus.jsonl`: a header identifying the recording,
4//! followed by test cases and their per-setting observations. It checks each line's JSON encoding,
5//! allowed fields, and values, then checks ordering and relationships between records. It also
6//! reconstructs fields the writer may omit, such as a read's source or an event's update index.
7//!
8//! The result is a [`Corpus`] or line-numbered [`Violation`]s. These checks follow
9//! `config-recorder/docs/record.md` independently of the Go writer. They validate the recording's
10//! structure, not whether ADP reads configuration the same way as the Agent. Comparisons with the
11//! schema and recorder files on disk belong to the separate `corpus_checks` tests.
12
13use std::collections::BTreeMap;
14use std::num::NonZeroU64;
15
16use crate::getter;
17use crate::json::{parse_line, JStr, Json};
18use crate::lists::{Getter, Group, Level, Source};
19use crate::model::*;
20
21/// A rule failure before its line number is known.
22struct Fail(Rule, String);
23
24impl From<String> for Fail {
25    fn from(s: String) -> Self {
26        Fail(Rule::Shape, s)
27    }
28}
29
30impl From<&str> for Fail {
31    fn from(s: &str) -> Self {
32        Fail(Rule::Shape, s.to_string())
33    }
34}
35
36type R<T> = Result<T, Fail>;
37
38fn fail<T>(rule: Rule, msg: impl Into<String>) -> R<T> {
39    Err(Fail(rule, msg.into()))
40}
41
42/// Checked access to an object's members, so that every member not consumed is an error.
43struct Obj<'a> {
44    members: &'a [(JStr, Json)],
45    used: Vec<bool>,
46    what: &'static str,
47}
48
49impl<'a> Obj<'a> {
50    fn new(v: &'a Json, what: &'static str) -> R<Self> {
51        let Json::Obj(members) = v else {
52            return fail(Rule::Shape, format!("{what}: expected an object, found {}", v.kind()));
53        };
54        for (k, _) in members {
55            if !k.go_canonical {
56                return fail(
57                    Rule::Canonical,
58                    format!("{what}: member name {:?} is not Go-escaped", k.text),
59                );
60            }
61        }
62        Ok(Obj {
63            members,
64            used: vec![false; members.len()],
65            what,
66        })
67    }
68
69    fn get(&mut self, name: &str) -> Option<&'a Json> {
70        let i = self.members.iter().position(|(k, _)| k.text == name)?;
71        self.used[i] = true;
72        Some(&self.members[i].1)
73    }
74
75    fn req_nullable(&mut self, name: &str) -> R<&'a Json> {
76        self.get(name)
77            .ok_or_else(|| format!("{}: missing required member `{name}`", self.what).into())
78    }
79
80    fn req(&mut self, name: &str) -> R<&'a Json> {
81        let v = self.req_nullable(name)?;
82        if matches!(v, Json::Null) {
83            return fail(Rule::Shape, format!("{}: `{name}` must not be null", self.what));
84        }
85        Ok(v)
86    }
87
88    /// An optional member: absent when it has no value, never `null` (record.md §1).
89    fn opt(&mut self, name: &str) -> R<Option<&'a Json>> {
90        match self.get(name) {
91            Some(Json::Null) => fail(
92                Rule::Shape,
93                format!("{}: optional member `{name}` must be absent, not null", self.what),
94            ),
95            v => Ok(v),
96        }
97    }
98
99    fn finish(self) -> R<()> {
100        for ((k, _), used) in self.members.iter().zip(&self.used) {
101            if !used {
102                return fail(Rule::Shape, format!("{}: unknown member `{}`", self.what, k.text));
103            }
104        }
105        Ok(())
106    }
107}
108
109fn string<'a>(v: &'a Json, what: &str) -> R<&'a str> {
110    match v {
111        Json::Str(s) if s.go_canonical => Ok(&s.text),
112        Json::Str(s) => fail(
113            Rule::Canonical,
114            format!("{what}: string {:?} is not Go-escaped", s.text),
115        ),
116        other => fail(
117            Rule::Shape,
118            format!("{what}: expected a string, found {}", other.kind()),
119        ),
120    }
121}
122
123fn boolean(v: &Json, what: &str) -> R<bool> {
124    match v {
125        Json::Bool(b) => Ok(*b),
126        other => fail(
127            Rule::Shape,
128            format!("{what}: expected a boolean, found {}", other.kind()),
129        ),
130    }
131}
132
133fn uint(v: &Json, what: &str) -> R<u64> {
134    match v {
135        Json::Num(n) if n.bytes().all(|c| c.is_ascii_digit()) => n
136            .parse()
137            .map_err(|_| format!("{what}: integer {n} out of range").into()),
138        other => fail(
139            Rule::Shape,
140            format!("{what}: expected a non-negative integer, found {other:?}"),
141        ),
142    }
143}
144
145fn array<'a>(v: &'a Json, what: &str) -> R<&'a [Json]> {
146    match v {
147        Json::Arr(a) => Ok(a),
148        other => fail(
149            Rule::Shape,
150            format!("{what}: expected an array, found {}", other.kind()),
151        ),
152    }
153}
154
155/// An optional array, which must be omitted rather than written empty.
156fn opt_nonempty<'a>(o: &mut Obj<'a>, name: &str) -> R<&'a [Json]> {
157    match o.opt(name)? {
158        None => Ok(&[]),
159        Some(v) => {
160            let a = array(v, name)?;
161            if a.is_empty() {
162                return fail(Rule::Shape, format!("{}: `{name}` must be omitted when empty", o.what));
163            }
164            Ok(a)
165        }
166    }
167}
168
169fn strings(v: &Json, what: &str) -> R<Vec<String>> {
170    array(v, what)?
171        .iter()
172        .map(|s| string(s, what).map(str::to_string))
173        .collect()
174}
175
176fn strictly_sorted(v: &[String]) -> bool {
177    v.windows(2).all(|w| w[0].as_bytes() < w[1].as_bytes())
178}
179
180fn listed<T: Copy + std::fmt::Display>(v: &str, parse: fn(&str) -> Option<T>, all: &[T], what: &str) -> R<T> {
181    parse(v).ok_or_else(|| {
182        let names: Vec<String> = all.iter().map(ToString::to_string).collect();
183        format!("{what}: {v:?} is not one of {names:?}").into()
184    })
185}
186
187fn source(v: &str, what: &str) -> R<Source> {
188    listed(v, Source::parse, Source::ALL, what)
189}
190
191/// A key a case reads: non-empty and lowercase, as the Agent flattens keys (case.md §6).
192fn case_key(v: &Json, what: &str) -> R<String> {
193    let key = string(v, what)?;
194    if key.is_empty() {
195        return fail(Rule::Shape, format!("{what}: a key must not be empty"));
196    }
197    if key.chars().any(char::is_uppercase) {
198        return fail(Rule::Shape, format!("{what}: key {key:?} has an uppercase letter"));
199    }
200    Ok(key.to_string())
201}
202
203fn getter_name(v: &str, what: &str) -> R<Getter> {
204    listed(v, Getter::parse, Getter::ALL, what)
205}
206
207/// Any JSON outside a streamed `value`: every string and member name must be Go-escaped.
208fn go_json(v: &Json, what: &str) -> R<()> {
209    match v {
210        Json::Str(_) => string(v, what).map(|_| ()),
211        Json::Arr(a) => a.iter().try_for_each(|x| go_json(x, what)),
212        Json::Obj(m) => m.iter().try_for_each(|(k, x)| {
213            if !k.go_canonical {
214                return fail(
215                    Rule::Canonical,
216                    format!("{what}: member name {:?} is not Go-escaped", k.text),
217                );
218            }
219            go_json(x, what)
220        }),
221        _ => Ok(()),
222    }
223}
224
225/// A typed value in `inputs` (case.md §7), kept as JSON.
226fn typed_value(v: &Json, what: &str) -> R<serde_json::Value> {
227    go_json(v, what)?;
228    Ok(v.to_value().map_err(|e| format!("{what}: {e}"))?)
229}
230
231fn is_hex(s: &str, len: usize) -> bool {
232    s.len() == len && s.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f'))
233}
234
235fn warning(v: &Json, what: &'static str) -> R<Warning> {
236    let mut o = Obj::new(v, what)?;
237    let level = listed(string(o.req("level")?, what)?, Level::parse, Level::ALL, what)?;
238    let message = string(o.req("message")?, what)?.to_string();
239    o.finish()?;
240    Ok(Warning { level, message })
241}
242
243fn warnings(o: &mut Obj<'_>, what: &'static str) -> R<Vec<Warning>> {
244    opt_nonempty(o, "warnings")?.iter().map(|w| warning(w, what)).collect()
245}
246
247/// The members of a streamed setting (record.md §5.1). `value` keeps protojson's escaping, so only
248/// its JSON structure is checked.
249fn streamed(o: &mut Obj<'_>) -> R<Setting> {
250    let what = o.what;
251    // record.md §5.1: `source` is written even when `""`, which is legal only here.
252    let src = source(string(o.req("source")?, what)?, &format!("{what} source"))?;
253    let unset_source = match o.opt("unset_source")? {
254        Some(u) => {
255            let s = source(string(u, what)?, &format!("{what} unset_source"))?;
256            if s == Source::Empty {
257                return fail(
258                    Rule::Shape,
259                    format!("{what} unset_source: \"\" is omitted, not written (record.md §5.1)"),
260                );
261            }
262            Some(s)
263        }
264        None => None,
265    };
266    let value = match o.get("value") {
267        Some(v) => Some(v.to_value().map_err(|e| format!("{what} value: {e}"))?),
268        None => None,
269    };
270    Ok(Setting {
271        source: src,
272        unset_source,
273        value,
274    })
275}
276
277fn header(v: &Json) -> R<Header> {
278    let mut o = Obj::new(v, "header")?;
279    string(o.req("type")?, "type")?;
280    match o.req("format")? {
281        Json::Num(n) if n == "1" => {}
282        other => {
283            return fail(
284                Rule::Shape,
285                format!("header: unknown format {other:?}; this reader knows format 1"),
286            )
287        }
288    }
289    let agent_commit = string(o.req("agent_commit")?, "header agent_commit")?.to_string();
290    if !is_hex(&agent_commit, 40) {
291        return fail(
292            Rule::Shape,
293            format!("header: agent_commit {agent_commit:?} is not 40 lowercase hex"),
294        );
295    }
296    let inputs_digest = string(o.req("inputs_digest")?, "header inputs_digest")?.to_string();
297    if !inputs_digest.strip_prefix("sha256:").is_some_and(|h| is_hex(h, 64)) {
298        return fail(
299            Rule::Shape,
300            format!("header: inputs_digest {inputs_digest:?} is not sha256: plus 64 lowercase hex"),
301        );
302    }
303    let mut text = |m: &str| -> R<String> { Ok(string(o.req(m)?, &format!("header {m}"))?.to_string()) };
304    let goos = text("goos")?;
305    let goarch = text("goarch")?;
306    let go_version = text("go_version")?;
307    let container_image = text("container_image")?;
308    let containerized = boolean(o.req("containerized")?, "header containerized")?;
309    let features = strings(o.req("features")?, "header features")?;
310    if !strictly_sorted(&features) {
311        return fail(Rule::Shape, "header: features are not sorted and unique");
312    }
313    o.finish()?;
314    Ok(Header {
315        agent_commit,
316        goos,
317        goarch,
318        go_version,
319        container_image,
320        containerized,
321        features,
322        inputs_digest,
323    })
324}
325
326/// What a case line says about the case once it started, before its key lines are read.
327struct StartedLine {
328    origin: String,
329    containerized: bool,
330    features: Vec<String>,
331    side_effects: Vec<SideEffect>,
332    updates: Vec<UpdateResult>,
333}
334
335/// A case line, plus the key lines read so far.
336struct Pending {
337    case: Case,
338    line: usize,
339    /// `inputs.keys` as written; `None` when omitted.
340    written_keys: Option<Vec<KeySpec>>,
341    started: Option<StartedLine>,
342    key_lines: Vec<KeyLine>,
343}
344
345impl Pending {
346    fn override_for(&self, key: &str) -> Option<&[Getter]> {
347        self.written_keys
348            .as_ref()?
349            .iter()
350            .find(|k| k.key == key)
351            .and_then(|k| k.getters.as_deref())
352    }
353
354    /// Rules that need all of the case's key lines; builds the case.
355    fn finish(self) -> R<Case> {
356        let Pending {
357            mut case,
358            line,
359            written_keys,
360            started,
361            key_lines,
362            ..
363        } = self;
364        case.input_line = line;
365        let Some(started) = started else {
366            if !key_lines.is_empty() {
367                return fail(Rule::Consistency, "a case with a startup_error must have no key lines");
368            }
369            let Some(keys) = written_keys else {
370                return fail(
371                    Rule::Reconstruction,
372                    "a case with a startup_error must write inputs.keys",
373                );
374            };
375            case.inputs.keys = keys;
376            return Ok(case);
377        };
378        let seen: Vec<String> = key_lines.iter().map(|k| k.key.clone()).collect();
379        let keys = match written_keys {
380            None => seen
381                .iter()
382                .map(|k| KeySpec {
383                    key: k.clone(),
384                    getters: None,
385                })
386                .collect(),
387            Some(entries) => {
388                let listed: Vec<String> = entries.iter().map(|k| k.key.clone()).collect();
389                let mut sorted = listed.clone();
390                sorted.sort();
391                if sorted != seen {
392                    return fail(
393                        Rule::Reconstruction,
394                        format!("the key lines {seen:?} are not exactly inputs.keys {listed:?}"),
395                    );
396                }
397                let needed = !strictly_sorted(&listed) || entries.iter().any(|k| k.getters.is_some());
398                if !needed {
399                    return fail(
400                        Rule::Reconstruction,
401                        "inputs.keys must be omitted: the keys are in byte order, have no getters override and \
402                         the case started",
403                    );
404                }
405                entries
406            }
407        };
408        if keys.is_empty() {
409            return fail(Rule::Consistency, "a case that started must have at least one key line");
410        }
411        if let Some(e) = started.side_effects.iter().find(|e| seen.contains(&e.key)) {
412            return fail(
413                Rule::Consistency,
414                format!("side_effects names the case's own key {:?}", e.key),
415            );
416        }
417        case.inputs.keys = keys;
418        case.outcome = Outcome::Started(Started {
419            origin: started.origin,
420            containerized: started.containerized,
421            features: started.features,
422            side_effects: started.side_effects,
423            updates: started.updates,
424            keys: key_lines,
425        });
426        Ok(case)
427    }
428}
429
430/// `inputs` (record.md §3.1); `keys` is returned separately since it may need reconstruction.
431fn inputs(v: &Json) -> R<(Inputs, Option<Vec<KeySpec>>)> {
432    let mut o = Obj::new(v, "inputs")?;
433    let env = match o.opt("env")? {
434        None => None,
435        Some(env) => {
436            let Json::Obj(members) = env else {
437                return fail(Rule::Shape, "inputs.env: expected an object");
438            };
439            let mut vars = BTreeMap::new();
440            for (name, value) in members {
441                let valid = name.go_canonical
442                    && name
443                        .text
444                        .bytes()
445                        .enumerate()
446                        .all(|(i, c)| c == b'_' || c.is_ascii_alphabetic() || (i > 0 && c.is_ascii_digit()))
447                    && !name.text.is_empty();
448                if !valid {
449                    return fail(
450                        Rule::Shape,
451                        format!("inputs.env: invalid variable name {:?}", name.text),
452                    );
453                }
454                vars.insert(name.text.clone(), string(value, "inputs.env value")?.to_string());
455            }
456            Some(vars)
457        }
458    };
459    let mut text = |m: &'static str| -> R<Option<String>> {
460        match o.opt(m)? {
461            Some(s) => Ok(Some(string(s, &format!("inputs.{m}"))?.to_string())),
462            None => Ok(None),
463        }
464    };
465    let yaml = text("yaml")?;
466    let fleet_policy = text("fleet_policy")?;
467    let mut cli = Vec::new();
468    for c in opt_nonempty(&mut o, "cli")? {
469        let mut e = Obj::new(c, "inputs.cli element")?;
470        let key = string(e.req("key")?, "inputs.cli key")?.to_string();
471        let value = typed_value(e.req_nullable("value")?, "inputs.cli value")?;
472        e.finish()?;
473        cli.push(CliOverride { key, value });
474    }
475    let mut updates = Vec::new();
476    for u in opt_nonempty(&mut o, "updates")? {
477        let mut e = Obj::new(u, "inputs.updates element")?;
478        let key = string(e.req("key")?, "inputs.updates key")?.to_string();
479        let unset = match e.opt("op")? {
480            None => false,
481            Some(op) if string(op, "inputs.updates op")? == "unset" => true,
482            Some(_) => return fail(Rule::Shape, "inputs.updates: `op` is written only for \"unset\""),
483        };
484        let src = source(
485            string(e.req("source")?, "inputs.updates source")?,
486            "inputs.updates source",
487        )?;
488        if !Source::UPDATE.contains(&src) {
489            return fail(
490                Rule::Shape,
491                format!("inputs.updates: source {src} may not be written by an update"),
492            );
493        }
494        let op = match (unset, e.get("value")) {
495            (true, Some(_)) => return fail(Rule::Shape, "inputs.updates: an unset has no `value`"),
496            (false, None) => return fail(Rule::Shape, "inputs.updates: a set needs a `value`"),
497            (false, Some(v)) => UpdateOp::Set(typed_value(v, "inputs.updates value")?),
498            (true, None) => UpdateOp::Unset,
499        };
500        e.finish()?;
501        updates.push(Update { key, op, source: src });
502    }
503    let keys = match o.opt("keys")? {
504        None => None,
505        Some(k) => {
506            let mut entries: Vec<KeySpec> = Vec::new();
507            for e in array(k, "inputs.keys")? {
508                let mut eo = Obj::new(e, "inputs.keys element")?;
509                let key = case_key(eo.req("key")?, "inputs.keys key")?;
510                let getters = match eo.opt("getters")? {
511                    None => None,
512                    Some(g) => {
513                        let g = strings(g, "inputs.keys getters")?;
514                        if g.is_empty() {
515                            return fail(Rule::Shape, "inputs.keys: a getters override must be non-empty");
516                        }
517                        let parsed: Vec<Getter> = g
518                            .iter()
519                            .map(|n| getter_name(n, "inputs.keys getters"))
520                            .collect::<R<Vec<_>>>()?;
521                        // case.md §8a item 4: a getters override must not name the same getter twice.
522                        let mut sorted = parsed.clone();
523                        sorted.sort();
524                        if sorted.windows(2).any(|w| w[0] == w[1]) {
525                            return fail(
526                                Rule::Shape,
527                                format!("inputs.keys: getters override {g:?} names the same getter twice"),
528                            );
529                        }
530                        Some(parsed)
531                    }
532                };
533                eo.finish()?;
534                if entries.iter().any(|x| x.key == key) {
535                    return fail(Rule::Shape, format!("inputs.keys: duplicate key {key:?}"));
536                }
537                entries.push(KeySpec { key, getters });
538            }
539            if entries.is_empty() {
540                return fail(Rule::Shape, "inputs.keys: must list at least one key");
541            }
542            Some(entries)
543        }
544    };
545    o.finish()?;
546    let inputs = Inputs {
547        env,
548        yaml,
549        fleet_policy,
550        cli,
551        updates,
552        keys: Vec::new(),
553    };
554    Ok((inputs, keys))
555}
556
557fn case_line(v: &Json, header: &Header) -> R<Pending> {
558    let mut o = Obj::new(v, "case line")?;
559    string(o.req("type")?, "type")?;
560    let name = string(o.req("case")?, "case")?.to_string();
561    let name_ok = name
562        .bytes()
563        .next()
564        .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
565        && name
566            .bytes()
567            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-');
568    if !name_ok {
569        return fail(
570            Rule::Shape,
571            format!("case name {name:?} does not match ^[a-z0-9][a-z0-9-]*$"),
572        );
573    }
574    let group = listed(string(o.req("group")?, "group")?, Group::parse, Group::ALL, "group")?;
575    let why = strings(o.req("why")?, "why")?;
576    if group == Group::Behavior && why.is_empty() {
577        return fail(Rule::Shape, "a behavior case must have a non-empty why");
578    }
579    let (inputs, written_keys) = inputs(o.req("inputs")?)?;
580    let origin = match (o.opt("origin")?, o.opt("startup_error")?) {
581        (Some(v), None) => Ok(string(v, "origin")?.to_string()),
582        (None, Some(v)) => Err(string(v, "startup_error")?.to_string()),
583        _ => {
584            return fail(
585                Rule::Consistency,
586                "a case line must have exactly one of `origin` and `startup_error`",
587            )
588        }
589    };
590    let containerized = o.opt("containerized")?;
591    let features = o.opt("features")?;
592    let side_effects = opt_nonempty(&mut o, "side_effects")?;
593    let recorded = opt_nonempty(&mut o, "updates")?;
594    let construction_warnings = opt_nonempty(&mut o, "construction_warnings")?
595        .iter()
596        .map(|w| warning(w, "construction_warnings element"))
597        .collect::<R<Vec<_>>>()?;
598    let sort_key = |w: &Warning| (w.message.clone(), w.level.as_str());
599    if construction_warnings
600        .windows(2)
601        .any(|w| sort_key(&w[0]) > sort_key(&w[1]))
602    {
603        return fail(
604            Rule::Shape,
605            "construction_warnings are not sorted by message, then level",
606        );
607    }
608    let mut pending = Pending {
609        case: Case {
610            name,
611            group,
612            why,
613            inputs,
614            construction_warnings,
615            input_line: 0,
616            outcome: Outcome::StartupError(String::new()),
617        },
618        line: 0,
619        written_keys,
620        started: None,
621        key_lines: Vec::new(),
622    };
623    let origin = match origin {
624        Ok(origin) => origin,
625        Err(error) => {
626            // record.md §3.3: no update ran, so `updates` is omitted; `inputs.updates` still lists them.
627            if containerized.is_some() || features.is_some() || !side_effects.is_empty() || !recorded.is_empty() {
628                return fail(
629                    Rule::Consistency,
630                    "on startup failure `features`, `containerized`, `side_effects` and `updates` must be omitted",
631                );
632            }
633            o.finish()?;
634            pending.case.outcome = Outcome::StartupError(error);
635            return Ok(pending);
636        }
637    };
638    let containerized = match containerized {
639        None => header.containerized,
640        Some(c) => {
641            let c = boolean(c, "containerized")?;
642            if c == header.containerized {
643                return fail(
644                    Rule::Consistency,
645                    "`containerized` is written only when it differs from the header",
646                );
647            }
648            c
649        }
650    };
651    let features = match features {
652        None => header.features.clone(),
653        Some(f) => {
654            let f = strings(f, "features")?;
655            if !strictly_sorted(&f) {
656                return fail(Rule::Shape, "features are not sorted and unique");
657            }
658            if f == header.features {
659                return fail(
660                    Rule::Consistency,
661                    "`features` is written only when it differs from the header",
662                );
663            }
664            f
665        }
666    };
667    let mut effects: Vec<SideEffect> = Vec::new();
668    for s in side_effects {
669        let mut e = Obj::new(s, "side_effects element")?;
670        let key = string(e.req("key")?, "side_effects key")?.to_string();
671        let setting = if let Some(absent) = e.opt("absent")? {
672            if !boolean(absent, "side_effects absent")? {
673                return fail(Rule::Shape, "side_effects: `absent` is written only as true");
674            }
675            None
676        } else {
677            Some(streamed(&mut e)?)
678        };
679        e.finish()?;
680        if effects.last().is_some_and(|p| p.key.as_bytes() >= key.as_bytes()) {
681            return fail(
682                Rule::Shape,
683                format!("side_effects are not strictly sorted by key at {key:?}"),
684            );
685        }
686        effects.push(SideEffect { key, setting });
687    }
688    let expected = pending.case.inputs.updates.len();
689    if recorded.len() != expected {
690        return fail(
691            Rule::Consistency,
692            format!(
693                "`updates` has {} elements but inputs.updates has {expected}",
694                recorded.len()
695            ),
696        );
697    }
698    let mut updates = Vec::new();
699    for u in recorded {
700        let mut e = Obj::new(u, "updates element")?;
701        let seq_delta = uint(e.req("seq_delta")?, "seq_delta")?;
702        let timed_out = match e.opt("timed_out")? {
703            None => false,
704            Some(t) => {
705                if !boolean(t, "timed_out")? {
706                    return fail(Rule::Shape, "updates: `timed_out` is written only as true");
707                }
708                if seq_delta == 0 {
709                    return fail(Rule::Consistency, "updates: `timed_out` requires seq_delta > 0");
710                }
711                true
712            }
713        };
714        let warnings = warnings(&mut e, "update warning")?;
715        e.finish()?;
716        updates.push(UpdateResult {
717            seq_delta,
718            timed_out,
719            warnings,
720        });
721    }
722    o.finish()?;
723    pending.started = Some(StartedLine {
724        origin,
725        containerized,
726        features,
727        side_effects: effects,
728        updates,
729    });
730    Ok(pending)
731}
732
733/// A read (record.md §5.3); returns it with its written `source`, which the caller reconstructs.
734fn read_checkpoint(v: &Json, what: &'static str) -> R<(Vec<GetterRead>, String, Option<Source>)> {
735    let mut o = Obj::new(v, what)?;
736    let mut reads = Vec::new();
737    let getters = array(o.req("getters")?, "getters")?;
738    if getters.is_empty() {
739        return fail(Rule::Shape, format!("{what}: getters must be non-empty"));
740    }
741    for g in getters {
742        let mut r = Obj::new(g, "getter result")?;
743        let name = getter_name(string(r.req("getter")?, "getter")?, "getter")?;
744        let raw = r.req_nullable("result")?;
745        go_json(raw, "getter result")?;
746        let result = getter::decode(name, raw).map_err(|e| Fail(Rule::GetterResult, format!("{what}: {e}")))?;
747        let warnings = warnings(&mut r, "getter warning")?;
748        r.finish()?;
749        reads.push(GetterRead {
750            getter: name,
751            result,
752            warnings,
753        });
754    }
755    let go_type = string(o.req("go_type")?, "go_type")?.to_string();
756    let written = match o.opt("source")? {
757        None => None,
758        Some(s) => {
759            let src = source(string(s, "read source")?, "read source")?;
760            // record.md §5.1's `""` is legal only for a streamed setting's `source`; a read's
761            // source (`GetSource(key).String()`) keeps its own rules and is never empty.
762            if src == Source::Empty {
763                return fail(Rule::Shape, format!("{what}.source must not be \"\""));
764            }
765            Some(src)
766        }
767    };
768    o.finish()?;
769    Ok((reads, go_type, written))
770}
771
772/// Reconstructs a read's `source` from the streamed setting it may be omitted in favour of (§5.3).
773fn read_source(written: Option<Source>, streamed: Option<Source>, what: &str) -> R<Source> {
774    match (written, streamed) {
775        (None, None) => fail(
776            Rule::Reconstruction,
777            format!("{what}.source must be written when the compared setting is null"),
778        ),
779        (Some(w), Some(s)) if w == s => fail(
780            Rule::Reconstruction,
781            format!("{what}.source must be omitted when it equals the streamed source {s:?}"),
782        ),
783        (Some(w), _) => Ok(w),
784        (None, Some(s)) => Ok(s),
785    }
786}
787
788fn key_line(v: &Json, case: &mut Pending) -> R<()> {
789    let Some(started) = &case.started else {
790        return fail(Rule::Consistency, "a case with a startup_error must have no key lines");
791    };
792    let mut o = Obj::new(v, "key line")?;
793    string(o.req("type")?, "type")?;
794    // The caller has matched `case` against the open case line.
795    string(o.req("case")?, "case")?;
796    let key = case_key(o.req("key")?, "key")?;
797    let snapshot = match o.req_nullable("snapshot")? {
798        Json::Null => None,
799        s => {
800            let mut so = Obj::new(s, "snapshot")?;
801            let setting = streamed(&mut so)?;
802            so.finish()?;
803            Some(setting)
804        }
805    };
806    let mut raw_events = Vec::new();
807    for e in opt_nonempty(&mut o, "events")? {
808        let mut eo = Obj::new(e, "event")?;
809        let setting = streamed(&mut eo)?;
810        let seq = NonZeroU64::new(uint(eo.req("seq")?, "event seq")?).ok_or("event seq must be >= 1")?;
811        let update = eo.opt("update")?.map(|u| uint(u, "event update")).transpose()?;
812        eo.finish()?;
813        raw_events.push((setting, seq, update));
814    }
815    // Reconstruct omitted event attributions (§5.2) and check written ones name an update (§3.3).
816    let updates = &case.case.inputs.updates;
817    let matching: Vec<usize> = (0..updates.len()).filter(|&i| updates[i].key == key).collect();
818    let written = raw_events.iter().filter(|e| e.2.is_some()).count();
819    if written != 0 && written != raw_events.len() {
820        return fail(
821            Rule::Reconstruction,
822            "event `update` must be written on all of a line's events or on none",
823        );
824    }
825    let attributed: Vec<usize> = if written == 0 {
826        if !raw_events.is_empty() && matching.len() != 1 {
827            return fail(
828                Rule::Reconstruction,
829                format!(
830                    "event `update` omitted but {} of the case's updates have key {key:?}",
831                    matching.len()
832                ),
833            );
834        }
835        raw_events.iter().map(|_| matching[0]).collect()
836    } else {
837        let idx: Vec<usize> = raw_events
838            .iter()
839            .map(|e| usize::try_from(e.2.unwrap_or_default()).unwrap_or(usize::MAX))
840            .collect();
841        if let Some(bad) = idx.iter().find(|&&i| i >= updates.len()) {
842            return fail(
843                Rule::Consistency,
844                format!("event `update` {bad} names no update (the case has {})", updates.len()),
845            );
846        }
847        if matching.len() == 1 && idx.iter().all(|&i| i == matching[0]) {
848            return fail(
849                Rule::Reconstruction,
850                "event `update` must be omitted: every event belongs to the one update of this key",
851            );
852        }
853        idx
854    };
855    let mut events = Vec::new();
856    for ((setting, seq, _), update) in raw_events.into_iter().zip(attributed) {
857        let delta = started.updates[update].seq_delta;
858        if seq.get() > delta {
859            return fail(
860                Rule::Consistency,
861                format!("event seq {seq} exceeds seq_delta {delta} of update {update}"),
862            );
863        }
864        events.push(Event { setting, seq, update });
865    }
866    let mut ro = Obj::new(o.req("reads")?, "reads")?;
867    let (snap_getters, go_type, written) = read_checkpoint(ro.req("snapshot")?, "reads.snapshot")?;
868    let snap_source = read_source(written, snapshot.as_ref().map(|s| s.source), "reads.snapshot")?;
869    let snapshot_read = Read {
870        getters: snap_getters,
871        go_type,
872        source: snap_source,
873    };
874    let final_ = match (ro.opt("final")?, updates.is_empty()) {
875        (Some(_), true) => return fail(Rule::Consistency, "reads.final is present but the case has no updates"),
876        (None, false) => return fail(Rule::Consistency, "reads.final is missing but the case has updates"),
877        (None, true) => None,
878        (Some(f), false) => {
879            let (getters, go_type, written) = read_checkpoint(f, "reads.final")?;
880            let compared = events.last().map(|e| &e.setting).or(snapshot.as_ref());
881            let source = read_source(written, compared.map(|s| s.source), "reads.final")?;
882            let names = |g: &[GetterRead]| g.iter().map(|r| r.getter).collect::<Vec<_>>();
883            if names(&getters) != names(&snapshot_read.getters) {
884                return fail(
885                    Rule::Consistency,
886                    "reads.final and reads.snapshot call different getters",
887                );
888            }
889            Some(Read {
890                getters,
891                go_type,
892                source,
893            })
894        }
895    };
896    ro.finish()?;
897    if let Some(over) = case.override_for(&key) {
898        let called: Vec<Getter> = snapshot_read.getters.iter().map(|r| r.getter).collect();
899        if over != called.as_slice() {
900            return fail(
901                Rule::Consistency,
902                format!("reads call {called:?}, not the inputs.keys override {over:?}"),
903            );
904        }
905    }
906    o.finish()?;
907    case.key_lines.push(KeyLine {
908        key,
909        snapshot,
910        events,
911        reads: Reads {
912            snapshot: snapshot_read,
913            final_,
914        },
915    });
916    Ok(())
917}
918
919fn push(errors: &mut Vec<Violation>, line: usize, Fail(rule, message): Fail) {
920    errors.push(Violation { line, rule, message });
921}
922
923/// Closes the open case: runs the rules that need all its key lines, then keeps it.
924fn close(pending: Option<Pending>, cases: &mut Vec<Case>, errors: &mut Vec<Violation>) {
925    if let Some(p) = pending {
926        let (line, name) = (p.line, p.case.name.clone());
927        match p.finish() {
928            Ok(c) => cases.push(c),
929            Err(Fail(rule, m)) => push(errors, line, Fail(rule, format!("case {name:?}: {m}"))),
930        }
931    }
932}
933
934fn sort_key(v: &Json) -> Option<(String, u8, String)> {
935    let Json::Obj(m) = v else { return None };
936    let get = |n: &str| m.iter().find(|(k, _)| k.text == n).and_then(|(_, v)| v.as_str());
937    match get("type")? {
938        "case" => Some((get("case")?.to_string(), 0, String::new())),
939        "key" => Some((get("case")?.to_string(), 1, get("key")?.to_string())),
940        _ => None,
941    }
942}
943
944fn member<'a>(v: &'a Json, name: &str) -> Option<&'a str> {
945    match v {
946        Json::Obj(m) => m.iter().find(|(k, _)| k.text == name).and_then(|(_, v)| v.as_str()),
947        _ => None,
948    }
949}
950
951/// Reads a whole corpus (record.md), filling in every member a writer may omit.
952///
953/// # Errors
954///
955/// Returns every rule violation found, each with its line. The reader goes on past a bad line, so
956/// one run reports all of them.
957pub fn read(bytes: &[u8]) -> Result<Corpus, Vec<Violation>> {
958    let mut errors = Vec::new();
959    if bytes.starts_with(b"\xef\xbb\xbf") {
960        push(&mut errors, 1, Fail(Rule::File, "starts with a BOM".into()));
961    }
962    if !bytes.is_empty() && !bytes.ends_with(b"\n") {
963        push(
964            &mut errors,
965            0,
966            Fail(Rule::File, "the last line does not end in \\n".into()),
967        );
968    }
969    let mut lines: Vec<&[u8]> = bytes.split(|&c| c == b'\n').collect();
970    if bytes.ends_with(b"\n") || bytes.is_empty() {
971        lines.pop();
972    }
973    let mut header_info: Option<Header> = None;
974    let mut pending: Option<Pending> = None;
975    let mut cases: Vec<Case> = Vec::new();
976    let mut prev: Option<(String, u8, String)> = None;
977    for (i, raw) in lines.iter().enumerate() {
978        let n = i + 1;
979        if raw.is_empty() {
980            push(&mut errors, n, Fail(Rule::File, "blank line".into()));
981            continue;
982        }
983        // Validated once per line; the scanner then works on `&str`.
984        let text = match String::from_utf8(raw.to_vec()) {
985            Ok(t) => t,
986            Err(e) => {
987                let at = e.utf8_error().valid_up_to() + 1;
988                push(&mut errors, n, Fail(Rule::File, format!("not UTF-8 at byte {at}")));
989                continue;
990            }
991        };
992        let v = match parse_line(&text) {
993            Ok(v) => v,
994            Err(e) => {
995                let e = e.strip_prefix("canonical form: ").unwrap_or(&e).to_string();
996                push(&mut errors, n, Fail(Rule::Canonical, e));
997                continue;
998            }
999        };
1000        let result = match (member(&v, "type"), n) {
1001            (Some("header"), 1) => header(&v).map(|h| header_info = Some(h)),
1002            (Some("header"), _) => fail(Rule::Order, "a header line may only be line 1"),
1003            (_, 1) => fail(Rule::Order, "the first line must be the header"),
1004            (Some("case"), _) => {
1005                close(pending.take(), &mut cases, &mut errors);
1006                match &header_info {
1007                    // Without a header, case lines cannot be checked against it; that is already reported.
1008                    None => Ok(()),
1009                    Some(h) => case_line(&v, h).and_then(|mut c| {
1010                        c.line = n;
1011                        if cases.iter().any(|x| x.name == c.case.name) {
1012                            return fail(Rule::Order, format!("case name {:?} is not unique", c.case.name));
1013                        }
1014                        pending = Some(c);
1015                        Ok(())
1016                    }),
1017                }
1018            }
1019            (Some("key"), _) => {
1020                let name = member(&v, "case");
1021                match pending.as_mut() {
1022                    Some(c) if Some(c.case.name.as_str()) == name => {
1023                        key_line(&v, c).map_err(|Fail(r, m)| Fail(r, format!("case {:?} key line: {m}", c.case.name)))
1024                    }
1025                    _ => fail(
1026                        Rule::Order,
1027                        format!("key line for case {name:?} does not follow its case line"),
1028                    ),
1029                }
1030            }
1031            (other, _) => fail(Rule::Shape, format!("line type {other:?} is not header, case or key")),
1032        };
1033        if let Err(f) = result {
1034            push(&mut errors, n, f);
1035        }
1036        if n > 1 {
1037            match sort_key(&v) {
1038                Some(k) => {
1039                    if let Some(p) = &prev {
1040                        let a = (p.0.as_bytes(), p.1, p.2.as_bytes());
1041                        let b = (k.0.as_bytes(), k.1, k.2.as_bytes());
1042                        if a >= b {
1043                            push(
1044                                &mut errors,
1045                                n,
1046                                Fail(Rule::Order, "lines are not strictly sorted by (case, rank, key)".into()),
1047                            );
1048                        }
1049                    }
1050                    prev = Some(k);
1051                }
1052                None => push(
1053                    &mut errors,
1054                    n,
1055                    Fail(Rule::Order, "line has no (case, key) to sort by".into()),
1056                ),
1057            }
1058        }
1059    }
1060    close(pending.take(), &mut cases, &mut errors);
1061    if lines.is_empty() {
1062        push(
1063            &mut errors,
1064            0,
1065            Fail(Rule::File, "the corpus is empty; it needs a header line".into()),
1066        );
1067    } else if header_info.is_some() && cases.is_empty() {
1068        push(&mut errors, 0, Fail(Rule::File, "the corpus has no case lines".into()));
1069    } else if header_info.is_some() {
1070        // record.md §3.2: `first_snapshot` needs the one `baseline-default` case; case.md §3.2
1071        // allows only one case of group `baseline`.
1072        let baseline: Vec<&Case> = cases.iter().filter(|c| c.group == Group::Baseline).collect();
1073        match baseline.len() {
1074            0 => push(
1075                &mut errors,
1076                0,
1077                Fail(
1078                    Rule::Consistency,
1079                    format!(
1080                        "the corpus has no case of group baseline named {BASELINE_CASE:?}; first_snapshot needs it"
1081                    ),
1082                ),
1083            ),
1084            1 if baseline[0].name != BASELINE_CASE => push(
1085                &mut errors,
1086                0,
1087                Fail(
1088                    Rule::Consistency,
1089                    format!(
1090                        "the corpus's one case of group baseline is named {:?}, not {BASELINE_CASE:?}",
1091                        baseline[0].name
1092                    ),
1093                ),
1094            ),
1095            1 => {}
1096            n => push(
1097                &mut errors,
1098                0,
1099                Fail(
1100                    Rule::Consistency,
1101                    format!("the corpus has {n} cases of group baseline; case.md §3.2 allows only one"),
1102                ),
1103            ),
1104        }
1105    }
1106    match header_info {
1107        Some(header) if errors.is_empty() => Ok(Corpus { header, cases }),
1108        _ => Err(errors),
1109    }
1110}