Algorithm Search⌘K

Algorithmresearch

Generalized symbolic trajectory evaluation

Also called GSTE.

Yang and Seger's extension of STE to assertion graphs that express properties over unbounded time, checked by a fixed point on ternary symbolic states.

Time
O(N E^2 (N + P) B^2) worst
Space
O(E N B) extra
Where
B = the number of nodes of the largest rail BDD (at most 2^(v + 1), v the number of symbolic constants); E = the number of edges of the assertion graph; N = the number of nodes of the circuit; P = the number of gate inputs
Properties
not completedeterministicnot exactiterative
Origin
Jin Yang, Carl Johan H. Seger, 2001

Generalized symbolic trajectory evaluation (GSTE) checks properties of a circuit over unbounded time. STE checks an assertion whose times run from 0 to a fixed depth dd. GSTE replaces this line of times by an assertion graph: a directed graph whose edges carry an antecedent and a consequent, each about one clock cycle. A path through the graph is a pattern of cycles, and loops in the graph give patterns of any length. The check computes, for each edge, one ternary symbolic state that lies below every state in which a run can take that edge. It finds these states by a fixed point that starts at ⊤\top (no state) and goes down the lattice. The lattice, the dual-rail encoding and the monotone gate evaluation are those of STE. This page covers the assertion graph and what it adds.

In plain words

Take a register that loads dd when enen is 1 and keeps its value when enen is 0. The property is "after a load of xx, while enen stays 0, the register holds xx". That holds for 1 cycle, 2 cycles, a thousand cycles. STE needs one check per length.

GSTE draws the property as a small graph. One edge says "load xx now". A loop says "enen is 0 now, and the register must hold xx". A path that takes the loop kk times is a hold of kk cycles. GSTE goes around the loop with ternary simulation until the state stops changing. That final state covers every number of turns, so one finite computation checks all lengths. As in STE, unknown values are X, and a pass is a proof.

The problem

Assertion graphs. An assertion graph is G=(V,v0,E)G = (V, v_0, E) with a finite set of vertices VV, an initial vertex v0v_0, and edges e=(src(e),dst(e))e = (\mathrm{src}(e), \mathrm{dst}(e)). Each edge has an antecedent ant(e)\mathrm{ant}(e) and a consequent cons(e)\mathrm{cons}(e). Each is a set of constraints (u,a,g)(u, a, g), read "if gg then node uu is aa" at the time the edge is taken, where aa and gg are Boolean expressions over symbolic constants. The constants keep one value along a whole run. An assignment of them is ϕ\phi.

Strong semantics. A run ρ\rho of the circuit, as on the STE page, gives each node a binary value ρt(u)\rho_t(u) at each time tt. The graph holds when for every ϕ\phi, every path e0e1⋯eke_0 e_1 \cdots e_k with src(e0)=v0\mathrm{src}(e_0) = v_0 and dst(ei)=src(ei+1)\mathrm{dst}(e_i) = \mathrm{src}(e_{i+1}), and every run that meets ant(ei)\mathrm{ant}(e_i) at time ii under ϕ\phi for all i≤ki \le k, the run meets cons(ek)\mathrm{cons}(e_k) at time kk under ϕ\phi. A consequent is excused only by the antecedents up to its own time. Yang and Seger call this the strong semantics. For each kk it is a bounded statement, but there is no bound on kk.

The task. Compute the set of ϕ\phi where the graph fails, as a BDD, or a superset of it that is exact in the common cases.

The algorithm

δ(F)\delta(F) is the least ternary state that a set of constraints asks for, as on the STE page. The meet ⊓\sqcap is the AND of the rails, so 0⊓1=X0 \sqcap 1 = \mathrm{X}, and ⊤⊓a=a\top \sqcap a = a. A ternary state with a ⊤\top node stands for the empty set of states, and line L7 then sets all its nodes to ⊤\top.

  1. GSTE(C, G)
  2. 1for each edge e do sim(e) ← ⊤ on every node
  3. 2repeat
  4. 3for each edge e do
  5. 4pre ← (X on every node if src(e) = v₀, else ⊤) ⊓ the meet of sim(e′) over the edges e′ into src(e)
  6. 5σ ← δ(ant(e)); for each latch s do σ(s) ← σ(s) ⊔ pre(next(s))
  7. 6for each gate u in topological order do σ(u) ← σ(u) ⊔ op̂(u)(σ of the fanins of u)
  8. 7new(e) ← σ, with every node set to ⊤ where pre or σ has a ⊤ node
  9. 8until new = sim; otherwise sim ← new and repeat
  10. 9residual ← the OR over all edges e of ¬[δ(cons(e)) ⊑ sim(e)]
  11. 10return residual

Line L4 gathers the states in which a run can be just before it takes ee. A path may start at v0v_0 from any state, so v0v_0 adds the all-X state. The meet over several in-edges keeps only what they share. It is an over-approximation of the union of the state sets. Lines L5 and L6 are one step of ternary symbolic simulation from that state with the antecedent of ee added. Line L7 marks the edge as not taken where the previous state set or the new one is empty. Line L8 stops when a whole round changes no BDD. Line L9 is the STE comparison, done once per edge on the fixed point.

A chain v0→v1→⋯→vd+1v_0 \to v_1 \to \cdots \to v_{d+1} with the constraints of time tt on its tt-th edge is an STE assertion. GSTE then does the STE computation, except that a conflict in a later antecedent does not excuse an earlier consequent. The new parts are the loops, the meets at vertices with several in-edges, and the fixed point.

Example

The circuit has inputs enen and dd, one latch rr with next(r)=m\mathrm{next}(r) = m, and gates en‾=¬en\overline{en} = \neg en, t1=en∧dt_1 = en \wedge d, t2=en‾∧rt_2 = \overline{en} \wedge r, m=t1∨t2m = t_1 \vee t_2. The graph has vertices v0,v1v_0, v_1 and three edges:

  • e0=(v0,v0)e_0 = (v_0, v_0), no antecedent and no consequent: wait any number of cycles.
  • e1=(v0,v1)e_1 = (v_0, v_1), antecedent "enen is 1, dd is xx": load xx.
  • e2=(v1,v1)e_2 = (v_1, v_1), antecedent "enen is 0", consequent "rr is xx": hold.

The fixed point, by rounds, shows rr and mm (other nodes follow from them):

round sim(e0)\mathrm{sim}(e_0) sim(e1)\mathrm{sim}(e_1): rr, mm sim(e2)\mathrm{sim}(e_2): rr, mm
0 all ⊤\top all ⊤\top all ⊤\top
1 all X X, xx all ⊤\top (pre is sim0(e1)⊓sim0(e2)=⊤\mathrm{sim}_0(e_1) \sqcap \mathrm{sim}_0(e_2) = \top)
2 all X X, xx xx, xx
3 all X X, xx xx, xx (pre is sim2(e1)⊓sim2(e2)\mathrm{sim}_2(e_1) \sqcap \mathrm{sim}_2(e_2), with m=xm = x in both)

Round 3 changes nothing, so the loop stops. On e1e_1, t1=1∧x=xt_1 = 1 \wedge x = x and t2=0∧X=0t_2 = 0 \wedge \mathrm{X} = 0, so m=xm = x although rr is X. On e2e_2, r=xr = x satisfies the consequent, and the residual is 0. The property holds for holds of every length, after a load at any time, from every initial state. The run used one symbolic constant.

Now replace mm by t1∨rt_1 \vee r, a register that can set but never clear. On e1e_1, m=x∨Xm = x \vee \mathrm{X}, which is 1 when x=1x = 1 and X when x=0x = 0. Then sim(e2)\mathrm{sim}(e_2) has rr with one-rail xx and zero-rail 0, and the consequent asks for zero-rail ¬x\neg x. The residual is ¬x\neg x. The failure is real: start with r=1r = 1, load 0, hold, and rr is still 1. The tests find this run by enumeration.

Correctness

Claim (soundness). If the residual is 0 at ϕ\phi, the graph holds at ϕ\phi under the strong semantics. More exactly, for every edge ee, the consequent of ee holds at every time at which some run takes ee along a path from v0v_0 whose antecedents it meets, wherever ¬[δ(cons(e))⊑sim(e)]\neg[\delta(\mathrm{cons}(e)) \sqsubseteq \mathrm{sim}(e)] is 0.

Key lemma. At the fixed point, for every path e0⋯eke_0 \cdots e_k from v0v_0 and every run ρ\rho that meets ant(ei)\mathrm{ant}(e_i) at time ii for all i≤ki \le k, sim(ek)(ϕ)⊑ρk\mathrm{sim}(e_k)(\phi) \sqsubseteq \rho_k at every node. The proof is by induction on kk. The state pre\mathrm{pre} of eke_k is X at k=0k = 0. At k>0k > 0 it is a meet that includes sim(ek−1)\mathrm{sim}(e_{k-1}), so it lies below sim(ek−1)\mathrm{sim}(e_{k-1}) and hence below ρk−1\rho_{k-1}. So pre(next(s))⊑ρk(s)\mathrm{pre}(\mathrm{next}(s)) \sqsubseteq \rho_k(s) for each latch. From there, lines L5 and L6 are one step of the STE lemma: joins of values below a binary value stay below it, and the gate tables are monotone. Since pre\mathrm{pre} and σ\sigma lie below binary states, neither has a ⊤\top, and line L7 changes nothing. With the lemma, δ(cons(ek))⊑sim(ek)⊑ρk\delta(\mathrm{cons}(e_k)) \sqsubseteq \mathrm{sim}(e_k) \sqsubseteq \rho_k, so ρ\rho meets cons(ek)\mathrm{cons}(e_k).

Termination. Each round applies a map FF that is monotone in the information order, since meet, join, the gate tables and the step of line L7 are all monotone. The first round gives sim1⊑⊤=sim0\mathrm{sim}_1 \sqsubseteq \top = \mathrm{sim}_0, and monotonicity gives simn+1⊑simn\mathrm{sim}_{n+1} \sqsubseteq \mathrm{sim}_n for all nn. At one ϕ\phi, each of the NEN E values can go down at most twice, from ⊤\top to 0 or 1 to X. A round that changes nothing at ϕ\phi stays unchanged at ϕ\phi for ever. So the loop ends after at most 2NE+12 N E + 1 rounds, at the greatest fixed point of FF in the information order. The proofs are in the correctness proof.

What is lost. The check is not complete for binary runs, for two reasons. X loses information, as in STE. The meet at a vertex also loses it: if one in-edge brings r=0r = 0 and another brings r=1r = 1, the meet has r=Xr = \mathrm{X}. When every input and every initial latch value is fixed and the graph is a chain, each sim(e)\mathrm{sim}(e) is the exact binary state of the one run, and the check is exact. The tests check this case.

Proof: The GSTE fixed point terminates and is sound for the strong semanticsfull

Setting. The lattice L={X,0,1,⊤}L = \{\mathrm{X}, 0, 1, \top\}, the dual-rail encoding, the circuit model and the gate tables op^\widehat{\mathrm{op}} are those of the STE proof. We use two facts proved there. Fact 1: a binary state ρt\rho_t meets a set of constraints FF at ϕ\phi exactly when δ(F)(ϕ)⊑ρt\delta(F)(\phi) \sqsubseteq \rho_t at every node. Fact 2: each op^\widehat{\mathrm{op}} is monotone and agrees with op\mathrm{op} on binary arguments. A ternary state is a map from nodes to LL. States are ordered node by node, and the meet ⊓\sqcap and join ⊔\sqcup are taken node by node. The meet is the AND of the rails: on LL it is the greatest lower bound, with 0⊓1=X0 \sqcap 1 = \mathrm{X} and ⊤⊓a=a\top \sqcap a = a. Fix an assignment ϕ\phi. All statements are at ϕ\phi, and the BDD operations act point by point, so it is enough to argue for one ϕ\phi.

For a state σ\sigma write empty(σ)\mathrm{empty}(\sigma) if some node of σ\sigma is ⊤\top. Let norm(σ,b)\mathrm{norm}(\sigma, b) be the state with every node ⊤\top if bb or empty(σ)\mathrm{empty}(\sigma) holds, and σ\sigma otherwise. Let FF map an assignment of states to edges, sim\mathrm{sim}, to the states new\mathrm{new} of lines L4 to L7:

pree=Ie⊓⊓dst(e′)=src(e)sim(e′),σe=close(δ(ant(e))⊔shift(pree)),F(sim)(e)=norm(σe,empty(pree)).\mathrm{pre}_e = I_e \sqcap \mathop{\large\sqcap}_{\mathrm{dst}(e') = \mathrm{src}(e)} \mathrm{sim}(e'), \qquad \sigma_e = \mathrm{close}\bigl(\delta(\mathrm{ant}(e)) \sqcup \mathrm{shift}(\mathrm{pre}_e)\bigr), \qquad F(\mathrm{sim})(e) = \mathrm{norm}(\sigma_e, \mathrm{empty}(\mathrm{pre}_e)).

Here IeI_e is the all-X state if src(e)=v0\mathrm{src}(e) = v_0 and the all-⊤\top state otherwise, shift(p)\mathrm{shift}(p) has p(next(s))p(\mathrm{next}(s)) at each latch ss and X elsewhere, and close\mathrm{close} is line L6, which joins each gate in topological order with op^\widehat{\mathrm{op}} of its fanins.

Lemma 1 (monotone round). If sim⊑sim′\mathrm{sim} \sqsubseteq \mathrm{sim}' at every edge and node, then F(sim)⊑F(sim′)F(\mathrm{sim}) \sqsubseteq F(\mathrm{sim}').

Proof. Meet and join are monotone in each argument, so pree⊑pree′\mathrm{pre}_e \sqsubseteq \mathrm{pre}'_e and shift(pree)⊑shift(pree′)\mathrm{shift}(\mathrm{pre}_e) \sqsubseteq \mathrm{shift}(\mathrm{pre}'_e). The map close\mathrm{close} is monotone by induction over the gates in topological order: each gate value is a join of its old value and op^\widehat{\mathrm{op}} of values that are already ordered, and both operations are monotone by Fact 2. So σe⊑σe′\sigma_e \sqsubseteq \sigma'_e. For norm\mathrm{norm}: the only element above ⊤\top is ⊤\top, so empty(σ)\mathrm{empty}(\sigma) and σ⊑σ′\sigma \sqsubseteq \sigma' give empty(σ′)\mathrm{empty}(\sigma'), and the same holds for pre\mathrm{pre}. If norm\mathrm{norm} sets F(sim′)(e)F(\mathrm{sim}')(e) to all ⊤\top, the claim holds since everything is below ⊤\top. Otherwise neither σe′\sigma'_e nor pree′\mathrm{pre}'_e is empty, hence neither σe\sigma_e nor pree\mathrm{pre}_e is, and both results are the unchanged σe⊑σe′\sigma_e \sqsubseteq \sigma'_e. □\square

Lemma 2 (termination). The loop of lines L2 to L8 stops after at most 2NE+12 N E + 1 rounds, where NN is the number of nodes and EE the number of edges, and on exit sim=F(sim)\mathrm{sim} = F(\mathrm{sim}).

Proof. Let sim0\mathrm{sim}_0 be all ⊤\top (line L1) and simn+1=F(simn)\mathrm{sim}_{n+1} = F(\mathrm{sim}_n). Then sim1⊑sim0\mathrm{sim}_1 \sqsubseteq \mathrm{sim}_0, since ⊤\top is the greatest element. If simn+1⊑simn\mathrm{sim}_{n+1} \sqsubseteq \mathrm{sim}_n, Lemma 1 gives simn+2⊑simn+1\mathrm{sim}_{n+2} \sqsubseteq \mathrm{sim}_{n+1}. So the sequence goes down at every node of every edge. Every chain in LL that goes strictly down has at most 3 elements (⊤\top, a binary value, X), so at ϕ\phi each of the NEN E values changes at most twice. If simn+1=simn\mathrm{sim}_{n+1} = \mathrm{sim}_n at ϕ\phi, then simn+2=F(simn+1)=F(simn)=simn+1\mathrm{sim}_{n+2} = F(\mathrm{sim}_{n+1}) = F(\mathrm{sim}_n) = \mathrm{sim}_{n+1} at ϕ\phi, because FF at ϕ\phi depends only on the values at ϕ\phi. So at each ϕ\phi the changing rounds come first and number at most 2NE2 N E. The loop stops at the first round that changes nothing at any ϕ\phi, which is round 2NE+12 N E + 1 or earlier, and line L8 stops only when new=sim\mathrm{new} = \mathrm{sim}, that is F(sim)=simF(\mathrm{sim}) = \mathrm{sim}. □\square

Lemma 3 (the fixed point is below every run). Let sim=F(sim)\mathrm{sim} = F(\mathrm{sim}). Let e0e1⋯eke_0 e_1 \cdots e_k be a path with src(e0)=v0\mathrm{src}(e_0) = v_0 and dst(ei)=src(ei+1)\mathrm{dst}(e_{i}) = \mathrm{src}(e_{i+1}), and let ρ\rho be a binary run that meets ant(ei)\mathrm{ant}(e_i) at time ii for all i≤ki \le k. Then sim(ek)⊑ρk\mathrm{sim}(e_k) \sqsubseteq \rho_k.

Proof. By induction on kk. Write e=eke = e_k.

First, pree⊑ρk−1\mathrm{pre}_e \sqsubseteq \rho_{k-1} at every node when k>0k > 0, and shift(pree)⊑ρk\mathrm{shift}(\mathrm{pre}_e) \sqsubseteq \rho_k at every node for every kk. For k=0k = 0, src(e)=v0\mathrm{src}(e) = v_0, so pree⊑Ie\mathrm{pre}_e \sqsubseteq I_e, which is all X, and shift(pree)\mathrm{shift}(\mathrm{pre}_e) is all X. For k>0k > 0, ek−1e_{k-1} is an edge into src(e)\mathrm{src}(e), so pree⊑sim(ek−1)⊑ρk−1\mathrm{pre}_e \sqsubseteq \mathrm{sim}(e_{k-1}) \sqsubseteq \rho_{k-1} by the induction hypothesis. Then shift(pree)(s)=pree(next(s))⊑ρk−1(next(s))=ρk(s)\mathrm{shift}(\mathrm{pre}_e)(s) = \mathrm{pre}_e(\mathrm{next}(s)) \sqsubseteq \rho_{k-1}(\mathrm{next}(s)) = \rho_k(s) at each latch, and X elsewhere.

Next, δ(ant(e))⊑ρk\delta(\mathrm{ant}(e)) \sqsubseteq \rho_k by Fact 1. A join of values below a binary value is below it, so the argument of close\mathrm{close} is below ρk\rho_k. Going through the gates in topological order, each gate uu gets the join of a value below ρk(u)\rho_k(u) and op^(u)\widehat{\mathrm{op}}(u) of fanin values below the ρk\rho_k values of the fanins. By Fact 2 the second term is below op(u)(ρk of the fanins)=ρk(u)\mathrm{op}(u)(\rho_k \text{ of the fanins}) = \rho_k(u). So σe⊑ρk\sigma_e \sqsubseteq \rho_k.

Last, no binary value is above ⊤\top, so neither σe\sigma_e nor pree\mathrm{pre}_e (when k>0k > 0) has a ⊤\top node. When k=0k = 0, pree⊑Ie\mathrm{pre}_e \sqsubseteq I_e is all X, which is not empty. So norm\mathrm{norm} returns σe\sigma_e, and sim(e)=F(sim)(e)=σe⊑ρk\mathrm{sim}(e) = F(\mathrm{sim})(e) = \sigma_e \sqsubseteq \rho_k. □\square

Theorem (soundness). Let sim\mathrm{sim} be the result of the loop. If, at ϕ\phi, δ(cons(e))⊑sim(e)\delta(\mathrm{cons}(e)) \sqsubseteq \mathrm{sim}(e) for every edge ee (the residual of line L9 is 0 at ϕ\phi), then the graph holds at ϕ\phi under the strong semantics.

Proof. By Lemma 2, sim=F(sim)\mathrm{sim} = F(\mathrm{sim}). Take a path e0⋯eke_0 \cdots e_k from v0v_0 and a run ρ\rho that meets ant(ei)\mathrm{ant}(e_i) at time ii for i≤ki \le k. Lemma 3 gives sim(ek)⊑ρk\mathrm{sim}(e_k) \sqsubseteq \rho_k, so δ(cons(ek))⊑ρk\delta(\mathrm{cons}(e_k)) \sqsubseteq \rho_k by transitivity, and by Fact 1 ρ\rho meets cons(ek)\mathrm{cons}(e_k) at time kk. ■\blacksquare

Remarks. Lemma 3 uses only sim=F(sim)\mathrm{sim} = F(\mathrm{sim}), so any fixed point gives a sound check. The loop finds the greatest fixed point in the information order, which is the most precise one: by Lemma 1 and induction, every fixed point ss has s=Fn(s)⊑Fn(⊤)=simns = F^n(s) \sqsubseteq F^n(\top) = \mathrm{sim}_n for all nn. The check is not complete. The meet at a vertex is only an upper bound, in the set order, of the union of the state sets of the in-edges, and X loses information as in STE. If the graph is a chain and the antecedents fix every input at every step and every latch at the first step, then at each ϕ\phi exactly one run takes each edge. By Lemma 3 and induction, each sim(ek)\mathrm{sim}(e_k) is then that run's binary state ρk\rho_k, and the check is exact. The tests check this case against enumeration of all runs.

Complexity

The model is the word RAM with hashing in expected constant time. Let NN be the number of nodes, PP the number of gate inputs, EE the number of edges and BB the largest rail BDD.

  • Line L4 costs O(N)O(N) meets per in-edge of src(e)\mathrm{src}(e). Computing it once per vertex, a round costs O(EN)O(E N) meets for line L4 over all vertices.
  • Lines L5 to L7 cost O(N+P)O(N + P) BDD operations per edge, so a round costs O(E(N+P))O(E (N + P)) operations, each O(B2)O(B^2) by Apply.
  • There are at most 2NE+12 N E + 1 rounds, which gives O(NE2(N+P)B2)O(N E^2 (N + P) B^2) time in the worst case.
  • The states of all edges take O(EN)O(E N) BDD roots, and the nodes they share take O(ENB)O(E N B) space.

The round bound is a worst case. In the example the states settle after two rounds, and a third round sees that nothing changed. The tests check the bound on random circuits and graphs. As in STE, the variables come from the symbolic constants of the graph, not from the circuit, and nodes outside the property stay X. Deciding whether a property holds is at least as hard as the STE case, which is coNP-hard.

Properties

  • Sound for all runs and all path lengths under the strong semantics.
  • Not complete: X and the meets at vertices can cause failures that no run shows. A failure must be checked against a binary run.
  • Terminates on every input, because the lattice of ternary symbolic states over a fixed set of variables is finite.
  • One fixed point covers patterns of any length, which a bounded method such as STE or bounded model checking cannot do.
  • The precision is set by the user through the shape of the graph, not by a fixed abstraction in the tool.

Variants and improvements

  • Other semantics. Under the strong semantics only past antecedents count. Yang and Seger also define a semantics over infinite paths in which antecedents later on the path count too. That needs more than the forward fixed point of this page. Restricting the infinite paths by fairness conditions leads to liveness properties.
  • Refinement by the graph. When a meet loses needed information, split the vertex into two copies, one per in-edge, or replace a set of concrete constants by one symbolic constant, so that one edge covers all the cases. Yang and Seger (2002) treat these choices as the abstraction of the check.
  • Concrete version. Replace ternary states by sets of binary states, meet by union and join by intersection. The fixed point is then reachability in the product of the circuit and the graph, and the check is exact. This is symbolic model checking of a safety property, at the cost of variables for all latches.

When to use it

Use GSTE for properties of unbounded length on circuits too large for a symbolic model checker, where the property reads only part of the state: data integrity in a memory or queue over any number of cycles, a register file that keeps a value until it is written, a control protocol given as a small graph of phases. If a bound is known and small, STE is simpler. If much of the state matters, a model checker with exact sets gives no false failures. For property languages with assertions on a simulator, see assertion-based verification.

Pitfalls

  • No wait loop at v0v_0. Without the edge e0e_0 of the example, every path starts with a load at time 0, and the check says nothing about a load at a later time. Most properties need a loop at the initial vertex with an empty antecedent.
  • Merging cases at one vertex. Two edges "load 0" and "load 1" into one vertex give r=Xr = \mathrm{X} there, and every later consequent on rr fails. Use one edge with a symbolic constant xx, or two vertices.
  • Reading the strong semantics as implication over the whole path. A consequent at time kk is not excused by a contradiction in the antecedent at time k+1k + 1. A property that relies on future inputs needs another semantics.
  • Vacuous edges. An edge whose antecedent conflicts with the circuit is never taken, and its consequents pass. Check which edges have sim(e)=⊤\mathrm{sim}(e) = \top everywhere, as the antecedent failure is checked in STE.
  • Symbolic variables that change. A symbolic constant has the same value on the whole path. To talk about a fresh value at each step, use X and a consequent that compares two nodes, or add a vertex per value.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

bdd.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the hv2 eda pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""A small reduced ordered BDD package with a unique table and an ITE cache.

A node is an integer. The terminals are 0 (false) and 1 (true). A variable is a
non-negative integer, and a smaller integer is nearer the root. Every inner node
is a triple (var, lo, hi) with lo != hi, and the unique table keeps one node per
triple, so two BDDs of the same manager are equal functions exactly when they
are the same integer.
"""

from __future__ import annotations

from typing import Iterable, Optional

FALSE = 0
TRUE = 1
_TERMINAL_VAR = 1 << 30


class BDD:
    """One manager. All BDDs that are combined must come from the same manager."""

    def __init__(self) -> None:
        self._var: list[int] = [_TERMINAL_VAR, _TERMINAL_VAR]
        self._lo: list[int] = [0, 1]
        self._hi: list[int] = [0, 1]
        self._unique: dict[tuple[int, int, int], int] = {}
        self._ite_cache: dict[tuple[int, int, int], int] = {}

    # -- construction -------------------------------------------------------
    def mk(self, v: int, lo: int, hi: int) -> int:
        """The node (v, lo, hi), reduced: equal children give the child."""
        if lo == hi:
            return lo
        key = (v, lo, hi)
        n = self._unique.get(key)
        if n is None:
            n = len(self._var)
            self._var.append(v)
            self._lo.append(lo)
            self._hi.append(hi)
            self._unique[key] = n
        return n

    def var(self, v: int) -> int:
        """The BDD of the single variable v."""
        return self.mk(v, FALSE, TRUE)

    def top(self, f: int) -> int:
        return self._var[f]

    def low(self, f: int) -> int:
        return self._lo[f]

    def high(self, f: int) -> int:
        return self._hi[f]

    def _cof(self, f: int, v: int, b: int) -> int:
        if self._var[f] != v:
            return f
        return self._hi[f] if b else self._lo[f]

    def ite(self, f: int, g: int, h: int) -> int:
        """If f then g else h, by Shannon expansion on the top variable."""
        if f == TRUE:
            return g
        if f == FALSE:
            return h
        if g == h:
            return g
        if g == TRUE and h == FALSE:
            return f
        key = (f, g, h)
        r = self._ite_cache.get(key)
        if r is not None:
            return r
        v = min(self._var[f], self._var[g], self._var[h])
        lo = self.ite(self._cof(f, v, 0), self._cof(g, v, 0), self._cof(h, v, 0))
        hi = self.ite(self._cof(f, v, 1), self._cof(g, v, 1), self._cof(h, v, 1))
        r = self.mk(v, lo, hi)
        self._ite_cache[key] = r
        return r

    def neg(self, f: int) -> int:
        return self.ite(f, FALSE, TRUE)

    def conj(self, f: int, g: int) -> int:
        return self.ite(f, g, FALSE)

    def disj(self, f: int, g: int) -> int:
        return self.ite(f, TRUE, g)

    def xor(self, f: int, g: int) -> int:
        return self.ite(f, self.neg(g), g)

    def xnor(self, f: int, g: int) -> int:
        return self.ite(f, g, self.neg(g))

    def restrict(self, f: int, v: int, b: int) -> int:
        """f with the variable v set to the constant b."""
        memo: dict[int, int] = {}

        def go(n: int) -> int:
            if n <= 1 or self._var[n] > v:
                return n
            if n in memo:
                return memo[n]
            if self._var[n] == v:
                r = self._hi[n] if b else self._lo[n]
            else:
                r = self.mk(self._var[n], go(self._lo[n]), go(self._hi[n]))
            memo[n] = r
            return r

        return go(f)

    def exists(self, f: int, vs: Iterable[int]) -> int:
        """Existential quantification of the variables vs."""
        for v in sorted(set(vs), reverse=True):
            f = self.disj(self.restrict(f, v, 0), self.restrict(f, v, 1))
        return f

    # -- queries ------------------------------------------------------------
    def evaluate(self, f: int, assignment: dict[int, int]) -> int:
        """The value of f at a point; a missing variable counts as 0."""
        while f > 1:
            f = self._hi[f] if assignment.get(self._var[f], 0) else self._lo[f]
        return f

    def size(self, f: int) -> int:
        """The number of nodes of f, terminals included."""
        seen: set[int] = set()
        stack = [f]
        while stack:
            n = stack.pop()
            if n in seen:
                continue
            seen.add(n)
            if n > 1:
                stack.append(self._lo[n])
                stack.append(self._hi[n])
        return len(seen)

    def support(self, f: int) -> set[int]:
        out: set[int] = set()
        seen: set[int] = set()
        stack = [f]
        while stack:
            n = stack.pop()
            if n <= 1 or n in seen:
                continue
            seen.add(n)
            out.add(self._var[n])
            stack.append(self._lo[n])
            stack.append(self._hi[n])
        return out

    def sat_one(self, f: int) -> Optional[dict[int, int]]:
        """One point where f is 1 (variables not on the path are left out), or None."""
        if f == FALSE:
            return None
        out: dict[int, int] = {}
        while f > 1:
            if self._lo[f] != FALSE:
                out[self._var[f]] = 0
                f = self._lo[f]
            else:
                out[self._var[f]] = 1
                f = self._hi[f]
        return out
generalized_symbolic_trajectory_evaluation.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-symbolic-trajectory-evaluation/. The authors are listed in prov/KNN3V9.jsonl.
"""Generalized symbolic trajectory evaluation (Yang and Seger) under the strong semantics.

An assertion graph has vertices, an initial vertex v0, and edges (src, dst, ant,
cons). The antecedent ant and the consequent cons of an edge are lists of
constraints (node, e, g), read "if g then node is e" at the time the edge is
taken, with e and g BDDs over the symbolic variables. The graph says: for every
path e0 e1 ... ek from v0 and every run that meets ant(ei) at time i for all
i <= k, the run meets cons(ek) at time k.

The check computes for each edge a ternary symbolic state sim(e), the least
information common to all states in which a run can take e. Values are
dual-rail pairs (one, zero) of BDDs on the lattice X below 0 and 1 below TOP,
as on the STE page. The fixed point starts at TOP (no state) and goes down.

Precondition: gates in topological order. Every round costs O(E (N + P)) dual-
rail operations, and there are at most 2 N E + 1 rounds.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Optional

from bdd import BDD, FALSE, TRUE

Val = tuple[int, int]          # (one, zero)
XV: Val = (FALSE, FALSE)
TV: Val = (TRUE, TRUE)


@dataclass(frozen=True)
class Circuit:
    """inputs; latches as (name, next_state_node); gates as (name, op, fanins) in topological order."""

    inputs: tuple[str, ...]
    latches: tuple[tuple[str, str], ...]
    gates: tuple[tuple[str, str, tuple[str, ...]], ...]

    def nodes(self) -> list[str]:
        return list(self.inputs) + [s for s, _ in self.latches] + [g for g, _, _ in self.gates]


Constraint = tuple[str, int, int]             # (node, value BDD, guard BDD)


@dataclass(frozen=True)
class Edge:
    src: int
    dst: int
    ant: tuple[Constraint, ...] = ()
    cons: tuple[Constraint, ...] = ()


@dataclass
class Result:
    passed: bool
    residual: int                  # the assignments where some edge fails
    failing: dict[int, int]        # edge index -> its own residual
    sim: list[dict[str, Val]]      # the fixed point, one state per edge
    rounds: int


def join(m: BDD, a: Val, b: Val) -> Val:
    return (m.disj(a[0], b[0]), m.disj(a[1], b[1]))


def meet(m: BDD, a: Val, b: Val) -> Val:
    return (m.conj(a[0], b[0]), m.conj(a[1], b[1]))


def leq(m: BDD, a: Val, b: Val) -> int:
    return m.conj(m.disj(m.neg(a[0]), b[0]), m.disj(m.neg(a[1]), b[1]))


def gate_value(m: BDD, op: str, args: list[Val]) -> Val:
    """The monotone ternary extension of a gate on dual-rail values."""
    if op == "BUF":
        return args[0]
    if op == "NOT":
        return (args[0][1], args[0][0])
    if op in ("AND", "NAND", "OR", "NOR"):
        conj_like = op in ("AND", "NAND")
        one, zero = (TRUE, FALSE) if conj_like else (FALSE, TRUE)
        for a1, a0 in args:
            if conj_like:
                one, zero = m.conj(one, a1), m.disj(zero, a0)
            else:
                one, zero = m.disj(one, a1), m.conj(zero, a0)
        return (zero, one) if op in ("NAND", "NOR") else (one, zero)
    if op in ("XOR", "XNOR"):
        one, zero = FALSE, TRUE
        for a1, a0 in args:
            one, zero = (m.disj(m.conj(one, a0), m.conj(zero, a1)),
                         m.disj(m.conj(one, a1), m.conj(zero, a0)))
        return (zero, one) if op == "XNOR" else (one, zero)
    raise ValueError(f"unknown gate type {op}")


def delta(m: BDD, cs: tuple[Constraint, ...]) -> dict[str, Val]:
    """The least values that a list of constraints asks for at one time."""
    out: dict[str, Val] = {}
    for u, e, g in cs:
        out[u] = join(m, out.get(u, XV), (m.conj(g, e), m.conj(g, m.neg(e))))
    return out


def empty(m: BDD, state: dict[str, Val]) -> int:
    """The assignments where some node is TOP, that is, where the state set is empty."""
    bad = FALSE
    for one, zero in state.values():
        bad = m.disj(bad, m.conj(one, zero))
    return bad


def empty_where_top(m: BDD, state: dict[str, Val], bad: int = FALSE) -> dict[str, Val]:
    """Where bad holds or some node is TOP the state is empty, so set every node to TOP there."""
    bad = m.disj(bad, empty(m, state))
    return {u: (m.disj(one, bad), m.disj(zero, bad)) for u, (one, zero) in state.items()}


def gste(c: Circuit, m: BDD, edges: list[Edge], v0: int = 0) -> Result:
    """Check the assertion graph given by edges, with initial vertex v0, on the circuit c."""
    nodes = c.nodes()
    top = {u: TV for u in nodes}
    allx = {u: XV for u in nodes}
    ants = [delta(m, e.ant) for e in edges]
    sim = [dict(top) for _ in edges]                                       # @line L1
    rounds = 0
    while True:                                                            # @line L2
        rounds += 1
        pre_of: dict[int, dict[str, Val]] = {}
        for v in {e.src for e in edges}:
            pre = dict(allx) if v == v0 else dict(top)
            for j, e in enumerate(edges):
                if e.dst == v:
                    pre = {u: meet(m, pre[u], sim[j][u]) for u in nodes}
            pre_of[v] = pre
        new = []
        for i, e in enumerate(edges):                                      # @line L3
            pre = pre_of[e.src]                                            # @line L4
            sigma = {u: ants[i].get(u, XV) for u in nodes}                 # @line L5
            for s, nxt in c.latches:
                sigma[s] = join(m, sigma[s], pre[nxt])
            for g, op, fanins in c.gates:                                  # @line L6
                sigma[g] = join(m, sigma[g], gate_value(m, op, [sigma[f] for f in fanins]))
            new.append(empty_where_top(m, sigma, empty(m, pre)))           # @line L7
        if new == sim:                                                     # @line L8
            break
        sim = new
    failing: dict[int, int] = {}
    residual = FALSE
    for i, e in enumerate(edges):                                          # @line L9
        ok = TRUE
        for u, v in delta(m, e.cons).items():
            ok = m.conj(ok, leq(m, v, sim[i][u]))
        failing[i] = m.neg(ok)
        residual = m.disj(residual, failing[i])
    return Result(residual == FALSE, residual, failing, sim, rounds)       # @line L10


def is_(node: str, e: int, guard: int = TRUE) -> Constraint:
    """The constraint "if guard then node is e" at the time of the edge."""
    return (node, e, guard)


def counterexample(m: BDD, r: Result) -> Optional[dict[int, int]]:
    return m.sat_one(r.residual)
test_generalized_symbolic_trajectory_evaluation.py 218 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/generalized-symbolic-trajectory-evaluation/. The authors are listed in prov/KNN3V9.jsonl.

import itertools
import random

from bdd import FALSE, TRUE, BDD
from generalized_symbolic_trajectory_evaluation import XV, Circuit, Edge, counterexample, gste, is_

OPS = ("BUF", "NOT", "AND", "OR", "NAND", "NOR", "XOR", "XNOR")


def boolean(op, xs):
    if op == "BUF":
        return xs[0]
    if op == "NOT":
        return 1 - xs[0]
    if op in ("AND", "NAND"):
        return int(all(xs)) ^ (op == "NAND")
    if op in ("OR", "NOR"):
        return int(any(xs)) ^ (op == "NOR")
    return (sum(xs) % 2) ^ (op == "XNOR")


def hold_register(buggy=False):
    """r loads d when en is 1 and keeps its value when en is 0 (the buggy one never clears)."""
    if buggy:
        gates = (("nen", "NOT", ("en",)), ("t1", "AND", ("en", "d")), ("m", "OR", ("t1", "r")))
    else:
        gates = (("nen", "NOT", ("en",)), ("t1", "AND", ("en", "d")),
                 ("t2", "AND", ("nen", "r")), ("m", "OR", ("t1", "t2")))
    return Circuit(("en", "d"), (("r", "m"),), gates)


def hold_graph(m):
    x = m.var(0)
    return [
        Edge(0, 0),                                                   # wait any number of cycles
        Edge(0, 1, ant=(is_("en", TRUE), is_("d", x))),               # load x
        Edge(1, 1, ant=(is_("en", FALSE),), cons=(is_("r", x),)),     # hold: r is x, for ever
    ]


def test_page_example_passes():
    m = BDD()
    r = gste(hold_register(), m, hold_graph(m))
    x = m.var(0)
    assert r.passed
    assert r.rounds == 3
    assert all(v == XV for v in r.sim[0].values())
    assert r.sim[1]["m"] == (x, m.neg(x)) and r.sim[1]["r"] == XV
    assert r.sim[2]["r"] == (x, m.neg(x)) and r.sim[2]["m"] == (x, m.neg(x))


def test_page_example_bug_is_found():
    m = BDD()
    r = gste(hold_register(buggy=True), m, hold_graph(m))
    x = m.var(0)
    assert not r.passed
    assert r.residual == m.neg(x)
    assert r.sim[2]["r"] == (x, FALSE)           # 1 when x is 1, X when x is 0
    assert counterexample(m, r) == {0: 0}
    # The failure is real: r = 1, then load 0, then hold, and r is still 1.
    assert violations(hold_register(buggy=True), m, hold_graph(m), {0: 0}, 3)


# ---------------------------------------------------------------- brute force

def runs(c, length):
    nl, ni = len(c.latches), len(c.inputs)
    for bits in itertools.product((0, 1), repeat=nl + ni * length):
        state = dict(zip([s for s, _ in c.latches], bits[:nl]))
        out = []
        for t in range(length):
            val = dict(state)
            val.update(zip(c.inputs, bits[nl + t * ni: nl + (t + 1) * ni]))
            for g, op, fi in c.gates:
                val[g] = boolean(op, [val[f] for f in fi])
            out.append(val)
            state = {s: val[n] for s, n in c.latches}
        yield out


def meets(m, cs, state, phi):
    return all(not m.evaluate(g, phi) or state[u] == m.evaluate(e, phi) for u, e, g in cs)


def active_edges(m, edges, run, phi, v0=0):
    """For each time k, the edges that end a path from v0 whose antecedents the run meets."""
    out = []
    reach = {v0}
    for state in run:
        act = {i for i, e in enumerate(edges) if e.src in reach and meets(m, e.ant, state, phi)}
        out.append(act)
        reach = {edges[i].dst for i in act}
    return out


def violations(c, m, edges, phi, length):
    found = []
    for run in runs(c, length):
        for k, act in enumerate(active_edges(m, edges, run, phi)):
            for i in act:
                if not meets(m, edges[i].cons, run[k], phi):
                    found.append((run, k, i))
    return found


def random_expr(m, rng, nv):
    k = rng.randrange(5)
    if k == 0:
        return rng.choice((FALSE, TRUE))
    v = m.var(rng.randrange(nv))
    if k == 1:
        return v
    if k == 2:
        return m.neg(v)
    w = m.var(rng.randrange(nv))
    return m.xor(v, w) if k == 3 else m.conj(v, w)


def random_circuit(rng):
    ni, nl = rng.randint(1, 2), rng.randint(1, 2)
    inputs = tuple(f"i{j}" for j in range(ni))
    lat = [f"s{j}" for j in range(nl)]
    nodes = list(inputs) + lat
    gates = []
    for j in range(rng.randint(1, 4)):
        op = rng.choice(OPS)
        ar = 1 if op in ("BUF", "NOT") else 2
        gates.append((f"g{j}", op, tuple(rng.choice(nodes) for _ in range(ar))))
        nodes.append(f"g{j}")
    return Circuit(inputs, tuple((s, rng.choice(nodes)) for s in lat), tuple(gates)), nodes


def random_graph(m, rng, nodes, nv):
    nvert = rng.randint(1, 3)
    edges = []
    for _ in range(rng.randint(1, 5)):
        guard = lambda: TRUE if rng.random() < 0.6 else random_expr(m, rng, nv)  # noqa: E731
        ant = tuple(is_(rng.choice(nodes), random_expr(m, rng, nv), guard()) for _ in range(rng.randint(0, 2)))
        cons = tuple(is_(rng.choice(nodes), random_expr(m, rng, nv), guard()) for _ in range(rng.randint(0, 1)))
        edges.append(Edge(rng.randrange(nvert), rng.randrange(nvert), ant, cons))
    return edges


def below_run(m, val, bit, phi):
    one, zero = m.evaluate(val[0], phi), m.evaluate(val[1], phi)
    return (not one or bit == 1) and (not zero or bit == 0)


def test_random_soundness_against_all_runs():
    rng = random.Random(4242)
    nv = 2
    checked = 0
    passed = 0
    for _ in range(500):
        c, nodes = random_circuit(rng)
        m = BDD()
        edges = random_graph(m, rng, nodes, nv)
        r = gste(c, m, edges)
        n_nodes, n_edges = len(nodes), len(edges)
        assert r.rounds <= 2 * n_nodes * n_edges + 1
        length = max(1, min(5, 9 // len(c.inputs) - len(c.latches)))
        all_runs = list(runs(c, length))
        for bits in itertools.product((0, 1), repeat=nv):
            phi = dict(enumerate(bits))
            bad = m.evaluate(r.residual, phi)
            passed += not bad
            for run in all_runs:
                for k, act in enumerate(active_edges(m, edges, run, phi)):
                    for i in act:
                        # The key lemma: sim(e) lies below every state where a run takes e.
                        for u, val in r.sim[i].items():
                            assert below_run(m, val, run[k][u], phi)
                        if not m.evaluate(r.failing[i], phi):
                            assert meets(m, edges[i].cons, run[k], phi)  # soundness
                        checked += 1
    assert checked > 5000 and passed > 500


def test_chain_with_everything_fixed_is_exact():
    # A chain of edges that sets all inputs at every step and all latches at the
    # first step has one run per assignment, and then the check is exact.
    rng = random.Random(99)
    for _ in range(300):
        c, nodes = random_circuit(rng)
        m = BDD()
        length = rng.randint(1, 3)
        edges = []
        for k in range(length):
            ant = tuple(is_(i, random_expr(m, rng, 2)) for i in c.inputs)
            if k == 0:
                ant += tuple(is_(s, random_expr(m, rng, 2)) for s, _ in c.latches)
            cons = (is_(rng.choice(nodes), random_expr(m, rng, 2)),)
            edges.append(Edge(k, k + 1, ant, cons))
        r = gste(c, m, edges)
        for bits in itertools.product((0, 1), repeat=2):
            phi = dict(enumerate(bits))
            assert bool(m.evaluate(r.residual, phi)) == bool(violations(c, m, edges, phi, length))


def test_unreachable_edge_is_never_checked():
    m = BDD()
    c = Circuit(("a",), (), (("z", "BUF", ("a",)),))
    edges = [Edge(1, 1, cons=(is_("z", TRUE),))]          # no path from v0 reaches vertex 1
    r = gste(c, m, edges)
    assert r.passed and r.sim[0]["z"] == (TRUE, TRUE)


def test_contradicting_antecedent_empties_the_edge():
    m = BDD()
    x = m.var(0)
    c = Circuit(("a",), (("r", "a"),), ())
    edges = [Edge(0, 1, ant=(is_("a", x), is_("a", m.neg(x)))), Edge(1, 1, cons=(is_("r", FALSE),))]
    r = gste(c, m, edges)
    assert r.passed                       # no run can take the first edge, so none reaches vertex 1
    assert r.sim[1]["r"] == (TRUE, TRUE)

History

Seger and Bryant (1995) built STE on a lattice of ternary states, with assertions of bounded depth. Jin Yang and Carl-Johan Seger at Intel extended the antecedent and consequent to the edges of an assertion graph. They presented GSTE at ICCD 2001 and in the IEEE Transactions on VLSI Systems in 2003, with the strong semantics, a semantics over infinite paths, and fixed point algorithms for the check. At FMCAD 2002 they described how the graph and the symbolic constants set the abstraction and how to refine it. GSTE was used at Intel on large circuits where the property reads only part of the state.

References

  1. J. Yang and C.-J. H. Seger, Introduction to generalized symbolic trajectory evaluation, IEEE Transactions on VLSI Systems 11(3), 345 to 353, 2003, assertion graphs with antecedent and consequent labels on edges, the strong semantics over finite initial paths, and the model checking algorithm by a fixed point over the edges
  2. J. Yang and C.-J. H. Seger, Introduction to generalized symbolic trajectory evaluation, ICCD 2001, 360 to 367, the conference version of the journal paper
  3. J. Yang and C.-J. H. Seger, Generalized symbolic trajectory evaluation, abstraction in action, Formal Methods in Computer-Aided Design (FMCAD 2002), LNCS 2517, 70 to 87, 2002, how the assertion graph and the symbolic constants set the abstraction of the check, and how to refine it when a check fails
  4. C.-J. H. Seger and R. E. Bryant, Formal verification by symbolic evaluation of partially-ordered trajectories, Formal Methods in System Design 6(2), 147 to 189, 1995, the lattice of ternary states and the monotone circuit model that GSTE keeps

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example