dive-trace 0.1.0

TLA+ counterexample trace format and independent trace validation
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
//! Counterexample transports: dive's format (versions 1 through 6) and TLC's JSON.
//!
//! # dive's format
//!
//! ```json
//! {
//!   "format": "dive-trace",
//!   "version": 1,
//!   "variables": ["big", "small"],
//!   "states": [
//!     {"action": null, "values": {"big": 0, "small": 0}},
//!     {"action": {"name": "FillBigJug", "location": "line 68, col 18 to line 69, col 34 of module DieHard"},
//!      "values": {"big": 5, "small": 0}}
//!   ],
//!   "ending": {"kind": "invariant", "name": "NotSolved"}
//! }
//! ```
//!
//! - `variables` lists the specification's variables. Every state assigns
//!   exactly these, in dive's value JSON ([`crate::value_json`]).
//! - `states[k].action` labels the step into state `k`: `null` for the
//!   initial state, and optional elsewhere. `name` is the action's name as
//!   TLC prints it, without parameters; `location` is informative.
//! - `ending` says what the trace claims ([`Ending`]):
//!
//!   | `kind` | Fields | Claim |
//!   |---|---|---|
//!   | `invariant` | `name` | the invariant is false in the last state |
//!   | `property` | `name` | the action property is false on the last step (or, for a one-state trace, the implied initial predicate is false in it) |
//!   | `deadlock` | | the last state has no successor |
//!   | `behavior` | | nothing beyond being a behavior of the specification (implementation traces) |
//!   | `lasso` | `back_to` | the last state's successor is state `back_to` (0-based); a liveness counterexample |
//!   | `stuttering` | | the behavior stutters forever after the last state |
//!   | `assertion`, `error` | `ec` (`error`, optional) | expanding the last state fails |
//!   | `invariant-error` | `name`, `ec` | evaluating the named invariant on the last state raises the given underlying error |
//!
//! The format version is the lowest one that can express the document:
//!
//! | Version | Adds |
//! |---|---|
//! | 1 | every ending kind above except `invariant-error` |
//! | 2 | the `invariant-error` ending |
//! | 3 | a terminal partial candidate, separate from the complete state rows |
//! | 4 | ordered errors on the candidate side of a step |
//! | 5 | errors in temporal-source rows after `Next` |
//! | 6 | errors in a source-final `VIEW` evaluation |
//!
//! Readers accept all six versions and reject a version-1 document that uses
//! the `invariant-error` ending. Unknown versions and ending kinds are
//! rejected, never guessed.
//!
//! `invariant-error.ec` is the underlying evaluation cause. The enclosing
//! check report retains TLC's deciding class, normally
//! `TLC_INVARIANT_EVALUATION_FAILED` (2111), or a separately qualified
//! diagnostic replay's class; replacing the cause with a wrapper is invalid. Validation
//! requires the named invariant to raise exactly that cause, with all
//! earlier states and earlier configured invariants passing.
//!
//! - `length` (optional) is the claimed number of states; it must match.
//! - `properties` lists all temporal properties violated by a lasso or
//!   stuttering word. Older documents without names remain unsupported for
//!   liveness validation. An enclosing report's names must agree with these.
//!
//! `dive check --output json` embeds this object as `counterexample.trace`;
//! [`TraceDoc::from_json`] accepts the object itself, a document that
//! carries it as `counterexample`, or `dive check`'s report or its
//! `counterexample` object.
//!
//! # TLC's format
//!
//! TLC's `-dumpTrace json` document (`{"vars": [...], "counterexample":
//! {"state": [[1, {...}], ...], "action": [[[1, {...}], {"name": ...}, [2,
//! {...}]], ...]}}`) is read too. It carries no ending, so one must be
//! given ([`TraceDoc::with_ending`]), and its values are in TLC's lossy form,
//! which [`crate::tlc`] interprets against the model.

use serde_json::{Map, Value as J, json};

/// The format name in [`TraceDoc::to_json`].
pub const FORMAT: &str = "dive-trace";

/// The base format version, still written for every ending kind that needs
/// nothing newer.
pub const VERSION: u64 = 1;

/// The format version required by named invariant-error endings.
pub const INVARIANT_ERROR_VERSION: u64 = 2;

/// Version for a terminal partial candidate separate from complete prefix rows.
pub const PARTIAL_STATE_VERSION: u64 = 3;

/// Version for an ordered candidate-side error with independent wrapper replay.
pub const CANDIDATE_ERROR_VERSION: u64 = 4;

/// Version for an independently replayed post-Next temporal-source-row error.
pub const TEMPORAL_SOURCE_ERROR_VERSION: u64 = 5;

/// Version for a source-final VIEW demand with independently reconstructed keys.
pub const VIEW_SOURCE_ERROR_VERSION: u64 = 6;

/// What a trace claims about its end.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Ending {
    /// The named invariant is false in the last state.
    Invariant(String),
    /// The named action property is false on the last step; for a
    /// one-state trace, the named implied initial predicate is false in it.
    Property(String),
    /// The last state has no successor.
    Deadlock,
    /// No violation: the trace is a behavior of the specification.
    Behavior,
    /// A liveness counterexample that loops back to state `back_to`
    /// (0-based).
    Lasso {
        /// The state the last state's successor equals.
        back_to: usize,
    },
    /// A liveness counterexample that stutters after the last state.
    Stuttering,
    /// An assertion fails while the last state is expanded.
    Assertion,
    /// An evaluation error while the last state is expanded.
    Error {
        /// TLC's error class, if known (`EC` name).
        ec: Option<String>,
    },
    /// The named invariant fails to evaluate in the last state. Earlier
    /// invariants and earlier states must pass. `ec` names the underlying
    /// error, not TLC's `TLC_INVARIANT_EVALUATION_FAILED` wrapper.
    InvariantError {
        /// The configured invariant name.
        name: String,
        /// The underlying evaluation error's `EC` name.
        ec: String,
    },
    /// A source-state demand error, checked only by a fresh source-bound session.
    /// Its descriptor requests independent replay, never grants authority.
    TemporalStateError {
        /// The expected TLC evaluation error class.
        ec: String,
        /// Untrusted stage and original inner source context.
        endpoint: crate::TemporalStateEndpoint,
    },
    /// A post-Next row error with independently reconstructed primary lifecycle.
    TemporalSourceError {
        /// Untrusted underlying row-error class, distinct from outer wrappers.
        ec: String,
        /// Original row-error source only; fresh replay supplies all authority.
        endpoint: crate::TemporalSourceEndpoint,
    },
    /// Next raises this underlying error before emitting any successor.
    /// Only fresh source-bound replay can establish the original context.
    NextStateError {
        /// The underlying evaluation error class, never a replay wrapper.
        ec: String,
        /// Untrusted original source context.
        endpoint: crate::NextStateEndpoint,
    },
    /// A generated final candidate raises an independently replayed error.
    CandidateStateError {
        /// Underlying primary error, distinct from the deciding wrapper.
        ec: String,
        /// Untrusted actual site, original source and both wrapper identities.
        endpoint: crate::CandidateStateEndpoint,
    },
    /// A VIEW demand fails on an independently generated candidate; the last
    /// complete row is its source, never the absent failing candidate.
    ViewSourceError {
        /// Underlying primary error, distinct from the diagnostic wrapper.
        ec: String,
        /// Untrusted original source and both exception identities.
        endpoint: crate::ViewSourceEndpoint,
    },
    /// An actual incomplete Next candidate, separately replayed from its prefix.
    PartialNext {
        /// Untrusted source context and assigned/unassigned bindings.
        endpoint: crate::PartialNextEndpoint,
    },
    /// An actual partial Init candidate, with no complete prefix state.
    PartialInit {
        /// Untrusted observed bindings/source, requiring fresh Init generation.
        endpoint: crate::PartialStateEndpoint,
    },
}

impl Ending {
    /// The JSON form.
    #[must_use]
    pub fn to_json(&self) -> J {
        match self {
            Self::Invariant(n) => json!({"kind": "invariant", "name": n}),
            Self::Property(n) => json!({"kind": "property", "name": n}),
            Self::Deadlock => json!({"kind": "deadlock"}),
            Self::Behavior => json!({"kind": "behavior"}),
            Self::Lasso { back_to } => json!({"kind": "lasso", "back_to": back_to}),
            Self::Stuttering => json!({"kind": "stuttering"}),
            Self::Assertion => json!({"kind": "assertion"}),
            Self::Error { ec } => json!({"kind": "error", "ec": ec}),
            Self::InvariantError { name, ec } => {
                json!({"kind": "invariant-error", "name": name, "ec": ec})
            }
            Self::TemporalStateError { ec, endpoint } => {
                json!({"kind":"error", "ec":ec, "endpoint":endpoint.to_json()})
            }
            Self::TemporalSourceError { ec, endpoint } => {
                json!({"kind":"error", "ec":ec, "endpoint":endpoint.to_json()})
            }
            Self::ViewSourceError { ec, endpoint } => {
                json!({"kind":"error", "ec":ec, "endpoint":endpoint.to_json()})
            }
            Self::CandidateStateError { ec, endpoint } => {
                json!({"kind":"error", "ec":ec, "endpoint":endpoint.to_json()})
            }
            Self::NextStateError { ec, endpoint } => {
                json!({"kind":"error", "ec":ec, "endpoint":endpoint.to_json()})
            }
            Self::PartialNext { endpoint } => {
                json!({"kind":"partial-state", "ec":"TLC_STATE_NOT_COMPLETELY_SPECIFIED_NEXT", "endpoint":endpoint.to_json()})
            }
            Self::PartialInit { endpoint } => {
                json!({"kind":"partial-state","ec":"TLC_INITIAL_STATE","endpoint":endpoint.to_json()})
            }
        }
    }

    /// Reads the JSON form.
    ///
    /// # Errors
    /// For an unknown kind or a missing field.
    #[allow(
        clippy::too_many_lines,
        reason = "closed endpoint variants are decoded together without fallback"
    )]
    pub fn from_json(j: &J) -> Result<Self, String> {
        let kind = j
            .get("kind")
            .and_then(J::as_str)
            .ok_or("an ending needs a `kind`")?;
        if j.get("endpoint").is_some() {
            let object = j.as_object().ok_or("ending must be an object")?;
            if kind == "partial-state" {
                if object.len() != 3 {
                    return Err("partial Next ending needs its exact incomplete-state class".into());
                }
                let endpoint = crate::PartialStateEndpoint::from_json(&j["endpoint"])?;
                return match (endpoint.initial(), j["ec"].as_str()) {
                    (false, Some("TLC_STATE_NOT_COMPLETELY_SPECIFIED_NEXT")) => {
                        Ok(Self::PartialNext { endpoint })
                    }
                    (true, Some("TLC_INITIAL_STATE")) => Ok(Self::PartialInit { endpoint }),
                    _ => Err("partial terminal phase and error class disagree".into()),
                };
            }
            if kind != "error" || object.len() != 3 || !object.contains_key("ec") {
                return Err("endpoint requires an exact error ending".into());
            }
            if j["endpoint"]["stage"] == "temporal-source-row" {
                return Ok(Self::TemporalSourceError {
                    ec: j["ec"]
                        .as_str()
                        .filter(|ec| !ec.is_empty())
                        .ok_or("temporal source endpoint needs an underlying error class")?
                        .to_owned(),
                    endpoint: crate::TemporalSourceEndpoint::from_json(&j["endpoint"])?,
                });
            }
            if j["endpoint"]["stage"] == "view-source-terminal" {
                return Ok(Self::ViewSourceError {
                    ec: j["ec"]
                        .as_str()
                        .filter(|ec| !ec.is_empty())
                        .ok_or("VIEW endpoint needs an underlying error class")?
                        .to_owned(),
                    endpoint: crate::ViewSourceEndpoint::from_json(&j["endpoint"])?,
                });
            }
            if j["endpoint"]["stage"] == "candidate-ordered-terminal" {
                return Ok(Self::CandidateStateError {
                    ec: j["ec"]
                        .as_str()
                        .filter(|ec| !ec.is_empty())
                        .ok_or("candidate endpoint needs an underlying error class")?
                        .to_owned(),
                    endpoint: crate::CandidateStateEndpoint::from_json(&j["endpoint"])?,
                });
            }
            if matches!(
                j["endpoint"]["stage"].as_str(),
                Some("next-before-successor" | "next-ordered-terminal")
            ) {
                return Ok(Self::NextStateError {
                    ec: j["ec"]
                        .as_str()
                        .filter(|ec| !ec.is_empty())
                        .ok_or("a Next endpoint needs an underlying error class")?
                        .to_owned(),
                    endpoint: crate::NextStateEndpoint::from_json(&j["endpoint"])?,
                });
            }
            let ec = j["ec"]
                .as_str()
                .filter(|ec| matches!(*ec, "TLC_MODULE_DIVISION_BY_ZERO" | "TLC_MODULE_EVALUATING"))
                .ok_or("unsupported temporal endpoint error class")?
                .to_owned();
            return Ok(Self::TemporalStateError {
                ec,
                endpoint: crate::TemporalStateEndpoint::from_json(&j["endpoint"])?,
            });
        }
        let name = || {
            j.get("name")
                .and_then(J::as_str)
                .map(str::to_owned)
                .ok_or_else(|| format!("a `{kind}` ending needs a `name`"))
        };
        Ok(match kind {
            "invariant" => Self::Invariant(name()?),
            "property" => Self::Property(name()?),
            "deadlock" => Self::Deadlock,
            "behavior" => Self::Behavior,
            "lasso" => Self::Lasso {
                back_to: j
                    .get("back_to")
                    .and_then(J::as_u64)
                    .and_then(|n| usize::try_from(n).ok())
                    .ok_or("a `lasso` ending needs `back_to`")?,
            },
            "stuttering" => Self::Stuttering,
            "assertion" => Self::Assertion,
            "error" => Self::Error {
                ec: j.get("ec").and_then(J::as_str).map(str::to_owned),
            },
            "invariant-error" => Self::InvariantError {
                name: name()?,
                ec: j
                    .get("ec")
                    .and_then(J::as_str)
                    .filter(|ec| !ec.is_empty())
                    .ok_or("an invariant-error ending needs an underlying `ec`")?
                    .to_owned(),
            },
            other => return Err(format!("unknown ending kind `{other}`")),
        })
    }

    /// The ending of a TLC counterexample reported with error class `class`
    /// (TLC's `EC` name) and violated property `property`. A temporal
    /// property violation needs the trace's loop, which TLC reports
    /// separately: `back_to` is the state its lasso returns to (0-based), or
    /// `None` for stuttering.
    #[must_use]
    pub fn from_tlc(class: &str, property: Option<&str>, back_to: Option<usize>) -> Option<Self> {
        let named = || property.map(str::to_owned);
        Some(match class {
            "TLC_INVARIANT_VIOLATED_INITIAL" | "TLC_INVARIANT_VIOLATED_BEHAVIOR" => {
                Self::Invariant(named()?)
            }
            "TLC_PROPERTY_VIOLATED_INITIAL" | "TLC_ACTION_PROPERTY_VIOLATED_BEHAVIOR" => {
                Self::Property(named()?)
            }
            "TLC_DEADLOCK_REACHED" => Self::Deadlock,
            "TLC_TEMPORAL_PROPERTY_VIOLATED" => match back_to {
                Some(back_to) => Self::Lasso { back_to },
                None => Self::Stuttering,
            },
            "TLC_VALUE_ASSERT_FAILED" => Self::Assertion,
            other => Self::Error {
                ec: Some(other.to_owned()),
            },
        })
    }

    /// Parses the command-line form: `invariant:NAME`, `property:NAME`,
    /// `deadlock`, `behavior`, `lasso:K`, `stuttering`, `assertion`,
    /// `error[:EC]`.
    ///
    /// # Errors
    /// For anything else.
    pub fn parse(text: &str) -> Result<Self, String> {
        let (kind, arg) = match text.split_once(':') {
            Some((k, a)) => (k, Some(a)),
            None => (text, None),
        };
        let mut j = json!({ "kind": kind });
        if let Some(a) = arg {
            match kind {
                "lasso" => {
                    j["back_to"] = J::from(
                        a.parse::<u64>()
                            .map_err(|_| format!("`{a}` is not a state index"))?,
                    );
                }
                "error" => j["ec"] = J::from(a),
                _ => j["name"] = J::from(a),
            }
        }
        Self::from_json(&j)
    }
}

/// The label of a step.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Label {
    /// The action's name, without parameters.
    pub name: String,
    /// Its location, as given.
    pub location: Option<String>,
}

/// Which format a document was read from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Source {
    /// dive's format.
    Dive,
    /// TLC's `-dumpTrace json`: values are in TLC's lossy form.
    Tlc,
}

/// A counterexample as data, before its values are read against a model.
#[derive(Clone, Debug, PartialEq)]
pub struct TraceDoc {
    /// The variables, as listed by the document.
    pub variables: Vec<String>,
    /// Each state's values by variable name, in the document's JSON form.
    pub states: Vec<Map<String, J>>,
    /// The label of the step into each state (`labels[0]` is `None`).
    pub labels: Vec<Option<Label>>,
    /// What the trace claims, if the document says.
    pub ending: Option<Ending>,
    /// The claimed number of states, if the document says.
    pub length: Option<usize>,
    /// The format.
    pub source: Source,
    /// All temporal properties claimed to be false on this periodic word.
    /// Empty for other endings, or for an older unnamed liveness document.
    pub properties: Vec<String>,
}

impl TraceDoc {
    /// Logical word length, including a separate terminal partial candidate.
    #[must_use]
    pub fn logical_length(&self) -> usize {
        self.states.len().saturating_add(usize::from(matches!(
            self.ending,
            Some(Ending::PartialNext { .. } | Ending::PartialInit { .. })
        )))
    }
    /// A behavior in dive's format, from states given as JSON objects
    /// (variable name to value, in dive's JSON form), with no labels. The
    /// ending is [`Ending::Behavior`]: use it to check an implementation's
    /// trace.
    ///
    /// # Errors
    /// If a state is not a JSON object.
    pub fn behavior(states: Vec<J>) -> Result<Self, String> {
        let mut out = Vec::with_capacity(states.len());
        for (k, s) in states.into_iter().enumerate() {
            match s {
                J::Object(m) => out.push(m),
                _ => return Err(format!("state {k} is not a JSON object")),
            }
        }
        let variables = out
            .first()
            .map(|m| m.keys().cloned().collect())
            .unwrap_or_default();
        let n = out.len();
        Ok(Self {
            variables,
            states: out,
            labels: vec![None; n],
            ending: Some(Ending::Behavior),
            length: None,
            source: Source::Dive,
            properties: Vec::new(),
        })
    }

    /// This document with its ending replaced.
    #[must_use]
    pub fn with_ending(mut self, ending: Ending) -> Self {
        self.ending = Some(ending);
        self
    }

    /// Names every temporal property this periodic word claims to violate.
    /// Validation checks the names, their truth values and completeness.
    #[must_use]
    pub fn with_properties(mut self, properties: Vec<String>) -> Self {
        self.properties = properties;
        self
    }

    /// Reads a document in dive's format (or one that carries it as
    /// `counterexample`), or in TLC's `-dumpTrace json` format.
    ///
    /// # Errors
    /// A message naming what is malformed.
    pub fn from_json(j: &J) -> Result<Self, String> {
        if j.get("format").and_then(J::as_str) == Some(FORMAT) {
            return Self::from_dive(j);
        }
        if let Some(witness) = j.get("error_witness")
            && witness.get("format").and_then(J::as_str) == Some(FORMAT)
        {
            if j.get("counterexample")
                .is_some_and(|value| !value.is_null())
            {
                return Err(
                    "a report cannot carry both a formal counterexample and an Init error witness"
                        .into(),
                );
            }
            let doc = Self::from_dive(witness)?;
            if !matches!(doc.ending, Some(Ending::PartialInit { .. })) {
                return Err("error_witness requires an Init partial terminal".into());
            }
            return Ok(doc);
        }
        // `dive check --output json`'s counterexample object carries the
        // document as `trace`; accept the object or the whole report.
        for t in [
            j.get("trace"),
            j.get("counterexample").and_then(|c| c.get("trace")),
        ]
        .into_iter()
        .flatten()
        {
            if t.get("format").and_then(J::as_str) == Some(FORMAT) {
                let mut doc = Self::from_dive(t)?;
                let outer = j.get("counterexample").unwrap_or(j);
                if let Some(names) = outer.get("properties") {
                    let names =
                        strings(Some(names)).ok_or("`properties` must be a list of names")?;
                    let outer_set: std::collections::BTreeSet<_> = names.iter().collect();
                    if outer_set.len() != names.len() {
                        return Err("enclosing report repeats a temporal property name".into());
                    }
                    if doc.properties.is_empty() {
                        doc.properties = names;
                    } else if doc.properties != names {
                        return Err("enclosing report and trace disagree on `properties`".into());
                    }
                }
                return Ok(doc);
            }
        }
        if let Some(c) = j.get("counterexample") {
            if c.get("format").and_then(J::as_str) == Some(FORMAT) {
                return Self::from_dive(c);
            }
            if j.get("vars").is_some() {
                return Self::from_tlc(j);
            }
        }
        Err(format!(
            "not a trace: expected a `{FORMAT}` document or TLC's -dumpTrace json document"
        ))
    }

    /// Reads [`TraceDoc::from_json`] from text.
    ///
    /// # Errors
    /// For invalid JSON or a malformed document.
    pub fn parse(text: &str) -> Result<Self, String> {
        let j: J = serde_json::from_str(text).map_err(|e| format!("invalid JSON: {e}"))?;
        Self::from_json(&j)
    }

    fn from_dive(j: &J) -> Result<Self, String> {
        let version = j.get("version").and_then(J::as_u64);
        if !matches!(
            version,
            Some(
                VERSION
                    | INVARIANT_ERROR_VERSION
                    | PARTIAL_STATE_VERSION
                    | CANDIDATE_ERROR_VERSION
                    | TEMPORAL_SOURCE_ERROR_VERSION
                    | VIEW_SOURCE_ERROR_VERSION
            )
        ) {
            return Err(format!(
                "unsupported {FORMAT} version {version:?}; this build reads versions {VERSION}, {INVARIANT_ERROR_VERSION}, {PARTIAL_STATE_VERSION}, {CANDIDATE_ERROR_VERSION}, {TEMPORAL_SOURCE_ERROR_VERSION} and {VIEW_SOURCE_ERROR_VERSION}"
            ));
        }
        let variables = strings(j.get("variables")).ok_or("`variables` must be a list of names")?;
        let states_j = j
            .get("states")
            .and_then(J::as_array)
            .ok_or("`states` must be a list")?;
        let mut states = Vec::with_capacity(states_j.len());
        let mut labels = Vec::with_capacity(states_j.len());
        for (k, s) in states_j.iter().enumerate() {
            let values = s
                .get("values")
                .and_then(J::as_object)
                .ok_or_else(|| format!("state {k} has no `values` object"))?;
            states.push(values.clone());
            labels.push(match s.get("action") {
                None | Some(J::Null) => None,
                Some(a) => Some(Label {
                    name: a
                        .get("name")
                        .and_then(J::as_str)
                        .ok_or_else(|| format!("state {k}: an action needs a `name`"))?
                        .to_owned(),
                    location: a.get("location").and_then(J::as_str).map(str::to_owned),
                }),
            });
        }
        let ending = match j.get("ending") {
            None | Some(J::Null) => None,
            Some(e) => Some(Ending::from_json(e)?),
        };
        if version == Some(VERSION) && matches!(ending, Some(Ending::InvariantError { .. })) {
            return Err("`invariant-error` requires dive-trace version 2".to_owned());
        }
        if matches!(
            ending,
            Some(Ending::PartialNext { .. } | Ending::PartialInit { .. })
        ) && version != Some(PARTIAL_STATE_VERSION)
        {
            return Err("a partial terminal candidate requires dive-trace version 3".into());
        }
        if version == Some(PARTIAL_STATE_VERSION)
            && !matches!(
                ending,
                Some(Ending::PartialNext { .. } | Ending::PartialInit { .. })
            )
        {
            return Err("dive-trace version 3 requires a partial terminal candidate".into());
        }
        if matches!(ending, Some(Ending::CandidateStateError { .. }))
            != (version == Some(CANDIDATE_ERROR_VERSION))
        {
            return Err("an ordered candidate error requires exactly dive-trace version 4".into());
        }
        if matches!(ending, Some(Ending::ViewSourceError { .. }))
            != (version == Some(VIEW_SOURCE_ERROR_VERSION))
        {
            return Err("a VIEW source error requires exactly dive-trace version 6".into());
        }
        if matches!(ending, Some(Ending::TemporalSourceError { .. }))
            != (version == Some(TEMPORAL_SOURCE_ERROR_VERSION))
        {
            return Err("a temporal source-row error requires exactly dive-trace version 5".into());
        }
        let length = match j.get("length") {
            None | Some(J::Null) => None,
            Some(l) => Some(
                l.as_u64()
                    .and_then(|n| usize::try_from(n).ok())
                    .ok_or("`length` must be a count")?,
            ),
        };
        Ok(Self {
            variables,
            states,
            labels,
            ending,
            length,
            source: Source::Dive,
            properties: match j.get("properties") {
                None => Vec::new(),
                Some(names) => {
                    strings(Some(names)).ok_or("`properties` must be a list of names")?
                }
            },
        })
    }

    fn from_tlc(j: &J) -> Result<Self, String> {
        let variables = strings(j.get("vars")).ok_or("`vars` must be a list of names")?;
        let cex = &j["counterexample"];
        let state_j = cex
            .get("state")
            .and_then(J::as_array)
            .ok_or("`counterexample.state` must be a list")?;
        let mut states = Vec::with_capacity(state_j.len());
        for (k, s) in state_j.iter().enumerate() {
            match s.as_array().map(Vec::as_slice) {
                Some([J::Number(n), J::Object(m)]) if n.as_u64() == Some(k as u64 + 1) => {
                    states.push(m.clone());
                }
                _ => {
                    return Err(format!(
                        "`counterexample.state[{k}]` is not [{}, {{...}}]",
                        k + 1
                    ));
                }
            }
        }
        let mut labels = vec![None; states.len()];
        let actions = cex
            .get("action")
            .and_then(J::as_array)
            .map(Vec::as_slice)
            .unwrap_or_default();
        let count = states.len();
        let state_at = |end: &J, at: usize| {
            matches!(end.as_array().map(Vec::as_slice),
                Some([J::Number(i), J::Object(m)])
                    if i.as_u64() == Some(at as u64 + 1) && states.get(at) == Some(m))
        };
        for (k, a) in actions.iter().enumerate() {
            let Some([from, label, to]) = a.as_array().map(Vec::as_slice) else {
                return Err(format!(
                    "`counterexample.action[{k}]` is not [from, label, to]"
                ));
            };
            if k + 1 == count {
                // A liveness counterexample's loop: from the last state back
                // to a listed one (itself, for stuttering). The ending
                // carries it; it must still connect listed states.
                let back = to
                    .get(0)
                    .and_then(J::as_u64)
                    .and_then(|i| usize::try_from(i).ok())
                    .filter(|&i| i >= 1 && i <= count);
                if !state_at(from, k) || !back.is_some_and(|i| state_at(to, i - 1)) {
                    return Err(format!(
                        "`counterexample.action[{k}]` is not a loop from the last state to a listed one"
                    ));
                }
                continue;
            }
            // TLC repeats the states around each step; they must be the
            // listed ones, or the document contradicts itself.
            for (end, at) in [(from, k), (to, k + 1)] {
                if !state_at(end, at) {
                    return Err(format!(
                        "`counterexample.action[{k}]` does not connect states {} and {}",
                        k + 1,
                        k + 2
                    ));
                }
            }
            labels[k + 1] = Some(Label {
                name: label
                    .get("name")
                    .and_then(J::as_str)
                    .ok_or_else(|| format!("`counterexample.action[{k}]` has no name"))?
                    .to_owned(),
                location: label.get("location").map(|l| match l {
                    J::Object(m) => format!(
                        "line {}, col {} to line {}, col {} of module {}",
                        m.get("beginLine").unwrap_or(&J::Null),
                        m.get("beginColumn").unwrap_or(&J::Null),
                        m.get("endLine").unwrap_or(&J::Null),
                        m.get("endColumn").unwrap_or(&J::Null),
                        m.get("module").and_then(J::as_str).unwrap_or("?"),
                    ),
                    other => other.to_string(),
                }),
            });
        }
        if !actions.is_empty() && actions.len() + 1 != count && actions.len() != count {
            return Err(format!(
                "{} states but {} steps",
                states.len(),
                actions.len()
            ));
        }
        Ok(Self {
            variables,
            states,
            labels,
            ending: None,
            length: None,
            source: Source::Tlc,
            properties: Vec::new(),
        })
    }

    /// Writes the document in dive's format. A document read from TLC's
    /// format keeps TLC's lossy values.
    #[must_use]
    pub fn to_json(&self) -> J {
        let states: Vec<J> = self
            .states
            .iter()
            .zip(&self.labels)
            .map(|(s, l)| {
                json!({
                    "action": l.as_ref().map(|l| json!({"name": l.name, "location": l.location})),
                    "values": s,
                })
            })
            .collect();
        let version = if matches!(
            self.ending,
            Some(Ending::PartialNext { .. } | Ending::PartialInit { .. })
        ) {
            PARTIAL_STATE_VERSION
        } else if matches!(self.ending, Some(Ending::CandidateStateError { .. })) {
            CANDIDATE_ERROR_VERSION
        } else if matches!(self.ending, Some(Ending::ViewSourceError { .. })) {
            VIEW_SOURCE_ERROR_VERSION
        } else if matches!(self.ending, Some(Ending::TemporalSourceError { .. })) {
            TEMPORAL_SOURCE_ERROR_VERSION
        } else if matches!(self.ending, Some(Ending::InvariantError { .. })) {
            INVARIANT_ERROR_VERSION
        } else {
            VERSION
        };
        let mut j = json!({
            "format": FORMAT,
            "version": version,
            "variables": self.variables,
            "states": states,
            "ending": self.ending.as_ref().map(Ending::to_json),
        });
        if let Some(n) = self.length {
            j["length"] = J::from(n);
        }
        if !self.properties.is_empty() {
            j["properties"] = J::from(self.properties.clone());
        }
        j
    }
}

fn strings(j: Option<&J>) -> Option<Vec<String>> {
    j?.as_array()?
        .iter()
        .map(|v| v.as_str().map(str::to_owned))
        .collect()
}

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

    #[test]
    fn reads_tlc_dump_trace_json() -> Result<(), String> {
        let text = r#"{"counterexample":{"action":[[[1,{"x":0}],{"name":"Next","location":{"beginLine":9,"beginColumn":9,"endLine":9,"endColumn":18,"module":"M"}},[2,{"x":1}]]],"state":[[1,{"x":0}],[2,{"x":1}]]},"vars":["x"]}"#;
        let d = TraceDoc::parse(text)?;
        assert_eq!(d.source, Source::Tlc);
        assert_eq!(d.states.len(), 2);
        assert_eq!(d.labels[0], None);
        let l = d.labels[1].clone().ok_or("label")?;
        assert_eq!(l.name, "Next");
        assert_eq!(
            l.location.as_deref(),
            Some("line 9, col 9 to line 9, col 18 of module M")
        );
        Ok(())
    }

    #[test]
    fn rejects_a_tlc_document_whose_steps_do_not_connect() {
        let text = r#"{"counterexample":{"action":[[[1,{"x":0}],{"name":"Next"},[2,{"x":5}]]],"state":[[1,{"x":0}],[2,{"x":1}]]},"vars":["x"]}"#;
        assert!(TraceDoc::parse(text).is_err());
    }

    #[test]
    fn dive_format_round_trips() -> Result<(), String> {
        let text = r#"{"format":"dive-trace","version":1,"variables":["x"],
            "states":[{"action":null,"values":{"x":0}},{"action":{"name":"A","location":null},"values":{"x":1}}],
            "ending":{"kind":"invariant","name":"Inv"},"length":2}"#;
        let d = TraceDoc::parse(text)?;
        assert_eq!(d.ending, Some(Ending::Invariant("Inv".to_owned())));
        assert_eq!(TraceDoc::from_json(&d.to_json())?, d);
        // Embedded in a `dive check --output json` document.
        let wrapped = json!({"schema_version": 1, "counterexample": d.to_json()});
        assert_eq!(TraceDoc::from_json(&wrapped)?, d);
        Ok(())
    }

    #[test]
    fn parses_command_line_endings() -> Result<(), String> {
        assert_eq!(
            Ending::parse("invariant:Inv")?,
            Ending::Invariant("Inv".into())
        );
        assert_eq!(Ending::parse("deadlock")?, Ending::Deadlock);
        assert_eq!(Ending::parse("lasso:2")?, Ending::Lasso { back_to: 2 });
        assert!(Ending::parse("invariant").is_err());
        assert!(Ending::parse("nonsense").is_err());
        Ok(())
    }
}