knotflow Lessons PDF ↓ Deutsch Handbook Modeller ↗ Source

Lesson 4.2 · IV Tools

Recomputing only what changed

What it's about: With the cache, exactly the same comes out as without, only faster. Lesson 1.1 said that a sequence of let lines is a data-flow graph as in a node editor, and that it follows for free that after a change only the dependent part needs to be recomputed. This lesson shows how knotflow keeps that promise. If you drag the plate thickness of the bone, it takes 0.1 seconds instead of ten, because the growth of the structure does not depend on the thickness at all. The way there leads through fingerprints: a number that uniquely identifies a statement together with everything it depends on.

What you should know first: Lesson 1.1 (the model as a data-flow graph) and the modeller in the browser (Lesson 4.1). For section 3, Lesson 2.2 helps: when a function looks up its names.

Change without cache with cache recomputed
Bone: plate thickness 9.7 s 0.09 s 1 of 19 statements
Bone: thickness back again 9.7 s 0.004 s nothing
Bone: remodelling speed 9.7 s 8.2 s 3 of 19, the growth itself
Voronoi nets: detail 0.02 → 0.05 10.4 s 4.9 s simplifying yes, isosurface no
Voronoi nets: detail back 10.4 s 0.14 s nothing
Tree roof: roof on/off 9.1 s 0.25 s 1 of 8

(Measured with the WebAssembly module. The status line in the browser then shows something like "1 of 19 new".)

1. Two ways to run a cache

Invalidating is the way of node editors: every component holds its result. When an input changes, all components downstream are marked "stale" and recomputed next time. For this the program has to know the graph and keep it up to date all the time.

Content-addressed is the way of build systems like Nix or Bazel, and of Git: a result is stored under a fingerprint of whatever determines it. Before computing, you form the fingerprint and look up whether there is already a result for it. Nothing is marked or maintained. And there are advantages that invalidating does not have:

knotflow does it content-addressed (crates/lang/src/cache.rs).

2. The fingerprint of a statement

What determines the value of let r = p + q? The text of the statement, and the values of p and q. Those in turn are determined by their texts and the names that appear in them, and so on, until you reach parameters whose values are known. So:

fingerprint(statement) = hash( text, texts of all reached lets and fns, values of all reached parameters, texts of imported libraries, contents of files read )

"Reached" means: the statement uses a name, its definition uses names again, and so on (Fingerprints::of, a depth-first search). A hash is a function that maps any number of bytes to a number, here 64 bits (DefaultHasher, SipHash). Two different inputs almost certainly give different numbers. More on that in section 6.

For this to be right, that is, for the same fingerprint to always mean the same value, one thing is required: the language has no side effects. No expression reads a clock or a random generator with internal state. That is why it mattered in Lesson 2.2 that rand(seed, i) is a pure function of seed and counter. If the language had a random() that returned something different on every call, every cache would be wrong. Whatever comes from outside the model goes into the fingerprint explicitly: the text of every imported library (Lesson 2.4) and the contents of every file that read reads (Lesson 2.5). That is why the path in read has to be written as a literal: only then is it known before computing which files the model needs.

Better too much than too little

Which names a statement uses, the cache reads off the syntax tree (graph::free_names): the names it does not bind itself. A function's parameters and names from where, patterns and comprehensions do not count, nor do field names in {lift: 10} or after the dot. At first, every identifier in the text counted. That is simpler, and one name too many costs only an unnecessary computation. In a large model, though, it chained up: a field was named like a function, whose parameter was named like a function that reads the crank angle. With that, nearly the whole model hung on the slider: 11.5 s instead of 0.8 s per move.

Counting too much is still the safe direction. Where the analysis is unsure, it counts the name, as in x.f(y): if x has no field f, the model's function f is meant. The other way round would be dangerous: a missed name would mean taking an old result even though something changed. It is the same when building software: a build system may rebuild too often, but never too rarely. A test moves every slider of every example on its own and compares with a run without the cache, byte for byte.

3. A trap: functions that look things up later

It would seem natural to follow only functions (fn) down to their text, and for a let to take its fingerprint as it was at computation time. That sounds right, but it is not:

let f = x => x + c      // c does not exist here yet
param c = 1
let y = f(1)

Functions only look up names when they are called (Lesson 2.2). f is a function that looks up c only when it is called in let y. But its fingerprint is formed in the first line, when c did not exist yet, and so it never changes. So f would come from the cache, as an old object from the old run, which looks things up in the old environment, where c = 1. With c = 5, y would then give 2 instead of 6.

Two rules prevent this:

  1. Values that contain functions do not go into the cache. A function belongs to the run in which it was made. Making it again costs next to nothing anyway.
  2. The fingerprint follows lets too, down to their text. y reaches the name c via f.

The test every_way_a_value_can_depend_on_a_parameter checks such paths against a run without cache: a function that reads a let defined later, a function in a record, a let from a let. That is the right way to test a cache, because with the cache, exactly the same must come out as without.

4. Expensive functions remember their results

Statements are sometimes too coarse. In the Voronoi nets, a single statement contains

fn net(k) = isosurface(blend(…), voxel: voxel) |> finish
export net(0) color "terracotta"

If detail changes, finish changes, so export net(0) has to run again, isosurface and all, even though the isosurface does not depend on detail. That is why there is a second level: some expensive built-in functions (isosurface, simplify, analyze_plane, voronoi_sphere, frame_sizing, arc_crossings and the surface tools intersect, offset_surface and shell from Lessons 3.6 and 3.8) remember their results under a hash of their name and their arguments. The isosurface gets the same shape as last time and immediately returns its old mesh. Only simplify recomputes (4.9 instead of 10.4 s).

Why not all functions? Hashing has a cost too: to know whether a mesh of four million triangles is the same as last time, you have to read all of it. For isosurface (seconds) that pays off, for blur (milliseconds, but a thousand times over during bone growth) it does not: the cache would be stuffed with intermediate results that nobody needs again. The booleans, fillet_edges and solve remember nothing themselves either: their results survive through the cache of statements, but a call inside a statement that changed computes again. To keep an expensive boolean, give it a let of its own.

5. Reusing triangles: identity instead of content

After the language comes the tessellation (Lesson 1.3). For the Romanesco it costs more than everything else: 3081 NURBS surfaces become 4.7 million triangles. Hashing the surfaces would be expensive, but it is not necessary. When a statement comes from the cache, it returns the same object as last time, not just an equal one. So the triangles are kept under the address of the surface (scene::Tessellations, Romanesco: 1.6 → 0.6 s).

One subtlety: once freed, a memory address can be given to a new object. Then a different surface would look like the old one. The cache therefore holds a reference to every surface it uses as a key. As long as the entry exists, the surface lives, and its address stays taken.

6. Limits and small print

Try it yourself

In the browser (cd web && npm run dev):

  1. Bone: drag thick, then steps. Watch the status line ("1 of 19 new"). Which statements depend on what? Compare with kf graph examples/bone.kf.
  2. Voronoi nets: set detail to 0.05 and back. Why is setting it back so much faster than setting it?
  3. In the bone's export, replace thick with a number and change it in the text instead of with the slider. What does the cache recompute now, and why the same as with the slider?
  4. Something to think about: why would a fingerprint from the syntax tree instead of the text be risky? (Hint: what else is in the syntax tree besides the structure? Lesson 2.1, error messages.)