tla-ts 0.0.3-dev.30014f9 → 0.0.3-dev.3082068

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 (48) hide show
  1. package/README.md +5 -1
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +48 -22
  4. package/dist/index.d.ts +48 -22
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +1 -1
  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 +19 -16
  11. package/dist/run-cli.js +20 -17
  12. package/dist/transfer.cjs +36 -15
  13. package/dist/transfer.js +36 -15
  14. package/package.json +1 -1
  15. package/src/ast.ts +93 -0
  16. package/src/check.ts +452 -98
  17. package/src/cli-options.ts +11 -5
  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 +76 -3
  23. package/src/evaluate.ts +163 -156
  24. package/src/exit-codes.ts +39 -42
  25. package/src/instances.ts +16 -15
  26. package/src/levels.ts +62 -34
  27. package/src/live-check.ts +772 -0
  28. package/src/liveness.ts +120 -543
  29. package/src/parallel-worker.ts +2 -2
  30. package/src/parallel.ts +5 -2
  31. package/src/parser.ts +21 -10
  32. package/src/resolve.ts +122 -44
  33. package/src/run-cli.ts +92 -19
  34. package/src/runtime.ts +3 -1
  35. package/src/spec-description.ts +19 -8
  36. package/src/standard-modules.ts +9 -8
  37. package/src/state-graph.ts +157 -0
  38. package/src/subexpressions.ts +10 -10
  39. package/src/successors.ts +146 -35
  40. package/src/symmetry.ts +16 -6
  41. package/src/tableau.ts +51 -24
  42. package/src/tlc-ext.ts +29 -12
  43. package/src/tlc-module.ts +14 -33
  44. package/src/tlc-modules.ts +4 -0
  45. package/src/tlc-order.ts +8 -4
  46. package/src/tlc-random.ts +9 -6
  47. package/src/tlc-summary.ts +20 -5
  48. package/src/values.ts +124 -21
package/src/check.ts CHANGED
@@ -1,32 +1,45 @@
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
+ TlaIllegalStateError,
20
+ TlaIncompleteStateError,
21
+ TlaModuleError,
22
+ UNEXPECTED_EXCEPTION,
23
+ } from "./errors";
24
+ import { EXIT_STATUS, setExitCode, withLivenessExitCode } from "./exit-codes";
7
25
  import {
8
26
  describeRange,
9
27
  evaluate,
10
28
  expectBoolean,
11
- formatRange,
12
- getChildren,
13
29
  getDefinition,
14
30
  isConstantLevel,
15
31
  isImpure,
16
- isLocallyResolved,
17
32
  type Context,
18
33
  type Environment,
19
34
  type Scope,
20
35
  } from "./evaluate";
21
36
  import {
22
37
  createLivenessChecker,
23
- expandTemporal,
24
- getLevel,
25
38
  type Lasso,
39
+ type LivenessChecker,
26
40
  type LiveSuccessor,
27
- type ScopedExpression,
28
- type TemporalProperty,
29
- } from "./liveness";
41
+ } from "./live-check";
42
+ import { expandTemporal, getLevel, type ScopedExpression, type TemporalProperty } from "./liveness";
30
43
  import { ACTION_LEVEL, createLevelAnalyzer, TEMPORAL_LEVEL } from "./levels";
31
44
  import { prettyPrint } from "./pretty-print";
32
45
  import {
@@ -38,12 +51,19 @@ import {
38
51
  } from "./successors";
39
52
  import {
40
53
  getActionLabel,
54
+ getActionSignature,
41
55
  getNextActions,
42
56
  getSpecificationValue,
43
57
  type SpecAction,
44
58
  } from "./spec-description";
59
+ import {
60
+ createStateWriter,
61
+ type GraphState,
62
+ type StateDump,
63
+ type StateWriter,
64
+ } from "./state-graph";
45
65
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
46
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
66
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
47
67
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
48
68
  import { createCanonicalizer } from "./canonical";
49
69
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
@@ -51,6 +71,8 @@ import { createCounterExample } from "./tlc-ext";
51
71
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
52
72
  import {
53
73
  combineHash,
74
+ createModelValue,
75
+ formatState,
54
76
  formatValue,
55
77
  getValueHash,
56
78
  isFunctionValue,
@@ -74,6 +96,8 @@ export interface CheckOptions {
74
96
  workers?: number;
75
97
  // TLC's -lncheck: "final" checks liveness only on the complete state graph.
76
98
  livenessCheck?: "default" | "final";
99
+ // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
100
+ dump?: StateDump;
77
101
  }
78
102
 
79
103
  export type CheckStatus =
@@ -95,6 +119,8 @@ export interface TraceStep {
95
119
 
96
120
  export interface Violation {
97
121
  name: string;
122
+ // Every temporal property that a liveness counterexample violates, in the configuration's order.
123
+ properties?: string[];
98
124
  trace: TraceStep[];
99
125
  loopStart: number | undefined;
100
126
  loopLabel?: string;
@@ -115,6 +141,14 @@ export interface EvaluationFailure {
115
141
  trace: TraceStep[];
116
142
  initialState: Record<string, Value> | undefined;
117
143
  exitCode: number;
144
+ replay?: Replay;
145
+ isWithoutStatistics?: boolean;
146
+ }
147
+
148
+ // TLC replays a failed step to print the expressions it was evaluating when the replay failed.
149
+ export interface Replay {
150
+ output: string[];
151
+ callStack: string[] | undefined;
118
152
  }
119
153
 
120
154
  export interface CheckResult {
@@ -226,7 +260,7 @@ const getConstantValue = (name: string, definition: Definition, environment: Env
226
260
  try {
227
261
  return evaluate(createIdentifier(name), getContext(environment, undefined, undefined));
228
262
  } catch (error) {
229
- if (error instanceof TlaEvaluationError) return undefined;
263
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
230
264
  throw error;
231
265
  }
232
266
  };
@@ -255,8 +289,11 @@ const getInvariants = (names: string[], environment: Environment) => {
255
289
  levels.params.size === 0
256
290
  ? ""
257
291
  : "\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.";
258
- throw new TlaConfigError(
259
- `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
292
+ throw setExitCode(
293
+ new TlaConfigError(
294
+ `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
295
+ ),
296
+ EXIT_STATUS.safetyEvaluationFailure,
260
297
  );
261
298
  }
262
299
  return [{ name, expression: createIdentifier(name), scope: undefined }];
@@ -354,8 +391,11 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
354
391
  conjunct.kind === "Always" &&
355
392
  getLevel(conjunct.expression, item.scope, environment) < ACTION_LEVEL
356
393
  ) {
357
- throw new TlaConfigError(
358
- `TLC cannot handle []P in the specification ${config.specification} when P is a state predicate`,
394
+ throw setExitCode(
395
+ new TlaConfigError(
396
+ `TLC cannot handle the temporal formula ${describeRange(conjunct.expression)}`,
397
+ ),
398
+ EXIT_STATUS.error,
359
399
  );
360
400
  }
361
401
  const level = getLevel(conjunct, item.scope, environment);
@@ -425,12 +465,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
425
465
  config.properties.forEach((name) => {
426
466
  const definition = getConfigPredicate("property", name, environment);
427
467
  if (!definition) return;
428
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
468
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
429
469
  const conjunct = item.expression;
430
470
  if (isConstantTrue(item, environment, "property")) return;
431
471
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
432
472
  properties.actionProperties.push({
433
- name,
473
+ name: item.name,
434
474
  box: conjunct.expression,
435
475
  action: conjunct.expression.action,
436
476
  subscript: conjunct.expression.subscript,
@@ -442,12 +482,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
442
482
  conjunct.kind === "Always" &&
443
483
  getLevel(conjunct.expression, item.scope, environment) <= 1
444
484
  ) {
445
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
485
+ // TLC names the invariant []P after P when P is an operator name.
486
+ const expression = conjunct.expression;
487
+ properties.invariants.push({
488
+ name: expression.kind === "Identifier" ? expression.name : item.name,
489
+ expression,
490
+ scope: item.scope,
491
+ });
446
492
  return;
447
493
  }
448
494
  const level = getLevel(conjunct, item.scope, environment);
449
495
  if (level < ACTION_LEVEL) {
450
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
496
+ properties.initialPredicates.push({
497
+ name: item.name,
498
+ expression: conjunct,
499
+ scope: item.scope,
500
+ });
451
501
  return;
452
502
  }
453
503
  if (level === ACTION_LEVEL) {
@@ -507,7 +557,9 @@ const getMembership = (
507
557
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
508
558
  named.flatMap((item) =>
509
559
  getConjuncts(item.expression, environment).map((expression) => {
510
- const variables = getReadVariables(expression, environment);
560
+ // A LET or an argument in the scope can read variables the expression doesn't name.
561
+ const variables =
562
+ item.scope === undefined ? getReadVariables(expression, environment) : undefined;
511
563
  return {
512
564
  name: item.name,
513
565
  expression,
@@ -754,11 +806,13 @@ export const createSearch = (
754
806
  if (view !== undefined || isFingerprintedLikeTlc) {
755
807
  return BigInt64Array.from(states, getTlcStateFingerprint);
756
808
  }
757
- const indices = getTlcOrder();
758
- const getFingerprint = createTlcFingerprinter();
759
- return BigInt64Array.from(fingerprintStates, (state) =>
760
- getFingerprint(indices.map((index) => state[index])),
809
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
810
+ const fingerprint = createTlcFingerprinter(
811
+ getTlcOrder(),
812
+ new Int32Array(fingerprints.buffer),
761
813
  );
814
+ fingerprintStates.forEach(fingerprint);
815
+ return fingerprints;
762
816
  },
763
817
  getFingerprintState: (state) => {
764
818
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -790,11 +844,17 @@ export const createSearch = (
790
844
  }
791
845
  }),
792
846
  satisfiesConstraints: (state, parent) =>
793
- constraints.every(
794
- (constraint) =>
795
- isUnchangedFor(constraint, state, parent) ||
796
- holdsLikeTlc(constraint.expression, getContext(environment, state, undefined)),
797
- ),
847
+ constraints.every((constraint) => {
848
+ try {
849
+ return (
850
+ isUnchangedFor(constraint, state, parent) ||
851
+ holdsLikeTlc(constraint.expression, getContext(environment, state, undefined))
852
+ );
853
+ } catch (error) {
854
+ // TLC reports a failing constraint on a successor like a failure of the next-state relation.
855
+ throw parent ? toNextStateError(error) : error;
856
+ }
857
+ }),
798
858
  findFailedInitialPredicate: (state) =>
799
859
  properties.initialPredicates.find(
800
860
  (predicate) =>
@@ -820,18 +880,20 @@ export const createSearch = (
820
880
  )
821
881
  );
822
882
  } catch (error) {
823
- throw withHeadline(error, `Evaluating action property ${property.name} failed.`);
883
+ throw withHeadline(
884
+ withNextStateExitCode(error),
885
+ `Evaluating action property ${property.name} failed.`,
886
+ );
824
887
  }
825
888
  }),
826
889
  satisfiesActionConstraints: (state, next) =>
827
- actionConstraints.every((constraint) =>
828
- holdsLikeTlc(
829
- constraint.expression,
830
- getContext(environment, state, next),
831
- (expression) =>
832
- `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)}`,
833
- ),
834
- ),
890
+ actionConstraints.every((constraint) => {
891
+ try {
892
+ return holdsLikeTlc(constraint.expression, getContext(environment, state, next));
893
+ } catch (error) {
894
+ throw toNextStateError(error);
895
+ }
896
+ }),
835
897
  trackStatePossible:
836
898
  statePossible.length === 0
837
899
  ? ignorePossible
@@ -857,6 +919,44 @@ export const createSearch = (
857
919
  };
858
920
  };
859
921
 
922
+ // TLC exits with the code of a standard module's failure only when the failure escapes the
923
+ // computation of next states. In every other phase, the phase decides the code.
924
+ const withNextStateExitCode = (error: unknown) =>
925
+ error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
926
+
927
+ // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
928
+ // module raised it as an EvalException.
929
+ const toNextStateError = (error: unknown) =>
930
+ error instanceof TlaEvaluationError &&
931
+ !(error instanceof TlaModuleError) &&
932
+ !(error instanceof TlaIncompleteStateError)
933
+ ? setExitCode(
934
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
935
+ getErrorExitCode(error),
936
+ )
937
+ : withNextStateExitCode(error);
938
+
939
+ // TLC keeps the stack only when an evaluation fails, and prints each expression on it once, however
940
+ // many times in a row it pushed it.
941
+ const getReplayedCallStack = (replay: () => void, trace: Expression[]) => {
942
+ try {
943
+ replay();
944
+ return undefined;
945
+ } catch (error) {
946
+ if (!(error instanceof TlaEvaluationError)) return [];
947
+ return trace
948
+ .flatMap((expression) => {
949
+ const range = expression.location.range;
950
+ return range
951
+ ? [
952
+ `Line ${range.start.line}, column ${range.start.column} to line ${range.end.line}, column ${range.end.column} in ${range.module}`,
953
+ ]
954
+ : [];
955
+ })
956
+ .filter((frame, index, frames) => index === 0 || frames[index - 1] !== frame);
957
+ }
958
+ };
959
+
860
960
  const withHeadline = (error: unknown, headline: string) =>
861
961
  error instanceof TlaEvaluationError
862
962
  ? setExitCode(
@@ -865,15 +965,30 @@ const withHeadline = (error: unknown, headline: string) =>
865
965
  )
866
966
  : error;
867
967
 
968
+ // TLC finishes the -dump file whether or not the search finds a violation.
868
969
  export const checkSequentially = (options: CheckOptions): CheckResult => {
869
- setNextStatePhase(false);
970
+ const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
971
+ try {
972
+ return searchStates(options, stateWriter);
973
+ } catch (error) {
974
+ // TLC reports a stack overflow outside the search as a failure of its own, with exit code 255.
975
+ throw isStackOverflow(error)
976
+ ? setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error)
977
+ : error;
978
+ } finally {
979
+ stateWriter?.close();
980
+ }
981
+ };
982
+
983
+ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
870
984
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
871
985
  const onPrint = options.onPrint ?? console.log;
872
986
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
873
987
  // before the trace would misplace them, so rebuilding a trace prints nothing.
874
- const output = { isMuted: false };
988
+ const output = { isMuted: false, replayed: undefined as string[] | undefined };
875
989
  const print = (text: string) => {
876
- if (!output.isMuted) onPrint(text);
990
+ if (output.replayed) output.replayed.push(text);
991
+ else if (!output.isMuted) onPrint(text);
877
992
  };
878
993
  const withoutOutput = <Result>(rebuild: () => Result) => {
879
994
  output.isMuted = true;
@@ -935,9 +1050,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
935
1050
  ),
936
1051
  });
937
1052
 
938
- const search = createSearch(config, environment, () =>
939
- getTlcVariableOrder(options.source, options.loadModule),
940
- );
1053
+ const getVariableOrder = () =>
1054
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable");
1055
+ const search = createSearch(config, environment, getVariableOrder);
941
1056
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
942
1057
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
943
1058
  if (!search) return createSuccess();
@@ -961,9 +1076,98 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
961
1076
  const spec = search.spec;
962
1077
  const getFingerprintState = search.getFingerprintState;
963
1078
  const nextActions = { value: undefined as SpecAction[] | undefined };
1079
+ const replayFailure = (
1080
+ result: CheckResult,
1081
+ replay: (tracedSearch: Search, traced: Environment) => void,
1082
+ ): CheckResult => {
1083
+ if (!result.failure) return result;
1084
+ const trace: Expression[] = [];
1085
+ const traced: Environment = { ...environment, evaluators: new WeakMap(), trace };
1086
+ const tracedSearch = createSearch(config, traced, getVariableOrder);
1087
+ if (!tracedSearch) return result;
1088
+ const replayed: string[] = [];
1089
+ output.replayed = replayed;
1090
+ const callStack = getReplayedCallStack(() => replay(tracedSearch, traced), trace);
1091
+ output.replayed = undefined;
1092
+ return { ...result, failure: { ...result.failure, replay: { output: replayed, callStack } } };
1093
+ };
1094
+ // TLC checks every initial state again, as when it first generated them.
1095
+ const replayInitialStates = (result: CheckResult) =>
1096
+ replayFailure(result, (tracedSearch, traced) => {
1097
+ if (spec.init === undefined) return;
1098
+ forEachInitialState(
1099
+ spec.init,
1100
+ traced,
1101
+ (state) => {
1102
+ tracedSearch.satisfiesConstraints(state);
1103
+ return (
1104
+ tracedSearch.findViolatedInvariant(state) !== undefined ||
1105
+ tracedSearch.findFailedInitialPredicate(state) !== undefined
1106
+ );
1107
+ },
1108
+ spec.scope,
1109
+ );
1110
+ });
1111
+ // TLC rebuilds the behavior up to the state it expanded before it replays the step.
1112
+ const rebuildBehavior = (index: number): void => {
1113
+ const parent = parents[index];
1114
+ if (parent === -1) {
1115
+ getSpecInitialStates();
1116
+ return;
1117
+ }
1118
+ rebuildBehavior(parent);
1119
+ getLabel(parent, states[parent], states[index]);
1120
+ };
1121
+ // TLC generates the successors of each action before it checks them. It checks the invariants
1122
+ // only of a successor outside the model, since it has seen the others.
1123
+ const replaySuccessors = (result: CheckResult, index: number) =>
1124
+ replayFailure(result, (tracedSearch, traced) => {
1125
+ rebuildBehavior(index);
1126
+ const state = states[index];
1127
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1128
+ nextActions.value.find((action) =>
1129
+ getSuccessors(action.expression, state, traced, action.scope).some((successor) => {
1130
+ const isInModel =
1131
+ tracedSearch.satisfiesConstraints(successor.state) &&
1132
+ tracedSearch.satisfiesActionConstraints(state, successor.state);
1133
+ return (
1134
+ (!isInModel && tracedSearch.findViolatedInvariant(successor.state) !== undefined) ||
1135
+ tracedSearch.findViolatedActionProperty(state, successor.state) !== undefined
1136
+ );
1137
+ }),
1138
+ );
1139
+ });
964
1140
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
1141
+ const tlcFingerprints: number[] = [];
965
1142
  const liveness = withLivenessExitCode(() =>
966
- createLivenessChecker(search.properties.liveness, spec.temporals, environment),
1143
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
1144
+ getFingerprint: (index) =>
1145
+ (tlcFingerprints[index] ??= Number(
1146
+ BigInt.asIntN(32, runtime.getFingerprint(states[index])),
1147
+ )),
1148
+ getSuccessors: (state) => {
1149
+ const successors: LiveSuccessor[] = [];
1150
+ if (spec.next === undefined) return successors;
1151
+ forEachSuccessor(
1152
+ spec.next,
1153
+ state,
1154
+ environment,
1155
+ (successor) => {
1156
+ canonicalizeState(successor.state);
1157
+ const isInModel =
1158
+ search.satisfiesConstraints(successor.state, state) &&
1159
+ search.satisfiesActionConstraints(state, successor.state);
1160
+ if (!isInModel) return false;
1161
+ const fingerprintState = getFingerprintState(successor.state);
1162
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1163
+ successors.push({ index, state: successor.state });
1164
+ return false;
1165
+ },
1166
+ spec.scope,
1167
+ );
1168
+ return successors;
1169
+ },
1170
+ }),
967
1171
  );
968
1172
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
969
1173
 
@@ -972,7 +1176,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
972
1176
  const parents: number[] = [];
973
1177
  const actions: (string | undefined)[] = [];
974
1178
  const depths: number[] = [];
975
- const buckets = new Map<number, number | number[]>();
1179
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1180
+ // and its index plus one side by side, probed by the hash.
1181
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
976
1182
  const canonicalizeState = createCanonicalizer();
977
1183
 
978
1184
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -985,11 +1191,16 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
985
1191
  position: number,
986
1192
  loopStart: number | undefined,
987
1193
  ) => {
988
- const state = steps[position].state;
989
- const next = (steps[position + 1] ?? steps[loopStart ?? position]).state;
990
1194
  // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
991
1195
  runtime.getLevel = () => position + 1;
992
1196
  runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
1197
+ return evaluateAlias(
1198
+ alias,
1199
+ steps[position].state,
1200
+ (steps[position + 1] ?? steps[loopStart ?? position]).state,
1201
+ );
1202
+ };
1203
+ const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) => {
993
1204
  try {
994
1205
  const body = getConfigDefinition("alias", alias, environment).body;
995
1206
  const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
@@ -1091,7 +1302,17 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1091
1302
  trace: TraceStep[],
1092
1303
  initialState?: Value[],
1093
1304
  failureOutDegrees?: number[],
1094
- ) => {
1305
+ ): CheckResult => {
1306
+ // TLC exits with 255 on a stack overflow while it computes next states, and prints the
1307
+ // behavior up to the state it was expanding.
1308
+ if (isStackOverflow(error)) {
1309
+ return current.isExpanding
1310
+ ? toFailure(
1311
+ setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error),
1312
+ getStateTrace(current.index),
1313
+ )
1314
+ : toFailure(new TlaEvaluationError(STACK_OVERFLOW), trace, initialState);
1315
+ }
1095
1316
  if (!(error instanceof TlaEvaluationError)) throw error;
1096
1317
  return {
1097
1318
  ...createResult("error", undefined, {
@@ -1104,7 +1325,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1104
1325
  outDegrees: failureOutDegrees,
1105
1326
  };
1106
1327
  };
1107
- const getPathTrace = (path: number[], loopStart?: number) => {
1328
+ const getPathSteps = (path: number[], loopStart?: number) => {
1108
1329
  const steps = getPathStates(path, NEXT_RECOVERY_FAILURE);
1109
1330
  const last = steps[steps.length - 1].state;
1110
1331
  const isClosed =
@@ -1113,7 +1334,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1113
1334
  loopStart === path.length - 1 ||
1114
1335
  findSuccessorWithFingerprint(last, path[loopStart]) !== undefined;
1115
1336
  if (!isClosed) throw new TlaEvaluationError(NEXT_RECOVERY_FAILURE);
1116
- return toTrace(steps, path, loopStart);
1337
+ return steps;
1117
1338
  };
1118
1339
  const getStateHash = (state: Value[]) => {
1119
1340
  let hash = 0x811c9dc5;
@@ -1127,19 +1348,35 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1127
1348
  }
1128
1349
  return true;
1129
1350
  };
1351
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1130
1352
  const findStateIndex = (hash: number, state: Value[]) => {
1131
- const bucket = buckets.get(hash);
1132
- if (bucket === undefined) return -1;
1133
- if (typeof bucket === "number") {
1134
- return isSameState(fingerprintStates[bucket], state) ? bucket : -1;
1353
+ const mask = seen.slots.length - 1;
1354
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1355
+ const entry = seen.slots[slot + 1];
1356
+ if (entry === 0) return -1;
1357
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1358
+ return entry - 1;
1359
+ }
1135
1360
  }
1136
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1361
+ };
1362
+ const insertSeen = (hash: number, entry: number) => {
1363
+ const mask = seen.slots.length - 1;
1364
+ let slot = getSlot(hash);
1365
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1366
+ seen.slots[slot] = hash;
1367
+ seen.slots[slot + 1] = entry;
1137
1368
  };
1138
1369
  const markSeen = (hash: number, index: number) => {
1139
- const bucket = buckets.get(hash);
1140
- if (bucket === undefined) buckets.set(hash, index);
1141
- else if (typeof bucket === "number") buckets.set(hash, [bucket, index]);
1142
- else bucket.push(index);
1370
+ seen.size++;
1371
+ if (seen.size * 4 > seen.slots.length) {
1372
+ const slots = seen.slots;
1373
+ seen.slots = new Int32Array(slots.length * 2);
1374
+ seen.shift--;
1375
+ for (let slot = 0; slot < slots.length; slot += 2) {
1376
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1377
+ }
1378
+ }
1379
+ insertSeen(hash, index + 1);
1143
1380
  };
1144
1381
  const countDistinctState = (depth: number) => {
1145
1382
  runtime.distinctStates = states.length + 1;
@@ -1165,6 +1402,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1165
1402
  isExpanding: false,
1166
1403
  candidate: undefined as Value[] | undefined,
1167
1404
  candidateLevel: 0,
1405
+ isFingerprinting: false,
1168
1406
  livenessSource: -1,
1169
1407
  };
1170
1408
  const getPath = (index: number): Value[][] =>
@@ -1179,7 +1417,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1179
1417
  };
1180
1418
  runtime.getCurrentState = () => (current.index === -1 ? undefined : states[current.index]);
1181
1419
  runtime.setLivenessSource = (index) => {
1182
- current.livenessSource = index;
1420
+ current.livenessSource = index ?? -1;
1183
1421
  };
1184
1422
  runtime.getLevel = (state) => {
1185
1423
  const source = current.livenessSource;
@@ -1190,6 +1428,18 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1190
1428
  return current.isExpanding ? depths[current.index] + 1 : 0;
1191
1429
  };
1192
1430
 
1431
+ const getGraphState = (state: Value[], level: number): GraphState => ({
1432
+ fingerprint: BigInt.asIntN(64, runtime.getFingerprint(state)),
1433
+ level,
1434
+ getLabel: () =>
1435
+ formatState(
1436
+ config.alias === undefined
1437
+ ? toRecord(state)
1438
+ : evaluateAlias(config.alias, state, undefined),
1439
+ ),
1440
+ getText: () => formatState(toRecord(state)),
1441
+ });
1442
+
1193
1443
  const visitInitialState = (state: Value[]) => {
1194
1444
  canonicalizeState(state);
1195
1445
  runtime.generatedStates++;
@@ -1206,6 +1456,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1206
1456
  countDistinctState(1);
1207
1457
  runtime.queueSize++;
1208
1458
  liveness?.addInitialState(states.length, state);
1459
+ stateWriter?.writeInitialState(getGraphState(state, 1));
1209
1460
  }
1210
1461
  const violated = search.findViolatedInvariant(state);
1211
1462
  if (violated) {
@@ -1226,20 +1477,36 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1226
1477
  addState(state, fingerprintState, -1, undefined);
1227
1478
  return undefined;
1228
1479
  };
1229
- const visitSuccessor = (index: number, successor: Successor, liveSuccessors: LiveSuccessor[]) => {
1480
+ const visitSuccessor = (
1481
+ index: number,
1482
+ successor: Successor,
1483
+ liveSuccessors: LiveSuccessor[],
1484
+ source: GraphState | undefined,
1485
+ action: SpecAction | undefined,
1486
+ ) => {
1230
1487
  const state = states[index];
1231
1488
  runtime.generatedStates++;
1232
1489
  current.candidate = successor.state;
1233
1490
  current.candidateLevel = depths[index] + 1;
1234
1491
  if (isCanonicalizedFirst) canonicalizeState(successor.state);
1492
+ current.isFingerprinting = true;
1235
1493
  const fingerprintState = getFingerprintState(successor.state);
1236
1494
  const hash = getStateHash(fingerprintState);
1495
+ current.isFingerprinting = false;
1237
1496
  const found = findStateIndex(hash, fingerprintState);
1238
1497
  const isStateInModel = search.satisfiesConstraints(successor.state, state);
1239
1498
  if (isStateInModel) search.trackStatePossible(successor.state);
1240
1499
  const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1241
1500
  if (isInModel) search.trackActionPossible(state, successor.state);
1242
1501
  const existing = isInModel ? found : -1;
1502
+ if (source && isInModel) {
1503
+ stateWriter?.writeSuccessor(
1504
+ source,
1505
+ getGraphState(successor.state, depths[index] + 1),
1506
+ existing !== -1,
1507
+ action && { name: action.name, signature: getActionSignature(action) },
1508
+ );
1509
+ }
1243
1510
  if (existing !== -1 && liveness) {
1244
1511
  const stored = states[existing];
1245
1512
  const isStored = stored.every((value, position) => value === successor.state[position]);
@@ -1297,10 +1564,22 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1297
1564
  spec.scope,
1298
1565
  );
1299
1566
  } catch (error) {
1300
- return toFailure(error, []);
1567
+ if (!(error instanceof TlaIllegalStateError))
1568
+ return replayInitialStates(toFailure(error, []));
1569
+ // TLC prints an illegal initial state with null for each variable it leaves undefined, and
1570
+ // stops before it prints the statistics.
1571
+ const illegal = toFailure(
1572
+ error,
1573
+ [],
1574
+ error.state.map((value) => value ?? createModelValue("null")),
1575
+ );
1576
+ return {
1577
+ ...illegal,
1578
+ failure: illegal.failure && { ...illegal.failure, isWithoutStatistics: true },
1579
+ };
1301
1580
  }
1302
1581
  }
1303
- if (outcome.result) return outcome.result;
1582
+ if (outcome.result) return replayInitialStates(outcome.result);
1304
1583
 
1305
1584
  const next = spec.next;
1306
1585
  if (next === undefined) {
@@ -1311,23 +1590,58 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1311
1590
  }
1312
1591
  return createSuccess();
1313
1592
  }
1593
+ // TLC labels and colors an edge of the -dump state graph by the action that generated it. When
1594
+ // the graph names its edges, the search generates successors action by action, as TLC does.
1595
+ const isNamingEdges = Boolean(
1596
+ options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1597
+ );
1598
+ const forEachActionSuccessor = (
1599
+ state: Value[],
1600
+ onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1601
+ ) => {
1602
+ if (!isNamingEdges) {
1603
+ return forEachSuccessor(
1604
+ next,
1605
+ state,
1606
+ environment,
1607
+ (successor) => onSuccessor(successor, undefined),
1608
+ spec.scope,
1609
+ );
1610
+ }
1611
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1612
+ const progress = { isStopped: false };
1613
+ return nextActions.value.reduce((count, action) => {
1614
+ if (progress.isStopped) return count;
1615
+ return (
1616
+ count +
1617
+ forEachSuccessor(
1618
+ action.expression,
1619
+ state,
1620
+ environment,
1621
+ (successor) => {
1622
+ progress.isStopped = onSuccessor(successor, action);
1623
+ return progress.isStopped;
1624
+ },
1625
+ action.scope,
1626
+ )
1627
+ );
1628
+ }, 0);
1629
+ };
1314
1630
  const expandState = (index: number) => {
1315
1631
  const state = states[index];
1316
1632
  const liveSuccessors: LiveSuccessor[] = [];
1317
- const successorCount = forEachSuccessor(
1318
- next,
1319
- state,
1320
- environment,
1321
- (successor) => {
1322
- try {
1323
- outcome.result = visitSuccessor(index, successor, liveSuccessors);
1324
- } catch (error) {
1325
- outcome.result = toFailure(error, getTrace(index, successor));
1326
- }
1327
- return outcome.result !== undefined;
1328
- },
1329
- spec.scope,
1330
- );
1633
+ const source = stateWriter && getGraphState(state, depths[index]);
1634
+ const successorCount = forEachActionSuccessor(state, (successor, action) => {
1635
+ try {
1636
+ outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1637
+ } catch (error) {
1638
+ // TLC reports a successor it cannot fingerprint as a failure of the state it expands.
1639
+ if (current.isFingerprinting) throw error;
1640
+ const failure = toFailure(error, getTrace(index, successor));
1641
+ outcome.result = isStackOverflow(error) ? failure : replaySuccessors(failure, index);
1642
+ }
1643
+ return outcome.result !== undefined;
1644
+ });
1331
1645
  current.isExpanding = false;
1332
1646
  if (outcome.result) return outcome.result;
1333
1647
  if (successorCount === 0 && config.checkDeadlock) {
@@ -1335,32 +1649,68 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1335
1649
  }
1336
1650
  try {
1337
1651
  const accepted = liveness?.addState(index, state, liveSuccessors);
1338
- current.livenessSource = -1;
1339
- if (!accepted) return undefined;
1652
+ if (!liveness || !accepted) return undefined;
1653
+ const steps = getPathSteps(accepted);
1654
+ const properties = liveness.getViolatedProperties(
1655
+ steps.map((step) => step.state),
1656
+ steps.length - 1,
1657
+ );
1340
1658
  return reportViolation("property-violation", {
1341
- name: accepted.name,
1342
- trace: getPathTrace(accepted.path),
1659
+ name: properties[0],
1660
+ properties,
1661
+ trace: toTrace(steps, accepted),
1343
1662
  });
1344
1663
  } catch (error) {
1345
1664
  return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1346
1665
  }
1347
1666
  };
1348
- const reportLasso = (lasso: Lasso) => {
1667
+ // TLC names the action when the next-state relation has more than one, and prints the
1668
+ // incomplete successor with null for each variable it leaves undefined.
1669
+ const reportIncompleteSuccessor = (error: TlaIncompleteStateError, index: number) => {
1670
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1671
+ const actions = nextActions.value;
1672
+ const action =
1673
+ actions.length === 1 ? actions[0] : actions.find((item) => item.name === error.action);
1674
+ const variables = `variable${error.missing.length > 1 ? "s are" : " is"} not defined: ${error.missing.join(", ")}.\n`;
1675
+ runtime.generatedStates++;
1676
+ return toFailure(
1677
+ actions.length === 1
1678
+ ? error
1679
+ : new TlaEvaluationError(
1680
+ `Successor state is not completely specified by action ${error.action} of the next-state relation. The following ${variables}`,
1681
+ ),
1682
+ [
1683
+ ...getStateTrace(index),
1684
+ {
1685
+ action: error.action,
1686
+ label: action && getActionLabel(action),
1687
+ state: toRecord(error.state.map((value) => value ?? createModelValue("null"))),
1688
+ },
1689
+ ],
1690
+ );
1691
+ };
1692
+ // TLC names the properties and the step back into the cycle from the states it prints.
1693
+ const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1349
1694
  const path = [...lasso.prefix, ...lasso.cycle];
1350
- const trace = getPathTrace(path, lasso.prefix.length);
1351
- const back = path[lasso.prefix.length];
1695
+ const loopStart = lasso.prefix.length;
1696
+ const steps = getPathSteps(path, loopStart);
1697
+ const trace = toTrace(steps, path, loopStart);
1698
+ const properties = checker.getViolatedProperties(
1699
+ steps.map((step) => step.state),
1700
+ loopStart,
1701
+ );
1702
+ const back = path[loopStart];
1352
1703
  const last = path[path.length - 1];
1704
+ const lastState = steps[steps.length - 1].state;
1353
1705
  const loopLabel =
1354
- back === last ? undefined : withoutOutput(() => getLabel(last, states[last], states[back]));
1706
+ back === last ? undefined : withoutOutput(() => getLabel(last, lastState, states[back]));
1355
1707
  return reportViolation(
1356
1708
  "liveness-violation",
1357
- { name: lasso.name, trace, loopStart: lasso.prefix.length, loopLabel },
1709
+ { name: properties[0], properties, trace, loopStart, loopLabel },
1358
1710
  () =>
1359
1711
  back === last
1360
1712
  ? trace[trace.length - 1].action
1361
- : getTraceSuccessors(states[last]).find((successor) =>
1362
- isSameState(successor.state, states[back]),
1363
- )?.action,
1713
+ : findSuccessorWithFingerprint(lastState, back)?.action,
1364
1714
  );
1365
1715
  };
1366
1716
  const isPeriodic = liveness !== undefined && options.livenessCheck !== "final";
@@ -1373,11 +1723,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1373
1723
  if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1374
1724
  periodic.size = expanded;
1375
1725
  const lasso = liveness?.findViolation();
1376
- current.livenessSource = -1;
1377
1726
  periodic.time += performance.now() - now;
1378
1727
  return lasso;
1379
1728
  };
1380
- setNextStatePhase(true);
1381
1729
  for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1382
1730
  current.index = index;
1383
1731
  current.candidate = undefined;
@@ -1386,22 +1734,28 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1386
1734
  try {
1387
1735
  outcome.result = expandState(index);
1388
1736
  } catch (error) {
1389
- outcome.result = toFailure(error, getStateTrace(index));
1737
+ const failure =
1738
+ error instanceof TlaIncompleteStateError
1739
+ ? reportIncompleteSuccessor(error, index)
1740
+ : toFailure(toNextStateError(error), getStateTrace(index));
1741
+ outcome.result =
1742
+ error instanceof TlaIncompleteStateError || isStackOverflow(error)
1743
+ ? failure
1744
+ : replaySuccessors(failure, index);
1390
1745
  }
1391
1746
  if (outcome.result) return outcome.result;
1392
1747
  outDegrees[getOutDegreeBucket()]++;
1393
1748
  expansion.newStates = 0;
1394
1749
  if (isPeriodic && performance.now() >= periodic.at) {
1395
1750
  const lasso = findPeriodicViolation(index + 1);
1396
- if (lasso) return reportLasso(lasso);
1751
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1397
1752
  }
1398
1753
  }
1399
1754
 
1400
1755
  current.index = -1;
1401
1756
  current.candidate = undefined;
1402
1757
  const lasso = liveness?.findViolation();
1403
- current.livenessSource = -1;
1404
- if (lasso) return reportLasso(lasso);
1758
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1405
1759
 
1406
1760
  const postconditionViolation = search.findPostconditionViolation();
1407
1761
  if (postconditionViolation) {