An Assertion-Based Program Logic for Probabilistic Programs

,


Introduction
The most mature systems for deductive verification of randomized algorithms are expectation-based techniques; seminal examples include PPDL [25] and pGCL [31].These approaches reason about expectations, functions E from states to real numbers, 7 propagating them backwards through a program until they are transformed into a mathematical function of the input.Expectationbased systems are both theoretically elegant [21,13,32,20]

and practically useful;
This is the full version of the paper. 7Treating a program as a function from input states s to output distributions µ(s), the expected value of E on µ(s) is an expectation.
implementations have verified numerous randomized algorithms [16,18].However, properties involving multiple probabilities or expected values can be cumbersome to verify-each expectation must be analyzed separately.An alternative approach envisioned by Ramshaw [34] is to work with predicates over distributions.A direct comparison with expectation-based techniques is difficult, as the approaches are quite different.In broad strokes, assertion-based systems can verify richer properties in one shot and have specifications that are arguably more intuitive, especially for reasoning about loops, while expectationbased approaches can transform expectations mechanically and can reason about non-determinism.However, the comparison is not very meaningful for an even simpler reason: existing assertion-based systems such as [7,15,35] are not as well developed as their expectation-based counterparts.
Restrictive assertions.Existing probabilistic program logics do not support reasoning about expected values, only probabilities.As a result, many properties about average-case behavior are not even expressible.Inconvenient reasoning for loops.The Hoare logic rule for deterministic loops does not directly generalize to probabilistic programs.Existing assertionbased systems either forbid loops, or impose complex semantic side conditions to control which assertions can be used as loop invariants.Such side conditions are restrictive and difficult to establish.No support for external or adversarial code.A strength of expectationbased techniques is reasoning about programs combining probabilities and non-determinism.In contrast, Morgan and McIver [27] argue that assertionbased techniques cannot support compositional reasoning for such a combination.For many applications, including cryptography, we would still like to reason about a commonly-encountered special case: programs using external or adversarial code.Many security properties in cryptography boil down to analyzing such programs, but existing program logics do not support adversarial code.Few concrete implementations.There are by now several independent implementations of expectation-based techniques, capable of verifying interesting probabilistic programs.In contrast, there are only scattered implementations of probabilistic program logics.
These limitations raise two points.Compared to expectation-based approaches: 1. Can assertion-based approaches achieve similar expressivity?2. Are there situations where assertion-based approaches are more suitable?
In this paper, we give positive evidence for both of these points. 8Towards the first point, we give a new assertion-based logic Ellora for probabilistic programs, overcoming limitations in existing probabilistic program logics.Ellora supports a rich set of assertions that can express concepts like expected values and probabilistic independence, and novel proof rules for verifying loops and adversarial code.We prove that Ellora is sound and relatively complete.Towards the second point, we evaluate Ellora in two ways.First, we define a new logic for proving probabilistic independence and distribution law propertieswhich are difficult to capture with expectation-based approaches-and then embed it into Ellora.This sub-logic is more narrowly focused than Ellora, but supports more concise reasoning for the target assertions.Our embedding demonstrates that the assertion-based approach can be flexibly integrated with intuitive, special-purpose reasoning principles.To further support this claim, we also provide an embedding of the Union Bound logic, a program logic for reasoning about accuracy bounds [4].Then, we develop a full-featured implementation of Ellora in the EasyCrypt theorem prover and exercise the logic by mechanically verifying a series of complex randomized algorithms.Our results suggest that the assertion-based approach can indeed be practically viable.
Abstract logic.To ease the presentation, we present Ellora in two stages.First, we consider an abstract version of the logic where assertions are general predicates over distributions, with no compact syntax.Our abstract logic makes two contributions: reasoning for loops, and for adversarial code.
Reasoning about Loops.Proving a property of a probabilistic loop typically requires establishing a loop invariant, but the class of loop invariants that can be soundly used depends on the termination behavior-stronger termination assumptions allows richer loop invariants.We identify three classes of assertions that can be used for reasoning about probabilistic loops, and provide a proof rule for each one: arbitrary assertions for certainly terminating loops, i.e. loops that terminate in a finite amount of iterations; topologically closed assertions for almost surely terminating loops, i.e. loops terminating with probability 1; downwards closed assertions for arbitrary loops.
The definition of topologically closed assertion is reminiscent of Ramshaw [34]; the stronger notion of downwards closed assertion appears to be new.
Besides broadening the class of loops that can be analyzed, our rules often enable simpler proofs.For instance, if the loop is certainly terminating, then there is no need to prove semantic side-conditions.Likewise, there is no need to consider the termination behavior of the loop when the invariant is downwards and topologically closed.For example, in many applications in cryptography, the target property is that a "bad" event has low probability: Pr [E] ≤ k.In our framework this assertion is downwards and topologically closed, so it can be a loop invariant regardless of the termination behavior.
Reasoning about Adversaries.Existing assertion-based logics cannot reason about probabilistic programs with adversarial code.Adversaries are special probabilistic procedures consisting of an interface listing the concrete procedures As is standard, we will model randomized computations using sub-distributions.Definition 1.A sub-distribution over a set A is defined by a mass function µ : A → [0, 1] that gives the probability of the unitary events a ∈ A. This mass function must be s.t.a∈A µ(a) is well-defined and |µ| = a∈A µ(a) ≤ 1.In particular, the support supp(µ) = {a ∈ A | µ(a) = 0} is discrete. 10The name "sub-distribution" emphasizes that the total probability may be strictly less than 1.When the weight |µ| is equal to 1, we call µ a distribution.We let SDist(A) denote the set of sub-distributions over A. The probability of an event Simple examples of sub-distributions include the null sub-distribution 0, which maps each element of the underlying space to 0; and the Dirac distribution centered on x, written δ x , which maps x to 1 and all other elements to 0. The following standard construction gives a monadic structure to sub-distributions.
We use notation reminiscent of expected values, as the definition is quite similar.
We will need two constructions to model branching statements.
Sub-distributions are partially ordered under the pointwise order.
for every a ∈ A, and we say We use the following lemma when reasoning about the semantics of loops.
Sub-distributions are stable under pointwise-limits.Definition 6.A sequence (µ n ) n∈N ∈ SDist(A) sub-distributions converges if for every a ∈ A, the sequence (µ n (a)) n∈N of real numbers converges.The limit sub-distribution is defined as for every a ∈ A. We write lim n→∞ µ n for µ ∞ .
Lemma 2. Let (µ n ) n∈N be a convergent sequence of sub-distributions.Then for any event E(x), we have: Any bounded increasing real sequence has a limit; the same is true of subdistributions.
Lemma 3. Let (µ n ) n∈N ∈ SDist(A) be an increasing sequence of sub-distributions.Then, this sequence converges to µ ∞ and µ n ≤ µ ∞ for every n ∈ N. In particular, for any event E, we have

Programs and Assertions
Now, we introduce our core programming language and its denotational semantics.
Programs.We base our development on pWhile, a strongly-typed imperative language with deterministic assignments, probabilistic assignments, conditionals, loops, and an abort statement which halts the computation with no result.Probabilistic assignments x $ ← g assign a value sampled from a distribution g to a program variable x.The syntax of statements is defined by the grammar: where x, e, and g range over typed variables in X , expressions in E and distribution expressions in D respectively.The set E of well-typed expressions is defined inductively from X and a set F of function symbols, while the set D of well-typed distribution expressions is defined by combining a set of distribution symbols S with expressions in E. Programs may call a set I of internal procedures as well as a set A of external procedures.We assume that we have code for internal procedures but not for external procedures-we only know indirect information, like which internal procedures they may call.Borrowing a convention from cryptography, we call internal procedures oracles and external procedures adversaries.Semantics.The denotational semantics of programs is adapted from the seminal work of [24] and interprets programs as sub-distribution transformers.We view states as type-preserving mappings from variables to values; we write State for the set of states and SDist(State) for the set of probabilistic states.For each procedure name f ∈ I ∪ A, we assume a set X L f ⊆ X of local variables s.t.X L f are pairwise disjoint.The other variables X \ f X L f are global variables.To define the interpretation of expressions and distribution expressions, we let e m denote the interpretation of expression e with respect to state m, and e µ denote the interpretation of expression e with respect to an initial sub-distribution µ over states defined by the clause e µ = E m∼µ [ e m ].Likewise, we define the semantics of commands in two stages: first interpreted in a single input memory, then interpreted in an input sub-distribution over memories.Definition 7. The semantics of commands are given in Fig. 1.
-The semantics s m of a statement s in initial state m is a sub-distribution over states.-The (lifted) semantics s µ of a statement s in initial sub-distribution µ over states is a sub-distribution over states.
We briefly comment on loops.The semantics of a loop while e do c is defined as the limit of its lower approximations, where the n-th lower approximation of while e do c µ is (if e then s) n ; if e then abort µ , where if e then s is shorthand for if e then s else skip and c n is the n-fold composition c; • • • ; c.Since the sequence is increasing, the limit is well-defined by Lemma 3. In contrast, the n-th approximation of while e do c µ defined by (if e then s) n µ may not converge, since they are not necessarily increasing.However, in the special case where the output distribution has weight 1, the n-th lower approximations and the n-th approximations have the same limit.Lemma 4. If the sub-distribution while e do c µ has weight 1, then the limit of (if e then s) n µ is defined and This follows by Lemma 1, since lower approximations are below approximations so the limit of their weights (and the weight of their limit) is 1.It will be useful to identify programs that terminate with probability 1. Informally, a program is lossless if all probabilistic assignments sample from full distributions rather than sub-distributions, there are no abort instructions, and the program is almost surely terminating, i.e. infinite traces have probability zero.Note that if we restrict the language to sample from full distributions, then losslessness coincides with almost sure termination.

Definition 8 (Lossless
Another important class of loops are loops with a uniform upper bound on the number of iterations.Formally, we say that a loop while e do s is certainly terminating if there exists k such that for every sub-distribution µ, we have | while e do s µ | = | (if e then s) k µ |.Note that certain termination of a loop does not entail losslessness-the output distribution of the loop may not have weight 1, for instance, if the loop samples from a sub-distribution or if the loop aborts with positive probability.
Semantics of Procedure Calls and Adversaries.The semantics of internal procedure calls is straightforward.Associated to each procedure name f ∈ I, we assume a designated input variable f arg ∈ X L f , a piece of code f body that executes the function call, and a result expression f res .A function call x ← I(e) is then equivalent to f arg ← e; f body ; x ← f res .Procedures are subject to wellformedness criteria: procedures should only use local variables in their scope and after initializing them, and should not perform recursive calls.
External procedure calls, also known as adversary calls, are a bit more involved.Each name a ∈ A is parametrized by a set a ocl ⊆ I of internal procedures which the adversary may call, a designated input variable a arg ∈ X L a , a (unspecified) piece of code a body that executes the function call, and a result expression a res .We assume that adversarial code can only access its local variables in X L a and can only make calls to procedures in a ocl .It is possible to impose more restrictions on adversaries-say, that they are lossless-but for simplicity we do not impose additional assumptions on adversaries here.
In this section we introduce a program logic for proving properties of probabilistic programs.The logic is abstract-assertions are arbitrary predicates on subdistributions-but the meta-theoretic properties are clearest in this setting.In the following section, we will give a concrete version suitable for practical use.
Usual set operations are lifted to assertions using their logical counterparts, e.g., η ∧ η = η ∩ η and ¬η = η.Our program logic uses a few additional constructions.Given a predicate φ over states, we define where supp(µ) is the set of all states with non-zero probability under µ.Intuitively, φ holds deterministically on all states that we may sample from the distribution.To reason about branching commands, given two assertions η 1 and η 2 , we let This assertion means that the sub-distribution is the sum of two sub-distributions such that η 1 holds on the first piece and η 2 holds on the second piece.
Given an assertion η and an event E ⊆ State, we let η |E (µ) = η(µ |E ).This assertion holds exactly when η is true on the portion of the sub-distribution satisfying E. Finally, given an assertion η and a function F from SDist(State) to SDist(State), we define η[F ] = λµ.η(F (µ)).Intuitively, η[F ] is true in a sub-distribution µ exactly when η holds on F (µ). Now, we can define the closedness properties of assertions.These properties will be critical to our rules for while loops.

Definition 10 (Closedness properties). A family of assertions
When (η n ) n is constant and equal to η, we say that η is u-/t-/d-closed.
Note that t-closedness implies u-closedness, but the converse does not hold.Moreover, u-closed, t-closed and d-closed assertions are closed under arbitrary intersections and finite unions, or in logical terms under finite boolean combinations, universal quantification over arbitrary sets and existential quantification over finite sets.
Finally, we introduce the necessary machinery for the frame rule.The set mod(s) of modified variables of a statement s consists of all the variables on the left of a deterministic or probabilistic assignment.In this setting, we say that an assertion η is separated from a set of variables X, written separated(η, X), if η(µ 1 ) ⇐⇒ η(µ 2 ) for any distributions where for a set of variables X, the restricted sub-distribution µ |X is where State |X and m |X restrict State and m to the variables in X.
Intuitively, an assertion is separated from a set of variables X if every two sub-distributions that agree on the variables outside X either both satisfy the assertion, or both refute the assertion.
Judgments and Proof Rules.Judgments are of the form {η} s {η }, where the assertions η and η are drawn from Assn.
for every interpretation of adversarial procedures and every probabilistic state µ such that η(µ).
Figure 2 describes the structural and basic rules of the proof system.Validity of judgments is preserved under standard structural rules, like the rule of consequence [Conseq].As usual, the rule of consequence allows to weaken the post-condition and to strengthen the post-condition; in our system, this rule serves as the interface between the program logic and mathematical theorems from probability theory.The [Exists] rule is helpful to deal with existentially quantified pre-conditions.
The rules for skip, assignments, random samplings and sequences are all straightforward.The rule for abort requires ⊥ to hold after execution; this assertion uniquely characterizes the resulting null sub-distribution.The rules for assignments and random samplings are semantical.
The rule [Cond] for conditionals requires that the post-condition must be of the form η 1 ⊕ η 2 ; this reflects the semantics of conditionals, which splits the initial probabilistic state depending on the guard, runs both branches, and recombines the resulting two probabilistic states.
The next two rules ([Split] and [Frame]) are useful for local reasoning.The [Split] rule reflects the additivity of the semantics and combines the pre-and post-conditions using the ⊕ operator.The [Frame] rule asserts that lossless statements preserve assertions that are not influenced by modified variables.
The rule [Call] for internal procedures is as expected, replacing the procedure call f with its definition.Figure 3 presents the rules for loops.We consider four rules specialized to the termination behavior.The [While] rule is the most general rule, as it deals with Fig. 2. Structural and basic rules arbitrary loops.For simplicity, we explain the rule in the special case where the family of assertions is constant, i.e. we have η n = η and η n = η .Informally, the η is the loop invariant and η is an auxiliary assertion used to prove the invariant.We require that η is u-closed, since the semantics of a loop is defined as the limit of its lower approximations.Moreover, the first premise ensures that starting from η, one guarded iteration of the loop establishes η ; the second premise ensures that restricting to ¬e a probabilistic state µ satisfying η yields a probabilistic state µ satisfying η.It is possible to give an alternative formulation where the second premise is substituted by the logical constraint η |¬e =⇒ η.As usual, the post-condition of the loop is the conjunction of the invariant with the negation of the guard (more precisely in our setting, that the guard has probability 0).
The [While-AST] rule deals with lossless loops.For simplicity, we explain the rule in the special case where the family of assertions is constant, i.e. we have η n = η.In this case, we know that lower approximations and approximations have the same limit, so we can directly prove an invariant that holds after one guarded iteration of the loop.On the other hand, we must now require that the η satisfies the stronger property of t-closedness.
The [While-D] rule handles arbitrary loops with a d-closed invariant; intuitively, restricting a sub-distribution that satisfies a downwards closed assertion η yields a sub-distribution which also satisfies η.
The [While-CT] rule deals with certainly terminating loops.In this case, there is no requirement on the assertions.
We briefly compare the rules from a verification perspective.If the assertion is d-closed, then the rule [While-D] is easier to use, since there is no need to prove any termination requirement.Alternatively, if we can prove certain termination of the loop, then the rule [While-CT] is the best to use since it does not impose any condition on assertions.When the loop is lossless, there is no need to introduce an auxiliary assertion η , which simplifies the proof goal.Note however that it might still be beneficial to use the [While] rule, even for lossless loops, because of the weaker requirement that the invariant is u-closed rather than t-closed.
Finally, Fig. 4 gives the adversary rule for general adversaries.It is highly similar to the general rule [While-D] for loops since the adversary may make an arbitrary sequence of calls to the oracles in a ocl and may not be lossless.Intuitively, η plays the role of the invariant: it must be d-closed and it must be preserved by every oracle call with arbitrary arguments.If this holds, then η is also preserved by the adversary call.Some framing conditions are required, similar to the ones of the [Frame] rule: the invariant must not be influenced by the state writable by the external procedures.
It is possible to give other variants of the adversary rule with more general invariants by restricting the adversary, e.g., requiring losslessness or bounding the number of calls the external procedure can make to oracles, leading to rules akin to the almost surely terminating and certainly terminating loop rules, respectively.
{η0} while e do s {η∞ ∧ ¬e} Soundness and Relative Completeness.Our proof system is sound and relatively complete with respect to the semantics; these proofs have also been formalized in the Coq proof assistant.
Completeness of the logic follows from the next lemma, whose proof makes an essential use of the [While] rule.In the sequel, we use 1 µ to denote the characteristic function of a probabilistic state µ, an assertion stating that the current state is equal to µ. Lemma 5.For every probabilistic state µ, the following judgment is provable using the rule of the logic: Proof.By induction on the structure of s.
s = abort, s = skip, x ← e and s = x $ ← g are trivial; s = s 1 ; s 2 , we have to prove We apply the [Seq] rule with η 1 = 1 s1 µ premises can be directly proved using the induction hypothesis; s = if e then s 1 else s 2 , we have to prove We apply the [Conseq] rule to be able to apply the the [Cond] rule with η 1 = 1 s1 µ |e and η 2 = 1 s2 µ |¬e Both premises can be proved by an application of the [Conseq] rule followed by the application of the induction hypothesis.
s = while e do s, we have to prove {1 µ } while e do s {1 limn→∞ (if e then s) n ;if e then abort µ }.
We first apply the [While] rule with η n = 1 (if e then s) n µ and For the first premise we apply the same process as for the conditional case: we apply the [Conseq] and [Cond] rules and we conclude using the induction hypothesis (and the [Skip] rule).For the second premise we follow the same process but we conclude using the [Abort] rule instead of the induction hypothesis.Finally we conclude since uclosed((η n ) n∈N ∞ ).
The abstract logic is also relatively complete.This property will be less important for our purposes, but it serves as a basic sanity check.
The side-conditions in the loop rules (e.g., uclosed/tclosed/dclosed and the weight conditions) are difficult to prove, since they are semantic properties.Next, we present a concrete version of the logic with give easy-to-check, syntactic sufficient conditions.

A Concrete Program Logic
To give a more practical version of the logic, we begin by setting a concrete syntax for assertions Assertions.We use a two-level assertion language, presented in Fig. 5.A probabilistic assertion η is a formula built from comparison of probabilistic expressions, using first-order quantifiers and connectives, and the special connective ⊕.A probabilistic expression p can be a logical variable v, an operator applied to probabilistic expressions o(p) (constants are 0-ary operators), or the expectation E[ẽ] of a state expression ẽ.A state expression ẽ is either a program variable x, the characteristic function 1 φ of a state assertion φ, an operator applied to state expressions o(ẽ), or the expectation E v∼g [ẽ] of state expression ẽ in a given distribution g.Finally, a state assertion φ is a first-order formula over program variables.Note that the set of operators is left unspecified but we assume that all the expressions in E and D can be encoded by operators. (S-expr.) The interpretation of the concrete syntax is as expected.The interpretation of probabilistic assertions is relative to a valuation ρ which maps logical variables to values, and is an element of Assn.The definition of the interpretation is straightforward; the only interesting case is where ẽ ρ m is the interpretation of the state expression ẽ in the memory m and valuation ρ.The interpretation of state expressions is a mapping from memories to values, which can be lifted to a mapping from distributions over memories to distributions over values.The definition of the interpretation is straightforward; the most interesting case is for expectation ].We present the full interpretations in the supplemental materials.Many standard concepts from probability theory have a natural representation in our syntax.For example: the probability that φ holds in some probabilistic state is represented by the probabilistic expression Pr[φ] = E[1 φ ]; probabilistic independence of state expressions ẽ1 , . . ., ẽn is modeled by the probabilistic assertion #{ẽ 1 , . . ., ẽn }, defined by the clause11 the fact that a distribution is proper is modeled by the probabilistic assertion L = Pr[ ] = 1; a state expression ẽ distributed according to a law g is modeled by the probabilistic assertion The inner expectation computes the probability that v drawn from g is equal to a fixed w; the outer expectation weights the inner probability by the probability of each value of w.
We can easily define operator from the previous section in our new syntax: φ = Pr[¬φ] = 0. Syntactic Proof Rules.Now that we have a concrete syntax for assertions, we can give syntactic versions of many of the existing proof rules.Such proof rules are often easier to use since they avoid reasoning about the semantics of commands and assertions.We tackle the non-looping rules first, beginning with the following syntactic rules for assignment and sampling: The rule for assignment is the usual rule from Hoare logic, replacing the program variable x by its corresponding expression e in the pre-condition.The replacement η[x := e] is done recursively on the probabilistic assertion η; for instance for expectations, it is defined by where ẽ[x := e] is the syntactic substitution.
The rule for sampling uses probabilistic substitution operator P g x (η), which replaces all occurrences of x in η by a new integration variable t and records that t is drawn from g; the operator is defined in Fig. 6.
Next, we turn to the loop rule.The side-conditions from Fig. 3 are purely semantic, while in practice it is more convenient to use a sufficient condition in the Hoare logic.We give sufficient conditions for ensuring certain and almostsure termination in Fig. 7; ẽ is an integer-valued expression.The first sidecondition C CTerm shows certain termination given a strictly decreasing variant ẽ = o(P g x (η1), . . ., P g x (ηn)) P g x (η1 η2) = P g x (η1) P g x (η2) for o ∈ Ops, ∈ {∧, ∨, ⇒}.
Fig. 7. Side-conditions for loop rules that is bounded below, similar to how a decreasing variant shows termination for deterministic programs.The second side-condition C ASTerm shows almostsure termination given a probabilistic variant ẽ, which must be bounded both above and below.While ẽ may increase with some probability, it must decrease with strictly positive probability.This condition was previously considered by [14] for probabilistic transition systems and also used in expectation-based approaches [30,17].Our framework can also support more refined conditions (e.g., based on super-martingales [8,28]), but the condition C ASTerm already suffices for most randomized algorithms.While t-closedness is a semantic condition (cf.Definition 10), there are simple syntactic conditions to guarantee it.For instance, assertions that carry a non-strict comparison ∈{≤, ≥, =} between two bounded probabilistic expressions are t-closed; the assertion stating probabilistic independence of a set of expressions is t-closed.
Precondition Calculus.With a concrete syntax for assertions, we are also able to incorporate syntactic reasoning principles.One classic tool is Morgan and McIver's greatest pre-expectation, which we take as inspiration for a pre-condition calculus for the loop-free fragment of Ellora.Given an assertion η and a loop-free statement s, we mechanically construct an assertion η * that is the pre-condition of s that implies η as a post-condition.The basic idea is to replace each expectation expression p inside η by an expression p * that has the same denotation before running s as p after running s.This process yields an assertion η * that, interpreted before running s, is logically equivalent to η interpreted after running s.
The computation rules for pre-conditions are defined in Fig. 8.For a probability assertion η, its pre-condition pc(s, η) corresponds to η where the expectation ex-pressions of the form E[ẽ] are replaced by their corresponding pre-term, pe(s, E[ẽ]).Pre-terms correspond loosely to Morgan and McIver's pre-expectations-we will make this correspondence more precise in the next section.The main interesting cases for computing pre-terms are for random sampling and conditionals.For random sampling the result is P g x (E[ẽ]), which corresponds to the [Sample] rule.For conditionals, the expectation expression is split into a part where e is true and a part where e is not true.We restrict the expectation to a part satisfying e with the operator This corresponds to the expected value of ẽ on the portion of the distribution where e is true.Then, we can build the pre-condition calculus into Ellora.6 Case Studies: Embedding Lightweight Logics While Ellora is suitable for general-purpose reasoning about probabilistic programs, in practice humans typically use more special-purpose proof techniquesoften targeting just a single, specific kind of property, like probabilistic independencewhen proving probabilistic assertions.When these techniques apply, they can be a convenient and powerful tool.
To capture this intuitive style of reasoning, researchers have considered lightweight program logics where the assertions and proof rules are tailored to a specific proof technique.We demonstrate how to integrate these tools in an assertion-based logic by introducing and embedding a new logic for reasoning about independence and distribution laws, useful properties when analyzing randomized algorithms.We crucially rely on the rich assertions in Ellora-it is not clear how to extend expectation-based approaches to support similar, lightweight reasoning.Then, we show to embed the union bound logic [4] for proving accuracy bounds.

Law and Independence Logic
We begin by describing the law and independence logic IL, a proof system with intuitive rules that are easy to apply and amenable to automation.For simplicity, we only consider programs which sample from the binomial distribution, and have deterministic control flow-for lack of space, we also omit procedure calls.
The assertion det(e) states that e is deterministic in the current distribution, i.e., there is at most one element in the support of its interpretation.The assertion # E states that the expressions in E are independent, as formalized in the previous section.The assertion e ∼ B(m, p) states that e is distributed according to a binomial distribution with parameter m (where m can be an expression) and constant probability p, i.e. the probability that e = k is equal to the probability that exactly k independent coin flips return heads using a biased coin that returns heads with probability p.
Assertions can be seen as an instance of a logical abstract domain, where the order between assertions is given by implication based on a small number of axioms.Examples of such axioms include independence of singletons, irreflexivity of independence, anti-monotonicity of independence, an axiom for the sum of binomial distributions, and rules for deterministic expressions: Definition 13.Judgments of the logic are of the form {ξ} s {ξ }, where ξ and ξ are IL-assertions.A judgment is valid if it is derivable from the rules of Fig. 9; structural rules and rule for sequential composition are similar to those from § 4 and omitted.
The rule [IL-Assgn] for deterministic assignments is as in § 4. The rule [IL-Sample] for random assignments yields as post-condition that the variable x and a set of expressions E are independent assuming that E is independent before the sampling, and moreover that x follows the law of the distribution that it is sampled from.The rule [IL-Cond] for conditionals requires that the guard is deterministic, and that each of the branches satisfies the specification; if the guard is not deterministic, there are simple examples where the rule is not sound. 12 The rule [IL-While] for loops requires that the loop is certainly terminating with a deterministic guard.Note that the requirement of certain termination could be avoided by restricting the structural rules such that a statement s has deterministic control flow whenever {ξ} s {ξ } is derivable.
We now turn to the embedding.The embedding of IL assertions into general assertions is immediate, except for det(e) which is translated as e ∨ ¬e.We let ξ denote the translation of ξ.
Proof sketch.By induction on the derivation.The interesting cases are conditionals and loops.For conditionals, the soundness follows from the soundness of the rule: To prove the soundness of this rule, we proceed by case analysis on e ∨ ¬e.We treat the case e; the other case is similar.In this case, η is equivalent to η 1 ∧ e ⊕ η 2 ∧ ¬e, where η 1 = η and η 2 = ⊥.Let η 1 = η and η 2 = ⊥; again, η 1 ⊕ η 2 is logically equivalent to η .The soundness of the rule thus follows from the soundness of the [Cond] and [Conseq] rules.For loops, there exists a natural number n such that while b do s is semantically equivalent to (if b then s) n .By assumption {ξ} s {ξ} holds, and thus by induction hypothesis {ξ} s {ξ}.We also have ξ =⇒ det(b), and hence {ξ} if b then s {ξ}.We conclude by [Seq].To illustrate our system IL, consider the statement s in Fig. 10 which flips a fair coin N times and counts the number of heads.Using the logic, we prove that c ∼ B(N • (N + 1)/2, 1/2) is a post-condition for s.We take the invariant: The invariant holds initially, as 0 ∼ B(0, 1/2).For the inductive case, we show: {c ∼ B (0, 1/2)} s 0 {c ∼ B ((j + 1)(j + 2)/2, 1/2)} where s 0 represents the loop body, i.e. x $ ← B (j, 1/2) ; c ← c + x.First, we apply the rule for sequence taking as intermediate assertion Each branch establishes #{x1, x2}, but this is not a valid post-condition for the conditional.There are similar examples using the binomial distribution.The first premise follows from the rule for random assignment and structural rules.The second premise follows from the rule for deterministic assignment and the rule of consequence, applying axioms about sums of binomial distributions.
We briefly comment on several limitations of IL.First, IL is restricted to programs with deterministic control flow, but this restriction could be partially relaxed by enriching IL with assertions for conditional independence.Such assertions are already expressible in the logic of Ellora; adding conditional independence would significantly broaden the scope of the IL proof system and open the possibility to rely on axiomatizations of conditional independence (e.g., based on graphoids [33]).Second, the logic only supports sampling from binomial distributions.It is possible to enrich the language of assertions with clauses c ∼ g where g can model other distributions, like the uniform distribution or the Laplace distribution.The main design challenge is finding a core set of useful facts about these distributions.Enriching the logic and automating the analysis are interesting avenues for further work.

Embedding the Union Bound Logic
The program logic aHL [4] was recently introduced for estimating accuracy of randomized computations.One main application of aHL is proving accuracy of randomized algorithms, both in the offline and online settings-i.e. with adversary calls.aHL is based on the union bound, a basic tool from probability theory, and has judgments of the form |= β {Φ} s {Ψ }, where s is a statement, Φ and Ψ are first-order formulae over program variables, and β is a probability, i.e. β ∈ [0, 1].A judgment |= β {Φ} s {Ψ } is valid if for every memory m such that Φ(m), the probability of ¬Ψ in s m is upper bounded by β, i.e.Pr s m [¬Ψ ] ≤ β.
Figure 11 presents some key rules of aHL, including a rule for sampling from the Laplace distribution L centered around e. The predicate C CTerm (k) indicates that the loop terminates in at most k steps on any memory that satisfies the pre-condition.Moreover, β is a function of .aHL has a simple embedding into Ellora.
In this section, we will demonstrate Ellora on a selection of examples; we present further examples in the supplemental material.Together, they exhibit a wide variety of different proof techniques and reasoning principles which are available in the Ellora's implementation.
Hypercube Routing.will begin with the hypercube routing algorithm [38,39].Consider a network topology (the hypercube) where each node is labeled by a bitstring of length D and two nodes are connected by an edge if and only if the two corresponding labels differ in exactly one bit position.
In the network, there is initially one packet at each node, and each packet has a unique destination.The algorithm implements a routing strategy based on bit fixing: if the current position has bitstring i, and the target node has bitstring j, we compare the bits in i and j from left to right, moving along the edge that corrects the first differing bit.Valiant's algorithm uses randomization to guarantee that the total number of steps grows logarithmically in the number of packets.In the first phase, each packet i select an intermediate destination ρ(i) uniformly at random, and use bit fixing to reach ρ(i).In the second phase, each packet use bit fixing to go from ρ(i) to the destination j.We will focus on the first phase since the reasoning for the second phase is nearly identical.We can model the strategy with the code in Figure 18, using some syntactic sugar for the for loops. 13We assume that initially, the position of the packet i is at node  The variable usedBy is a map that logs if an edge is already used by a packet, it is empty at the beginning of each iteration.For each packet, we try to move it across one edge along the path to its intermediate destination.The function getEdge returns the next edge to follow, following the bit-fixing scheme.If the packet can progress (its edge is not used), then its current position is updated and the edge is marked as used.
We show that if the number of timesteps T is 4D + 1, then all packets reach their intermediate destination in at most T steps, except with a small probability 2 −2D of failure.That is, the number of timesteps grows linearly in D, logarithmic in the number of packets.This is formalized in our system as:

Fig. 13. Coupon collector
Modeling Infinite Processes.Our second example is the coupon collector process.The algorithm draws a uniformly random coupon (we have N coupon) on each day, terminating when it has drawn at least one of each kind of coupon.The code of the algorithm is displayed in Fig. 13; the array cp records of the coupons seen so far, t holds the number of steps taken before seeing a new coupon, and X tracks of the total number of steps.Our goal is to bound the average number of iterations.This is formalized in our logic as: . proc pwInd (N : int) : return X Fig. 14.Pairwise Independence Limited Randomness.Pairwise independence says that if we see the result of X i , we do not gain information about all other variables X k .However, if we see the result of two variables X i , X j , we may gain information about X k .There are many constructions in the algorithms literature that grow a small number of independent bits into more pairwise independent bits.Figure 14 gives one procedure, where ⊕ is exclusive-or, and bits(j) is the set of positions set to 1 in the binary expansion of j.The proof uses the following fact, which we fully verify: for a uniformly distributed Boolean random variable Y , and a random variable for any two Boolean functions f, g.Then, note that X[i] = {j∈bits(i)} B[j] where the big XOR operator ranges over the indices j where the bit representation of i has bit j set.For any two i, k ∈ [1, . . ., 2 N ] distinct, there is a bit position in [1, . . ., N] where i and k differ; call this position r and suppose it is set in i but not in k.By rewriting, Since B[j] are all independent, X[i] # X[k] follows from Eq. ( 1) taking Z to be the distribution on tuples . This verifies pairwise independence: Adversarial Programs.Pseudorandom functions (PRF) and pseudorandom permutations (PRP) are two idealized primitives that play a central role in the design of symmetric-key systems.Although the most natural assumption to make about a blockcipher is that it behaves as a pseudorandom permutation, most commonly the security of such a system is analyzed by replacing the blockcipher with a perfectly random function.The PRP/PRF Switching Lemma [19,6] fills the gap: given a bound for the security of a blockcipher as a pseudorandom function, it gives a bound for its security as a pseudorandom permutation.
Lemma 4 (PRP/PRF switching lemma).Let A be an adversary with blackbox access to an oracle O implementing either a random permutation on {0, 1} l or a random function from {0, 1} l to {0, 1} l .Then the probability that the adversary A distinguishes between the two oracles in at most q calls is bounded by , where H is a map storing each adversary call and |H| is its size.
Proving this lemma can be done using the Fundamental Lemma of Game-Playing, and bounding the probability of bad in the program from Fig. 15.We focus on the latter.Here we apply the [Adv] rule of Ellora with the invariant ∀k, 2 l+1 where |H| is the size of the map H, i.e. the number of adversary call.Intuitively, the invariant says that at each call to the oracle the probability that bad has been set before and that the number of adversary call is less than k is bounded by a polynomial in k.
The invariant is d-closed and true before the adversary call, since at that point Pr[bad] = 0. Then we need to prove that the oracle preserves the invariant, which can be done easily using the precondition calculus ([PC] rule).

Implementation and Mechanization
We have built a prototype implementation of Ellora within EasyCrypt [5,2], a theorem prover originally designed for verifying cryptographic protocols.Easy-Crypt provides a convenient environment for constructing proofs in various Hoare logics, supporting interactive, tactic-based proofs for manipulating assertions and allowing users to invoke external tools, like SMT-solvers, to discharge proof obligations.EasyCrypt provides a mature set of libraries for both data structures (sets, maps, lists, arrays, etc.) and mathematical theorems (algebra, real analysis, etc.), which we extended with theorems from probability theory.We used the implementation for verifying many examples from the literature, including all the programs presented in § 7 as well as some additional examples (such as polynomial identity test, private running sums, properties about random walks, etc.).The verified proofs bear a strong resemblance to the existing, paper proofs.Independently of this work, Ellora has been used to formalize the main theorem about a randomized gossip-based protocol for distributed systems [?, Theorem 2.1].Some libraries developed in the scope of Ellora have been incorporated into the main branch of EasyCrypt, including a general library on probabilistic independence.

Example
A New Library for Probabilistic Independence.In order to support assertions of the concrete program logic, we enhanced the standard libraries of EasyCrypt, notably the ones dealing with big operators and sub-distributions.Like all EasyCrypt libraries, they are written in a foundational style, i.e. they are defined instead of axiomatized.A large part of our libraries are proved formally from first principles.However, some results, such as concentration bounds, are currently declared as axioms.
Our formalization of probabilistic independence deserves special mention.We formalized two different (but logically equivalent) notions of independence.The first is in terms of products of probabilities, and is based on heterogenous lists.Since Ellora (like EasyCrypt) has no support for heterogeneous lists, we use a smart encoding based on second-order predicates.The second definition is more abstract, in terms of product and marginal distributions.While the first definition is easier to use when reasoning about randomized algorithms, the second definition is more suited for proving mathematical facts.We prove the two definitions equivalent, and formalize a collection of related theorems.
Mechanized Meta-Theory.The proofs of soundness and relative completeness of the abstract logic, without adversary calls, and the syntactical termination arguments have been mechanized in the Coq proof assistant.The development is available in supplemental material.

Related Work
More on Assertion-Based Techniques.The earliest assertion-based system is due to Ramshaw [34], who proposes a program logic where assertions can be formulas involving frequencies, essentially probabilities on sub-distributions.Ramshaw's logic allows assertions to be combined with operators like ⊕, similar to our approach.[15] presents a Hoare-style logic with general assertions on the distribution, allowing expected values and probabilities.However, his while rule is based on a semantic condition on the guarded loop body, which is less desirable for verification because it requires reasoning about the semantics of programs.[7] give decidability results for a probabilistic Hoare logic without while loops.We are not aware of any existing system that supports assertions about general expected values; existing works also restrict to Boolean distributions.[35] formalize a Hoare logic for probabilistic programs but unlike our work, their assertions are interpreted on distributions rather than sub-distributions.For conditionals, their semantics rescales the distribution of states that enter each branch.However, their assertion language is limited and they impose strong restrictions on loops.
Other Approaches.Researchers have proposed many other approaches to verify probabilistic program.For instance, verification of Markov transition systems goes back to at least [14,37]; our condition for ensuring almost-sure termination in loops is directly inspired by their work.Automated methods include model checking (see e.g., [1,22,26]) and abstract interpretation (see e.g., [29,11]).Techniques for reasoning about higher-order (functional) probabilistic languages are an active subject of research (see e.g., [?,?,?]).For analyzing probabilistic loops, in particular, there are tools for reasoning about running time.There are also automated systems for synthesizing invariants [10,3].[8,9] use a martingale method to compute the expected time of the coupon collector process for N = 5fixing N lets them focus on a program where the outer while loop is fully unrolled.Martingales are also used by [12] for analyzing probabilistic termination.Finally, there are approaches involving symbolic execution; [36] use a mix of static and dynamic analysis to check probabilistic programs from the approximate computing literature.
We introduced an expressive program logic for probabilistic programs, and showed that assertion-based systems are suited for practical verification of probabilistic programs.Owing to their richer assertions, program logics are a more suitable foundation for specialized reasoning principles than expectation-based systems.As evidence, our program logic can be smoothly extended with custom reasoning for probabilistic independence and union bounds.Future work includes proving better accuracy bounds for differentially private algorithms, and exploring further integration of Ellora into EasyCrypt.
Fig. 17.Precondition calculus loop.Indeed, we remark that the statement ∃k (ẽ ≤ k) holds at first iteration by the precondition hypothesis.Let: Then unrolling the loop and using the semantical [Seq] rule ensure by induction the claimed domination.The termination of the loop arises then naturally from the exit condition (ẽ = 0 ⇒ ¬b).

D.2 Almost-Sure Termination
The main challenge for proving the soundness of the is proving termination; from there, we can conclude by rule [While-C ASTerm ].Our arguments use basic notations and theorems from the theory of Markov processes.
Proposition 12 (Soundness of rule [While-C ASTerm ]).Let η be a t-closed assertion.For any sub-distributions µ, such that C ASTerm is valid.Then while b do s µ |= η.
Proof.As indicated, by soundness of the semantic while rule for almost-sure termination, and the premises, it suffices to prove almost-sure termination.The sketch of the proof is the following: Step one: Variant as a Random variable.We consider the integer-valued variant ẽ as a random variable over the space of states.Let the family (ẽ i ) i represents the value taken by ẽ after the i-th iteration of the loop.Then we have, using the semantical [Seq] rule and the -The sequence is uniformly bounded by K.
-The probability of decreasing is bounded below by : Step two: Modelization with a Markov chain.First, we can assume that K > 0 since if K = 0, the loop terminates immediately.Consider the following finite Markov chain (X i ) i , over the state space S = {0, . . ., K}, following the transitions: This chain models the following behavior: with probability the value decrease by one, while with probability 1− it jumps to K. Since zero is the only connected component of the underlying graph, the probability of terminating in the state zero is 1 by a standard result on Markov chains.
Step three: Stochastic domination.By construction, there exists a natural coupling between ( Xi ) and (ẽ i ) i , since the probability of the event ẽi decrease is greater than the probability of the event Xi decrease.Since we impose that X 0 = ẽ0 (initial position), a simple induction over i ensure that we have, for this coupling:

E.1 Randomization for Approximation: Vertex Cover
We begin with a classical application of randomization: approximation algorithms for computationally hard problems.For problems that take long time to solve in the worst case, we can sometimes devise efficient algorithms that find a solution that is "nearly" as good as the true solution.
Our first example illustrates a famous approximation algorithm for the vertex cover problem.The input is a graph described by vertices V and edges E. The goal is to output a vertex cover: a subset C ⊆ V such that each edge has at least one endpoint in C, and such that C is as small as possible.
It is known that this problem is NP-complete, but there is simple randomized algorithm that returns a vertex cover that is at on average at most twice the size of the optimal vertex cover.The algorithm proceeds by maintaining a current cover (initially empty) and considering each edge in order.If neither endpoint is in current cover, the algorithm adds one of the two endpoints uniformly at random.The Ellora program is: Here, we represent edges as a finite set of pairs of nodes.We loop through the edges, adding one point of each uncovered edge to the cover C uniformly at random.The operator b ?e 1 : e 2 returns e 1 if b is true, and e 2 if not.
To prove the approximation guarantee, we first assume that we have a set of nodes C * .We only assume that C * is a valid vertex cover; i.e., each edge has at least one endpoint in C * .Then, we use the following loop invariant: Given the loop invariant, we can prove the conclusion by letting C * be the cover OP T of minimal size, and reasoning about intersections and differences of sets.
Clearly the invariant is initially true.To see why the invariant is preserved, let e be the current edge, with both endpoints out of C. Since C * is a vertex cover, it has at least one endpoint of e.Since our algorithm includes an endpoint of e uniformly at random, the probability we choose a vertex not in C * is at most 1/2, so the expectation on the left in Eq. ( 5) increases by at most 1/2.If e is not covered in C but is covered by C * , there is at least a 1/2 probability that we increase the intersection C ∩ C * , so the right side in Eq. ( 5) increases by at least 1/2.Thus, the invariant is preserved, and we can prove and by reasoning on intersection and difference of sets,

E.2 Random Walks: Termination and Reachability
A canonical example of a random process is a random walk.There are many variations, but the basic scenario describes a numeric position changing over time, where the position depends on the position at the previous timestep, influenced by random noise drawn from some distribution.
To demonstrate how to verify interesting facts about random processes, we will model a one-dimensional random walk on the natural numbers.We start at position 0, and repeatedly update our position according to the following rules.From 0, we always make a step to 1. From non-zero positions, we flip a fair coin that is biased to come up heads with probability p > 0. If heads, we increase our position by 1; if tails, we decrease by 1.
We will prove two facts about this random walk.First, for any natural number T , the probability of eventually reaching T is 1.Second, when we reach T , we must first pass through all intermediate points 1, . . ., T − 1.In Ellora, we can express the random walk with the following code.In order to verify this example, we will use the probabilistic while rule [While-ASTerm].First we establish almost-sure termination by finding an appropriate termination measure: the distance between our current position, and T. Indeed, this measure is bounded by T, and has a non-negative (at least 1/2) probability of decreasing each iteration.Therefore, the loop terminates almost-surely, and thus our random walk eventually reaches any point T with probability 1.
To prove our second assertion-that we visit every point from 0 to T-we use the following loop invariant for the while command: In other words, if we have reached position pos, then we must have already reached every position in [0, pos].Since this invariant is t-closed, we may apply rule [While-ASTerm] and the invariant holds at the end of the loop.With the assertion pos = T at termination, we have enough to prove that each position is visited: The losslessness post-condition indicates that the walk terminates almostsurely.

E.3 Amplification: Polynomial Identity Testing
A second use of randomness is in running independent trials of the same algorithm.This technique, known as probability amplification, runs a randomized algorithm several times in order to reduce the error probability.Roughly speaking, a single trial may have high error with some probability, but by repeating the trial it is unlikely that all of the trials yield poor results.By combining the results appropriately-e.g., with a majority vote for algorithms with binary outputs, or by selecting the best answer when we can check the quality of the solution-we can produce an output that is more accurate than a single run of the original algorithm.
An example in this vein is probabilistic polynomial identity testing.Given two multivariate polynomials P (x 1 , . . ., x n ) and Q(x 1 , . . ., x n ) over the finite field F q of q elements, we want to check whether P = Q, or equivalently, whether the polynomial P − Q is zero or not.We will take n uniformly random samples (v i ) i from F q and check whether (P − Q)(v 1 , . . ., v n ) = 0. We repeat the trial q times, rejecting if we see a sample where the difference is non-zero.In our system, this corresponds to the following program: The proof uses an instance of the Schwartz-Zippel lemma due to Øystein Ore for finite fields, which upper bounds the probability of randomly picking a root of a polynomial over a finite field.
Lemma 13.Let P a non-zero polynomial function over F q .If we sample the variables v 1 , . . ., v n uniformly at random from F q , then We encode this lemma as an axiom in our system: With this fact, we can prove the following loop invariant: finally proving that We have also verified Freivald's algorithm, an amplification-based algorithm for checking matrix multiplication.

E.4 Concentration Bounds: Private Running Sums
Now, we turn to examples involving independence of random variables.Our first example is drawn from the differential privacy literature.Given a list of N integers, we add noise from a two-sided geometric distribution to each entry in order to protect privacy, and we calculate the partial sums of the noisy values: x 1 , x 1 + x 2 , x 1 + x 2 + x 3 , and so on.We wish to measure how far the noisy sums deviate from the true sums.
In Ellora, we can express this algorithm as follows: The parameter to the noise distribution twogeom is a numeric parameter controlling the strength of the privacy guarantee, by changing the magnitude of the noise.Our loop invariant tracks three pieces of information: (i) noise[i] is distributed according to twogeom( ); (ii) the array noise remains independent; and (iii) out[i] stores the noisy running sum: To bound the error introduced by the noise, we need to bound p∈[q] noise[p] .Since we know that the elements in noise are all independent, we can apply a concentration bound to bound the probability of a large error in the p-th running sum, concluding: for a particular function Q derived from the Berry-Esseen theorem.

E.5 Hypercube Routing in More Details
We will begin with the hypercube routing algorithm [38,39].To set the stage, consider a network where each node is labeled by a bitstring of length D, and two nodes are connected by an edge if and only if the two corresponding labels differ in exactly one bit position.This network topology is known as a hypercube, a D-dimensional version of the standard cube; a simple example with D = 3 is in Fig. 18.In the network, there is initially one packet at each node, and each packet has a unique destination.Our goal is to design a routing strategy that will move the packets from node to node, following the edges, until all packets reach their destination.Furthermore, the routing should be oblivious: to avoid coordination overhead, each packet must select a path without considering the behavior of the other packets.
To model the flow of packets, each packet's current position is a node in the graph.Time proceeds in a series of steps, and at each step at most one packet can traverse any single edge.If several packets try to use the same edge simultaneously, one packet will be selected to move (for any selection strategy that selects some packet).The other packets wait at their current position; these packets are delayed and make no progress this step.
The routing strategy is based on bit fixing: if the current position has bitstring i, and the target node has bitstring j, we compare the bits in i and j from left to right, moving along the edge that corrects the first differing bit.For instance, if we are at 111 and we wish to reach 100, we will move along the edge corresponding to the second position: from 111 to 101, and then along the edge corresponding to the third position: from 101 to 100.See Fig. 18 for a picture.
While this strategy is simple and oblivious, there are permutations π that require a total number of steps growing linearly in the number of packets to route all packets.Valiant proposes a simple modification, so that the total number of steps grows logarithmically in the number of packets.In the first phase, each packet i will first select an intermediate destination ρ(i) uniformly at random from all nodes, and use bit fixing to reach ρ(i).In the second phase, each packet will use bit fixing to go from ρ(i) to the destination π(i).We will focus on the first phase, since the reasoning for the second phase is nearly identical.We can model the strategy with the following code, using some syntactic sugar for the for loops; recall that the number of node in a hypercube of dimension D is 2 D so each node can be identified by a number in [ We assume that initially the position of the packet i is at node i (see Map.init).Then, we initialize the random intermediate destinations ρ.The remaining loop encodes the evaluation of the routing strategy iterated T time.The variable usedBy is a map that logs if an edge is already used by a packet, it is empty at the beginning of each iteration.For each packet, we try to move it across one edge along the path to its intermediate destination.The function getEdge returns the next edge to follow, following the bit-fixing scheme.If the packet can progress (its edge is not used), then its current position is updated and the edge is marked as used.
Our goal is to show that if the number of timesteps T is 4D + 1, then all packets reach their intermediate destination in at most T steps, except with a small probability 2 −2D of failure.That is, the number of timesteps grows linearly in D, logarithmic in the number of packets.At a high level, the analysis involves three steps.
The first step is to consider a single packet traveling from i to ρ(i), and to calculate the average number of other packets that share at least one edge with i's path P .Let H ρ (i, j) be 1 if the paths of packets i and j share at least one edge and 0 otherwise.Then, the load R ρ (i) on i's path is the sum of H ρ (i, j) over all the other packets j.By using the fact that each intermediate destination in ρ is uniformly distributed, and by analyzing the number of packets beside i's that use each edge on i's path, we can upper bound the expected value of R ρ (i) by D/2.In the second step, we move from a bound on the expectation of R ρ (i) to a high-probability bound : we want to show that R ρ (i) < 3D holds except with a small probability of failure.The key tool is the Chernoff bound, which gives high probability bounds of sums of independent samples.The libraries in Ellora include a mechanized proof of a generalized Chernoff bound, with the following statement (leaving off some of the parameters): lemma Chernoff n(d:mem distr)(X :int → mem → bool): Returning to the proof, we bounded the expectation of R ρ in the previous step.To apply the Chernoff bound, we need to show that for any packet i, the expressions H ρ (i, j) are independent for all j.This is not exactly true, since H ρ (i, j 1 ) and H ρ (i, j 2 ) both depend on the (random) destination ρ(i) of packet i.However, it suffices to show that these variables are independent if we fix the value of ρ(i); then we can apply the Chernoff bound to upper bound R ρ with high probability.
Finally, we can bound the total delay of any packet.This portion of the proof rests on an intricate loop invariant assigning an imaginary coin for each delay step to some packet that crosses P .By showing that each packet holds at most one coin, we can conclude that the i's delay is at most the number R ρ (i) of crossing packets.With our high probability bound from the previous step, we can show that T = 4D + 1 timesteps is sufficient to route all packets i to ρ(i), except with some small probability:

E.6 Coupon Collector in More Details
Our second example is the coupon collector process.The algorithm draws a uniformly random coupon (we have N coupon) on each day, terminating when it has drawn at least one of each kind of coupon.The code of the algorithm is as follows.The array cp keeps track of the coupons seen so far; initially cp[i] = 0. We divide the loop into a sequence of phases (the outer loop) where in each phase we repeatedly sample coupons and wait until we see a new coupon (the inner loop).We keep track of the number of steps we spend in each phase p in t[p], and the total number of steps in X.
Our goal is to bound the average number of iterations.The code involves two nested loops, so we have two loop invariants.The inner loop has a probabilistic guard: at every iteration, there is a finite probability that the loop terminates (i.e., if we draw a new coupon), but there is no finite bound on the number of iterations we need to run.Since our desired loop invariant is not downwards closed, we must apply the rule for almost sure termination.We use a variant that is 1 if we have not seen a new coupon, and 0 if we have seen a new coupon.Note that each iteration, we have a strictly positive probability ρ(p) of seeing a new coupon and decreasing the variant.Furthermore, the variant is bounded by 1, and the loop exits when the variant reaches 0. So, the side-condition C ASTerm holds.For the inner loop, we prove that forall c the invariant η i is preserved: Note that this is a t-closed formula; there is an existential in the second disjunction, but it has finite domain (for fixed c).
For intuition, for every natural number c there are two cases: Either we have already unrolled more than c iterations, or not.The first disjunction corresponds to the first case, since loops where the guard is true all have ct ≥ c, and the probability of stopping at c iterations is (1 − ρ(p)) c ρ(p)-we see c old coupons, and then a new one.Otherwise, we have the second disjunction.The integer k represents the current number of unfoldings of the loop.If the loop is continuing then k = ct.If the loop is terminated, it terminated before the current iteration: ct < k.Furthermore, the probability of continuing at iteration k is The outer loop is easier to handle, since the loop has a fixed bound N on the number of iterations so we can use the rule for certain termination.For the loop invariant, we take: The first conjunct states that the previous waiting times follow a geometric distribution with parameter ρ(i); this assertion follows from the previous reasoning on the inner loop.The second conjunct asserts that X holds the total waiting time so far.The final two conjuncts state that there are at most p − 1 flags set in cp.Thus, at the end of the outer loop.By applying linearity of expectations and a fact about the expectation of the geometric distribution, we can bound the expected running time: .

12
Consider the following program where Bern(p) is the Bernoulli distribution with parameter p: b

Fig. 12 .
Fig. 12. Hypercube Routing i (see Map.init).Then, we initialize the random intermediate destinations ρ.The remaining loop encodes the evaluation of the routing strategy iterated T time.The variable usedBy is a map that logs if an edge is already used by a packet, it is empty at the beginning of each iteration.For each packet, we try to move it across one edge along the path to its intermediate destination.The function
).A statement s is lossless if for every sub-distribution µ, | s µ | = |µ|, where |µ| is the total probability of µ.Programs that are not lossless are called lossy.