tla-ts 0.0.10-dev.28c823e4b → 0.0.10-dev.b4a856304

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 (68) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.d.cts +0 -34
  3. package/dist/index.d.ts +0 -34
  4. package/dist/index.js +1 -1
  5. package/dist/parallel-worker.cjs +1 -1
  6. package/dist/parallel-worker.js +1 -1
  7. package/dist/prove.cjs +43 -43
  8. package/dist/prove.js +47 -47
  9. package/dist/run.cjs +30 -30
  10. package/dist/run.js +33 -33
  11. package/dist/transfer.cjs +38 -38
  12. package/dist/transfer.js +39 -39
  13. package/package.json +1 -1
  14. package/src/ast.ts +5 -0
  15. package/src/bags.ts +5 -2
  16. package/src/builtins.ts +8 -1
  17. package/src/check.ts +193 -128
  18. package/src/cli/run.ts +2 -0
  19. package/src/cli/runtime-invariants.ts +7 -8
  20. package/src/cli/shared.ts +4 -0
  21. package/src/cli/tlc-arguments.ts +30 -24
  22. package/src/cli/tlc-usage.ts +3 -2
  23. package/src/evaluate.ts +102 -26
  24. package/src/java-overrides.ts +9 -4
  25. package/src/json-reader.ts +2 -1
  26. package/src/json.ts +11 -4
  27. package/src/levels.ts +15 -7
  28. package/src/lexer.ts +83 -72
  29. package/src/liveness-checker.ts +106 -77
  30. package/src/liveness.ts +34 -10
  31. package/src/parallel.ts +33 -26
  32. package/src/parser.ts +226 -163
  33. package/src/pcal/ast.ts +65 -53
  34. package/src/pcal/parse.ts +191 -144
  35. package/src/pcal/tokenize.ts +115 -91
  36. package/src/pcal/translate.ts +98 -83
  37. package/src/pcal/validate.ts +50 -48
  38. package/src/pretty-print.ts +6 -6
  39. package/src/randomization.ts +4 -1
  40. package/src/resolve.ts +70 -12
  41. package/src/runtime.ts +18 -11
  42. package/src/sany/builtins.ts +3 -1
  43. package/src/sany/generator.ts +127 -74
  44. package/src/sany/levels.ts +9 -5
  45. package/src/sany/lexer.ts +44 -40
  46. package/src/sany/linter.ts +1 -0
  47. package/src/search.ts +1 -1
  48. package/src/simulate.ts +59 -50
  49. package/src/spec-description.ts +34 -23
  50. package/src/standard-definitions.ts +3 -0
  51. package/src/standard-modules.ts +12 -1
  52. package/src/state-graph.ts +8 -1
  53. package/src/subexpressions.ts +47 -38
  54. package/src/successors.ts +35 -14
  55. package/src/symmetry.ts +19 -4
  56. package/src/tlc/fingerprint.ts +21 -15
  57. package/src/tlc/jar-data.ts +1 -0
  58. package/src/tlc/messages.ts +21 -2
  59. package/src/tlc/order.ts +38 -20
  60. package/src/tlc/random.ts +30 -18
  61. package/src/tlc/replay.ts +33 -13
  62. package/src/tlc/summary.ts +45 -36
  63. package/src/tlc/tlc-operators.ts +14 -4
  64. package/src/tlc/tlcext-operators.ts +15 -11
  65. package/src/tlc/trace-spec.ts +4 -0
  66. package/src/tlc/value-stream.ts +13 -9
  67. package/src/tlc/version.ts +1 -0
  68. package/src/values.ts +181 -74
package/src/check.ts CHANGED
@@ -21,11 +21,11 @@ import {
21
21
  TlaStackOverflowError,
22
22
  UNEXPECTED_EVAL_EXCEPTION,
23
23
  UNEXPECTED_EXCEPTION,
24
- formatRange,
25
24
  } from "./errors";
26
25
  import {
27
26
  createTracingEnvironment,
28
27
  describeRange,
28
+ formatRange,
29
29
  getDefinition,
30
30
  isImpure,
31
31
  type CallStack,
@@ -130,30 +130,30 @@ export interface CheckOptions {
130
130
  makeDirectory?: (path: string) => void;
131
131
  seed?: bigint;
132
132
  workers?: number;
133
- /** TLC's -lncheck: "final" checks liveness only on the complete graph, "off" never looks for a cycle. */
133
+ // TLC's -lncheck: "final" checks liveness only on the complete graph, "off" never looks for a cycle.
134
134
  livenessCheck?: "default" | "final" | "off";
135
- /** TLC's -fp: the index of the polynomial in TLC's FP64.Polys that fingerprints states. */
135
+ // TLC's -fp: the index of the polynomial in TLC's FP64.Polys that fingerprints states.
136
136
  fingerprintPolynomial?: number;
137
- /** False for TLC's -terse, which prints a lazy value, such as SUBSET S, without enumerating it. */
137
+ // False for TLC's -terse, which prints a lazy value, such as SUBSET S, without enumerating it.
138
138
  isLazyValueExpanded?: boolean;
139
- /** TLC's -view: prints each state as the value of the configuration's VIEW. */
139
+ // TLC's -view: prints each state as the value of the configuration's VIEW.
140
140
  isViewPrinted?: boolean;
141
- /** TLC's -maxSetSize: the most elements TLC enumerates into a set, or states into a list of them. */
141
+ // TLC's -maxSetSize: the most elements TLC enumerates into a set, or states into a list of them.
142
142
  maxSetSize?: number;
143
- /** TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile. */
143
+ // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
144
144
  dump?: StateDump;
145
- /** TLC's -tool, which changes the messages of TLC's errors. */
145
+ // TLC's -tool, which changes the messages of TLC's errors.
146
146
  isTool?: boolean;
147
- /** TLC's -continue: reports each violation through onProgress and goes on. */
147
+ // TLC's -continue: reports each violation through onProgress and goes on.
148
148
  isContinued?: boolean;
149
149
  moduleOperators?: ModuleOperator[];
150
- /** TLC's trace exploration spec, and the binary trace TLC records for it unless -noTEBin. */
150
+ // TLC's trace exploration spec, and the binary trace TLC records for it unless -noTEBin.
151
151
  traceSpec?: TraceSpecOptions;
152
- /** Whether the caller printed SANY's report, its warnings included, before the check. */
152
+ // Whether the caller printed SANY's report, its warnings included, before the check.
153
153
  isSanyReported?: boolean;
154
- /** False for TLC's -nowarning, which changes how TLC computes some successors. */
154
+ // False for TLC's -nowarning, which changes how TLC computes some successors.
155
155
  isWarningEnabled?: boolean;
156
- /** TLC's -coverage, in minutes. */
156
+ // TLC's -coverage, in minutes.
157
157
  coverage?: number;
158
158
  version?: TlcVersion;
159
159
  onProgress?: (progress: CheckProgress) => void;
@@ -176,6 +176,7 @@ export interface InitialStatesProgress {
176
176
  count: number;
177
177
  }
178
178
 
179
+ // A check TLC reports as violated before it stops replaying the initial states.
179
180
  export interface InitialStateViolation {
180
181
  kind: "initial-state-violation";
181
182
  status: "invariant-violation" | "liveness-violation";
@@ -183,6 +184,7 @@ export interface InitialStateViolation {
183
184
  state: Record<string, Value>;
184
185
  }
185
186
 
187
+ // A line the spec prints, or what TLC reports as it replays the initial states.
186
188
  export type OutputLine = string | InitialStatesProgress | InitialStateViolation;
187
189
 
188
190
  export type CheckProgress =
@@ -198,16 +200,17 @@ export type CheckProgress =
198
200
  | {
199
201
  kind: "liveness-started";
200
202
  branches: number;
201
- /** Whether TLC checks the complete state graph. */
203
+ // Whether TLC checks the complete state graph, and how many states of it each branch has.
202
204
  isComplete: boolean;
203
- /** How many states of the graph each branch has. */
204
205
  states: number;
205
206
  statistics: SearchStatistics;
206
207
  }
207
208
  | { kind: "liveness-finished" }
208
209
  | { kind: "sequential-fallback"; string: string }
209
210
  | { kind: "warning"; code: number; text: string }
211
+ // A violation that the search goes on past with -continue.
210
212
  | { kind: "violation"; status: CheckStatus; violation: Violation }
213
+ // A method of the class named after a module, which TLC reports as it loads the class.
211
214
  | ({ kind: "java-override" } & JavaOverride);
212
215
 
213
216
  export interface SearchStatistics extends Pick<
@@ -227,30 +230,30 @@ export type CheckStatus =
227
230
 
228
231
  export interface TraceStep {
229
232
  action: string | undefined;
230
- /** TLC's name, parameters and location for the action that took this step. */
233
+ // TLC's name, parameters and location for the action that took this step.
231
234
  label: string | undefined;
232
235
  state: Record<string, Value>;
233
- /** What the spec prints before this step as TLC rebuilds the trace, and before it for the first. */
236
+ // What the spec prints before this step as TLC rebuilds the trace, and before it for the first.
234
237
  output?: OutputLine[];
235
238
  }
236
239
 
237
240
  export interface Violation {
238
241
  name: string;
239
- /** Every temporal property that a liveness counterexample violates, in the configuration's order. */
242
+ // Every temporal property that a liveness counterexample violates, in the configuration's order.
240
243
  properties?: string[];
241
244
  trace: TraceStep[];
242
- /** What the spec prints after the trace, as TLC finds the lasso's step back or rebuilds the trace. */
245
+ // What the spec prints after the trace, as TLC finds the lasso's step back or rebuilds the trace.
243
246
  traceOutput?: OutputLine[];
244
- /** What the postconditions print, which TLC checks after the lasso's step back. */
247
+ // What the postconditions print, which TLC checks after the lasso's step back.
245
248
  postconditionOutput?: OutputLine[];
246
249
  loopStart: number | undefined;
247
250
  loopLabel?: string;
248
251
  message?: string;
249
252
  counts?: string;
250
253
  unwitnessed?: Postcondition;
251
- /** A POSTCONDITION that is false or fails, which TLC checks as it prints the counterexample. */
254
+ // A POSTCONDITION that is false or fails, which TLC checks as it prints the counterexample.
252
255
  postcondition?: Postcondition;
253
- /** What TLC warns about after a counterexample, with its code. */
256
+ // What TLC warns about after a counterexample, with its code.
254
257
  warning?: { code: number; text: string };
255
258
  }
256
259
 
@@ -261,7 +264,7 @@ export interface Postcondition {
261
264
  counts?: string;
262
265
  }
263
266
 
264
- /** An evaluation that failed during the search, with the behavior up to the state TLC was working on. */
267
+ // An evaluation that failed during the search, with the behavior up to the state TLC was working on.
265
268
  export interface EvaluationFailure {
266
269
  code: number;
267
270
  message: string;
@@ -270,17 +273,17 @@ export interface EvaluationFailure {
270
273
  traceOutput?: OutputLine[];
271
274
  initialState: Record<string, Value> | undefined;
272
275
  exitCode: number;
273
- /** The expressions TLC was evaluating, outermost first, when its replay finds them. */
276
+ // The expressions TLC was evaluating, outermost first, when its replay finds them.
274
277
  callStack: Expression[] | undefined;
275
- /** Whether TLC prints the call stack before the error, as it does for a failed liveness check. */
278
+ // Whether TLC prints the call stack before the error, as it does for a failed liveness check.
276
279
  isCallStackFirst?: boolean;
277
- /** The FingerprintException the replay raises, which TLC reports in place of the call stack. */
280
+ // The FingerprintException the replay raises, which TLC reports in place of the call stack.
278
281
  fingerprint?: FingerprintFailure;
279
- /** How TLC reports failing again as it prints the trace, since it can't fingerprint the state. */
282
+ // How TLC reports failing again as it prints the trace, since it can't fingerprint the state.
280
283
  traceFailure?: FailureMessage;
281
- /** A POSTCONDITION that is false or fails after the trace, which TLC checks as it prints one. */
284
+ // A POSTCONDITION that is false or fails after the trace, which TLC checks as it prints one.
282
285
  postcondition?: Postcondition;
283
- /** Whether TLC stops before it prints the statistics, as it does for an illegal initial state. */
286
+ // Whether TLC stops before it prints the statistics, as it does for an illegal initial state.
284
287
  isWithoutStatistics?: boolean;
285
288
  }
286
289
 
@@ -303,17 +306,17 @@ export interface CheckResult {
303
306
  distinctStates: number;
304
307
  queuedStates: number;
305
308
  depth: number;
306
- /** Once TLC computed all the initial states without a violation or an error. */
309
+ // Once TLC computed all the initial states without a violation or an error.
307
310
  initialStates: InitialStates | undefined;
308
- /** How many expanded states found each number of new states, when TLC prints the outdegree. */
311
+ // How many expanded states found each number of new states, when TLC prints the outdegree.
309
312
  outDegrees: number[] | undefined;
310
- /** The smallest distance between two fingerprints, when TLC estimates a collision from them. */
313
+ // The smallest distance between two fingerprints, when TLC estimates a collision from them.
311
314
  fingerprintDistance: bigint | undefined;
312
- /** A temporal property TLC finds violated as it adds a deadlocked state, reported after. */
315
+ // A temporal property TLC finds violated as it adds a deadlocked state, reported after.
313
316
  additionalViolation?: Violation;
314
- /** Where TLC's worker fails to add the state to the behavior graph after it reports a violation. */
317
+ // Where TLC's worker fails to add the state to the behavior graph after it reports a violation.
315
318
  liveCallStack?: Expression[];
316
- /** The outdegrees when TLC's workers stop on a violation that TLC 1.7.4 reports as a success. */
319
+ // The outdegrees when TLC's workers stop on a violation that TLC 1.7.4 reports as a success.
317
320
  violationOutDegrees?: number[];
318
321
  traceSpec?: string;
319
322
  coverage?: CoverageReport;
@@ -333,24 +336,6 @@ interface TraceOptions {
333
336
  known?: number;
334
337
  }
335
338
 
336
- interface ReportedViolation extends Omit<Violation, "loopStart"> {
337
- loopStart?: number;
338
- }
339
-
340
- interface RebuiltState {
341
- state: Value[];
342
- level: number;
343
- }
344
-
345
- interface SearchPosition {
346
- index: number;
347
- isExpanding: boolean;
348
- candidate: Value[] | undefined;
349
- candidateLevel: number;
350
- livenessSource: number;
351
- rebuilt: RebuiltState | undefined;
352
- }
353
-
354
339
  interface FailureOptions {
355
340
  initialState?: Value[];
356
341
  isInitial?: boolean;
@@ -361,6 +346,7 @@ interface FailureOptions {
361
346
  isNextState?: boolean;
362
347
  isCallStackFirst?: boolean;
363
348
  traceFailure?: FailureMessage;
349
+ // Whether TLC prints the call stack of adding the state to the behavior graph, not a replay.
364
350
  isLiveCallStack?: boolean;
365
351
  }
366
352
 
@@ -372,9 +358,11 @@ const appendTraceOutput = <Traced extends Behavior>(behavior: Traced, lines: Out
372
358
  const INITIAL_RECOVERY_FAILURE = "Failed to recover the initial state from its fingerprint.";
373
359
  const NEXT_RECOVERY_FAILURE = "Failed to recover the next state from its fingerprint.";
374
360
 
361
+ // Stops a replay where TLC stops it without a failure, as at a violated invariant.
375
362
  const STOP_REPLAY = new Error("The replay stopped");
376
363
  const STOP_WALK = new Error("The walk stopped");
377
364
 
365
+ // When TLC's replay of the initial states doesn't fail again, it exits with the error's code.
378
366
  const getInitialExitCode = (error: TlaEvaluationError) => {
379
367
  const coded = getCodedMessage(error.message);
380
368
  return coded &&
@@ -384,12 +372,15 @@ const getInitialExitCode = (error: TlaEvaluationError) => {
384
372
  : getErrorExitCode(error);
385
373
  };
386
374
 
375
+ // When the replay fails again, a standard module's EvalException decides the exit status, and
376
+ // any other failure exits as a nested expression failure. A heading or wrapping error defers.
387
377
  const getReplayExitCode = (error: TlaEvaluationError): number => {
388
378
  const inner = error.cause;
389
379
  if (inner instanceof TlaEvaluationError) return getReplayExitCode(inner);
390
380
  return error instanceof TlaModuleError ? error.exitCode : EXIT_STATUS.specEvaluationFailure;
391
381
  };
392
382
 
383
+ // TLC finishes the -dump file whether or not the search finds a violation.
393
384
  export const checkSequentially = (options: CheckOptions): CheckResult => {
394
385
  const stateWriter =
395
386
  options.dump && createStateWriter(options.dump, options.writeFile, options.version);
@@ -402,6 +393,8 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
402
393
  }
403
394
  };
404
395
 
396
+ // TLC checks liveness on the graph so far after 3 seconds and then every minute, once the graph
397
+ // has grown by a tenth and liveness checking has taken at most a fifth of the time.
405
398
  const PERIODIC_START = 3000;
406
399
  const PROGRESS_INTERVAL = 60_000;
407
400
  const LIVENESS_GROWTH = 0.1;
@@ -413,19 +406,20 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
413
406
  ? parseConfig(options.config, options.version)
414
407
  : options.config;
415
408
  const onPrint = options.onPrint ?? console.log;
416
- let capturedLines: OutputLine[] | undefined;
409
+ // TLC prints again while it rebuilds a trace, so rebuilding keeps what it prints for the trace.
410
+ const capturedOutput = { lines: undefined as OutputLine[] | undefined };
417
411
  const print = (text: string) => {
418
- if (capturedLines) capturedLines.push(text);
412
+ if (capturedOutput.lines) capturedOutput.lines.push(text);
419
413
  else onPrint(text);
420
414
  };
421
415
  const captureOutput = <Result>(rebuild: () => Result) => {
422
- const outer = capturedLines;
416
+ const outer = capturedOutput.lines;
423
417
  const lines: OutputLine[] = [];
424
- capturedLines = lines;
418
+ capturedOutput.lines = lines;
425
419
  try {
426
420
  return { result: rebuild(), lines };
427
421
  } finally {
428
- capturedLines = outer;
422
+ capturedOutput.lines = outer;
429
423
  }
430
424
  };
431
425
  const order = createTlcOrder(options.source, options.loadModule);
@@ -475,8 +469,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
475
469
  specification.variableLocations,
476
470
  specification.instanceActions,
477
471
  );
478
- let searchDepth = 0;
479
- let computedInitialStates: InitialStates | undefined;
472
+ const statistics = { depth: 0, initialStates: undefined as InitialStates | undefined };
480
473
  const getTraceSpec = (trace: TraceStep[], loopStart: number | undefined) =>
481
474
  options.traceSpec &&
482
475
  writeTraceSpec({
@@ -495,9 +488,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
495
488
  });
496
489
  const createResult = (
497
490
  status: CheckStatus,
498
- violation?: ReportedViolation,
491
+ violation?: Omit<Violation, "loopStart"> & { loopStart?: number },
499
492
  failure?: EvaluationFailure,
500
493
  ): CheckResult => {
494
+ // TLC writes the trace it printed, and a safety property's counterexample doesn't loop back.
501
495
  const traceSpec = getTraceSpec(
502
496
  violation?.trace ?? failure?.trace ?? [],
503
497
  status === "property-violation" ? undefined : violation?.loopStart,
@@ -509,8 +503,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
509
503
  generatedStates: runtime.generatedStates,
510
504
  distinctStates: runtime.distinctStates,
511
505
  queuedStates: runtime.queueSize,
512
- depth: runtime.generatedStates === 0 ? 0 : Math.max(searchDepth, 1),
513
- initialStates: computedInitialStates,
506
+ depth: runtime.generatedStates === 0 ? 0 : Math.max(statistics.depth, 1),
507
+ initialStates: statistics.initialStates,
514
508
  outDegrees: undefined,
515
509
  fingerprintDistance: undefined,
516
510
  coverage: coverage?.relations.some((relation) => relation.kind === "next")
@@ -525,13 +519,16 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
525
519
  };
526
520
  };
527
521
  const outDegrees = Array.from({ length: OUT_DEGREE_BUCKETS }, () => 0);
528
- let newStateCount = 0;
529
- const getOutDegreeBucket = () => Math.min(newStateCount, OUT_DEGREE_BUCKETS - 1);
522
+ const expansion = { newStates: 0 };
523
+ const getOutDegreeBucket = () => Math.min(expansion.newStates, OUT_DEGREE_BUCKETS - 1);
524
+ // TLC counts the state it was expanding when an evaluation failed, except TLC 1.7.4.
530
525
  const getPartialOutDegrees = () =>
531
526
  outDegrees.map((count, degree) => (degree === getOutDegreeBucket() ? count + 1 : count));
532
527
  const getFailureOutDegrees = () => (is174 ? [...outDegrees] : getPartialOutDegrees());
528
+ // TLC 1.7.4 doesn't name the properties a counterexample violates, so it evaluates none of them.
533
529
  const getViolatedProperties = (checker: LivenessChecker, path: Value[][], cycleStart: number) =>
534
530
  is174 ? [] : checker.getViolatedProperties(path, cycleStart);
531
+ // A violation in a successor ends the expansion of a state before TLC counts it.
535
532
  const withOutDegrees = (result: CheckResult, degrees = [...outDegrees]): CheckResult => ({
536
533
  ...result,
537
534
  violationOutDegrees: degrees,
@@ -563,11 +560,12 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
563
560
  runtime.isStarted = true;
564
561
  const assumptionViolation = findViolatedAssumption();
565
562
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
566
- computedInitialStates = { generated: 0, distinct: 0 };
563
+ // TLC computes the initial states of a spec without variables, of which there are none.
564
+ statistics.initialStates = { generated: 0, distinct: 0 };
567
565
  options.onProgress?.({ kind: "initial-states-started" });
568
566
  options.onProgress?.({
569
567
  kind: "initial-states-computed",
570
- initialStates: computedInitialStates,
568
+ initialStates: statistics.initialStates,
571
569
  });
572
570
  return createSuccess();
573
571
  }
@@ -575,6 +573,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
575
573
  config.postconditions.length > 0 ||
576
574
  config.possible.length > 0 ||
577
575
  specification.moduleOperators.some((operator) => operator.kind === "postcondition");
576
+ // The state of each step without the alias, and its action, which CounterExample records.
578
577
  const traceSteps = new WeakMap<
579
578
  TraceStep,
580
579
  { state: Record<string, Value>; action: SpecAction | undefined }
@@ -584,6 +583,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
584
583
  const action = traceSteps.get(step)?.action;
585
584
  return action ? toActionValue(action) : createActionRecord(step.action);
586
585
  };
586
+ // TLC checks the postconditions on each trace it prints, so what they print follows the trace.
587
587
  const checkTracePostconditions = (
588
588
  trace: TraceStep[],
589
589
  loop: { start: number; action: Value } | undefined,
@@ -603,7 +603,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
603
603
  };
604
604
  const reportViolation = (
605
605
  status: CheckStatus,
606
- violation: ReportedViolation,
606
+ violation: Omit<Violation, "loopStart"> & { loopStart?: number },
607
607
  getLoopAction?: () => Value,
608
608
  ) => {
609
609
  const start = violation.loopStart;
@@ -618,13 +618,15 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
618
618
  ...(checked.postcondition && { postcondition: checked.postcondition }),
619
619
  });
620
620
  };
621
- // Deviation from TLC: -continue ends with the status of the first violation, not a success.
622
- let continuedStatus: CheckStatus | undefined;
621
+ // With -continue, TLC prints the trace of a violation without checking the postconditions. It
622
+ // never records the violation, and reports a success at the end, where tla-ts ends with the
623
+ // status of the first violation, as -dfid and -simulate do.
624
+ const continued = { status: undefined as CheckStatus | undefined };
623
625
  const reportContinuedViolation = (
624
626
  status: CheckStatus,
625
627
  violation: Omit<Violation, "loopStart">,
626
628
  ) => {
627
- continuedStatus ??= status;
629
+ continued.status ??= status;
628
630
  options.onProgress?.({
629
631
  kind: "violation",
630
632
  status,
@@ -633,9 +635,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
633
635
  };
634
636
  const spec = search.spec;
635
637
  const getFingerprintState = search.getFingerprintState;
636
- let specNextActions: SpecAction[] | undefined;
638
+ const specNextActions = { value: undefined as SpecAction[] | undefined };
637
639
  const getSpecNextActions = () =>
638
- (specNextActions ??= getNextActions(config, environment, specification.instanceActions));
640
+ (specNextActions.value ??= getNextActions(config, environment, specification.instanceActions));
639
641
  // Tool's constructor splits the next-state relation into actions before TLC checks anything.
640
642
  getSpecNextActions();
641
643
  runtime.getSuccessorAction = (state, next) =>
@@ -678,9 +680,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
678
680
  onState(successor);
679
681
  },
680
682
  (partial) => {
681
- const missing = environment.variables.filter(
682
- (_variable, index) => partial[index] === undefined,
683
- );
683
+ const missing = environment.variables.filter((_, index) => partial[index] === undefined);
684
684
  throw new TlaIncompleteSuccessorError(
685
685
  `Successor state is not completely specified by action ${action.name}. The following variables are not assigned: ${missing.join(", ")}`,
686
686
  partial,
@@ -715,6 +715,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
715
715
  replay(tracing);
716
716
  return undefined;
717
717
  } catch (error) {
718
+ // A replay that overflows the stack again has an empty call stack.
718
719
  if (isStackOverflow(error)) return { callStack: [], fingerprint: undefined };
719
720
  if (!(error instanceof TlaEvaluationError) || !callStack) return undefined;
720
721
  return {
@@ -724,6 +725,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
724
725
  };
725
726
  }
726
727
  };
728
+ // Outermost first: each value fails as it fingerprints a value it holds.
727
729
  const findFailedSources = (value: Value, sources: CallStack["sources"]): Expression[] => {
728
730
  if (typeof value !== "object") return [];
729
731
  const source = sources.get(value);
@@ -733,11 +735,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
733
735
  ...(failed === undefined ? [] : findFailedSources(failed, sources)),
734
736
  ];
735
737
  };
738
+ // A value the replay built raises a FingerprintException when TLC fails to fingerprint it.
736
739
  const fingerprintReplayed = (state: Value[], callStack: CallStack | undefined) => {
737
740
  for (const value of getFingerprintState(state)) {
738
741
  const error = getFingerprintError(value);
739
742
  if (!error) continue;
740
743
  const sources = callStack ? findFailedSources(value, callStack.sources) : [];
744
+ // TLC fingerprints a state outside any evaluation, so its call stack is empty.
741
745
  if (callStack && sources.length > 0) {
742
746
  callStack.expressions.length = 0;
743
747
  callStack.isFrozen = true;
@@ -747,8 +751,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
747
751
  }
748
752
  state.forEach(markFingerprinted);
749
753
  };
754
+ // TLC's set of states already holds the state that failed.
750
755
  const createReplayedStates = () => {
751
- const replayed = unstoredFingerprint ? [unstoredFingerprint] : [];
756
+ const replayed = unstoredState.fingerprint ? [unstoredState.fingerprint] : [];
752
757
  return (state: Value[], callStack: CallStack | undefined) => {
753
758
  fingerprintReplayed(state, callStack);
754
759
  const fingerprintState = getFingerprintState(state);
@@ -761,8 +766,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
761
766
  return true;
762
767
  };
763
768
  };
769
+ // TLC reports its progress again as it replays the initial states. After a FingerprintException
770
+ // or a StackOverflowError, it only counts the states left, then throws the error.
764
771
  const replayInit = () => {
765
- let replayedCount = 0;
772
+ const replayed = { count: 0 };
766
773
  const deferred: unknown[] = [];
767
774
  const addReplayed = createReplayedStates();
768
775
  return getReplayFailure((tracing) => {
@@ -770,9 +777,11 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
770
777
  getInitActions(config, environment, specification.instanceActions),
771
778
  tracing,
772
779
  (state) => {
773
- reportInitialStatesProgress(replayedCount, (progress) => capturedLines?.push(progress));
774
- replayedCount++;
775
- runtime.generatedStates = replayedCount;
780
+ reportInitialStatesProgress(replayed.count, (progress) =>
781
+ capturedOutput.lines?.push(progress),
782
+ );
783
+ replayed.count++;
784
+ runtime.generatedStates = replayed.count;
776
785
  if (deferred.length > 0) return;
777
786
  try {
778
787
  const addFingerprint = () => {
@@ -783,7 +792,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
783
792
  const violation = search.checkReplayedInitialState(state, tracing, addFingerprint);
784
793
  if (violation) {
785
794
  const traced = toTrace([{ action: undefined, state }], []).trace[0].state;
786
- capturedLines?.push({
795
+ capturedOutput.lines?.push({
787
796
  kind: "initial-state-violation",
788
797
  ...violation,
789
798
  state: traced,
@@ -801,6 +810,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
801
810
  if (deferred.length > 0) throw deferred[0];
802
811
  });
803
812
  };
813
+ // TLC's replay writes each successor in the model to the -dump state graph again.
804
814
  const replayNext = (index: number) =>
805
815
  getReplayFailure((tracing) => {
806
816
  const state = states[index];
@@ -826,6 +836,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
826
836
  });
827
837
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
828
838
  const tlcFingerprints: number[] = [];
839
+ // TLC warns about the liveness checker before it builds it.
829
840
  if (search.properties.liveness.length > 0) {
830
841
  options.onProgress?.({
831
842
  kind: "liveness-initializing",
@@ -836,13 +847,12 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
836
847
  const liveness = withLivenessExitCode(() =>
837
848
  withUnexpectedException(() =>
838
849
  createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
839
- getFingerprint: (successor) =>
840
- (tlcFingerprints[successor.index] ??= Number(
841
- BigInt.asIntN(32, runtime.getFingerprint(successor.state)),
842
- )),
850
+ getFingerprint: ({ index, state }) =>
851
+ (tlcFingerprints[index] ??= Number(BigInt.asIntN(32, runtime.getFingerprint(state)))),
843
852
  getSuccessors: (source, state) => {
844
853
  const successors: LiveSuccessor[] = [];
845
854
  if (spec.next === undefined) return successors;
855
+ // The constraints read the level of the state whose successors they check.
846
856
  const livenessSource = current.livenessSource;
847
857
  current.livenessSource = source;
848
858
  try {
@@ -871,7 +881,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
871
881
  }),
872
882
  ),
873
883
  );
884
+ // ModelChecker rejects a temporal property whose negation has no solution.
874
885
  if (liveness?.branches === 0) throw createTautologyError();
886
+ // TLC 1.7.4 creates its model checker, which TLCGet reads, once it has built the liveness checker.
875
887
  runtime.isStarted = true;
876
888
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
877
889
 
@@ -891,6 +903,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
891
903
  position: number,
892
904
  loopStart: number | undefined,
893
905
  ) => {
906
+ // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace. The
907
+ // search reads them again once the alias is evaluated, as it goes on with -continue.
894
908
  const searchLevel = runtime.getLevel;
895
909
  const searchBehavior = runtime.getBehavior;
896
910
  runtime.getLevel = () => position + 1;
@@ -908,6 +922,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
908
922
  };
909
923
  const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) =>
910
924
  search.evaluateAlias(alias, state, next, options.isTool ?? false);
925
+ // TLC finds the action of a step as the first that takes it, evaluated as when the search
926
+ // expanded the previous state, by a held successor's values and otherwise by fingerprint.
911
927
  const findStepAction = (index: number, previous: Value[], state: Value[], isHeld: boolean) => {
912
928
  const actions = getSpecNextActions();
913
929
  const expanding = { ...current };
@@ -935,6 +951,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
935
951
  Object.assign(current, expanding);
936
952
  }
937
953
  };
954
+ // TLC rebuilds the states it doesn't keep, all but the last `known`, from the initial predicate,
955
+ // finds the action of each later step, and then rebuilds the trace once more, unless it is a
956
+ // liveness counterexample or TLC is 1.7.4.
938
957
  const toTrace = (
939
958
  steps: Successor[],
940
959
  path: number[],
@@ -942,7 +961,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
942
961
  ): Behavior => {
943
962
  const alias = config.alias;
944
963
  const known = traceOptions.known ?? 1;
964
+ // Rebuilding the trace from the initial predicate can reset what TLCSet stored.
945
965
  const initialOutput = steps.length > 1 ? captureOutput(getSpecInitialStates).lines : [];
966
+ // TLC finds the action that takes each step before it evaluates the alias.
946
967
  const stepActions = steps.map((step, position) =>
947
968
  position === 0 || step.action === "Stuttering"
948
969
  ? { result: undefined, lines: [] }
@@ -957,7 +978,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
957
978
  );
958
979
  const outputs = stepActions.map((step) => step.lines);
959
980
  const loopStart = traceOptions.loopStart;
981
+ // TLC 1.7.4 rebuilds a lasso up to its cycle at once, then each cycle state as it prints it.
960
982
  const rebuilt = is174 && loopStart !== undefined ? loopStart + 1 : steps.length - known;
983
+ // What the trace prints once comes from each time TLC rebuilds it, which coverage counts.
961
984
  if (coverage && steps.length > 1) {
962
985
  const isRebuiltAgain = known > 0 && !is174;
963
986
  if (rebuilt > 0 && isRebuiltAgain) captureOutput(getSpecInitialStates);
@@ -1000,6 +1023,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1000
1023
  if (coverage) return getCoveredInitialStates();
1001
1024
  return spec.init === undefined ? [] : getInitialStates(spec.init, environment, spec.scope);
1002
1025
  };
1026
+ // TLC rebuilds a successor action by action, up to the first that generates it. A trace keeps
1027
+ // what the spec prints as TLC rebuilds it, so finding its states prints nothing.
1003
1028
  const findTraceSuccessor = (state: Value[], isMatch: (successor: Successor) => boolean) =>
1004
1029
  captureOutput(() => {
1005
1030
  for (const action of getSpecNextActions()) {
@@ -1028,6 +1053,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1028
1053
  steps.push({ state: previous, action: "Stuttering" });
1029
1054
  continue;
1030
1055
  }
1056
+ // TLC rebuilds each state at its level, which TLCGet reads.
1031
1057
  const rebuilt = current.rebuilt;
1032
1058
  current.rebuilt = { state: previous, level: depths[path[position - 1]] };
1033
1059
  const successor = findSuccessorWithFingerprint(previous, path[position]);
@@ -1054,7 +1080,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1054
1080
  : lastSuccessor.action;
1055
1081
  return toTrace([...steps, { state: lastSuccessor.state, action }], path, { known: 2 });
1056
1082
  };
1057
- // Deviation from TLC: TLCTrace#printTrace prints a lone initial state without the alias.
1083
+ // TLC rebuilds a lone initial state, unlike TLC 1.7.4. TLCTrace#printTrace prints it without the
1084
+ // alias, where tla-ts applies the alias as it does to every other trace.
1058
1085
  const getStateTrace = (index: number): Behavior =>
1059
1086
  parents[index] === -1
1060
1087
  ? {
@@ -1076,6 +1103,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1076
1103
  traceOutput: is174 ? [] : captureOutput(getSpecInitialStates).lines,
1077
1104
  }
1078
1105
  : getTrace(index);
1106
+ // TLC rebuilds the trace for the postcondition after a violation, but not after a failure.
1107
+ // TLC fails again to fingerprint the successor in the trace, as an unexpected exception.
1079
1108
  const isUnfingerprintable = (state: Value[]) => {
1080
1109
  try {
1081
1110
  return getFingerprintState(state).some((value) => getFingerprintError(value) !== undefined);
@@ -1087,7 +1116,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1087
1116
  const getFailedTrace = (index: number, successor: Successor): Behavior => ({
1088
1117
  trace: getTrace(index, successor).trace,
1089
1118
  });
1119
+ // TLC names the initial state it was checking unless a standard module's Java code failed.
1090
1120
  const getFailureExitCode = (error: TlaEvaluationError, failureOptions: FailureOptions) => {
1121
+ // TLC 1.7.4 exits with the result of replaying the initial states, which fails again only here.
1091
1122
  if (
1092
1123
  failureOptions.isInitial &&
1093
1124
  !failureOptions.callStack &&
@@ -1100,11 +1131,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1100
1131
  return failureOptions.isInitial ? getInitialExitCode(error) : getErrorExitCode(error);
1101
1132
  }
1102
1133
  if (failureOptions.isCallStackFirst) return getErrorExitCode(error);
1134
+ // Without a replay, TLC exits with the code of the error, as for any error it didn't expect.
1103
1135
  if (failureOptions.isLiveCallStack) {
1104
1136
  return (
1105
1137
  getExitCode(error) ?? (error instanceof TlaModuleError ? error.exitCode : EXIT_STATUS.error)
1106
1138
  );
1107
1139
  }
1140
+ // TLC exits with the code of a failed initial replay whatever the error, as for a fingerprint.
1108
1141
  return failureOptions.isInitial || failureOptions.fingerprint
1109
1142
  ? EXIT_STATUS.specEvaluationFailure
1110
1143
  : getReplayExitCode(failureOptions.replayError ?? error);
@@ -1141,11 +1174,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1141
1174
  outDegrees: failureOptions.outDegrees,
1142
1175
  };
1143
1176
  };
1177
+ // TLC reports a partial successor with the trace to it, naming the action if there are several.
1144
1178
  const reportIncompleteSuccessor = (index: number, error: TlaIncompleteSuccessorError) => {
1145
1179
  runtime.generatedStates++;
1146
1180
  const actions = getSpecNextActions();
1147
1181
  const named =
1148
1182
  actions.length === 1 ? actions : actions.filter((item) => item.name === error.action);
1183
+ // Inline disjuncts of the next-state relation share its name, so TLC's is the one that failed.
1149
1184
  const action =
1150
1185
  named.length === 1
1151
1186
  ? named[0]
@@ -1199,6 +1234,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1199
1234
  hash = combineHash(hash, getValueHash(state[index]));
1200
1235
  return hash & 0x3fffffff;
1201
1236
  };
1237
+ // TLC fingerprints a state once it finds the state in the model.
1202
1238
  const fingerprintModelState = (state: Value[]) => {
1203
1239
  for (const value of state) {
1204
1240
  const error = getFingerprintError(value);
@@ -1241,10 +1277,11 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1241
1277
  }
1242
1278
  insertSeen(hash, index + 1);
1243
1279
  };
1244
- let unstoredFingerprint: Value[] | undefined;
1280
+ // TLC adds a new successor to its states before it checks it, which the check stores after.
1281
+ const unstoredState = { fingerprint: undefined as Value[] | undefined };
1245
1282
  const countDistinctState = (depth: number) => {
1246
1283
  runtime.distinctStates = states.length + 1;
1247
- searchDepth = Math.max(searchDepth, depth);
1284
+ statistics.depth = Math.max(statistics.depth, depth);
1248
1285
  runtime.diameter = Math.max(runtime.diameter, depth);
1249
1286
  };
1250
1287
  const addState = (
@@ -1261,13 +1298,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1261
1298
  depths.push(depth);
1262
1299
  };
1263
1300
 
1264
- const current: SearchPosition = {
1301
+ const current = {
1265
1302
  index: -1,
1266
1303
  isExpanding: false,
1267
- candidate: undefined,
1304
+ candidate: undefined as Value[] | undefined,
1268
1305
  candidateLevel: 0,
1269
1306
  livenessSource: -1,
1270
- rebuilt: undefined,
1307
+ rebuilt: undefined as { state: Value[]; level: number } | undefined,
1271
1308
  };
1272
1309
  const getPath = (index: number): Value[][] =>
1273
1310
  index === -1 ? [] : [...getPath(parents[index]), states[index]];
@@ -1285,6 +1322,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1285
1322
  };
1286
1323
  runtime.getLevel = (state) => {
1287
1324
  const source = current.livenessSource;
1325
+ // TLC 1.7.4 reads the level of the state its worker explores, whichever state it evaluates.
1288
1326
  if (is174) {
1289
1327
  const explored = source !== -1 ? source : current.isExpanding ? current.index : -1;
1290
1328
  return explored === -1 ? 0 : depths[explored];
@@ -1330,7 +1368,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1330
1368
  }
1331
1369
  const isSeen = isInModel && findStateIndex(hash, fingerprintState) !== -1;
1332
1370
  if (isSeen) return undefined;
1333
- unstoredFingerprint = isInModel ? fingerprintState : undefined;
1371
+ unstoredState.fingerprint = isInModel ? fingerprintState : undefined;
1334
1372
  if (isInModel) {
1335
1373
  countDistinctState(1);
1336
1374
  runtime.queueSize++;
@@ -1415,12 +1453,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1415
1453
  liveSuccessors.push({ index: existing, state: isStored ? stored : successor.state });
1416
1454
  }
1417
1455
  const isNew = isInModel && existing === -1;
1456
+ // TLC adds a new state to the behavior graph's successors before it checks the invariants.
1418
1457
  if (isNew && liveness) liveSuccessors.push({ index: states.length, state: successor.state });
1419
- unstoredFingerprint = isNew ? fingerprintState : undefined;
1458
+ unstoredState.fingerprint = isNew ? fingerprintState : undefined;
1420
1459
  if (isNew) {
1421
1460
  countDistinctState(depths[index] + 1);
1422
- newStateCount++;
1423
- if (coverage) coverage.secondary[coveredNode]++;
1461
+ expansion.newStates++;
1462
+ if (coverage) coverage.secondary[coveredAction.node]++;
1424
1463
  }
1425
1464
  if (existing === -1) {
1426
1465
  try {
@@ -1432,6 +1471,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1432
1471
  if (violation) reportContinuedViolation("invariant-violation", violation);
1433
1472
  } catch (error) {
1434
1473
  if (isStackOverflow(error)) throw error;
1474
+ // TLC replays the expansion and skips the invariants of a seen state, the failed one
1475
+ // included unless the constraints exclude it. A failed replay leaves out the outdegree.
1435
1476
  const replay = captureOutput(() => replayNext(index));
1436
1477
  return createFailureResult(
1437
1478
  error,
@@ -1458,16 +1499,18 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1458
1499
  return undefined;
1459
1500
  };
1460
1501
 
1461
- let outcome: CheckResult | undefined;
1462
- let coveredNode = -1;
1502
+ const outcome: { result: CheckResult | undefined } = { result: undefined };
1503
+ const coveredAction = { node: -1 };
1463
1504
  if (liveness) {
1464
1505
  options.onProgress?.({ kind: "liveness-prepared", branches: liveness.branches });
1465
1506
  }
1507
+ // TLC checks the assumptions once it has built the liveness checker.
1466
1508
  const assumptionViolation = findViolatedAssumption();
1467
1509
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
1468
1510
  options.onProgress?.({ kind: "initial-states-started" });
1469
1511
  if (spec.init !== undefined) {
1470
- let overflowState: Value[] | undefined;
1512
+ // TLC keeps an initial state's StackOverflowError, counts the states after it, then reports it.
1513
+ const overflow: { state: Value[] | undefined } = { state: undefined };
1471
1514
  const reportInitialFailure = (error: unknown, state: Value[]) => {
1472
1515
  const replay = captureOutput(replayInit);
1473
1516
  return createFailureResult(
@@ -1479,18 +1522,18 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1479
1522
  try {
1480
1523
  const onInitialState = (state: Value[]) => {
1481
1524
  reportInitialStatesProgress(runtime.initialStates, options.onProgress);
1482
- if (overflowState) {
1525
+ if (overflow.state) {
1483
1526
  runtime.generatedStates++;
1484
1527
  runtime.initialStates++;
1485
1528
  return false;
1486
1529
  }
1487
1530
  try {
1488
- outcome = visitInitialState(state);
1531
+ outcome.result = visitInitialState(state);
1489
1532
  } catch (error) {
1490
- if (isStackOverflow(error)) overflowState = state;
1491
- else outcome = reportInitialFailure(error, state);
1533
+ if (isStackOverflow(error)) overflow.state = state;
1534
+ else outcome.result = reportInitialFailure(error, state);
1492
1535
  }
1493
- return outcome !== undefined;
1536
+ return outcome.result !== undefined;
1494
1537
  };
1495
1538
  if (coverage) {
1496
1539
  try {
@@ -1510,10 +1553,11 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1510
1553
  } else {
1511
1554
  forEachInitialState(spec.init, environment, onInitialState, spec.scope);
1512
1555
  }
1513
- if (overflowState) {
1514
- outcome = reportInitialFailure(createStackOverflowError(), overflowState);
1556
+ if (overflow.state) {
1557
+ outcome.result = reportInitialFailure(createStackOverflowError(), overflow.state);
1515
1558
  }
1516
1559
  } catch (error) {
1560
+ // TLC prints null for each undefined variable and stops before the statistics.
1517
1561
  if (error instanceof TlaIllegalStateError) {
1518
1562
  const illegal = createFailureResult(
1519
1563
  error,
@@ -1525,6 +1569,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1525
1569
  failure: illegal.failure && { ...illegal.failure, isWithoutStatistics: true },
1526
1570
  };
1527
1571
  }
1572
+ // TLC prints the error before it replays the initial predicate with its call stack.
1528
1573
  const replay = captureOutput(replayInit);
1529
1574
  return createFailureResult(
1530
1575
  error,
@@ -1533,14 +1578,14 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1533
1578
  );
1534
1579
  }
1535
1580
  }
1536
- if (outcome) return outcome;
1537
- computedInitialStates = {
1581
+ if (outcome.result) return outcome.result;
1582
+ statistics.initialStates = {
1538
1583
  generated: runtime.initialStates,
1539
1584
  distinct: runtime.distinctStates,
1540
1585
  };
1541
1586
  options.onProgress?.({
1542
1587
  kind: "initial-states-computed",
1543
- initialStates: computedInitialStates,
1588
+ initialStates: statistics.initialStates,
1544
1589
  });
1545
1590
 
1546
1591
  const next = spec.next;
@@ -1552,6 +1597,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1552
1597
  }
1553
1598
  return createSuccess();
1554
1599
  }
1600
+ // TLC labels and colors a -dump edge by its action, so a graph that names its edges generates
1601
+ // successors action by action.
1555
1602
  const isNamingEdges = Boolean(
1556
1603
  options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1557
1604
  );
@@ -1563,19 +1610,19 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1563
1610
  onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1564
1611
  ) => {
1565
1612
  if (coverage) {
1566
- let successorCount = 0;
1613
+ const progress = { count: 0 };
1567
1614
  try {
1568
1615
  coverageActions.forEach((action) => {
1569
- coveredNode = action.node;
1616
+ coveredAction.node = action.node;
1570
1617
  walkCoveredSuccessors(action, state, (successor) => {
1571
- successorCount++;
1618
+ progress.count++;
1572
1619
  if (onSuccessor({ state: successor, action: action.name }, action)) throw STOP_WALK;
1573
1620
  });
1574
1621
  });
1575
1622
  } catch (error) {
1576
1623
  if (error !== STOP_WALK) throw error;
1577
1624
  }
1578
- return successorCount;
1625
+ return progress.count;
1579
1626
  }
1580
1627
  if (!isNamingEdges) {
1581
1628
  return forEachSuccessor(
@@ -1588,9 +1635,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1588
1635
  onUnsatisfied,
1589
1636
  );
1590
1637
  }
1591
- let isStopped = false;
1638
+ const progress = { isStopped: false };
1592
1639
  return getSpecNextActions().reduce((count, action) => {
1593
- if (isStopped) return count;
1640
+ if (progress.isStopped) return count;
1594
1641
  return (
1595
1642
  count +
1596
1643
  forEachSuccessor(
@@ -1598,8 +1645,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1598
1645
  state,
1599
1646
  environment,
1600
1647
  (successor) => {
1601
- isStopped = onSuccessor(successor, action);
1602
- return isStopped;
1648
+ progress.isStopped = onSuccessor(successor, action);
1649
+ return progress.isStopped;
1603
1650
  },
1604
1651
  action.scope,
1605
1652
  undefined,
@@ -1608,6 +1655,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1608
1655
  );
1609
1656
  }, 0);
1610
1657
  };
1658
+ // TLC's worker adds a state to the behavior graph even after its next states fail, and prints
1659
+ // the call stack of an error in that, unless it is a FingerprintException. TLC 1.7.4 prints none.
1611
1660
  const getLiveCallStack = (index: number, liveSuccessors: LiveSuccessor[]) => {
1612
1661
  if (!liveness || is174) return undefined;
1613
1662
  const replay = getReplayFailure((tracing) =>
@@ -1615,6 +1664,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1615
1664
  );
1616
1665
  return replay?.callStack.length && !replay.fingerprint ? replay.callStack : undefined;
1617
1666
  };
1667
+ // On an error in adding the state after the trace, TLC adds it again to print the call stack
1668
+ // instead of replaying the next-state relation, which TLC 1.7.4 doesn't.
1618
1669
  const addFailedLiveState = (index: number, liveSuccessors: LiveSuccessor[]) => {
1619
1670
  try {
1620
1671
  liveness?.addState(index, states[index], liveSuccessors);
@@ -1633,8 +1684,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1633
1684
  const replay = captureOutput(() => replayNext(index));
1634
1685
  return { result: replay.result, lines: [...live.lines, ...replay.lines] };
1635
1686
  };
1687
+ // TLC reports a stack overflow in the next states without a replay, up to the state it expands.
1636
1688
  const reportNextStateOverflow = (index: number) =>
1637
1689
  createFailureResult(createStackOverflowError(), getStateTrace(index), { isNextState: true });
1690
+ // After the trace, TLC replays the next-state relation with its call stack, printing again.
1638
1691
  const reportNextStateFailure = (
1639
1692
  error: unknown,
1640
1693
  index: number,
@@ -1663,17 +1716,19 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1663
1716
  : undefined;
1664
1717
  const successorCount = forEachActionSuccessor(state, writeUnsatisfied, (successor, action) => {
1665
1718
  try {
1666
- outcome = visitSuccessor(index, successor, liveSuccessors, source, action);
1719
+ outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1667
1720
  } catch (error) {
1668
1721
  if (isStackOverflow(error)) {
1669
- outcome = reportNextStateOverflow(index);
1722
+ outcome.result = reportNextStateOverflow(index);
1670
1723
  return true;
1671
1724
  }
1725
+ // TLC 1.7.4 reports the wrapped error without the trace, except for a failed property, and
1726
+ // stops its worker before it adds the state to the behavior graph.
1672
1727
  const replay = is174
1673
1728
  ? captureOutput(() => replayNext(index))
1674
1729
  : replayFailedNext(index, liveSuccessors);
1675
1730
  if (is174 && error instanceof TlaEvaluationError && !isHeadedError(error)) {
1676
- outcome = createFailureResult(
1731
+ outcome.result = createFailureResult(
1677
1732
  new TlaEvaluationError(`${getWrappedException(error)}${error.message}`, error),
1678
1733
  appendTraceOutput({ trace: [] }, replay.lines),
1679
1734
  { isNextState: true, ...replay.result },
@@ -1690,7 +1745,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1690
1745
  true,
1691
1746
  )
1692
1747
  : undefined;
1693
- outcome = createFailureResult(
1748
+ outcome.result = createFailureResult(
1694
1749
  error,
1695
1750
  appendTraceOutput(
1696
1751
  traceFailure ? getStateTrace(index) : getFailedTrace(index, successor),
@@ -1699,10 +1754,11 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1699
1754
  { isNextState: true, ...replay.result, traceFailure },
1700
1755
  );
1701
1756
  }
1702
- return outcome !== undefined;
1757
+ return outcome.result !== undefined;
1703
1758
  });
1704
1759
  current.isExpanding = false;
1705
- const result = outcome;
1760
+ const result = outcome.result;
1761
+ // TLC 1.7.4's worker stops at a violation.
1706
1762
  if (result?.violation && !is174) {
1707
1763
  const live = captureOutput(() => addFailedLiveState(index, liveSuccessors));
1708
1764
  return {
@@ -1732,6 +1788,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1732
1788
  };
1733
1789
  if (successorCount === 0 && config.checkDeadlock) {
1734
1790
  const deadlock = reportViolation("deadlock", { name: "deadlock", ...getStateTrace(index) });
1791
+ // TLC's worker still adds the deadlocked state to the behavior graph, reports a temporal
1792
+ // property that violates, and then counts the state as expanded.
1735
1793
  const live = captureOutput(() => {
1736
1794
  try {
1737
1795
  return { additional: addLiveState()?.violation };
@@ -1743,6 +1801,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1743
1801
  const reported = deadlock.violation
1744
1802
  ? { ...deadlock, violation: appendTraceOutput(deadlock.violation, live.lines) }
1745
1803
  : deadlock;
1804
+ // An error in adding the state stops TLC 1.7.4's worker before it counts the state.
1746
1805
  const counted = withOutDegrees(
1747
1806
  reported,
1748
1807
  live.result.isFailed ? getFailureOutDegrees() : getPartialOutDegrees(),
@@ -1754,6 +1813,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1754
1813
  try {
1755
1814
  return addLiveState();
1756
1815
  } catch (error) {
1816
+ // TLC 1.7.4 reports this as an unexpected exception, without the trace or a call stack.
1757
1817
  if (is174 && error instanceof TlaEvaluationError) {
1758
1818
  const unexpected = new TlaEvaluationError(
1759
1819
  `${isEvalException(error) ? UNEXPECTED_EVAL_EXCEPTION : UNEXPECTED_EXCEPTION}${error.message}`,
@@ -1764,6 +1824,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1764
1824
  { outDegrees: getFailureOutDegrees() },
1765
1825
  );
1766
1826
  }
1827
+ // TLC adds the state again for the call stack, prints it first, and blames the next states.
1767
1828
  const replay = getReplayFailure((tracing) =>
1768
1829
  liveness?.addState(index, state, liveSuccessors, tracing),
1769
1830
  );
@@ -1792,6 +1853,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1792
1853
  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}`,
1793
1854
  };
1794
1855
  };
1856
+ // TLC names the properties and the step back into the cycle from the states it prints.
1795
1857
  const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1796
1858
  const path = [...lasso.prefix, ...lasso.cycle];
1797
1859
  const loopStart = lasso.prefix.length;
@@ -1862,20 +1924,22 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1862
1924
  current.isExpanding = true;
1863
1925
  const liveSuccessors: LiveSuccessor[] = [];
1864
1926
  try {
1865
- outcome = expandState(index, liveSuccessors);
1927
+ outcome.result = expandState(index, liveSuccessors);
1866
1928
  } catch (error) {
1867
- outcome =
1929
+ outcome.result =
1868
1930
  error instanceof TlaIncompleteSuccessorError
1869
1931
  ? reportIncompleteSuccessor(index, error)
1870
1932
  : reportNextStateFailure(error, index, liveSuccessors);
1871
1933
  }
1872
- if (outcome) return outcome;
1934
+ if (outcome.result) return outcome.result;
1873
1935
  outDegrees[getOutDegreeBucket()]++;
1874
- newStateCount = 0;
1936
+ expansion.newStates = 0;
1937
+ // TLC checks liveness on the graph so far, then reports how far the search got.
1875
1938
  if ((isPeriodic || options.onProgress) && performance.now() >= periodic.at) {
1876
1939
  periodic.at = performance.now() + PROGRESS_INTERVAL;
1877
1940
  const lasso = isPeriodic ? findPeriodicViolation(index + 1) : undefined;
1878
1941
  if (liveness && lasso) return reportLasso(liveness, lasso);
1942
+ // TLC reports the coverage with every report after the first `coverage` reports since the last.
1879
1943
  const isCoverageDue = options.coverage !== undefined && periodic.coverageCount === 0;
1880
1944
  periodic.coverageCount = isCoverageDue
1881
1945
  ? Math.trunc(options.coverage ?? 0)
@@ -1903,6 +1967,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1903
1967
  const lasso = finalLiveness?.findViolation();
1904
1968
  if (finalLiveness && lasso) return reportLasso(finalLiveness, lasso);
1905
1969
 
1970
+ // TLC finishes the check of the temporal properties before it checks the postconditions.
1906
1971
  if (finalLiveness) options.onProgress?.({ kind: "liveness-finished" });
1907
1972
  const missingPostcondition = specification.moduleOperators.find(
1908
1973
  (operator) => operator.kind === "postcondition" && operator.key === undefined,
@@ -1920,5 +1985,5 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1920
1985
  postcondition,
1921
1986
  });
1922
1987
  }
1923
- return continuedStatus ? createResult(continuedStatus) : createSuccess();
1988
+ return continued.status ? createResult(continued.status) : createSuccess();
1924
1989
  };