tla-ts 0.0.10-dev.96638cd93 → 0.0.10-dev.a17d6d9fa

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 (89) hide show
  1. package/dist/deciders.cjs +30 -30
  2. package/dist/deciders.js +30 -30
  3. package/dist/index.cjs +1 -1
  4. package/dist/index.d.cts +1 -1
  5. package/dist/index.d.ts +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/parallel-worker.cjs +1 -1
  8. package/dist/parallel-worker.js +1 -1
  9. package/dist/prove.cjs +60 -60
  10. package/dist/prove.js +73 -73
  11. package/dist/run.cjs +42 -42
  12. package/dist/run.js +42 -42
  13. package/dist/transfer.cjs +34 -34
  14. package/dist/transfer.js +29 -29
  15. package/dist/worker.cjs +1 -1
  16. package/dist/worker.js +1 -1
  17. package/package.json +1 -1
  18. package/src/bags.ts +5 -2
  19. package/src/builtins.ts +4 -3
  20. package/src/check-failure.ts +1 -1
  21. package/src/check-trace.ts +90 -51
  22. package/src/check.ts +251 -133
  23. package/src/cli/tlc.ts +3 -2
  24. package/src/codegen.ts +18 -5
  25. package/src/dfid.ts +13 -8
  26. package/src/environment.ts +1 -0
  27. package/src/evaluate.ts +25 -9
  28. package/src/exit-codes.ts +1 -0
  29. package/src/java-hash.ts +14 -0
  30. package/src/liveness-checker.ts +63 -31
  31. package/src/liveness.ts +48 -10
  32. package/src/parser.ts +6 -1
  33. package/src/prover/smt/solver/arith-rewriter.ts +11 -3
  34. package/src/prover/smt/solver/array-rewriter.ts +12 -2
  35. package/src/prover/smt/solver/asserted-formulas.ts +109 -63
  36. package/src/prover/smt/solver/ast.ts +5 -3
  37. package/src/prover/smt/solver/auf-solver.ts +23 -12
  38. package/src/prover/smt/solver/bit-blast-tactic.ts +26 -0
  39. package/src/prover/smt/solver/bound-simplifier.ts +10 -11
  40. package/src/prover/smt/solver/card2bv.ts +31 -15
  41. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +39 -23
  42. package/src/prover/smt/solver/context.ts +24 -7
  43. package/src/prover/smt/solver/dependent-expr-state.ts +1 -1
  44. package/src/prover/smt/solver/elim-bounds.ts +89 -0
  45. package/src/prover/smt/solver/elim-uncnstr.ts +1 -1
  46. package/src/prover/smt/solver/internalizer.ts +1 -1
  47. package/src/prover/smt/solver/lp/lp-settings.ts +4 -0
  48. package/src/prover/smt/solver/model-evaluator.ts +2 -0
  49. package/src/prover/smt/solver/model-generator.ts +82 -42
  50. package/src/prover/smt/solver/opt-context.ts +11 -4
  51. package/src/prover/smt/solver/opt-pareto.ts +19 -0
  52. package/src/prover/smt/solver/opt-solver.ts +3 -2
  53. package/src/prover/smt/solver/poly-rewriter.ts +1 -0
  54. package/src/prover/smt/solver/proto-model.ts +4 -2
  55. package/src/prover/smt/solver/push-app-ite.ts +37 -0
  56. package/src/prover/smt/solver/qsat.ts +16 -6
  57. package/src/prover/smt/solver/rewriter.ts +31 -25
  58. package/src/prover/smt/solver/sat/goal2sat.ts +0 -1
  59. package/src/prover/smt/solver/sat/inc-sat-solver.ts +13 -4
  60. package/src/prover/smt/solver/sat/sat-tactic.ts +9 -2
  61. package/src/prover/smt/solver/smt-kernel.ts +30 -2
  62. package/src/prover/smt/solver/smt-setup.ts +28 -4
  63. package/src/prover/smt/solver/smtlib-parser.ts +26 -3
  64. package/src/prover/smt/solver/smtlib-script.ts +34 -21
  65. package/src/prover/smt/solver/solve-eqs.ts +24 -17
  66. package/src/prover/smt/solver/solver.ts +18 -3
  67. package/src/prover/smt/solver/tactic.ts +68 -41
  68. package/src/prover/smt/solver/theory-bv.ts +11 -1
  69. package/src/prover/smt/solver/theory-fpa.ts +1 -1
  70. package/src/prover/smt/solver/theory-lra-final-check.ts +1 -0
  71. package/src/prover/smt/solver/theory-lra-internalize.ts +1 -0
  72. package/src/prover/smt/solver/theory-lra-propagate.ts +7 -1
  73. package/src/prover/smt/solver/theory-lra.ts +1 -0
  74. package/src/prover/smt/solver/tseitin-cnf.ts +1 -0
  75. package/src/resolve.ts +120 -52
  76. package/src/runtime.ts +4 -0
  77. package/src/search.ts +117 -81
  78. package/src/simulate.ts +110 -50
  79. package/src/spec-description.ts +3 -4
  80. package/src/standard-modules.ts +15 -6
  81. package/src/subexpressions.ts +34 -9
  82. package/src/successors.ts +3 -2
  83. package/src/tlc/random.ts +2 -1
  84. package/src/tlc/replay.ts +3 -2
  85. package/src/tlc/tlc-operators.ts +7 -7
  86. package/src/tlc/tlcext-operators.ts +26 -10
  87. package/src/tlc/trace-spec.ts +6 -20
  88. package/src/typed-tier.ts +3 -2
  89. package/src/values.ts +95 -57
package/src/search.ts CHANGED
@@ -52,6 +52,7 @@ import {
52
52
  type Context,
53
53
  type Environment,
54
54
  type Scope,
55
+ type State,
55
56
  } from "./evaluate";
56
57
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
57
58
  import type { JavaOverride } from "./java-overrides";
@@ -85,11 +86,13 @@ import { createTlcOrder } from "./tlc/order";
85
86
  import { getTlcFingerprint, getTlcFingerprints, setFingerprintPolynomial } from "./tlc/fingerprint";
86
87
  import type { TlcVersion } from "./tlc/version";
87
88
  import {
89
+ createModelValue,
88
90
  formatValue,
89
91
  freezeStringOrder,
90
92
  getWrittenPairs,
91
93
  isFunctionValue,
92
94
  isUpdatedElementOf,
95
+ markNormalized,
93
96
  setAliasName,
94
97
  setStringOrder,
95
98
  setValueOptions,
@@ -656,20 +659,26 @@ const getPredicate = (expression: Expression, environment: Environment) => {
656
659
  };
657
660
 
658
661
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
659
- named.flatMap((item) =>
660
- getConjuncts(item.expression, environment).map((expression) => {
661
- const variables =
662
- item.scope === undefined ? getReadVariables(expression, environment) : undefined;
663
- return {
664
- name: item.name,
665
- expression,
666
- scope: item.scope,
667
- variables,
668
- membership: getMembership(expression, variables, environment),
669
- predicate: getPredicate(item.expression, environment),
670
- };
671
- }),
672
- );
662
+ named.flatMap((item) => {
663
+ const predicate = getPredicate(item.expression, environment);
664
+ const isImpure =
665
+ item.scope === undefined && getReadVariables(predicate, environment) === undefined;
666
+ // TLC evaluates an invariant whole, so one that prints isn't split into conjuncts.
667
+ return (isImpure ? [predicate] : getConjuncts(item.expression, environment)).map(
668
+ (expression) => {
669
+ const variables =
670
+ item.scope === undefined ? getReadVariables(expression, environment) : undefined;
671
+ return {
672
+ name: item.name,
673
+ expression,
674
+ scope: item.scope,
675
+ variables,
676
+ membership: getMembership(expression, variables, environment),
677
+ predicate,
678
+ };
679
+ },
680
+ );
681
+ });
673
682
 
674
683
  const isUnchangedFor = (stateCheck: StateCheck, state: Value[], parent: Value[] | undefined) => {
675
684
  const variables = stateCheck.variables;
@@ -712,8 +721,8 @@ export interface Search {
712
721
  toRecord: (state: Value[]) => Record<string, Value>;
713
722
  evaluateAlias: (
714
723
  alias: string,
715
- state: Value[],
716
- next: Value[] | undefined,
724
+ state: State,
725
+ next: State | undefined,
717
726
  isTool: boolean,
718
727
  ) => Record<string, Value>;
719
728
  spec: Specification;
@@ -738,12 +747,13 @@ export interface Search {
738
747
  }
739
748
  | undefined;
740
749
  findViolatedInvariant: (state: Value[], parent?: Value[]) => StateCheck | undefined;
741
- getViolatedInvariants: (state: Value[]) => StateCheck[];
750
+ forEachViolatedInvariant: (state: Value[], onViolated: (invariant: StateCheck) => void) => void;
742
751
  checkReplayedInitialState: (
743
752
  state: Value[],
744
753
  tracing: Environment,
745
754
  addFingerprint: () => void,
746
- ) => Pick<InitialStateViolation, "status" | "name"> | undefined;
755
+ onViolated: (violation: Pick<InitialStateViolation, "status" | "name">) => void,
756
+ ) => void;
747
757
  checkReplayedSuccessor: (
748
758
  state: Value[],
749
759
  next: Value[],
@@ -783,8 +793,8 @@ export const getIncompleteSuccessorMessage = (
783
793
 
784
794
  export const getContext = (
785
795
  environment: Environment,
786
- state: Value[] | undefined,
787
- next: Value[] | undefined,
796
+ state: State | undefined,
797
+ next: State | undefined,
788
798
  scope?: Scope,
789
799
  ) => ({ environment, scope, state, next });
790
800
 
@@ -817,7 +827,7 @@ const getExpectedBoolean = (expression: Expression, environment: Environment) =>
817
827
 
818
828
  const holdsAsConjunct = (check: StateCheck, context: Context) =>
819
829
  holdsLikeTlc(check.expression, context, (expression, environment) => {
820
- holdsLikeTlc(check.predicate, context);
830
+ if (check.predicate !== check.expression) holdsLikeTlc(check.predicate, context);
821
831
  return getExpectedBoolean(expression, environment);
822
832
  });
823
833
 
@@ -1052,6 +1062,12 @@ export const createSearch = (
1052
1062
  ...getCoveredChecks("invariant", configInvariants),
1053
1063
  ...getCoveredChecks("invariant", properties.invariants, false),
1054
1064
  ];
1065
+ const coveredInvariantChecks = new Map(
1066
+ [...configInvariants, ...properties.invariants].map((item, index) => [
1067
+ getPredicate(item.expression, environment),
1068
+ coveredInvariants[index],
1069
+ ]),
1070
+ );
1055
1071
  const coveredActionConstraints = getCoveredChecks("constraint", actionConstraints);
1056
1072
  const coveredConstraints = getCoveredChecks("constraint", namedConstraints);
1057
1073
  const coveredInitialPredicates = getCoveredChecks("implied", properties.initialPredicates, false);
@@ -1074,9 +1090,6 @@ export const createSearch = (
1074
1090
  return undefined;
1075
1091
  }
1076
1092
  };
1077
- const isCoveredHeld = (checks: CoveredCheck[], state: Value[], next?: Value[]) =>
1078
- coverage !== undefined &&
1079
- checks.every((check) => evaluateCovered(coverage, check, state, next) === true);
1080
1093
  const satisfiesCovered = (checks: CoveredCheck[], state: Value[], next?: Value[]) => {
1081
1094
  if (!coverage) return undefined;
1082
1095
  for (const check of checks) {
@@ -1132,9 +1145,15 @@ export const createSearch = (
1132
1145
  };
1133
1146
  const getViewValue = (expression: Expression, state: Value[]) =>
1134
1147
  evaluate(expression, getContext(environment, state, undefined));
1148
+ const getRepresentativeState = (state: Value[]) => {
1149
+ // TLC's TLCStateMut#fingerPrint deep-normalizes a state before it evaluates the view.
1150
+ if (view !== undefined) state.forEach(markNormalized);
1151
+ return symmetryGroup === undefined
1152
+ ? state
1153
+ : getRepresentative(state, symmetryGroup, getTlcOrder());
1154
+ };
1135
1155
  const getTlcStateFingerprint = (state: Value[]) => {
1136
- const representative =
1137
- symmetryGroup === undefined ? state : getRepresentative(state, symmetryGroup, getTlcOrder());
1156
+ const representative = getRepresentativeState(state);
1138
1157
  return getTlcFingerprint(
1139
1158
  view === undefined
1140
1159
  ? getTlcOrder().map((index) => representative[index])
@@ -1142,15 +1161,16 @@ export const createSearch = (
1142
1161
  );
1143
1162
  };
1144
1163
  const findFailedInitialPredicate = (state: Value[]) =>
1145
- isCoveredHeld(coveredInitialPredicates, state)
1146
- ? undefined
1147
- : properties.initialPredicates.find(
1148
- (predicate) =>
1149
- !holdsLikeTlc(
1150
- predicate.expression,
1151
- getContext(environment, state, undefined, predicate.scope),
1152
- ),
1153
- );
1164
+ properties.initialPredicates.find((predicate, index) => {
1165
+ const value =
1166
+ coverage && evaluateCovered(coverage, coveredInitialPredicates[index], state, undefined);
1167
+ return typeof value === "boolean"
1168
+ ? !value
1169
+ : !holdsLikeTlc(
1170
+ predicate.expression,
1171
+ getContext(environment, state, undefined, predicate.scope),
1172
+ );
1173
+ });
1154
1174
  const violatingStates = new WeakSet<Value[]>();
1155
1175
  const isViolated = (invariant: StateCheck, state: Value[], parent: Value[] | undefined) => {
1156
1176
  const checkedParent = parent && !violatingStates.has(parent) ? parent : undefined;
@@ -1174,6 +1194,21 @@ export const createSearch = (
1174
1194
  );
1175
1195
  }
1176
1196
  };
1197
+ const isPredicateViolated = (
1198
+ predicate: StateCheck,
1199
+ state: Value[],
1200
+ parent: Value[] | undefined,
1201
+ ) => {
1202
+ const covered = coveredInvariantChecks.get(predicate.predicate);
1203
+ const value =
1204
+ coverage && covered ? evaluateCovered(coverage, covered, state, undefined) : undefined;
1205
+ return typeof value === "boolean"
1206
+ ? !value
1207
+ : invariants.some(
1208
+ (invariant) =>
1209
+ invariant.predicate === predicate.predicate && isViolated(invariant, state, parent),
1210
+ );
1211
+ };
1177
1212
  const isFingerprintedLikeTlc = hasWideString(config, environment);
1178
1213
  runtime.getFingerprint = getTlcStateFingerprint;
1179
1214
  const findUnwitnessedPossible = () => {
@@ -1229,14 +1264,16 @@ export const createSearch = (
1229
1264
  spec,
1230
1265
  toRecord,
1231
1266
  evaluateAlias: (alias, state, next, isTool) => {
1267
+ const getStateRecord = () =>
1268
+ toRecord(state.map((value) => value ?? createModelValue("null")));
1232
1269
  try {
1233
1270
  getConfigDefinition("alias", alias, environment);
1234
1271
  const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
1235
1272
  const record = toAliasRecord(value);
1236
- return record === undefined ? toRecord(state) : setAliasName(record, alias);
1273
+ return record === undefined ? getStateRecord() : setAliasName(record, alias);
1237
1274
  } catch (error) {
1238
1275
  if (!(error instanceof TlaConfigError || error instanceof TlaEvaluationError)) throw error;
1239
- return { ...toRecord(state), _ALIASEvalError: formatNestedMessage(error.message, isTool) };
1276
+ return { ...getStateRecord(), _ALIASEvalError: formatNestedMessage(error.message, isTool) };
1240
1277
  }
1241
1278
  },
1242
1279
  isSymmetric: symmetryGroup !== undefined,
@@ -1320,40 +1357,38 @@ export const createSearch = (
1320
1357
  },
1321
1358
  getFingerprintState: (state) => {
1322
1359
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
1323
- const representative =
1324
- symmetryGroup === undefined
1325
- ? state
1326
- : getRepresentative(state, symmetryGroup, getTlcOrder());
1360
+ const representative = getRepresentativeState(state);
1327
1361
  return view === undefined ? representative : [getViewValue(view.expression, representative)];
1328
1362
  },
1329
1363
  findViolatedInvariant: (state, parent) => {
1330
- const checked = isCoveredHeld(coveredInvariants, state) ? runtimeChecks : invariants;
1331
- const violated = checked.find((invariant) => isViolated(invariant, state, parent));
1364
+ const violated =
1365
+ coverage === undefined
1366
+ ? invariants.find((invariant) => isViolated(invariant, state, parent))
1367
+ : invariantPredicates.find((predicate) => isPredicateViolated(predicate, state, parent));
1332
1368
  if (violated) violatingStates.add(state);
1333
1369
  return violated;
1334
1370
  },
1335
- getViolatedInvariants: (state) => {
1336
- const violated = invariantPredicates.filter((predicate) =>
1337
- invariants.some(
1338
- (invariant) =>
1339
- invariant.predicate === predicate.predicate && isViolated(invariant, state, undefined),
1340
- ),
1341
- );
1342
- if (violated.length > 0) violatingStates.add(state);
1343
- return violated;
1371
+ forEachViolatedInvariant: (state, onViolated) => {
1372
+ for (const predicate of invariantPredicates) {
1373
+ if (!isPredicateViolated(predicate, state, undefined)) continue;
1374
+ violatingStates.add(state);
1375
+ onViolated(predicate);
1376
+ }
1344
1377
  },
1345
- checkReplayedInitialState: (state, tracing, addFingerprint) => {
1378
+ checkReplayedInitialState: (state, tracing, addFingerprint, onViolated) => {
1346
1379
  const holdsIn = (expression: Expression, scope: Scope | undefined) =>
1347
1380
  holdsLikeTlc(expression, getContext(tracing, state, undefined, scope));
1348
1381
  if (constraints.every((constraint) => holdsIn(constraint.predicate, constraint.scope))) {
1349
1382
  addFingerprint();
1350
1383
  }
1351
- const invariant = invariantPredicates.find((check) => !holdsIn(check.predicate, check.scope));
1352
- if (invariant) return { status: "invariant-violation", name: invariant.name };
1384
+ for (const invariant of invariantPredicates) {
1385
+ if (holdsIn(invariant.predicate, invariant.scope)) continue;
1386
+ onViolated({ status: "invariant-violation", name: invariant.name });
1387
+ }
1353
1388
  const predicate = properties.initialPredicates.find(
1354
1389
  (check) => !holdsIn(check.expression, check.scope),
1355
1390
  );
1356
- return predicate && { status: "liveness-violation", name: predicate.name };
1391
+ if (predicate) onViolated({ status: "liveness-violation", name: predicate.name });
1357
1392
  },
1358
1393
  checkReplayedSuccessor: (state, next, tracing, addFingerprint) => {
1359
1394
  const isInModel =
@@ -1390,31 +1425,32 @@ export const createSearch = (
1390
1425
  ),
1391
1426
  findFailedInitialPredicate,
1392
1427
  findViolatedActionProperty: (state, next) =>
1393
- isCoveredHeld(coveredActionProperties, state, next)
1394
- ? undefined
1395
- : actionProperties.find((property) => {
1396
- try {
1397
- return (
1398
- !holdsLikeTlc(
1399
- property.action,
1400
- getContext(environment, state, next, property.scope),
1401
- () =>
1402
- `Attempted to evaluate an expression of form [A]_e, but A was not a boolean.\n${describeRange(property.box)}`,
1403
- ) &&
1404
- !holds(
1405
- property.unchanged,
1406
- getContext(environment, state, next, property.scope),
1407
- "a subscript",
1408
- )
1409
- );
1410
- } catch (error) {
1411
- throw withHeadline(
1412
- withNextStateExitCode(error),
1413
- MESSAGE_CODE.actionPropertyEvaluationFailed,
1414
- `Evaluating action property ${property.name} failed.`,
1415
- );
1416
- }
1417
- }),
1428
+ actionProperties.find((property, index) => {
1429
+ const value =
1430
+ coverage && evaluateCovered(coverage, coveredActionProperties[index], state, next);
1431
+ if (typeof value === "boolean") return !value;
1432
+ try {
1433
+ return (
1434
+ !holdsLikeTlc(
1435
+ property.action,
1436
+ getContext(environment, state, next, property.scope),
1437
+ () =>
1438
+ `Attempted to evaluate an expression of form [A]_e, but A was not a boolean.\n${describeRange(property.box)}`,
1439
+ ) &&
1440
+ !holds(
1441
+ property.unchanged,
1442
+ getContext(environment, state, next, property.scope),
1443
+ "a subscript",
1444
+ )
1445
+ );
1446
+ } catch (error) {
1447
+ throw withHeadline(
1448
+ withNextStateExitCode(error),
1449
+ MESSAGE_CODE.actionPropertyEvaluationFailed,
1450
+ `Evaluating action property ${property.name} failed.`,
1451
+ );
1452
+ }
1453
+ }),
1418
1454
  satisfiesActionConstraints: (state, next) =>
1419
1455
  satisfiesCovered(coveredActionConstraints, state, next) ??
1420
1456
  actionConstraints.every((constraint) => holdsActionConstraint(constraint, state, next)),
package/src/simulate.ts CHANGED
@@ -10,7 +10,9 @@ import {
10
10
  UNEXPECTED_EVAL_EXCEPTION,
11
11
  UNEXPECTED_EXCEPTION,
12
12
  } from "./errors";
13
+ import type { State } from "./evaluate";
13
14
  import { EXIT_STATUS, getMessageExitStatus, withLivenessExitCode } from "./exit-codes";
15
+ import { getHashMapOrder } from "./java-hash";
14
16
  import { createLivenessChecker, type LivenessChecker } from "./liveness-checker";
15
17
  import { getIncompleteSuccessorMessage, prepareSearch, reportAssumptionViolation } from "./search";
16
18
  import { getActionLabel, toActionValue, type SpecAction } from "./spec-description";
@@ -27,13 +29,20 @@ import {
27
29
  withUnexpectedException,
28
30
  } from "./tlc/messages";
29
31
  import { createJavaRandom, nextPrime, type JavaRandom } from "./tlc/random";
30
- import { createCounterExample } from "./tlc/tlcext-operators";
31
32
  import {
33
+ createActionRecord,
34
+ createCounterExample,
35
+ createTlcRecord,
36
+ type CounterExampleLoop,
37
+ } from "./tlc/tlcext-operators";
38
+ import {
39
+ computeLikeTlcOnFailure,
32
40
  createModelValue,
33
41
  createRecord,
34
42
  formatState,
35
43
  getSetBound,
36
- isSameValue,
44
+ markNormalized,
45
+ valuesEqual,
37
46
  type Value,
38
47
  } from "./values";
39
48
 
@@ -67,6 +76,7 @@ interface TraceNode {
67
76
  predecessor: TraceNode | undefined;
68
77
  level: number;
69
78
  deferred?: (next: Value[]) => void;
79
+ incomplete?: State;
70
80
  }
71
81
 
72
82
  interface WorkerError {
@@ -77,6 +87,7 @@ interface WorkerError {
77
87
  isException: boolean;
78
88
  isSummarized: boolean;
79
89
  violation?: Violation;
90
+ counterExample?: Value;
80
91
  }
81
92
 
82
93
  const FATAL_CODES = new Set<number>([
@@ -91,14 +102,25 @@ const RL_ALPHA = 0.3;
91
102
  const RL_GAMMA = 0.7;
92
103
  const RL_REWARD = -10;
93
104
 
94
- const isSameState = (left: Value[], right: Value[]) =>
95
- left.every((value, index) => isSameValue(value, right[index]));
105
+ const isUnequal = () => false;
106
+
107
+ // TLC's SimulationWorker#getTrace drops a step its TLCState#equals finds stuttering, which sorts the records it compares.
108
+ const isRepeatedState = (state: Value[], predecessor: Value[], order: number[]) => {
109
+ for (let position = 0; position < order.length; position++) {
110
+ const index = order[position];
111
+ // Deviation from TLC: TLCState#equals fails on values it can't compare, which hangs TLC's simulation.
112
+ if (!computeLikeTlcOnFailure(valuesEqual, isUnequal, state[index], predecessor[index])) {
113
+ return false;
114
+ }
115
+ }
116
+ return true;
117
+ };
96
118
 
97
- const getTrace = (last: TraceNode) => {
119
+ const getTrace = (last: TraceNode, order: number[]) => {
98
120
  const trace: TraceNode[] = [];
99
121
  for (let node: TraceNode | undefined = last; node; node = node.predecessor) {
100
122
  const predecessor = node.predecessor;
101
- if (predecessor && isSameState(node.state, predecessor.state)) continue;
123
+ if (predecessor && isRepeatedState(node.state, predecessor.state, order)) continue;
102
124
  trace.unshift(node);
103
125
  }
104
126
  trace.forEach((node, index) => {
@@ -108,6 +130,7 @@ const getTrace = (last: TraceNode) => {
108
130
  return trace;
109
131
  };
110
132
 
133
+ // Deviation from TLC: LiveCheck1 gives the initial state no stuttering step into a tableau node that isn't initial, so it misses a behavior that stutters there.
111
134
  const findTemporalViolation = (
112
135
  trace: TraceNode[],
113
136
  getFingerprint: (state: Value[]) => bigint,
@@ -151,6 +174,7 @@ const findTemporalViolation = (
151
174
  fingerprints[length - 1] === getFingerprint(states[path[lasso.prefix.length]]);
152
175
  return {
153
176
  length,
177
+ isStuttering,
154
178
  loopStart: isStuttering ? length - 1 : cyclePosition - 1,
155
179
  properties: checker.getViolatedProperties(
156
180
  trace.slice(0, length).map((node) => node.state),
@@ -252,10 +276,6 @@ export const simulate = (options: SimulationOptions): number => {
252
276
  let evaluatedAction: SpecAction | undefined;
253
277
  runtime.getSuccessorAction = () => evaluatedAction;
254
278
  runtime.getLevel = (state) => nodes.get(state)?.level ?? 0;
255
- runtime.getBehavior = (state) => {
256
- const node = nodes.get(state);
257
- return node ? getTrace(node).map((step) => step.state) : [state];
258
- };
259
279
  runtime.getSimulationValue = (key, state) => {
260
280
  const node = state && nodes.get(state);
261
281
  switch (key) {
@@ -268,7 +288,7 @@ export const simulate = (options: SimulationOptions): number => {
268
288
  case "action":
269
289
  return node && toActionValue(node.action);
270
290
  case "config":
271
- return createRecord([
291
+ return createTlcRecord([
272
292
  ["mode", options.isGenerating ? "generate" : "simulate"],
273
293
  ["depth", traceDepth === INFINITE_DEPTH ? -1 : traceDepth],
274
294
  ["traces", Number(BigInt.asIntN(32, traceLimit))],
@@ -284,14 +304,19 @@ export const simulate = (options: SimulationOptions): number => {
284
304
  for (let step = node; step && step.level > 1; step = step.predecessor) {
285
305
  actions.set(step.action.name, (actions.get(step.action.name) ?? 0) + 1);
286
306
  }
287
- return createRecord([
307
+ // TLC's SimulationWorker counts the actions of a behavior in a HashMap.
308
+ const counts = getHashMapOrder([...actions.keys()]).map((name): [string, Value] => [
309
+ name,
310
+ actions.get(name) ?? 0,
311
+ ]);
312
+ return createTlcRecord([
288
313
  ["traces", statistics.traces],
289
314
  ["duration", Math.floor((Date.now() - runtime.startedAt) / 1000)],
290
315
  ["generated", statistics.generatedStates],
291
316
  [
292
317
  "behavior",
293
- createRecord([
294
- ["actions", createRecord([...actions])],
318
+ createTlcRecord([
319
+ ["actions", createTlcRecord(counts)],
295
320
  ["id", currentTrace],
296
321
  ]),
297
322
  ],
@@ -311,6 +336,10 @@ export const simulate = (options: SimulationOptions): number => {
311
336
  if (!search) {
312
337
  throw new TlaUnsupportedError("tla-ts can't simulate a specification without variables");
313
338
  }
339
+ runtime.getBehavior = (state) => {
340
+ const node = nodes.get(state);
341
+ return node ? getTrace(node, search.getTlcOrder()).map((step) => step.state) : [state];
342
+ };
314
343
  const reportPostcondition = (isAfterViolation: boolean) => {
315
344
  const postcondition = search.findPostconditionViolation(isAfterViolation);
316
345
  if (!postcondition) return undefined;
@@ -329,8 +358,13 @@ export const simulate = (options: SimulationOptions): number => {
329
358
  createLivenessChecker(temporalProperties, search.spec.temporals, environment, {
330
359
  getFingerprint: (successor) =>
331
360
  Number(BigInt.asIntN(32, runtime.getFingerprint(successor.state))),
332
- getSuccessors: (index) =>
333
- successors[index].map((successor) => ({ index: successor, state: states[successor] })),
361
+ forEachActionSuccessors: (index, _state, onSuccessors) =>
362
+ onSuccessors(
363
+ successors[index].map((successor) => ({
364
+ index: successor,
365
+ state: states[successor],
366
+ })),
367
+ ),
334
368
  }),
335
369
  ),
336
370
  );
@@ -351,25 +385,35 @@ export const simulate = (options: SimulationOptions): number => {
351
385
  const toRecord = (state: (Value | undefined)[]) =>
352
386
  search.toRecord(state.map((value) => value ?? createModelValue("null")));
353
387
  const toTraceSteps = (trace: TraceNode[]): TraceStep[] =>
354
- trace.map((node, index) => ({
355
- action: node.action.name,
356
- label: getActionLabel(node.action, options.version, node.level === 1),
357
- state:
358
- config.alias === undefined || !node.state.every((value) => value !== undefined)
359
- ? toRecord(node.state)
360
- : search.evaluateAlias(
361
- config.alias,
362
- node.state,
363
- (trace[index + 1] ?? node).state,
364
- options.isTool ?? false,
365
- ),
366
- }));
367
- const getCounterExample = (trace: TraceNode[]) =>
388
+ trace.map((node, index) => {
389
+ const successor = trace[index + 1] ?? node;
390
+ return {
391
+ action: node.action.name,
392
+ label: getActionLabel(node.action, options.version, node.level === 1),
393
+ state:
394
+ config.alias === undefined
395
+ ? toRecord(node.state)
396
+ : search.evaluateAlias(
397
+ config.alias,
398
+ node.incomplete ?? node.state,
399
+ successor.incomplete ?? successor.state,
400
+ options.isTool ?? false,
401
+ ),
402
+ };
403
+ });
404
+ const getCounterExample = (
405
+ trace: TraceNode[],
406
+ steps = toTraceSteps(trace),
407
+ loop?: CounterExampleLoop,
408
+ ) =>
368
409
  createCounterExample(
369
- trace.map((node) => search.toRecord(node.state)),
410
+ steps.map((step) => step.state),
370
411
  trace.slice(1).map((node) => toActionValue(node.action)),
371
- undefined,
412
+ loop,
372
413
  );
414
+ // TLC's Simulator binds CounterExample to an initial state that violates an invariant, not to its alias.
415
+ const getInitialCounterExample = (node: TraceNode) =>
416
+ createCounterExample([toRecord(node.state)], [], undefined);
373
417
 
374
418
  const initialStates: TraceNode[] = [];
375
419
  const isComplete = (state: (Value | undefined)[]): state is Value[] =>
@@ -431,7 +475,7 @@ export const simulate = (options: SimulationOptions): number => {
431
475
  MESSAGE_CODE.invariantViolatedInitial,
432
476
  `Invariant ${violated.name} is violated by the initial state:\n${formatState(alias)}`,
433
477
  );
434
- runtime.counterExample = getCounterExample([node]);
478
+ runtime.counterExample = getInitialCounterExample(node);
435
479
  reportPostcondition(true);
436
480
  return EXIT_STATUS.safetyViolation;
437
481
  }
@@ -443,7 +487,7 @@ export const simulate = (options: SimulationOptions): number => {
443
487
  MESSAGE_CODE.propertyViolatedInitial,
444
488
  `Property ${predicate.name} is violated by the initial state:\n${formatState(alias)}`,
445
489
  );
446
- runtime.counterExample = getCounterExample([node]);
490
+ runtime.counterExample = getInitialCounterExample(node);
447
491
  reportPostcondition(true);
448
492
  return EXIT_STATUS.livenessViolation;
449
493
  }
@@ -475,6 +519,8 @@ export const simulate = (options: SimulationOptions): number => {
475
519
  undefined,
476
520
  false,
477
521
  );
522
+ // TLC's Simulator deep-normalizes the initial states, which sorts their records.
523
+ initialStates.forEach((node) => node.state.forEach(markNormalized));
478
524
 
479
525
  const toWorkerError = (code: number, text: string, node: TraceNode): WorkerError => ({
480
526
  code,
@@ -545,6 +591,7 @@ export const simulate = (options: SimulationOptions): number => {
545
591
  action,
546
592
  current,
547
593
  );
594
+ node.incomplete = error.state;
548
595
  const text = getIncompleteSuccessorMessage(
549
596
  error.variables,
550
597
  action.name,
@@ -563,18 +610,34 @@ export const simulate = (options: SimulationOptions): number => {
563
610
  runtime.getFingerprint,
564
611
  search.getReward,
565
612
  );
566
- const getTemporalViolation = (last: TraceNode): Violation | undefined => {
613
+ const getTemporalViolation = (last: TraceNode): WorkerError | undefined => {
567
614
  if (temporalProperties.length === 0) return undefined;
568
- const trace = getTrace(last);
615
+ const trace = getTrace(last, search.getTlcOrder());
616
+ // TLC's LiveCheck#checkTrace fingerprints each state, which sorts its records.
617
+ for (let position = 0; position < trace.length; position++) {
618
+ trace[position].state.forEach(markNormalized);
619
+ }
569
620
  const found = findTemporalViolation(trace, runtime.getFingerprint, createTemporalChecker);
570
621
  if (!found) return undefined;
571
622
  const back = trace[found.length];
623
+ const lasso = trace.slice(0, found.length);
624
+ const steps = toTraceSteps(lasso);
625
+ const loopAction =
626
+ found.isStuttering || !back ? createActionRecord(undefined) : toActionValue(back.action);
572
627
  return {
573
- name: found.properties[0],
574
- properties: found.properties,
575
- trace: toTraceSteps(trace.slice(0, found.length)),
576
- loopStart: found.loopStart,
577
- loopLabel: back && getActionLabel(back.action, options.version, back.level === 1),
628
+ ...toWorkerError(MESSAGE_CODE.temporalPropertyViolated, "", last),
629
+ isException: true,
630
+ violation: {
631
+ name: found.properties[0],
632
+ properties: found.properties,
633
+ trace: steps,
634
+ loopStart: found.loopStart,
635
+ loopLabel: back && getActionLabel(back.action, options.version, back.level === 1),
636
+ },
637
+ counterExample: getCounterExample(lasso, steps, {
638
+ start: found.loopStart,
639
+ action: loopAction,
640
+ }),
578
641
  };
579
642
  };
580
643
  const simulateTrace = (): WorkerError | "stopped" | undefined => {
@@ -603,13 +666,7 @@ export const simulate = (options: SimulationOptions): number => {
603
666
  }
604
667
  if (runtime.isStopped) return "stopped";
605
668
  const violation = getTemporalViolation(currentNode);
606
- if (violation) {
607
- return {
608
- ...toWorkerError(MESSAGE_CODE.temporalPropertyViolated, "", currentNode),
609
- isException: true,
610
- violation,
611
- };
612
- }
669
+ if (violation) return violation;
613
670
  const length = Math.min(traceDepth, currentNode.level);
614
671
  const delta = length - statistics.levelMean;
615
672
  statistics.levelMean += Math.trunc(delta / Math.max(statistics.traces, 1));
@@ -684,14 +741,17 @@ export const simulate = (options: SimulationOptions): number => {
684
741
  reportMessage(error.code, error.message, error.toolMessage);
685
742
  output({
686
743
  kind: "behavior",
687
- trace: toTraceSteps(getTrace(error.node)),
744
+ trace: toTraceSteps(getTrace(error.node, search.getTlcOrder())),
688
745
  isLastStateOnly: traceDepth === INFINITE_DEPTH,
689
746
  });
690
747
  if (error.isSummarized) printSummary();
691
748
  });
692
749
  const last = reported[reported.length - 1];
693
750
  const errorStatus = last ? getMessageExitStatus(last.code) : EXIT_STATUS.success;
694
- if (last) runtime.counterExample = getCounterExample(getTrace(last.node));
751
+ if (last) {
752
+ runtime.counterExample =
753
+ last.counterExample ?? getCounterExample(getTrace(last.node, search.getTlcOrder()));
754
+ }
695
755
  const postcondition = reportPostcondition(last !== undefined);
696
756
  const postconditionStatus = postcondition
697
757
  ? getMessageExitStatus(postcondition.code)