tla-ts 0.0.10-dev.99796fe03 → 0.0.10-dev.a17d6d9fa

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 (226) 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 +54 -54
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.d.cts +3 -2
  7. package/dist/index.d.ts +3 -2
  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 +60 -60
  14. package/dist/prove.js +78 -78
  15. package/dist/run.cjs +42 -44
  16. package/dist/run.js +44 -46
  17. package/dist/tlapm.cjs +1 -1
  18. package/dist/tlapm.js +2 -2
  19. package/dist/transfer.cjs +43 -43
  20. package/dist/transfer.js +39 -39
  21. package/dist/worker.cjs +6 -6
  22. package/dist/worker.js +6 -6
  23. package/package.json +1 -1
  24. package/src/ast.ts +1 -0
  25. package/src/bags.ts +50 -29
  26. package/src/builtins.ts +4 -3
  27. package/src/check-failure.ts +1 -1
  28. package/src/check-trace.ts +90 -51
  29. package/src/check.ts +367 -178
  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 +1 -2
  33. package/src/cli/tlc.ts +16 -10
  34. package/src/cli/xml-exporter.ts +1 -1
  35. package/src/codegen.ts +26 -9
  36. package/src/dependencies.ts +49 -9
  37. package/src/dfid.ts +22 -10
  38. package/src/environment.ts +58 -33
  39. package/src/errors.ts +7 -0
  40. package/src/evaluate.ts +117 -41
  41. package/src/exit-codes.ts +4 -2
  42. package/src/instances.ts +5 -5
  43. package/src/java-hash.ts +14 -0
  44. package/src/java-overrides.ts +2 -2
  45. package/src/levels.ts +138 -90
  46. package/src/liveness-checker.ts +81 -33
  47. package/src/liveness.ts +49 -11
  48. package/src/obligations/index.ts +1 -1
  49. package/src/obligations/normalize.ts +1 -4
  50. package/src/obligations/printer.ts +5 -5
  51. package/src/parallel-worker.ts +8 -2
  52. package/src/parallel.ts +5 -0
  53. package/src/parser.ts +112 -145
  54. package/src/prover/isabelle/isar/attrib.ts +4 -4
  55. package/src/prover/isabelle/isar/rule-cases.ts +8 -6
  56. package/src/prover/isabelle/provers/clasimp.ts +1 -1
  57. package/src/prover/isabelle/provers/hypsubst.ts +2 -2
  58. package/src/prover/isabelle/pure/rewriter.ts +3 -3
  59. package/src/prover/isabelle/pure/term.ts +3 -3
  60. package/src/prover/prep/md5.ts +26 -29
  61. package/src/prover/smt/rewrite.ts +2 -7
  62. package/src/prover/smt/simplify.ts +1 -1
  63. package/src/prover/smt/solver/arith-rewriter.ts +11 -3
  64. package/src/prover/smt/solver/array-rewriter.ts +12 -2
  65. package/src/prover/smt/solver/asserted-formulas.ts +169 -58
  66. package/src/prover/smt/solver/ast-lt.ts +1 -1
  67. package/src/prover/smt/solver/ast.ts +63 -14
  68. package/src/prover/smt/solver/auf-solver.ts +23 -12
  69. package/src/prover/smt/solver/bit-blast-tactic.ts +26 -0
  70. package/src/prover/smt/solver/blast-term-ite.ts +47 -0
  71. package/src/prover/smt/solver/bound-simplifier.ts +11 -13
  72. package/src/prover/smt/solver/bv-decl-plugin.ts +13 -10
  73. package/src/prover/smt/solver/bv-rewriter.ts +1 -1
  74. package/src/prover/smt/solver/card2bv.ts +32 -18
  75. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +39 -24
  76. package/src/prover/smt/solver/context.ts +47 -9
  77. package/src/prover/smt/solver/ctx-simplify.ts +1 -2
  78. package/src/prover/smt/solver/datatype-decl-plugin.ts +15 -7
  79. package/src/prover/smt/solver/dependent-expr-state.ts +9 -4
  80. package/src/prover/smt/solver/diff-neq.ts +1 -2
  81. package/src/prover/smt/solver/elim-bounds.ts +89 -0
  82. package/src/prover/smt/solver/elim-term-ite-tactic.ts +48 -0
  83. package/src/prover/smt/solver/elim-uncnstr.ts +5 -8
  84. package/src/prover/smt/solver/euf/arith-internalize.ts +1 -1
  85. package/src/prover/smt/solver/euf/array-internalize.ts +1 -1
  86. package/src/prover/smt/solver/euf/bv-internalize.ts +1 -1
  87. package/src/prover/smt/solver/euf/egraph.ts +4 -11
  88. package/src/prover/smt/solver/euf/euf-solver.ts +1 -2
  89. package/src/prover/smt/solver/euf/mam.ts +1 -5
  90. package/src/prover/smt/solver/euf/q-ematch.ts +1 -2
  91. package/src/prover/smt/solver/euf/th-solver.ts +0 -7
  92. package/src/prover/smt/solver/expr2polynomial.ts +204 -79
  93. package/src/prover/smt/solver/factor.ts +36 -14
  94. package/src/prover/smt/solver/fd-solver.ts +2 -0
  95. package/src/prover/smt/solver/fix-dl-var.ts +1 -2
  96. package/src/prover/smt/solver/fpa-rewriter.ts +1 -2
  97. package/src/prover/smt/solver/fpa2bv-converter.ts +3 -1
  98. package/src/prover/smt/solver/fpa2bv-rewriter.ts +1 -0
  99. package/src/prover/smt/solver/goal.ts +6 -3
  100. package/src/prover/smt/solver/goal2nlsat.ts +57 -30
  101. package/src/prover/smt/solver/hashtable.ts +4 -0
  102. package/src/prover/smt/solver/internalizer.ts +1 -1
  103. package/src/prover/smt/solver/logic-tactics.ts +9 -2
  104. package/src/prover/smt/solver/lp/lp-settings.ts +5 -1
  105. package/src/prover/smt/solver/lp/nla-core.ts +1 -1
  106. package/src/prover/smt/solver/lp/nla-grobner.ts +2 -2
  107. package/src/prover/smt/solver/lp/nra-solver.ts +45 -39
  108. package/src/prover/smt/solver/lp/pdd.ts +2 -3
  109. package/src/prover/smt/solver/lp/union-find.ts +1 -1
  110. package/src/prover/smt/solver/mam-compiler.ts +1 -1
  111. package/src/prover/smt/solver/model-based-opt.ts +1 -1
  112. package/src/prover/smt/solver/model-evaluator.ts +2 -0
  113. package/src/prover/smt/solver/model-generator.ts +85 -43
  114. package/src/prover/smt/solver/mpf.ts +2 -4
  115. package/src/prover/smt/solver/mus.ts +2 -3
  116. package/src/prover/smt/solver/muz/dl-context.ts +10 -4
  117. package/src/prover/smt/solver/muz/dl-mk-slice.ts +3 -3
  118. package/src/prover/smt/solver/muz/dl-rule.ts +2 -2
  119. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +1 -1
  120. package/src/prover/smt/solver/muz/horn-tactic.ts +1 -1
  121. package/src/prover/smt/solver/muz/spacer-context.ts +2 -4
  122. package/src/prover/smt/solver/muz/spacer-pdr.ts +1 -0
  123. package/src/prover/smt/solver/nlqsat.ts +1 -1
  124. package/src/prover/smt/solver/nlsat/algebraic.ts +196 -92
  125. package/src/prover/smt/solver/nlsat/atoms.ts +52 -33
  126. package/src/prover/smt/solver/nlsat/explain.ts +375 -217
  127. package/src/prover/smt/solver/nlsat/levelwise.ts +460 -240
  128. package/src/prover/smt/solver/nlsat/polynomial.ts +2366 -681
  129. package/src/prover/smt/solver/nlsat/solver.ts +74 -64
  130. package/src/prover/smt/solver/nlsat/transcendentals.ts +41 -17
  131. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +8 -4
  132. package/src/prover/smt/solver/nlsat/upolynomial.ts +41 -18
  133. package/src/prover/smt/solver/nlsat-tactic.ts +1 -1
  134. package/src/prover/smt/solver/nnf.ts +6 -2
  135. package/src/prover/smt/solver/opt-context.ts +20 -7
  136. package/src/prover/smt/solver/opt-nlsat.ts +29 -18
  137. package/src/prover/smt/solver/opt-pareto.ts +19 -0
  138. package/src/prover/smt/solver/opt-preprocess.ts +1 -1
  139. package/src/prover/smt/solver/opt-solver.ts +9 -5
  140. package/src/prover/smt/solver/optsmt.ts +1 -1
  141. package/src/prover/smt/solver/pb-rewriter.ts +1 -4
  142. package/src/prover/smt/solver/poly-rewriter.ts +75 -18
  143. package/src/prover/smt/solver/probes.ts +88 -23
  144. package/src/prover/smt/solver/proto-model.ts +8 -8
  145. package/src/prover/smt/solver/push-app-ite.ts +37 -0
  146. package/src/prover/smt/solver/qe-arith-plugin.ts +2 -4
  147. package/src/prover/smt/solver/qe-lite.ts +2 -2
  148. package/src/prover/smt/solver/qe.ts +3 -2
  149. package/src/prover/smt/solver/qsat.ts +16 -6
  150. package/src/prover/smt/solver/quantifier-manager.ts +14 -9
  151. package/src/prover/smt/solver/recfun-decl-plugin.ts +2 -1
  152. package/src/prover/smt/solver/rewriter.ts +31 -25
  153. package/src/prover/smt/solver/rlimit.ts +4 -0
  154. package/src/prover/smt/solver/sat/config.ts +1 -1
  155. package/src/prover/smt/solver/sat/goal2sat.ts +0 -1
  156. package/src/prover/smt/solver/sat/inc-sat-solver.ts +39 -5
  157. package/src/prover/smt/solver/sat/model-converter.ts +1 -1
  158. package/src/prover/smt/solver/sat/pb-solver.ts +1 -1
  159. package/src/prover/smt/solver/sat/sat-tactic.ts +13 -5
  160. package/src/prover/smt/solver/sat/simplifier.ts +1 -1
  161. package/src/prover/smt/solver/sat/solver.ts +25 -47
  162. package/src/prover/smt/solver/seq-axioms.ts +20 -35
  163. package/src/prover/smt/solver/seq-decl-plugin.ts +1 -1
  164. package/src/prover/smt/solver/seq-derive.ts +2 -2
  165. package/src/prover/smt/solver/seq-eq-solver.ts +2 -2
  166. package/src/prover/smt/solver/seq-monadic.ts +7 -5
  167. package/src/prover/smt/solver/seq-re-rewriter.ts +2 -1
  168. package/src/prover/smt/solver/seq-re-util.ts +1 -1
  169. package/src/prover/smt/solver/seq-regex-bisim.ts +1 -1
  170. package/src/prover/smt/solver/seq-regex-live.ts +2 -2
  171. package/src/prover/smt/solver/seq-rewriter.ts +31 -29
  172. package/src/prover/smt/solver/seq-skolem.ts +0 -23
  173. package/src/prover/smt/solver/seq-view-witness.ts +4 -4
  174. package/src/prover/smt/solver/smt-kernel.ts +39 -5
  175. package/src/prover/smt/solver/smt-setup.ts +96 -10
  176. package/src/prover/smt/solver/smtlib-parser.ts +584 -223
  177. package/src/prover/smt/solver/smtlib-script.ts +509 -154
  178. package/src/prover/smt/solver/solve-eqs.ts +36 -37
  179. package/src/prover/smt/solver/solver.ts +18 -3
  180. package/src/prover/smt/solver/tactic.ts +284 -168
  181. package/src/prover/smt/solver/theory-bv.ts +13 -3
  182. package/src/prover/smt/solver/theory-fpa.ts +1 -1
  183. package/src/prover/smt/solver/theory-lra-final-check.ts +1 -0
  184. package/src/prover/smt/solver/theory-lra-internalize.ts +2 -0
  185. package/src/prover/smt/solver/theory-lra-propagate.ts +11 -3
  186. package/src/prover/smt/solver/theory-lra.ts +1 -1
  187. package/src/prover/smt/solver/theory-pb.ts +24 -7
  188. package/src/prover/smt/solver/theory-seq-solve.ts +1 -1
  189. package/src/prover/smt/solver/theory-seq-state.ts +2 -21
  190. package/src/prover/smt/solver/tseitin-cnf.ts +1 -0
  191. package/src/prover/tlapm/cache.ts +8 -8
  192. package/src/prover/zenon/index-table.ts +5 -2
  193. package/src/prover/zenon/isar-case.ts +1 -1
  194. package/src/prover/zenon/isar.ts +2 -2
  195. package/src/prover/zenon/phrase.ts +1 -1
  196. package/src/resolve.ts +959 -243
  197. package/src/runtime.ts +7 -1
  198. package/src/sany/builtins.ts +10 -10
  199. package/src/sany/generation.ts +2 -13
  200. package/src/sany/generator-definitions.ts +3 -1
  201. package/src/sany/generator-expressions.ts +36 -30
  202. package/src/sany/generator-proofs.ts +5 -3
  203. package/src/sany/generator.ts +2 -1
  204. package/src/sany/lexer.ts +3 -3
  205. package/src/sany/modules.ts +4 -2
  206. package/src/sany/nodes.ts +1 -1
  207. package/src/sany/selectors.ts +11 -6
  208. package/src/sany/xml.ts +2 -3
  209. package/src/search.ts +166 -101
  210. package/src/simulate.ts +110 -50
  211. package/src/spec-description.ts +5 -6
  212. package/src/standard-modules.ts +15 -6
  213. package/src/subexpressions.ts +398 -108
  214. package/src/successors.ts +4 -2
  215. package/src/symmetry.ts +1 -1
  216. package/src/tlc/jar-data.ts +10 -0
  217. package/src/tlc/messages.ts +3 -3
  218. package/src/tlc/order.ts +14 -3
  219. package/src/tlc/random.ts +2 -1
  220. package/src/tlc/replay.ts +3 -2
  221. package/src/tlc/tlc-operators.ts +10 -8
  222. package/src/tlc/tlcext-operators.ts +44 -15
  223. package/src/tlc/trace-spec.ts +9 -22
  224. package/src/typed-tier.ts +32 -25
  225. package/src/typescript/types.ts +2 -2
  226. package/src/values.ts +135 -78
package/src/check.ts CHANGED
@@ -37,6 +37,7 @@ import {
37
37
  } from "./check-failure";
38
38
  import {
39
39
  createTraceBuilder,
40
+ NEXT_RECOVERY_FAILURE,
40
41
  type Behavior,
41
42
  type SearchPosition,
42
43
  type TracedStep,
@@ -108,7 +109,11 @@ import {
108
109
  walkSuccessors,
109
110
  } from "./tlc/replay";
110
111
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc/summary";
111
- import { createActionRecord, createCounterExample } from "./tlc/tlcext-operators";
112
+ import {
113
+ createActionRecord,
114
+ createCounterExample,
115
+ type CounterExampleLoop,
116
+ } from "./tlc/tlcext-operators";
112
117
  import type { TlcVersion } from "./tlc/version";
113
118
  import { runTypedSearch, type TypedResult } from "./typed-tier";
114
119
  import {
@@ -206,7 +211,7 @@ export type CheckProgress =
206
211
  branches: number;
207
212
  /** Whether TLC checks the complete state graph. */
208
213
  isComplete: boolean;
209
- /** How many states of the graph each branch has. */
214
+ /** How many states the graphs of all branches have together. */
210
215
  states: number;
211
216
  statistics: SearchStatistics;
212
217
  }
@@ -309,7 +314,7 @@ export interface CheckResult {
309
314
  outDegrees: number[] | undefined;
310
315
  /** The smallest distance between two fingerprints, when TLC estimates a collision from them. */
311
316
  fingerprintDistance: bigint | undefined;
312
- /** A temporal property TLC finds violated as it adds a deadlocked state, reported after. */
317
+ /** A temporal property TLC finds violated as it adds the state it stopped at to the behavior graph, reported after. */
313
318
  additionalViolation?: Violation;
314
319
  /** Where TLC's worker fails to add the state to the behavior graph after it reports a violation. */
315
320
  liveCallStack?: Expression[];
@@ -327,11 +332,28 @@ interface ReportedViolation extends Omit<Violation, "loopStart"> {
327
332
  loopStart?: number;
328
333
  }
329
334
 
335
+ interface CounterExampleOptions {
336
+ isConsole: boolean;
337
+ }
338
+
330
339
  const appendTraceOutput = <Traced extends Behavior>(behavior: Traced, lines: OutputLine[]) => ({
331
340
  ...behavior,
332
341
  traceOutput: [...(behavior.traceOutput ?? []), ...lines],
333
342
  });
334
343
 
344
+ const toUnexpectedError = (error: TlaEvaluationError) =>
345
+ new TlaEvaluationError(
346
+ `${isEvalException(error) ? UNEXPECTED_EVAL_EXCEPTION : UNEXPECTED_EXCEPTION}${error.message}`,
347
+ );
348
+
349
+ const getTraceFailure = (error: TlaEvaluationError) =>
350
+ getFailureMessage(
351
+ isEvalException(error)
352
+ ? new TlaEvaluationError(`${UNEXPECTED_EVAL_EXCEPTION}${error.message}`)
353
+ : error,
354
+ true,
355
+ );
356
+
335
357
  const STOP_REPLAY = new Error("The replay stopped");
336
358
  const STOP_WALK = new Error("The walk stopped");
337
359
 
@@ -415,6 +437,15 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
415
437
  key.startsWith(`${name}${KEY_SEPARATOR}`),
416
438
  ),
417
439
  });
440
+ const getCoverage = () =>
441
+ coverage?.relations.some((relation) => relation.kind === "next")
442
+ ? getCoverageReport(
443
+ coverage,
444
+ environment,
445
+ specification.variableLocations,
446
+ search?.getTlcOrder() ?? [],
447
+ )
448
+ : undefined;
418
449
  const createResult = (
419
450
  status: CheckStatus,
420
451
  violation?: ReportedViolation,
@@ -435,14 +466,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
435
466
  initialStates: computedInitialStates,
436
467
  outDegrees: undefined,
437
468
  fingerprintDistance: undefined,
438
- coverage: coverage?.relations.some((relation) => relation.kind === "next")
439
- ? getCoverageReport(
440
- coverage,
441
- environment,
442
- specification.variableLocations,
443
- search?.getTlcOrder() ?? [],
444
- )
445
- : undefined,
469
+ coverage: getCoverage(),
446
470
  ...(traceSpec !== undefined && { traceSpec }),
447
471
  };
448
472
  };
@@ -466,7 +490,12 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
466
490
  : getFingerprintDistance(runtime.distinctStates, runtime.generatedStates, (visit) =>
467
491
  visit(
468
492
  search
469
- ? search.getStoredFingerprints(states, fingerprintStates)
493
+ ? search.getStoredFingerprints(
494
+ exploredStates.length === 0 ? states : states.concat(exploredStates),
495
+ exploredStates.length === 0
496
+ ? fingerprintStates
497
+ : fingerprintStates.concat(exploredFingerprintStates),
498
+ )
470
499
  : BigInt64Array.from(states, runtime.getFingerprint),
471
500
  ),
472
501
  ),
@@ -479,6 +508,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
479
508
  () => created.order.getDeclarationOrder("variable"),
480
509
  options.onProgress,
481
510
  specification.moduleOperators,
511
+ specification.runtimeInvariants,
482
512
  );
483
513
  const findViolatedAssumption = () =>
484
514
  findAssumptionViolation(specification.assumptions, environment);
@@ -500,19 +530,24 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
500
530
  specification.moduleOperators.some((operator) => operator.kind === "postcondition");
501
531
  const tracedSteps = new WeakMap<TraceStep, TracedStep>();
502
532
  const getStepState = (step: TraceStep) => tracedSteps.get(step)?.state ?? step.state;
533
+ // TLC's Worker#doPostCondition and LiveCheck bind CounterExample to the alias of each state, while its initial states and lassos keep the states.
534
+ const getStepAlias = (step: TraceStep) => tracedSteps.get(step)?.alias ?? step.state;
503
535
  const getStepAction = (step: TraceStep) => {
504
536
  const action = tracedSteps.get(step)?.action;
505
537
  return action ? toActionValue(action) : createActionRecord(step.action);
506
538
  };
507
539
  const checkTracePostconditions = (
508
540
  trace: TraceStep[],
509
- loop: { start: number; action: Value } | undefined,
541
+ loop: CounterExampleLoop | undefined,
542
+ getState: (step: TraceStep) => Record<string, Value>,
543
+ isConsole = true,
510
544
  ) => {
511
545
  if (hasPostconditions) {
512
546
  runtime.counterExample = createCounterExample(
513
- trace.map(getStepState),
547
+ trace.map(getState),
514
548
  trace.slice(1).map(getStepAction),
515
549
  loop,
550
+ isConsole,
516
551
  );
517
552
  }
518
553
  const unwitnessed = search.findUnwitnessedPossible();
@@ -524,12 +559,14 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
524
559
  const reportViolation = (
525
560
  status: CheckStatus,
526
561
  violation: ReportedViolation,
562
+ getState = getStepAlias,
527
563
  getLoopAction?: () => Value,
528
564
  ) => {
529
565
  const start = violation.loopStart;
530
566
  const checked = checkTracePostconditions(
531
567
  violation.trace,
532
568
  start === undefined || !getLoopAction ? undefined : { start, action: getLoopAction() },
569
+ getState,
533
570
  );
534
571
  return createResult(status, {
535
572
  ...violation,
@@ -555,12 +592,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
555
592
  const getFingerprintState = search.getFingerprintState;
556
593
  // Tool's constructor splits the next-state relation into actions before TLC checks anything.
557
594
  const nextActions = getDescription().actions;
558
- runtime.getSuccessorAction = (state, next) =>
559
- nextActions.find((action) =>
560
- getSuccessors(action.expression, state, environment, action.scope).some((successor) =>
561
- successor.state.every((value, index) => isSameValue(value, next[index])),
562
- ),
563
- );
564
595
  const addCoverageRelations = (kind: "init" | "next", actions: SpecAction[]) =>
565
596
  actions.map((action): CoveredAction => ({
566
597
  ...action,
@@ -610,6 +641,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
610
641
  );
611
642
  return successors;
612
643
  };
644
+ // TLC generates the successors of each action again, which its coverage counts.
645
+ const findSuccessorAction = (state: Value[], isMatch: (successor: Successor) => boolean) =>
646
+ coverage
647
+ ? coverageActions.find((item) => getCoveredSuccessors(item, state).some(isMatch))
648
+ : nextActions.find((item) =>
649
+ getSuccessors(item.expression, state, environment, item.scope).some(isMatch),
650
+ );
651
+ runtime.getSuccessorAction = (state, next) =>
652
+ findSuccessorAction(state, (successor) =>
653
+ successor.state.every((value, index) => isSameValue(value, next[index])),
654
+ );
613
655
  const rejectIncompleteInitialState = (partial: (Value | undefined)[]) => {
614
656
  throw setExitCode(new TlaIllegalStateError([...partial]), EXIT_STATUS.error);
615
657
  };
@@ -628,8 +670,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
628
670
  return (state: Value[], callStack: CallStack | undefined) => {
629
671
  fingerprintReplayed(state, getFingerprintState(state), callStack);
630
672
  const fingerprintState = getFingerprintState(state);
673
+ const hash = getStateHash(fingerprintState);
631
674
  const isSeen =
632
- findStateIndex(seenStates, getStateHash(fingerprintState), fingerprintState) !== -1 ||
675
+ findStateIndex(seenStates, hash, fingerprintState) !== -1 ||
676
+ isExplored(hash, fingerprintState) ||
633
677
  replayed.some((seen) => isSameState(seen, fingerprintState));
634
678
  if (isSeen) return false;
635
679
  replayed.push(fingerprintState);
@@ -653,16 +697,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
653
697
  runtime.queueSize++;
654
698
  liveness?.addInitialState(states.length, state, tracing);
655
699
  };
656
- const violation = search.checkReplayedInitialState(state, tracing, addFingerprint);
657
- if (violation) {
700
+ search.checkReplayedInitialState(state, tracing, addFingerprint, (violation) => {
658
701
  const traced = traces.toTrace([{ action: undefined, state }], []).trace[0].state;
659
702
  capturedLines?.push({
660
703
  kind: "initial-state-violation",
661
704
  ...violation,
662
705
  state: traced,
663
706
  });
664
- throw STOP_REPLAY;
665
- }
707
+ if (!options.isContinued || violation.status !== "invariant-violation") {
708
+ throw STOP_REPLAY;
709
+ }
710
+ });
666
711
  } catch (error) {
667
712
  const isFingerprintFailure =
668
713
  error instanceof TlaEvaluationError && tracing.callStack?.fingerprint !== undefined;
@@ -711,37 +756,50 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
711
756
  (tlcFingerprints[successor.index] ??= Number(
712
757
  BigInt.asIntN(32, runtime.getFingerprint(successor.state)),
713
758
  )),
714
- getSuccessors: (source, state) => {
715
- const successors: LiveSuccessor[] = [];
716
- if (spec.next === undefined) return successors;
717
- const livenessSource = current.livenessSource;
718
- current.livenessSource = source;
719
- try {
720
- forEachSuccessor(
721
- spec.next,
722
- state,
723
- environment,
724
- (successor) => {
725
- canonicalizeState(successor.state);
726
- const isInModel =
727
- search.satisfiesConstraints(successor.state, state) &&
728
- search.satisfiesActionConstraints(state, successor.state);
729
- if (!isInModel) return false;
730
- const fingerprintState = getFingerprintState(successor.state);
731
- const hash = getStateHash(fingerprintState);
732
- const index = findStateIndex(seenStates, hash, fingerprintState);
733
- successors.push({
734
- index: index === -1 ? getPendingIndex(hash, fingerprintState) : index,
735
- state: successor.state,
736
- });
737
- return false;
738
- },
739
- spec.scope,
740
- );
741
- } finally {
742
- current.livenessSource = livenessSource;
759
+ forEachActionSuccessors: (source, state, onSuccessors) => {
760
+ let successors: LiveSuccessor[] = [];
761
+ const addSuccessor = (successor: Value[]) => {
762
+ canonicalizeState(successor);
763
+ const isInModel =
764
+ search.satisfiesConstraints(successor, state) &&
765
+ search.satisfiesActionConstraints(state, successor);
766
+ if (!isInModel) return;
767
+ const fingerprintState = getFingerprintState(successor);
768
+ const hash = getStateHash(fingerprintState);
769
+ const index = findStateIndex(seenStates, hash, fingerprintState);
770
+ successors.push({
771
+ index: index === -1 ? getPendingIndex(hash, fingerprintState) : index,
772
+ state: successor,
773
+ });
774
+ };
775
+ const visitSuccessor = (successor: Successor) => {
776
+ addSuccessor(successor.state);
777
+ return false;
778
+ };
779
+ const actionCount = coverage ? coverageActions.length : nextActions.length;
780
+ for (let position = 0; position < actionCount; position++) {
781
+ successors = [];
782
+ const livenessSource = current.livenessSource;
783
+ current.livenessSource = source;
784
+ try {
785
+ // TLC's coverage counts the successors of each action the graph generates again.
786
+ if (coverage) {
787
+ walkCoveredSuccessors(coverageActions[position], state, addSuccessor);
788
+ } else {
789
+ const action = nextActions[position];
790
+ forEachSuccessor(
791
+ action.expression,
792
+ state,
793
+ environment,
794
+ visitSuccessor,
795
+ action.scope,
796
+ );
797
+ }
798
+ } finally {
799
+ current.livenessSource = livenessSource;
800
+ }
801
+ onSuccessors(successors);
743
802
  }
744
- return successors;
745
803
  },
746
804
  }),
747
805
  ),
@@ -756,6 +814,11 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
756
814
  const actions: (string | undefined)[] = [];
757
815
  const depths: number[] = [];
758
816
  const seenStates = createStateTable(fingerprintStates);
817
+ const exploredStates: Value[][] = [];
818
+ const exploredFingerprintStates: Value[][] = [];
819
+ let exploredTable: StateTable | undefined;
820
+ const isExplored = (hash: number, fingerprintState: Value[]) =>
821
+ exploredTable !== undefined && findStateIndex(exploredTable, hash, fingerprintState) !== -1;
759
822
  const pendingFingerprintStates: Value[][] = [];
760
823
  let pendingStates: StateTable | undefined;
761
824
  const getPendingIndex = (hash: number, fingerprintState: Value[]) => {
@@ -787,13 +850,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
787
850
  failed: unknown,
788
851
  behavior: Behavior,
789
852
  failureOptions: FailureOptions = {},
853
+ counterExample?: CounterExampleOptions,
790
854
  ) => {
791
855
  const error = isStackOverflow(failed) ? new TlaStackOverflowError() : failed;
792
856
  if (!(error instanceof TlaEvaluationError)) throw error;
793
857
  const checked =
794
- behavior.trace.length > 0 && !failureOptions.traceFailure
795
- ? checkTracePostconditions(behavior.trace, undefined)
796
- : undefined;
858
+ counterExample &&
859
+ checkTracePostconditions(behavior.trace, undefined, getStepAlias, counterExample.isConsole);
797
860
  const postcondition = checked?.unwitnessed ?? checked?.postcondition;
798
861
  const traceOutput = [...(behavior.traceOutput ?? []), ...(checked?.lines ?? [])];
799
862
  return {
@@ -818,29 +881,61 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
818
881
  outDegrees: failureOptions.outDegrees,
819
882
  };
820
883
  };
821
- const reportIncompleteSuccessor = (index: number, error: TlaIncompleteSuccessorError) => {
884
+ // Deviation from TLC: Worker#doPostCondition throws an ArrayIndexOutOfBoundsException at an incomplete successor, where tla-ts checks the postconditions with the successor in CounterExample.
885
+ const reportIncompleteSuccessor = (
886
+ index: number,
887
+ error: TlaIncompleteSuccessorError,
888
+ liveSuccessors: LiveSuccessor[],
889
+ ) => {
822
890
  runtime.generatedStates++;
823
- const named =
824
- nextActions.length === 1
825
- ? nextActions
826
- : nextActions.filter((item) => item.name === error.action);
827
- const action =
828
- named.length === 1
829
- ? named[0]
830
- : captureOutput(() =>
831
- named.find((item) =>
832
- hasIncompleteSuccessor(item.expression, states[index], environment, item.scope),
833
- ),
834
- ).result;
891
+ const found = captureOutput(() => {
892
+ try {
893
+ return {
894
+ action: nextActions.find((item) =>
895
+ hasIncompleteSuccessor(item.expression, states[index], environment, item.scope),
896
+ ),
897
+ traceFailure: undefined,
898
+ };
899
+ } catch (failed) {
900
+ if (!(failed instanceof TlaEvaluationError)) throw failed;
901
+ return { action: undefined, traceFailure: getTraceFailure(failed) };
902
+ }
903
+ });
904
+ const action = found.result.action;
905
+ const traceFailure = found.result.traceFailure;
835
906
  const message = getIncompleteSuccessorMessage(
836
907
  error.variables,
837
908
  error.action,
838
909
  nextActions.length,
839
910
  options.version,
840
911
  );
841
- const undefinedValue = createModelValue("null");
842
- const partial = error.state.map((value) => value ?? undefinedValue);
843
- const failure = createFailureResult(error, traces.getStateTrace(index));
912
+ const live = captureOutput(() => addFailedLiveState(index, liveSuccessors));
913
+ const trace = traces.getStateTrace(index, error.state).trace;
914
+ const failure = createFailureResult(
915
+ error,
916
+ appendTraceOutput(
917
+ {
918
+ trace: traceFailure
919
+ ? trace
920
+ : [
921
+ ...trace,
922
+ traces.getIncompleteStep(
923
+ error.state,
924
+ trace.length + 1,
925
+ {
926
+ action: error.action,
927
+ label: action && getActionLabel(action, options.version),
928
+ output: found.lines,
929
+ },
930
+ action,
931
+ ),
932
+ ],
933
+ },
934
+ live.lines,
935
+ ),
936
+ { callStack: live.result, traceFailure },
937
+ { isConsole: true },
938
+ );
844
939
  return withOutDegrees({
845
940
  ...failure,
846
941
  failure: failure.failure && {
@@ -849,14 +944,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
849
944
  message,
850
945
  toolMessage: message,
851
946
  exitCode: EXIT_STATUS.specEvaluationFailure,
852
- trace: [
853
- ...failure.failure.trace,
854
- {
855
- action: error.action,
856
- label: action && getActionLabel(action, options.version),
857
- state: toRecord(partial),
858
- },
859
- ],
860
947
  },
861
948
  });
862
949
  };
@@ -868,7 +955,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
868
955
  };
869
956
  let unstoredFingerprint: Value[] | undefined;
870
957
  const countDistinctState = (depth: number) => {
871
- runtime.distinctStates = states.length + 1;
958
+ runtime.distinctStates = states.length + exploredStates.length + 1;
872
959
  searchDepth = Math.max(searchDepth, depth);
873
960
  runtime.diameter = Math.max(runtime.diameter, depth);
874
961
  };
@@ -909,24 +996,34 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
909
996
  tracedSteps,
910
997
  captureOutput,
911
998
  getInitialStates: getSpecInitialStates,
912
- findSuccessorAction: (state, isMatch) =>
913
- coverage
914
- ? coverageActions.find((item) => getCoveredSuccessors(item, state).some(isMatch))
915
- : nextActions.find((item) =>
916
- getSuccessors(item.expression, state, environment, item.scope).some(isMatch),
917
- ),
999
+ findSuccessorAction,
918
1000
  });
919
1001
  const getPath = (index: number): Value[][] =>
920
1002
  index === -1 ? [] : [...getPath(parents[index]), states[index]];
1003
+ // TLC adds a successor's fingerprint to its set before it checks the invariants of the successor.
921
1004
  runtime.isSeen = (state) => {
922
1005
  const fingerprintState = getFingerprintState(state);
923
- return findStateIndex(seenStates, getStateHash(fingerprintState), fingerprintState) !== -1;
1006
+ const hash = getStateHash(fingerprintState);
1007
+ return (
1008
+ findStateIndex(seenStates, hash, fingerprintState) !== -1 ||
1009
+ isExplored(hash, fingerprintState) ||
1010
+ (unstoredFingerprint !== undefined && isSameState(unstoredFingerprint, fingerprintState))
1011
+ );
1012
+ };
1013
+ runtime.markExplored = (state) => {
1014
+ const fingerprintState = getFingerprintState(state);
1015
+ exploredTable ??= createStateTable(exploredFingerprintStates);
1016
+ markSeenState(exploredTable, getStateHash(fingerprintState), exploredStates.length);
1017
+ exploredStates.push(state);
1018
+ exploredFingerprintStates.push(fingerprintState);
1019
+ runtime.distinctStates++;
924
1020
  };
925
1021
  runtime.getBehavior = (state) => {
926
1022
  const index = state === current.candidate ? -1 : states.indexOf(state);
927
1023
  return index === -1 ? [...getPath(current.index), state] : getPath(index);
928
1024
  };
929
- runtime.getCurrentState = () => (current.index === -1 ? undefined : states[current.index]);
1025
+ runtime.getCurrentState = () =>
1026
+ current.rebuilt?.state ?? (current.index === -1 ? undefined : states[current.index]);
930
1027
  runtime.setLivenessSource = (index) => {
931
1028
  current.livenessSource = index ?? -1;
932
1029
  };
@@ -985,7 +1082,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
985
1082
  stateWriter?.writeInitialState(getGraphState(state, 1));
986
1083
  }
987
1084
  if (options.isContinued) {
988
- search.getViolatedInvariants(state).forEach((invariant) =>
1085
+ search.forEachViolatedInvariant(state, (invariant) =>
989
1086
  reportContinuedViolation("invariant-violation", {
990
1087
  name: invariant.name,
991
1088
  ...traces.toTrace([{ action: undefined, state }], []),
@@ -994,17 +1091,19 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
994
1091
  }
995
1092
  const violated = options.isContinued ? undefined : search.findViolatedInvariant(state);
996
1093
  if (violated) {
997
- return reportViolation("invariant-violation", {
998
- name: violated.name,
999
- ...traces.toTrace([{ action: undefined, state }], []),
1000
- });
1094
+ return reportViolation(
1095
+ "invariant-violation",
1096
+ { name: violated.name, ...traces.toTrace([{ action: undefined, state }], []) },
1097
+ getStepState,
1098
+ );
1001
1099
  }
1002
1100
  const failedPredicate = search.findFailedInitialPredicate(state);
1003
1101
  if (failedPredicate) {
1004
- return reportViolation("liveness-violation", {
1005
- name: failedPredicate.name,
1006
- ...traces.toTrace([{ action: undefined, state }], []),
1007
- });
1102
+ return reportViolation(
1103
+ "liveness-violation",
1104
+ { name: failedPredicate.name, ...traces.toTrace([{ action: undefined, state }], []) },
1105
+ getStepState,
1106
+ );
1008
1107
  }
1009
1108
  if (!isInModel) return undefined;
1010
1109
  markSeenState(seenStates, hash, states.length);
@@ -1025,7 +1124,14 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1025
1124
  fingerprintModelState(fingerprintState);
1026
1125
  successor.state.forEach(markFingerprinted);
1027
1126
  }
1028
- return { fingerprintState, hash, isInModel, existing: isInModel ? foundIndex : -1 };
1127
+ const existing = isInModel ? foundIndex : -1;
1128
+ return {
1129
+ fingerprintState,
1130
+ hash,
1131
+ isInModel,
1132
+ existing,
1133
+ isSeen: existing !== -1 || (isInModel && isExplored(hash, fingerprintState)),
1134
+ };
1029
1135
  };
1030
1136
  const visitSuccessor = (
1031
1137
  index: number,
@@ -1044,7 +1150,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1044
1150
  stateWriter?.writeSuccessor(
1045
1151
  source,
1046
1152
  getGraphState(successor.state, depths[index] + 1),
1047
- found.existing !== -1,
1153
+ found.isSeen,
1048
1154
  action && getGraphAction(action),
1049
1155
  );
1050
1156
  }
@@ -1066,7 +1172,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1066
1172
  const isStored = stored.every((value, position) => value === successor.state[position]);
1067
1173
  liveSuccessors.push({ index: found.existing, state: isStored ? stored : successor.state });
1068
1174
  }
1069
- const isNew = found.isInModel && found.existing === -1;
1175
+ if (found.isSeen && found.existing === -1 && liveness) {
1176
+ liveSuccessors.push({
1177
+ index: getPendingIndex(found.hash, found.fingerprintState),
1178
+ state: successor.state,
1179
+ });
1180
+ }
1181
+ const isNew = found.isInModel && !found.isSeen;
1070
1182
  if (isNew && liveness) liveSuccessors.push({ index: states.length, state: successor.state });
1071
1183
  unstoredFingerprint = isNew ? found.fingerprintState : undefined;
1072
1184
  if (isNew) {
@@ -1074,7 +1186,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1074
1186
  newStateCount++;
1075
1187
  if (coverage) coverage.secondary[coveredNode]++;
1076
1188
  }
1077
- if (found.existing === -1) {
1189
+ if (!found.isSeen) {
1078
1190
  try {
1079
1191
  const violated = search.findViolatedInvariant(successor.state, state);
1080
1192
  const violation = violated && { name: violated.name, ...traces.getTrace(index, successor) };
@@ -1156,7 +1268,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1156
1268
  kind: "liveness-started",
1157
1269
  branches: liveness.branches,
1158
1270
  isComplete: true,
1159
- states: typed.distinctStates,
1271
+ states: liveness.branches * typed.distinctStates,
1160
1272
  statistics,
1161
1273
  });
1162
1274
  options.onProgress?.({ kind: "liveness-finished" });
@@ -1220,14 +1332,29 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1220
1332
  }
1221
1333
  } catch (error) {
1222
1334
  if (error instanceof TlaIllegalStateError) {
1335
+ reportInitialStatesProgress(runtime.initialStates, options.onProgress);
1336
+ runtime.generatedStates++;
1337
+ runtime.initialStates++;
1338
+ const state = error.state.map((value) => value ?? createModelValue("null"));
1339
+ // Deviation from TLC: CounterExample holds a Java null for an unassigned variable and leaks a NullPointerException, where tla-ts binds the model value null.
1340
+ const checked = checkTracePostconditions(
1341
+ [{ action: undefined, label: undefined, state: toRecord(state) }],
1342
+ undefined,
1343
+ getStepState,
1344
+ );
1345
+ const postcondition = checked.unwitnessed ?? checked.postcondition;
1223
1346
  const illegal = createFailureResult(
1224
1347
  error,
1225
- { trace: [] },
1226
- { initialState: error.state.map((value) => value ?? createModelValue("null")) },
1348
+ { trace: [], traceOutput: checked.lines },
1349
+ { initialState: state },
1227
1350
  );
1228
1351
  return {
1229
1352
  ...illegal,
1230
- failure: illegal.failure && { ...illegal.failure, isWithoutStatistics: true },
1353
+ failure: illegal.failure && {
1354
+ ...illegal.failure,
1355
+ isWithoutStatistics: true,
1356
+ ...(postcondition && { postcondition }),
1357
+ },
1231
1358
  };
1232
1359
  }
1233
1360
  const replay = captureOutput(replayInit);
@@ -1313,6 +1440,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1313
1440
  );
1314
1441
  }, 0);
1315
1442
  };
1443
+ // Deviation from TLC: Worker#doNextCheckLiveness doesn't catch a FingerprintException from its rerun, so TLC prints the behavior without the failure.
1316
1444
  const getLiveCallStack = (index: number, liveSuccessors: LiveSuccessor[]) => {
1317
1445
  if (!liveness || is174) return undefined;
1318
1446
  const replay = getReplayFailure(environment, (tracing) =>
@@ -1338,21 +1466,82 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1338
1466
  const replay = captureOutput(() => replayNext(index));
1339
1467
  return { result: replay.result, lines: [...live.lines, ...replay.lines] };
1340
1468
  };
1341
- const reportNextStateOverflow = (index: number) =>
1342
- createFailureResult(createStackOverflowError(), traces.getStateTrace(index), { phase: "next" });
1469
+ const getNextFailureTrace = (index: number, counterExample?: CounterExampleOptions) => {
1470
+ const behavior = traces.getStateTrace(index);
1471
+ return counterExample ? behavior : { trace: behavior.trace };
1472
+ };
1473
+ const reportNextStateOverflow = (index: number, counterExample?: CounterExampleOptions) =>
1474
+ createFailureResult(
1475
+ createStackOverflowError(),
1476
+ getNextFailureTrace(index, counterExample),
1477
+ { phase: "next" },
1478
+ counterExample,
1479
+ );
1480
+ // 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.
1343
1481
  const reportNextStateFailure = (
1344
1482
  error: unknown,
1345
1483
  index: number,
1346
1484
  liveSuccessors: LiveSuccessor[],
1485
+ generated: number,
1347
1486
  ) => {
1348
- if (isStackOverflow(error)) return reportNextStateOverflow(index);
1487
+ // TLC's Worker goes on to find a state without successors deadlocked after it fails, which checks the postconditions.
1488
+ const counterExample =
1489
+ config.checkDeadlock && runtime.generatedStates === generated
1490
+ ? { isConsole: false }
1491
+ : undefined;
1492
+ if (isStackOverflow(error)) return reportNextStateOverflow(index, counterExample);
1349
1493
  const replay = replayFailedNext(index, liveSuccessors);
1350
1494
  return createFailureResult(
1351
1495
  withNextStateExitCode(error),
1352
- appendTraceOutput(traces.getStateTrace(index), replay.lines),
1496
+ appendTraceOutput(getNextFailureTrace(index, counterExample), replay.lines),
1353
1497
  { phase: "next", ...replay.result },
1498
+ counterExample,
1354
1499
  );
1355
1500
  };
1501
+ const addLiveState = (
1502
+ index: number,
1503
+ liveSuccessors: LiveSuccessor[],
1504
+ source: GraphState | undefined,
1505
+ ) => {
1506
+ if (liveness && source && (is174 || options.dump?.stuttering)) {
1507
+ stateWriter?.writeStuttering(source);
1508
+ }
1509
+ const accepted = liveness?.addState(index, states[index], liveSuccessors);
1510
+ if (!liveness || !accepted) return undefined;
1511
+ // Deviation from TLC: under -continue, TLC's LiveCheck throws an InvariantViolatedException after it reports the property, which its Worker reports as unexpected.
1512
+ const steps = traces.getPathSteps(accepted);
1513
+ const properties = getViolatedProperties(
1514
+ liveness,
1515
+ steps.map((step) => step.state),
1516
+ steps.length - 1,
1517
+ );
1518
+ return reportViolation("property-violation", {
1519
+ name: properties[0],
1520
+ properties,
1521
+ ...traces.toTrace(steps, accepted, { known: 0 }),
1522
+ });
1523
+ };
1524
+ const addReportedLiveState = (
1525
+ index: number,
1526
+ liveSuccessors: LiveSuccessor[],
1527
+ source: GraphState | undefined,
1528
+ ) =>
1529
+ captureOutput(() => {
1530
+ try {
1531
+ return {
1532
+ additional: addLiveState(index, liveSuccessors, source)?.violation,
1533
+ isFailed: false,
1534
+ callStack: undefined,
1535
+ };
1536
+ } catch (error) {
1537
+ if (!(error instanceof TlaEvaluationError)) throw error;
1538
+ return {
1539
+ additional: undefined,
1540
+ isFailed: true,
1541
+ callStack: getLiveCallStack(index, liveSuccessors),
1542
+ };
1543
+ }
1544
+ });
1356
1545
  const expandState = (index: number, liveSuccessors: LiveSuccessor[]) => {
1357
1546
  const state = states[index];
1358
1547
  const source = stateWriter && getGraphState(state, depths[index]);
@@ -1387,14 +1576,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1387
1576
  }
1388
1577
  const isTraceFailed = isUnfingerprintable(successor.state);
1389
1578
  const traceFailure =
1390
- isTraceFailed && error instanceof TlaEvaluationError
1391
- ? getFailureMessage(
1392
- isEvalException(error)
1393
- ? new TlaEvaluationError(`${UNEXPECTED_EVAL_EXCEPTION}${error.message}`)
1394
- : error,
1395
- true,
1396
- )
1397
- : undefined;
1579
+ isTraceFailed && error instanceof TlaEvaluationError ? getTraceFailure(error) : undefined;
1398
1580
  outcome = createFailureResult(
1399
1581
  error,
1400
1582
  appendTraceOutput(
@@ -1409,45 +1591,23 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1409
1591
  current.isExpanding = false;
1410
1592
  const result = outcome;
1411
1593
  if (result?.violation && !is174) {
1412
- const live = captureOutput(() => addFailedLiveState(index, liveSuccessors));
1594
+ const live = addReportedLiveState(index, liveSuccessors, source);
1413
1595
  return {
1414
1596
  ...result,
1415
1597
  violation: appendTraceOutput(result.violation, live.lines),
1416
- ...(live.result && { liveCallStack: live.result }),
1598
+ // TLC adds the state to the behavior graph before it reports the coverage.
1599
+ coverage: getCoverage(),
1600
+ ...(live.result.additional && { additionalViolation: live.result.additional }),
1601
+ ...(live.result.callStack && { liveCallStack: live.result.callStack }),
1417
1602
  };
1418
1603
  }
1419
1604
  if (result) return result;
1420
- const addLiveState = () => {
1421
- if (liveness && source && (is174 || options.dump?.stuttering)) {
1422
- stateWriter?.writeStuttering(source);
1423
- }
1424
- const accepted = liveness?.addState(index, state, liveSuccessors);
1425
- if (!liveness || !accepted) return undefined;
1426
- const steps = traces.getPathSteps(accepted);
1427
- const properties = getViolatedProperties(
1428
- liveness,
1429
- steps.map((step) => step.state),
1430
- steps.length - 1,
1431
- );
1432
- return reportViolation("property-violation", {
1433
- name: properties[0],
1434
- properties,
1435
- ...traces.toTrace(steps, accepted, { known: 0 }),
1436
- });
1437
- };
1438
1605
  if (successorCount === 0 && config.checkDeadlock) {
1439
1606
  const deadlock = reportViolation("deadlock", {
1440
1607
  name: "deadlock",
1441
1608
  ...traces.getStateTrace(index),
1442
1609
  });
1443
- const live = captureOutput(() => {
1444
- try {
1445
- return { additional: addLiveState()?.violation };
1446
- } catch (error) {
1447
- if (!(error instanceof TlaEvaluationError)) throw error;
1448
- return { isFailed: true, callStack: getLiveCallStack(index, liveSuccessors) };
1449
- }
1450
- });
1610
+ const live = addReportedLiveState(index, liveSuccessors, source);
1451
1611
  const reported = deadlock.violation
1452
1612
  ? { ...deadlock, violation: appendTraceOutput(deadlock.violation, live.lines) }
1453
1613
  : deadlock;
@@ -1460,14 +1620,11 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1460
1620
  return live.result.callStack ? { ...counted, liveCallStack: live.result.callStack } : counted;
1461
1621
  }
1462
1622
  try {
1463
- return addLiveState();
1623
+ return addLiveState(index, liveSuccessors, source);
1464
1624
  } catch (error) {
1465
1625
  if (is174 && error instanceof TlaEvaluationError) {
1466
- const unexpected = new TlaEvaluationError(
1467
- `${isEvalException(error) ? UNEXPECTED_EVAL_EXCEPTION : UNEXPECTED_EXCEPTION}${error.message}`,
1468
- );
1469
1626
  return createFailureResult(
1470
- setExitCode(unexpected, EXIT_STATUS.error),
1627
+ setExitCode(toUnexpectedError(error), EXIT_STATUS.error),
1471
1628
  { trace: [] },
1472
1629
  { outDegrees: getFailureOutDegrees() },
1473
1630
  );
@@ -1499,10 +1656,20 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1499
1656
  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}`,
1500
1657
  };
1501
1658
  };
1659
+ const toLivenessFailure = (error: TlaEvaluationError) =>
1660
+ setExitCode(toUnexpectedError(error), EXIT_STATUS.abort);
1661
+ const getLassoSteps = (path: number[]) => {
1662
+ try {
1663
+ return traces.getPathSteps(path);
1664
+ } catch (error) {
1665
+ if (!(error instanceof TlaEvaluationError)) throw error;
1666
+ throw toLivenessFailure(error);
1667
+ }
1668
+ };
1502
1669
  const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1503
1670
  const path = [...lasso.prefix, ...lasso.cycle];
1504
1671
  const loopStart = lasso.prefix.length;
1505
- const steps = traces.getPathSteps(path, loopStart);
1672
+ const steps = getLassoSteps(path);
1506
1673
  const trace = traces.toTrace(steps, path, { loopStart, known: 0 }).trace;
1507
1674
  const properties = getViolatedProperties(
1508
1675
  checker,
@@ -1512,13 +1679,28 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1512
1679
  const cycleStart = path[loopStart];
1513
1680
  const cycleEnd = path[path.length - 1];
1514
1681
  const lastState = steps[steps.length - 1].state;
1515
- const loop =
1516
- cycleStart === cycleEnd
1517
- ? { result: undefined, lines: [] }
1518
- : captureOutput(() =>
1519
- traces.findStepAction(cycleEnd, lastState, states[cycleStart], false),
1520
- );
1521
- const isStutteringWarned = cycleStart === cycleEnd && lasso.isCycleConstrained;
1682
+ const isStuttering = cycleStart === cycleEnd;
1683
+ const loop = isStuttering
1684
+ ? { result: undefined, lines: [] }
1685
+ : captureOutput(() => traces.findStepAction(cycleEnd, lastState, states[cycleStart], false));
1686
+ const back =
1687
+ isStuttering || loop.result
1688
+ ? undefined
1689
+ : traces.findSuccessorWithFingerprint(lastState, cycleEnd, cycleStart);
1690
+ if (!isStuttering && !loop.result && !back) {
1691
+ options.onProgress?.({
1692
+ kind: "violation",
1693
+ status: "property-violation",
1694
+ violation: {
1695
+ name: properties[0],
1696
+ properties,
1697
+ trace,
1698
+ traceOutput: loop.lines,
1699
+ loopStart: undefined,
1700
+ },
1701
+ });
1702
+ throw toLivenessFailure(new TlaEvaluationError(NEXT_RECOVERY_FAILURE));
1703
+ }
1522
1704
  return reportViolation(
1523
1705
  "liveness-violation",
1524
1706
  {
@@ -1528,40 +1710,44 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1528
1710
  traceOutput: loop.lines,
1529
1711
  loopStart,
1530
1712
  loopLabel: loop.result && getActionLabel(loop.result, options.version),
1531
- warning: isStutteringWarned ? getStutteringWarning() : undefined,
1713
+ warning: isStuttering && lasso.isCycleConstrained ? getStutteringWarning() : undefined,
1532
1714
  },
1715
+ getStepState,
1533
1716
  () =>
1534
- cycleStart === cycleEnd
1717
+ isStuttering
1535
1718
  ? getStepAction(trace[trace.length - 1])
1536
1719
  : loop.result
1537
1720
  ? toActionValue(loop.result)
1538
- : createActionRecord(
1539
- traces.findSuccessorWithFingerprint(lastState, cycleStart)?.action,
1540
- ),
1721
+ : createActionRecord(back?.action),
1541
1722
  );
1542
1723
  };
1543
1724
  const isPeriodic = liveness !== undefined && (options.livenessCheck ?? "default") === "default";
1544
1725
  const startedAt = performance.now();
1545
1726
  const periodic = {
1546
1727
  at: startedAt + PERIODIC_START,
1547
- size: 1,
1728
+ checkedCounts: liveness?.getStateCounts().map(() => 1) ?? [],
1548
1729
  time: 0,
1549
1730
  coverageCount: Math.trunc(options.coverage ?? 0),
1550
1731
  };
1551
- const findPeriodicViolation = (expanded: number) => {
1732
+ const getGraphStates = (checker: LivenessChecker) =>
1733
+ checker.getStateCounts().reduce((sum, count) => sum + count, 0);
1734
+ const findPeriodicViolation = (checker: LivenessChecker) => {
1552
1735
  const now = performance.now();
1553
- const isGrown = (expanded - periodic.size) / periodic.size > LIVENESS_GROWTH;
1736
+ const counts = checker.getStateCounts();
1737
+ const isGrown = counts.some(
1738
+ (count, branch) =>
1739
+ (count - periodic.checkedCounts[branch]) / periodic.checkedCounts[branch] > LIVENESS_GROWTH,
1740
+ );
1554
1741
  if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1555
- periodic.size = expanded;
1556
- if (!liveness) return undefined;
1742
+ periodic.checkedCounts = counts;
1557
1743
  options.onProgress?.({
1558
1744
  kind: "liveness-started",
1559
- branches: liveness.branches,
1745
+ branches: checker.branches,
1560
1746
  isComplete: false,
1561
- states: expanded,
1747
+ states: getGraphStates(checker),
1562
1748
  statistics: createResult("success"),
1563
1749
  });
1564
- const lasso = liveness.findViolation();
1750
+ const lasso = checker.findViolation();
1565
1751
  if (!lasso) options.onProgress?.({ kind: "liveness-finished" });
1566
1752
  periodic.time += performance.now() - now;
1567
1753
  return lasso;
@@ -1674,20 +1860,21 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1674
1860
  runtime.queueSize = states.length - index - 1;
1675
1861
  current.isExpanding = true;
1676
1862
  const liveSuccessors: LiveSuccessor[] = [];
1863
+ const generated = runtime.generatedStates;
1677
1864
  try {
1678
1865
  outcome = expandState(index, liveSuccessors);
1679
1866
  } catch (error) {
1680
1867
  outcome =
1681
1868
  error instanceof TlaIncompleteSuccessorError
1682
- ? reportIncompleteSuccessor(index, error)
1683
- : reportNextStateFailure(error, index, liveSuccessors);
1869
+ ? reportIncompleteSuccessor(index, error, liveSuccessors)
1870
+ : reportNextStateFailure(error, index, liveSuccessors, generated);
1684
1871
  }
1685
1872
  if (outcome) return outcome;
1686
1873
  outDegrees[getOutDegreeBucket()]++;
1687
1874
  newStateCount = 0;
1688
1875
  if ((isPeriodic || options.onProgress) && performance.now() >= periodic.at) {
1689
1876
  periodic.at = performance.now() + PROGRESS_INTERVAL;
1690
- const lasso = isPeriodic ? findPeriodicViolation(index + 1) : undefined;
1877
+ const lasso = isPeriodic && liveness ? findPeriodicViolation(liveness) : undefined;
1691
1878
  if (liveness && lasso) return reportLasso(liveness, lasso);
1692
1879
  const isCoverageDue = options.coverage !== undefined && periodic.coverageCount === 0;
1693
1880
  periodic.coverageCount = isCoverageDue
@@ -1709,7 +1896,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1709
1896
  kind: "liveness-started",
1710
1897
  branches: finalLiveness.branches,
1711
1898
  isComplete: true,
1712
- states: runtime.distinctStates,
1899
+ states: typedLasso
1900
+ ? finalLiveness.branches * runtime.distinctStates
1901
+ : getGraphStates(finalLiveness),
1713
1902
  statistics: createResult("success"),
1714
1903
  });
1715
1904
  }