207 points · by adgasf · 10y ago · 79 comments
A program in Haskell can only crash in one way (on a hypothetical computer that doesn't break or run out of RAM): if you write a function that doesn't have an output for every input. You can prevent this through totality checkers such as the one presented in "GADTs meet their match", which you can enable in GHC, the most popular Haskell compiler.
However, programs can still loop forever.
There are several approaches to fix this. One approach is to require recursive functions to monotonically decrease on their arguments. Languages like Idris and Agda support this. The downside is you are no longer Turing complete.
The approach mentioned in the paper is to make a formal distinction between finite and infinite data (data and codata), and in this way you can keep termination checking for functions on finite data, but you also get to keep Turing completeness. What you do instead of proving completeness for functions that might run forever is you prove that the function "does something useful" every time it recurses.
If not, your program could be "total" in most of the useful senses, and subparts could have tighter bounds, without any harm.
Also, I recommend reading Harper's throughts about it:
"Old Neglected Theorems Are Still Theorems" https://existentialtype.wordpress.com/2014/03/20/old-neglect...
It also reminds me of the NASA coding standards, rule 4:
"All loops must have a fixed upper-bound", see http://pixelscommander.com/en/javascript/nasa-coding-standar...
(Related HN discussion: https://news.ycombinator.com/item?id=8856226)
A tactic language doesn't need to be total, since it's only run at compile-time, so no errors can leak into the resulting proof/program. The worst that can happen is the compiler hangs.
Coq comes with "ltac", which is a horrible imperative language that leads to very fragile proofs. On the other hand, mtac is just Coq's normal, total FP language ("gallina"). A monad is used to wrap up general recursion, so that gallina can be used un-changed.
During compilation, these monadic values are forced, which either leads to a value or causes the compiler to hang. This is a really nice compromise, since you can write Haskell-style FP code which "obviously terminates", without having to prove that it terminates, you still have access to all of the nice dependent type machinery, and the end result (the program, not the meta-program) is guaranteed to be total (unlike, say, an Idris function which turns off the totality checker).
What are you referring to? Data/codata checking works with local type inference.
This is similar to the Brown-Palsberg self-interpreter in a total language, which caused a lot of confusion recently because it's not a self-interpreter (it doesn't take source code as an argument). I think it's better to stick with common definitions and accept that total languages are not Turing complete and can't self-interpret.
Free (() ->) Integer
And then using corecursion to evaluate this step by step.The actual definition of Turing completeness is the ability to implement any program that a Turing machine can compute, which you can with corecursion.
http://docs.idris-lang.org/en/latest/tutorial/theorems.html#...
The topic often comes up in the discussion of smart contracts on public blockchains, and people often get confused about what Rice's theorem says. I recently did a small write up on the topic (plug, plug)
https://hackernoon.com/smart-contracts-turing-completeness-r...
In your post, you write:
> However, almost all correct programs of interest are going to be essentially provably correct. Moreover, the proof of their correctness will be relatively straightforward.
This has been shown to be false in practice. The difficulty of proving real-world program correctness shows that real-world cases can get arbitrarily close to the worst-case predicted by the theory. Proving small programs like seL4 took required experts, and even then demanded an extreme simplification of all involved algorithms so that proof would be feasible. Even then, the cost was far beyond what any "ordinary" software could afford, and even after a great streamlining of the process and the use of "easily verifiable" languages, it is expected to be suitable only for resource-rich high-assurance software.
Note that I'm not saying that formal methods are useless. I regularly use formal methods myself. But making them affordable is an art.
I've written at length about the relevant theory here: http://blog.paralleluniverse.co/2016/07/23/correctness-and-c...
1) Yes, even in weak models, proving correctness is still intractable in general. However, this does not mean that a general algorithm has to be slow when run on typical instances. Typical instances are designed with a proof of correctness in mind, which is a strong indication that such a proof should be accessible.
Unless you're generating programs randomy, programming generally entails carrying at least an informal proof of correctness in mind.
2) As you point out it is currently very hard and tedious to formalize those proofs. However, I believe this isn't a fundamental barrier. We need better tooling, more clever proof-finding algorithm to bridge the gaps, clearer interfaces. Importantly, it is not a computational barrier.
There is nothing about the formal verification of typical software that intrinsically requires expensive computations. Compare it to image recognition. It used to be very hard to do in software and it didn't work well. But when it finally started working, it didn't turn out to be particularly computer intensive.
I think the same is true in formal verification. We don't know how to do it very well, but we're not up against theorems in complexity theory, we just lack the know-how.
True, but we have a few decades of experience with model checkers running on real programs. Yes, they work very well and are quite affordable, but their domain is rather specific (there is amazing work on model checkers designed to expand their domain and work on ever-larger programs, but the results aren't in yet).
> Unless you're generating programs randomly, programming generally entails carrying at least an informal proof of correctness in mind.
There are various results showing that the difference in size between an informal proof (even when correct, which, as experience shows often isn't[1]) and a formal one may be exponential.
> We need better tooling, more clever proof-finding algorithm to bridge the gaps, clearer interfaces.
Absolutely, but we must understand there are fundamental problems in play.
> Importantly, it is not a computational barrier. There is nothing about the formal verification of typical software that intrinsically requires expensive computation.
This is unknown, but not very promising; certainly not promising enough to assume this will definitely be possible some day (let alone soon). See the result about symbolic model checking (basically the cost of proof that is allowed to exploit linguistic constructs) that I mention in my post. It turns out that in the general case (this time, we're not talking about completely "random" programs, but "random" programs that can be expressed succinctly in some language), it is as hard as a proof that doesn't exploit language, and the difficulty was found to hold in practice (the paper I quote calls it an "empirical fact"), i.e., real-world programs do get close to the worst-case.
The goal of software verification nowadays isn't to find methods to verify general programs, but to find methods that catch a particular class of bugs (static analysis) or to prove arbitrary properties for specific domains or small programs (model checkers). The PLT approaches mostly focus on end-to-end verification, and don't currently attempt to make it affordable for "ordinary" programs. They're trying to make it as affordable as high-assurance testing (the kind done at NASA). In the seventies, the hope was that formal methods would one day allow us to prove arbitrary correctness properties of ordinary software. This is no longer the goal of the verification community today, despite the great achievements in some areas.
[1]: Even when the informal proof is not just "in mind", but on paper, written by experts and peer reviewed: https://brooker.co.za/blog/2014/03/08/model-checking.html
[0] Specifically the generic case decidability of the Halting Problem for one-sided tape Turing Machines? https://en.wikipedia.org/wiki/Generic-case_complexity#The_ha...
As to whether the class of programs humans write are theoretically feasibly verifiable, nobody knows for sure, but the problem is certainly not easy, judging by all attempts so far.
My favourite point was that simply by adding an instruction counter, we can make every program terminate, but this does not make the program considerably easier to reason about. It reminds me of Ethereum's limit on Turing Completeness (Gas).
So the idea seems to be a programming framework that on one hand guarantees termination, while on the other hand is sufficiently powerful to be useful. That is "useful despite being sub-turing".
I spent some time causally studying the subject of sub-turing languages, and found something notable. If a language guarantees that all its programs consume input as they go, that program is guaranteed to terminate, and so the language itself is sub-turing. One example of such program could be a compiler, which makes for a great example of a useful application of a sub-turing language.
It's a fascinating subject because sub-turing language programs are a lot easier to analyze.
link(codegen(analyze(typecheck(parse(lex(source))))))
And compilers are one of the easiest kinds of programs to write naturally in a functional language.This has been called being "Pacman Complete" by Edwin Brady. I very nice catchy term, IMO.
The paper opens with:
The driving idea of functional programming is to make programming more closely related to mathematics.
From a paper by John Backus:
Associated with the functional style of programming is an algebra of programs whose variables range over programs and whose operations are combining forms. This algebra can be used to transform programs and to solve equations whose “unknowns” are programs in much the same way one transforms equations in high school algebra.
Are they talking about the same thing here?
Also, are there advantages to having such an algebra of programs outside of correctness verification?
Yes, they're talking about roughly the same thing. The kernel of the idea is called "equational reasoning", which exploits the key mathematical characteristic of functional programs, that they are referentially transparent [0].
> Also, are there advantages to having such an algebra of programs outside of correctness verification?
Proving correctness is a big one, but you can also use these techniques to derive more sophisticated algorithms from a naive (but correct) first implementation. For an example, see section 4 on the implementation of an efficient minimax algorithm in a short paper by Richard Bird [1]. (You will have to read some of the previous sections to understand the example.)
If that piques your interest, Bird's introductory book on functional programming written with Philip Wadler [2] introduces the technique, which is usually called "program calculation". (Though published in 1988, their book remains a great introduction to functional programming.) If you really want to go off the deep end, Jeremy Gibbons's extensive lectures notes, published as a book chapter [3], are the best source I know. (Beware: here be category theory.)
0. https://en.m.wikipedia.org/wiki/Referential_transparency
1. R. Bird (1988), "Algebraic identities for program calculation", http://comjnl.oxfordjournals.org/content/32/2/122.full.pdf [PDF]
2. R. Bird and P. Wadler (1988), Introduction to Functional Programming. It's out of print and hard copies are scarce, but a scan is available at https://usi-pl.github.io/lc/sp-2015/doc/Bird_Wadler.%20Intro... [PDF]
3. J. Gibbons (2002), "Calculating Functional Programs, http://www.cs.ox.ac.uk/jeremy.gibbons/publications/acmmpc-ca... [PDF]
Totality does in no way make proving correctness easier in practice. See http://blog.paralleluniverse.co/2016/07/23/correctness-and-c...
Totality really mostly helps when using typed programming languages as proofs of general (non-executable) mathematical theorems via propositions-as-types. Without it, the logic will be inconsistent. For actual programs, though, it makes little difference.
It's not just that "there is more", it's that there is everything.
The halting problem which we're talking about here is actually easily generalizable into a set of generic theorems about static analysis of programs in general. The usual first step is to prove the first incompleteness theorem (no axiom system proves all of the interesting facts about the integers), then modify that into a proof of the second incompleteness theorem (that every logic which proves its own consistency must be inconsistent). But it goes way further than that to Rice's theorem: every nontrivial semantic property of a computer program is undecidable. Put another way, the only way for the compiler to know that something is true is for there to be a really simple up-front convention which makes it true.
Suppose you want to make sure, statically, that you never dereference a null pointer. This says that the only way a compiler could ever be strong enough to prove this is if it's syntactically impossible to create a null pointer in the language in the first place, so that it's a "trivial property" of all programs that they never dereference null pointers.
Suppose you want to prove that a certain block of code is the fastest possible code which does a certain thing. The only ways to do this require the language to "normalize" all of its expressions so that there is only one block of code for everything you want to do. If there's more than one way to do it, then the analysis "is this the fastest code?" is nontrivial and you can't prove it! (You can always get heuristics of course to try to cover the most common cases, but your heuristics will never cover everything you want.)
Suppose Microsoft wants to fix Word and Excel's macro systems to a new form that cannot contain viruses: the only way to do that is if the macro system is either (a) Turing-incomplete, so that you can analyze its programs, or else (b) unable to do the virusy things that you're worried about in the first place. Otherwise there will always be a macro-virus which passes the virus-checker.
No, no, no. The original halting theorem is avoided in total languages, but the much more important version which forms the core of the time-hierarchy theorem, sometimes known as "bounded halting", holds unchanged. It is a generalization of halting which basically says that you cannot know anything about a program (including halting) any faster than running it (more precisely, you cannot know whether a program P halts in input x within n steps in fewer than n steps; all the other corollaries like Rice follow in the same way). This means that the cost of verification is the same for total and non-total programs, with the theoretically interesting but pragmatically irrelevant promise that the cost is some unbounded finite number in the total case.
If you want to convince yourself that totality cannot make proving program properties easier with an intuitive argument, consider this: take any program ever written, and to every loop and every recursive call add a counter initialized to 2^100 that is decremented with every iteration/recursion and stops the program when it reaches zero (which will not happen until the end of the universe). Your program is now provably total, yet its semantics have not changed a bit. I.e., you can already assume without loss of generality that every program is a total program and that every language is a total language. Is verification easier now that you know this?
The only case where you cannot make this assumption is when your language is used as a theorem prover to prove general mathematical theorems (that aren't executed and may actually "reach" infinity), and this is where totality matters.
See my post for a more in-depth discussion: http://blog.paralleluniverse.co/2016/07/23/correctness-and-c...
And we usually don't wait that long. A function that executes when loading a web page times out in the order of seconds.
Once you have deadlines, all bets are off - the function is not deterministic for any large enough input. Equational reasoning does not preserve performance - it could cause a program that previously ran fast enough to time out.
So, knowing that function terminates seems only theoretically useful. It doesn't tell us whether a program change is really safe. It would be more useful to put some kind of bound on the resources a function can consume.
In Etherium's language, there is a concept of "gas" which is an abstract limit on how much work a function can do. (The advantage over a timeout is that it's not machine-specific.) I sometimes wonder if anyone has applied this concept to functional programming? Could we define a language so that it uses static analysis to maintain guarantees about a function's use of gas?
Have a look at areas like "cost semantics", e.g. http://lambda-the-ultimate.org/node/5021
This takes a language's semantics, i.e. how to evaluate each sort of expression, and extends it to include extra information which can represent time taken, memory usage, cache usage, etc.
A simplistic way to track big-O complexity in types is given at http://twanvl.nl/blog/agda/sorting
Note that "gas" systems don't need to produce their result within the given gas limit; it's acceptable for the gas to run out and no value to be produced. This is trivial to prove correct, as it only requires that the language/DSL correctly keeps track of the gas, which can be done "once and for all" since it doesn't have anything to do with whatever algorithm you're writing to use the gas.
The machinery for doing that is old hat to functional programming: tracking gas usage is basically a Writer; stopping when gas runs out is basically a Maybe.
Statically ensuring that a function is within a gas limit is like statically ensuring that a "Maybe t" value contains a "t" value (as opposed to "Nothing").
fib (n+2) = fib (n+1) + fib (n+2)
Something's wrong there...There are also essentially no total languages today. Idris, Coq, etc. have support for totality, but there's nothing widespread or simple that does. I expect a total language would be quite useful in certain contexts (real-time, scripting, running user code, compilers), but the drive for - I can do whatever I want in this language - is so strong that a total language would need to provide significant, useful advantages to see adoption.
1. Totality doesn't guarantee that your program would actually terminate. A program that loops 2^100 times never terminates, yet is provably total. It is possible that empirically programs that are proven total turn out more likely to terminate, but in that case there is no need to enforce totality everywhere. You can prove termination whenever you like.
2. Proving totality can be extremely hard (yet another reason not to enforce it everywhere). So much so that Xavier Leroy, the world-expert who wrote CompCert, the only real-world, non-trivial program ever written in Coq, found termination proofs so difficult that he skipped them in CompCert, instead inserting a counter that he thought would suffice and throwing a runtime exception if it ever runs out before the function terminates.
As to total programming languages, safety-critical real-time software sometimes makes use of languages that are finite-state-machines, a far more restrictive model than Turner's total language. Nevertheless, bear in mind that even for FSMs, program verification is not generally tractable. How easy it is to verify a program depends almost entirely on one thing: how simple your algorithm is. All sorts of linguistic restrictions or safe runtimes can help prevent very important classes of bugs (like memory safety) that are local program properties, but do very little to make the cost of more global, logical properties affordable (which isn't surprising given that even the most restrictive computation model, the FSM, doesn't yield generally feasible verification).
As you obviously meant, no total general-purpose languages. I'm sure that HTML is total, for example. You also later qualified that "no total languages" meant "no widespread, simple, total languages", which I think is a very different statement!
It seems to me that your next sentence addresses this better than I could.
> that's not very interesting from the standpoint of totality: we already know that Web browsers are supposed to show something no matter how mangled their input is.
So isn't it interesting that they do that? I think that the prevalence of scripting languages on the modern web (and, if you like to look farther back in history, the reluctant Turing completeness of TeX) strongly suggests that it wasn't at all inevitable that we would get a total language for web design.
That is, to prove that it is total is presumably not much of an accomplishment, but that it is total is very interesting (and, from the point of view of the success of the web, important) indeed.
Edit: As far as HTML goes, I was attempting to describe "programming languages" - or perhaps algorithmic languages - which I don't consider HTML falling under.
For example, something as simple as assigning a variable has so much more meaning and functionality than I am used to, thanks to pattern matching.
I look forward to diving deeper into functional programming. Thanks for posting.
Functional programming tends to take this even further, by eliminating variable assignment to some degree or another. Different languages approach this differently, for instance:
- Erlang (and I assume this extends to Elixir) asserts a variable's value, rather than assigning it. You can see how this works by attempting to assign another value to the same variable: it will throw an error.
- Clojure (and I assume most lisps?) bind a variable to a symbol, but that only applies to the code that follows; if you access a binding, then rebind it, the previous access will only reference the original value. (Clojure, being impure, has ways around this in a bunch of ways.)
Once I grokked FP, I started thinking about this the other way around. If I see code like this in FP:
x = 5;
foo
I read this as "evaluate 'foo', substituting 'x' with '5'" (accounting for shadowing, etc.). In other words, it's sugar for "let x = 5 in foo", or "(lambda x. foo) 5".In contrast, I read the same 2 lines in an imperative program as "first update the contents of memory location 'x' to contain '5', then evaluate 'foo'". This is much more complicated (i.e. has more meaning/function) than the FP version:
- We're specifying an evaluation order (do this, then do that), whilst the FP version works with any evaluation order. Among other things, this makes it difficult to evaluate in parallel (imagine if '5' were 'someExpensiveCalculation' and 'foo' were 'anotherExpensiveCalculationWhichMightNotUseTheFirst').
- We need a notion of "memory cells", which don't follow the lexical/syntactic nature of scoped variables; i.e. the first line may affect references in a seemingly separate piece of code. This makes reasoning much harder (although techniques like separation logic can make many common cases easier).
- The 'foo' calculation may affect the contents of 'x', so we can't trust the "equation" 'x = 5' to hold after (or even part-way-through!) the evaluation of 'foo'
One nice approach is "static single assignment"; it looks imperative (e.g. "single assignment C" looks like C), but it follows the FP semantics. In other words, it's useful when you want to show that your code is "straightforward": if you write it in C, the maintainer/compiler might guess that it's straightforward (e.g. that you don't invalidate the "x = 5") but doesn't know; in single assignment C, they know because the compiler enforces it.
https://en.wikipedia.org/wiki/Charity_(programming_language)
Very interesting stuff.