tla-ts 0.0.10-dev.3a85c3a9e → 0.0.10-dev.45c0eaef5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (260) hide show
  1. package/dist/compile.cjs +3 -3
  2. package/dist/compile.js +1 -1
  3. package/dist/deciders.cjs +36 -36
  4. package/dist/deciders.js +53 -53
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.d.cts +18 -4
  7. package/dist/index.d.ts +18 -4
  8. package/dist/index.js +1 -1
  9. package/dist/parallel-worker.cjs +1 -1
  10. package/dist/parallel-worker.js +1 -1
  11. package/dist/prove-worker.cjs +1 -1
  12. package/dist/prove-worker.js +1 -1
  13. package/dist/prove.cjs +56 -56
  14. package/dist/prove.js +79 -79
  15. package/dist/run.cjs +40 -44
  16. package/dist/run.js +42 -46
  17. package/dist/tlapm.cjs +1 -1
  18. package/dist/tlapm.js +2 -2
  19. package/dist/transfer.cjs +97 -92
  20. package/dist/transfer.js +97 -92
  21. package/dist/worker.cjs +7 -7
  22. package/dist/worker.js +7 -7
  23. package/package.json +1 -1
  24. package/src/ast.ts +31 -3
  25. package/src/bags.ts +50 -29
  26. package/src/builtins.ts +4 -3
  27. package/src/check-failure.ts +13 -11
  28. package/src/check-trace.ts +146 -107
  29. package/src/check.ts +535 -281
  30. package/src/cli/runtime-invariants.ts +20 -56
  31. package/src/cli/tlc-arguments.ts +2 -2
  32. package/src/cli/tlc-output.ts +21 -7
  33. package/src/cli/tlc.ts +31 -11
  34. package/src/cli/xml-exporter.ts +1 -1
  35. package/src/codegen.ts +23 -10
  36. package/src/coverage.ts +255 -18
  37. package/src/dependencies.ts +68 -15
  38. package/src/dfid.ts +101 -36
  39. package/src/environment.ts +131 -41
  40. package/src/errors.ts +7 -0
  41. package/src/evaluate.ts +424 -135
  42. package/src/exit-codes.ts +28 -13
  43. package/src/instances.ts +135 -11
  44. package/src/java-hash.ts +14 -0
  45. package/src/java-overrides.ts +2 -2
  46. package/src/levels.ts +675 -236
  47. package/src/lexer.ts +12 -2
  48. package/src/liveness-checker.ts +204 -62
  49. package/src/liveness.ts +55 -10
  50. package/src/obligations/index.ts +1 -1
  51. package/src/obligations/normalize.ts +1 -4
  52. package/src/obligations/printer.ts +5 -5
  53. package/src/obligations/source.ts +2 -0
  54. package/src/parallel-worker.ts +8 -2
  55. package/src/parallel.ts +5 -0
  56. package/src/parser.ts +180 -149
  57. package/src/prover/isabelle/isar/attrib.ts +4 -4
  58. package/src/prover/isabelle/isar/rule-cases.ts +8 -6
  59. package/src/prover/isabelle/provers/clasimp.ts +1 -1
  60. package/src/prover/isabelle/provers/hypsubst.ts +2 -2
  61. package/src/prover/isabelle/pure/rewriter.ts +3 -3
  62. package/src/prover/isabelle/pure/term.ts +3 -3
  63. package/src/prover/prep/md5.ts +26 -29
  64. package/src/prover/smt/rewrite.ts +2 -7
  65. package/src/prover/smt/simplify.ts +1 -1
  66. package/src/prover/smt/solver/arith-rewriter.ts +11 -3
  67. package/src/prover/smt/solver/array-rewriter.ts +12 -2
  68. package/src/prover/smt/solver/asserted-formulas.ts +171 -58
  69. package/src/prover/smt/solver/ast-lt.ts +1 -1
  70. package/src/prover/smt/solver/ast.ts +66 -14
  71. package/src/prover/smt/solver/auf-solver.ts +23 -12
  72. package/src/prover/smt/solver/bit-blast-tactic.ts +27 -1
  73. package/src/prover/smt/solver/blast-term-ite.ts +47 -0
  74. package/src/prover/smt/solver/bound-simplifier.ts +11 -13
  75. package/src/prover/smt/solver/bv-decl-plugin.ts +13 -10
  76. package/src/prover/smt/solver/bv-rewriter.ts +1 -1
  77. package/src/prover/smt/solver/card2bv.ts +35 -18
  78. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +39 -24
  79. package/src/prover/smt/solver/context.ts +84 -15
  80. package/src/prover/smt/solver/ctx-simplify.ts +1 -2
  81. package/src/prover/smt/solver/datatype-decl-plugin.ts +15 -7
  82. package/src/prover/smt/solver/dependent-expr-state.ts +28 -16
  83. package/src/prover/smt/solver/diff-neq.ts +1 -2
  84. package/src/prover/smt/solver/dt2bv-tactic.ts +57 -21
  85. package/src/prover/smt/solver/elim-bounds.ts +89 -0
  86. package/src/prover/smt/solver/elim-term-ite-tactic.ts +48 -0
  87. package/src/prover/smt/solver/elim-uncnstr.ts +5 -8
  88. package/src/prover/smt/solver/euf/arith-internalize.ts +1 -1
  89. package/src/prover/smt/solver/euf/array-internalize.ts +1 -1
  90. package/src/prover/smt/solver/euf/bv-internalize.ts +1 -1
  91. package/src/prover/smt/solver/euf/egraph.ts +4 -10
  92. package/src/prover/smt/solver/euf/euf-solver.ts +1 -2
  93. package/src/prover/smt/solver/euf/mam.ts +1 -5
  94. package/src/prover/smt/solver/euf/q-ematch.ts +1 -2
  95. package/src/prover/smt/solver/euf/th-solver.ts +0 -7
  96. package/src/prover/smt/solver/expr2polynomial.ts +204 -79
  97. package/src/prover/smt/solver/factor.ts +36 -14
  98. package/src/prover/smt/solver/fd-solver.ts +608 -139
  99. package/src/prover/smt/solver/fix-dl-var.ts +1 -2
  100. package/src/prover/smt/solver/fpa-rewriter.ts +1 -2
  101. package/src/prover/smt/solver/fpa2bv-converter.ts +3 -1
  102. package/src/prover/smt/solver/fpa2bv-rewriter.ts +1 -0
  103. package/src/prover/smt/solver/goal.ts +6 -3
  104. package/src/prover/smt/solver/goal2nlsat.ts +57 -30
  105. package/src/prover/smt/solver/hashtable.ts +4 -0
  106. package/src/prover/smt/solver/internalizer.ts +1 -1
  107. package/src/prover/smt/solver/logic-tactics.ts +15 -5
  108. package/src/prover/smt/solver/lp/containers.ts +7 -1
  109. package/src/prover/smt/solver/lp/core-solver.ts +12 -8
  110. package/src/prover/smt/solver/lp/cross-nested.ts +1 -3
  111. package/src/prover/smt/solver/lp/lar-solver.ts +1 -1
  112. package/src/prover/smt/solver/lp/lp-settings.ts +6 -2
  113. package/src/prover/smt/solver/lp/nex-creator.ts +3 -2
  114. package/src/prover/smt/solver/lp/nex.ts +2 -1
  115. package/src/prover/smt/solver/lp/nla-basics.ts +46 -1
  116. package/src/prover/smt/solver/lp/nla-core.ts +26 -6
  117. package/src/prover/smt/solver/lp/nla-grobner.ts +158 -81
  118. package/src/prover/smt/solver/lp/nra-solver.ts +138 -95
  119. package/src/prover/smt/solver/lp/pdd-interval.ts +6 -2
  120. package/src/prover/smt/solver/lp/pdd-simplifier.ts +60 -20
  121. package/src/prover/smt/solver/lp/pdd-solver.ts +72 -39
  122. package/src/prover/smt/solver/lp/pdd.ts +725 -290
  123. package/src/prover/smt/solver/lp/union-find.ts +1 -1
  124. package/src/prover/smt/solver/mam-compiler.ts +1 -1
  125. package/src/prover/smt/solver/maxcore.ts +2 -1
  126. package/src/prover/smt/solver/maxsmt-base.ts +1 -0
  127. package/src/prover/smt/solver/model-based-opt.ts +1 -1
  128. package/src/prover/smt/solver/model-checker.ts +1 -1
  129. package/src/prover/smt/solver/model-evaluator.ts +2 -0
  130. package/src/prover/smt/solver/model-generator.ts +85 -43
  131. package/src/prover/smt/solver/mpf.ts +2 -4
  132. package/src/prover/smt/solver/mus.ts +2 -3
  133. package/src/prover/smt/solver/muz/dl-context.ts +22 -44
  134. package/src/prover/smt/solver/muz/dl-mk-coi-filter.ts +1 -1
  135. package/src/prover/smt/solver/muz/dl-mk-slice.ts +3 -3
  136. package/src/prover/smt/solver/muz/dl-rule.ts +8 -9
  137. package/src/prover/smt/solver/muz/hnf.ts +2 -2
  138. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +1 -1
  139. package/src/prover/smt/solver/muz/horn-tactic.ts +15 -2
  140. package/src/prover/smt/solver/muz/rule-properties.ts +22 -0
  141. package/src/prover/smt/solver/muz/spacer-context.ts +2 -4
  142. package/src/prover/smt/solver/muz/spacer-pdr.ts +1 -0
  143. package/src/prover/smt/solver/muz/spacer-prop-solver.ts +1 -1
  144. package/src/prover/smt/solver/nlqsat.ts +1 -1
  145. package/src/prover/smt/solver/nlsat/algebraic.ts +196 -92
  146. package/src/prover/smt/solver/nlsat/atoms.ts +52 -33
  147. package/src/prover/smt/solver/nlsat/explain.ts +375 -217
  148. package/src/prover/smt/solver/nlsat/levelwise.ts +460 -240
  149. package/src/prover/smt/solver/nlsat/polynomial.ts +2366 -681
  150. package/src/prover/smt/solver/nlsat/solver.ts +74 -71
  151. package/src/prover/smt/solver/nlsat/transcendentals.ts +41 -17
  152. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +8 -4
  153. package/src/prover/smt/solver/nlsat/upolynomial.ts +41 -18
  154. package/src/prover/smt/solver/nlsat-tactic.ts +1 -1
  155. package/src/prover/smt/solver/nnf.ts +6 -2
  156. package/src/prover/smt/solver/opt-context.ts +21 -7
  157. package/src/prover/smt/solver/opt-nlsat.ts +29 -18
  158. package/src/prover/smt/solver/opt-pareto.ts +19 -0
  159. package/src/prover/smt/solver/opt-preprocess.ts +1 -1
  160. package/src/prover/smt/solver/opt-solver.ts +10 -6
  161. package/src/prover/smt/solver/optsmt.ts +1 -1
  162. package/src/prover/smt/solver/parallel-tactic.ts +1 -1
  163. package/src/prover/smt/solver/pb-rewriter.ts +1 -4
  164. package/src/prover/smt/solver/poly-rewriter.ts +75 -18
  165. package/src/prover/smt/solver/probes.ts +88 -23
  166. package/src/prover/smt/solver/proto-model.ts +8 -8
  167. package/src/prover/smt/solver/push-app-ite.ts +37 -0
  168. package/src/prover/smt/solver/qe-arith-plugin.ts +2 -4
  169. package/src/prover/smt/solver/qe-lite.ts +2 -2
  170. package/src/prover/smt/solver/qe.ts +3 -2
  171. package/src/prover/smt/solver/qsat.ts +23 -8
  172. package/src/prover/smt/solver/quantifier-manager.ts +14 -9
  173. package/src/prover/smt/solver/recfun-decl-plugin.ts +2 -1
  174. package/src/prover/smt/solver/rewriter-tpl.ts +7 -6
  175. package/src/prover/smt/solver/rewriter.ts +31 -25
  176. package/src/prover/smt/solver/rlimit.ts +20 -3
  177. package/src/prover/smt/solver/sat/config.ts +1 -1
  178. package/src/prover/smt/solver/sat/goal2sat.ts +65 -12
  179. package/src/prover/smt/solver/sat/inc-sat-solver.ts +129 -43
  180. package/src/prover/smt/solver/sat/model-converter.ts +1 -1
  181. package/src/prover/smt/solver/sat/pb-constraint.ts +7 -0
  182. package/src/prover/smt/solver/sat/pb-solver.ts +26 -7
  183. package/src/prover/smt/solver/sat/sat-tactic.ts +17 -7
  184. package/src/prover/smt/solver/sat/sat2goal.ts +72 -48
  185. package/src/prover/smt/solver/sat/simplifier.ts +1 -1
  186. package/src/prover/smt/solver/sat/solver.ts +27 -47
  187. package/src/prover/smt/solver/seq-axioms.ts +20 -35
  188. package/src/prover/smt/solver/seq-decl-plugin.ts +1 -1
  189. package/src/prover/smt/solver/seq-derive.ts +4 -7
  190. package/src/prover/smt/solver/seq-eq-solver.ts +2 -2
  191. package/src/prover/smt/solver/seq-monadic.ts +7 -5
  192. package/src/prover/smt/solver/seq-re-rewriter.ts +2 -1
  193. package/src/prover/smt/solver/seq-re-util.ts +1 -1
  194. package/src/prover/smt/solver/seq-regex-bisim.ts +1 -1
  195. package/src/prover/smt/solver/seq-regex-live.ts +2 -2
  196. package/src/prover/smt/solver/seq-rewriter.ts +31 -29
  197. package/src/prover/smt/solver/seq-skolem.ts +0 -23
  198. package/src/prover/smt/solver/seq-view-witness.ts +4 -4
  199. package/src/prover/smt/solver/smt-consequences.ts +1 -1
  200. package/src/prover/smt/solver/smt-kernel.ts +48 -7
  201. package/src/prover/smt/solver/smt-setup.ts +106 -13
  202. package/src/prover/smt/solver/smtlib-parser.ts +589 -224
  203. package/src/prover/smt/solver/smtlib-script.ts +713 -210
  204. package/src/prover/smt/solver/solve-eqs.ts +36 -37
  205. package/src/prover/smt/solver/solver.ts +18 -3
  206. package/src/prover/smt/solver/tactic.ts +350 -195
  207. package/src/prover/smt/solver/theory-bv.ts +13 -3
  208. package/src/prover/smt/solver/theory-fpa.ts +1 -1
  209. package/src/prover/smt/solver/theory-lra-final-check.ts +1 -0
  210. package/src/prover/smt/solver/theory-lra-internalize.ts +10 -0
  211. package/src/prover/smt/solver/theory-lra-propagate.ts +11 -3
  212. package/src/prover/smt/solver/theory-lra-state.ts +1 -1
  213. package/src/prover/smt/solver/theory-lra.ts +1 -1
  214. package/src/prover/smt/solver/theory-pb.ts +24 -7
  215. package/src/prover/smt/solver/theory-seq-solve.ts +1 -1
  216. package/src/prover/smt/solver/theory-seq-state.ts +2 -21
  217. package/src/prover/smt/solver/theory-without-terms.ts +24 -0
  218. package/src/prover/smt/solver/tseitin-cnf.ts +1 -0
  219. package/src/prover/tlapm/cache.ts +8 -8
  220. package/src/prover/zenon/equality-rules.ts +24 -0
  221. package/src/prover/zenon/expr.ts +21 -0
  222. package/src/prover/zenon/index-table.ts +7 -2
  223. package/src/prover/zenon/isar-case.ts +1 -1
  224. package/src/prover/zenon/isar.ts +2 -2
  225. package/src/prover/zenon/phrase.ts +1 -1
  226. package/src/prover/zenon/rules.ts +2 -1
  227. package/src/resolve.ts +1274 -258
  228. package/src/runtime.ts +25 -2
  229. package/src/sany/builtins.ts +10 -10
  230. package/src/sany/generation.ts +5 -15
  231. package/src/sany/generator-def-entries.ts +123 -36
  232. package/src/sany/generator-definitions.ts +5 -3
  233. package/src/sany/generator-expressions.ts +60 -37
  234. package/src/sany/generator-proofs.ts +18 -12
  235. package/src/sany/generator.ts +12 -6
  236. package/src/sany/lexer.ts +15 -7
  237. package/src/sany/modules.ts +4 -2
  238. package/src/sany/nodes.ts +1 -1
  239. package/src/sany/selectors.ts +11 -6
  240. package/src/sany/xml.ts +2 -3
  241. package/src/search.ts +348 -153
  242. package/src/simulate.ts +250 -185
  243. package/src/spec-description.ts +15 -7
  244. package/src/standard-definitions.ts +5 -0
  245. package/src/standard-modules.ts +56 -22
  246. package/src/subexpressions.ts +564 -138
  247. package/src/successors.ts +50 -20
  248. package/src/symmetry.ts +2 -1
  249. package/src/tlc/jar-data.ts +10 -0
  250. package/src/tlc/messages.ts +3 -3
  251. package/src/tlc/order.ts +14 -3
  252. package/src/tlc/random.ts +2 -1
  253. package/src/tlc/replay.ts +147 -46
  254. package/src/tlc/tlc-operators.ts +10 -8
  255. package/src/tlc/tlcext-operators.ts +87 -26
  256. package/src/tlc/trace-spec.ts +11 -25
  257. package/src/trace-liveness.ts +529 -0
  258. package/src/typed-tier.ts +52 -31
  259. package/src/typescript/types.ts +2 -2
  260. package/src/values.ts +150 -79
package/src/check.ts CHANGED
@@ -1,11 +1,9 @@
1
1
  import type { Expression } from "./ast";
2
2
  import { parseConfig, type ModelConfig } from "./config";
3
3
  import {
4
- addCoverageRelation,
5
- buildCoverage,
6
4
  countCoverageVariables,
7
5
  createCoverage,
8
- getCoverageLabel,
6
+ createCoverageEnvironment,
9
7
  getCoverageReport,
10
8
  type CoverageReport,
11
9
  } from "./coverage";
@@ -25,8 +23,8 @@ import {
25
23
  describeRange,
26
24
  getDefinition,
27
25
  type CallStack,
28
- type Environment,
29
26
  type FingerprintFailure,
27
+ type State,
30
28
  } from "./evaluate";
31
29
  import { EXIT_STATUS, setExitCode, withLivenessExitCode } from "./exit-codes";
32
30
  import {
@@ -37,6 +35,7 @@ import {
37
35
  } from "./check-failure";
38
36
  import {
39
37
  createTraceBuilder,
38
+ NEXT_RECOVERY_FAILURE,
40
39
  type Behavior,
41
40
  type SearchPosition,
42
41
  type TracedStep,
@@ -47,6 +46,7 @@ import {
47
46
  getStateHash,
48
47
  isSameState,
49
48
  markSeenState,
49
+ type StateTable,
50
50
  } from "./fingerprints";
51
51
  import type { JavaOverride } from "./java-overrides";
52
52
  import {
@@ -56,6 +56,7 @@ import {
56
56
  type LiveSuccessor,
57
57
  } from "./liveness-checker";
58
58
  import {
59
+ addActionCoverage,
59
60
  createCheckEnvironment,
60
61
  createMissingOperatorError,
61
62
  createSearch,
@@ -63,7 +64,10 @@ import {
63
64
  findAssumptionViolation,
64
65
  reportInitialStatesProgress,
65
66
  reportStartup,
67
+ STOP_WALK,
68
+ walkCoveredSuccessors,
66
69
  withNextStateExitCode,
70
+ type CoveredAction,
67
71
  } from "./search";
68
72
  import {
69
73
  getActionLabel,
@@ -81,6 +85,7 @@ import {
81
85
  type StateWriter,
82
86
  } from "./state-graph";
83
87
  import {
88
+ createIncompleteSuccessorError,
84
89
  forEachInitialState,
85
90
  forEachSuccessor,
86
91
  getInitialStates,
@@ -100,14 +105,13 @@ import {
100
105
  import { createTautologyError } from "./liveness";
101
106
  import { KEY_SEPARATOR } from "./resolve";
102
107
  import { writeTraceSpec } from "./tlc/trace-spec";
103
- import {
104
- getPrimedRanges,
105
- replayInitialStates,
106
- replaySuccessors,
107
- walkSuccessors,
108
- } from "./tlc/replay";
108
+ import { replayInitialStates, replaySuccessors, walkSuccessors } from "./tlc/replay";
109
109
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc/summary";
110
- import { createActionRecord, createCounterExample } from "./tlc/tlcext-operators";
110
+ import {
111
+ createActionRecord,
112
+ createCounterExample,
113
+ type CounterExampleLoop,
114
+ } from "./tlc/tlcext-operators";
111
115
  import type { TlcVersion } from "./tlc/version";
112
116
  import { runTypedSearch, type TypedResult } from "./typed-tier";
113
117
  import {
@@ -205,7 +209,7 @@ export type CheckProgress =
205
209
  branches: number;
206
210
  /** Whether TLC checks the complete state graph. */
207
211
  isComplete: boolean;
208
- /** How many states of the graph each branch has. */
212
+ /** How many states the graphs of all branches have together. */
209
213
  states: number;
210
214
  statistics: SearchStatistics;
211
215
  }
@@ -266,6 +270,11 @@ export interface Postcondition {
266
270
  counts?: string;
267
271
  }
268
272
 
273
+ export interface TraceFailure extends FailureMessage {
274
+ /** What the spec prints as TLC rebuilds the step it then fails to print. */
275
+ output: OutputLine[];
276
+ }
277
+
269
278
  /** An evaluation that failed during the search, with the behavior up to the state TLC was working on. */
270
279
  export interface EvaluationFailure {
271
280
  code: number;
@@ -282,7 +291,7 @@ export interface EvaluationFailure {
282
291
  /** The FingerprintException the replay raises, which TLC reports in place of the call stack. */
283
292
  fingerprint?: FingerprintFailure;
284
293
  /** How TLC reports failing again as it prints the trace, since it can't fingerprint the state. */
285
- traceFailure?: FailureMessage;
294
+ traceFailure?: TraceFailure;
286
295
  /** A POSTCONDITION that is false or fails after the trace, which TLC checks as it prints one. */
287
296
  postcondition?: Postcondition;
288
297
  /** Whether TLC stops before it prints the statistics, as it does for an illegal initial state. */
@@ -308,7 +317,7 @@ export interface CheckResult {
308
317
  outDegrees: number[] | undefined;
309
318
  /** The smallest distance between two fingerprints, when TLC estimates a collision from them. */
310
319
  fingerprintDistance: bigint | undefined;
311
- /** A temporal property TLC finds violated as it adds a deadlocked state, reported after. */
320
+ /** A temporal property TLC finds violated as it adds the state it stopped at to the behavior graph, reported after. */
312
321
  additionalViolation?: Violation;
313
322
  /** Where TLC's worker fails to add the state to the behavior graph after it reports a violation. */
314
323
  liveCallStack?: Expression[];
@@ -318,21 +327,35 @@ export interface CheckResult {
318
327
  coverage?: CoverageReport;
319
328
  }
320
329
 
321
- interface CoveredAction extends SpecAction {
322
- node: number;
323
- }
324
-
325
330
  interface ReportedViolation extends Omit<Violation, "loopStart"> {
326
331
  loopStart?: number;
327
332
  }
328
333
 
334
+ interface CounterExampleOptions {
335
+ isConsole: boolean;
336
+ }
337
+
329
338
  const appendTraceOutput = <Traced extends Behavior>(behavior: Traced, lines: OutputLine[]) => ({
330
339
  ...behavior,
331
340
  traceOutput: [...(behavior.traceOutput ?? []), ...lines],
332
341
  });
333
342
 
343
+ const toUnexpectedError = (error: TlaEvaluationError) =>
344
+ new TlaEvaluationError(
345
+ `${isEvalException(error) ? UNEXPECTED_EVAL_EXCEPTION : UNEXPECTED_EXCEPTION}${error.message}`,
346
+ );
347
+
348
+ const getTraceFailure = (error: TlaEvaluationError, output: OutputLine[]): TraceFailure => ({
349
+ ...getFailureMessage(
350
+ isEvalException(error)
351
+ ? new TlaEvaluationError(`${UNEXPECTED_EVAL_EXCEPTION}${error.message}`)
352
+ : error,
353
+ true,
354
+ ),
355
+ output,
356
+ });
357
+
334
358
  const STOP_REPLAY = new Error("The replay stopped");
335
- const STOP_WALK = new Error("The walk stopped");
336
359
 
337
360
  export const checkSequentially = (options: CheckOptions): CheckResult => {
338
361
  const stateWriter =
@@ -379,14 +402,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
379
402
  options.coverage === undefined
380
403
  ? undefined
381
404
  : createCoverage(specification.environment.variables.length);
382
- const environment: Environment = coverage
383
- ? {
384
- ...specification.environment,
385
- evaluators: new WeakMap(),
386
- entryEvaluators: new WeakMap(),
387
- definitionEvaluators: new WeakMap(),
388
- coverage,
389
- }
405
+ const environment = coverage
406
+ ? createCoverageEnvironment(specification.environment, coverage)
390
407
  : specification.environment;
391
408
  const runtime = environment.runtime;
392
409
  const is174 = runtime.version === "1.7.4";
@@ -414,6 +431,15 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
414
431
  key.startsWith(`${name}${KEY_SEPARATOR}`),
415
432
  ),
416
433
  });
434
+ const getCoverage = () =>
435
+ coverage?.relations.some((relation) => relation.kind === "next")
436
+ ? getCoverageReport(
437
+ coverage,
438
+ environment,
439
+ specification.variableLocations,
440
+ search?.getTlcOrder() ?? [],
441
+ )
442
+ : undefined;
417
443
  const createResult = (
418
444
  status: CheckStatus,
419
445
  violation?: ReportedViolation,
@@ -434,14 +460,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
434
460
  initialStates: computedInitialStates,
435
461
  outDegrees: undefined,
436
462
  fingerprintDistance: undefined,
437
- coverage: coverage?.relations.some((relation) => relation.kind === "next")
438
- ? getCoverageReport(
439
- coverage,
440
- environment,
441
- specification.variableLocations,
442
- search?.getTlcOrder() ?? [],
443
- )
444
- : undefined,
463
+ coverage: getCoverage(),
445
464
  ...(traceSpec !== undefined && { traceSpec }),
446
465
  };
447
466
  };
@@ -465,7 +484,12 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
465
484
  : getFingerprintDistance(runtime.distinctStates, runtime.generatedStates, (visit) =>
466
485
  visit(
467
486
  search
468
- ? search.getStoredFingerprints(states, fingerprintStates)
487
+ ? search.getStoredFingerprints(
488
+ exploredStates.length === 0 ? states : states.concat(exploredStates),
489
+ exploredStates.length === 0
490
+ ? fingerprintStates
491
+ : fingerprintStates.concat(exploredFingerprintStates),
492
+ )
469
493
  : BigInt64Array.from(states, runtime.getFingerprint),
470
494
  ),
471
495
  ),
@@ -478,6 +502,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
478
502
  () => created.order.getDeclarationOrder("variable"),
479
503
  options.onProgress,
480
504
  specification.moduleOperators,
505
+ specification.runtimeInvariants,
481
506
  );
482
507
  const findViolatedAssumption = () =>
483
508
  findAssumptionViolation(specification.assumptions, environment);
@@ -499,19 +524,24 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
499
524
  specification.moduleOperators.some((operator) => operator.kind === "postcondition");
500
525
  const tracedSteps = new WeakMap<TraceStep, TracedStep>();
501
526
  const getStepState = (step: TraceStep) => tracedSteps.get(step)?.state ?? step.state;
527
+ // TLC's Worker#doPostCondition and LiveCheck bind CounterExample to the alias of each state, while its initial states and lassos keep the states.
528
+ const getStepAlias = (step: TraceStep) => tracedSteps.get(step)?.alias ?? step.state;
502
529
  const getStepAction = (step: TraceStep) => {
503
530
  const action = tracedSteps.get(step)?.action;
504
531
  return action ? toActionValue(action) : createActionRecord(step.action);
505
532
  };
506
533
  const checkTracePostconditions = (
507
534
  trace: TraceStep[],
508
- loop: { start: number; action: Value } | undefined,
535
+ loop: CounterExampleLoop | undefined,
536
+ getState: (step: TraceStep) => Record<string, Value>,
537
+ isConsole = true,
509
538
  ) => {
510
539
  if (hasPostconditions) {
511
540
  runtime.counterExample = createCounterExample(
512
- trace.map(getStepState),
541
+ trace.map(getState),
513
542
  trace.slice(1).map(getStepAction),
514
543
  loop,
544
+ isConsole,
515
545
  );
516
546
  }
517
547
  const unwitnessed = search.findUnwitnessedPossible();
@@ -523,12 +553,14 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
523
553
  const reportViolation = (
524
554
  status: CheckStatus,
525
555
  violation: ReportedViolation,
556
+ getState = getStepAlias,
526
557
  getLoopAction?: () => Value,
527
558
  ) => {
528
559
  const start = violation.loopStart;
529
560
  const checked = checkTracePostconditions(
530
561
  violation.trace,
531
562
  start === undefined || !getLoopAction ? undefined : { start, action: getLoopAction() },
563
+ getState,
532
564
  );
533
565
  return createResult(status, {
534
566
  ...violation,
@@ -554,61 +586,43 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
554
586
  const getFingerprintState = search.getFingerprintState;
555
587
  // Tool's constructor splits the next-state relation into actions before TLC checks anything.
556
588
  const nextActions = getDescription().actions;
557
- runtime.getSuccessorAction = (state, next) =>
558
- nextActions.find((action) =>
559
- getSuccessors(action.expression, state, environment, action.scope).some((successor) =>
560
- successor.state.every((value, index) => isSameValue(value, next[index])),
561
- ),
562
- );
563
- const addCoverageRelations = (kind: "init" | "next", actions: SpecAction[]) =>
564
- actions.map((action): CoveredAction => ({
565
- ...action,
566
- node: coverage
567
- ? addCoverageRelation(
568
- coverage,
569
- kind,
570
- getCoverageLabel(action.name, action.expression, environment),
571
- action.expression,
572
- action.scope,
573
- )
574
- : -1,
575
- }));
576
- const coverageInits = addCoverageRelations("init", coverage ? getDescription().inits : []);
577
- const coverageActions = addCoverageRelations("next", coverage ? nextActions : []);
578
- if (coverage) buildCoverage(coverage, environment, getPrimedRanges(coverageActions, environment));
579
- const walkCoveredSuccessors = (
580
- action: CoveredAction,
581
- state: Value[],
582
- onState: (successor: Value[]) => void,
583
- ) =>
589
+ const covered = coverage && addActionCoverage(coverage, environment, getDescription());
590
+ const coverageInits = covered?.inits ?? [];
591
+ const coverageActions = covered?.actions ?? [];
592
+ const hasCoveredIncompleteSuccessor = (action: CoveredAction, state: Value[]) => {
593
+ let complete = 0;
594
+ let incomplete = 0;
584
595
  walkSuccessors(
585
596
  action,
586
597
  action.node,
587
598
  state,
588
599
  environment,
589
- (successor) => {
590
- if (coverage) coverage.primary[action.node]++;
591
- onState(successor);
592
- },
593
- (partial) => {
594
- const missing = environment.variables.filter(
595
- (_variable, index) => partial[index] === undefined,
596
- );
597
- throw new TlaIncompleteSuccessorError(
598
- `Successor state is not completely specified by action ${action.name}. The following variables are not assigned: ${missing.join(", ")}`,
599
- partial,
600
- action.name,
601
- missing,
602
- );
600
+ () => complete++,
601
+ () => {
602
+ incomplete++;
603
+ return true;
603
604
  },
604
605
  );
605
- const getCoveredSuccessors = (action: CoveredAction, state: Value[]) => {
606
- const successors: Successor[] = [];
607
- walkCoveredSuccessors(action, state, (successor) =>
608
- successors.push({ state: successor, action: action.name }),
609
- );
610
- return successors;
606
+ if (coverage) coverage.primary[action.node] += complete + incomplete;
607
+ return incomplete > 0;
611
608
  };
609
+ // TLC generates the successors of each action again, which its coverage counts.
610
+ const findSuccessorAction = (state: Value[], isMatch: (successor: Successor) => boolean) =>
611
+ coverage
612
+ ? coverageActions.find((item) => {
613
+ const successors: Successor[] = [];
614
+ walkCoveredSuccessors(coverage, item, state, environment, (successor) =>
615
+ successors.push({ state: successor, action: item.name }),
616
+ );
617
+ return successors.some(isMatch);
618
+ })
619
+ : nextActions.find((item) =>
620
+ getSuccessors(item.expression, state, environment, item.scope).some(isMatch),
621
+ );
622
+ runtime.getSuccessorAction = (state, next) =>
623
+ findSuccessorAction(state, (successor) =>
624
+ successor.state.every((value, index) => isSameValue(value, next[index])),
625
+ );
612
626
  const rejectIncompleteInitialState = (partial: (Value | undefined)[]) => {
613
627
  throw setExitCode(new TlaIllegalStateError([...partial]), EXIT_STATUS.error);
614
628
  };
@@ -627,8 +641,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
627
641
  return (state: Value[], callStack: CallStack | undefined) => {
628
642
  fingerprintReplayed(state, getFingerprintState(state), callStack);
629
643
  const fingerprintState = getFingerprintState(state);
644
+ const hash = getStateHash(fingerprintState);
630
645
  const isSeen =
631
- findStateIndex(seenStates, getStateHash(fingerprintState), fingerprintState) !== -1 ||
646
+ findStateIndex(seenStates, hash, fingerprintState) !== -1 ||
647
+ isExplored(hash, fingerprintState) ||
632
648
  replayed.some((seen) => isSameState(seen, fingerprintState));
633
649
  if (isSeen) return false;
634
650
  replayed.push(fingerprintState);
@@ -641,7 +657,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
641
657
  const deferred: unknown[] = [];
642
658
  const addReplayed = createReplayedStates();
643
659
  return getReplayFailure(environment, (tracing) => {
644
- replayInitialStates(getDescription().inits, tracing, (state) => {
660
+ replayInitialStates(coverage ? coverageInits : getDescription().inits, tracing, (state) => {
645
661
  reportInitialStatesProgress(replayedCount, (progress) => capturedLines?.push(progress));
646
662
  replayedCount++;
647
663
  runtime.generatedStates = replayedCount;
@@ -652,16 +668,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
652
668
  runtime.queueSize++;
653
669
  liveness?.addInitialState(states.length, state, tracing);
654
670
  };
655
- const violation = search.checkReplayedInitialState(state, tracing, addFingerprint);
656
- if (violation) {
671
+ search.checkReplayedInitialState(state, tracing, addFingerprint, (violation) => {
657
672
  const traced = traces.toTrace([{ action: undefined, state }], []).trace[0].state;
658
673
  capturedLines?.push({
659
674
  kind: "initial-state-violation",
660
675
  ...violation,
661
676
  state: traced,
662
677
  });
663
- throw STOP_REPLAY;
664
- }
678
+ if (!options.isContinued || violation.status !== "invariant-violation") {
679
+ throw STOP_REPLAY;
680
+ }
681
+ });
665
682
  } catch (error) {
666
683
  const isFingerprintFailure =
667
684
  error instanceof TlaEvaluationError && tracing.callStack?.fingerprint !== undefined;
@@ -677,7 +694,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
677
694
  const state = states[index];
678
695
  const source = stateWriter && getGraphState(state, depths[index]);
679
696
  const addReplayed = createReplayedStates();
680
- replaySuccessors(nextActions, state, tracing, (next, action) => {
697
+ replaySuccessors(coverage ? coverageActions : nextActions, state, tracing, (next, action) => {
681
698
  const addFingerprint = () => {
682
699
  const isUnseen = addReplayed(next, tracing.callStack);
683
700
  if (source) {
@@ -703,6 +720,15 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
703
720
  isConstrained: search.isConstrained,
704
721
  });
705
722
  }
723
+ let liveState: Value[] = [];
724
+ const addIncomplete = (successor: State, action: string | undefined) => {
725
+ if (
726
+ search.satisfiesConstraints(successor, liveState) &&
727
+ search.satisfiesActionConstraints(liveState, successor)
728
+ ) {
729
+ throw createIncompleteSuccessorError(successor, action, environment);
730
+ }
731
+ };
706
732
  const liveness = withLivenessExitCode(() =>
707
733
  withUnexpectedException(() =>
708
734
  createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
@@ -710,37 +736,67 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
710
736
  (tlcFingerprints[successor.index] ??= Number(
711
737
  BigInt.asIntN(32, runtime.getFingerprint(successor.state)),
712
738
  )),
713
- getSuccessors: (source, state) => {
714
- const successors: LiveSuccessor[] = [];
715
- if (spec.next === undefined) return successors;
716
- const livenessSource = current.livenessSource;
717
- current.livenessSource = source;
718
- try {
719
- forEachSuccessor(
720
- spec.next,
721
- state,
722
- environment,
723
- (successor) => {
724
- canonicalizeState(successor.state);
725
- const isInModel =
726
- search.satisfiesConstraints(successor.state, state) &&
727
- search.satisfiesActionConstraints(state, successor.state);
728
- if (!isInModel) return false;
729
- const fingerprintState = getFingerprintState(successor.state);
730
- const index = findStateIndex(
731
- seenStates,
732
- getStateHash(fingerprintState),
733
- fingerprintState,
739
+ forEachActionSuccessors: (source, state, onSuccessors, replay) => {
740
+ liveState = state;
741
+ let successors: LiveSuccessor[] = [];
742
+ const addSuccessor = (successor: Value[]) => {
743
+ canonicalizeState(successor);
744
+ const isInModel =
745
+ search.satisfiesConstraints(successor, state) &&
746
+ search.satisfiesActionConstraints(state, successor);
747
+ if (!isInModel) return;
748
+ const fingerprintState = getFingerprintState(successor);
749
+ const hash = getStateHash(fingerprintState);
750
+ const index = findStateIndex(seenStates, hash, fingerprintState);
751
+ successors.push({
752
+ index: index === -1 ? getPendingIndex(hash, fingerprintState) : index,
753
+ state: successor,
754
+ });
755
+ };
756
+ const visitSuccessor = (successor: Successor) => {
757
+ addSuccessor(successor.state);
758
+ return false;
759
+ };
760
+ const actionCount = coverage ? coverageActions.length : nextActions.length;
761
+ for (let position = 0; position < actionCount; position++) {
762
+ successors = [];
763
+ const livenessSource = current.livenessSource;
764
+ current.livenessSource = source;
765
+ try {
766
+ if (coverage) {
767
+ // TLC's coverage counts the successors of each action the graph generates again.
768
+ walkCoveredSuccessors(
769
+ coverage,
770
+ coverageActions[position],
771
+ state,
772
+ replay ?? environment,
773
+ addSuccessor,
774
+ addIncomplete,
734
775
  );
735
- successors.push({ index, state: successor.state });
736
- return false;
737
- },
738
- spec.scope,
739
- );
740
- } finally {
741
- current.livenessSource = livenessSource;
776
+ } else if (replay) {
777
+ const action = nextActions[position];
778
+ walkSuccessors(action, -1, state, replay, addSuccessor, (partial) => {
779
+ addIncomplete(partial, action.name);
780
+ return true;
781
+ });
782
+ } else {
783
+ const action = nextActions[position];
784
+ forEachSuccessor(
785
+ action.expression,
786
+ state,
787
+ environment,
788
+ visitSuccessor,
789
+ action.scope,
790
+ undefined,
791
+ undefined,
792
+ addIncomplete,
793
+ );
794
+ }
795
+ } finally {
796
+ current.livenessSource = livenessSource;
797
+ }
798
+ onSuccessors(successors);
742
799
  }
743
- return successors;
744
800
  },
745
801
  }),
746
802
  ),
@@ -755,13 +811,31 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
755
811
  const actions: (string | undefined)[] = [];
756
812
  const depths: number[] = [];
757
813
  const seenStates = createStateTable(fingerprintStates);
758
- const canonicalizeState = createCanonicalizer();
814
+ const exploredStates: Value[][] = [];
815
+ const exploredFingerprintStates: Value[][] = [];
816
+ let exploredTable: StateTable | undefined;
817
+ const isExplored = (hash: number, fingerprintState: Value[]) =>
818
+ exploredTable !== undefined && findStateIndex(exploredTable, hash, fingerprintState) !== -1;
819
+ const pendingFingerprintStates: Value[][] = [];
820
+ let pendingStates: StateTable | undefined;
821
+ const getPendingIndex = (hash: number, fingerprintState: Value[]) => {
822
+ pendingStates ??= createStateTable(pendingFingerprintStates);
823
+ const found = findStateIndex(pendingStates, hash, fingerprintState);
824
+ const position = found === -1 ? pendingFingerprintStates.length : found;
825
+ if (found === -1) {
826
+ markSeenState(pendingStates, hash, position);
827
+ pendingFingerprintStates.push(fingerprintState);
828
+ }
829
+ return -2 - position;
830
+ };
831
+ // TLC's states keep their own values, and coverage charges the cost model each value carries.
832
+ const canonicalizeState = coverage ? (state: Value[]) => state : createCanonicalizer();
759
833
 
760
834
  const toRecord = search.toRecord;
761
- const getSpecInitialStates = () => {
762
- if (coverage) return getCoveredInitialStates();
763
- return spec.init === undefined ? [] : getInitialStates(spec.init, environment, spec.scope);
764
- };
835
+ const getUncoveredInitialStates = () =>
836
+ spec.init === undefined ? [] : getInitialStates(spec.init, environment, spec.scope);
837
+ const getSpecInitialStates = () =>
838
+ coverage ? getCoveredInitialStates() : getUncoveredInitialStates();
765
839
  const isUnfingerprintable = (state: Value[]) => {
766
840
  try {
767
841
  return getFingerprintState(state).some((value) => getFingerprintError(value) !== undefined);
@@ -770,19 +844,27 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
770
844
  return true;
771
845
  }
772
846
  };
847
+ const checkFailedTrace = (behavior: Behavior, counterExample?: CounterExampleOptions) => {
848
+ if (!counterExample) return { behavior, postcondition: undefined };
849
+ const checked = checkTracePostconditions(
850
+ behavior.trace,
851
+ undefined,
852
+ getStepAlias,
853
+ counterExample.isConsole,
854
+ );
855
+ return {
856
+ behavior: appendTraceOutput(behavior, checked.lines),
857
+ postcondition: checked.unwitnessed ?? checked.postcondition,
858
+ };
859
+ };
773
860
  const createFailureResult = (
774
861
  failed: unknown,
775
862
  behavior: Behavior,
776
863
  failureOptions: FailureOptions = {},
864
+ postcondition?: Postcondition,
777
865
  ) => {
778
866
  const error = isStackOverflow(failed) ? new TlaStackOverflowError() : failed;
779
867
  if (!(error instanceof TlaEvaluationError)) throw error;
780
- const checked =
781
- behavior.trace.length > 0 && !failureOptions.traceFailure
782
- ? checkTracePostconditions(behavior.trace, undefined)
783
- : undefined;
784
- const postcondition = checked?.unwitnessed ?? checked?.postcondition;
785
- const traceOutput = [...(behavior.traceOutput ?? []), ...(checked?.lines ?? [])];
786
868
  return {
787
869
  ...createResult("error", undefined, {
788
870
  ...getFailureMessage(
@@ -790,7 +872,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
790
872
  failureOptions.phase !== undefined && failureOptions.phase !== "initial",
791
873
  ),
792
874
  ...behavior,
793
- ...(traceOutput.length > 0 && { traceOutput }),
794
875
  ...(postcondition && { postcondition }),
795
876
  initialState:
796
877
  failureOptions.initialState && !(error instanceof TlaModuleError)
@@ -805,29 +886,70 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
805
886
  outDegrees: failureOptions.outDegrees,
806
887
  };
807
888
  };
808
- const reportIncompleteSuccessor = (index: number, error: TlaIncompleteSuccessorError) => {
889
+ // Deviation from TLC: Worker#doPostCondition throws an ArrayIndexOutOfBoundsException at an incomplete successor, where tla-ts checks the postconditions with the successor in CounterExample.
890
+ const reportIncompleteSuccessor = (
891
+ index: number,
892
+ error: TlaIncompleteSuccessorError,
893
+ liveSuccessors: LiveSuccessor[],
894
+ ) => {
809
895
  runtime.generatedStates++;
810
- const named =
811
- nextActions.length === 1
812
- ? nextActions
813
- : nextActions.filter((item) => item.name === error.action);
814
- const action =
815
- named.length === 1
816
- ? named[0]
817
- : captureOutput(() =>
818
- named.find((item) =>
819
- hasIncompleteSuccessor(item.expression, states[index], environment, item.scope),
820
- ),
821
- ).result;
896
+ const found = captureOutput(() => {
897
+ try {
898
+ return {
899
+ action: coverage
900
+ ? coverageActions.find((item) => hasCoveredIncompleteSuccessor(item, states[index]))
901
+ : nextActions.find((item) =>
902
+ hasIncompleteSuccessor(item.expression, states[index], environment, item.scope),
903
+ ),
904
+ failed: undefined,
905
+ };
906
+ } catch (failed) {
907
+ if (!(failed instanceof TlaEvaluationError)) throw failed;
908
+ return { action: undefined, failed };
909
+ }
910
+ });
911
+ const action = found.result.action;
912
+ const traceFailure = found.result.failed && getTraceFailure(found.result.failed, found.lines);
822
913
  const message = getIncompleteSuccessorMessage(
823
914
  error.variables,
824
915
  error.action,
825
916
  nextActions.length,
826
917
  options.version,
827
918
  );
828
- const undefinedValue = createModelValue("null");
829
- const partial = error.state.map((value) => value ?? undefinedValue);
830
- const failure = createFailureResult(error, traces.getStateTrace(index));
919
+ const live = captureOutput(() => addFailedLiveState(index, liveSuccessors));
920
+ const trace = traces.getStateTrace(index, {
921
+ incomplete: error.state,
922
+ isPrintedOnly: true,
923
+ }).trace;
924
+ const checked = checkFailedTrace(
925
+ appendTraceOutput(
926
+ {
927
+ trace: traceFailure
928
+ ? trace
929
+ : [
930
+ ...trace,
931
+ traces.getIncompleteStep(
932
+ error.state,
933
+ trace.length + 1,
934
+ {
935
+ action: error.action,
936
+ label: action && getActionLabel(action, options.version),
937
+ output: found.lines,
938
+ },
939
+ action,
940
+ ),
941
+ ],
942
+ },
943
+ live.lines,
944
+ ),
945
+ { isConsole: true },
946
+ );
947
+ const failure = createFailureResult(
948
+ error,
949
+ checked.behavior,
950
+ { callStack: live.result, traceFailure },
951
+ checked.postcondition,
952
+ );
831
953
  return withOutDegrees({
832
954
  ...failure,
833
955
  failure: failure.failure && {
@@ -836,14 +958,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
836
958
  message,
837
959
  toolMessage: message,
838
960
  exitCode: EXIT_STATUS.specEvaluationFailure,
839
- trace: [
840
- ...failure.failure.trace,
841
- {
842
- action: error.action,
843
- label: action && getActionLabel(action, options.version),
844
- state: toRecord(partial),
845
- },
846
- ],
847
961
  },
848
962
  });
849
963
  };
@@ -855,7 +969,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
855
969
  };
856
970
  let unstoredFingerprint: Value[] | undefined;
857
971
  const countDistinctState = (depth: number) => {
858
- runtime.distinctStates = states.length + 1;
972
+ runtime.distinctStates = states.length + exploredStates.length + 1;
859
973
  searchDepth = Math.max(searchDepth, depth);
860
974
  runtime.diameter = Math.max(runtime.diameter, depth);
861
975
  };
@@ -896,24 +1010,35 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
896
1010
  tracedSteps,
897
1011
  captureOutput,
898
1012
  getInitialStates: getSpecInitialStates,
899
- findSuccessorAction: (state, isMatch) =>
900
- coverage
901
- ? coverageActions.find((item) => getCoveredSuccessors(item, state).some(isMatch))
902
- : nextActions.find((item) =>
903
- getSuccessors(item.expression, state, environment, item.scope).some(isMatch),
904
- ),
1013
+ getUncoveredInitialStates,
1014
+ findSuccessorAction,
905
1015
  });
906
1016
  const getPath = (index: number): Value[][] =>
907
1017
  index === -1 ? [] : [...getPath(parents[index]), states[index]];
1018
+ // TLC adds a successor's fingerprint to its set before it checks the invariants of the successor.
908
1019
  runtime.isSeen = (state) => {
909
1020
  const fingerprintState = getFingerprintState(state);
910
- return findStateIndex(seenStates, getStateHash(fingerprintState), fingerprintState) !== -1;
1021
+ const hash = getStateHash(fingerprintState);
1022
+ return (
1023
+ findStateIndex(seenStates, hash, fingerprintState) !== -1 ||
1024
+ isExplored(hash, fingerprintState) ||
1025
+ (unstoredFingerprint !== undefined && isSameState(unstoredFingerprint, fingerprintState))
1026
+ );
1027
+ };
1028
+ runtime.markExplored = (state) => {
1029
+ const fingerprintState = getFingerprintState(state);
1030
+ exploredTable ??= createStateTable(exploredFingerprintStates);
1031
+ markSeenState(exploredTable, getStateHash(fingerprintState), exploredStates.length);
1032
+ exploredStates.push(state);
1033
+ exploredFingerprintStates.push(fingerprintState);
1034
+ runtime.distinctStates++;
911
1035
  };
912
1036
  runtime.getBehavior = (state) => {
913
1037
  const index = state === current.candidate ? -1 : states.indexOf(state);
914
1038
  return index === -1 ? [...getPath(current.index), state] : getPath(index);
915
1039
  };
916
- runtime.getCurrentState = () => (current.index === -1 ? undefined : states[current.index]);
1040
+ runtime.getCurrentState = () =>
1041
+ current.rebuilt?.state ?? (current.index === -1 ? undefined : states[current.index]);
917
1042
  runtime.setLivenessSource = (index) => {
918
1043
  current.livenessSource = index ?? -1;
919
1044
  };
@@ -949,14 +1074,15 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
949
1074
  });
950
1075
 
951
1076
  const visitInitialState = (state: Value[]) => {
952
- canonicalizeState(state);
953
1077
  runtime.generatedStates++;
954
1078
  runtime.initialStates++;
955
1079
  current.candidate = state;
956
1080
  current.candidateLevel = 1;
957
- const fingerprintState = getFingerprintState(state);
958
- const hash = getStateHash(fingerprintState);
959
1081
  const isInModel = search.satisfiesConstraints(state);
1082
+ // TLC fingerprints only a state in the model, which sorts its records in place.
1083
+ if (isInModel) canonicalizeState(state);
1084
+ const fingerprintState = isInModel ? getFingerprintState(state) : state;
1085
+ const hash = isInModel ? getStateHash(fingerprintState) : 0;
960
1086
  if (isInModel) {
961
1087
  search.trackStatePossible(state);
962
1088
  fingerprintModelState(fingerprintState);
@@ -972,7 +1098,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
972
1098
  stateWriter?.writeInitialState(getGraphState(state, 1));
973
1099
  }
974
1100
  if (options.isContinued) {
975
- search.getViolatedInvariants(state).forEach((invariant) =>
1101
+ search.forEachViolatedInvariant(state, (invariant) =>
976
1102
  reportContinuedViolation("invariant-violation", {
977
1103
  name: invariant.name,
978
1104
  ...traces.toTrace([{ action: undefined, state }], []),
@@ -981,17 +1107,19 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
981
1107
  }
982
1108
  const violated = options.isContinued ? undefined : search.findViolatedInvariant(state);
983
1109
  if (violated) {
984
- return reportViolation("invariant-violation", {
985
- name: violated.name,
986
- ...traces.toTrace([{ action: undefined, state }], []),
987
- });
1110
+ return reportViolation(
1111
+ "invariant-violation",
1112
+ { name: violated.name, ...traces.toTrace([{ action: undefined, state }], []) },
1113
+ getStepState,
1114
+ );
988
1115
  }
989
1116
  const failedPredicate = search.findFailedInitialPredicate(state);
990
1117
  if (failedPredicate) {
991
- return reportViolation("liveness-violation", {
992
- name: failedPredicate.name,
993
- ...traces.toTrace([{ action: undefined, state }], []),
994
- });
1118
+ return reportViolation(
1119
+ "liveness-violation",
1120
+ { name: failedPredicate.name, ...traces.toTrace([{ action: undefined, state }], []) },
1121
+ getStepState,
1122
+ );
995
1123
  }
996
1124
  if (!isInModel) return undefined;
997
1125
  markSeenState(seenStates, hash, states.length);
@@ -1001,18 +1129,24 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1001
1129
  // Looks a successor up, where the constraints keep it in the model, as the search does before it
1002
1130
  // checks the successor.
1003
1131
  const lookUpSuccessor = (state: Value[], successor: Successor) => {
1004
- const fingerprintState = getFingerprintState(successor.state);
1005
- const hash = getStateHash(fingerprintState);
1006
- const foundIndex = findStateIndex(seenStates, hash, fingerprintState);
1007
1132
  const isStateInModel = search.satisfiesConstraints(successor.state, state);
1008
1133
  if (isStateInModel) search.trackStatePossible(successor.state);
1009
1134
  const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1135
+ const fingerprintState = isInModel ? getFingerprintState(successor.state) : successor.state;
1136
+ const hash = isInModel ? getStateHash(fingerprintState) : 0;
1010
1137
  if (isInModel) {
1011
1138
  search.trackActionPossible(state, successor.state);
1012
1139
  fingerprintModelState(fingerprintState);
1013
1140
  successor.state.forEach(markFingerprinted);
1014
1141
  }
1015
- return { fingerprintState, hash, isInModel, existing: isInModel ? foundIndex : -1 };
1142
+ const existing = isInModel ? findStateIndex(seenStates, hash, fingerprintState) : -1;
1143
+ return {
1144
+ fingerprintState,
1145
+ hash,
1146
+ isInModel,
1147
+ existing,
1148
+ isSeen: existing !== -1 || (isInModel && isExplored(hash, fingerprintState)),
1149
+ };
1016
1150
  };
1017
1151
  const visitSuccessor = (
1018
1152
  index: number,
@@ -1031,7 +1165,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1031
1165
  stateWriter?.writeSuccessor(
1032
1166
  source,
1033
1167
  getGraphState(successor.state, depths[index] + 1),
1034
- found.existing !== -1,
1168
+ found.isSeen,
1035
1169
  action && getGraphAction(action),
1036
1170
  );
1037
1171
  }
@@ -1053,7 +1187,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1053
1187
  const isStored = stored.every((value, position) => value === successor.state[position]);
1054
1188
  liveSuccessors.push({ index: found.existing, state: isStored ? stored : successor.state });
1055
1189
  }
1056
- const isNew = found.isInModel && found.existing === -1;
1190
+ if (found.isSeen && found.existing === -1 && liveness) {
1191
+ liveSuccessors.push({
1192
+ index: getPendingIndex(found.hash, found.fingerprintState),
1193
+ state: successor.state,
1194
+ });
1195
+ }
1196
+ const isNew = found.isInModel && !found.isSeen;
1057
1197
  if (isNew && liveness) liveSuccessors.push({ index: states.length, state: successor.state });
1058
1198
  unstoredFingerprint = isNew ? found.fingerprintState : undefined;
1059
1199
  if (isNew) {
@@ -1061,20 +1201,26 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1061
1201
  newStateCount++;
1062
1202
  if (coverage) coverage.secondary[coveredNode]++;
1063
1203
  }
1064
- if (found.existing === -1) {
1204
+ if (!found.isSeen) {
1065
1205
  try {
1066
1206
  const violated = search.findViolatedInvariant(successor.state, state);
1067
- const violation = violated && { name: violated.name, ...traces.getTrace(index, successor) };
1207
+ const violation = violated && {
1208
+ name: violated.name,
1209
+ ...traces.getTrace(index, successor, { isPrintedOnly: options.isContinued }),
1210
+ };
1068
1211
  if (violation && !options.isContinued) {
1069
1212
  return withOutDegrees(reportViolation("invariant-violation", violation));
1070
1213
  }
1071
1214
  if (violation) reportContinuedViolation("invariant-violation", violation);
1072
1215
  } catch (error) {
1073
1216
  if (isStackOverflow(error)) throw error;
1074
- const replay = captureOutput(() => replayNext(index));
1217
+ const behavior = traces.getTrace(index, successor, { isPrintedOnly: true });
1218
+ const replay = is174
1219
+ ? captureOutput(() => replayNext(index))
1220
+ : replayFailedNext(index, liveSuccessors);
1075
1221
  return createFailureResult(
1076
1222
  error,
1077
- appendTraceOutput(traces.getFailedTrace(index, successor), replay.lines),
1223
+ appendTraceOutput(behavior, replay.lines),
1078
1224
  replay.result ?? { outDegrees: getFailureOutDegrees() },
1079
1225
  );
1080
1226
  }
@@ -1082,7 +1228,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1082
1228
  const violatedProperty = search.findViolatedActionProperty(state, successor.state);
1083
1229
  const propertyViolation = violatedProperty && {
1084
1230
  name: violatedProperty.name,
1085
- ...traces.getTrace(index, successor),
1231
+ ...traces.getTrace(index, successor, { isPrintedOnly: options.isContinued }),
1086
1232
  };
1087
1233
  if (propertyViolation && !options.isContinued) {
1088
1234
  return withOutDegrees(reportViolation("liveness-violation", propertyViolation));
@@ -1092,6 +1238,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1092
1238
  if (coverage) countCoverageVariables(coverage, successor.state);
1093
1239
  if (!isCanonicalizedFirst) canonicalizeState(successor.state);
1094
1240
  markSeenState(seenStates, found.hash, states.length);
1241
+ if (pendingStates) {
1242
+ const pending = findStateIndex(pendingStates, found.hash, found.fingerprintState);
1243
+ if (pending !== -1) liveness?.storeState(-2 - pending, states.length);
1244
+ }
1095
1245
  addState(successor.state, found.fingerprintState, index, successor.action);
1096
1246
  runtime.queueSize++;
1097
1247
  return undefined;
@@ -1139,7 +1289,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1139
1289
  kind: "liveness-started",
1140
1290
  branches: liveness.branches,
1141
1291
  isComplete: true,
1142
- states: typed.distinctStates,
1292
+ states: liveness.branches * typed.distinctStates,
1143
1293
  statistics,
1144
1294
  });
1145
1295
  options.onProgress?.({ kind: "liveness-finished" });
@@ -1203,14 +1353,29 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1203
1353
  }
1204
1354
  } catch (error) {
1205
1355
  if (error instanceof TlaIllegalStateError) {
1356
+ reportInitialStatesProgress(runtime.initialStates, options.onProgress);
1357
+ runtime.generatedStates++;
1358
+ runtime.initialStates++;
1359
+ const state = error.state.map((value) => value ?? createModelValue("null"));
1360
+ // Deviation from TLC: CounterExample holds a Java null for an unassigned variable and leaks a NullPointerException, where tla-ts binds the model value null.
1361
+ const checked = checkTracePostconditions(
1362
+ [{ action: undefined, label: undefined, state: toRecord(state) }],
1363
+ undefined,
1364
+ getStepState,
1365
+ );
1366
+ const postcondition = checked.unwitnessed ?? checked.postcondition;
1206
1367
  const illegal = createFailureResult(
1207
1368
  error,
1208
- { trace: [] },
1209
- { initialState: error.state.map((value) => value ?? createModelValue("null")) },
1369
+ { trace: [], traceOutput: checked.lines },
1370
+ { initialState: state },
1210
1371
  );
1211
1372
  return {
1212
1373
  ...illegal,
1213
- failure: illegal.failure && { ...illegal.failure, isWithoutStatistics: true },
1374
+ failure: illegal.failure && {
1375
+ ...illegal.failure,
1376
+ isWithoutStatistics: true,
1377
+ ...(postcondition && { postcondition }),
1378
+ },
1214
1379
  };
1215
1380
  }
1216
1381
  const replay = captureOutput(replayInit);
@@ -1255,7 +1420,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1255
1420
  try {
1256
1421
  coverageActions.forEach((action) => {
1257
1422
  coveredNode = action.node;
1258
- walkCoveredSuccessors(action, state, (successor) => {
1423
+ walkCoveredSuccessors(coverage, action, state, environment, (successor) => {
1259
1424
  successorCount++;
1260
1425
  if (onSuccessor({ state: successor, action: action.name }, action)) throw STOP_WALK;
1261
1426
  });
@@ -1296,6 +1461,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1296
1461
  );
1297
1462
  }, 0);
1298
1463
  };
1464
+ // Deviation from TLC: Worker#doNextCheckLiveness doesn't catch a FingerprintException from its rerun, so TLC prints the behavior without the failure.
1299
1465
  const getLiveCallStack = (index: number, liveSuccessors: LiveSuccessor[]) => {
1300
1466
  if (!liveness || is174) return undefined;
1301
1467
  const replay = getReplayFailure(environment, (tracing) =>
@@ -1309,6 +1475,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1309
1475
  return undefined;
1310
1476
  } catch (error) {
1311
1477
  if (!(error instanceof TlaEvaluationError)) throw error;
1478
+ // TLC fails to fingerprint an incomplete successor with an exception Worker#doNextCheckLiveness doesn't rerun for a call stack.
1479
+ if (error instanceof TlaIncompleteSuccessorError) return undefined;
1312
1480
  return getLiveCallStack(index, liveSuccessors);
1313
1481
  }
1314
1482
  };
@@ -1319,23 +1487,91 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1319
1487
  return { result, lines: live.lines };
1320
1488
  }
1321
1489
  const replay = captureOutput(() => replayNext(index));
1322
- return { result: replay.result, lines: [...live.lines, ...replay.lines] };
1490
+ const result: FailureOptions =
1491
+ replay.result ?? (is174 ? {} : { outDegrees: getFailureOutDegrees() });
1492
+ return { result, lines: [...live.lines, ...replay.lines] };
1493
+ };
1494
+ const getNextFailureTrace = (index: number, counterExample?: CounterExampleOptions) =>
1495
+ checkFailedTrace(
1496
+ traces.getStateTrace(index, { isPrintedOnly: !counterExample }),
1497
+ counterExample,
1498
+ );
1499
+ const reportNextStateOverflow = (index: number, counterExample?: CounterExampleOptions) => {
1500
+ const checked = getNextFailureTrace(index, counterExample);
1501
+ return createFailureResult(
1502
+ createStackOverflowError(),
1503
+ checked.behavior,
1504
+ { phase: "next" },
1505
+ checked.postcondition,
1506
+ );
1323
1507
  };
1324
- const reportNextStateOverflow = (index: number) =>
1325
- createFailureResult(createStackOverflowError(), traces.getStateTrace(index), { phase: "next" });
1508
+ // Deviation from TLC: under -continue, TLC's Worker reports a state whose next-state relation failed as deadlocked, or else reports the failure twice as its replay fails again.
1509
+ // Deviation from TLC: under -continue, ModelChecker#doNextEvalFailed rethrows a failed invariant to Worker#doNextFailed, which reports it again with the code of its error.
1326
1510
  const reportNextStateFailure = (
1327
1511
  error: unknown,
1328
1512
  index: number,
1329
1513
  liveSuccessors: LiveSuccessor[],
1514
+ generated: number,
1330
1515
  ) => {
1331
- if (isStackOverflow(error)) return reportNextStateOverflow(index);
1516
+ // TLC's Worker goes on to find a state without successors deadlocked after it fails, which checks the postconditions.
1517
+ const counterExample =
1518
+ config.checkDeadlock && runtime.generatedStates === generated
1519
+ ? { isConsole: false }
1520
+ : undefined;
1521
+ if (isStackOverflow(error)) return reportNextStateOverflow(index, counterExample);
1522
+ const checked = getNextFailureTrace(index, counterExample);
1332
1523
  const replay = replayFailedNext(index, liveSuccessors);
1333
1524
  return createFailureResult(
1334
1525
  withNextStateExitCode(error),
1335
- appendTraceOutput(traces.getStateTrace(index), replay.lines),
1526
+ appendTraceOutput(checked.behavior, replay.lines),
1336
1527
  { phase: "next", ...replay.result },
1528
+ checked.postcondition,
1337
1529
  );
1338
1530
  };
1531
+ const addLiveState = (
1532
+ index: number,
1533
+ liveSuccessors: LiveSuccessor[],
1534
+ source: GraphState | undefined,
1535
+ ) => {
1536
+ if (liveness && source && (is174 || options.dump?.stuttering)) {
1537
+ stateWriter?.writeStuttering(source);
1538
+ }
1539
+ const accepted = liveness?.addState(index, states[index], liveSuccessors);
1540
+ if (!liveness || !accepted) return undefined;
1541
+ // Deviation from TLC: under -continue, TLC's LiveCheck throws an InvariantViolatedException after it reports the property, which its Worker reports as unexpected.
1542
+ const steps = traces.getPathSteps(accepted);
1543
+ const properties = getViolatedProperties(
1544
+ liveness,
1545
+ steps.map((step) => step.state),
1546
+ steps.length - 1,
1547
+ );
1548
+ return reportViolation("property-violation", {
1549
+ name: properties[0],
1550
+ properties,
1551
+ ...traces.toTrace(steps, accepted, { known: 0 }),
1552
+ });
1553
+ };
1554
+ const addReportedLiveState = (
1555
+ index: number,
1556
+ liveSuccessors: LiveSuccessor[],
1557
+ source: GraphState | undefined,
1558
+ ) =>
1559
+ captureOutput(() => {
1560
+ try {
1561
+ return {
1562
+ additional: addLiveState(index, liveSuccessors, source)?.violation,
1563
+ isFailed: false,
1564
+ callStack: undefined,
1565
+ };
1566
+ } catch (error) {
1567
+ if (!(error instanceof TlaEvaluationError)) throw error;
1568
+ return {
1569
+ additional: undefined,
1570
+ isFailed: true,
1571
+ callStack: getLiveCallStack(index, liveSuccessors),
1572
+ };
1573
+ }
1574
+ });
1339
1575
  const expandState = (index: number, liveSuccessors: LiveSuccessor[]) => {
1340
1576
  const state = states[index];
1341
1577
  const source = stateWriter && getGraphState(state, depths[index]);
@@ -1357,10 +1593,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1357
1593
  outcome = reportNextStateOverflow(index);
1358
1594
  return true;
1359
1595
  }
1360
- const replay = is174
1361
- ? captureOutput(() => replayNext(index))
1362
- : replayFailedNext(index, liveSuccessors);
1363
1596
  if (is174 && error instanceof TlaEvaluationError && !isHeadedError(error)) {
1597
+ const replay = captureOutput(() => replayNext(index));
1364
1598
  outcome = createFailureResult(
1365
1599
  new TlaEvaluationError(`${getWrappedException(error)}${error.message}`, error),
1366
1600
  appendTraceOutput({ trace: [] }, replay.lines),
@@ -1368,72 +1602,61 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1368
1602
  );
1369
1603
  return true;
1370
1604
  }
1371
- const isTraceFailed = isUnfingerprintable(successor.state);
1372
- const traceFailure =
1373
- isTraceFailed && error instanceof TlaEvaluationError
1374
- ? getFailureMessage(
1375
- isEvalException(error)
1376
- ? new TlaEvaluationError(`${UNEXPECTED_EVAL_EXCEPTION}${error.message}`)
1377
- : error,
1378
- true,
1379
- )
1605
+ const traceError =
1606
+ error instanceof TlaEvaluationError && isUnfingerprintable(successor.state)
1607
+ ? error
1380
1608
  : undefined;
1381
- outcome = createFailureResult(
1382
- error,
1383
- appendTraceOutput(
1384
- traceFailure ? traces.getStateTrace(index) : traces.getFailedTrace(index, successor),
1385
- replay.lines,
1386
- ),
1387
- { phase: "next", ...replay.result, traceFailure },
1388
- );
1609
+ const behavior = traceError
1610
+ ? traces.getStateTrace(index, { isPrintedOnly: true })
1611
+ : traces.getTrace(index, successor, { isPrintedOnly: true });
1612
+ const traceFailure =
1613
+ traceError &&
1614
+ getTraceFailure(
1615
+ traceError,
1616
+ captureOutput(() => {
1617
+ try {
1618
+ traces.findStepAction(index, state, successor.state, true);
1619
+ } catch (failed) {
1620
+ if (!(failed instanceof TlaEvaluationError)) throw failed;
1621
+ }
1622
+ }).lines,
1623
+ );
1624
+ const replay = is174
1625
+ ? captureOutput(() => replayNext(index))
1626
+ : replayFailedNext(index, liveSuccessors);
1627
+ outcome = createFailureResult(error, appendTraceOutput(behavior, replay.lines), {
1628
+ phase: "next",
1629
+ ...replay.result,
1630
+ traceFailure,
1631
+ });
1389
1632
  }
1390
1633
  return outcome !== undefined;
1391
1634
  });
1392
1635
  current.isExpanding = false;
1393
1636
  const result = outcome;
1394
1637
  if (result?.violation && !is174) {
1395
- const live = captureOutput(() => addFailedLiveState(index, liveSuccessors));
1638
+ const live = addReportedLiveState(index, liveSuccessors, source);
1396
1639
  return {
1397
1640
  ...result,
1398
1641
  violation: appendTraceOutput(result.violation, live.lines),
1399
- ...(live.result && { liveCallStack: live.result }),
1642
+ // TLC adds the state to the behavior graph before it reports the coverage.
1643
+ coverage: getCoverage(),
1644
+ ...(live.result.additional && { additionalViolation: live.result.additional }),
1645
+ ...(live.result.callStack && { liveCallStack: live.result.callStack }),
1400
1646
  };
1401
1647
  }
1402
1648
  if (result) return result;
1403
- const addLiveState = () => {
1404
- if (liveness && source && (is174 || options.dump?.stuttering)) {
1405
- stateWriter?.writeStuttering(source);
1406
- }
1407
- const accepted = liveness?.addState(index, state, liveSuccessors);
1408
- if (!liveness || !accepted) return undefined;
1409
- const steps = traces.getPathSteps(accepted);
1410
- const properties = getViolatedProperties(
1411
- liveness,
1412
- steps.map((step) => step.state),
1413
- steps.length - 1,
1414
- );
1415
- return reportViolation("property-violation", {
1416
- name: properties[0],
1417
- properties,
1418
- ...traces.toTrace(steps, accepted, { known: 0 }),
1419
- });
1420
- };
1421
1649
  if (successorCount === 0 && config.checkDeadlock) {
1422
1650
  const deadlock = reportViolation("deadlock", {
1423
1651
  name: "deadlock",
1424
1652
  ...traces.getStateTrace(index),
1425
1653
  });
1426
- const live = captureOutput(() => {
1427
- try {
1428
- return { additional: addLiveState()?.violation };
1429
- } catch (error) {
1430
- if (!(error instanceof TlaEvaluationError)) throw error;
1431
- return { isFailed: true, callStack: getLiveCallStack(index, liveSuccessors) };
1432
- }
1433
- });
1434
- const reported = deadlock.violation
1435
- ? { ...deadlock, violation: appendTraceOutput(deadlock.violation, live.lines) }
1436
- : deadlock;
1654
+ const live = addReportedLiveState(index, liveSuccessors, source);
1655
+ const reported = {
1656
+ ...deadlock,
1657
+ violation: deadlock.violation && appendTraceOutput(deadlock.violation, live.lines),
1658
+ coverage: getCoverage(),
1659
+ };
1437
1660
  const counted = withOutDegrees(
1438
1661
  reported,
1439
1662
  live.result.isFailed ? getFailureOutDegrees() : getPartialOutDegrees(),
@@ -1443,14 +1666,11 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1443
1666
  return live.result.callStack ? { ...counted, liveCallStack: live.result.callStack } : counted;
1444
1667
  }
1445
1668
  try {
1446
- return addLiveState();
1669
+ return addLiveState(index, liveSuccessors, source);
1447
1670
  } catch (error) {
1448
1671
  if (is174 && error instanceof TlaEvaluationError) {
1449
- const unexpected = new TlaEvaluationError(
1450
- `${isEvalException(error) ? UNEXPECTED_EVAL_EXCEPTION : UNEXPECTED_EXCEPTION}${error.message}`,
1451
- );
1452
1672
  return createFailureResult(
1453
- setExitCode(unexpected, EXIT_STATUS.error),
1673
+ setExitCode(toUnexpectedError(error), EXIT_STATUS.error),
1454
1674
  { trace: [] },
1455
1675
  { outDegrees: getFailureOutDegrees() },
1456
1676
  );
@@ -1458,7 +1678,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1458
1678
  const replay = getReplayFailure(environment, (tracing) =>
1459
1679
  liveness?.addState(index, state, liveSuccessors, tracing),
1460
1680
  );
1461
- return createFailureResult(error, traces.getStateTrace(index), {
1681
+ const behavior = traces.getStateTrace(index, { isPrintedOnly: true });
1682
+ const replayed = captureOutput(() => replayNext(index));
1683
+ return createFailureResult(error, appendTraceOutput(behavior, replayed.lines), {
1462
1684
  outDegrees: getFailureOutDegrees(),
1463
1685
  callStack: replay?.callStack.length ? replay.callStack : undefined,
1464
1686
  phase: "liveness",
@@ -1482,10 +1704,20 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1482
1704
  text: `The stuttering counterexample above may be caused by the absence of a fairness constraint in the behavior specification ${name} defined at ${formatRange(range)}. To rule out such counterexamples, conjoin a suitable fairness constraint to ${name} ${book}`,
1483
1705
  };
1484
1706
  };
1707
+ const toLivenessFailure = (error: TlaEvaluationError) =>
1708
+ setExitCode(toUnexpectedError(error), EXIT_STATUS.abort);
1709
+ const getLassoSteps = (path: number[]) => {
1710
+ try {
1711
+ return traces.getPathSteps(path);
1712
+ } catch (error) {
1713
+ if (!(error instanceof TlaEvaluationError)) throw error;
1714
+ throw toLivenessFailure(error);
1715
+ }
1716
+ };
1485
1717
  const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1486
1718
  const path = [...lasso.prefix, ...lasso.cycle];
1487
1719
  const loopStart = lasso.prefix.length;
1488
- const steps = traces.getPathSteps(path, loopStart);
1720
+ const steps = getLassoSteps(path);
1489
1721
  const trace = traces.toTrace(steps, path, { loopStart, known: 0 }).trace;
1490
1722
  const properties = getViolatedProperties(
1491
1723
  checker,
@@ -1495,13 +1727,28 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1495
1727
  const cycleStart = path[loopStart];
1496
1728
  const cycleEnd = path[path.length - 1];
1497
1729
  const lastState = steps[steps.length - 1].state;
1498
- const loop =
1499
- cycleStart === cycleEnd
1500
- ? { result: undefined, lines: [] }
1501
- : captureOutput(() =>
1502
- traces.findStepAction(cycleEnd, lastState, states[cycleStart], false),
1503
- );
1504
- const isStutteringWarned = cycleStart === cycleEnd && lasso.isCycleConstrained;
1730
+ const isStuttering = cycleStart === cycleEnd;
1731
+ const loop = isStuttering
1732
+ ? { result: undefined, lines: [] }
1733
+ : captureOutput(() => traces.findStepAction(cycleEnd, lastState, states[cycleStart], false));
1734
+ const back =
1735
+ isStuttering || loop.result
1736
+ ? undefined
1737
+ : traces.findSuccessorWithFingerprint(lastState, cycleEnd, cycleStart);
1738
+ if (!isStuttering && !loop.result && !back) {
1739
+ options.onProgress?.({
1740
+ kind: "violation",
1741
+ status: "property-violation",
1742
+ violation: {
1743
+ name: properties[0],
1744
+ properties,
1745
+ trace,
1746
+ traceOutput: loop.lines,
1747
+ loopStart: undefined,
1748
+ },
1749
+ });
1750
+ throw toLivenessFailure(new TlaEvaluationError(NEXT_RECOVERY_FAILURE));
1751
+ }
1505
1752
  return reportViolation(
1506
1753
  "liveness-violation",
1507
1754
  {
@@ -1511,40 +1758,44 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1511
1758
  traceOutput: loop.lines,
1512
1759
  loopStart,
1513
1760
  loopLabel: loop.result && getActionLabel(loop.result, options.version),
1514
- warning: isStutteringWarned ? getStutteringWarning() : undefined,
1761
+ warning: isStuttering && lasso.isCycleConstrained ? getStutteringWarning() : undefined,
1515
1762
  },
1763
+ getStepState,
1516
1764
  () =>
1517
- cycleStart === cycleEnd
1765
+ isStuttering
1518
1766
  ? getStepAction(trace[trace.length - 1])
1519
1767
  : loop.result
1520
1768
  ? toActionValue(loop.result)
1521
- : createActionRecord(
1522
- traces.findSuccessorWithFingerprint(lastState, cycleStart)?.action,
1523
- ),
1769
+ : createActionRecord(back?.action),
1524
1770
  );
1525
1771
  };
1526
1772
  const isPeriodic = liveness !== undefined && (options.livenessCheck ?? "default") === "default";
1527
1773
  const startedAt = performance.now();
1528
1774
  const periodic = {
1529
1775
  at: startedAt + PERIODIC_START,
1530
- size: 1,
1776
+ checkedCounts: liveness?.getStateCounts().map(() => 1) ?? [],
1531
1777
  time: 0,
1532
1778
  coverageCount: Math.trunc(options.coverage ?? 0),
1533
1779
  };
1534
- const findPeriodicViolation = (expanded: number) => {
1780
+ const getGraphStates = (checker: LivenessChecker) =>
1781
+ checker.getStateCounts().reduce((sum, count) => sum + count, 0);
1782
+ const findPeriodicViolation = (checker: LivenessChecker) => {
1535
1783
  const now = performance.now();
1536
- const isGrown = (expanded - periodic.size) / periodic.size > LIVENESS_GROWTH;
1784
+ const counts = checker.getStateCounts();
1785
+ const isGrown = counts.some(
1786
+ (count, branch) =>
1787
+ (count - periodic.checkedCounts[branch]) / periodic.checkedCounts[branch] > LIVENESS_GROWTH,
1788
+ );
1537
1789
  if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1538
- periodic.size = expanded;
1539
- if (!liveness) return undefined;
1790
+ periodic.checkedCounts = counts;
1540
1791
  options.onProgress?.({
1541
1792
  kind: "liveness-started",
1542
- branches: liveness.branches,
1793
+ branches: checker.branches,
1543
1794
  isComplete: false,
1544
- states: expanded,
1795
+ states: getGraphStates(checker),
1545
1796
  statistics: createResult("success"),
1546
1797
  });
1547
- const lasso = liveness.findViolation();
1798
+ const lasso = checker.findViolation();
1548
1799
  if (!lasso) options.onProgress?.({ kind: "liveness-finished" });
1549
1800
  periodic.time += performance.now() - now;
1550
1801
  return lasso;
@@ -1657,20 +1908,21 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1657
1908
  runtime.queueSize = states.length - index - 1;
1658
1909
  current.isExpanding = true;
1659
1910
  const liveSuccessors: LiveSuccessor[] = [];
1911
+ const generated = runtime.generatedStates;
1660
1912
  try {
1661
1913
  outcome = expandState(index, liveSuccessors);
1662
1914
  } catch (error) {
1663
1915
  outcome =
1664
1916
  error instanceof TlaIncompleteSuccessorError
1665
- ? reportIncompleteSuccessor(index, error)
1666
- : reportNextStateFailure(error, index, liveSuccessors);
1917
+ ? reportIncompleteSuccessor(index, error, liveSuccessors)
1918
+ : reportNextStateFailure(error, index, liveSuccessors, generated);
1667
1919
  }
1668
1920
  if (outcome) return outcome;
1669
1921
  outDegrees[getOutDegreeBucket()]++;
1670
1922
  newStateCount = 0;
1671
1923
  if ((isPeriodic || options.onProgress) && performance.now() >= periodic.at) {
1672
1924
  periodic.at = performance.now() + PROGRESS_INTERVAL;
1673
- const lasso = isPeriodic ? findPeriodicViolation(index + 1) : undefined;
1925
+ const lasso = isPeriodic && liveness ? findPeriodicViolation(liveness) : undefined;
1674
1926
  if (liveness && lasso) return reportLasso(liveness, lasso);
1675
1927
  const isCoverageDue = options.coverage !== undefined && periodic.coverageCount === 0;
1676
1928
  periodic.coverageCount = isCoverageDue
@@ -1692,7 +1944,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1692
1944
  kind: "liveness-started",
1693
1945
  branches: finalLiveness.branches,
1694
1946
  isComplete: true,
1695
- states: runtime.distinctStates,
1947
+ states: typedLasso
1948
+ ? finalLiveness.branches * runtime.distinctStates
1949
+ : getGraphStates(finalLiveness),
1696
1950
  statistics: createResult("success"),
1697
1951
  });
1698
1952
  }