tla-ts 0.0.3-dev.3c70a97 → 0.0.3-dev.3ff2308

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 +53 -22
  4. package/dist/index.d.ts +53 -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 -17
  11. package/dist/run-cli.js +20 -18
  12. package/dist/transfer.cjs +34 -17
  13. package/dist/transfer.js +34 -17
  14. package/package.json +1 -1
  15. package/src/ast.ts +3 -0
  16. package/src/builtins.ts +9 -3
  17. package/src/check.ts +452 -93
  18. package/src/cli-options.ts +11 -5
  19. package/src/codegen.ts +6 -3
  20. package/src/config.ts +224 -170
  21. package/src/environment.ts +111 -19
  22. package/src/errors.ts +78 -1
  23. package/src/evaluate.ts +182 -26
  24. package/src/exit-codes.ts +22 -3
  25. package/src/instances.ts +4 -4
  26. package/src/levels.ts +55 -27
  27. package/src/live-check.ts +132 -70
  28. package/src/liveness.ts +117 -22
  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 +106 -29
  33. package/src/run-cli.ts +103 -18
  34. package/src/runtime.ts +2 -0
  35. package/src/spec-description.ts +12 -6
  36. package/src/standard-modules.ts +52 -43
  37. package/src/state-graph.ts +157 -0
  38. package/src/successors.ts +169 -33
  39. package/src/symmetry.ts +16 -6
  40. package/src/tableau.ts +51 -24
  41. package/src/tlc-ext.ts +27 -2
  42. package/src/tlc-module.ts +14 -33
  43. package/src/tlc-modules.ts +4 -0
  44. package/src/tlc-order.ts +8 -4
  45. package/src/tlc-random.ts +9 -6
  46. package/src/tlc-summary.ts +20 -5
  47. package/src/value-sources.ts +29 -0
  48. package/src/values.ts +207 -53
package/src/check.ts CHANGED
@@ -11,8 +11,13 @@ import { getReadVariables } from "./dependencies";
11
11
  import { createEnvironment } from "./environment";
12
12
  import {
13
13
  getErrorExitCode,
14
+ isStackOverflow,
15
+ formatRange,
16
+ STACK_OVERFLOW,
14
17
  TlaConfigError,
15
18
  TlaEvaluationError,
19
+ TlaIllegalStateError,
20
+ TlaIncompleteStateError,
16
21
  TlaModuleError,
17
22
  UNEXPECTED_EXCEPTION,
18
23
  } from "./errors";
@@ -21,7 +26,6 @@ import {
21
26
  describeRange,
22
27
  evaluate,
23
28
  expectBoolean,
24
- formatRange,
25
29
  getDefinition,
26
30
  isConstantLevel,
27
31
  isImpure,
@@ -32,6 +36,7 @@ import {
32
36
  import {
33
37
  createLivenessChecker,
34
38
  type Lasso,
39
+ type LiveGraph,
35
40
  type LivenessChecker,
36
41
  type LiveSuccessor,
37
42
  } from "./live-check";
@@ -47,19 +52,29 @@ import {
47
52
  } from "./successors";
48
53
  import {
49
54
  getActionLabel,
55
+ getActionSignature,
50
56
  getNextActions,
51
57
  getSpecificationValue,
52
58
  type SpecAction,
53
59
  } from "./spec-description";
60
+ import {
61
+ createStateWriter,
62
+ type GraphState,
63
+ type StateDump,
64
+ type StateWriter,
65
+ } from "./state-graph";
54
66
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
55
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
67
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
56
68
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
57
69
  import { createCanonicalizer } from "./canonical";
58
70
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
59
71
  import { createCounterExample } from "./tlc-ext";
72
+ import { getFingerprintTrace, valueSources } from "./value-sources";
60
73
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
61
74
  import {
62
75
  combineHash,
76
+ createModelValue,
77
+ formatState,
63
78
  formatValue,
64
79
  getValueHash,
65
80
  isFunctionValue,
@@ -83,6 +98,8 @@ export interface CheckOptions {
83
98
  workers?: number;
84
99
  // TLC's -lncheck: "final" checks liveness only on the complete state graph.
85
100
  livenessCheck?: "default" | "final";
101
+ // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
102
+ dump?: StateDump;
86
103
  }
87
104
 
88
105
  export type CheckStatus =
@@ -126,6 +143,25 @@ export interface EvaluationFailure {
126
143
  trace: TraceStep[];
127
144
  initialState: Record<string, Value> | undefined;
128
145
  exitCode: number;
146
+ replay?: Replay;
147
+ isWithoutStatistics?: boolean;
148
+ }
149
+
150
+ // TLC replays a failed step to print the expressions it was evaluating when the replay failed.
151
+ export interface Replay {
152
+ output: string[];
153
+ callStack: string[] | undefined;
154
+ fingerprint?: Fingerprint;
155
+ // The worker that fails to check liveness replays the step at once, so TLC prints the stack
156
+ // before the error, and only when it holds a frame.
157
+ isBeforeError?: boolean;
158
+ }
159
+
160
+ // TLC reports an error from a method of a value that has a source as one it was unable to
161
+ // fingerprint. With an empty stack, it lists the sources of the values instead.
162
+ export interface Fingerprint {
163
+ sources: string[];
164
+ reason: string;
129
165
  }
130
166
 
131
167
  export interface CheckResult {
@@ -237,7 +273,7 @@ const getConstantValue = (name: string, definition: Definition, environment: Env
237
273
  try {
238
274
  return evaluate(createIdentifier(name), getContext(environment, undefined, undefined));
239
275
  } catch (error) {
240
- if (error instanceof TlaEvaluationError) return undefined;
276
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
241
277
  throw error;
242
278
  }
243
279
  };
@@ -266,8 +302,11 @@ const getInvariants = (names: string[], environment: Environment) => {
266
302
  levels.params.size === 0
267
303
  ? ""
268
304
  : "\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.";
269
- throw new TlaConfigError(
270
- `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
305
+ throw setExitCode(
306
+ new TlaConfigError(
307
+ `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
308
+ ),
309
+ EXIT_STATUS.safetyEvaluationFailure,
271
310
  );
272
311
  }
273
312
  return [{ name, expression: createIdentifier(name), scope: undefined }];
@@ -365,8 +404,11 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
365
404
  conjunct.kind === "Always" &&
366
405
  getLevel(conjunct.expression, item.scope, environment) < ACTION_LEVEL
367
406
  ) {
368
- throw new TlaConfigError(
369
- `TLC cannot handle []P in the specification ${config.specification} when P is a state predicate`,
407
+ throw setExitCode(
408
+ new TlaConfigError(
409
+ `TLC cannot handle the temporal formula ${describeRange(conjunct.expression)}`,
410
+ ),
411
+ EXIT_STATUS.error,
370
412
  );
371
413
  }
372
414
  const level = getLevel(conjunct, item.scope, environment);
@@ -436,12 +478,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
436
478
  config.properties.forEach((name) => {
437
479
  const definition = getConfigPredicate("property", name, environment);
438
480
  if (!definition) return;
439
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
481
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
440
482
  const conjunct = item.expression;
441
483
  if (isConstantTrue(item, environment, "property")) return;
442
484
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
443
485
  properties.actionProperties.push({
444
- name,
486
+ name: item.name,
445
487
  box: conjunct.expression,
446
488
  action: conjunct.expression.action,
447
489
  subscript: conjunct.expression.subscript,
@@ -453,12 +495,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
453
495
  conjunct.kind === "Always" &&
454
496
  getLevel(conjunct.expression, item.scope, environment) <= 1
455
497
  ) {
456
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
498
+ // TLC names the invariant []P after P when P is an operator name.
499
+ const expression = conjunct.expression;
500
+ properties.invariants.push({
501
+ name: expression.kind === "Identifier" ? expression.name : item.name,
502
+ expression,
503
+ scope: item.scope,
504
+ });
457
505
  return;
458
506
  }
459
507
  const level = getLevel(conjunct, item.scope, environment);
460
508
  if (level < ACTION_LEVEL) {
461
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
509
+ properties.initialPredicates.push({
510
+ name: item.name,
511
+ expression: conjunct,
512
+ scope: item.scope,
513
+ });
462
514
  return;
463
515
  }
464
516
  if (level === ACTION_LEVEL) {
@@ -518,7 +570,9 @@ const getMembership = (
518
570
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
519
571
  named.flatMap((item) =>
520
572
  getConjuncts(item.expression, environment).map((expression) => {
521
- const variables = getReadVariables(expression, environment);
573
+ // A LET or an argument in the scope can read variables the expression doesn't name.
574
+ const variables =
575
+ item.scope === undefined ? getReadVariables(expression, environment) : undefined;
522
576
  return {
523
577
  name: item.name,
524
578
  expression,
@@ -765,11 +819,13 @@ export const createSearch = (
765
819
  if (view !== undefined || isFingerprintedLikeTlc) {
766
820
  return BigInt64Array.from(states, getTlcStateFingerprint);
767
821
  }
768
- const indices = getTlcOrder();
769
- const getFingerprint = createTlcFingerprinter();
770
- return BigInt64Array.from(fingerprintStates, (state) =>
771
- getFingerprint(indices.map((index) => state[index])),
822
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
823
+ const fingerprint = createTlcFingerprinter(
824
+ getTlcOrder(),
825
+ new Int32Array(fingerprints.buffer),
772
826
  );
827
+ fingerprintStates.forEach(fingerprint);
828
+ return fingerprints;
773
829
  },
774
830
  getFingerprintState: (state) => {
775
831
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -801,11 +857,17 @@ export const createSearch = (
801
857
  }
802
858
  }),
803
859
  satisfiesConstraints: (state, parent) =>
804
- constraints.every(
805
- (constraint) =>
806
- isUnchangedFor(constraint, state, parent) ||
807
- holdsLikeTlc(constraint.expression, getContext(environment, state, undefined)),
808
- ),
860
+ constraints.every((constraint) => {
861
+ try {
862
+ return (
863
+ isUnchangedFor(constraint, state, parent) ||
864
+ holdsLikeTlc(constraint.expression, getContext(environment, state, undefined))
865
+ );
866
+ } catch (error) {
867
+ // TLC reports a failing constraint on a successor like a failure of the next-state relation.
868
+ throw parent ? toNextStateError(error) : error;
869
+ }
870
+ }),
809
871
  findFailedInitialPredicate: (state) =>
810
872
  properties.initialPredicates.find(
811
873
  (predicate) =>
@@ -838,13 +900,13 @@ export const createSearch = (
838
900
  }
839
901
  }),
840
902
  satisfiesActionConstraints: (state, next) =>
841
- actionConstraints.every((constraint) =>
842
- holdsLikeTlc(
843
- constraint.expression,
844
- getContext(environment, state, next),
845
- (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
846
- ),
847
- ),
903
+ actionConstraints.every((constraint) => {
904
+ try {
905
+ return holdsLikeTlc(constraint.expression, getContext(environment, state, next));
906
+ } catch (error) {
907
+ throw toNextStateError(error);
908
+ }
909
+ }),
848
910
  trackStatePossible:
849
911
  statePossible.length === 0
850
912
  ? ignorePossible
@@ -875,6 +937,59 @@ export const createSearch = (
875
937
  const withNextStateExitCode = (error: unknown) =>
876
938
  error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
877
939
 
940
+ // TLC reports a failure of the next-state relation, or of the liveness check of a step, as an
941
+ // unexpected exception, unless a standard module raised it as an EvalException.
942
+ const toNextStateError = (error: unknown) =>
943
+ error instanceof TlaEvaluationError &&
944
+ !(error instanceof TlaModuleError) &&
945
+ !(error instanceof TlaIncompleteStateError)
946
+ ? setExitCode(
947
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
948
+ getErrorExitCode(error),
949
+ )
950
+ : withNextStateExitCode(error);
951
+
952
+ const isRepeated = (frame: string, index: number, frames: string[]) =>
953
+ index > 0 && frames[index - 1] === frame;
954
+
955
+ // FingerprintException#getTrace numbers the sources from the outermost value and lists the innermost
956
+ // first.
957
+ const getSourceTrace = (sources: Expression[]) =>
958
+ sources
959
+ .flatMap((source) => (source.location.range ? [formatRange(source.location.range)] : []))
960
+ .filter((source, index, all) => !isRepeated(source, index, all))
961
+ .map((source, index) => `${index}) ${source}`)
962
+ .reverse();
963
+
964
+ // TLC keeps the stack only when an evaluation fails, and prints each expression on it once, however
965
+ // many times in a row it pushed it.
966
+ const getReplayedCallStack = (
967
+ replay: () => void,
968
+ trace: Expression[],
969
+ ): Pick<Replay, "callStack" | "fingerprint"> => {
970
+ try {
971
+ replay();
972
+ return { callStack: undefined };
973
+ } catch (error) {
974
+ if (!(error instanceof TlaEvaluationError)) return { callStack: [] };
975
+ const callStack = trace
976
+ .flatMap((expression) => {
977
+ const range = expression.location.range;
978
+ return range
979
+ ? [
980
+ `Line ${range.start.line}, column ${range.start.column} to line ${range.end.line}, column ${range.end.column} in ${range.module}`,
981
+ ]
982
+ : [];
983
+ })
984
+ .filter((frame, index, frames) => !isRepeated(frame, index, frames));
985
+ const sources = getFingerprintTrace(error);
986
+ return {
987
+ callStack,
988
+ fingerprint: sources && { sources: getSourceTrace(sources), reason: error.message },
989
+ };
990
+ }
991
+ };
992
+
878
993
  const withHeadline = (error: unknown, headline: string) =>
879
994
  error instanceof TlaEvaluationError
880
995
  ? setExitCode(
@@ -883,14 +998,30 @@ const withHeadline = (error: unknown, headline: string) =>
883
998
  )
884
999
  : error;
885
1000
 
1001
+ // TLC finishes the -dump file whether or not the search finds a violation.
886
1002
  export const checkSequentially = (options: CheckOptions): CheckResult => {
1003
+ const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
1004
+ try {
1005
+ return searchStates(options, stateWriter);
1006
+ } catch (error) {
1007
+ // TLC reports a stack overflow outside the search as a failure of its own, with exit code 255.
1008
+ throw isStackOverflow(error)
1009
+ ? setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error)
1010
+ : error;
1011
+ } finally {
1012
+ stateWriter?.close();
1013
+ }
1014
+ };
1015
+
1016
+ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
887
1017
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
888
1018
  const onPrint = options.onPrint ?? console.log;
889
1019
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
890
1020
  // before the trace would misplace them, so rebuilding a trace prints nothing.
891
- const output = { isMuted: false };
1021
+ const output = { isMuted: false, replayed: undefined as string[] | undefined };
892
1022
  const print = (text: string) => {
893
- if (!output.isMuted) onPrint(text);
1023
+ if (output.replayed) output.replayed.push(text);
1024
+ else if (!output.isMuted) onPrint(text);
894
1025
  };
895
1026
  const withoutOutput = <Result>(rebuild: () => Result) => {
896
1027
  output.isMuted = true;
@@ -952,9 +1083,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
952
1083
  ),
953
1084
  });
954
1085
 
955
- const search = createSearch(config, environment, () =>
956
- getTlcVariableOrder(options.source, options.loadModule),
957
- );
1086
+ const getVariableOrder = () =>
1087
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable");
1088
+ const search = createSearch(config, environment, getVariableOrder);
958
1089
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
959
1090
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
960
1091
  if (!search) return createSuccess();
@@ -978,37 +1109,113 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
978
1109
  const spec = search.spec;
979
1110
  const getFingerprintState = search.getFingerprintState;
980
1111
  const nextActions = { value: undefined as SpecAction[] | undefined };
1112
+ const replayFailure = (
1113
+ result: CheckResult,
1114
+ replay: (tracedSearch: Search, traced: Environment) => void,
1115
+ isBeforeError = false,
1116
+ ): CheckResult => {
1117
+ if (!result.failure) return result;
1118
+ const trace: Expression[] = [];
1119
+ const traced: Environment = { ...environment, evaluators: new WeakMap(), trace };
1120
+ const tracedSearch = createSearch(config, traced, getVariableOrder);
1121
+ if (!tracedSearch) return result;
1122
+ const replayed: string[] = [];
1123
+ output.replayed = replayed;
1124
+ valueSources.current = new WeakMap();
1125
+ const replayedStack = getReplayedCallStack(() => replay(tracedSearch, traced), trace);
1126
+ valueSources.current = undefined;
1127
+ output.replayed = undefined;
1128
+ return {
1129
+ ...result,
1130
+ failure: { ...result.failure, replay: { output: replayed, ...replayedStack, isBeforeError } },
1131
+ };
1132
+ };
1133
+ // TLC fingerprints a state outside CallStackTool, so a failure leaves the stack empty.
1134
+ const fingerprintReplayed = (state: Value[], traced: Environment) => {
1135
+ try {
1136
+ getStateHash(getFingerprintState(state));
1137
+ } catch (error) {
1138
+ if (traced.trace) traced.trace.length = 0;
1139
+ throw error;
1140
+ }
1141
+ };
1142
+ // TLC checks every initial state again, as when it first generated them.
1143
+ const replayInitialStates = (result: CheckResult) =>
1144
+ replayFailure(result, (tracedSearch, traced) => {
1145
+ if (spec.init === undefined) return;
1146
+ forEachInitialState(
1147
+ spec.init,
1148
+ traced,
1149
+ (state) => {
1150
+ if (tracedSearch.satisfiesConstraints(state)) fingerprintReplayed(state, traced);
1151
+ return (
1152
+ tracedSearch.findViolatedInvariant(state) !== undefined ||
1153
+ tracedSearch.findFailedInitialPredicate(state) !== undefined
1154
+ );
1155
+ },
1156
+ spec.scope,
1157
+ );
1158
+ });
1159
+ // TLC rebuilds the behavior up to the state it expanded before it replays the step.
1160
+ const rebuildBehavior = (index: number): void => {
1161
+ const parent = parents[index];
1162
+ if (parent === -1) {
1163
+ getSpecInitialStates();
1164
+ return;
1165
+ }
1166
+ rebuildBehavior(parent);
1167
+ getLabel(parent, states[parent], states[index]);
1168
+ };
1169
+ // TLC generates the successors of each action before it checks them. It checks the invariants
1170
+ // only of a successor outside the model, since it has seen the others.
1171
+ const replaySuccessors = (result: CheckResult, index: number) =>
1172
+ replayFailure(result, (tracedSearch, traced) => {
1173
+ rebuildBehavior(index);
1174
+ const state = states[index];
1175
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1176
+ nextActions.value.find((action) =>
1177
+ getSuccessors(action.expression, state, traced, action.scope).some((successor) => {
1178
+ const isInModel =
1179
+ tracedSearch.satisfiesConstraints(successor.state) &&
1180
+ tracedSearch.satisfiesActionConstraints(state, successor.state);
1181
+ if (isInModel) fingerprintReplayed(successor.state, traced);
1182
+ return (
1183
+ (!isInModel && tracedSearch.findViolatedInvariant(successor.state) !== undefined) ||
1184
+ tracedSearch.findViolatedActionProperty(state, successor.state) !== undefined
1185
+ );
1186
+ }),
1187
+ );
1188
+ });
981
1189
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
982
1190
  const tlcFingerprints: number[] = [];
1191
+ const liveGraph: LiveGraph = {
1192
+ getFingerprint: (index) =>
1193
+ (tlcFingerprints[index] ??= Number(BigInt.asIntN(32, runtime.getFingerprint(states[index])))),
1194
+ getSuccessors: (state) => {
1195
+ const successors: LiveSuccessor[] = [];
1196
+ if (spec.next === undefined) return successors;
1197
+ forEachSuccessor(
1198
+ spec.next,
1199
+ state,
1200
+ environment,
1201
+ (successor) => {
1202
+ canonicalizeState(successor.state);
1203
+ const isInModel =
1204
+ search.satisfiesConstraints(successor.state, state) &&
1205
+ search.satisfiesActionConstraints(state, successor.state);
1206
+ if (!isInModel) return false;
1207
+ const fingerprintState = getFingerprintState(successor.state);
1208
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1209
+ successors.push({ index, state: successor.state });
1210
+ return false;
1211
+ },
1212
+ spec.scope,
1213
+ );
1214
+ return successors;
1215
+ },
1216
+ };
983
1217
  const liveness = withLivenessExitCode(() =>
984
- createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
985
- getFingerprint: (index) =>
986
- (tlcFingerprints[index] ??= Number(
987
- BigInt.asIntN(32, runtime.getFingerprint(states[index])),
988
- )),
989
- getSuccessors: (state) => {
990
- const successors: LiveSuccessor[] = [];
991
- if (spec.next === undefined) return successors;
992
- forEachSuccessor(
993
- spec.next,
994
- state,
995
- environment,
996
- (successor) => {
997
- canonicalizeState(successor.state);
998
- const isInModel =
999
- search.satisfiesConstraints(successor.state, state) &&
1000
- search.satisfiesActionConstraints(state, successor.state);
1001
- if (!isInModel) return false;
1002
- const fingerprintState = getFingerprintState(successor.state);
1003
- const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1004
- successors.push({ index, state: successor.state });
1005
- return false;
1006
- },
1007
- spec.scope,
1008
- );
1009
- return successors;
1010
- },
1011
- }),
1218
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, liveGraph),
1012
1219
  );
1013
1220
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
1014
1221
 
@@ -1017,7 +1224,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1017
1224
  const parents: number[] = [];
1018
1225
  const actions: (string | undefined)[] = [];
1019
1226
  const depths: number[] = [];
1020
- const buckets = new Map<number, number | number[]>();
1227
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1228
+ // and its index plus one side by side, probed by the hash.
1229
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
1021
1230
  const canonicalizeState = createCanonicalizer();
1022
1231
 
1023
1232
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -1030,11 +1239,16 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1030
1239
  position: number,
1031
1240
  loopStart: number | undefined,
1032
1241
  ) => {
1033
- const state = steps[position].state;
1034
- const next = (steps[position + 1] ?? steps[loopStart ?? position]).state;
1035
1242
  // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
1036
1243
  runtime.getLevel = () => position + 1;
1037
1244
  runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
1245
+ return evaluateAlias(
1246
+ alias,
1247
+ steps[position].state,
1248
+ (steps[position + 1] ?? steps[loopStart ?? position]).state,
1249
+ );
1250
+ };
1251
+ const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) => {
1038
1252
  try {
1039
1253
  const body = getConfigDefinition("alias", alias, environment).body;
1040
1254
  const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
@@ -1136,7 +1350,17 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1136
1350
  trace: TraceStep[],
1137
1351
  initialState?: Value[],
1138
1352
  failureOutDegrees?: number[],
1139
- ) => {
1353
+ ): CheckResult => {
1354
+ // TLC exits with 255 on a stack overflow while it computes next states, and prints the
1355
+ // behavior up to the state it was expanding.
1356
+ if (isStackOverflow(error)) {
1357
+ return current.isExpanding
1358
+ ? toFailure(
1359
+ setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error),
1360
+ getStateTrace(current.index),
1361
+ )
1362
+ : toFailure(new TlaEvaluationError(STACK_OVERFLOW), trace, initialState);
1363
+ }
1140
1364
  if (!(error instanceof TlaEvaluationError)) throw error;
1141
1365
  return {
1142
1366
  ...createResult("error", undefined, {
@@ -1172,19 +1396,35 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1172
1396
  }
1173
1397
  return true;
1174
1398
  };
1399
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1175
1400
  const findStateIndex = (hash: number, state: Value[]) => {
1176
- const bucket = buckets.get(hash);
1177
- if (bucket === undefined) return -1;
1178
- if (typeof bucket === "number") {
1179
- return isSameState(fingerprintStates[bucket], state) ? bucket : -1;
1401
+ const mask = seen.slots.length - 1;
1402
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1403
+ const entry = seen.slots[slot + 1];
1404
+ if (entry === 0) return -1;
1405
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1406
+ return entry - 1;
1407
+ }
1180
1408
  }
1181
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1409
+ };
1410
+ const insertSeen = (hash: number, entry: number) => {
1411
+ const mask = seen.slots.length - 1;
1412
+ let slot = getSlot(hash);
1413
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1414
+ seen.slots[slot] = hash;
1415
+ seen.slots[slot + 1] = entry;
1182
1416
  };
1183
1417
  const markSeen = (hash: number, index: number) => {
1184
- const bucket = buckets.get(hash);
1185
- if (bucket === undefined) buckets.set(hash, index);
1186
- else if (typeof bucket === "number") buckets.set(hash, [bucket, index]);
1187
- else bucket.push(index);
1418
+ seen.size++;
1419
+ if (seen.size * 4 > seen.slots.length) {
1420
+ const slots = seen.slots;
1421
+ seen.slots = new Int32Array(slots.length * 2);
1422
+ seen.shift--;
1423
+ for (let slot = 0; slot < slots.length; slot += 2) {
1424
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1425
+ }
1426
+ }
1427
+ insertSeen(hash, index + 1);
1188
1428
  };
1189
1429
  const countDistinctState = (depth: number) => {
1190
1430
  runtime.distinctStates = states.length + 1;
@@ -1210,6 +1450,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1210
1450
  isExpanding: false,
1211
1451
  candidate: undefined as Value[] | undefined,
1212
1452
  candidateLevel: 0,
1453
+ isFingerprinting: false,
1213
1454
  livenessSource: -1,
1214
1455
  };
1215
1456
  const getPath = (index: number): Value[][] =>
@@ -1235,6 +1476,18 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1235
1476
  return current.isExpanding ? depths[current.index] + 1 : 0;
1236
1477
  };
1237
1478
 
1479
+ const getGraphState = (state: Value[], level: number): GraphState => ({
1480
+ fingerprint: BigInt.asIntN(64, runtime.getFingerprint(state)),
1481
+ level,
1482
+ getLabel: () =>
1483
+ formatState(
1484
+ config.alias === undefined
1485
+ ? toRecord(state)
1486
+ : evaluateAlias(config.alias, state, undefined),
1487
+ ),
1488
+ getText: () => formatState(toRecord(state)),
1489
+ });
1490
+
1238
1491
  const visitInitialState = (state: Value[]) => {
1239
1492
  canonicalizeState(state);
1240
1493
  runtime.generatedStates++;
@@ -1251,6 +1504,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1251
1504
  countDistinctState(1);
1252
1505
  runtime.queueSize++;
1253
1506
  liveness?.addInitialState(states.length, state);
1507
+ stateWriter?.writeInitialState(getGraphState(state, 1));
1254
1508
  }
1255
1509
  const violated = search.findViolatedInvariant(state);
1256
1510
  if (violated) {
@@ -1271,20 +1525,36 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1271
1525
  addState(state, fingerprintState, -1, undefined);
1272
1526
  return undefined;
1273
1527
  };
1274
- const visitSuccessor = (index: number, successor: Successor, liveSuccessors: LiveSuccessor[]) => {
1528
+ const visitSuccessor = (
1529
+ index: number,
1530
+ successor: Successor,
1531
+ liveSuccessors: LiveSuccessor[],
1532
+ source: GraphState | undefined,
1533
+ action: SpecAction | undefined,
1534
+ ) => {
1275
1535
  const state = states[index];
1276
1536
  runtime.generatedStates++;
1277
1537
  current.candidate = successor.state;
1278
1538
  current.candidateLevel = depths[index] + 1;
1279
1539
  if (isCanonicalizedFirst) canonicalizeState(successor.state);
1540
+ current.isFingerprinting = true;
1280
1541
  const fingerprintState = getFingerprintState(successor.state);
1281
1542
  const hash = getStateHash(fingerprintState);
1543
+ current.isFingerprinting = false;
1282
1544
  const found = findStateIndex(hash, fingerprintState);
1283
1545
  const isStateInModel = search.satisfiesConstraints(successor.state, state);
1284
1546
  if (isStateInModel) search.trackStatePossible(successor.state);
1285
1547
  const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1286
1548
  if (isInModel) search.trackActionPossible(state, successor.state);
1287
1549
  const existing = isInModel ? found : -1;
1550
+ if (source && isInModel) {
1551
+ stateWriter?.writeSuccessor(
1552
+ source,
1553
+ getGraphState(successor.state, depths[index] + 1),
1554
+ existing !== -1,
1555
+ action && { name: action.name, signature: getActionSignature(action) },
1556
+ );
1557
+ }
1288
1558
  if (existing !== -1 && liveness) {
1289
1559
  const stored = states[existing];
1290
1560
  const isStored = stored.every((value, position) => value === successor.state[position]);
@@ -1342,10 +1612,22 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1342
1612
  spec.scope,
1343
1613
  );
1344
1614
  } catch (error) {
1345
- return toFailure(error, []);
1615
+ if (!(error instanceof TlaIllegalStateError))
1616
+ return replayInitialStates(toFailure(error, []));
1617
+ // TLC prints an illegal initial state with null for each variable it leaves undefined, and
1618
+ // stops before it prints the statistics.
1619
+ const illegal = toFailure(
1620
+ error,
1621
+ [],
1622
+ error.state.map((value) => value ?? createModelValue("null")),
1623
+ );
1624
+ return {
1625
+ ...illegal,
1626
+ failure: illegal.failure && { ...illegal.failure, isWithoutStatistics: true },
1627
+ };
1346
1628
  }
1347
1629
  }
1348
- if (outcome.result) return outcome.result;
1630
+ if (outcome.result) return replayInitialStates(outcome.result);
1349
1631
 
1350
1632
  const next = spec.next;
1351
1633
  if (next === undefined) {
@@ -1356,23 +1638,58 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1356
1638
  }
1357
1639
  return createSuccess();
1358
1640
  }
1641
+ // TLC labels and colors an edge of the -dump state graph by the action that generated it. When
1642
+ // the graph names its edges, the search generates successors action by action, as TLC does.
1643
+ const isNamingEdges = Boolean(
1644
+ options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1645
+ );
1646
+ const forEachActionSuccessor = (
1647
+ state: Value[],
1648
+ onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1649
+ ) => {
1650
+ if (!isNamingEdges) {
1651
+ return forEachSuccessor(
1652
+ next,
1653
+ state,
1654
+ environment,
1655
+ (successor) => onSuccessor(successor, undefined),
1656
+ spec.scope,
1657
+ );
1658
+ }
1659
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1660
+ const progress = { isStopped: false };
1661
+ return nextActions.value.reduce((count, action) => {
1662
+ if (progress.isStopped) return count;
1663
+ return (
1664
+ count +
1665
+ forEachSuccessor(
1666
+ action.expression,
1667
+ state,
1668
+ environment,
1669
+ (successor) => {
1670
+ progress.isStopped = onSuccessor(successor, action);
1671
+ return progress.isStopped;
1672
+ },
1673
+ action.scope,
1674
+ )
1675
+ );
1676
+ }, 0);
1677
+ };
1359
1678
  const expandState = (index: number) => {
1360
1679
  const state = states[index];
1361
1680
  const liveSuccessors: LiveSuccessor[] = [];
1362
- const successorCount = forEachSuccessor(
1363
- next,
1364
- state,
1365
- environment,
1366
- (successor) => {
1367
- try {
1368
- outcome.result = visitSuccessor(index, successor, liveSuccessors);
1369
- } catch (error) {
1370
- outcome.result = toFailure(error, getTrace(index, successor));
1371
- }
1372
- return outcome.result !== undefined;
1373
- },
1374
- spec.scope,
1375
- );
1681
+ const source = stateWriter && getGraphState(state, depths[index]);
1682
+ const successorCount = forEachActionSuccessor(state, (successor, action) => {
1683
+ try {
1684
+ outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1685
+ } catch (error) {
1686
+ // TLC reports a successor it cannot fingerprint as a failure of the state it expands.
1687
+ if (current.isFingerprinting) throw error;
1688
+ const failure = toFailure(error, getTrace(index, successor));
1689
+ outcome.result = isStackOverflow(error) ? failure : replaySuccessors(failure, index);
1690
+ }
1691
+ return outcome.result !== undefined;
1692
+ });
1376
1693
  current.isExpanding = false;
1377
1694
  if (outcome.result) return outcome.result;
1378
1695
  if (successorCount === 0 && config.checkDeadlock) {
@@ -1392,9 +1709,44 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1392
1709
  trace: toTrace(steps, accepted),
1393
1710
  });
1394
1711
  } catch (error) {
1395
- return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1712
+ return replayFailure(
1713
+ toFailure(toNextStateError(error), getStateTrace(index), undefined, getPartialOutDegrees()),
1714
+ (_, traced) =>
1715
+ createLivenessChecker(
1716
+ search.properties.liveness,
1717
+ spec.temporals,
1718
+ traced,
1719
+ liveGraph,
1720
+ )?.addState(index, state, liveSuccessors),
1721
+ true,
1722
+ );
1396
1723
  }
1397
1724
  };
1725
+ // TLC names the action when the next-state relation has more than one, and prints the
1726
+ // incomplete successor with null for each variable it leaves undefined.
1727
+ const reportIncompleteSuccessor = (error: TlaIncompleteStateError, index: number) => {
1728
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1729
+ const actions = nextActions.value;
1730
+ const action =
1731
+ actions.length === 1 ? actions[0] : actions.find((item) => item.name === error.action);
1732
+ const variables = `variable${error.missing.length > 1 ? "s are" : " is"} not defined: ${error.missing.join(", ")}.\n`;
1733
+ runtime.generatedStates++;
1734
+ return toFailure(
1735
+ actions.length === 1
1736
+ ? error
1737
+ : new TlaEvaluationError(
1738
+ `Successor state is not completely specified by action ${error.action} of the next-state relation. The following ${variables}`,
1739
+ ),
1740
+ [
1741
+ ...getStateTrace(index),
1742
+ {
1743
+ action: error.action,
1744
+ label: action && getActionLabel(action),
1745
+ state: toRecord(error.state.map((value) => value ?? createModelValue("null"))),
1746
+ },
1747
+ ],
1748
+ );
1749
+ };
1398
1750
  // TLC names the properties and the step back into the cycle from the states it prints.
1399
1751
  const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1400
1752
  const path = [...lasso.prefix, ...lasso.cycle];
@@ -1440,7 +1792,14 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1440
1792
  try {
1441
1793
  outcome.result = expandState(index);
1442
1794
  } catch (error) {
1443
- outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1795
+ const failure =
1796
+ error instanceof TlaIncompleteStateError
1797
+ ? reportIncompleteSuccessor(error, index)
1798
+ : toFailure(toNextStateError(error), getStateTrace(index));
1799
+ outcome.result =
1800
+ error instanceof TlaIncompleteStateError || isStackOverflow(error)
1801
+ ? failure
1802
+ : replaySuccessors(failure, index);
1444
1803
  }
1445
1804
  if (outcome.result) return outcome.result;
1446
1805
  outDegrees[getOutDegreeBucket()]++;