tla-ts 0.0.10-dev.1ebc153bd → 0.0.10-dev.22f7435d3

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 (108) hide show
  1. package/dist/deciders.cjs +31 -31
  2. package/dist/deciders.js +30 -30
  3. package/dist/index.cjs +1 -1
  4. package/dist/index.d.cts +6 -2
  5. package/dist/index.d.ts +6 -2
  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 +68 -68
  10. package/dist/prove.js +61 -61
  11. package/dist/run.cjs +42 -42
  12. package/dist/run.js +44 -44
  13. package/dist/transfer.cjs +38 -38
  14. package/dist/transfer.js +29 -29
  15. package/dist/worker.cjs +7 -7
  16. package/dist/worker.js +7 -7
  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 +9 -6
  21. package/src/check-trace.ts +116 -64
  22. package/src/check.ts +343 -166
  23. package/src/cli/tlc-output.ts +1 -0
  24. package/src/cli/tlc.ts +3 -2
  25. package/src/codegen.ts +23 -8
  26. package/src/dependencies.ts +5 -4
  27. package/src/dfid.ts +13 -8
  28. package/src/environment.ts +1 -0
  29. package/src/evaluate.ts +58 -23
  30. package/src/exit-codes.ts +27 -13
  31. package/src/java-hash.ts +14 -0
  32. package/src/liveness-checker.ts +131 -81
  33. package/src/liveness.ts +48 -10
  34. package/src/parser.ts +6 -1
  35. package/src/prover/smt/solver/arith-rewriter.ts +11 -3
  36. package/src/prover/smt/solver/array-rewriter.ts +12 -2
  37. package/src/prover/smt/solver/asserted-formulas.ts +109 -63
  38. package/src/prover/smt/solver/ast.ts +5 -3
  39. package/src/prover/smt/solver/auf-solver.ts +23 -12
  40. package/src/prover/smt/solver/bit-blast-tactic.ts +26 -0
  41. package/src/prover/smt/solver/bound-simplifier.ts +10 -11
  42. package/src/prover/smt/solver/card2bv.ts +34 -15
  43. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +39 -23
  44. package/src/prover/smt/solver/context.ts +44 -11
  45. package/src/prover/smt/solver/dependent-expr-state.ts +19 -13
  46. package/src/prover/smt/solver/dt2bv-tactic.ts +36 -20
  47. package/src/prover/smt/solver/elim-bounds.ts +89 -0
  48. package/src/prover/smt/solver/elim-uncnstr.ts +1 -1
  49. package/src/prover/smt/solver/fd-solver.ts +146 -39
  50. package/src/prover/smt/solver/internalizer.ts +1 -1
  51. package/src/prover/smt/solver/lp/lp-settings.ts +4 -0
  52. package/src/prover/smt/solver/maxcore.ts +2 -1
  53. package/src/prover/smt/solver/maxsmt-base.ts +1 -0
  54. package/src/prover/smt/solver/model-checker.ts +1 -1
  55. package/src/prover/smt/solver/model-evaluator.ts +2 -0
  56. package/src/prover/smt/solver/model-generator.ts +82 -42
  57. package/src/prover/smt/solver/muz/dl-context.ts +12 -40
  58. package/src/prover/smt/solver/muz/dl-mk-coi-filter.ts +1 -1
  59. package/src/prover/smt/solver/muz/dl-rule.ts +6 -7
  60. package/src/prover/smt/solver/muz/hnf.ts +2 -2
  61. package/src/prover/smt/solver/muz/horn-tactic.ts +14 -1
  62. package/src/prover/smt/solver/muz/rule-properties.ts +22 -0
  63. package/src/prover/smt/solver/muz/spacer-prop-solver.ts +1 -1
  64. package/src/prover/smt/solver/opt-context.ts +12 -4
  65. package/src/prover/smt/solver/opt-pareto.ts +19 -0
  66. package/src/prover/smt/solver/opt-solver.ts +4 -3
  67. package/src/prover/smt/solver/parallel-tactic.ts +1 -1
  68. package/src/prover/smt/solver/poly-rewriter.ts +1 -0
  69. package/src/prover/smt/solver/proto-model.ts +4 -2
  70. package/src/prover/smt/solver/push-app-ite.ts +37 -0
  71. package/src/prover/smt/solver/qsat.ts +23 -8
  72. package/src/prover/smt/solver/rewriter-tpl.ts +7 -6
  73. package/src/prover/smt/solver/rewriter.ts +31 -25
  74. package/src/prover/smt/solver/sat/goal2sat.ts +0 -1
  75. package/src/prover/smt/solver/sat/inc-sat-solver.ts +56 -28
  76. package/src/prover/smt/solver/sat/sat-tactic.ts +13 -4
  77. package/src/prover/smt/solver/sat/sat2goal.ts +10 -7
  78. package/src/prover/smt/solver/smt-consequences.ts +1 -1
  79. package/src/prover/smt/solver/smt-kernel.ts +39 -4
  80. package/src/prover/smt/solver/smt-setup.ts +28 -4
  81. package/src/prover/smt/solver/smtlib-parser.ts +31 -4
  82. package/src/prover/smt/solver/smtlib-script.ts +219 -82
  83. package/src/prover/smt/solver/solve-eqs.ts +24 -17
  84. package/src/prover/smt/solver/solver.ts +18 -3
  85. package/src/prover/smt/solver/tactic.ts +132 -78
  86. package/src/prover/smt/solver/theory-bv.ts +11 -1
  87. package/src/prover/smt/solver/theory-fpa.ts +1 -1
  88. package/src/prover/smt/solver/theory-lra-final-check.ts +1 -0
  89. package/src/prover/smt/solver/theory-lra-internalize.ts +1 -0
  90. package/src/prover/smt/solver/theory-lra-propagate.ts +7 -1
  91. package/src/prover/smt/solver/theory-lra.ts +1 -0
  92. package/src/prover/smt/solver/tseitin-cnf.ts +1 -0
  93. package/src/resolve.ts +446 -167
  94. package/src/runtime.ts +4 -0
  95. package/src/search.ts +161 -92
  96. package/src/simulate.ts +165 -102
  97. package/src/spec-description.ts +3 -4
  98. package/src/standard-modules.ts +56 -22
  99. package/src/subexpressions.ts +168 -49
  100. package/src/successors.ts +6 -3
  101. package/src/symmetry.ts +1 -0
  102. package/src/tlc/random.ts +2 -1
  103. package/src/tlc/replay.ts +22 -14
  104. package/src/tlc/tlc-operators.ts +7 -7
  105. package/src/tlc/tlcext-operators.ts +26 -10
  106. package/src/tlc/trace-spec.ts +6 -20
  107. package/src/typed-tier.ts +9 -4
  108. package/src/values.ts +95 -57
package/src/simulate.ts CHANGED
@@ -10,8 +10,10 @@ import {
10
10
  UNEXPECTED_EVAL_EXCEPTION,
11
11
  UNEXPECTED_EXCEPTION,
12
12
  } from "./errors";
13
- import { EXIT_STATUS, getMessageExitStatus, withLivenessExitCode } from "./exit-codes";
14
- import { createLivenessChecker, type LivenessChecker } from "./liveness-checker";
13
+ import type { State } from "./evaluate";
14
+ import { EXIT_STATUS, getMessageExitStatus, withLivenessChecksExitCode } from "./exit-codes";
15
+ import { getHashMapOrder } from "./java-hash";
16
+ import { createLivenessChecks, type LivenessChecks, type SearchGraph } from "./liveness-checker";
15
17
  import { getIncompleteSuccessorMessage, prepareSearch, reportAssumptionViolation } from "./search";
16
18
  import { getActionLabel, toActionValue, type SpecAction } from "./spec-description";
17
19
  import { forEachInitialState, forEachSuccessor } from "./successors";
@@ -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;
96
106
 
97
- const getTrace = (last: TraceNode) => {
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
+ };
118
+
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,19 +130,22 @@ 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,
114
- createChecker: (successors: number[][], states: Value[][]) => LivenessChecker | undefined,
137
+ checks: LivenessChecks,
115
138
  ) => {
116
139
  const fingerprints = trace.map((node) => getFingerprint(node.state));
117
140
  const indices = new Map<bigint, number>();
118
141
  const states: Value[][] = [];
119
142
  const successors: number[][] = [];
143
+ const stateFingerprints: number[] = [];
120
144
  fingerprints.forEach((fingerprint, position) => {
121
145
  if (!indices.has(fingerprint)) {
122
146
  indices.set(fingerprint, states.length);
123
147
  states.push(trace[position].state);
148
+ stateFingerprints.push(Number(BigInt.asIntN(32, fingerprint)));
124
149
  successors.push([]);
125
150
  }
126
151
  if (position === 0) return;
@@ -130,33 +155,38 @@ const findTemporalViolation = (
130
155
  successors[source].push(target);
131
156
  }
132
157
  });
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
- ),
158
+ const stateSuccessors = successors.map((targets) =>
159
+ targets.map((target) => ({ index: target, state: states[target] })),
142
160
  );
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
- ),
161
+ const search: SearchGraph<Value[]> = {
162
+ getFingerprint: (successor) => stateFingerprints[successor.index],
163
+ forEachActionSuccessors: (index, _state, onSuccessors) => onSuccessors(stateSuccessors[index]),
159
164
  };
165
+ // TLC's LiveCheck1 checks the behavior against one solution after another, up to the first it violates.
166
+ for (let position = 0; position < checks.solutions.length; position++) {
167
+ const checker = checks.createChecker(search, [checks.solutions[position]]);
168
+ checker.addInitialState(0, states[0]);
169
+ states.forEach((state, index) => checker.addState(index, state, stateSuccessors[index]));
170
+ const lasso = checker.findViolation();
171
+ if (!lasso) continue;
172
+ const getLength = (path: number[]) =>
173
+ path.filter((index, position) => position === 0 || index !== path[position - 1]).length;
174
+ const path = [...lasso.prefix, ...lasso.cycle];
175
+ const length = getLength(path);
176
+ const cyclePosition = getLength(path.slice(0, lasso.prefix.length + 1));
177
+ const isStuttering =
178
+ fingerprints[length - 1] === getFingerprint(states[path[lasso.prefix.length]]);
179
+ return {
180
+ length,
181
+ isStuttering,
182
+ loopStart: isStuttering ? length - 1 : cyclePosition - 1,
183
+ properties: checker.getViolatedProperties(
184
+ trace.slice(0, length).map((node) => node.state),
185
+ cyclePosition - 1,
186
+ ),
187
+ };
188
+ }
189
+ return undefined;
160
190
  };
161
191
 
162
192
  const createScheduler = (
@@ -252,10 +282,6 @@ export const simulate = (options: SimulationOptions): number => {
252
282
  let evaluatedAction: SpecAction | undefined;
253
283
  runtime.getSuccessorAction = () => evaluatedAction;
254
284
  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
285
  runtime.getSimulationValue = (key, state) => {
260
286
  const node = state && nodes.get(state);
261
287
  switch (key) {
@@ -268,7 +294,7 @@ export const simulate = (options: SimulationOptions): number => {
268
294
  case "action":
269
295
  return node && toActionValue(node.action);
270
296
  case "config":
271
- return createRecord([
297
+ return createTlcRecord([
272
298
  ["mode", options.isGenerating ? "generate" : "simulate"],
273
299
  ["depth", traceDepth === INFINITE_DEPTH ? -1 : traceDepth],
274
300
  ["traces", Number(BigInt.asIntN(32, traceLimit))],
@@ -284,14 +310,19 @@ export const simulate = (options: SimulationOptions): number => {
284
310
  for (let step = node; step && step.level > 1; step = step.predecessor) {
285
311
  actions.set(step.action.name, (actions.get(step.action.name) ?? 0) + 1);
286
312
  }
287
- return createRecord([
313
+ // TLC's SimulationWorker counts the actions of a behavior in a HashMap.
314
+ const counts = getHashMapOrder([...actions.keys()]).map((name): [string, Value] => [
315
+ name,
316
+ actions.get(name) ?? 0,
317
+ ]);
318
+ return createTlcRecord([
288
319
  ["traces", statistics.traces],
289
320
  ["duration", Math.floor((Date.now() - runtime.startedAt) / 1000)],
290
321
  ["generated", statistics.generatedStates],
291
322
  [
292
323
  "behavior",
293
- createRecord([
294
- ["actions", createRecord([...actions])],
324
+ createTlcRecord([
325
+ ["actions", createTlcRecord(counts)],
295
326
  ["id", currentTrace],
296
327
  ]),
297
328
  ],
@@ -311,6 +342,10 @@ export const simulate = (options: SimulationOptions): number => {
311
342
  if (!search) {
312
343
  throw new TlaUnsupportedError("tla-ts can't simulate a specification without variables");
313
344
  }
345
+ runtime.getBehavior = (state) => {
346
+ const node = nodes.get(state);
347
+ return node ? getTrace(node, search.getTlcOrder()).map((step) => step.state) : [state];
348
+ };
314
349
  const reportPostcondition = (isAfterViolation: boolean) => {
315
350
  const postcondition = search.findPostconditionViolation(isAfterViolation);
316
351
  if (!postcondition) return undefined;
@@ -322,19 +357,12 @@ export const simulate = (options: SimulationOptions): number => {
322
357
  );
323
358
  return postcondition;
324
359
  };
325
- const temporalProperties = search.properties.liveness;
326
- const createTemporalChecker = (successors: number[][], states: Value[][]) =>
327
- withLivenessExitCode(() =>
328
- withUnexpectedException(() =>
329
- createLivenessChecker(temporalProperties, search.spec.temporals, environment, {
330
- getFingerprint: (successor) =>
331
- Number(BigInt.asIntN(32, runtime.getFingerprint(successor.state))),
332
- getSuccessors: (index) =>
333
- successors[index].map((successor) => ({ index: successor, state: states[successor] })),
334
- }),
335
- ),
336
- );
337
- const branches = createTemporalChecker([], [])?.branches;
360
+ const livenessChecks = withLivenessChecksExitCode(() =>
361
+ withUnexpectedException(() =>
362
+ createLivenessChecks(search.properties.liveness, search.spec.temporals, environment),
363
+ ),
364
+ );
365
+ const branches = livenessChecks?.solutions.length;
338
366
  if (branches) options.onProgress?.({ kind: "liveness-prepared", branches });
339
367
  const assumptionStatus = reportAssumptionViolation(
340
368
  specification.assumptions,
@@ -351,25 +379,35 @@ export const simulate = (options: SimulationOptions): number => {
351
379
  const toRecord = (state: (Value | undefined)[]) =>
352
380
  search.toRecord(state.map((value) => value ?? createModelValue("null")));
353
381
  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[]) =>
382
+ trace.map((node, index) => {
383
+ const successor = trace[index + 1] ?? node;
384
+ return {
385
+ action: node.action.name,
386
+ label: getActionLabel(node.action, options.version, node.level === 1),
387
+ state:
388
+ config.alias === undefined
389
+ ? toRecord(node.state)
390
+ : search.evaluateAlias(
391
+ config.alias,
392
+ node.incomplete ?? node.state,
393
+ successor.incomplete ?? successor.state,
394
+ options.isTool ?? false,
395
+ ),
396
+ };
397
+ });
398
+ const getCounterExample = (
399
+ trace: TraceNode[],
400
+ steps = toTraceSteps(trace),
401
+ loop?: CounterExampleLoop,
402
+ ) =>
368
403
  createCounterExample(
369
- trace.map((node) => search.toRecord(node.state)),
404
+ steps.map((step) => step.state),
370
405
  trace.slice(1).map((node) => toActionValue(node.action)),
371
- undefined,
406
+ loop,
372
407
  );
408
+ // TLC's Simulator binds CounterExample to an initial state that violates an invariant, not to its alias.
409
+ const getInitialCounterExample = (node: TraceNode) =>
410
+ createCounterExample([toRecord(node.state)], [], undefined);
373
411
 
374
412
  const initialStates: TraceNode[] = [];
375
413
  const isComplete = (state: (Value | undefined)[]): state is Value[] =>
@@ -414,6 +452,7 @@ export const simulate = (options: SimulationOptions): number => {
414
452
  undefined,
415
453
  false,
416
454
  );
455
+ const generatedNodes: TraceNode[] = [];
417
456
  for (const state of generated) {
418
457
  if (!isComplete(state)) {
419
458
  reportMessage(
@@ -431,22 +470,11 @@ export const simulate = (options: SimulationOptions): number => {
431
470
  MESSAGE_CODE.invariantViolatedInitial,
432
471
  `Invariant ${violated.name} is violated by the initial state:\n${formatState(alias)}`,
433
472
  );
434
- runtime.counterExample = getCounterExample([node]);
473
+ runtime.counterExample = getInitialCounterExample(node);
435
474
  reportPostcondition(true);
436
475
  return EXIT_STATUS.safetyViolation;
437
476
  }
438
- // Deviation from TLC: its simulator checks no implied init, tla-ts checks them after invariants.
439
- const predicate = search.findFailedInitialPredicate(state);
440
- if (predicate) {
441
- const alias = toTraceSteps([node])[0].state;
442
- reportMessage(
443
- MESSAGE_CODE.propertyViolatedInitial,
444
- `Property ${predicate.name} is violated by the initial state:\n${formatState(alias)}`,
445
- );
446
- runtime.counterExample = getCounterExample([node]);
447
- reportPostcondition(true);
448
- return EXIT_STATUS.livenessViolation;
449
- }
477
+ generatedNodes.push(node);
450
478
  if (search.satisfiesConstraints(state)) {
451
479
  search.trackStatePossible(state);
452
480
  initialStates.push(node);
@@ -469,12 +497,32 @@ export const simulate = (options: SimulationOptions): number => {
469
497
  );
470
498
  return EXIT_STATUS.error;
471
499
  }
500
+ // Deviation from TLC: its simulator checks no implied init, tla-ts checks them after TLC's own checks of the initial states.
501
+ for (const node of generatedNodes) {
502
+ try {
503
+ const predicate = search.findFailedInitialPredicate(node.state);
504
+ if (predicate) {
505
+ const alias = toTraceSteps([node])[0].state;
506
+ reportMessage(
507
+ MESSAGE_CODE.propertyViolatedInitial,
508
+ `Property ${predicate.name} is violated by the initial state:\n${formatState(alias)}`,
509
+ );
510
+ runtime.counterExample = getInitialCounterExample(node);
511
+ reportPostcondition(true);
512
+ return EXIT_STATUS.livenessViolation;
513
+ }
514
+ } catch (error) {
515
+ return reportInitialException(error, node.state);
516
+ }
517
+ }
472
518
  reportMessage(
473
519
  MESSAGE_CODE.initGenerated1,
474
520
  `Finished computing initial states: ${initialStates.length} distinct state generated at ${formatTlcDate(new Date())}.`,
475
521
  undefined,
476
522
  false,
477
523
  );
524
+ // TLC's Simulator deep-normalizes the initial states, which sorts their records.
525
+ initialStates.forEach((node) => node.state.forEach(markNormalized));
478
526
 
479
527
  const toWorkerError = (code: number, text: string, node: TraceNode): WorkerError => ({
480
528
  code,
@@ -545,6 +593,7 @@ export const simulate = (options: SimulationOptions): number => {
545
593
  action,
546
594
  current,
547
595
  );
596
+ node.incomplete = error.state;
548
597
  const text = getIncompleteSuccessorMessage(
549
598
  error.variables,
550
599
  action.name,
@@ -563,18 +612,34 @@ export const simulate = (options: SimulationOptions): number => {
563
612
  runtime.getFingerprint,
564
613
  search.getReward,
565
614
  );
566
- const getTemporalViolation = (last: TraceNode): Violation | undefined => {
567
- if (temporalProperties.length === 0) return undefined;
568
- const trace = getTrace(last);
569
- const found = findTemporalViolation(trace, runtime.getFingerprint, createTemporalChecker);
615
+ const getTemporalViolation = (last: TraceNode): WorkerError | undefined => {
616
+ if (!livenessChecks) return undefined;
617
+ const trace = getTrace(last, search.getTlcOrder());
618
+ // TLC's LiveCheck#checkTrace fingerprints each state, which sorts its records.
619
+ for (let position = 0; position < trace.length; position++) {
620
+ trace[position].state.forEach(markNormalized);
621
+ }
622
+ const found = findTemporalViolation(trace, runtime.getFingerprint, livenessChecks);
570
623
  if (!found) return undefined;
571
624
  const back = trace[found.length];
625
+ const lasso = trace.slice(0, found.length);
626
+ const steps = toTraceSteps(lasso);
627
+ const loopAction =
628
+ found.isStuttering || !back ? createActionRecord(undefined) : toActionValue(back.action);
572
629
  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),
630
+ ...toWorkerError(MESSAGE_CODE.temporalPropertyViolated, "", last),
631
+ isException: true,
632
+ violation: {
633
+ name: found.properties[0],
634
+ properties: found.properties,
635
+ trace: steps,
636
+ loopStart: found.loopStart,
637
+ loopLabel: back && getActionLabel(back.action, options.version, back.level === 1),
638
+ },
639
+ counterExample: getCounterExample(lasso, steps, {
640
+ start: found.loopStart,
641
+ action: loopAction,
642
+ }),
578
643
  };
579
644
  };
580
645
  const simulateTrace = (): WorkerError | "stopped" | undefined => {
@@ -586,6 +651,7 @@ export const simulate = (options: SimulationOptions): number => {
586
651
  let successors: TraceNode[] = [];
587
652
  for (let attempt = 0; attempt < nextActions.length; attempt++) {
588
653
  const result = getSuccessors(currentNode, nextActions[actionIndex]);
654
+ // Deviation from TLC: TLCSet("exit") interrupts TLC's SimulationWorker, whose BlockingQueue#put then drops a violation found in the same step.
589
655
  if (result.error) return result.error;
590
656
  successors = result.successors;
591
657
  if (successors.length > 0) break;
@@ -603,13 +669,7 @@ export const simulate = (options: SimulationOptions): number => {
603
669
  }
604
670
  if (runtime.isStopped) return "stopped";
605
671
  const violation = getTemporalViolation(currentNode);
606
- if (violation) {
607
- return {
608
- ...toWorkerError(MESSAGE_CODE.temporalPropertyViolated, "", currentNode),
609
- isException: true,
610
- violation,
611
- };
612
- }
672
+ if (violation) return violation;
613
673
  const length = Math.min(traceDepth, currentNode.level);
614
674
  const delta = length - statistics.levelMean;
615
675
  statistics.levelMean += Math.trunc(delta / Math.max(statistics.traces, 1));
@@ -684,14 +744,17 @@ export const simulate = (options: SimulationOptions): number => {
684
744
  reportMessage(error.code, error.message, error.toolMessage);
685
745
  output({
686
746
  kind: "behavior",
687
- trace: toTraceSteps(getTrace(error.node)),
747
+ trace: toTraceSteps(getTrace(error.node, search.getTlcOrder())),
688
748
  isLastStateOnly: traceDepth === INFINITE_DEPTH,
689
749
  });
690
750
  if (error.isSummarized) printSummary();
691
751
  });
692
752
  const last = reported[reported.length - 1];
693
753
  const errorStatus = last ? getMessageExitStatus(last.code) : EXIT_STATUS.success;
694
- if (last) runtime.counterExample = getCounterExample(getTrace(last.node));
754
+ if (last) {
755
+ runtime.counterExample =
756
+ last.counterExample ?? getCounterExample(getTrace(last.node, search.getTlcOrder()));
757
+ }
695
758
  const postcondition = reportPostcondition(last !== undefined);
696
759
  const postconditionStatus = postcondition
697
760
  ? getMessageExitStatus(postcondition.code)
@@ -13,7 +13,6 @@ import { substitutionFrames, withSubstitutionFrames } from "./instances";
13
13
  import type { InstanceAction } from "./environment";
14
14
  import { formatRange, TlaError, TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
15
15
  import {
16
- bindDefinitions,
17
16
  bindOperatorArguments,
18
17
  describeNode,
19
18
  evaluate,
@@ -26,7 +25,7 @@ import {
26
25
  type Scope,
27
26
  } from "./evaluate";
28
27
  import { ACTION_LEVEL, CONSTANT_LEVEL, TEMPORAL_LEVEL, VARIABLE_LEVEL } from "./levels";
29
- import { getLevel } from "./liveness";
28
+ import { bindLetDefinitions, getLevel } from "./liveness";
30
29
  import { createRecord, createSet, createTuple, formatValue, type Value } from "./values";
31
30
  import { LITERAL_KINDS } from "./tlc/replay";
32
31
  import type { TlcVersion } from "./tlc/version";
@@ -176,7 +175,7 @@ const unwrapBinding = (
176
175
  if (expression.kind === "Let") {
177
176
  return {
178
177
  expression: expression.body,
179
- scope: bindDefinitions(expression.definitions, getConstantContext(environment, scope)),
178
+ scope: bindLetDefinitions(expression, scope, environment),
180
179
  };
181
180
  }
182
181
  const thunk = getThunk(expression, scope);
@@ -268,7 +267,7 @@ const getActions = (
268
267
  case "Let":
269
268
  return getActions(
270
269
  expression.body,
271
- bindDefinitions(expression.definitions, getConstantContext(environment, scope)),
270
+ bindLetDefinitions(expression, scope, environment),
272
271
  closure,
273
272
  environment,
274
273
  instanceActions,
@@ -18,6 +18,7 @@ import {
18
18
  overrideWithJava,
19
19
  } from "./builtins";
20
20
  import type { Builtin, BuiltinArgument, Context } from "./evaluate";
21
+ import { prettyPrint } from "./pretty-print";
21
22
  import type { CheckerRuntime } from "./runtime";
22
23
  import { createBagsOperators } from "./bags";
23
24
  import { createIoUtilsOperators, createJsonOperators, type FileSystem } from "./json";
@@ -40,6 +41,7 @@ import {
40
41
  formatValue,
41
42
  getCardinality,
42
43
  getDomain,
44
+ getFunctionClass,
43
45
  getSortedIntersection,
44
46
  someStreamedElement,
45
47
  isElementOf,
@@ -123,6 +125,43 @@ const combineReducible = (
123
125
  return createEnumeratedSet(union);
124
126
  };
125
127
 
128
+ const isIntervalInSortedSet = (interval: IntervalValue, set: SetValue) => {
129
+ const elements = set.elements;
130
+ let low = 0;
131
+ let high = elements.length;
132
+ while (low < high) {
133
+ const middle = (low + high) >> 1;
134
+ const probe = elements[middle];
135
+ if (typeof probe !== "number") return undefined;
136
+ if (probe < interval.low) low = middle + 1;
137
+ else high = middle;
138
+ }
139
+ for (let element = interval.low; element <= interval.high; element++, low++) {
140
+ if (low === elements.length) return false;
141
+ const probe = elements[low];
142
+ if (probe !== element) return typeof probe === "number" ? false : undefined;
143
+ }
144
+ return true;
145
+ };
146
+
147
+ const isIntervalSubset = (left: IntervalValue, right: Value) => {
148
+ const isWithin =
149
+ typeof right === "object" &&
150
+ right.kind === "Interval" &&
151
+ right.low <= left.low &&
152
+ right.high >= left.high;
153
+ if (isWithin) return true;
154
+ const isContained =
155
+ typeof right === "object" && right.kind === "Set"
156
+ ? isIntervalInSortedSet(left, right)
157
+ : undefined;
158
+ if (isContained !== undefined) return isContained;
159
+ for (let element = left.low; element <= left.high; element++) {
160
+ if (!isElementOf(element, right)) return false;
161
+ }
162
+ return true;
163
+ };
164
+
126
165
  const defineShortCircuit = (
127
166
  name: string,
128
167
  compute: (left: boolean, right: () => boolean) => boolean,
@@ -157,6 +196,7 @@ export const CORE_OPERATORS: Builtin[] = [
157
196
  (args) => !isElementOf(getValue(args, 0, "\\notin"), getValue(args, 1, "\\notin")),
158
197
  ),
159
198
  defineBinary("\\subseteq", (left, right) => {
199
+ if (typeof left === "object" && left.kind === "Interval") return isIntervalSubset(left, right);
160
200
  if (!isSetValue(left)) {
161
201
  throw new TlaEvaluationError(`\\subseteq expects a set but received ${formatValue(left)}`);
162
202
  }
@@ -167,18 +207,6 @@ export const CORE_OPERATORS: Builtin[] = [
167
207
  right.kind === "Subset" &&
168
208
  isEnumerable(left.base);
169
209
  if (isPowerSets) return isSubsetOf(toFiniteSet(left.base).elements, right.base);
170
- if (typeof left === "object" && left.kind === "Interval") {
171
- const isWithin =
172
- typeof right === "object" &&
173
- right.kind === "Interval" &&
174
- right.low <= left.low &&
175
- right.high >= left.high;
176
- if (isWithin) return true;
177
- for (let element = left.low; element <= left.high; element++) {
178
- if (!isElementOf(element, right)) return false;
179
- }
180
- return true;
181
- }
182
210
  return !someStreamedElement(left, (element) => !isElementOf(element, right));
183
211
  }),
184
212
  ...SET_OPERATORS.map((operator) =>
@@ -313,11 +341,10 @@ const createArithmeticOperators = (module: string) => {
313
341
  }
314
342
  return ((left % right) + right) % right;
315
343
  }),
316
- defineOperator("..", 2, (args) => {
317
- const low = getValue(args, 0, "..");
344
+ defineBinary("..", (low, high) => {
318
345
  // TLC's MethodHandle casts the last argument first.
319
- const high = getJavaInteger(getValue(args, 1, ".."), dotDotSignature);
320
- return { kind: "Interval", low: getJavaInteger(low, dotDotSignature), high };
346
+ const highNumber = getJavaInteger(high, dotDotSignature);
347
+ return { kind: "Interval", low: getJavaInteger(low, dotDotSignature), high: highNumber };
321
348
  }),
322
349
  ];
323
350
  };
@@ -376,7 +403,7 @@ const INTEGERS_OPERATORS = [
376
403
  const getSequenceArgument = (args: BuiltinArgument[], index: number, message: string) => {
377
404
  const value = getValue(args, index, message);
378
405
  const elements = getSequenceElements(value);
379
- if (!elements) throw new TlaModuleError(`${message}\n${formatValue(value)}`);
406
+ if (!elements) throw new TlaModuleError(`${message}\n${prettyPrint(formatValue(value))}`);
380
407
  return elements;
381
408
  };
382
409
 
@@ -425,12 +452,19 @@ const createSequencesOperators = (version: TlcVersion) =>
425
452
  const left = getSequenceOrString(args, 0, getEvaluatingMessage("s \\o t", "sequence"));
426
453
  if (typeof left !== "string") {
427
454
  const right = getSequenceArgument(args, 1, getEvaluatingMessage("t \\o s", "sequence"));
455
+ const kept =
456
+ left.length === 0
457
+ ? getValue(args, 1, "\\o")
458
+ : right.length === 0
459
+ ? getValue(args, 0, "\\o")
460
+ : undefined;
461
+ if (kept !== undefined && getFunctionClass(kept) === "tuple") return kept;
428
462
  return createTuple([...left, ...right]);
429
463
  }
430
464
  const right = getValue(args, 1, "\\o");
431
465
  if (typeof right !== "string") {
432
466
  throw new TlaModuleError(
433
- `${getEvaluatingMessage("t \\o s", "string")}\n${formatValue(right)}`,
467
+ `${getEvaluatingMessage("t \\o s", "string")}\n${prettyPrint(formatValue(right))}`,
434
468
  );
435
469
  }
436
470
  return rankString(left + right);
@@ -470,7 +504,7 @@ const createSequencesOperators = (version: TlcVersion) =>
470
504
  : undefined;
471
505
  if (outOfDomain) {
472
506
  throw new TlaModuleError(
473
- `The ${outOfDomain.position} argument of SubSeq must be in the domain of its first argument:\n${formatValue(getValue(args, 0, "SubSeq"))}\n, but instead it is\n${outOfDomain.value}`,
507
+ `The ${outOfDomain.position} argument of SubSeq must be in the domain of its first argument:\n${prettyPrint(formatValue(getValue(args, 0, "SubSeq")))}\n, but instead it is\n${outOfDomain.value}`,
474
508
  );
475
509
  }
476
510
  return sliceSequence(sequence, start - 1, end);
@@ -503,7 +537,7 @@ const createFiniteSetsOperators = (version: TlcVersion) =>
503
537
  (typeof set === "object" && (set.kind === "InfiniteSet" || set.kind === "SequenceSet"))
504
538
  ) {
505
539
  throw new TlaModuleError(
506
- `Attempted to compute cardinality of the value\n${formatValue(set)}`,
540
+ `Attempted to compute cardinality of the value\n${prettyPrint(formatValue(set))}`,
507
541
  );
508
542
  }
509
543
  return getCardinality(set, version);
@@ -516,7 +550,7 @@ const TRANSITIVE_CLOSURE_OPERATORS = [
516
550
  const relation = getValue(args, 0, "Warshall");
517
551
  if (!isSetValue(relation) || isOverriddenSet(relation)) {
518
552
  throw new TlaModuleError(
519
- `Applying TransitiveClosure to the following value,\nwhich is not an enumerable set:\n${formatValue(relation)}`,
553
+ `Applying TransitiveClosure to the following value,\nwhich is not an enumerable set:\n${prettyPrint(formatValue(relation))}`,
520
554
  );
521
555
  }
522
556
  // TLC sizes the relation, which normalizes it.
@@ -536,7 +570,7 @@ const TRANSITIVE_CLOSURE_OPERATORS = [
536
570
  const ends = getSequenceElements(edge);
537
571
  if (ends?.length !== 2) {
538
572
  throw new TlaModuleError(
539
- `Attempted to apply TransitiveClosure to a set containing\nthe following value:\n${formatValue(edge)}`,
573
+ `Attempted to apply TransitiveClosure to a set containing\nthe following value:\n${prettyPrint(formatValue(edge))}`,
540
574
  );
541
575
  }
542
576
  return [getNodeIndex(ends[0]), getNodeIndex(ends[1])];