Algorithm Search⌘K

Algorithmresearch

Observability-based coverage

Also called OCCOM, tag coverage.

Devadas, Ghosh and Keutzer's metric, made fast by OCCOM, that propagates tags from each assignment and counts it covered only if an error there would reach an output.

Time
O(V P n / w) worst
Space
O(n^2 / w) extra
Where
P = the number of gate input pins; V = the number of vectors; n = the number of lines, all of them tag sites; w = the word size
Properties
deterministicnot exactiterative
Origin
Srinivas Devadas, Abhijit Ghosh, Kurt Keutzer, 1996

Observability-based coverage counts a piece of a design as covered by a simulation only when an error at that piece would have reached an output, not merely when the piece was executed. Devadas, Ghosh and Keutzer (1996) attach a tag to the value computed at each assignment of the HDL code, propagate tags through the operators during simulation, and count an assignment as covered when its tag reaches an output. Fallah, Devadas and Keutzer made the computation fast in OCCOM (1998). This page gives a gate-level version of the idea, in which a tag means "this line has the wrong value", proves that a tag at an output means that the error is really observable for that vector, and shows that the converse fails because of reconvergent fanout.

In plain words

Ordinary code coverage asks: did this line run? But a line can run, compute a wrong value, and the wrong value can die before anyone sees it, because a later gate or condition blocks it. Then the test could never catch a bug at that line, although the line was "covered".

This method puts a marker on a value, meaning "suppose this value were wrong". It then follows the marker through the circuit during the normal simulation. At each gate it asks: if only this input were wrong, would the output be wrong too? If yes, the marker moves on. A marker that reaches an output proves that a bug at its source would have shown. A marker that dies means the test saw nothing of that place. The rule is careful: a marker it moves is real, but it sometimes stops a marker that would reach the output.

The problem

Input. A combinational circuit CC of AND, OR, NAND, NOR, XOR, XNOR, NOT and BUF gates in topological order, with nn lines (primary inputs and gate outputs) and PP gate input pins; a set VV of input vectors; and a set of sites, here all lines.

The exact target. For a vector vv and a site tt, let CtC^t be the circuit with the value of line tt complemented, as seen by every gate that reads tt. Site tt is observable for vv when some primary output of CtC^t differs from that of CC. Equivalently, if the circuit is cut at tt and tt becomes a free variable, the Boolean difference of some output with respect to tt is 1 at vv. The exact observability coverage of VV is the fraction of sites that are observable for at least one vector of VV.

What is computed. For each vector, a set of tagged sites, by one pass over the circuit, and the fraction of sites tagged at an output for at least one vector. The tagged set is contained in the observable set (proved below). It is equal on circuits without reconvergent fanout, and smaller in general.

Not a code metric, not fault coverage. Flipping line tt under vv is the single stuck-at fault "tt stuck at the complement of its value", so at gate level the exact target is the set of stem faults that the vectors detect, in the sense of fault simulation. The question is different: here the vectors come from functional simulation and the sites stand for design errors, and the number is a coverage of the design, not the fault coverage of a manufacturing test.

The algorithm

Every line starts with its own tag. A gate passes the tags of input iji_j to its output when every other input has a value that does not decide the gate alone (a non-controlling value: 1 for AND and NAND, 0 for OR and NOR, anything for XOR, XNOR, NOT and BUF) and does not itself depend on the tagged site. The second condition is what makes the rule sound: a tag that arrives at a gate along two paths could cancel or change the gate in a way that the rule does not track, so it is dropped. Fin(ℓ)\mathrm{Fin}(\ell) is the set of lines on which ℓ\ell depends, ℓ\ell included.

  1. TagCoverage(C, V)
  2. 1for each line ℓ in topological order: Fin(ℓ) ← {ℓ} ∪ ⋃ of Fin(i) over the inputs i of ℓ
  3. 2Covered ← ∅
  4. 3for each vector v in V:
  5. 4simulate C on v to get val(ℓ) for every line ℓ
  6. 5for each primary input x: Tag(x) ← {x}
  7. 6for each gate g with output ℓ and inputs i_1, ..., i_k, in topological order:
  8. 7Tag(ℓ) ← {ℓ}
  9. 8for j ← 1 to k:
  10. 9if no i_m with m ≠ j has the controlling value of g then
  11. 10Tag(ℓ) ← Tag(ℓ) ∪ (Tag(i_j) \ ⋃ of Fin(i_m) over m ≠ j)
  12. 11Covered ← Covered ∪ ⋃ of Tag(o) over the primary outputs o
  13. 12return Covered and |Covered| / n

Line L1 computes the cones once. Lines L4 to L10 are one simulation with tag sets. Line L9 is the sensitization test of path tracing: the other inputs must let a change through. Line L10 removes the sites that also reach the gate by another input, which is where reconvergence is cut off. Line L11 collects the sites whose tags reached an output.

Example

Take the inputs x,b,c,dx, b, c, d, the gates p=AND(x,b)p = \mathrm{AND}(x, b), q=AND(x,c)q = \mathrm{AND}(x, c), y=OR(p,q)y = \mathrm{OR}(p, q) and z=AND(q,d)z = \mathrm{AND}(q, d), and the outputs yy and zz. The line xx fans out to pp and qq, and the two paths meet again at yy. There are 8 sites.

Vector 1: (x,b,c,d)=(0,1,1,0)(x, b, c, d) = (0, 1, 1, 0). The values are p=q=y=z=0p = q = y = z = 0.

line rule applied Tag
p=AND(x,b)p = \mathrm{AND}(x, b) b=1b = 1 passes xx; x=0x = 0 blocks bb {p,x}\{p, x\}
q=AND(x,c)q = \mathrm{AND}(x, c) c=1c = 1 passes xx; x=0x = 0 blocks cc {q,x}\{q, x\}
y=OR(p,q)y = \mathrm{OR}(p, q) q=0q = 0 passes pp, minus Fin(q)∋x\mathrm{Fin}(q) \ni x; p=0p = 0 passes qq, minus Fin(p)∋x\mathrm{Fin}(p) \ni x {y,p,q}\{y, p, q\}
z=AND(q,d)z = \mathrm{AND}(q, d) d=0d = 0 blocks qq; q=0q = 0 blocks dd {z}\{z\}

The tagged sites at the outputs are {p,q,y,z}\{p, q, y, z\}, 4 of 8. Flipping each site and simulating gives the observable set {x,p,q,y,z}\{x, p, q, y, z\}, 5 of 8. The site xx is observable (flipping it makes p=q=y=1p = q = y = 1) but its tag was dropped at yy, because both inputs of yy depend on xx.

Vector 2: (1,0,1,1)(1, 0, 1, 1). The values are p=0p = 0, q=1q = 1, y=1y = 1, z=1z = 1. The tags are Tag(p)={p,b}\mathrm{Tag}(p) = \{p, b\}, Tag(q)={q,x,c}\mathrm{Tag}(q) = \{q, x, c\}, Tag(y)={y,q,c}\mathrm{Tag}(y) = \{y, q, c\} (the input q=1q = 1 is controlling for the OR, so pp passes nothing, and xx is removed from the tags of qq because x∈Fin(p)x \in \mathrm{Fin}(p)) and Tag(z)={z,q,x,c,d}\mathrm{Tag}(z) = \{z, q, x, c, d\}. The tagged sites at the outputs are {x,c,d,q,y,z}\{x, c, d, q, y, z\}, and flipping each site gives the same set.

Both vectors. The tag coverage is {p,q,y,z}∪{x,c,d,q,y,z}\{p, q, y, z\} \cup \{x, c, d, q, y, z\}, 7 of 8, equal to the exact coverage. Only bb is missed: it is observable only when x=1x = 1 and c=0c = 0, and neither vector has that. Every line of this circuit is evaluated on every vector, so a line or toggle count of the gates says nothing about bb, while the tag coverage points at it.

Correctness

The proof is in proofs/correctness.md. It shows, by induction over the lines in topological order:

  • Cones. If t∉Fin(ℓ)t \notin \mathrm{Fin}(\ell), flipping tt does not change ℓ\ell.
  • Soundness. If t∈Tag(ℓ)t \in \mathrm{Tag}(\ell), flipping tt changes ℓ\ell. At line L10 exactly one input of the gate changes, the others are non-controlling, and a gate whose other inputs are non-controlling passes a change of one input. So every tagged site at an output is observable for its vector, and the tag coverage is at most the exact coverage.
  • Exactness without reconvergence. If every line feeds at most one gate input, the tagged sets equal the observable sets.
  • Not complete in general. Vector 1 of the example has xx observable and not tagged.

These are proved for the gate-level model of this page. The papers state their tag calculus for HDL operators on words, where the claims of soundness and the trade-offs between rules are their own; this page does not reproduce them.

Proof: Observability tags are sound, exact on fanout-free circuits, and not complete in generalfull

Setting. CC is a combinational circuit whose lines are its primary inputs and the outputs of its gates, listed in topological order. Each gate has a type in AND, OR, NAND, NOR, XOR, XNOR, NOT and BUF. The controlling value of AND and NAND is 0, of OR and NOR it is 1, and XOR, XNOR, NOT and BUF have none; a value is non-controlling for a gate when it is not the controlling value. Fix an input vector vv, and let val(ℓ)\mathrm{val}(\ell) be the value of line ℓ\ell. For a site tt, the flipped circuit CtC^t is CC with the value of line tt replaced by its complement, seen by every gate that reads tt; its values are valt(ℓ)\mathrm{val}^t(\ell). Site tt is observable for vv when valt(o)≠val(o)\mathrm{val}^t(o) \ne \mathrm{val}(o) for some primary output oo. Fin(ℓ)\mathrm{Fin}(\ell) is the set computed at line L1: ℓ\ell and every line on which ℓ\ell depends. Tag(ℓ)\mathrm{Tag}(\ell) is the set computed at lines L5 to L10 for vv.

Fact (gates with one changed input). Let a gate have inputs i1,…,iki_1, \ldots, i_k, and suppose that only iji_j changes its value. If every other input is non-controlling for the gate, the output changes. If some other input has the controlling value, the output does not change.

Proof. For AND with every other input at 1, the output equals iji_j, so it changes; with some other input at 0, the output is 0 before and after. NAND is the complement of AND. OR and NOR are the duals with 0 and 1 exchanged. For XOR the output is iji_j XOR the parity of the other inputs, which do not change, so the output changes; XNOR is its complement. NOT and BUF have one input. □\square

Lemma 1 (cones). If t∉Fin(ℓ)t \notin \mathrm{Fin}(\ell), then valt(ℓ)=val(ℓ)\mathrm{val}^t(\ell) = \mathrm{val}(\ell).

Proof. Induction over the lines in topological order. A primary input ℓ≠t\ell \ne t has the same value in CC and CtC^t. A gate output ℓ≠t\ell \ne t with t∉Fin(ℓ)t \notin \mathrm{Fin}(\ell) has t∉Fin(i)t \notin \mathrm{Fin}(i) for each of its inputs ii, because Fin(ℓ)⊇Fin(i)\mathrm{Fin}(\ell) \supseteq \mathrm{Fin}(i). By the induction hypothesis its inputs have the same values in both circuits, and ℓ\ell is computed by the same gate, so ℓ\ell has the same value. □\square

Lemma 2 (soundness). If t∈Tag(ℓ)t \in \mathrm{Tag}(\ell), then valt(ℓ)≠val(ℓ)\mathrm{val}^t(\ell) \ne \mathrm{val}(\ell).

Proof. Induction over the lines in topological order. If t=ℓt = \ell, the value of ℓ\ell is complemented in CtC^t by definition; this covers line L5 and line L7. Otherwise ℓ\ell is the output of a gate with inputs i1,…,iki_1, \ldots, i_k, and tt was added at line L10 for some jj. Then t∈Tag(ij)t \in \mathrm{Tag}(i_j), t∉Fin(im)t \notin \mathrm{Fin}(i_m) for every m≠jm \ne j, and every imi_m with m≠jm \ne j has a non-controlling value (line L9). By the induction hypothesis iji_j changes in CtC^t. By Lemma 1 no other input changes. The value of ℓ\ell is not complemented by the flip, since ℓ≠t\ell \ne t. By the Fact, ℓ\ell changes. □\square

Theorem 1 (tags reaching an output are observable). Every site in ⋃oTag(o)\bigcup_o \mathrm{Tag}(o), the set added to Covered at line L11 for vv, is observable for vv. Hence the coverage returned at line L12 is at most the exact observability coverage of the same vector set.

Proof. Apply Lemma 2 to the primary output oo with t∈Tag(o)t \in \mathrm{Tag}(o). The second sentence follows because Covered is a union over the vectors of sets that are each contained in the exact set of that vector. ■\blacksquare

Theorem 2 (exact on fanout-free circuits). If every line of CC feeds at most one gate input, then for every line ℓ\ell, t∈Tag(ℓ)t \in \mathrm{Tag}(\ell) if and only if valt(ℓ)≠val(ℓ)\mathrm{val}^t(\ell) \ne \mathrm{val}(\ell).

Proof. One direction is Lemma 2. For the other, use induction over the lines in topological order, and suppose that ℓ\ell changes in CtC^t. If ℓ=t\ell = t, then t∈Tag(ℓ)t \in \mathrm{Tag}(\ell) by line L5 or line L7. If ℓ\ell is a primary input other than tt, it cannot change. Otherwise ℓ≠t\ell \ne t is the output of a gate with inputs i1,…,iki_1, \ldots, i_k. Since ℓ\ell changes and the gate is the same in both circuits, some input changes, and by Lemma 1 that input iji_j has t∈Fin(ij)t \in \mathrm{Fin}(i_j). In a circuit in which each line feeds at most one gate input, the sets Fin(i1),…,Fin(ik)\mathrm{Fin}(i_1), \ldots, \mathrm{Fin}(i_k) are pairwise disjoint: a line in two of them would reach the gate along two paths that enter it at different pins, and the line where the two paths first part would feed two gate inputs. So t∉Fin(im)t \notin \mathrm{Fin}(i_m) for m≠jm \ne j, and by Lemma 1 only iji_j changes. By the Fact, every imi_m with m≠jm \ne j is non-controlling, since otherwise ℓ\ell would not change. By the induction hypothesis t∈Tag(ij)t \in \mathrm{Tag}(i_j). So the test of line L9 passes for jj, and line L10 adds tt to Tag(ℓ)\mathrm{Tag}(\ell). ■\blacksquare

The converse of Theorem 1 fails. Take the inputs x,b,c,dx, b, c, d, the gates p=AND(x,b)p = \mathrm{AND}(x, b), q=AND(x,c)q = \mathrm{AND}(x, c), y=OR(p,q)y = \mathrm{OR}(p, q), z=AND(q,d)z = \mathrm{AND}(q, d), the outputs yy and zz, and v=(x,b,c,d)=(0,1,1,0)v = (x, b, c, d) = (0, 1, 1, 0). Then p=q=y=z=0p = q = y = z = 0. In CxC^x, p=q=1p = q = 1 and y=1y = 1, so xx is observable. The algorithm puts xx in Tag(p)\mathrm{Tag}(p) and Tag(q)\mathrm{Tag}(q). At yy, for the input pp the other input qq has x∈Fin(q)x \in \mathrm{Fin}(q), and for the input qq the other input pp has x∈Fin(p)x \in \mathrm{Fin}(p), so line L10 adds xx for neither. At zz, the input d=0d = 0 is controlling for the input qq. So x∉Tag(y)∪Tag(z)x \notin \mathrm{Tag}(y) \cup \mathrm{Tag}(z), although xx is observable. The loss comes from reconvergent fanout, which Theorem 2 excludes.

Relation to the Boolean difference. Cut the circuit at line tt, so that tt becomes a free variable τ\tau and each output oo becomes a function o(τ,v)o(\tau, v). Site tt is observable for vv exactly when the Boolean difference ∂o/∂τ\partial o / \partial \tau is 1 at vv for some output oo. Theorem 1 says that the tag rule computes an under-approximation of this set, and Theorem 2 that it computes the set exactly for fanout-free circuits. Flipping line tt under vv is also the single stuck-at fault "tt stuck at the complement of val(t)\mathrm{val}(t)", so tt is observable for vv exactly when vv detects that fault.

Complexity

On a word RAM with sets of sites as bit vectors of ⌈n/w⌉\lceil n / w \rceil words:

  • Cones. Line L1 does one union per pin, O(Pn/w)O(P n / w) time, and stores nn sets, O(n2/w)O(n^2 / w) words.
  • One vector. The simulation is O(n+P)O(n + P). For a gate with kk inputs, prefix and suffix unions of the cones give the union over m≠jm \ne j for every jj with O(k)O(k) unions in all, so lines L6 to L10 cost O(Pn/w)O(P n / w).
  • All vectors. O(VPn/w)O(V P n / w) time in the worst case, and O(n2/w)O(n^2 / w) extra space.

The exact answer costs about the same at gate level. One extra simulation per site and vector gives the observable sets in O(Vn(n+P))O(V n (n + P)) word operations, or O(Vn(n+P)/w)O(V n (n + P) / w) with bit-parallel simulation of ww flips at once. Deductive fault simulation of the stem faults, which keeps exact lists of faults per line, also runs in one pass per vector. So the tag rule is not a speed-up at gate level. Its value is on HDL code, where values are words and an operator such as an adder or a comparison has no simple exact rule for a change in one operand, while a conservative tag rule per operator is easy to state.

Properties

  • Sound, not complete. Tagged implies observable for that vector; the converse fails on reconvergent fanout.
  • Monotone in the vector set. Adding vectors can only add covered sites.
  • Deterministic. The result depends only on the circuit and the vectors.
  • A lower bound on detection. At gate level, a covered site tt means that some vector detects the stuck-at fault on the stem tt at the complement of its value under that vector.

Variants and improvements

  • The HDL metric. Devadas, Ghosh and Keutzer tag the value assigned by each statement of the HDL description and propagate tags through the operators of the code by their tag calculus. A statement is covered when its tag reaches an output. Code coverage asks only whether the statement ran.
  • OCCOM. Fallah, Devadas and Keutzer compute the metric efficiently during simulation of the HDL description.
  • Sequential designs. Tags enter registers and can reach an output in a later cycle. A site is covered when its tag reaches an output at any later cycle of the run, so the propagation runs along the simulation in time.
  • Exact sets by deductive rules. Use the rules of deductive fault simulation on the flip faults: with no input at the controlling value, the output set is the union of the input sets (for XOR and XNOR, the sites that are in an odd number of them); otherwise it is the set of sites that are in the set of every controlling input and in no set of a non-controlling input; then add the output line itself. These sets are exact for single errors in a combinational circuit, and line L10 is a cheaper and weaker form of them.
  • Path tracing. Critical path tracing walks backward from the outputs along sensitized inputs and treats stems with reconvergent fanout by a separate check, which gives the exact set at gate level.
  • Mutation-style checks. Inserting an actual change into the code (an operator replaced, a constant changed) and running the suite again gives an exact answer for that change, at the cost of one run per change.

When to use it

Use it when line and decision coverage are high but the suite may still miss bugs because wrong values are masked before any checker sees them. It points at statements or lines whose effects never reach an output. Use exact flip simulation or deductive fault simulation instead when the design is a small gate-level netlist and the exact answer is cheap. Do not read a tag coverage of 100 percent as proof that every bug is found: a site is covered by one error effect for one vector, not by every possible wrong value, and an output that is reached must still be checked by the test bench.

Pitfalls

  • Reading untagged as unobservable. The rule is sound only in one direction. An untagged site may be observable through reconvergent paths, as in vector 1 of the example.
  • Dropping the cone test. Without the condition t∉Fin(im)t \notin \mathrm{Fin}(i_m) at line L10, the rule is not sound: if two inputs of an AND both change, one from 0 to 1 and the other from 1 to 0, the output can stay the same while the rule moves the tag.
  • Outputs that nobody checks. Reaching a primary output is the model of observation. If the test bench compares only some outputs, or only at some cycles, those are the outputs to use.
  • One error value. At gate level a flip is the only possible error. On words, a tag for "the value is wrong" stands for many possible wrong values, and a rule that is sound for one of them may not be for another.
  • Confusing it with fault coverage. The number counts design sites under functional vectors. It is not the fault coverage of a manufacturing test, even though it uses the same propagation ideas.

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.

observability_based_coverage.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/observability-based-coverage/. The authors are listed in prov/XHG8NR.jsonl.
"""Observability tags on a gate-level circuit, after Devadas, Ghosh and Keutzer (1996).

A circuit has named primary inputs, gates in topological order and named
primary outputs. Every line (a primary input or a gate output) is a tag site.
A tag on line t stands for an error that flips the value of t. For one input
vector, tag_sets() computes for every line the set of sites whose tag reaches
it by the rule of the page: a tag passes a gate input when every other input
of the gate has a non-controlling value and does not depend on the tagged site.
The rule is sound (a tag at a line means that flipping the site flips the
line) and not complete. observable_sites() is the exact brute force.
"""

from fractions import Fraction

GATE_TYPES = ("AND", "OR", "NAND", "NOR", "XOR", "XNOR", "NOT", "BUF")
# The controlling input value of each gate type; None means no controlling value.
CONTROLLING = {"AND": 0, "NAND": 0, "OR": 1, "NOR": 1,
               "XOR": None, "XNOR": None, "NOT": None, "BUF": None}


class Circuit:
    """A combinational circuit. gates is a list of (name, type, [input names])."""

    def __init__(self, inputs, gates, outputs):
        self.inputs = list(inputs)
        self.gates = [(name, kind, list(ins)) for name, kind, ins in gates]
        self.outputs = list(outputs)
        seen = set(self.inputs)
        for name, kind, ins in self.gates:
            if kind not in GATE_TYPES:
                raise ValueError("unknown gate type " + kind)
            if kind in ("NOT", "BUF") and len(ins) != 1:
                raise ValueError(name + " needs one input")
            if kind not in ("NOT", "BUF") and len(ins) < 2:
                raise ValueError(name + " needs two or more inputs")
            for x in ins:
                if x not in seen:
                    raise ValueError("gates are not in topological order at " + name)
            if name in seen:
                raise ValueError("line defined twice: " + name)
            seen.add(name)
        for o in self.outputs:
            if o not in seen:
                raise ValueError("unknown output " + o)

    def lines(self):
        return self.inputs + [name for name, _, _ in self.gates]


def gate_value(kind, values):
    if kind == "AND":
        return int(all(values))
    if kind == "OR":
        return int(any(values))
    if kind == "NAND":
        return 1 - int(all(values))
    if kind == "NOR":
        return 1 - int(any(values))
    if kind == "XOR":
        return sum(values) % 2
    if kind == "XNOR":
        return 1 - sum(values) % 2
    if kind == "NOT":
        return 1 - values[0]
    return values[0]  # BUF


def simulate(circuit, vector, flip=None):
    """Values of all lines for vector (a dict input -> 0 or 1).

    If flip names a line, that line takes the complement of its computed value,
    and every gate that reads it sees the complement.
    """
    val = {}
    for x in circuit.inputs:
        val[x] = vector[x]
        if x == flip:
            val[x] = 1 - val[x]
    for name, kind, ins in circuit.gates:
        val[name] = gate_value(kind, [val[x] for x in ins])
        if name == flip:
            val[name] = 1 - val[name]
    return val


def fanin_cones(circuit):
    """Fin(l): the set of lines on which line l depends, l included."""
    fin = {x: {x} for x in circuit.inputs}
    for name, _, ins in circuit.gates:
        cone = {name}
        for x in ins:
            cone |= fin[x]
        fin[name] = cone  # @line L1
    return fin


def tag_sets(circuit, vector, fin=None):
    """Return (values, tags): tags[l] is the set of sites whose tag reaches line l."""
    if fin is None:
        fin = fanin_cones(circuit)
    val = simulate(circuit, vector)  # @line L4
    tag = {x: {x} for x in circuit.inputs}  # @line L5
    for name, kind, ins in circuit.gates:  # @line L6
        ctrl = CONTROLLING[kind]
        out = {name}  # @line L7
        k = len(ins)
        # prefix and suffix unions of the cones, so each pin costs O(1) unions
        prefix = [set()]
        for x in ins:
            prefix.append(prefix[-1] | fin[x])
        suffix = [set()]
        for x in reversed(ins):
            suffix.append(suffix[-1] | fin[x])
        suffix.reverse()
        bad = [ctrl is not None and val[x] == ctrl for x in ins]
        n_bad = sum(bad)
        for j, x in enumerate(ins):  # @line L8
            others_bad = n_bad - (1 if bad[j] else 0)
            if others_bad == 0:  # @line L9
                blocked = prefix[j] | suffix[j + 1]
                out |= tag[x] - blocked  # @line L10
        tag[name] = out
    return val, tag


def tagged_sites(circuit, vector, fin=None):
    """Sites whose tag reaches some primary output for this vector."""
    _, tag = tag_sets(circuit, vector, fin)
    reached = set()
    for o in circuit.outputs:
        reached |= tag[o]  # @line L11
    return reached


def observable_sites(circuit, vector):
    """Brute force: sites whose flip changes some primary output for this vector."""
    good = simulate(circuit, vector)
    result = set()
    for t in circuit.lines():
        bad = simulate(circuit, vector, flip=t)
        if any(bad[o] != good[o] for o in circuit.outputs):
            result.add(t)
    return result


def tag_coverage(circuit, vectors, sites=None):
    """Observability-based coverage of a vector set: (covered sites, ratio as a Fraction)."""
    if sites is None:
        sites = circuit.lines()
    sites = list(sites)
    fin = fanin_cones(circuit)
    covered = set()  # @line L2
    for v in vectors:  # @line L3
        covered |= tagged_sites(circuit, v, fin)
    covered &= set(sites)
    return covered, Fraction(len(covered), len(sites))  # @line L12


def exact_coverage(circuit, vectors, sites=None):
    """The same ratio with the brute-force observable sets."""
    if sites is None:
        sites = circuit.lines()
    sites = list(sites)
    covered = set()
    for v in vectors:
        covered |= observable_sites(circuit, v)
    covered &= set(sites)
    return covered, Fraction(len(covered), len(sites))


def example_circuit():
    """The circuit of the page: x reconverges at the OR gate y."""
    return Circuit(
        inputs=["x", "b", "c", "d"],
        gates=[("p", "AND", ["x", "b"]),
               ("q", "AND", ["x", "c"]),
               ("y", "OR", ["p", "q"]),
               ("z", "AND", ["q", "d"])],
        outputs=["y", "z"])


if __name__ == "__main__":
    c = example_circuit()
    vectors = [dict(x=0, b=1, c=1, d=0), dict(x=1, b=0, c=1, d=1)]
    for v in vectors:
        val, tag = tag_sets(c, v)
        print(v, {l: sorted(tag[l]) for l in c.lines()})
        print("  tagged", sorted(tagged_sites(c, v)), "exact", sorted(observable_sites(c, v)))
    print(tag_coverage(c, vectors), exact_coverage(c, vectors))
test_observability_based_coverage.py 156 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/observability-based-coverage/. The authors are listed in prov/XHG8NR.jsonl.

import itertools
import random
from fractions import Fraction

import pytest

from observability_based_coverage import (
    GATE_TYPES, Circuit, example_circuit, exact_coverage, fanin_cones,
    observable_sites, simulate, tag_coverage, tag_sets, tagged_sites)


def all_vectors(circuit):
    for bits in itertools.product((0, 1), repeat=len(circuit.inputs)):
        yield dict(zip(circuit.inputs, bits))


def random_kind(rng, k):
    if k == 1:
        return rng.choice(("NOT", "BUF"))
    return rng.choice(("AND", "OR", "NAND", "NOR", "XOR", "XNOR"))


def random_circuit(rng):
    n = rng.randint(2, 5)
    inputs = ["i%d" % i for i in range(n)]
    lines = list(inputs)
    gates = []
    for g in range(rng.randint(1, 9)):
        k = rng.choice((1, 2, 2, 2, 3))
        k = min(k, len(lines))
        ins = rng.sample(lines, k)
        kind = random_kind(rng, k)
        name = "g%d" % g
        gates.append((name, kind, ins))
        lines.append(name)
    outs = sorted(set(rng.sample(lines, rng.randint(1, 3))) | {lines[-1]})
    return Circuit(inputs, gates, outs)


def random_fanout_free_circuit(rng):
    """Every line feeds at most one gate input."""
    inputs = []
    pool = []

    def fresh_input():
        name = "i%d" % len(inputs)
        inputs.append(name)
        return name

    for _ in range(rng.randint(1, 3)):
        pool.append(fresh_input())
    gates = []
    for g in range(rng.randint(1, 8)):
        k = rng.choice((1, 2, 2, 3))
        while len(pool) < k:
            pool.append(fresh_input())
        ins = rng.sample(pool, k)
        for x in ins:
            pool.remove(x)
        name = "g%d" % g
        gates.append((name, random_kind(rng, k), ins))
        pool.append(name)
    return Circuit(inputs, gates, sorted(pool))


def test_example_of_the_page():
    c = example_circuit()
    v1 = dict(x=0, b=1, c=1, d=0)
    v2 = dict(x=1, b=0, c=1, d=1)
    _, tag = tag_sets(c, v1)
    assert tag["p"] == {"p", "x"} and tag["q"] == {"q", "x"}
    assert tag["y"] == {"y", "p", "q"} and tag["z"] == {"z"}
    assert tagged_sites(c, v1) == {"p", "q", "y", "z"}
    assert observable_sites(c, v1) == {"x", "p", "q", "y", "z"}
    assert tagged_sites(c, v2) == observable_sites(c, v2) == {"x", "c", "d", "q", "y", "z"}
    covered, ratio = tag_coverage(c, [v1, v2])
    assert ratio == Fraction(7, 8) and covered == set(c.lines()) - {"b"}
    assert exact_coverage(c, [v1, v2]) == (covered, ratio)
    assert tag_coverage(c, [v1])[1] == Fraction(4, 8)
    assert exact_coverage(c, [v1])[1] == Fraction(5, 8)


def test_converse_fails_on_reconvergence():
    c = example_circuit()
    v = dict(x=0, b=1, c=1, d=0)
    assert "x" not in tagged_sites(c, v)
    good = simulate(c, v)
    bad = simulate(c, v, flip="x")
    assert good["y"] == 0 and bad["y"] == 1


def test_cones_lemma_on_random_circuits():
    rng = random.Random(11)
    for _ in range(80):
        c = random_circuit(rng)
        fin = fanin_cones(c)
        for v in all_vectors(c):
            good = simulate(c, v)
            for t in c.lines():
                bad = simulate(c, v, flip=t)
                for line in c.lines():
                    if t not in fin[line]:
                        assert bad[line] == good[line]


def test_soundness_on_random_circuits():
    rng = random.Random(2024)
    strict = 0
    for _ in range(180):
        c = random_circuit(rng)
        fin = fanin_cones(c)
        for v in all_vectors(c):
            good, tag = tag_sets(c, v, fin)
            flipped = {t: simulate(c, v, flip=t) for t in c.lines()}
            for line in c.lines():
                for t in tag[line]:
                    assert flipped[t][line] != good[line]
            tagged = tagged_sites(c, v, fin)
            exact = observable_sites(c, v)
            assert tagged <= exact
            strict += len(exact - tagged)
    assert strict > 0  # the rule is not complete on these circuits


def test_exact_on_fanout_free_circuits():
    rng = random.Random(7)
    for _ in range(250):
        c = random_fanout_free_circuit(rng)
        fin = fanin_cones(c)
        for v in all_vectors(c):
            assert tagged_sites(c, v, fin) == observable_sites(c, v)


def test_coverage_never_exceeds_exact():
    rng = random.Random(99)
    for _ in range(100):
        c = random_circuit(rng)
        vectors = list(all_vectors(c))
        rng.shuffle(vectors)
        some = vectors[: rng.randint(1, len(vectors))]
        tc, tr = tag_coverage(c, some)
        ec, er = exact_coverage(c, some)
        assert tc <= ec and tr <= er


def test_gate_types_and_errors():
    assert set(GATE_TYPES) == {"AND", "OR", "NAND", "NOR", "XOR", "XNOR", "NOT", "BUF"}
    with pytest.raises(ValueError):
        Circuit(["a"], [("g", "AND", ["a", "h"])], ["g"])
    with pytest.raises(ValueError):
        Circuit(["a"], [("g", "NOT", ["a", "a"])], ["g"])
    with pytest.raises(ValueError):
        Circuit(["a", "b"], [("g", "MUX", ["a", "b"])], ["g"])

History

Devadas, Ghosh and Keutzer proposed in 1996 to count an assignment of the HDL code as covered only when an error there propagates to an output, and gave a calculus of tags for this. The idea is close to the sensitization of paths in test generation and fault simulation, applied to design errors instead of manufacturing faults. Fallah, Devadas and Keutzer gave the efficient computation OCCOM at DAC 1998 and in IEEE TCAD in 2001. Tasiran and Keutzer place the metric among the code and state-machine metrics in their 2001 survey.

References

  1. S. Devadas, A. Ghosh and K. Keutzer, An observability-based code coverage metric for functional simulation, Proceedings of the IEEE/ACM International Conference on Computer-Aided Design (ICCAD), 418 to 425, 1996, the tags attached to assignments, the tag calculus for the operators of the code, and the definition of an assignment as covered when its tag reaches an output
  2. F. Fallah, S. Devadas and K. Keutzer, OCCOM, efficient computation of observability-based code coverage metrics for functional verification, Proceedings of the 35th Design Automation Conference, 152 to 157, 1998, the efficient computation of the tag metric during simulation of the HDL description
  3. F. Fallah, S. Devadas and K. Keutzer, OCCOM, efficient computation of observability-based code coverage metrics for functional verification, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 20(8), 1003 to 1015, 2001, the journal version of OCCOM (general locator)
  4. Serdar Tasiran and Kurt Keutzer, Coverage metrics for functional validation of hardware designs, IEEE Design and Test of Computers 18(4), 36 to 45, 2001, the section on observability-based metrics and their place among code coverage metrics
  5. Miron Abramovici, Melvin A. Breuer and Arthur D. Friedman, Digital Systems Testing and Testable Design, IEEE Press, 1994, the chapter on fault simulation (deductive fault simulation and the rules for controlling values), the source of the propagation rules used here

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