tla-ts 0.0.3-dev.31e0776 → 0.0.3-dev.33ae522

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.
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";
@@ -59,14 +64,16 @@ import {
59
64
  type StateWriter,
60
65
  } from "./state-graph";
61
66
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
62
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
67
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
63
68
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
64
69
  import { createCanonicalizer } from "./canonical";
65
70
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
66
71
  import { createCounterExample } from "./tlc-ext";
72
+ import { getFingerprintTrace, valueSources } from "./value-sources";
67
73
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
68
74
  import {
69
75
  combineHash,
76
+ createModelValue,
70
77
  formatState,
71
78
  formatValue,
72
79
  getValueHash,
@@ -136,6 +143,25 @@ export interface EvaluationFailure {
136
143
  trace: TraceStep[];
137
144
  initialState: Record<string, Value> | undefined;
138
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;
139
165
  }
140
166
 
141
167
  export interface CheckResult {
@@ -247,7 +273,7 @@ const getConstantValue = (name: string, definition: Definition, environment: Env
247
273
  try {
248
274
  return evaluate(createIdentifier(name), getContext(environment, undefined, undefined));
249
275
  } catch (error) {
250
- if (error instanceof TlaEvaluationError) return undefined;
276
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
251
277
  throw error;
252
278
  }
253
279
  };
@@ -276,8 +302,11 @@ const getInvariants = (names: string[], environment: Environment) => {
276
302
  levels.params.size === 0
277
303
  ? ""
278
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.";
279
- throw new TlaConfigError(
280
- `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,
281
310
  );
282
311
  }
283
312
  return [{ name, expression: createIdentifier(name), scope: undefined }];
@@ -375,8 +404,11 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
375
404
  conjunct.kind === "Always" &&
376
405
  getLevel(conjunct.expression, item.scope, environment) < ACTION_LEVEL
377
406
  ) {
378
- throw new TlaConfigError(
379
- `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,
380
412
  );
381
413
  }
382
414
  const level = getLevel(conjunct, item.scope, environment);
@@ -446,12 +478,12 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
446
478
  config.properties.forEach((name) => {
447
479
  const definition = getConfigPredicate("property", name, environment);
448
480
  if (!definition) return;
449
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
481
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
450
482
  const conjunct = item.expression;
451
483
  if (isConstantTrue(item, environment, "property")) return;
452
484
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
453
485
  properties.actionProperties.push({
454
- name,
486
+ name: item.name,
455
487
  box: conjunct.expression,
456
488
  action: conjunct.expression.action,
457
489
  subscript: conjunct.expression.subscript,
@@ -463,12 +495,22 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
463
495
  conjunct.kind === "Always" &&
464
496
  getLevel(conjunct.expression, item.scope, environment) <= 1
465
497
  ) {
466
- 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
+ });
467
505
  return;
468
506
  }
469
507
  const level = getLevel(conjunct, item.scope, environment);
470
508
  if (level < ACTION_LEVEL) {
471
- 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
+ });
472
514
  return;
473
515
  }
474
516
  if (level === ACTION_LEVEL) {
@@ -777,11 +819,13 @@ export const createSearch = (
777
819
  if (view !== undefined || isFingerprintedLikeTlc) {
778
820
  return BigInt64Array.from(states, getTlcStateFingerprint);
779
821
  }
780
- const indices = getTlcOrder();
781
- const getFingerprint = createTlcFingerprinter();
782
- return BigInt64Array.from(fingerprintStates, (state) =>
783
- getFingerprint(indices.map((index) => state[index])),
822
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
823
+ const fingerprint = createTlcFingerprinter(
824
+ getTlcOrder(),
825
+ new Int32Array(fingerprints.buffer),
784
826
  );
827
+ fingerprintStates.forEach(fingerprint);
828
+ return fingerprints;
785
829
  },
786
830
  getFingerprintState: (state) => {
787
831
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
@@ -813,11 +857,17 @@ export const createSearch = (
813
857
  }
814
858
  }),
815
859
  satisfiesConstraints: (state, parent) =>
816
- constraints.every(
817
- (constraint) =>
818
- isUnchangedFor(constraint, state, parent) ||
819
- holdsLikeTlc(constraint.expression, getContext(environment, state, undefined)),
820
- ),
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
+ }),
821
871
  findFailedInitialPredicate: (state) =>
822
872
  properties.initialPredicates.find(
823
873
  (predicate) =>
@@ -850,13 +900,13 @@ export const createSearch = (
850
900
  }
851
901
  }),
852
902
  satisfiesActionConstraints: (state, next) =>
853
- actionConstraints.every((constraint) =>
854
- holdsLikeTlc(
855
- constraint.expression,
856
- getContext(environment, state, next),
857
- (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
858
- ),
859
- ),
903
+ actionConstraints.every((constraint) => {
904
+ try {
905
+ return holdsLikeTlc(constraint.expression, getContext(environment, state, next));
906
+ } catch (error) {
907
+ throw toNextStateError(error);
908
+ }
909
+ }),
860
910
  trackStatePossible:
861
911
  statePossible.length === 0
862
912
  ? ignorePossible
@@ -887,6 +937,59 @@ export const createSearch = (
887
937
  const withNextStateExitCode = (error: unknown) =>
888
938
  error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
889
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
+
890
993
  const withHeadline = (error: unknown, headline: string) =>
891
994
  error instanceof TlaEvaluationError
892
995
  ? setExitCode(
@@ -898,9 +1001,16 @@ const withHeadline = (error: unknown, headline: string) =>
898
1001
  // TLC finishes the -dump file whether or not the search finds a violation.
899
1002
  export const checkSequentially = (options: CheckOptions): CheckResult => {
900
1003
  const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
901
- const result = searchStates(options, stateWriter);
902
- stateWriter?.close();
903
- return result;
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
+ }
904
1014
  };
905
1015
 
906
1016
  const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
@@ -908,9 +1018,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
908
1018
  const onPrint = options.onPrint ?? console.log;
909
1019
  // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
910
1020
  // before the trace would misplace them, so rebuilding a trace prints nothing.
911
- const output = { isMuted: false };
1021
+ const output = { isMuted: false, replayed: undefined as string[] | undefined };
912
1022
  const print = (text: string) => {
913
- if (!output.isMuted) onPrint(text);
1023
+ if (output.replayed) output.replayed.push(text);
1024
+ else if (!output.isMuted) onPrint(text);
914
1025
  };
915
1026
  const withoutOutput = <Result>(rebuild: () => Result) => {
916
1027
  output.isMuted = true;
@@ -972,9 +1083,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
972
1083
  ),
973
1084
  });
974
1085
 
975
- const search = createSearch(config, environment, () =>
976
- getTlcVariableOrder(options.source, options.loadModule),
977
- );
1086
+ const getVariableOrder = () =>
1087
+ getTlcDeclarationOrder(options.source, options.loadModule, "variable");
1088
+ const search = createSearch(config, environment, getVariableOrder);
978
1089
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
979
1090
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
980
1091
  if (!search) return createSuccess();
@@ -998,37 +1109,113 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
998
1109
  const spec = search.spec;
999
1110
  const getFingerprintState = search.getFingerprintState;
1000
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
+ });
1001
1189
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
1002
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
+ };
1003
1217
  const liveness = withLivenessExitCode(() =>
1004
- createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
1005
- getFingerprint: (index) =>
1006
- (tlcFingerprints[index] ??= Number(
1007
- BigInt.asIntN(32, runtime.getFingerprint(states[index])),
1008
- )),
1009
- getSuccessors: (state) => {
1010
- const successors: LiveSuccessor[] = [];
1011
- if (spec.next === undefined) return successors;
1012
- forEachSuccessor(
1013
- spec.next,
1014
- state,
1015
- environment,
1016
- (successor) => {
1017
- canonicalizeState(successor.state);
1018
- const isInModel =
1019
- search.satisfiesConstraints(successor.state, state) &&
1020
- search.satisfiesActionConstraints(state, successor.state);
1021
- if (!isInModel) return false;
1022
- const fingerprintState = getFingerprintState(successor.state);
1023
- const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1024
- successors.push({ index, state: successor.state });
1025
- return false;
1026
- },
1027
- spec.scope,
1028
- );
1029
- return successors;
1030
- },
1031
- }),
1218
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, liveGraph),
1032
1219
  );
1033
1220
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
1034
1221
 
@@ -1037,7 +1224,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1037
1224
  const parents: number[] = [];
1038
1225
  const actions: (string | undefined)[] = [];
1039
1226
  const depths: number[] = [];
1040
- 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 };
1041
1230
  const canonicalizeState = createCanonicalizer();
1042
1231
 
1043
1232
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -1161,7 +1350,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1161
1350
  trace: TraceStep[],
1162
1351
  initialState?: Value[],
1163
1352
  failureOutDegrees?: number[],
1164
- ) => {
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
+ }
1165
1364
  if (!(error instanceof TlaEvaluationError)) throw error;
1166
1365
  return {
1167
1366
  ...createResult("error", undefined, {
@@ -1197,19 +1396,35 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1197
1396
  }
1198
1397
  return true;
1199
1398
  };
1399
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1200
1400
  const findStateIndex = (hash: number, state: Value[]) => {
1201
- const bucket = buckets.get(hash);
1202
- if (bucket === undefined) return -1;
1203
- if (typeof bucket === "number") {
1204
- 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
+ }
1205
1408
  }
1206
- 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;
1207
1416
  };
1208
1417
  const markSeen = (hash: number, index: number) => {
1209
- const bucket = buckets.get(hash);
1210
- if (bucket === undefined) buckets.set(hash, index);
1211
- else if (typeof bucket === "number") buckets.set(hash, [bucket, index]);
1212
- 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);
1213
1428
  };
1214
1429
  const countDistinctState = (depth: number) => {
1215
1430
  runtime.distinctStates = states.length + 1;
@@ -1235,6 +1450,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1235
1450
  isExpanding: false,
1236
1451
  candidate: undefined as Value[] | undefined,
1237
1452
  candidateLevel: 0,
1453
+ isFingerprinting: false,
1238
1454
  livenessSource: -1,
1239
1455
  };
1240
1456
  const getPath = (index: number): Value[][] =>
@@ -1321,8 +1537,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1321
1537
  current.candidate = successor.state;
1322
1538
  current.candidateLevel = depths[index] + 1;
1323
1539
  if (isCanonicalizedFirst) canonicalizeState(successor.state);
1540
+ current.isFingerprinting = true;
1324
1541
  const fingerprintState = getFingerprintState(successor.state);
1325
1542
  const hash = getStateHash(fingerprintState);
1543
+ current.isFingerprinting = false;
1326
1544
  const found = findStateIndex(hash, fingerprintState);
1327
1545
  const isStateInModel = search.satisfiesConstraints(successor.state, state);
1328
1546
  if (isStateInModel) search.trackStatePossible(successor.state);
@@ -1394,10 +1612,22 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1394
1612
  spec.scope,
1395
1613
  );
1396
1614
  } catch (error) {
1397
- 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
+ };
1398
1628
  }
1399
1629
  }
1400
- if (outcome.result) return outcome.result;
1630
+ if (outcome.result) return replayInitialStates(outcome.result);
1401
1631
 
1402
1632
  const next = spec.next;
1403
1633
  if (next === undefined) {
@@ -1453,7 +1683,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1453
1683
  try {
1454
1684
  outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1455
1685
  } catch (error) {
1456
- outcome.result = toFailure(error, getTrace(index, successor));
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);
1457
1690
  }
1458
1691
  return outcome.result !== undefined;
1459
1692
  });
@@ -1476,9 +1709,44 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1476
1709
  trace: toTrace(steps, accepted),
1477
1710
  });
1478
1711
  } catch (error) {
1479
- 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
+ );
1480
1723
  }
1481
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
+ };
1482
1750
  // TLC names the properties and the step back into the cycle from the states it prints.
1483
1751
  const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1484
1752
  const path = [...lasso.prefix, ...lasso.cycle];
@@ -1524,7 +1792,14 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1524
1792
  try {
1525
1793
  outcome.result = expandState(index);
1526
1794
  } catch (error) {
1527
- 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);
1528
1803
  }
1529
1804
  if (outcome.result) return outcome.result;
1530
1805
  outDegrees[getOutDegreeBucket()]++;
package/src/codegen.ts CHANGED
@@ -10,6 +10,8 @@ import {
10
10
  getSubsetOperator,
11
11
  getEvaluator,
12
12
  getFieldError,
13
+ getNonFunctionError,
14
+ getNonRecordError,
13
15
  isClosedConstant,
14
16
  isTlcInteger,
15
17
  isValueArgument,
@@ -250,12 +252,13 @@ const generateExpression = (generator: Generator, expression: Expression, frame:
250
252
  case "FunctionApplication": {
251
253
  keepLazy(expression.function);
252
254
  const functionCode = generate(expression.function);
255
+ const describeNonFunction = addReference(generator, getNonFunctionError(expression));
253
256
  if (expression.args.length === 1)
254
- return `apply(${functionCode}, ${generate(expression.args[0])})`;
255
- return `apply(${functionCode}, tuple([${expression.args.map((arg) => generate(arg)).join(", ")}]))`;
257
+ return `apply(${functionCode}, ${generate(expression.args[0])}, undefined, ${describeNonFunction})`;
258
+ return `apply(${functionCode}, tuple([${expression.args.map((arg) => generate(arg)).join(", ")}]), undefined, ${describeNonFunction})`;
256
259
  }
257
260
  case "FieldAccess":
258
- return `apply(${generate(expression.record)}, ${JSON.stringify(expression.field)}, ${addReference(generator, getFieldError(expression))})`;
261
+ return `apply(${generate(expression.record)}, ${JSON.stringify(expression.field)}, ${addReference(generator, getFieldError(expression))}, ${addReference(generator, getNonRecordError(expression))})`;
259
262
  case "Record": {
260
263
  const fields = getSortedFields(expression.fields);
261
264
  if (hasDuplicateFields(fields)) return generateDelegate(generator, expression, frame);