Algorithm Search⌘K

Techniqueresearch

Liquid types

Also called logically qualified data types.

Infers refinement types by abstract interpretation over conjunctions of given qualifiers, with SMT queries to check each subtyping step.

Liquid types is a method to infer refinement types automatically. The user gives a finite set of qualifiers, small predicate patterns such as 0≤ν0 \leq \nu or ν<⋆\nu < \star, where ⋆\star stands for any program variable. Every unknown refinement in the program is then a conjunction of instances of these qualifiers, and the method finds the strongest such conjunctions that make the program type check, using an SMT solver for each implication. The name stands for "logically qualified data types" (Rondon, Kawaguchi and Jhala 2008). The refinement type system decides whether given types are correct; liquid types finds the types. The method is predicate abstraction applied to types, and its fixed point loop is the same as the Houdini algorithm for program annotations.

In plain words

Writing refinement types by hand is a lot of work. Every helper function and every loop needs a fact such as "this index is between 0 and the length of the array". Liquid types guesses these facts from a short list of patterns that you give, such as "is at least 0" and "is less than some variable". For each unknown fact, it starts with every pattern that could apply, joined by "and". This is too strong to be true in most places. It then looks at each place where the fact must hold, asks the solver which patterns fail there, and drops them. It repeats until nothing more fails. Since the list of patterns is finite, the dropping must stop. What is left is the strongest fact that the patterns can say.

When it applies

  • The program is in a typed functional language, or can be put in A-normal form with types from Hindley-Milner inference. The liquid types are refinements of those types.
  • The refinements needed for the property are conjunctions of a few qualifier patterns. Bounds of array indices, sizes of lists, sortedness of adjacent elements, and ordering between arguments and results are typical.
  • The qualifiers are in a decidable logic, such as linear integer arithmetic with uninterpreted functions, so each implication is one decidable SMT query.
  • The properties to prove are given as refinements on primitives and on some function signatures, for example a precondition on array access or division.

The template

Liquid templates and constraints

Let QQ be the set of qualifiers. For a refinement position whose scope contains the variables XX, let QX⋆Q^\star_X be the set of instances of QQ where each ⋆\star is replaced by a variable of XX of the right base type. It is finite because QQ and XX are finite. A liquid type is a refinement type whose refinements are conjunctions of such instances.

  1. Shapes. Run HM inference. Give each base type position that has no user annotation a fresh liquid variable κ\kappa, so the refinement there is unknown.
  2. Constraints. Walk the program with the rules of the refinement type system, with κ\kappa in place of each unknown. Each use of subtyping gives an implication [ ⁣[Γ] ⁣]∧φ1⇒φ2[\![\Gamma]\!] \wedge \varphi_1 \Rightarrow \varphi_2, where the context, φ1\varphi_1 and φ2\varphi_2 may contain liquid variables under a pending substitution θ\theta (from T-App and T-Var), written θ κ\theta\,\kappa. A constraint whose right side is some θ κ\theta\,\kappa is a κ\kappa-constraint. A constraint whose right side has no liquid variable is a check.
  3. Solve. Find an assignment AA of a subset of Qκ⋆Q^\star_\kappa to each κ\kappa that makes all constraints valid, where a subset means its conjunction.
  1. SOLVE(constraints C, qualifier instances Q*)
  2. 1for each liquid variable κ do A(κ) ← Q*(κ) ▷ all candidates, the strongest guess
  3. 2repeat
  4. 3changed ← false
  5. 4for each κ-constraint H ⇒ θ κ in C do
  6. 5for each q in A(κ) do
  7. 6if not VALID(A(H) ⇒ θ q) then ▷ one SMT query
  8. 7A(κ) ← A(κ) minus {q} ; changed ← true
  9. 8until not changed
  10. 9for each check H ⇒ φ in C do
  11. 10if not VALID(A(H) ⇒ φ) then report an error at its source position
  12. 11return A

Here A(H)A(H) replaces each liquid variable in HH by the conjunction that AA gives it. The liquid variables occur only as conjuncts on the left of an implication or alone on the right, so a larger set A(κ)A(\kappa) makes every left side stronger.

Termination

Theorem. SOLVE ends after at most ∣C∣⋅(1+∑κ∣Qκ⋆∣)⋅max⁡κ∣Qκ⋆∣|C| \cdot (1 + \sum_\kappa |Q^\star_\kappa|) \cdot \max_\kappa |Q^\star_\kappa| validity queries, plus one query for each check.

Proof. Each pass of L2 to L8 other than the last removes at least one qualifier from some A(κ)A(\kappa), and nothing is ever added. The sets start with ∑κ∣Qκ⋆∣\sum_\kappa |Q^\star_\kappa| elements in all, so there are at most that many passes that change something, and then one pass that changes nothing. A pass makes at most ∣C∣⋅max⁡κ∣Qκ⋆∣|C| \cdot \max_\kappa |Q^\star_\kappa| queries. Each query is an implication in a decidable logic, so each one ends. □\square

The bound uses only the finiteness of Q⋆Q^\star. With an infinite candidate set, such as all linear inequalities, the same loop could remove candidates forever, which is why invariant inference in general needs widening or interpolation (CEGAR and loop invariant synthesis).

Correctness

Soundness. When SOLVE returns AA, every κ\kappa-constraint is valid under AA (the last pass removed nothing), and every check is valid. So the refinement typing with AA put in for each κ\kappa satisfies every premise of S-Base, and it is a valid refinement typing. By the soundness of refinement types, the program does not fail any refined precondition.

Strongest solution. Call an assignment SS a solution if it makes all κ\kappa-constraints valid. The invariant is: for every solution SS and every κ\kappa, S(κ)⊆A(κ)S(\kappa) \subseteq A(\kappa). It holds at L1, since A(κ)A(\kappa) is all of Qκ⋆Q^\star_\kappa. Suppose L7 removes qq from A(κ)A(\kappa), because A(H)⇒θqA(H) \Rightarrow \theta q is not valid, and suppose q∈S(κ)q \in S(\kappa). Since S⊆AS \subseteq A pointwise and liquid variables occur positively in HH, A(H)⇒S(H)A(H) \Rightarrow S(H) is valid. Since SS is a solution, S(H)⇒θS(κ)S(H) \Rightarrow \theta S(\kappa) is valid, and θS(κ)⇒θq\theta S(\kappa) \Rightarrow \theta q because qq is a conjunct. So A(H)⇒θqA(H) \Rightarrow \theta q is valid, a contradiction. So the invariant is kept, and the final AA is the greatest solution: the strongest liquid types. This is the greatest fixed point of a monotone map on a finite lattice of subsets (Knaster-Tarski), reached from the top.

Relative completeness. If any liquid assignment SS over QQ makes all constraints valid, checks included, then SOLVE reports no error. Each check H⇒φH \Rightarrow \varphi holds under SS, and A(H)⇒S(H)A(H) \Rightarrow S(H) by the invariant, so it holds under AA. An error therefore means that no liquid typing over the given qualifiers exists. The program may still be safe, with an invariant that the qualifiers cannot express.

Cost

∣Qκ⋆∣|Q^\star_\kappa| is at most ∣Q∣⋅∣X∣k|Q| \cdot |X|^k for qualifiers with kk holes and ∣X∣|X| variables in scope, so it grows with the number of variables. In practice qualifiers have one or two holes, and most candidates are removed in the first pass. The SMT queries dominate the time.

Classic examples

Maximum. Let Q={ν≥⋆,ν≤⋆}Q = \{\nu \geq \star, \nu \leq \star\} with ⋆\star ranging over the variables in scope and the constant 0, and infer the result of let max x y = if x > y then x else y, with unrefined arguments. The result has scope {x,y}\{x, y\}, so Qκ⋆Q^\star_\kappa is {ν≥0,ν≥x,ν≥y,ν≤0,ν≤x,ν≤y}\{\nu \geq 0, \nu \geq x, \nu \geq y, \nu \leq 0, \nu \leq x, \nu \leq y\}. The two branches give

C1:x>y∧ν=x⇒κC2:¬(x>y)∧ν=y⇒κC_1 : x > y \wedge \nu = x \Rightarrow \kappa \qquad C_2 : \neg(x > y) \wedge \nu = y \Rightarrow \kappa
Step Constraint Removed A(κ)A(\kappa) after
start all six
1 C1C_1 ν≥0\nu \geq 0, ν≤0\nu \leq 0, ν≤y\nu \leq y ν≥x\nu \geq x, ν≥y\nu \geq y, ν≤x\nu \leq x
2 C2C_2 ν≤x\nu \leq x ν≥x\nu \geq x, ν≥y\nu \geq y
3 C1C_1, C2C_2 nothing ν≥x\nu \geq x, ν≥y\nu \geq y

For example, ν≥0\nu \geq 0 is removed at step 1 because x=−1,y=−2,ν=−1x = -1, y = -2, \nu = -1 satisfies the left side of C1C_1 and not ν≥0\nu \geq 0. The result is max:x:int→y:int→{ν:int∣ν≥x∧ν≥y}\mathit{max} : x{:}\mathsf{int} \to y{:}\mathsf{int} \to \{\nu : \mathsf{int} \mid \nu \geq x \wedge \nu \geq y\}.

A loop invariant for array bounds. Take, with len:arr→{ν:int∣ν≥0}\mathsf{len} : \mathsf{arr} \to \{\nu : \mathsf{int} \mid \nu \geq 0\} and get\mathit{get} requiring 0≤i<len a0 \leq i < \mathsf{len}\ a,

let rec sum a i acc = if i >= len a then acc else sum a (i + 1) (acc + get a i)
let total a = sum a 0 0

with Q={0≤ν,ν<len ⋆,ν≤len ⋆}Q = \{0 \leq \nu, \nu < \mathsf{len}\ \star, \nu \leq \mathsf{len}\ \star\}. The parameter i gets κi\kappa_i with candidates 0≤ν0 \leq \nu, ν<len a\nu < \mathsf{len}\ a and ν≤len a\nu \leq \mathsf{len}\ a. The call in total gives len a≥0∧ν=0⇒κi\mathsf{len}\ a \geq 0 \wedge \nu = 0 \Rightarrow \kappa_i, which keeps 0≤ν0 \leq \nu and ν≤len a\nu \leq \mathsf{len}\ a and removes ν<len a\nu < \mathsf{len}\ a (the array may be empty). The recursive call gives κi[i/ν]∧¬(i≥len a)∧ν=i+1⇒κi\kappa_i[i/\nu] \wedge \neg(i \geq \mathsf{len}\ a) \wedge \nu = i + 1 \Rightarrow \kappa_i, which keeps both 0≤ν0 \leq \nu and ν≤len a\nu \leq \mathsf{len}\ a. The check at get\mathit{get} is 0≤i∧i≤len a∧¬(i≥len a)∧ν=i⇒0≤ν∧ν<len a0 \leq i \wedge i \leq \mathsf{len}\ a \wedge \neg(i \geq \mathsf{len}\ a) \wedge \nu = i \Rightarrow 0 \leq \nu \wedge \nu < \mathsf{len}\ a, which is valid. The inferred invariant is 0≤i≤len a0 \leq i \leq \mathsf{len}\ a, and the bound check in get can be removed with no annotation by the user. Rondon et al. (2008) report this kind of result on OCaml benchmarks.

A missing qualifier. With Q={ν<len ⋆}Q = \{\nu < \mathsf{len}\ \star\} only, the call in total removes the one candidate, κi\kappa_i becomes true\mathit{true}, and the check at get\mathit{get} fails because ii could be negative. The program is safe, but no liquid type over this QQ shows it, and the error says only that the qualifiers are not enough.

Variations

  • Horn clause solving. The constraints are constrained Horn clauses with the κ\kappa as unknown predicates. Liquid Haskell's solver, liquid-fixpoint, solves them over qualifiers as above. General Horn clause solvers use interpolation and need no qualifiers, but they may not terminate.
  • Liquid Haskell (Vazou et al. 2014) adds measures (functions such as the length of a list that may be used in refinements), abstract refinements and termination checking, and mines qualifiers from the type signatures in the program.
  • Low-level liquid types (Rondon et al. 2010) infers refinements for C-like code with pointers and a heap.
  • Houdini (Flanagan and Leino 2001) runs the same "start with all candidates, remove the refuted ones" loop with a program verifier in place of the SMT queries, to infer annotations for ESC/Java.
  • Abstract interpretation view. The domain is the finite lattice of conjunctions over Q⋆Q^\star, ordered by inclusion, and the loop is a fixed point iteration in it. A richer domain, such as polyhedra, would need widening to end (abstract interpretation).

Pitfalls

  • The qualifiers decide what can be proved. An error may mean a bug or a missing qualifier, and the tool cannot tell which. Good tools mine qualifiers from annotations and offer defaults.
  • Candidate sets grow fast. Qualifiers with many holes, or many variables in scope, give large Q⋆Q^\star and many queries. Keep holes few and scopes small.
  • Monotonicity is needed. The proof of the strongest solution uses that liquid variables occur only positively on the left of implications. A rule that puts a κ\kappa under a negation breaks the argument.
  • Decidable logic only. A nonlinear qualifier makes the SMT queries incomplete. A query that returns "unknown" must be treated as "not valid", which removes the qualifier and may cause a false error.
  • Precision at higher-order calls. A function passed as an argument gets one liquid type for all its uses inside the callee. Liquid types give each use of a polymorphic function fresh templates for its type variables, which keeps facts about the elements. A monomorphic signature loses them.

Exercises

  1. In the maximum example, why is ν≤x\nu \leq x kept by C1C_1 but removed by C2C_2? Answer. In C1C_1 the result is xx, so ν≤x\nu \leq x holds. In C2C_2 the result is yy with x≤yx \leq y, and y≤xy \leq x fails when y>xy > x, for example x=0,y=1x = 0, y = 1.
  2. Give the bound on the number of passes that change something, for one liquid variable with 6 candidates. Answer. At most 6, since each such pass removes at least one candidate, followed by one final pass that changes nothing.
  3. Why does SOLVE start from the conjunction of all candidates and not from true\mathit{true}? Answer. Loop invariants are inductive: a fact about i at the recursive call follows only if the same fact is assumed for the current i. In the sum example, 0≤i+10 \leq i + 1 follows from 0≤i0 \leq i and not from true\mathit{true}. A loop that starts from true\mathit{true} and adds a candidate only when the current facts imply it never adds 0≤ν0 \leq \nu. Starting from all candidates assumes them all and then removes those that fail.
  4. In the array example, add the qualifier ν=⋆+1\nu = \star + 1. Does the result change? Answer. No. In the scope of κi\kappa_i the only other variable is a, which is an array, so ν=⋆+1\nu = \star + 1 has no well-sorted instance. Q⋆Q^\star for κi\kappa_i is the same, and the result is still 0≤ν∧ν≤len a0 \leq \nu \wedge \nu \leq \mathsf{len}\ a.

References

  1. Patrick M. Rondon, Ming Kawaguchi and Ranjit Jhala, Liquid types, ACM SIGPLAN Conference on Programming Language Design and Implementation (PLDI 2008), pages 159 to 169, logical qualifiers and liquid types, the liquid typing rules, constraint generation with liquid type variables, the iterative weakening algorithm, and the experiments on array bound checks in OCaml programs
  2. Patrick M. Rondon, Ming Kawaguchi and Ranjit Jhala, Low-level liquid types, Thirty-Seventh ACM Symposium on Principles of Programming Languages (POPL 2010), pages 131 to 144, liquid type inference for a low-level imperative language with pointers and a heap
  3. Cormac Flanagan and K. Rustan M. Leino, Houdini, an annotation assistant for ESC/Java, FME 2001, Lecture Notes in Computer Science, pages 500 to 517, the algorithm that starts from all candidate annotations and removes those that the checker refutes until none is refuted
  4. Niki Vazou, Eric L. Seidel, Ranjit Jhala, Dimitrios Vytiniotis and Simon Peyton Jones, Refinement types for Haskell, ACM SIGPLAN International Conference on Functional Programming (ICFP 2014), pages 269 to 282, Liquid Haskell, liquid type inference under lazy evaluation, and termination checking
  5. Ranjit Jhala and Niki Vazou, Refinement types, a tutorial, Foundations and Trends in Programming Languages 6(3-4), 2021, pages 159 to 317, the chapters on refinement inference with Horn constraints and their solution over qualifiers

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • three classic examples