tla-ts 0.0.10-dev.28c823e4b → 0.0.10-dev.63a6693bd

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 (172) hide show
  1. package/dist/compile.cjs +6 -6
  2. package/dist/compile.js +10 -10
  3. package/dist/deciders.cjs +29 -29
  4. package/dist/deciders.js +40 -40
  5. package/dist/index.cjs +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-worker.cjs +1 -1
  10. package/dist/prove-worker.js +1 -1
  11. package/dist/prove.cjs +54 -54
  12. package/dist/prove.js +52 -52
  13. package/dist/run.cjs +42 -42
  14. package/dist/run.js +44 -44
  15. package/dist/tlapm.cjs +2 -2
  16. package/dist/tlapm.js +2 -2
  17. package/dist/transfer.cjs +39 -39
  18. package/dist/transfer.js +41 -41
  19. package/dist/worker.cjs +4 -4
  20. package/dist/worker.js +4 -4
  21. package/package.json +1 -1
  22. package/src/ast.ts +44 -39
  23. package/src/builtins.ts +4 -13
  24. package/src/check-failure.ts +116 -0
  25. package/src/check-trace.ts +282 -0
  26. package/src/check.ts +152 -518
  27. package/src/cli/options.ts +6 -31
  28. package/src/cli/shared.ts +1 -1
  29. package/src/cli/tlapm.ts +14 -13
  30. package/src/cli/tlc-arguments.ts +222 -210
  31. package/src/cli/tlc-output.ts +687 -0
  32. package/src/cli/tlc-usage.ts +1 -1
  33. package/src/cli/tlc.ts +34 -701
  34. package/src/cli/xml-exporter.ts +23 -33
  35. package/src/codegen.ts +5 -10
  36. package/src/coverage.ts +3 -10
  37. package/src/dependencies.ts +8 -13
  38. package/src/dfid.ts +16 -16
  39. package/src/environment-config.ts +315 -0
  40. package/src/environment.ts +45 -333
  41. package/src/errors.ts +3 -2
  42. package/src/evaluate.ts +5 -4
  43. package/src/fingerprints.ts +65 -1
  44. package/src/instances.ts +47 -10
  45. package/src/java-hash.ts +7 -0
  46. package/src/json.ts +4 -7
  47. package/src/levels.ts +39 -42
  48. package/src/liveness-checker.ts +24 -37
  49. package/src/liveness.ts +47 -54
  50. package/src/obligations/action.ts +4 -11
  51. package/src/obligations/anonymize.ts +4 -2
  52. package/src/obligations/expression.ts +18 -2
  53. package/src/obligations/generate.ts +45 -38
  54. package/src/obligations/index.ts +2 -2
  55. package/src/obligations/module.ts +27 -38
  56. package/src/obligations/normalize.ts +2 -1
  57. package/src/obligations/simplify.ts +39 -44
  58. package/src/obligations/source.ts +47 -57
  59. package/src/obligations/temporal.ts +5 -5
  60. package/src/parallel-worker.ts +10 -30
  61. package/src/parallel.ts +22 -45
  62. package/src/parser.ts +19 -34
  63. package/src/prover/decide-pool.ts +3 -3
  64. package/src/prover/deciders.ts +3 -3
  65. package/src/prover/isabelle/encode.ts +1 -1
  66. package/src/prover/isabelle/isar/inner-syntax.ts +9 -4
  67. package/src/prover/isabelle/isar/method.ts +14 -25
  68. package/src/prover/isabelle/isar/theory.ts +11 -10
  69. package/src/prover/isabelle/isar/type-check.ts +6 -6
  70. package/src/prover/isabelle/provers/blast/blast.ts +7 -63
  71. package/src/prover/isabelle/provers/hypsubst.ts +17 -26
  72. package/src/prover/isabelle/pure/bicompose.ts +9 -25
  73. package/src/prover/isabelle/pure/conv.ts +2 -8
  74. package/src/prover/isabelle/pure/drule.ts +9 -2
  75. package/src/prover/isabelle/pure/logic.ts +1 -1
  76. package/src/prover/isabelle/pure/raw-simplifier.ts +4 -13
  77. package/src/prover/isabelle/pure/rewriter.ts +5 -9
  78. package/src/prover/isabelle/pure/table.ts +2 -1
  79. package/src/prover/isabelle/pure/tactical.ts +42 -35
  80. package/src/prover/isabelle/pure/thm.ts +14 -11
  81. package/src/prover/isabelle/tla/classical-setup.ts +17 -14
  82. package/src/prover/isabelle/tla/context.ts +7 -2
  83. package/src/prover/isabelle/tla/logic.ts +10 -21
  84. package/src/prover/isabelle/tla/simpdata.ts +1 -10
  85. package/src/prover/prep/action.ts +11 -19
  86. package/src/prover/prep/fingerprint.ts +2 -5
  87. package/src/prover/prep/methods.ts +24 -3
  88. package/src/prover/prove.ts +87 -64
  89. package/src/prover/smt/context.ts +1 -2
  90. package/src/prover/smt/data.ts +418 -406
  91. package/src/prover/smt/encode.ts +30 -18
  92. package/src/prover/smt/rewrite.ts +657 -626
  93. package/src/prover/smt/solver/ast.ts +0 -22
  94. package/src/prover/smt/solver/auf-solver.ts +2 -5
  95. package/src/prover/smt/solver/context.ts +3 -3
  96. package/src/prover/smt/solver/e-matching.ts +1 -1
  97. package/src/prover/smt/solver/expr-safe-replace.ts +1 -1
  98. package/src/prover/smt/solver/internalizer.ts +1 -2
  99. package/src/prover/smt/solver/lp/dioph-eq.ts +1 -8
  100. package/src/prover/smt/solver/lp/hnf-cutter.ts +1 -1
  101. package/src/prover/smt/solver/lp/nla-core.ts +2 -6
  102. package/src/prover/smt/solver/mam-compiler.ts +4 -2
  103. package/src/prover/smt/solver/model-checker.ts +1 -1
  104. package/src/prover/smt/solver/model-finder.ts +12 -17
  105. package/src/prover/smt/solver/model-macro-solver.ts +11 -19
  106. package/src/prover/smt/solver/nlsat/algebraic.ts +9 -9
  107. package/src/prover/smt/solver/nlsat/atoms.ts +20 -4
  108. package/src/prover/smt/solver/nlsat/explain.ts +7 -22
  109. package/src/prover/smt/solver/nlsat/levelwise.ts +1 -6
  110. package/src/prover/smt/solver/nlsat/polynomial.ts +12 -3
  111. package/src/prover/smt/solver/nlsat/solver.ts +12 -24
  112. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +1 -1
  113. package/src/prover/smt/solver/proto-model.ts +0 -4
  114. package/src/prover/smt/solver/quantifier-analyzer.ts +10 -10
  115. package/src/prover/smt/solver/quantifier-manager.ts +1 -5
  116. package/src/prover/smt/solver/smtlib-parser.ts +78 -94
  117. package/src/prover/smt/solver/theory-lra-bounds.ts +1 -2
  118. package/src/prover/smt/solver/theory-lra-internalize.ts +5 -16
  119. package/src/prover/tlapm/cache.ts +28 -18
  120. package/src/prover/tlapm/tlapm.ts +15 -9
  121. package/src/prover/verdict.ts +7 -0
  122. package/src/prover/zenon/check/check.ts +1 -2
  123. package/src/prover/zenon/check/records.ts +1 -1
  124. package/src/prover/zenon/check/relations.ts +2 -1
  125. package/src/prover/zenon/check/rewrites.ts +2 -15
  126. package/src/prover/zenon/check/sets.ts +40 -58
  127. package/src/prover/zenon/check/terms.ts +1 -2
  128. package/src/prover/zenon/eqrel.ts +2 -0
  129. package/src/prover/zenon/expr.ts +7 -0
  130. package/src/prover/zenon/index-table.ts +9 -19
  131. package/src/prover/zenon/isar.ts +35 -35
  132. package/src/prover/zenon/llproof.ts +2 -11
  133. package/src/prover/zenon/mltoll.ts +12 -28
  134. package/src/prover/zenon/parse.ts +3 -6
  135. package/src/prover/zenon/search.ts +4 -14
  136. package/src/prover/zenon/tla/functions.ts +2 -2
  137. package/src/prover/zenon/tla/llproof.ts +9 -11
  138. package/src/prover/zenon/tla/records.ts +1 -6
  139. package/src/prover/zenon/tla/sets.ts +15 -14
  140. package/src/prover/zenon/tla/tla.ts +7 -6
  141. package/src/resolve.ts +55 -72
  142. package/src/sany/generation.ts +394 -0
  143. package/src/sany/generator-def-entries.ts +210 -0
  144. package/src/sany/generator-definitions.ts +686 -0
  145. package/src/sany/generator-expressions.ts +1100 -0
  146. package/src/sany/generator-proofs.ts +662 -0
  147. package/src/sany/generator.ts +155 -2625
  148. package/src/sany/lexer.ts +17 -16
  149. package/src/sany/nodes.ts +6 -13
  150. package/src/sany/report.ts +3 -6
  151. package/src/sany/selectors.ts +35 -38
  152. package/src/sany/xml.ts +23 -55
  153. package/src/search.ts +65 -27
  154. package/src/simulate.ts +157 -133
  155. package/src/spec-description.ts +33 -48
  156. package/src/standard-modules.ts +16 -32
  157. package/src/state-graph.ts +2 -7
  158. package/src/substitution-levels.ts +5 -4
  159. package/src/successors.ts +5 -7
  160. package/src/tlc/messages.ts +20 -15
  161. package/src/tlc/order.ts +2 -9
  162. package/src/tlc/random.ts +4 -4
  163. package/src/tlc/replay.ts +8 -15
  164. package/src/tlc/tlc-operators.ts +2 -3
  165. package/src/tlc/trace-spec.ts +25 -45
  166. package/src/typescript/actions.ts +2 -4
  167. package/src/typescript/collections.ts +34 -20
  168. package/src/typescript/compile.ts +1 -3
  169. package/src/typescript/formula.ts +5 -3
  170. package/src/typescript/model.ts +4 -5
  171. package/src/typescript/steps.ts +20 -18
  172. package/src/values.ts +63 -158
package/src/search.ts CHANGED
@@ -57,7 +57,12 @@ import {
57
57
  import { expandTemporal, getLevel, type ScopedExpression, type TemporalProperty } from "./liveness";
58
58
  import { prettyPrint } from "./pretty-print";
59
59
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
60
- import { getSpecificationValue, getSubscriptVariables } from "./spec-description";
60
+ import {
61
+ getSpecDescription,
62
+ getSpecificationValue,
63
+ getSubscriptVariables,
64
+ type SpecDescription,
65
+ } from "./spec-description";
61
66
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
62
67
  import {
63
68
  formatInnerMessage,
@@ -71,6 +76,7 @@ import { getTlcFingerprint, getTlcFingerprints, setFingerprintPolynomial } from
71
76
  import type { TlcVersion } from "./tlc/version";
72
77
  import {
73
78
  formatValue,
79
+ freezeStringOrder,
74
80
  getWrittenPairs,
75
81
  isFunctionValue,
76
82
  isUpdatedElementOf,
@@ -82,6 +88,27 @@ import {
82
88
  type Value,
83
89
  } from "./values";
84
90
 
91
+ interface EnvironmentSettings extends Pick<
92
+ CheckOptions,
93
+ | "source"
94
+ | "loadModule"
95
+ | "loadClass"
96
+ | "readFile"
97
+ | "writeFile"
98
+ | "makeDirectory"
99
+ | "seed"
100
+ | "isTool"
101
+ | "traceSpec"
102
+ | "isSanyReported"
103
+ | "isWarningEnabled"
104
+ | "version"
105
+ | "moduleOperators"
106
+ | "fingerprintPolynomial"
107
+ | "maxSetSize"
108
+ | "isLazyValueExpanded"
109
+ | "isViewPrinted"
110
+ > {}
111
+
85
112
  interface NamedExpression {
86
113
  name: string;
87
114
  expression: Expression;
@@ -136,6 +163,12 @@ const createIdentifier = (name: string): Expression => ({
136
163
  location: START,
137
164
  });
138
165
 
166
+ const createNamedIdentifier = (name: string): NamedExpression => ({
167
+ name,
168
+ expression: createIdentifier(name),
169
+ scope: undefined,
170
+ });
171
+
139
172
  const UNNAMED_ARGUMENT_KINDS = new Set(["name", "property"]);
140
173
 
141
174
  const getConfigOperator = (kind: string, name: string, environment: Environment) => {
@@ -250,7 +283,7 @@ const getInvariants = (names: string[], environment: Environment) => {
250
283
  EXIT_STATUS.safetyEvaluationFailure,
251
284
  );
252
285
  }
253
- return [{ name, expression: createIdentifier(name), scope: undefined }];
286
+ return [createNamedIdentifier(name)];
254
287
  });
255
288
  };
256
289
 
@@ -533,9 +566,7 @@ const getNamedExpressions = (
533
566
  environment: Environment,
534
567
  ): NamedExpression[] =>
535
568
  names.flatMap((name) =>
536
- getConfigPredicate(kind, name, environment)
537
- ? [{ name, expression: createIdentifier(name), scope: undefined }]
538
- : [],
569
+ getConfigPredicate(kind, name, environment) ? [createNamedIdentifier(name)] : [],
539
570
  );
540
571
 
541
572
  const getBodyRange = (name: string, environment: Environment) => {
@@ -549,13 +580,13 @@ const getPossiblePredicates = (names: string[], environment: Environment) =>
549
580
  throw new TlaConfigError(`_POSSIBLE lists ${name} more than once`);
550
581
  }
551
582
  getConfigDefinition("possible", name, environment);
552
- const expression = createIdentifier(name);
553
- if (getLevel(expression, undefined, environment) === TEMPORAL_LEVEL) {
583
+ const possible = createNamedIdentifier(name);
584
+ if (getLevel(possible.expression, undefined, environment) === TEMPORAL_LEVEL) {
554
585
  throw new TlaConfigError(
555
586
  `The possible of ${name} is equal to a temporal formula; only state- and action-level predicates are supported`,
556
587
  );
557
588
  }
558
- return { name, expression, scope: undefined };
589
+ return possible;
559
590
  });
560
591
 
561
592
  const getMembership = (
@@ -634,7 +665,7 @@ const hasWideString = (config: ModelConfig, environment: Environment) =>
634
665
  definition.bounds.some((bound) => isWideExpression(bound.set))),
635
666
  );
636
667
 
637
- interface Search {
668
+ export interface Search {
638
669
  properties: Properties;
639
670
  toRecord: (state: Value[]) => Record<string, Value>;
640
671
  evaluateAlias: (
@@ -770,21 +801,23 @@ export const findAssumptionViolation = (
770
801
  return undefined;
771
802
  };
772
803
 
773
- export const prepareSearch = (options: CheckOptions) => {
774
- const config =
775
- typeof options.config === "string"
776
- ? parseConfig(options.config, options.version)
777
- : options.config;
804
+ export const createCheckEnvironment = (
805
+ config: ModelConfig,
806
+ options: EnvironmentSettings,
807
+ print: (text: string) => void,
808
+ isStringOrderFrozen = false,
809
+ ) => {
778
810
  const order = createTlcOrder(options.source, options.loadModule);
779
811
  setStringOrder(order.getStringOrder(config));
780
812
  setValueOptions(options);
781
813
  setFingerprintPolynomial(options.fingerprintPolynomial ?? 0);
814
+ if (isStringOrderFrozen) freezeStringOrder();
782
815
  const specification = createEnvironment(config, {
783
816
  source: options.source,
784
817
  loadModule: options.loadModule,
785
818
  order,
786
819
  loadClass: options.loadClass,
787
- print: options.onPrint ?? console.log,
820
+ print,
788
821
  files: {
789
822
  readFile: options.readFile,
790
823
  writeFile: options.writeFile,
@@ -798,24 +831,32 @@ export const prepareSearch = (options: CheckOptions) => {
798
831
  version: options.version,
799
832
  moduleOperators: options.moduleOperators,
800
833
  });
834
+ return { order, specification };
835
+ };
836
+
837
+ export const prepareSearch = (options: CheckOptions) => {
838
+ const config =
839
+ typeof options.config === "string"
840
+ ? parseConfig(options.config, options.version)
841
+ : options.config;
842
+ const created = createCheckEnvironment(config, options, options.onPrint ?? console.log);
843
+ const specification = created.specification;
801
844
  reportStartup(specification, config, options.onProgress);
802
845
  const environment = specification.environment;
846
+ let description: SpecDescription | undefined;
847
+ const getDescription = () =>
848
+ (description ??= getSpecDescription(config, environment, specification.instanceActions));
803
849
  environment.runtime.getSpecification = () =>
804
- getSpecificationValue(
805
- config,
806
- environment,
807
- specification.variableLocations,
808
- specification.instanceActions,
809
- );
850
+ getSpecificationValue(getDescription(), config, environment, specification.variableLocations);
810
851
  const search = createSearch(
811
852
  config,
812
853
  environment,
813
854
  specification.variableLocations,
814
- () => order.getDeclarationOrder("variable"),
855
+ () => created.order.getDeclarationOrder("variable"),
815
856
  options.onProgress,
816
857
  specification.moduleOperators,
817
858
  );
818
- return { config, specification, environment, search };
859
+ return { config, specification, environment, search, getDescription };
819
860
  };
820
861
 
821
862
  export const reportAssumptionViolation = (
@@ -980,10 +1021,7 @@ export const createSearch = (
980
1021
  ? undefined
981
1022
  : getConfigDefinition("view function", config.view, environment);
982
1023
  const viewName = config.view ?? getModuleOperators("view")[0]?.name;
983
- const view =
984
- viewName === undefined
985
- ? undefined
986
- : { name: viewName, expression: createIdentifier(viewName), scope: undefined };
1024
+ const view = viewName === undefined ? undefined : createNamedIdentifier(viewName);
987
1025
  const actionProperties = properties.actionProperties.map((property) => {
988
1026
  const unchanged: Expression = {
989
1027
  kind: "Unchanged",
package/src/simulate.ts CHANGED
@@ -11,15 +11,9 @@ import {
11
11
  UNEXPECTED_EXCEPTION,
12
12
  } from "./errors";
13
13
  import { EXIT_STATUS, getMessageExitStatus, withLivenessExitCode } from "./exit-codes";
14
- import { createLivenessChecker } from "./liveness-checker";
14
+ import { createLivenessChecker, type LivenessChecker } from "./liveness-checker";
15
15
  import { getIncompleteSuccessorMessage, prepareSearch, reportAssumptionViolation } from "./search";
16
- import {
17
- getActionLabel,
18
- getInitActions,
19
- getNextActions,
20
- toActionValue,
21
- type SpecAction,
22
- } from "./spec-description";
16
+ import { getActionLabel, toActionValue, type SpecAction } from "./spec-description";
23
17
  import { forEachInitialState, forEachSuccessor } from "./successors";
24
18
  import {
25
19
  formatInnerMessage,
@@ -32,7 +26,7 @@ import {
32
26
  MESSAGE_CODE,
33
27
  withUnexpectedException,
34
28
  } from "./tlc/messages";
35
- import { createJavaRandom, nextPrime } from "./tlc/random";
29
+ import { createJavaRandom, nextPrime, type JavaRandom } from "./tlc/random";
36
30
  import { createCounterExample } from "./tlc/tlcext-operators";
37
31
  import {
38
32
  createModelValue,
@@ -100,8 +94,131 @@ const RL_REWARD = -10;
100
94
  const isSameState = (left: Value[], right: Value[]) =>
101
95
  left.every((value, index) => isSameValue(value, right[index]));
102
96
 
97
+ const getTrace = (last: TraceNode) => {
98
+ const trace: TraceNode[] = [];
99
+ for (let node: TraceNode | undefined = last; node; node = node.predecessor) {
100
+ const predecessor = node.predecessor;
101
+ if (predecessor && isSameState(node.state, predecessor.state)) continue;
102
+ trace.unshift(node);
103
+ }
104
+ trace.forEach((node, index) => {
105
+ node.predecessor = trace[index - 1];
106
+ node.level = index + 1;
107
+ });
108
+ return trace;
109
+ };
110
+
111
+ const findTemporalViolation = (
112
+ trace: TraceNode[],
113
+ getFingerprint: (state: Value[]) => bigint,
114
+ createChecker: (successors: number[][], states: Value[][]) => LivenessChecker | undefined,
115
+ ) => {
116
+ const fingerprints = trace.map((node) => getFingerprint(node.state));
117
+ const indices = new Map<bigint, number>();
118
+ const states: Value[][] = [];
119
+ const successors: number[][] = [];
120
+ fingerprints.forEach((fingerprint, position) => {
121
+ if (!indices.has(fingerprint)) {
122
+ indices.set(fingerprint, states.length);
123
+ states.push(trace[position].state);
124
+ successors.push([]);
125
+ }
126
+ if (position === 0) return;
127
+ const source = indices.get(fingerprints[position - 1]) ?? 0;
128
+ const target = indices.get(fingerprint) ?? 0;
129
+ if (source !== target && !successors[source].includes(target)) {
130
+ successors[source].push(target);
131
+ }
132
+ });
133
+ const checker = createChecker(successors, states);
134
+ if (!checker) return undefined;
135
+ checker.addInitialState(0, states[0]);
136
+ states.forEach((state, index) =>
137
+ checker.addState(
138
+ index,
139
+ state,
140
+ successors[index].map((successor) => ({ index: successor, state: states[successor] })),
141
+ ),
142
+ );
143
+ const lasso = checker.findViolation();
144
+ if (!lasso) return undefined;
145
+ const getLength = (path: number[]) =>
146
+ path.filter((index, position) => position === 0 || index !== path[position - 1]).length;
147
+ const path = [...lasso.prefix, ...lasso.cycle];
148
+ const length = getLength(path);
149
+ const cyclePosition = getLength(path.slice(0, lasso.prefix.length + 1));
150
+ const isStuttering =
151
+ fingerprints[length - 1] === getFingerprint(states[path[lasso.prefix.length]]);
152
+ return {
153
+ length,
154
+ loopStart: isStuttering ? length - 1 : cyclePosition - 1,
155
+ properties: checker.getViolatedProperties(
156
+ trace.slice(0, length).map((node) => node.state),
157
+ cyclePosition - 1,
158
+ ),
159
+ };
160
+ };
161
+
162
+ const createScheduler = (
163
+ scheduler: SimulationOptions["scheduler"],
164
+ nextActions: SpecAction[],
165
+ random: JavaRandom,
166
+ getFingerprint: (state: Value[]) => bigint,
167
+ getReward: (state: Value[] | undefined, next: Value[], fallback: number) => number,
168
+ ) => {
169
+ const qualities = nextActions.map(() => new Map<bigint | SpecAction, number>());
170
+ const getQualityKey = (node: TraceNode) =>
171
+ scheduler === "rlaction" ? node.action : getFingerprint(node.state);
172
+ const getRewardOf = (node: TraceNode) =>
173
+ getReward(node.predecessor?.state, node.state, RL_REWARD);
174
+ return {
175
+ getNextActionIndex: (node: TraceNode) => {
176
+ if (scheduler === "random") {
177
+ return Math.floor(random.nextDouble() * nextActions.length);
178
+ }
179
+ const key = getQualityKey(node);
180
+ qualities.forEach((quality) => {
181
+ if (!quality.has(key)) quality.set(key, 0);
182
+ });
183
+ const weights = qualities.map((quality) => Math.exp(quality.get(key) ?? 0));
184
+ const total = weights.reduce((sum, weight) => sum + weight, 0);
185
+ const ranked = weights
186
+ .map((weight, index) => ({ index, weight: weight / total }))
187
+ .sort((left, right) => right.weight - left.weight);
188
+ const threshold = random.nextDouble();
189
+ let cumulativeWeight = 0;
190
+ const chosen = ranked.find((item, position) => {
191
+ cumulativeWeight = position === 0 ? item.weight : cumulativeWeight + item.weight;
192
+ return cumulativeWeight >= threshold;
193
+ });
194
+ return (chosen ?? ranked[ranked.length - 1]).index;
195
+ },
196
+ markDisabled: (index: number, node: TraceNode) => {
197
+ if (scheduler === "random") return;
198
+ // TLC's rlaction scheduler stores the reward, then overwrites it as the rl scheduler does.
199
+ if (scheduler === "rlaction") getRewardOf(node);
200
+ qualities[index].set(getQualityKey(node), -Number.MAX_VALUE);
201
+ },
202
+ learnTrace: (last: TraceNode) => {
203
+ for (let node = last; node.predecessor; node = node.predecessor) {
204
+ const key = getQualityKey(node);
205
+ const maxQuality = qualities.reduce(
206
+ (max, quality) => Math.max(max, quality.get(key) ?? -Number.MAX_VALUE),
207
+ -Number.MAX_VALUE,
208
+ );
209
+ const quality = qualities[nextActions.indexOf(node.action)];
210
+ const predecessorKey = getQualityKey(node.predecessor);
211
+ quality.set(
212
+ predecessorKey,
213
+ (1 - RL_ALPHA) * (quality.get(predecessorKey) ?? 0) +
214
+ RL_ALPHA * (getRewardOf(node) + RL_GAMMA * maxQuality),
215
+ );
216
+ }
217
+ },
218
+ };
219
+ };
220
+
103
221
  export const simulate = (options: SimulationOptions): number => {
104
- const isTool = options.isTool ?? false;
105
222
  const output = options.onSimulation;
106
223
  const prepared = prepareSearch(options);
107
224
  const config = prepared.config;
@@ -111,6 +228,7 @@ export const simulate = (options: SimulationOptions): number => {
111
228
  const search = prepared.search;
112
229
  const seed = options.seed ?? 0n;
113
230
  const traceDepth = options.traceDepth === -1 ? INFINITE_DEPTH : options.traceDepth;
231
+ const traceLimit = options.traceCount ?? (1n << 63n) - 1n;
114
232
  const random = createJavaRandom(seed);
115
233
  for (let index = 0n; index < options.aril; index++) random.nextDouble();
116
234
  const workerRandom = createJavaRandom(random.nextLong());
@@ -126,8 +244,9 @@ export const simulate = (options: SimulationOptions): number => {
126
244
  output({ kind: "message", code, isError, message: text, toolMessage: toolText });
127
245
  const printSummary = () => output({ kind: "summary", statistics: { ...statistics } });
128
246
  const nodes = new WeakMap<(Value | undefined)[], TraceNode>();
129
- const initActions = getInitActions(config, environment, specification.instanceActions);
130
- const nextActions = getNextActions(config, environment, specification.instanceActions);
247
+ const description = prepared.getDescription();
248
+ const initActions = description.inits;
249
+ const nextActions = description.actions;
131
250
  let traceCount = 0;
132
251
  let currentTrace = 0;
133
252
  runtime.getLevel = (state) => nodes.get(state)?.level ?? 0;
@@ -150,7 +269,7 @@ export const simulate = (options: SimulationOptions): number => {
150
269
  return createRecord([
151
270
  ["mode", options.isGenerating ? "generate" : "simulate"],
152
271
  ["depth", traceDepth === INFINITE_DEPTH ? -1 : traceDepth],
153
- ["traces", Number(BigInt.asIntN(32, options.traceCount ?? (1n << 63n) - 1n))],
272
+ ["traces", Number(BigInt.asIntN(32, traceLimit))],
154
273
  ["deadlock", config.checkDeadlock],
155
274
  ["seed", String(seed)],
156
275
  ["aril", String(options.aril)],
@@ -227,19 +346,6 @@ export const simulate = (options: SimulationOptions): number => {
227
346
  nodes.set(state, node);
228
347
  return node;
229
348
  };
230
- const getTrace = (last: TraceNode) => {
231
- const trace: TraceNode[] = [];
232
- for (let node: TraceNode | undefined = last; node; node = node.predecessor) {
233
- const predecessor = node.predecessor;
234
- if (predecessor && isSameState(node.state, predecessor.state)) continue;
235
- trace.unshift(node);
236
- }
237
- trace.forEach((node, index) => {
238
- node.predecessor = trace[index - 1];
239
- node.level = index + 1;
240
- });
241
- return trace;
242
- };
243
349
  const toRecord = (state: (Value | undefined)[]) =>
244
350
  search.toRecord(state.map((value) => value ?? createModelValue("null")));
245
351
  const toTraceSteps = (trace: TraceNode[]): TraceStep[] =>
@@ -253,7 +359,7 @@ export const simulate = (options: SimulationOptions): number => {
253
359
  config.alias,
254
360
  node.state,
255
361
  (trace[index + 1] ?? node).state,
256
- isTool,
362
+ options.isTool ?? false,
257
363
  ),
258
364
  }));
259
365
  const getCounterExample = (trace: TraceNode[]) =>
@@ -368,60 +474,6 @@ export const simulate = (options: SimulationOptions): number => {
368
474
  false,
369
475
  );
370
476
 
371
- const findTemporalViolation = (last: TraceNode): Violation | undefined => {
372
- if (temporalProperties.length === 0) return undefined;
373
- const trace = getTrace(last);
374
- const fingerprints = trace.map((node) => runtime.getFingerprint(node.state));
375
- const indices = new Map<bigint, number>();
376
- const states: Value[][] = [];
377
- const successors: number[][] = [];
378
- fingerprints.forEach((fingerprint, position) => {
379
- if (!indices.has(fingerprint)) {
380
- indices.set(fingerprint, states.length);
381
- states.push(trace[position].state);
382
- successors.push([]);
383
- }
384
- if (position === 0) return;
385
- const source = indices.get(fingerprints[position - 1]) ?? 0;
386
- const target = indices.get(fingerprint) ?? 0;
387
- if (source !== target && !successors[source].includes(target)) {
388
- successors[source].push(target);
389
- }
390
- });
391
- const checker = createTemporalChecker(successors, states);
392
- if (!checker) return undefined;
393
- checker.addInitialState(0, states[0]);
394
- states.forEach((state, index) =>
395
- checker.addState(
396
- index,
397
- state,
398
- successors[index].map((successor) => ({ index: successor, state: states[successor] })),
399
- ),
400
- );
401
- const lasso = checker.findViolation();
402
- if (!lasso) return undefined;
403
- const getLength = (path: number[]) =>
404
- path.filter((index, position) => position === 0 || index !== path[position - 1]).length;
405
- const path = [...lasso.prefix, ...lasso.cycle];
406
- const length = getLength(path);
407
- const cyclePosition = getLength(path.slice(0, lasso.prefix.length + 1));
408
- const printed = trace.slice(0, length);
409
- const isStuttering =
410
- fingerprints[length - 1] === runtime.getFingerprint(states[path[lasso.prefix.length]]);
411
- const loopStart = isStuttering ? length - 1 : cyclePosition - 1;
412
- const properties = checker.getViolatedProperties(
413
- printed.map((node) => node.state),
414
- cyclePosition - 1,
415
- );
416
- const back = trace[length];
417
- return {
418
- name: properties[0],
419
- properties,
420
- trace: toTraceSteps(printed),
421
- loopStart,
422
- loopLabel: back && getActionLabel(back.action, options.version, back.level === 1),
423
- };
424
- };
425
477
  const toWorkerError = (code: number, text: string, node: TraceNode): WorkerError => ({
426
478
  code,
427
479
  message: text,
@@ -501,59 +553,32 @@ export const simulate = (options: SimulationOptions): number => {
501
553
  return { successors, error: failure };
502
554
  };
503
555
  let currentNode = initialStates[0];
504
- const qualities = nextActions.map(() => new Map<bigint | SpecAction, number>());
505
- const getQualityKey = (node: TraceNode) =>
506
- options.scheduler === "rlaction" ? node.action : runtime.getFingerprint(node.state);
507
- const getRewardOf = (node: TraceNode) =>
508
- search.getReward(node.predecessor?.state, node.state, RL_REWARD);
509
- const getNextActionIndex = (node: TraceNode) => {
510
- if (options.scheduler === "random") {
511
- return Math.floor(workerRandom.nextDouble() * nextActions.length);
512
- }
513
- const key = getQualityKey(node);
514
- qualities.forEach((quality) => {
515
- if (!quality.has(key)) quality.set(key, 0);
516
- });
517
- const weights = qualities.map((quality) => Math.exp(quality.get(key) ?? 0));
518
- const total = weights.reduce((sum, weight) => sum + weight, 0);
519
- const ranked = weights
520
- .map((weight, index) => ({ index, weight: weight / total }))
521
- .sort((left, right) => right.weight - left.weight);
522
- const threshold = workerRandom.nextDouble();
523
- let cumulativeWeight = 0;
524
- const chosen = ranked.find((item, position) => {
525
- cumulativeWeight = position === 0 ? item.weight : cumulativeWeight + item.weight;
526
- return cumulativeWeight >= threshold;
527
- });
528
- return (chosen ?? ranked[ranked.length - 1]).index;
529
- };
530
- const markDisabled = (index: number, node: TraceNode) => {
531
- if (options.scheduler === "random") return;
532
- // TLC's rlaction scheduler stores the reward, then overwrites it as the rl scheduler does.
533
- if (options.scheduler === "rlaction") getRewardOf(node);
534
- qualities[index].set(getQualityKey(node), -Number.MAX_VALUE);
535
- };
536
- const learnTrace = (last: TraceNode) => {
537
- for (let node = last; node.predecessor; node = node.predecessor) {
538
- const key = getQualityKey(node);
539
- const maxQuality = qualities.reduce(
540
- (max, quality) => Math.max(max, quality.get(key) ?? -Number.MAX_VALUE),
541
- -Number.MAX_VALUE,
542
- );
543
- const quality = qualities[nextActions.indexOf(node.action)];
544
- const predecessorKey = getQualityKey(node.predecessor);
545
- quality.set(
546
- predecessorKey,
547
- (1 - RL_ALPHA) * (quality.get(predecessorKey) ?? 0) +
548
- RL_ALPHA * (getRewardOf(node) + RL_GAMMA * maxQuality),
549
- );
550
- }
556
+ const scheduler = createScheduler(
557
+ options.scheduler,
558
+ nextActions,
559
+ workerRandom,
560
+ runtime.getFingerprint,
561
+ search.getReward,
562
+ );
563
+ const getTemporalViolation = (last: TraceNode): Violation | undefined => {
564
+ if (temporalProperties.length === 0) return undefined;
565
+ const trace = getTrace(last);
566
+ const found = findTemporalViolation(trace, runtime.getFingerprint, createTemporalChecker);
567
+ if (!found) return undefined;
568
+ const back = trace[found.length];
569
+ return {
570
+ name: found.properties[0],
571
+ properties: found.properties,
572
+ trace: toTraceSteps(trace.slice(0, found.length)),
573
+ loopStart: found.loopStart,
574
+ loopLabel: back && getActionLabel(back.action, options.version, back.level === 1),
575
+ };
551
576
  };
552
577
  const simulateTrace = (): WorkerError | "stopped" | undefined => {
553
578
  currentNode = initialStates[Math.floor(workerRandom.nextDouble() * initialStates.length)];
554
579
  for (let depth = 0; depth < traceDepth; depth++) {
555
580
  if (runtime.isStopped) return "stopped";
556
- let actionIndex = getNextActionIndex(currentNode);
581
+ let actionIndex = scheduler.getNextActionIndex(currentNode);
557
582
  const prime = nextPrime(workerRandom);
558
583
  let successors: TraceNode[] = [];
559
584
  for (let attempt = 0; attempt < nextActions.length; attempt++) {
@@ -561,7 +586,7 @@ export const simulate = (options: SimulationOptions): number => {
561
586
  if (result.error) return result.error;
562
587
  successors = result.successors;
563
588
  if (successors.length > 0) break;
564
- markDisabled(actionIndex, currentNode);
589
+ scheduler.markDisabled(actionIndex, currentNode);
565
590
  actionIndex = (actionIndex + prime) % nextActions.length;
566
591
  }
567
592
  if (successors.length === 0) {
@@ -574,7 +599,7 @@ export const simulate = (options: SimulationOptions): number => {
574
599
  currentNode.deferred?.(currentNode.state);
575
600
  }
576
601
  if (runtime.isStopped) return "stopped";
577
- const violation = findTemporalViolation(currentNode);
602
+ const violation = getTemporalViolation(currentNode);
578
603
  if (violation) {
579
604
  return {
580
605
  ...toWorkerError(MESSAGE_CODE.temporalPropertyViolated, "", currentNode),
@@ -586,7 +611,7 @@ export const simulate = (options: SimulationOptions): number => {
586
611
  const delta = length - statistics.levelMean;
587
612
  statistics.levelMean += Math.trunc(delta / Math.max(statistics.traces, 1));
588
613
  statistics.levelM2 += delta * (length - statistics.levelMean);
589
- if (options.scheduler === "rl") learnTrace(currentNode);
614
+ if (options.scheduler === "rl") scheduler.learnTrace(currentNode);
590
615
  return undefined;
591
616
  };
592
617
  const toException = (error: unknown, node: TraceNode): WorkerError => {
@@ -617,7 +642,6 @@ export const simulate = (options: SimulationOptions): number => {
617
642
  runtime.getRandom = () => enumerableRandom;
618
643
  const errors: WorkerError[] = [];
619
644
  const isContinued = options.isContinued ?? false;
620
- const traceLimit = options.traceCount ?? (1n << 63n) - 1n;
621
645
  while (true) {
622
646
  statistics.traces++;
623
647
  currentTrace = statistics.traces;