tla-ts 0.0.3-dev.6979965 → 0.0.3-dev.6a30eee

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/liveness.ts CHANGED
@@ -27,14 +27,10 @@ import {
27
27
  createPair,
28
28
  createUnary,
29
29
  getLiveLevel,
30
- getSolutions,
31
- isFulfilling,
32
30
  type LiveEnabled,
33
31
  type LiveExpression,
34
- type Solution,
35
- type Tableau,
36
32
  } from "./tableau";
37
- import { isSameValue, type Value } from "./values";
33
+ import type { Value } from "./values";
38
34
 
39
35
  export interface ScopedExpression {
40
36
  expression: Expression;
@@ -45,50 +41,6 @@ export interface TemporalProperty extends ScopedExpression {
45
41
  name: string;
46
42
  }
47
43
 
48
- export interface LiveSuccessor {
49
- index: number;
50
- state: Value[];
51
- }
52
-
53
- export interface Lasso {
54
- name: string;
55
- prefix: number[];
56
- cycle: number[];
57
- }
58
-
59
- interface SafetyViolation {
60
- name: string;
61
- path: number[];
62
- }
63
-
64
- export interface LivenessChecker {
65
- addInitialState: (index: number, state: Value[]) => void;
66
- addState: (
67
- index: number,
68
- state: Value[],
69
- successors: LiveSuccessor[],
70
- ) => SafetyViolation | undefined;
71
- findViolation: () => Lasso | undefined;
72
- }
73
-
74
- interface Check {
75
- solution: Solution;
76
- stateResults: Uint8Array[];
77
- actionResults: Uint8Array[];
78
- consistency: Uint8Array[];
79
- product: BehaviorGraph | undefined;
80
- productNodes: Map<number, number>;
81
- nodesByState: Map<number, number[]>;
82
- }
83
-
84
- interface BehaviorGraph {
85
- states: number[];
86
- tableauNodes: number[];
87
- edges: number[][];
88
- initial: number[];
89
- parents: number[];
90
- }
91
-
92
44
  const MAXIMUM_EXPANSION_DEPTH = 100;
93
45
 
94
46
  const TEMPORAL_OPERATORS = new Set(["~>", "-+->"]);
@@ -278,7 +230,7 @@ const createAngleAction = (action: Expression, subscript: Expression): Expressio
278
230
  location: action.location,
279
231
  });
280
232
 
281
- const toLiveExpression = (
233
+ export const toLiveExpression = (
282
234
  root: Expression,
283
235
  rootScope: Scope | undefined,
284
236
  environment: Environment,
@@ -464,7 +416,7 @@ const toLiveExpression = (
464
416
  return convert(root, rootScope);
465
417
  };
466
418
 
467
- const evaluateLive = (
419
+ export const evaluateLive = (
468
420
  expression: LiveExpression,
469
421
  state: Value[],
470
422
  next: Value[] | undefined,
@@ -512,7 +464,7 @@ const evaluateLive = (
512
464
  }
513
465
  };
514
466
 
515
- const evaluateOnLasso = (
467
+ export const evaluateOnLasso = (
516
468
  expression: LiveExpression,
517
469
  path: Value[][],
518
470
  cycleStart: number,
@@ -547,472 +499,3 @@ const evaluateOnLasso = (
547
499
  );
548
500
  }
549
501
  };
550
-
551
- const liveKeys = new WeakMap<LiveExpression, string>();
552
-
553
- const atomCount = { value: 0 };
554
-
555
- const getLiveKey = (expression: LiveExpression): string => {
556
- const cached = liveKeys.get(expression);
557
- if (cached !== undefined) return cached;
558
- const key =
559
- expression.kind === "Boolean"
560
- ? String(expression.value)
561
- : "body" in expression
562
- ? `${expression.kind}(${getLiveKey(expression.body)})`
563
- : "operands" in expression
564
- ? `${expression.kind}(${expression.operands.map(getLiveKey).join(",")})`
565
- : `${expression.kind}#${atomCount.value++}`;
566
- liveKeys.set(expression, key);
567
- return key;
568
- };
569
-
570
- const isSameState = (left: Value[], right: Value[]) =>
571
- left.every((value, position) => isSameValue(value, right[position]));
572
-
573
- const getStronglyConnectedComponents = (
574
- nodeCount: number,
575
- getSuccessors: (node: number) => number[],
576
- visit: (component: number[], successors: (node: number) => number[]) => boolean,
577
- ) => {
578
- const order = new Int32Array(nodeCount).fill(-1);
579
- const lowLink = new Int32Array(nodeCount);
580
- const onStack = new Uint8Array(nodeCount);
581
- const stack: number[] = [];
582
- const counter = { value: 0 };
583
- const successorCache = new Map<number, number[]>();
584
- const getCachedSuccessors = (node: number) => {
585
- const cached = successorCache.get(node);
586
- if (cached) return cached;
587
- const successors = getSuccessors(node);
588
- successorCache.set(node, successors);
589
- return successors;
590
- };
591
- for (let root = 0; root < nodeCount; root++) {
592
- if (order[root] !== -1) continue;
593
- const frames: { node: number; position: number }[] = [];
594
- const open = (node: number) => {
595
- order[node] = counter.value;
596
- lowLink[node] = counter.value++;
597
- stack.push(node);
598
- onStack[node] = 1;
599
- frames.push({ node, position: 0 });
600
- };
601
- open(root);
602
- while (frames.length > 0) {
603
- const frame = frames[frames.length - 1];
604
- const successors = getCachedSuccessors(frame.node);
605
- if (frame.position < successors.length) {
606
- const target = successors[frame.position++];
607
- if (order[target] === -1) open(target);
608
- else if (onStack[target])
609
- lowLink[frame.node] = Math.min(lowLink[frame.node], order[target]);
610
- continue;
611
- }
612
- frames.pop();
613
- const parent = frames[frames.length - 1];
614
- if (parent) lowLink[parent.node] = Math.min(lowLink[parent.node], lowLink[frame.node]);
615
- if (lowLink[frame.node] !== order[frame.node]) continue;
616
- const component: number[] = [];
617
- while (true) {
618
- const member = stack.pop();
619
- if (member === undefined) break;
620
- onStack[member] = 0;
621
- component.push(member);
622
- if (member === frame.node) break;
623
- }
624
- const isFound = visit(component, getCachedSuccessors);
625
- component.forEach((member) => successorCache.delete(member));
626
- if (isFound) return;
627
- }
628
- }
629
- };
630
-
631
- const getShortestPath = (
632
- from: number,
633
- to: number,
634
- members: Set<number>,
635
- getSuccessors: (node: number) => number[],
636
- ) => {
637
- if (from === to) return [from];
638
- const parents = new Map<number, number>([[from, -1]]);
639
- const queue = [from];
640
- for (let position = 0; position < queue.length; position++) {
641
- for (const target of getSuccessors(queue[position])) {
642
- if (parents.has(target) || !members.has(target)) continue;
643
- parents.set(target, queue[position]);
644
- if (target === to) {
645
- const path: number[] = [];
646
- for (let node = to; node !== -1; node = parents.get(node) ?? -1) path.push(node);
647
- return path.reverse();
648
- }
649
- queue.push(target);
650
- }
651
- }
652
- return [from];
653
- };
654
-
655
- const removeRepeats = (path: number[]) =>
656
- path.filter((node, position) => position === 0 || path[position - 1] !== node);
657
-
658
- export const createLivenessChecker = (
659
- properties: TemporalProperty[],
660
- temporals: ScopedExpression[],
661
- environment: Environment,
662
- ): LivenessChecker | undefined => {
663
- if (properties.length === 0) return undefined;
664
- const fairness = temporals.map((item) =>
665
- toLiveExpression(item.expression, item.scope, environment),
666
- );
667
- const negations = properties.map((property) =>
668
- createUnary("Not", toLiveExpression(property.expression, property.scope, environment)),
669
- );
670
- const violation = negations.length === 1 ? negations[0] : createJunction("Or", negations);
671
- const formula =
672
- fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
673
- const solutions = getSolutions(formula);
674
- if (solutions.length === 0) {
675
- throw new TlaEvaluationError("Temporal formula is a tautology (its negation is unsatisfiable)");
676
- }
677
- const checks = solutions.map((solution): Check => ({
678
- solution,
679
- stateResults: [],
680
- actionResults: [],
681
- consistency: [],
682
- product: solution.tableau && {
683
- states: [],
684
- tableauNodes: [],
685
- edges: [],
686
- initial: [],
687
- parents: [],
688
- },
689
- productNodes: new Map(),
690
- nodesByState: new Map(),
691
- }));
692
- const actionKeys = new Map<string, number>();
693
- const actionIds = checks.map((check) =>
694
- check.solution.actionChecks.map((predicate) => {
695
- const key = getLiveKey(predicate);
696
- const known = actionKeys.get(key);
697
- if (known !== undefined) return known;
698
- actionKeys.set(key, actionKeys.size);
699
- return actionKeys.size - 1;
700
- }),
701
- );
702
- const states: Value[][] = [];
703
- const targets: number[][] = [];
704
- const edgeStates: Value[][][] = [];
705
- const initial: number[] = [];
706
-
707
- const isConsistent = (
708
- predicates: LiveExpression[],
709
- state: Value[],
710
- cache: Map<LiveExpression, boolean>,
711
- ) =>
712
- predicates.every((predicate) => evaluateLive(predicate, state, undefined, environment, cache));
713
-
714
- const getProductNode = (
715
- check: Check,
716
- product: BehaviorGraph,
717
- state: number,
718
- tableauNode: number,
719
- parent: number,
720
- ) => {
721
- const key = state * (check.solution.tableau?.nodes.length ?? 1) + tableauNode;
722
- const existing = check.productNodes.get(key);
723
- if (existing !== undefined) return { node: existing, isNew: false };
724
- const node = product.states.length;
725
- check.productNodes.set(key, node);
726
- product.states.push(state);
727
- product.tableauNodes.push(tableauNode);
728
- product.edges.push([]);
729
- product.parents.push(parent);
730
- const siblings = check.nodesByState.get(state);
731
- if (siblings) siblings.push(node);
732
- else check.nodesByState.set(state, [node]);
733
- return { node, isNew: true };
734
- };
735
-
736
- const getAttribution = (path: number[], cycleStart: number) => {
737
- const lasso = path.map((state) => states[state]);
738
- return (
739
- properties.find(
740
- (_, position) =>
741
- !evaluateOnLasso(negations[position].body, lasso, cycleStart, 0, environment),
742
- ) ?? properties[0]
743
- ).name;
744
- };
745
-
746
- const expandProduct = (check: Check, product: BehaviorGraph, tableau: Tableau, state: number) => {
747
- const hasEmptyModel = check.solution.models.some(
748
- (model) =>
749
- model.eventuallyAlways.length === 0 &&
750
- model.infinitelyOftenStates.length === 0 &&
751
- model.infinitelyOftenActions.length === 0,
752
- );
753
- const nodeCount = tableau.nodes.length;
754
- const pending = (check.nodesByState.get(state) ?? []).map((node) => ({ node, isDone: false }));
755
- while (pending.length > 0) {
756
- const item = pending.pop();
757
- if (!item) break;
758
- const source = product.states[item.node];
759
- const successors = tableau.nodes[product.tableauNodes[item.node]].successors;
760
- const isAccepted =
761
- item.isDone &&
762
- hasEmptyModel &&
763
- successors.some((successor) => {
764
- const node = tableau.nodes[successor];
765
- return node.particle.length === 0 && node.successors.every((next) => next === successor);
766
- });
767
- if (isAccepted) {
768
- const path = removeRepeats(
769
- getPrefix(product, item.node).map((node) => product.states[node]),
770
- );
771
- return { name: getAttribution(path, path.length - 1), path };
772
- }
773
- const consistency = check.consistency[source];
774
- targets[source].forEach((target, edgeIndex) => {
775
- for (const successor of successors) {
776
- if (!consistency[edgeIndex * nodeCount + successor]) continue;
777
- const created = getProductNode(check, product, target, successor, item.node);
778
- product.edges[item.node].push(created.node, edgeIndex);
779
- if (created.isNew && targets[target] !== undefined) {
780
- pending.push({ node: created.node, isDone: true });
781
- }
782
- }
783
- });
784
- }
785
- return undefined;
786
- };
787
-
788
- const addInitialState = (index: number, state: Value[]) => {
789
- initial.push(index);
790
- states[index] = state;
791
- for (const check of checks) {
792
- const tableau = check.solution.tableau;
793
- const product = check.product;
794
- if (!tableau || !product) continue;
795
- const cache = new Map<LiveExpression, boolean>();
796
- for (let node = 0; node < tableau.initialCount; node++) {
797
- if (!isConsistent(tableau.nodes[node].statePredicates, state, cache)) continue;
798
- product.initial.push(getProductNode(check, product, index, node, -1).node);
799
- }
800
- }
801
- };
802
-
803
- const addState = (index: number, state: Value[], successors: LiveSuccessor[]) => {
804
- environment.runtime.setLivenessSource(index);
805
- states[index] = state;
806
- const edges: LiveSuccessor[] = [];
807
- const edgesByTarget = new Map<number, LiveSuccessor[]>();
808
- for (const successor of [...successors, { index, state }]) {
809
- const sameTarget = edgesByTarget.get(successor.index);
810
- const isDuplicate =
811
- sameTarget !== undefined &&
812
- (successor.index < index ||
813
- sameTarget.some((edge) => isSameState(edge.state, successor.state)));
814
- if (isDuplicate) continue;
815
- edges.push(successor);
816
- if (sameTarget) sameTarget.push(successor);
817
- else edgesByTarget.set(successor.index, [successor]);
818
- }
819
- targets[index] = edges.map((edge) => edge.index);
820
- edgeStates[index] = edges.map((edge) => edge.state);
821
- const stateCache = new Map<LiveExpression, boolean>();
822
- const successorCaches = edges.map(() => new Map<LiveExpression, boolean>());
823
- for (const check of checks) {
824
- const solution = check.solution;
825
- check.stateResults[index] = Uint8Array.from(solution.stateChecks, (predicate) =>
826
- evaluateLive(predicate, state, undefined, environment, stateCache) ? 1 : 0,
827
- );
828
- const tableau = solution.tableau;
829
- const product = check.product;
830
- if (!tableau || !product) continue;
831
- const nodeCount = tableau.nodes.length;
832
- const consistency = new Uint8Array(edges.length * nodeCount);
833
- edges.forEach((edge, edgeIndex) => {
834
- tableau.nodes.forEach((node, nodeIndex) => {
835
- const isTrue = isConsistent(node.statePredicates, edge.state, successorCaches[edgeIndex]);
836
- consistency[edgeIndex * nodeCount + nodeIndex] = isTrue ? 1 : 0;
837
- });
838
- });
839
- check.consistency[index] = consistency;
840
- const accepted = expandProduct(check, product, tableau, index);
841
- if (accepted) return accepted;
842
- }
843
- return undefined;
844
- };
845
-
846
- const computeActionResults = (source: number) => {
847
- environment.runtime.setLivenessSource(source);
848
- const state = states[source];
849
- const successors = edgeStates[source];
850
- const values = successors.map(() => new Int8Array(actionKeys.size).fill(-1));
851
- checks.forEach((check, checkIndex) => {
852
- const solution = check.solution;
853
- const ids = actionIds[checkIndex];
854
- const stateResults = check.stateResults[source];
855
- const stateCache = new Map(
856
- solution.stateChecks.map((predicate, position) => [
857
- predicate,
858
- stateResults[position] === 1,
859
- ]),
860
- );
861
- const actionCount = solution.actionChecks.length;
862
- const actions = new Uint8Array(successors.length * actionCount);
863
- successors.forEach((successor, edgeIndex) => {
864
- const known = values[edgeIndex];
865
- for (let position = 0; position < actionCount; position++) {
866
- const actionId = ids[position];
867
- if (known[actionId] === -1) {
868
- const predicate = solution.actionChecks[position];
869
- known[actionId] = evaluateLive(predicate, state, successor, environment, stateCache)
870
- ? 1
871
- : 0;
872
- }
873
- actions[edgeIndex * actionCount + position] = known[actionId];
874
- }
875
- });
876
- check.actionResults[source] = actions;
877
- });
878
- };
879
-
880
- const getActionResults = (check: Check, source: number) => {
881
- if (check.actionResults[source] === undefined) computeActionResults(source);
882
- return check.actionResults[source];
883
- };
884
-
885
- const getGraph = (check: Check): BehaviorGraph =>
886
- check.product ?? {
887
- states: states.map((_, index) => index),
888
- tableauNodes: states.map(() => -1),
889
- edges: Array.from({ length: states.length }, (_, index) =>
890
- (targets[index] ?? []).flatMap((target, edgeIndex) => [target, edgeIndex]),
891
- ),
892
- initial,
893
- parents: [],
894
- };
895
-
896
- const getPrefix = (graph: BehaviorGraph, entry: number) => {
897
- if (graph.parents.length > 0) {
898
- const path: number[] = [];
899
- for (let node = entry; node !== -1; node = graph.parents[node]) path.push(node);
900
- return path.reverse();
901
- }
902
- const parents = new Map<number, number>(graph.initial.map((node) => [node, -1]));
903
- const queue = [...graph.initial];
904
- for (let position = 0; position < queue.length && !parents.has(entry); position++) {
905
- const edges = graph.edges[queue[position]];
906
- for (let offset = 0; offset < edges.length; offset += 2) {
907
- if (parents.has(edges[offset])) continue;
908
- parents.set(edges[offset], queue[position]);
909
- queue.push(edges[offset]);
910
- }
911
- }
912
- const path: number[] = [];
913
- for (let node = entry; node !== -1; node = parents.get(node) ?? -1) path.push(node);
914
- return path.reverse();
915
- };
916
-
917
- const findInCheck = (check: Check): Lasso | undefined => {
918
- const solution = check.solution;
919
- const tableau = solution.tableau;
920
- const graph = getGraph(check);
921
- const actionCount = solution.actionChecks.length;
922
- const getAction = (node: number, edgeIndex: number, position: number) =>
923
- getActionResults(check, graph.states[node])[edgeIndex * actionCount + position] === 1;
924
- for (const model of solution.models) {
925
- const isAllowed = (node: number, edgeIndex: number) =>
926
- model.eventuallyAlways.every((position) => getAction(node, edgeIndex, position));
927
- const getSuccessors = (node: number) => {
928
- const edges = graph.edges[node];
929
- const successors: number[] = [];
930
- for (let offset = 0; offset < edges.length; offset += 2) {
931
- if (isAllowed(node, edges[offset + 1])) successors.push(edges[offset]);
932
- }
933
- return successors;
934
- };
935
- const lasso = { value: undefined as Lasso | undefined };
936
- getStronglyConnectedComponents(
937
- graph.states.length,
938
- getSuccessors,
939
- (component, successors) => {
940
- const members = new Set(component);
941
- if (component.length === 1 && !successors(component[0]).includes(component[0]))
942
- return false;
943
- const stateWitnesses = model.infinitelyOftenStates.map((position) =>
944
- component.find((node) => check.stateResults[graph.states[node]][position] === 1),
945
- );
946
- const actionWitnesses = model.infinitelyOftenActions.map((position) => {
947
- for (const node of component) {
948
- const edges = graph.edges[node];
949
- for (let offset = 0; offset < edges.length; offset += 2) {
950
- const isWitness =
951
- members.has(edges[offset]) &&
952
- isAllowed(node, edges[offset + 1]) &&
953
- getAction(node, edges[offset + 1], position);
954
- if (isWitness) return [node, edges[offset]];
955
- }
956
- }
957
- return undefined;
958
- });
959
- const promiseWitnesses = solution.promises.map((promise) =>
960
- component.find(
961
- (node) =>
962
- tableau !== undefined &&
963
- isFulfilling(tableau.nodes[graph.tableauNodes[node]].particle, promise),
964
- ),
965
- );
966
- const isViolation =
967
- stateWitnesses.every((witness) => witness !== undefined) &&
968
- actionWitnesses.every((witness) => witness !== undefined) &&
969
- promiseWitnesses.every((witness) => witness !== undefined);
970
- if (!isViolation) return false;
971
- const entry = component[component.length - 1];
972
- const waypoints = [
973
- ...stateWitnesses.flatMap((witness) => witness ?? []),
974
- ...actionWitnesses.flatMap((witness) => witness ?? []),
975
- ...promiseWitnesses.flatMap((witness) => witness ?? []),
976
- ];
977
- const cycle = [entry];
978
- for (const waypoint of waypoints) {
979
- cycle.push(
980
- ...getShortestPath(cycle[cycle.length - 1], waypoint, members, successors).slice(1),
981
- );
982
- }
983
- if (cycle.length === 1 && !successors(entry).includes(entry)) {
984
- cycle.push(successors(entry).find((node) => members.has(node)) ?? entry);
985
- }
986
- const closing = getShortestPath(cycle[cycle.length - 1], entry, members, successors);
987
- cycle.push(...closing.slice(1, -1));
988
- const prefix = removeRepeats(getPrefix(graph, entry).map((node) => graph.states[node]));
989
- const cycleStates = removeRepeats(cycle.map((node) => graph.states[node]));
990
- if (cycleStates.length > 1 && cycleStates[cycleStates.length - 1] === cycleStates[0]) {
991
- cycleStates.pop();
992
- }
993
- prefix.pop();
994
- lasso.value = {
995
- name: getAttribution([...prefix, ...cycleStates], prefix.length),
996
- prefix,
997
- cycle: cycleStates,
998
- };
999
- return true;
1000
- },
1001
- );
1002
- if (lasso.value) return lasso.value;
1003
- }
1004
- return undefined;
1005
- };
1006
-
1007
- return {
1008
- addInitialState,
1009
- addState,
1010
- findViolation: () => {
1011
- for (const check of checks) {
1012
- const lasso = findInCheck(check);
1013
- if (lasso) return lasso;
1014
- }
1015
- return undefined;
1016
- },
1017
- };
1018
- };