tla-ts 0.0.3-dev.e927a09 → 0.0.3-dev.e9c5857

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