tla-ts 0.0.2 → 0.0.3-dev.14337b3

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 (65) hide show
  1. package/README.md +78 -12
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +85 -15
  4. package/dist/index.d.ts +85 -15
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +2 -2
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +22 -2
  11. package/dist/run-cli.js +22 -2
  12. package/dist/transfer.cjs +37 -16
  13. package/dist/transfer.js +37 -16
  14. package/package.json +3 -1
  15. package/src/ast.ts +137 -4
  16. package/src/check.ts +378 -100
  17. package/src/cli-options.ts +64 -0
  18. package/src/codegen.ts +15 -22
  19. package/src/config.ts +224 -170
  20. package/src/dependencies.ts +2 -2
  21. package/src/environment.ts +116 -28
  22. package/src/errors.ts +101 -3
  23. package/src/evaluate.ts +129 -153
  24. package/src/exit-codes.ts +39 -42
  25. package/src/fingerprints.ts +46 -11
  26. package/src/instances.ts +16 -15
  27. package/src/levels.ts +62 -34
  28. package/src/lexer.ts +11 -2
  29. package/src/live-check.ts +772 -0
  30. package/src/liveness.ts +116 -543
  31. package/src/obligation-action.ts +384 -0
  32. package/src/obligation-anon.ts +575 -0
  33. package/src/obligation-deref.ts +637 -0
  34. package/src/obligation-expression.ts +1060 -0
  35. package/src/obligation-format.ts +406 -0
  36. package/src/obligation-generate.ts +1074 -0
  37. package/src/obligation-levels.ts +329 -0
  38. package/src/obligation-module.ts +1042 -0
  39. package/src/obligation-printer.ts +889 -0
  40. package/src/obligation-proof.ts +76 -0
  41. package/src/obligation-source.ts +1084 -0
  42. package/src/obligation-tuples.ts +184 -0
  43. package/src/obligations.ts +316 -0
  44. package/src/parallel-worker.ts +168 -212
  45. package/src/parallel.ts +78 -37
  46. package/src/parser.ts +315 -60
  47. package/src/resolve.ts +122 -44
  48. package/src/run-cli.ts +376 -44
  49. package/src/runtime.ts +3 -1
  50. package/src/spec-description.ts +19 -8
  51. package/src/standard-levels.ts +3 -3
  52. package/src/standard-modules.ts +2 -7
  53. package/src/state-graph.ts +157 -0
  54. package/src/subexpressions.ts +10 -10
  55. package/src/successors.ts +99 -25
  56. package/src/symmetry.ts +30 -8
  57. package/src/tableau.ts +51 -24
  58. package/src/tlc-ext.ts +29 -12
  59. package/src/tlc-module.ts +14 -33
  60. package/src/tlc-modules.ts +4 -0
  61. package/src/tlc-order.ts +25 -7
  62. package/src/tlc-random.ts +9 -6
  63. package/src/tlc-summary.ts +20 -5
  64. package/src/transfer.ts +22 -1
  65. package/src/values.ts +179 -42
package/src/check.ts CHANGED
@@ -1,15 +1,30 @@
1
- import type { Assumption, Definition, Expression, SourceLocation } from "./ast";
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Assumption,
5
+ type Definition,
6
+ type Expression,
7
+ type SourceLocation,
8
+ } from "./ast";
2
9
  import { parseConfig, type ConfigValue, type ModelConfig } from "./config";
3
10
  import { getReadVariables } from "./dependencies";
4
11
  import { createEnvironment } from "./environment";
5
- import { getErrorExitCode, TlaConfigError, TlaEvaluationError, TlaModuleError } from "./errors";
6
- import { EXIT_STATUS, setExitCode, setNextStatePhase, withLivenessExitCode } from "./exit-codes";
12
+ import {
13
+ getErrorExitCode,
14
+ isStackOverflow,
15
+ formatRange,
16
+ STACK_OVERFLOW,
17
+ TlaConfigError,
18
+ TlaEvaluationError,
19
+ TlaIncompleteStateError,
20
+ TlaModuleError,
21
+ UNEXPECTED_EXCEPTION,
22
+ } from "./errors";
23
+ import { EXIT_STATUS, setExitCode, withLivenessExitCode } from "./exit-codes";
7
24
  import {
8
25
  describeRange,
9
26
  evaluate,
10
27
  expectBoolean,
11
- formatRange,
12
- getChildren,
13
28
  getDefinition,
14
29
  isConstantLevel,
15
30
  isImpure,
@@ -19,13 +34,11 @@ import {
19
34
  } from "./evaluate";
20
35
  import {
21
36
  createLivenessChecker,
22
- expandTemporal,
23
- getLevel,
24
37
  type Lasso,
38
+ type LivenessChecker,
25
39
  type LiveSuccessor,
26
- type ScopedExpression,
27
- type TemporalProperty,
28
- } from "./liveness";
40
+ } from "./live-check";
41
+ import { expandTemporal, getLevel, type ScopedExpression, type TemporalProperty } from "./liveness";
29
42
  import { ACTION_LEVEL, createLevelAnalyzer, TEMPORAL_LEVEL } from "./levels";
30
43
  import { prettyPrint } from "./pretty-print";
31
44
  import {
@@ -37,12 +50,19 @@ import {
37
50
  } from "./successors";
38
51
  import {
39
52
  getActionLabel,
53
+ getActionSignature,
40
54
  getNextActions,
41
55
  getSpecificationValue,
42
56
  type SpecAction,
43
57
  } from "./spec-description";
58
+ import {
59
+ createStateWriter,
60
+ type GraphState,
61
+ type StateDump,
62
+ type StateWriter,
63
+ } from "./state-graph";
44
64
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
45
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
65
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
46
66
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
47
67
  import { createCanonicalizer } from "./canonical";
48
68
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
@@ -50,10 +70,13 @@ import { createCounterExample } from "./tlc-ext";
50
70
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
51
71
  import {
52
72
  combineHash,
73
+ createModelValue,
74
+ formatState,
53
75
  formatValue,
54
76
  getValueHash,
55
77
  isFunctionValue,
56
78
  isSameValue,
79
+ isUpdatedElementOf,
57
80
  setStringOrder,
58
81
  toFiniteFunction,
59
82
  type Value,
@@ -72,6 +95,8 @@ export interface CheckOptions {
72
95
  workers?: number;
73
96
  // TLC's -lncheck: "final" checks liveness only on the complete state graph.
74
97
  livenessCheck?: "default" | "final";
98
+ // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
99
+ dump?: StateDump;
75
100
  }
76
101
 
77
102
  export type CheckStatus =
@@ -93,6 +118,8 @@ export interface TraceStep {
93
118
 
94
119
  export interface Violation {
95
120
  name: string;
121
+ // Every temporal property that a liveness counterexample violates, in the configuration's order.
122
+ properties?: string[];
96
123
  trace: TraceStep[];
97
124
  loopStart: number | undefined;
98
125
  loopLabel?: string;
@@ -139,6 +166,13 @@ interface NamedExpression {
139
166
 
140
167
  interface StateCheck extends NamedExpression {
141
168
  variables: number[] | undefined;
169
+ membership: Membership | undefined;
170
+ }
171
+
172
+ // A conjunct `x \in S` whose S reads no variables.
173
+ interface Membership {
174
+ variable: number;
175
+ set: Expression;
142
176
  }
143
177
 
144
178
  interface ActionProperty {
@@ -217,7 +251,7 @@ const getConstantValue = (name: string, definition: Definition, environment: Env
217
251
  try {
218
252
  return evaluate(createIdentifier(name), getContext(environment, undefined, undefined));
219
253
  } catch (error) {
220
- if (error instanceof TlaEvaluationError) return undefined;
254
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
221
255
  throw error;
222
256
  }
223
257
  };
@@ -246,8 +280,11 @@ const getInvariants = (names: string[], environment: Environment) => {
246
280
  levels.params.size === 0
247
281
  ? ""
248
282
  : "\nNote that a bug can cause TLC to incorrectly report this error.\nIf you believe your TLA+ or PlusCal specification to be correct,\nplease check if this bug described in LevelNode.java starting at line 590ff affects you.";
249
- throw new TlaConfigError(
250
- `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
283
+ throw setExitCode(
284
+ new TlaConfigError(
285
+ `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
286
+ ),
287
+ EXIT_STATUS.safetyEvaluationFailure,
251
288
  );
252
289
  }
253
290
  return [{ name, expression: createIdentifier(name), scope: undefined }];
@@ -345,8 +382,11 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
345
382
  conjunct.kind === "Always" &&
346
383
  getLevel(conjunct.expression, item.scope, environment) < ACTION_LEVEL
347
384
  ) {
348
- throw new TlaConfigError(
349
- `TLC cannot handle []P in the specification ${config.specification} when P is a state predicate`,
385
+ throw setExitCode(
386
+ new TlaConfigError(
387
+ `TLC cannot handle the temporal formula ${describeRange(conjunct.expression)}`,
388
+ ),
389
+ EXIT_STATUS.error,
350
390
  );
351
391
  }
352
392
  const level = getLevel(conjunct, item.scope, environment);
@@ -416,12 +456,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
416
456
  config.properties.forEach((name) => {
417
457
  const definition = getConfigPredicate("property", name, environment);
418
458
  if (!definition) return;
419
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
459
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
420
460
  const conjunct = item.expression;
421
461
  if (isConstantTrue(item, environment, "property")) return;
422
462
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
423
463
  properties.actionProperties.push({
424
- name,
464
+ name: item.name,
425
465
  box: conjunct.expression,
426
466
  action: conjunct.expression.action,
427
467
  subscript: conjunct.expression.subscript,
@@ -433,12 +473,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
433
473
  conjunct.kind === "Always" &&
434
474
  getLevel(conjunct.expression, item.scope, environment) <= 1
435
475
  ) {
436
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
476
+ // TLC names the invariant []P after P when P is an operator name.
477
+ const expression = conjunct.expression;
478
+ properties.invariants.push({
479
+ name: expression.kind === "Identifier" ? expression.name : item.name,
480
+ expression,
481
+ scope: item.scope,
482
+ });
437
483
  return;
438
484
  }
439
485
  const level = getLevel(conjunct, item.scope, environment);
440
486
  if (level < ACTION_LEVEL) {
441
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
487
+ properties.initialPredicates.push({
488
+ name: item.name,
489
+ expression: conjunct,
490
+ scope: item.scope,
491
+ });
442
492
  return;
443
493
  }
444
494
  if (level === ACTION_LEVEL) {
@@ -481,14 +531,34 @@ const getPossiblePredicates = (names: string[], environment: Environment) =>
481
531
  return { name, expression, scope: undefined };
482
532
  });
483
533
 
534
+ const getMembership = (
535
+ expression: Expression,
536
+ variables: number[] | undefined,
537
+ environment: Environment,
538
+ ): Membership | undefined => {
539
+ if (expression.kind !== "Apply" || expression.operator !== "\\in" || variables?.length !== 1)
540
+ return undefined;
541
+ const element = expression.args[0];
542
+ if (element.kind !== "Identifier" || isLocallyResolved(element)) return undefined;
543
+ return environment.variableIndex.get(element.name) === variables[0]
544
+ ? { variable: variables[0], set: expression.args[1] }
545
+ : undefined;
546
+ };
547
+
484
548
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
485
549
  named.flatMap((item) =>
486
- getConjuncts(item.expression, environment).map((expression) => ({
487
- name: item.name,
488
- expression,
489
- scope: item.scope,
490
- variables: getReadVariables(expression, environment),
491
- })),
550
+ getConjuncts(item.expression, environment).map((expression) => {
551
+ // A LET or an argument in the scope can read variables the expression doesn't name.
552
+ const variables =
553
+ item.scope === undefined ? getReadVariables(expression, environment) : undefined;
554
+ return {
555
+ name: item.name,
556
+ expression,
557
+ scope: item.scope,
558
+ variables,
559
+ membership: getMembership(expression, variables, environment),
560
+ };
561
+ }),
492
562
  );
493
563
 
494
564
  const isUnchangedFor = (stateCheck: StateCheck, state: Value[], parent: Value[] | undefined) => {
@@ -727,11 +797,13 @@ export const createSearch = (
727
797
  if (view !== undefined || isFingerprintedLikeTlc) {
728
798
  return BigInt64Array.from(states, getTlcStateFingerprint);
729
799
  }
730
- const indices = getTlcOrder();
731
- const getFingerprint = createTlcFingerprinter();
732
- return BigInt64Array.from(fingerprintStates, (state) =>
733
- getFingerprint(indices.map((index) => state[index])),
800
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
801
+ const fingerprint = createTlcFingerprinter(
802
+ getTlcOrder(),
803
+ new Int32Array(fingerprints.buffer),
734
804
  );
805
+ fingerprintStates.forEach(fingerprint);
806
+ return fingerprints;
735
807
  },
736
808
  getFingerprintState: (state) => {
737
809
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -743,10 +815,16 @@ export const createSearch = (
743
815
  invariants.find((invariant) => {
744
816
  if (isUnchangedFor(invariant, state, parent)) return false;
745
817
  try {
746
- return !holdsLikeTlc(
747
- invariant.expression,
748
- getContext(environment, state, undefined, invariant.scope),
749
- );
818
+ const context = getContext(environment, state, undefined, invariant.scope);
819
+ const membership = invariant.membership;
820
+ // The parent satisfies every invariant, so only the entries the step changed can fail.
821
+ return parent && membership
822
+ ? !isUpdatedElementOf(
823
+ state[membership.variable],
824
+ parent[membership.variable],
825
+ evaluate(membership.set, context),
826
+ )
827
+ : !holdsLikeTlc(invariant.expression, context);
750
828
  } catch (error) {
751
829
  // TLC reports a failure only on a state after the initial states as an invariant failure.
752
830
  if (!parent) throw error;
@@ -757,11 +835,17 @@ export const createSearch = (
757
835
  }
758
836
  }),
759
837
  satisfiesConstraints: (state, parent) =>
760
- constraints.every(
761
- (constraint) =>
762
- isUnchangedFor(constraint, state, parent) ||
763
- holdsLikeTlc(constraint.expression, getContext(environment, state, undefined)),
764
- ),
838
+ constraints.every((constraint) => {
839
+ try {
840
+ return (
841
+ isUnchangedFor(constraint, state, parent) ||
842
+ holdsLikeTlc(constraint.expression, getContext(environment, state, undefined))
843
+ );
844
+ } catch (error) {
845
+ // TLC reports a failing constraint on a successor like a failure of the next-state relation.
846
+ throw parent ? toNextStateError(error) : error;
847
+ }
848
+ }),
765
849
  findFailedInitialPredicate: (state) =>
766
850
  properties.initialPredicates.find(
767
851
  (predicate) =>
@@ -787,18 +871,20 @@ export const createSearch = (
787
871
  )
788
872
  );
789
873
  } catch (error) {
790
- throw withHeadline(error, `Evaluating action property ${property.name} failed.`);
874
+ throw withHeadline(
875
+ withNextStateExitCode(error),
876
+ `Evaluating action property ${property.name} failed.`,
877
+ );
791
878
  }
792
879
  }),
793
880
  satisfiesActionConstraints: (state, next) =>
794
- actionConstraints.every((constraint) =>
795
- holdsLikeTlc(
796
- constraint.expression,
797
- getContext(environment, state, next),
798
- (expression) =>
799
- `TLC threw an unexpected exception.\nThis was probably caused by an error in the spec or model.\nSee the User Output or TLC Console for clues to what happened.\nThe exception was a java.lang.RuntimeException\n: ${getExpectedBoolean(expression, environment)}`,
800
- ),
801
- ),
881
+ actionConstraints.every((constraint) => {
882
+ try {
883
+ return holdsLikeTlc(constraint.expression, getContext(environment, state, next));
884
+ } catch (error) {
885
+ throw toNextStateError(error);
886
+ }
887
+ }),
802
888
  trackStatePossible:
803
889
  statePossible.length === 0
804
890
  ? ignorePossible
@@ -824,6 +910,23 @@ export const createSearch = (
824
910
  };
825
911
  };
826
912
 
913
+ // TLC exits with the code of a standard module's failure only when the failure escapes the
914
+ // computation of next states. In every other phase, the phase decides the code.
915
+ const withNextStateExitCode = (error: unknown) =>
916
+ error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
917
+
918
+ // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
919
+ // module raised it as an EvalException.
920
+ const toNextStateError = (error: unknown) =>
921
+ error instanceof TlaEvaluationError &&
922
+ !(error instanceof TlaModuleError) &&
923
+ !(error instanceof TlaIncompleteStateError)
924
+ ? setExitCode(
925
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
926
+ getErrorExitCode(error),
927
+ )
928
+ : withNextStateExitCode(error);
929
+
827
930
  const withHeadline = (error: unknown, headline: string) =>
828
931
  error instanceof TlaEvaluationError
829
932
  ? setExitCode(
@@ -832,8 +935,22 @@ const withHeadline = (error: unknown, headline: string) =>
832
935
  )
833
936
  : error;
834
937
 
938
+ // TLC finishes the -dump file whether or not the search finds a violation.
835
939
  export const checkSequentially = (options: CheckOptions): CheckResult => {
836
- setNextStatePhase(false);
940
+ const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
941
+ try {
942
+ return searchStates(options, stateWriter);
943
+ } catch (error) {
944
+ // TLC reports a stack overflow outside the search as a failure of its own, with exit code 255.
945
+ throw isStackOverflow(error)
946
+ ? setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error)
947
+ : error;
948
+ } finally {
949
+ stateWriter?.close();
950
+ }
951
+ };
952
+
953
+ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
837
954
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
838
955
  const onPrint = options.onPrint ?? console.log;
839
956
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
@@ -903,7 +1020,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
903
1020
  });
904
1021
 
905
1022
  const search = createSearch(config, environment, () =>
906
- getTlcVariableOrder(options.source, options.loadModule),
1023
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable"),
907
1024
  );
908
1025
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
909
1026
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
@@ -929,8 +1046,36 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
929
1046
  const getFingerprintState = search.getFingerprintState;
930
1047
  const nextActions = { value: undefined as SpecAction[] | undefined };
931
1048
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
1049
+ const tlcFingerprints: number[] = [];
932
1050
  const liveness = withLivenessExitCode(() =>
933
- createLivenessChecker(search.properties.liveness, spec.temporals, environment),
1051
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
1052
+ getFingerprint: (index) =>
1053
+ (tlcFingerprints[index] ??= Number(
1054
+ BigInt.asIntN(32, runtime.getFingerprint(states[index])),
1055
+ )),
1056
+ getSuccessors: (state) => {
1057
+ const successors: LiveSuccessor[] = [];
1058
+ if (spec.next === undefined) return successors;
1059
+ forEachSuccessor(
1060
+ spec.next,
1061
+ state,
1062
+ environment,
1063
+ (successor) => {
1064
+ canonicalizeState(successor.state);
1065
+ const isInModel =
1066
+ search.satisfiesConstraints(successor.state, state) &&
1067
+ search.satisfiesActionConstraints(state, successor.state);
1068
+ if (!isInModel) return false;
1069
+ const fingerprintState = getFingerprintState(successor.state);
1070
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1071
+ successors.push({ index, state: successor.state });
1072
+ return false;
1073
+ },
1074
+ spec.scope,
1075
+ );
1076
+ return successors;
1077
+ },
1078
+ }),
934
1079
  );
935
1080
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
936
1081
 
@@ -939,7 +1084,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
939
1084
  const parents: number[] = [];
940
1085
  const actions: (string | undefined)[] = [];
941
1086
  const depths: number[] = [];
942
- const buckets = new Map<number, number | number[]>();
1087
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1088
+ // and its index plus one side by side, probed by the hash.
1089
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
943
1090
  const canonicalizeState = createCanonicalizer();
944
1091
 
945
1092
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -952,11 +1099,16 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
952
1099
  position: number,
953
1100
  loopStart: number | undefined,
954
1101
  ) => {
955
- const state = steps[position].state;
956
- const next = (steps[position + 1] ?? steps[loopStart ?? position]).state;
957
1102
  // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
958
1103
  runtime.getLevel = () => position + 1;
959
1104
  runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
1105
+ return evaluateAlias(
1106
+ alias,
1107
+ steps[position].state,
1108
+ (steps[position + 1] ?? steps[loopStart ?? position]).state,
1109
+ );
1110
+ };
1111
+ const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) => {
960
1112
  try {
961
1113
  const body = getConfigDefinition("alias", alias, environment).body;
962
1114
  const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
@@ -1058,7 +1210,17 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1058
1210
  trace: TraceStep[],
1059
1211
  initialState?: Value[],
1060
1212
  failureOutDegrees?: number[],
1061
- ) => {
1213
+ ): CheckResult => {
1214
+ // TLC exits with 255 on a stack overflow while it computes next states, and prints the
1215
+ // behavior up to the state it was expanding.
1216
+ if (isStackOverflow(error)) {
1217
+ return current.isExpanding
1218
+ ? toFailure(
1219
+ setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error),
1220
+ getStateTrace(current.index),
1221
+ )
1222
+ : toFailure(new TlaEvaluationError(STACK_OVERFLOW), trace, initialState);
1223
+ }
1062
1224
  if (!(error instanceof TlaEvaluationError)) throw error;
1063
1225
  return {
1064
1226
  ...createResult("error", undefined, {
@@ -1071,7 +1233,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1071
1233
  outDegrees: failureOutDegrees,
1072
1234
  };
1073
1235
  };
1074
- const getPathTrace = (path: number[], loopStart?: number) => {
1236
+ const getPathSteps = (path: number[], loopStart?: number) => {
1075
1237
  const steps = getPathStates(path, NEXT_RECOVERY_FAILURE);
1076
1238
  const last = steps[steps.length - 1].state;
1077
1239
  const isClosed =
@@ -1080,7 +1242,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1080
1242
  loopStart === path.length - 1 ||
1081
1243
  findSuccessorWithFingerprint(last, path[loopStart]) !== undefined;
1082
1244
  if (!isClosed) throw new TlaEvaluationError(NEXT_RECOVERY_FAILURE);
1083
- return toTrace(steps, path, loopStart);
1245
+ return steps;
1084
1246
  };
1085
1247
  const getStateHash = (state: Value[]) => {
1086
1248
  let hash = 0x811c9dc5;
@@ -1094,19 +1256,35 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1094
1256
  }
1095
1257
  return true;
1096
1258
  };
1259
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1097
1260
  const findStateIndex = (hash: number, state: Value[]) => {
1098
- const bucket = buckets.get(hash);
1099
- if (bucket === undefined) return -1;
1100
- if (typeof bucket === "number") {
1101
- return isSameState(fingerprintStates[bucket], state) ? bucket : -1;
1261
+ const mask = seen.slots.length - 1;
1262
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1263
+ const entry = seen.slots[slot + 1];
1264
+ if (entry === 0) return -1;
1265
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1266
+ return entry - 1;
1267
+ }
1102
1268
  }
1103
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1269
+ };
1270
+ const insertSeen = (hash: number, entry: number) => {
1271
+ const mask = seen.slots.length - 1;
1272
+ let slot = getSlot(hash);
1273
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1274
+ seen.slots[slot] = hash;
1275
+ seen.slots[slot + 1] = entry;
1104
1276
  };
1105
1277
  const markSeen = (hash: number, index: number) => {
1106
- const bucket = buckets.get(hash);
1107
- if (bucket === undefined) buckets.set(hash, index);
1108
- else if (typeof bucket === "number") buckets.set(hash, [bucket, index]);
1109
- else bucket.push(index);
1278
+ seen.size++;
1279
+ if (seen.size * 4 > seen.slots.length) {
1280
+ const slots = seen.slots;
1281
+ seen.slots = new Int32Array(slots.length * 2);
1282
+ seen.shift--;
1283
+ for (let slot = 0; slot < slots.length; slot += 2) {
1284
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1285
+ }
1286
+ }
1287
+ insertSeen(hash, index + 1);
1110
1288
  };
1111
1289
  const countDistinctState = (depth: number) => {
1112
1290
  runtime.distinctStates = states.length + 1;
@@ -1132,6 +1310,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1132
1310
  isExpanding: false,
1133
1311
  candidate: undefined as Value[] | undefined,
1134
1312
  candidateLevel: 0,
1313
+ isFingerprinting: false,
1135
1314
  livenessSource: -1,
1136
1315
  };
1137
1316
  const getPath = (index: number): Value[][] =>
@@ -1146,7 +1325,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1146
1325
  };
1147
1326
  runtime.getCurrentState = () => (current.index === -1 ? undefined : states[current.index]);
1148
1327
  runtime.setLivenessSource = (index) => {
1149
- current.livenessSource = index;
1328
+ current.livenessSource = index ?? -1;
1150
1329
  };
1151
1330
  runtime.getLevel = (state) => {
1152
1331
  const source = current.livenessSource;
@@ -1157,6 +1336,18 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1157
1336
  return current.isExpanding ? depths[current.index] + 1 : 0;
1158
1337
  };
1159
1338
 
1339
+ const getGraphState = (state: Value[], level: number): GraphState => ({
1340
+ fingerprint: BigInt.asIntN(64, runtime.getFingerprint(state)),
1341
+ level,
1342
+ getLabel: () =>
1343
+ formatState(
1344
+ config.alias === undefined
1345
+ ? toRecord(state)
1346
+ : evaluateAlias(config.alias, state, undefined),
1347
+ ),
1348
+ getText: () => formatState(toRecord(state)),
1349
+ });
1350
+
1160
1351
  const visitInitialState = (state: Value[]) => {
1161
1352
  canonicalizeState(state);
1162
1353
  runtime.generatedStates++;
@@ -1173,6 +1364,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1173
1364
  countDistinctState(1);
1174
1365
  runtime.queueSize++;
1175
1366
  liveness?.addInitialState(states.length, state);
1367
+ stateWriter?.writeInitialState(getGraphState(state, 1));
1176
1368
  }
1177
1369
  const violated = search.findViolatedInvariant(state);
1178
1370
  if (violated) {
@@ -1193,20 +1385,36 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1193
1385
  addState(state, fingerprintState, -1, undefined);
1194
1386
  return undefined;
1195
1387
  };
1196
- const visitSuccessor = (index: number, successor: Successor, liveSuccessors: LiveSuccessor[]) => {
1388
+ const visitSuccessor = (
1389
+ index: number,
1390
+ successor: Successor,
1391
+ liveSuccessors: LiveSuccessor[],
1392
+ source: GraphState | undefined,
1393
+ action: SpecAction | undefined,
1394
+ ) => {
1197
1395
  const state = states[index];
1198
1396
  runtime.generatedStates++;
1199
1397
  current.candidate = successor.state;
1200
1398
  current.candidateLevel = depths[index] + 1;
1201
1399
  if (isCanonicalizedFirst) canonicalizeState(successor.state);
1400
+ current.isFingerprinting = true;
1202
1401
  const fingerprintState = getFingerprintState(successor.state);
1203
1402
  const hash = getStateHash(fingerprintState);
1403
+ current.isFingerprinting = false;
1204
1404
  const found = findStateIndex(hash, fingerprintState);
1205
1405
  const isStateInModel = search.satisfiesConstraints(successor.state, state);
1206
1406
  if (isStateInModel) search.trackStatePossible(successor.state);
1207
1407
  const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1208
1408
  if (isInModel) search.trackActionPossible(state, successor.state);
1209
1409
  const existing = isInModel ? found : -1;
1410
+ if (source && isInModel) {
1411
+ stateWriter?.writeSuccessor(
1412
+ source,
1413
+ getGraphState(successor.state, depths[index] + 1),
1414
+ existing !== -1,
1415
+ action && { name: action.name, signature: getActionSignature(action) },
1416
+ );
1417
+ }
1210
1418
  if (existing !== -1 && liveness) {
1211
1419
  const stored = states[existing];
1212
1420
  const isStored = stored.every((value, position) => value === successor.state[position]);
@@ -1278,23 +1486,57 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1278
1486
  }
1279
1487
  return createSuccess();
1280
1488
  }
1489
+ // TLC labels and colors an edge of the -dump state graph by the action that generated it. When
1490
+ // the graph names its edges, the search generates successors action by action, as TLC does.
1491
+ const isNamingEdges = Boolean(
1492
+ options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1493
+ );
1494
+ const forEachActionSuccessor = (
1495
+ state: Value[],
1496
+ onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1497
+ ) => {
1498
+ if (!isNamingEdges) {
1499
+ return forEachSuccessor(
1500
+ next,
1501
+ state,
1502
+ environment,
1503
+ (successor) => onSuccessor(successor, undefined),
1504
+ spec.scope,
1505
+ );
1506
+ }
1507
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1508
+ const progress = { isStopped: false };
1509
+ return nextActions.value.reduce((count, action) => {
1510
+ if (progress.isStopped) return count;
1511
+ return (
1512
+ count +
1513
+ forEachSuccessor(
1514
+ action.expression,
1515
+ state,
1516
+ environment,
1517
+ (successor) => {
1518
+ progress.isStopped = onSuccessor(successor, action);
1519
+ return progress.isStopped;
1520
+ },
1521
+ action.scope,
1522
+ )
1523
+ );
1524
+ }, 0);
1525
+ };
1281
1526
  const expandState = (index: number) => {
1282
1527
  const state = states[index];
1283
1528
  const liveSuccessors: LiveSuccessor[] = [];
1284
- const successorCount = forEachSuccessor(
1285
- next,
1286
- state,
1287
- environment,
1288
- (successor) => {
1289
- try {
1290
- outcome.result = visitSuccessor(index, successor, liveSuccessors);
1291
- } catch (error) {
1292
- outcome.result = toFailure(error, getTrace(index, successor));
1293
- }
1294
- return outcome.result !== undefined;
1295
- },
1296
- spec.scope,
1297
- );
1529
+ const source = stateWriter && getGraphState(state, depths[index]);
1530
+ const successorCount = forEachActionSuccessor(state, (successor, action) => {
1531
+ try {
1532
+ outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1533
+ } catch (error) {
1534
+ // TLC reports a successor it cannot fingerprint as a failure of the state it expands.
1535
+ if (current.isFingerprinting) throw error;
1536
+ outcome.result = toFailure(error, getTrace(index, successor));
1537
+ }
1538
+ return outcome.result !== undefined;
1539
+ });
1298
1540
  current.isExpanding = false;
1299
1541
  if (outcome.result) return outcome.result;
1300
1542
  if (successorCount === 0 && config.checkDeadlock) {
@@ -1302,32 +1544,68 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1302
1544
  }
1303
1545
  try {
1304
1546
  const accepted = liveness?.addState(index, state, liveSuccessors);
1305
- current.livenessSource = -1;
1306
- if (!accepted) return undefined;
1547
+ if (!liveness || !accepted) return undefined;
1548
+ const steps = getPathSteps(accepted);
1549
+ const properties = liveness.getViolatedProperties(
1550
+ steps.map((step) => step.state),
1551
+ steps.length - 1,
1552
+ );
1307
1553
  return reportViolation("property-violation", {
1308
- name: accepted.name,
1309
- trace: getPathTrace(accepted.path),
1554
+ name: properties[0],
1555
+ properties,
1556
+ trace: toTrace(steps, accepted),
1310
1557
  });
1311
1558
  } catch (error) {
1312
1559
  return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1313
1560
  }
1314
1561
  };
1315
- const reportLasso = (lasso: Lasso) => {
1562
+ // TLC names the action when the next-state relation has more than one, and prints the
1563
+ // incomplete successor with null for each variable it leaves undefined.
1564
+ const reportIncompleteSuccessor = (error: TlaIncompleteStateError, index: number) => {
1565
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1566
+ const actions = nextActions.value;
1567
+ const action =
1568
+ actions.length === 1 ? actions[0] : actions.find((item) => item.name === error.action);
1569
+ const variables = `variable${error.missing.length > 1 ? "s are" : " is"} not defined: ${error.missing.join(", ")}.\n`;
1570
+ runtime.generatedStates++;
1571
+ return toFailure(
1572
+ actions.length === 1
1573
+ ? error
1574
+ : new TlaEvaluationError(
1575
+ `Successor state is not completely specified by action ${error.action} of the next-state relation. The following ${variables}`,
1576
+ ),
1577
+ [
1578
+ ...getStateTrace(index),
1579
+ {
1580
+ action: error.action,
1581
+ label: action && getActionLabel(action),
1582
+ state: toRecord(error.state.map((value) => value ?? createModelValue("null"))),
1583
+ },
1584
+ ],
1585
+ );
1586
+ };
1587
+ // TLC names the properties and the step back into the cycle from the states it prints.
1588
+ const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1316
1589
  const path = [...lasso.prefix, ...lasso.cycle];
1317
- const trace = getPathTrace(path, lasso.prefix.length);
1318
- const back = path[lasso.prefix.length];
1590
+ const loopStart = lasso.prefix.length;
1591
+ const steps = getPathSteps(path, loopStart);
1592
+ const trace = toTrace(steps, path, loopStart);
1593
+ const properties = checker.getViolatedProperties(
1594
+ steps.map((step) => step.state),
1595
+ loopStart,
1596
+ );
1597
+ const back = path[loopStart];
1319
1598
  const last = path[path.length - 1];
1599
+ const lastState = steps[steps.length - 1].state;
1320
1600
  const loopLabel =
1321
- back === last ? undefined : withoutOutput(() => getLabel(last, states[last], states[back]));
1601
+ back === last ? undefined : withoutOutput(() => getLabel(last, lastState, states[back]));
1322
1602
  return reportViolation(
1323
1603
  "liveness-violation",
1324
- { name: lasso.name, trace, loopStart: lasso.prefix.length, loopLabel },
1604
+ { name: properties[0], properties, trace, loopStart, loopLabel },
1325
1605
  () =>
1326
1606
  back === last
1327
1607
  ? trace[trace.length - 1].action
1328
- : getTraceSuccessors(states[last]).find((successor) =>
1329
- isSameState(successor.state, states[back]),
1330
- )?.action,
1608
+ : findSuccessorWithFingerprint(lastState, back)?.action,
1331
1609
  );
1332
1610
  };
1333
1611
  const isPeriodic = liveness !== undefined && options.livenessCheck !== "final";
@@ -1340,11 +1618,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1340
1618
  if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1341
1619
  periodic.size = expanded;
1342
1620
  const lasso = liveness?.findViolation();
1343
- current.livenessSource = -1;
1344
1621
  periodic.time += performance.now() - now;
1345
1622
  return lasso;
1346
1623
  };
1347
- setNextStatePhase(true);
1348
1624
  for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1349
1625
  current.index = index;
1350
1626
  current.candidate = undefined;
@@ -1353,22 +1629,24 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1353
1629
  try {
1354
1630
  outcome.result = expandState(index);
1355
1631
  } catch (error) {
1356
- outcome.result = toFailure(error, getStateTrace(index));
1632
+ outcome.result =
1633
+ error instanceof TlaIncompleteStateError
1634
+ ? reportIncompleteSuccessor(error, index)
1635
+ : toFailure(toNextStateError(error), getStateTrace(index));
1357
1636
  }
1358
1637
  if (outcome.result) return outcome.result;
1359
1638
  outDegrees[getOutDegreeBucket()]++;
1360
1639
  expansion.newStates = 0;
1361
1640
  if (isPeriodic && performance.now() >= periodic.at) {
1362
1641
  const lasso = findPeriodicViolation(index + 1);
1363
- if (lasso) return reportLasso(lasso);
1642
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1364
1643
  }
1365
1644
  }
1366
1645
 
1367
1646
  current.index = -1;
1368
1647
  current.candidate = undefined;
1369
1648
  const lasso = liveness?.findViolation();
1370
- current.livenessSource = -1;
1371
- if (lasso) return reportLasso(lasso);
1649
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1372
1650
 
1373
1651
  const postconditionViolation = search.findPostconditionViolation();
1374
1652
  if (postconditionViolation) {