tla-ts 0.0.3-dev.4c8c06c → 0.0.3-dev.4cf9a33

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