Study notes: A Postscript to Curious OCaml

Recall questions for A Postscript to Curious OCaml: OxCaml, Rust and Lean. Answer each from memory, then open the answer to compare. The link under a question leads to the section it draws on.

Before reading

The essay and these questions assume:

Helpful, not required:

Questions

The answers state what the essay says. It is written in the first person by Łukasz Stafiniak, with Claude, as a postscript to the fourth edition of Curious OCaml. The programs it reports were written and run by agents, and “we” means the two authors. Several questions ask you to read a piece of code from the essay, so keep the essay open at the section a question names.

Five times

state

A promise made in a comment can be checked at five different times. Name them in order. Which of them does the book’s file-reading module use, and what does the essay say languages differ in?

Answer

The promise can be left in the comment, where nothing checks it. It can be checked while the program runs. It can be checked by a test, on the inputs the test tries. It can be checked by the compiler, in every program that uses the module. It can be proved, for every input. The five run from latest to earliest. The book’s module checks at run time: a flag active is cleared when the file is closed, and a read through an escaped reader raises. Languages differ in how far along that order a promise can be moved, and in what the move costs.

The four promises

recall The book ↗

Which four promises does the essay find in the book, and how does the book keep each?

Answer
  1. A reader is not used outside the scope that opened its file. Kept by a flag.
  2. A suspended computation is resumed exactly once. Half kept, by an exception.
  3. No code changes a mutable cell that other code is relying on. Kept, in the book’s scheduler, by running everything on one thread.
  4. A module satisfies its laws. Kept by tests.

The first three are about how a value is used. The fourth is about what a module does.

One annotation

What single change makes OxCaml’s compiler keep the reader’s promise? What does the change say, what does the compiler then refuse, and what still got through?

Answer

The function consume is declared to take the reader at mode local: (consume : (unit -> 'b option) @ local -> 'a). A local value may not outlive the region it was given to, and a region is roughly the extent of a call. So the annotation says that the consumer will not keep the reader. The compiler then rejects a caller that returns the reader, one that stores it in a reference, and one that returns a function which calls it. The agent tried twelve ways round and the compiler refused eleven. The twelfth was a hand-written external declaring the identity function to turn local values into global ones, and it compiled without a warning. Twelve attempts are not a proof.

The price on the next page

The book’s own first_lines is rejected against the annotated module. Why, and what did it take to get it accepted? Which annotations did the compiler not need?

Answer

stream_of_reader turns the reader into a lazy stream whose tail is a function that holds the reader, and a stream that holds the reader could carry it out. The compiler cannot see that stake uses the stream up on the spot. Getting the three lines accepted took a second stream type whose tails are local, and five annotations: @ local on the tail’s result and @@ global on the element, both in the type, exclave_ twice, and [@nontail] once. @@ global says a field never holds a local value. exclave_ builds a result in the caller’s region. [@nontail] stops a call from being a tail call, so that the region is still there when the call returns. Nothing says that lstake and lstream_of_reader take their arguments locally. The compiler infers that.

Where inference stops

A helper function with no annotation accepted the local reader in one place and refused it in another. Where, and what rule explains the difference? What follows for libraries?

Answer

Written in the same file as its use, the helper accepted the reader. In a file of its own it did not, with an ordinary interface or with none. OxCaml infers a parameter local only when a use in the same file needs it, and otherwise exports it as global. So whether a library works with local values depends on what it declares and not on its code. List.init, List.iter and Seq.unfold refused the reader for that reason. Jane Street’s own libraries are annotated, and a library written for plain OCaml is not. An experimental extension in the installed compiler infers the general mode and exports it, and with it the helper worked from its own file.

Three answers to one promise

How do OxCaml, Rust and Lean 4 each treat the promise that the reader does not escape? Say for each what it leaves open.

Answer
  • OxCaml checks it in the compiler with a mode. local has two levels, this region or global, and cannot say “as long as that particular outer scope”.
  • Rust checks it with a lifetime. In a direct translation no lifetime is written: &mut lends the reader for a lifetime the compiler fills in, and the result type cannot carry it out. A Rust programmer would not write the module at all, since the file is a value whose destructor closes it on every path. A program may still call std::mem::forget and skip the close.
  • Lean does not check it, and the escape is harmless. IO.FS.withFile closes nothing. Lean counts references, and the handle is closed when the last one goes.

Eleven and two

Count the presses of the shift key in std::io::Result<Vec<String>> and in the same type as OCaml would spell it, string vec Std.Io.result. What does the essay conclude from the count, and from the author’s reading of the local stream?

Answer

In the Rust spelling each :: is two shifted colons, which gives four. R, V and S give three, and the four angle brackets give four. That is eleven. In the OCaml spelling only S and I are shifted, which gives two. The essay also counts punctuation in the experiment’s programs: 30 percent of the characters in the Rust files, 18 in the OCaml and 20 in the OxCaml, from few and short files. OxCaml’s local stream carries five ownership marks spelled as words, and it reads fine to the author. So part of what he felt as bloat in Rust was spelling.

Runs or computes

The Rust signature of with_lines is impl FnOnce(&mut dyn FnMut() -> Option<String>) -> R, with path: &str. In OCaml the function’s type is string -> ((unit -> string option) -> 'a) -> 'a. Say what each extra mark in the Rust signature tells, and how RAII bears on the distinction.

Answer

impl and dyn say how the two calls are compiled. &str and String say who frees a piece of text. FnOnce, FnMut and &mut say whether a function is consumed by its call, changed by it, or lent. None of this changes which lines come out, so these are distinctions about how the program runs and not about what it computes. RAII ties the two. A loan is seldom essential to what a function computes, yet in this signature the &mut is what keeps the reader inside its scope. Who owns a piece of text matters only to how the program runs. Who owns a file decides when it is closed, which is part of what the program does. Rust has one mechanism for both, so every string is written with the care that only the file needs.

Defaults

The essay says much of the difference between Rust and OxCaml is in the defaults. State the two defaults. What did OxCaml still ask for in the local stream, and of what kind are those marks?

Answer

In Rust every value is owned or lent, and each signature says which. In OxCaml a value is shared and collected unless a mode says otherwise, and within a file the compiler infers the modes of functions. The local stream still needed two marks in a type and three about regions. exclave_ and [@nontail] are about how the program runs, as dyn and String are. OxCaml asks for them only where a mode has been asked for.

Two rules in “exactly once”

“Exactly once” is two rules. Name them and the two kinds of type system. Then say who checks each rule, and when: OCaml, OxCaml as shipped, OxCaml with the agent’s wrapper, and Rust.

Answer

The rules are at most once and at least once. A type system that enforces the first is affine, and one that enforces both is linear.

  • OCaml checks the first at run time, by an exception on the second resumption, and the second not at all.
  • OxCaml has a mode once, but its shipped interface to effects does not use it and raises the same exception.
  • With a wrapper of about twenty lines that hands the handler its continuation at mode once, a handler that resumes twice does not compile. The second rule stays unchecked.
  • Rust has no effect handlers. A closure of type FnOnce called twice is a compile error. A closure dropped without being called runs the destructors of what it captured, so a captured file is closed after all, unless the closure is forgotten with mem::forget.

No compiler in the essay checks that a continuation is not dropped.

The token

What does OxCaml add so that a missing handler is caught before the program runs? What does it cost, and what does it fail to prove?

Answer

The safe way to perform an effect takes a token, which a handler supplies and which is proof that the code is running inside one. The cost is that every function between the handler and the perform passes the token along. The book’s chapter lists “No infection” among the gains of effects over monads, and the token brings a little of the infection back. It also proves less than one would like: that some handler is installed, and not that the handler knows this effect. A program whose handler handles Ask and whose body performs something else compiles, and stops at run time with Effect.Unhandled.

Where two promises meet

A consumer of the scoped reader performs an effect while inside the scope, and the handler drops the continuation. Predict how many times the file is closed, and say why neither of the checks from the first section helps. Does it differ between OCaml and OxCaml?

Answer

The file is closed zero times. The run printed closes = 0. The close is in the finally of Fun.protect, which runs only when the consumer returns or raises. The consumer is suspended and never resumed, so the scope is never left. The flag checks reads after the scope has ended, and the scope has not ended. The mode checks that the reader does not leave the scope, and it has not left. The result is the same in OCaml and in OxCaml.

Four lines

let a = ref 1 in let b = a in b := 2; assert (!a = 2). What does OCaml do with these lines, what does Rust do with their counterpart, and where does OxCaml step in? What does OCaml 5 promise a program whose domains race?

Answer

OCaml accepts the lines and the assertion holds: a and b are two names for one cell. Rust refuses the counterpart, because a value that is being changed through one reference cannot be read through another, even on a single thread: “cannot borrow cell as mutable because it is also borrowed as immutable”. So Rust restricts the aliasing itself. OxCaml leaves a single domain as the book describes it and steps in only where a second domain could look. A value is contended if another domain may be writing to it, and then its mutable fields may not be touched. A function is portable if it may be sent to another domain. Shared mutable state goes in a capsule, reached only while its lock is held. OCaml 5 lets a program race and limits the damage: memory safety is preserved, and a race cannot disturb unrelated data or earlier and later moments of the program.

Neither contains the other

Give the essay’s answer to whether OxCaml is simply better than Rust. Name what each can say that the other cannot, how their features combine, and the verdict.

Answer

No. Rust can name a scope and tie a value to it, lend a value for writing and take it back, and produce a program with no runtime system under it. Its traits find the implementation that fits a type without being told. OCaml and OxCaml share data freely because a collector frees what nobody holds, and they have functors, effect handlers, generalized algebraic data types and guaranteed tail calls. In OCaml most features can be used without thought for the others, and much of that follows from the collector. Rust’s ownership reaches into every feature: three kinds of closure, two kinds of string, and a type of its own for a function that may suspend. Where OxCaml was asked for a mode, features stopped being independent too. The verdict: as designs, neither contains the other. Wherever the runtime, the platform, the libraries or the promise of stability decides, Rust is better, and those decide often. For a program that is already OCaml and needs control in a few places, OxCaml is better, if one can live on one firm’s schedule.

Three ways to generate code

A language can help with generating code in three ways. Name them, say which language offers which, and say which one the author’s project needs and why MacoCaml would not supply it.

Answer
  1. Compiling code while the program runs. MetaOCaml does it, and OxCaml now has typed quotations that are spliced, compiled and run at run time.
  2. Macros, code that runs while the program is being compiled. Rust has them. OCaml has preprocessors, separate programs that rewrite a file’s syntax tree before it is type-checked. MacoCaml is a research design of typed macros for OCaml, implemented in a fork of the compiler. OxCaml has the quotations and not the macros.
  3. A preprocessor that knows the types. This is what OCANNL needs: its notation for tensor code is a syntax extension, and in OCaml a syntax extension runs before type inference. Rust’s macros run before the types are known too.

MacoCaml’s macros are purely generative: they build code and cannot take apart the code they are given. In Part II the essay names Lean’s elaborators, which run inside the type checker, as the thing itself.

What the suite establishes

What does the book’s Map_laws suite assert, and on which maps? What does the chapter say that is worth, and why does the essay call OCaml the wrong place to give the proof?

Answer

The suite takes any module with the signature of a map. Its check asserts the map axioms for one map: member agrees with find, a key added twice is found with its newer value, a removed key is gone, and adding or removing one key leaves the others undisturbed. It runs check on every map that can be built from the empty one by at most three additions and removals of three keys. The chapter calls that evidence and not proof, and says a proof would state the invariant of the representation, show that empty satisfies it and that add and remove preserve it. OCaml is the wrong place for the proof because an OCaml type is a weaker claim than a proposition: every OCaml type is inhabited by a program that loops or raises.

Three things said

Porting the search tree to Lean weakened no law, but three things had to be said that the OCaml leaves unsaid. What are they?

Answer
  1. The order on keys. OCaml compares keys of any type with a built-in <. Lean wanted a relation and its laws: nothing is less than itself, the relation is transitive, and two different keys are ordered one way or the other.
  2. That a helper cannot fail where it is used. The OCaml split_rightmost raises on an empty tree and is called only on a tree that is not empty. In Lean it returns an optional result, and the proof shows the empty case does not arise.
  3. Which equality is meant. With floating-point keys the book’s own law fails in OCaml, because nan is not equal to itself. The Lean version chose an equality in which everything equals itself. In OCaml the matter is a sentence in the text, and in Lean it is part of the definition.

Reading the proof

In the proof that add keeps a tree ordered, where do the three cases for a node come from? Which case needs a law of the order, which law, and why is the fact it needs not already at hand?

Answer

simp only [add] replaces add by its definition, which contains two ifs. A split divides the proof at an if into the case where the condition holds and the case where it does not, and records which. The first split is on k = k2 and the second on k < k2, which gives the three branches of add. If the keys are equal, the four proofs of the node’s clauses serve as they are. If the new key is smaller, add goes left, the proof for the left subtree is replaced by the recursive call, and a lemma shows the left subtree’s keys are still below the root. The last case needs the fact that the root’s key is below the new one. Neither split recorded that. They recorded that the keys differ and that the new one is not the smaller, and the third law of the order, totality, turns those two into the fact needed. It is the only place where the proof uses a law of the order. The recursive call is the induction, and the pattern that takes the proof of Ordered apart treats a proof of a conjunction as a tuple.

What needs the invariant

The proofs found something nobody had asked. What is it, how can it be read off two theorem statements, and why could the test suite not show it?

Answer

The laws about add hold for every tree, ordered or not, and for every relation <, lawful or not. add and find walk down the same path, whatever the path is, so find finds what add put there. Only the laws about remove need the invariant. The statement of find_add_self has no hypotheses beyond the key, the value and the tree. The statement of find_remove_self asks for a lawful order and for a proof that the tree is ordered. The test suite could not show the difference because it only ever builds ordered trees.

Why it stops

Lean rejects the Datalog engine’s loop when it is written as the book writes it. What does Lean ask for, and what is the answer in this case?

Answer

The loop applies its rules round after round until a round adds nothing, and Lean answers “fail to show termination”. A recursive function in Lean can be reasoned about only if Lean has a reason why it ends. Here the reason is that every round stays inside a finite set of possible facts, those that can be written with the program’s constants. The OCaml engine depends on that and never says it.

Four difficulties

The essay grants that the case for proving with agents has become stronger, then gives four difficulties. State each with the essay’s own example.

Answer
  1. An account of a proof can be wrong while the checker is right. An agent left three holes and reported the rest too hard; its log said otherwise, and sent back it finished. The source file can mislead in the same way.
  2. The statement. A checked proof establishes its statement, and whether the statement says what was meant is a separate question. The red-black theorem says deletion returns a valid tree and does not say the tree holds exactly the other keys.
  3. A failed proof says less than a failed test. The test for the lecture’s bug printed a counterexample. The attempted proof of the broken code stopped at goals that showed only difficulty, and concluding that the statement was false still took a witness.
  4. The boundary. The proof is about Lean code transcribed from the book’s OCaml, and nothing proves the transcription matches. A proof also stops at the edge of the language: an audit of a proved compression library found no error in the proved code and two outside it, one in Lean’s runtime.

The source file can mislead

A search of a Lean source file for the word that marks a gap finds nothing, and yet a theorem in it rests on an unproved assumption. How can that be, and what shows it?

Answer

When a Lean file has an error in it, Lean puts an unproved assumption in place of the proof that failed, and nothing in the file says so. The command #print axioms lists what a theorem depends on, and there the assumption appears as sorryAx. The command gives the checker’s answer, where the source file gives only an account.

What a test says and what a proof says

Compare what a failing test and a failing proof tell an agent. Then give the essay’s example of the opposite case, where the proof found what tests had not.

Answer

A test says no and hands over an input: insert 1, 2 and 3, remove 1, and the tree is no longer valid. A proof says yes. Asked to prove the broken deletion correct, Lean stopped first at a goal that showed only that the proof was hard, and after one more case split a goal read False at the case the code mishandles. To conclude that the statement was false still took a witness. In the other direction, the first invariant the agent tried for the corrected deletion held on fifty thousand tested cases and was too weak to carry the induction. An agent needs both.

The reservation

Where does the author’s reservation about proof lie, what is his reason, and what does he propose instead? Which finding of the essay does he count as an example?

Answer

The reservation is about building code that is verified from the start. The errors measured this year are in statements, and a statement written before the program has run has nothing to be checked against. What makes sense to him is the other order: to explore running code, and to update it with specifications that are insights into the problem. That add needs no invariant is, he thinks, an insight of this kind. It came from a proof, about code that already worked. On the wider question the essay’s answer is no: as a language to write programs in, Lean is behind OCaml and Rust in libraries, stability and its interface to C, and as the place where a program written elsewhere gets its proof it has become affordable quickly.

What found the defects

The authors counted what rejected the agents’ work during the making of the edition. What had they expected to head the table, what headed it, and what can such a count not see? How were the edition’s defects found?

Answer

They expected the type checker to head the table. The most frequent rejection was a chapter whose executed output no longer matched its text, and the compiler came second. The type checker may have prevented a great deal before any run, and a count of rejections cannot see that. The book’s standing tests mostly did not find the defects. In case after case an agent read something, doubted it, and wrote a probe, a throwaway program that typically ran in a third of a second. The tests in the book came afterwards, to fasten the fix down. So the first thing these agents had was a loop fast enough to make doubt cheap, and an interpreted language would do as well on that point.

Three senses

“Does the way types structure thinking apply to an agent?” The essay gives the question three senses. State them and the kind of evidence it has for each.

Answer
  • Feedback: the checker rejects and the agent repairs. This is measured, by a study of compile errors in models’ TypeScript and by the authors’ own count.
  • A plan held while writing: a signature in view narrows what is written next, and a type with five cases asks for five branches. There are measurements when the constraint is applied from outside, by forcing output to be well typed as it is produced.
  • A habit, carried into places where nothing enforces it. For this there was no evidence, so the authors ran an experiment.

The experiment and its result

Describe the experiment on working types first and its main result. What did differ, and what did the agents asked to extend the programs do?

Answer

Agents wrote a small Datalog interpreter from a precise specification, against hidden tests, in OCaml, TypeScript and Python. Half were told to work types first, writing the kinds of things in the problem as types and an interface for every module before anything else, and half were told nothing about method. Each program by the faster model was then handed to a fresh agent with an extension to implement. The main result is that nothing happened: correctness was the same under either instruction in all three languages, and the task was too easy to show a difference. What differed was the shape of the programs. The precise type appeared unasked where the language made it cost one line, as for terms in OCaml and TypeScript, and nowhere else. In Python the uninstructed declaration of terms was a comment. For the kinds of error nobody wrote a type until asked, and in Python not even then. The extenders wrote to the representation they found: a case added to a type where there was a type, a string where there were strings.

The rider

The memoir said that agents and people benefit from the same things, strictness and a compiler that checks every case is covered. What rider does the essay add, and from what observation? What does it warn against concluding from the experiment?

Answer

One OCaml extension introduced a bug that OCaml warns about, and the warning never appeared, because the agent that wrote the original program had put a flag in its build script that turns all warnings off. Two others of its group had done the same. The essay sets this beside writing any in TypeScript and weakening a theorem. The rider: a compiler that checks every case is covered helps an agent as it helps a person, provided the agent cannot quietly tell it to stop. The warning against over-reading: nothing in the experiments shows that OCaml’s types made agents more correct. The failures that differed between languages concerned strings read as text in one encoding and written in another, which no type checker in the three languages would have caught, and there were too few to be sure the languages differ at all.

What the reader needs

The author no longer writes the code and asks what he needs as the one who reads. Can the part that must be read be made small? Give the essay’s answer, its evidence, the one saving it allows, and what it says about laws that concern speed.

Answer

It would be convenient if the part to be read were small and the part a machine checks were large, and it is not so simple. What a program is meant to do can seldom be said in much less space than the program: the search tree is 44 lines and its laws took 73 to state. The proofs are long, and they are the machine’s to read. The saving is where a program is long for the sake of how it runs. There the laws about what it computes stay short, and one suite of map axioms serves a list of pairs and a red-black tree alike. That suite says nothing about speed. A law about how the program runs can be as loose or as exact as one likes: a bound on depth would fit any balanced tree, and the rule about colors fits one. The closer a law follows the algorithm, the less it saves. Laws, like tests, need not shorten the meaning. They give another way into it, in pieces that can each be read alone and that a machine holds the program to.

What is not established

limits

List claims the essay marks as limited by its own evidence.

Answer
  • That no safe program can defeat the local annotation: twelve attempts are not a proof.
  • The Lean column of the first table, which rests partly on documentation and not on programs that were run.
  • How well agents write OxCaml: there is no measurement, only Jane Street’s report.
  • The punctuation count: the files are few and short.
  • That OxCaml has no macros: stated as far as the authors found.
  • The red-black theorem: it does not say the tree keeps exactly the other keys, and nothing proves that the Lean transcription matches the book’s OCaml.
  • The experiment on types first: the task was too easy to show a difference in correctness.
  • The author’s remark that agents were good at OCaml early: an observation and no more, since nobody has measured the quality of a corpus.

Terms

Introduced in this essay:

From other essays: