---
title: Building a model
summary: A model is built inside a scope a writer opens, by ordinary functions of handles, and published as an immutable snapshot that may be read from any thread or forked into a branch.
order: 3
depends_on: [concepts/operations]
---

# Building a model

A model is built forward, the way it is thought of: a quantity, then what is computed from it, then the next quantity.
Building happens inside a **scope** that a **writer** opens, by ordinary functions of [handles](/concepts/spaces.md#typed-handles) that name no writer, device or precision, and the writer publishes what was built as an immutable **snapshot**.
This page describes the writer, the scope and its functions, what happens on a mistake, and snapshots and branches.

## The writer and its scope

From `crates/skoro-core/src/writer.rs`, lines 33–47:

```rust
/// Runs `body` with a building scope open on this thread, and publishes what it built. A
/// scope that recorded a failure publishes nothing and returns the failure; one that panics
/// drops its draft as it unwinds.
pub fn build<R>(&mut self, body: impl FnOnce() -> R) -> Result<R, Failure> {
    let draft = Draft::new(self.latest.0.as_ref().clone());
    let (result, frame) = scope::open(Frame::Scope(draft), body);
    let Frame::Scope(draft) = frame else {
        unreachable!("build gets back the scope it opened")
    };
    if let Some(failure) = draft.failure {
        return Err(failure);
    }
    self.publish(draft.model);
    Ok(result)
}
```

`build` opens a building scope on the current thread and runs the closure in it.
Every function that builds (making a quantity, applying an [operation](/concepts/operations.md), adding a term) adds its node to the innermost open scope, which is why a function of handles needs no model passed to it: the same function builds into whichever model's scope it is called in.
When the closure returns, the writer publishes the new model.

The scope's own functions make the roots of a model, its quantities and constants, and place quantities at addresses:

From `crates/skoro-core/src/scope.rs`, lines 329–347:

```rust
/// A quantity of `marker`'s space at `address`, under the open namespaces (`AddressTaken`).
#[track_caller]
pub fn quantity<T: Declares>(address: impl Into<Address>, marker: T) -> Q<T> {
    let (address, space) = (address.into(), marker.space());
    let location = Location::caller();
    Q::from_id(build(location, |draft, prefix| {
        draft.quantity(prefix.join(&address), space)
    }))
}

/// A quantity of `space` at `address`, under the open namespaces (`AddressTaken`).
#[track_caller]
pub fn quantity_in(address: impl Into<Address>, space: Space) -> QDyn {
    let address = address.into();
    let location = Location::caller();
    QDyn::from_id(build(location, |draft, prefix| {
        draft.quantity(prefix.join(&address), space)
    }))
}
```

From `crates/skoro-core/src/scope.rs`, lines 375–386:

```rust
/// A constant of `marker`'s space (`ValueShape` when the value does not fit it).
#[track_caller]
pub fn constant<T: Declares>(marker: T, value: impl IntoHostValue<T>) -> Q<T> {
    let (space, value) = (marker.space(), value.into_host_value());
    let location = Location::caller();
    Q::from_id(build(location, |draft, _| draft.constant(space, value)))
}

/// Runs `body` with `prefix` prefixed to the addresses of the quantities it makes and looks up.
pub fn namespace<R>(prefix: impl Into<Address>, body: impl FnOnce() -> R) -> R {
    open(Frame::Namespace(prefix.into()), body).0
}
```

A **quantity** is an uncertain value of the model, made at an **address**: a path of names and indices such as `tick/1/x`, where a segment of digits is an index.
`namespace` prefixes the addresses of everything made inside it, so the model of one tick can be written once, as a function, and called under `tick/0`, `tick/1` and so on.
`lookup` finds a quantity by its address under the open namespaces.
A **constant** is a value fixed when the model is built; a constant and anything computed from constants alone is folded into a value as soon as it is added.

## The compilation graph

What a scope builds is the model's **compilation graph**.
Its nodes are the model's values: the quantities and constants, which are its roots, and the outputs of operations, among them the log-densities of [terms](/concepts/terms.md).
Its edges run from each input of an operation to its output.
A scope only adds: it builds nodes on top of the previous snapshot's, and nothing already published changes.
Nodes leave the graph only through a [retirement](/concepts/terms.md#retirement), which removes the quantities it retires, what is computed from them, and the values it leaves needed by nothing.

Here is a scope building the compilation graph of a model of a vehicle and a landmark, to which the page on [terms](/concepts/terms.md#an-example) returns, one line at a time.
Step through it, or play it:

From `crates/skoro-core/tests/queries.rs`, lines 32–57:

```rust
let mut writer = Writer::new();
let (x0, x1, m, z0, z1, zeta, sigma, t) = writer
    .build(|| {
        let half = constant(Real, 0.5);
        let x0 = quantity("tick/0/x", Vector::<2>);
        let t1 = score(x0, -(x0 * x0).sum() * half);
        let m = quantity("landmark", Vector::<2>);
        let t2 = score(m, -(m * m).sum() * half);
        let zeta = quantity("tick/1/imu", Vector::<2>);
        let sigma = quantity("sigma", Positive::<1>);
        let x1 = quantity("tick/1/x", Vector::<2>);
        let step = x1 - x0 - zeta;
        let t3 = score(x1, -(step * step).sum());
        let z0 = quantity("tick/0/z", Vector::<2>);
        let r0 = z0 - (m - x0);
        let t4 = score(z0, -(r0 * r0).sum());
        let z1 = quantity("tick/1/z", Vector::<2>);
        let r1 = z1 - (m - x1);
        let t5 = score(z1, -(r1 * r1).sum());
        let r = x1 - x0;
        let inverse = (sigma * sigma).recip().as_real().sum();
        let t6 = factor(-(r * r).sum() * half * inverse - 2.0 * sigma.log().sum());
        let t7 = factor(-sigma.log().sum());
        (x0, x1, m, z0, z1, zeta, sigma, [t1, t2, t3, t4, t5, t6, t7])
    })
    .unwrap();
```

**Walkthrough: A scope builds the compilation graph.** The running example, line by line. Each blue or purple node stands for the operations on its line, drawn as one; the compilation graph has a node for each.

1. A writer of an empty model: its latest snapshot has no nodes. (at `let mut writer = Writer::new();`)
2. `build` opens a scope on this thread: a draft of the model, copied from the writer's latest snapshot, pushed on the thread's stack of frames. Every building function below adds its node to the innermost draft, which is why none of them is passed a model. (at `.build(|| {`; appears: `scope: a draft`)
3. A constant: a value fixed when the model is built, and a root of the compilation graph. (at `let half`; appears: `½` (Constant))
4. A quantity, at the address `tick/0/x`: an uncertain value, and another root. (at `let x0 =`; appears: $x_0$ (Quantity))
5. Its log-density $\ell_1 = -\tfrac12 \, x_0 \cdot x_0$ is four operations, each a node with an edge from each input. `score` then records $\ell_1$ as the term `t1`, which scores $x_0$: a term names a node of the graph, and adds none. (at `let t1`; appears: $\ell_1$ (A term's log-density))
6. A second quantity, the landmark $m$, and the term that scores it. The constant `half` is one node, read by both. (at `let m =`, `let t2`; appears: $m$ (Quantity), $\ell_2$ (A term's log-density))
7. Three more quantities: an inertial reading $\zeta$, a scale $\sigma$ and the next position $x_1$. The order quantities are made in is the model's ancestral order. (at `let zeta`, `let sigma`, `let x1 =`; appears: $\zeta$ (Quantity), $\sigma$ (Quantity), $x_1$ (Quantity))
8. `step`, computed from three quantities, gets an edge from each, and its square scores $x_1$ as `t3`. (at `let step`, `let t3`; appears: `step` (Mapped value), $\ell_3$ (A term's log-density))
9. Each measurement is a quantity scored by a term of its residual. (at `let z0 =`, `let r0`, `let t4`, `let z1 =`, `let r1`, `let t5`; appears: $z_0$ (Quantity), $r_0$ (Mapped value), $\ell_4$ (A term's log-density), $z_1$ (Quantity), $r_1$ (Mapped value), $\ell_5$ (A term's log-density))
10. Two likelihood factors, `t6` and `t7`: terms that score nothing. A function of handles never asks which model it builds into, so the same code could as well have built these into a branch. (at `let r =`, `let inverse`, `let t6`, `let t7`; appears: $r$ (Mapped value), $\sigma^{-2}$ (Mapped value), $\ell_6$ (A term's log-density), $\ell_7$ (A term's log-density))
11. The closure returns, and no building function recorded a failure, so the writer publishes the draft as its new snapshot: an immutable model, cheap to clone, from which queries are compiled. (at `[t1, t2, t3`, `.unwrap();`; appears: `snapshot`; goes: `scope: a draft`)

A node all of whose inputs are fixed in the model, constants or nodes folded before it, is **folded** as it is added: its operation is lowered for the host and run once, at double precision, and the node keeps the value.
A call of a [composite](/concepts/operations.md#composites) is folded the same way, by a program compiled from the composite's body:

From `crates/skoro-core/tests/composite.rs`, lines 325–342:

```rust
fn a_call_of_constants_folds_when_added() {
    let part = Composite::define(
        "test.part",
        Vec::new(),
        &[Space::Vector(2), Space::Real],
        |q| in_place(q[0], q[1]),
    )
    .unwrap();
    let mut writer = Writer::new();
    let f = writer
        .build(|| {
            let x = constant(Vector::<2>, [0.4, -0.9]).untyped();
            let s = constant(Real, 1.3).untyped();
            part.call(&[x, s])
        })
        .unwrap();
    let snapshot = writer.snapshot();
    let folded = snapshot.node(f.id()).unwrap().value().unwrap().clone();
```

**Walkthrough: A call of constants folds as it is added.** The composite's body is $\Sigma(e^{q_0} \odot \sin q_0) \, q_1$, from `in_place`.

1. `define` runs the body in a definition scope of its own, with a handle standing for each input. (at `let part = Composite::define(`; appears: composite `test.part`, $q_0$ (A composite's input), $q_1$ (A composite's input))
2. The operations the body applies build into the composite, not into any model: its nodes are kept, once, as the composite's body. (at `|q| in_place(q[0], q[1])`; appears: `exp` (Mapped value), `sin` (Mapped value), `×` (Mapped value), `Σ` (Mapped value), `×` (Mapped value))
3. A scope, and two constants in it. (at `.build(|| {`, `let x = constant`, `let s = constant`; appears: `scope`, $x$ (Constant), $s$ (Constant))
4. A call of the composite is one node of the model, with an edge from each argument. (at `part.call(&[x, s])`; appears: $f$ (A call of a composite))
5. Every input of the call is fixed in the model, so the scope folds the node as it adds it: it lowers the call's operation for the host, at double precision, and a composite lowers to itself. (at `part.call(&[x, s])`)
6. The lowering compiles the composite into a program of its own, binding its inputs to the constants. A lowering keeps each composite it compiles, by name and parameters, so one it meets twice is compiled once. (at `part.call(&[x, s])`)
7. The program runs forward once, on the constants' values. (at `part.call(&[x, s])`; flows along: $x$ → $q_0$, $s$ → $q_1$, $q_0$ → `exp`, $q_0$ → `sin`, `exp` → `×`, `sin` → `×`, `×` → `Σ`, `Σ` → `×`, $q_1$ → `×`)
8. The node keeps the value it computed, and is fixed in the model from now on: a node built on it alone folds in turn, and a query reads it as a constant. (at `part.call(&[x, s])`; becomes: $f$ → Folded value; goes: $x$ → $q_0$, $s$ → $q_1$; set aside: composite `test.part`, $q_0$, $q_1$, `exp`, `sin`, `×`, `Σ`, `×`)
9. The scope publishes, and the snapshot holds the folded value: reading it needs no query and no program. (at `let snapshot = writer.snapshot();`, `let folded = snapshot.node(f.id())`; appears: `snapshot`; goes: `scope`)

## Mistakes, and where they were made

Building never panics on a mistake in the model.
Each building function checks its inputs (that they exist in this model, that their spaces suit the operation, that an address is not taken) and, on a fault, records it and returns a **failed** handle.
Everything built on a failed handle fails in turn, and the scope publishes nothing.
`build` then returns the first fault, with the line of user code that caused it:

From `crates/skoro-core/tests/building.rs`, lines 52–75:

```rust
#[test]
fn scope_reports_the_first_failure_and_where() {
    let mut writer = Writer::new();
    let mut line = 0;
    let failure = writer
        .build(|| {
            let x = quantity("x", Real);
            let v = quantity("v", Vector::<2>);
            line = line!() + 1;
            let first = add(x, v);
            add(first, x);
            quantity("x", Real); // a second failure, not reported
        })
        .unwrap_err();
    assert!(matches!(
        failure.error,
        Error::SpaceMismatch {
            operation: "skoro.add",
            ..
        }
    ));
    assert_eq!(failure.location.line(), line);
    assert_eq!(failure.location.file(), file!());
}
```

So the failure points at `add(x, v)`, where a real number was added to a vector, rather than at the second mistake or at whatever later tried to use the model.

## Snapshots, readers and branches

A snapshot is an immutable model, cheap to clone, which the queries of [the next pages](/concepts/queries.md) are compiled from.
A writer hands out its latest snapshot, and a `Reader` that loads the newest one from any thread, so estimators can run on snapshots while the writer goes on building.

A snapshot can also be **forked** into a writer of its own: a branch, which shares everything with the snapshot it came from and changes independently of it.
This is how a model is held under several hypotheses at once.

From `crates/skoro-core/tests/branches.rs`, lines 41–55:

```rust
#[test]
fn branches_do_not_see_each_other() {
    let mut main = Writer::new();
    main.build(|| quantity("x", Real)).unwrap();
    let mut branch = main.snapshot().fork();
    let (main_reader, branch_reader) = (main.reader(), branch.reader());
    let a = main.build(|| quantity("a", Real)).unwrap();
    let b = branch.build(|| quantity("b", Real)).unwrap();
    let (main, branch) = (main_reader.latest(), branch_reader.latest());
    assert!(main.node(a.id()).is_some() && main.node(b.id()).is_none());
    assert!(branch.node(b.id()).is_some() && branch.node(a.id()).is_none());
    // Each branch may use an address the other took.
    let mut other = branch.fork();
    assert!(other.build(|| quantity("a", Real)).is_ok());
}
```

**Walkthrough: Branches share what they had.** Each snapshot holds the nodes of its model; a later one is built on an earlier one, and shares its nodes rather than copying them.

1. A writer of an empty model. (at `let mut main = Writer::new();`; appears: writer `main`)
2. Its first scope publishes $s_1$, which holds the quantity $x$. (at `main.build(|| quantity("x", Real))`; appears: $s_1$ (Snapshot), $x$ (Quantity))
3. `fork` makes a second writer whose latest snapshot is $s_1$ itself: a branch, which shares everything and has copied nothing. (at `let mut branch = main.snapshot().fork();`; appears: writer `branch`)
4. A reader loads its writer's newest snapshot, from any thread. Both are at $s_1$. (at `let (main_reader, branch_reader)`)
5. Building on `main` publishes $s_2$, built on $s_1$: it holds $x$'s node, the same allocation as $s_1$'s, and a new quantity $a$. (at `let a = main.build`; appears: $s_2$ (Snapshot), $a$ (Quantity))
6. Building on the branch publishes $s_3$, also built on $s_1$: $x$ again, and $b$. (at `let b = branch.build`; appears: $s_3$ (Snapshot), $b$ (Quantity))
7. Each reader now loads its own writer's newest snapshot. (at `let (main, branch) = (main_reader.latest()`)
8. Neither sees the other's quantity. The handle of $x$, made before the fork, names the same node on both. (at `assert!(main.node(a.id())`, `assert!(branch.node(b.id())`)
9. A fork of $s_3$ is a third writer, and its scope may take the address `a`, which only `main` had taken: addresses, like nodes, belong to a branch. (at `let mut other = branch.fork();`, `quantity("a", Real)).is_ok()`; appears: writer `other`, $s_4$ (Snapshot), $a'$ (Quantity))

A handle stays valid on every branch that shares its node, so the quantities made before the fork are named the same way on each.

> [!DECISION] One writer per branch, many snapshots
> A model changes only through its writer, by building, forking or retiring, and is read only through snapshots.
> See [position 3 of the charter](/archive/charter/writeup.md#3-one-writer-per-branch-many-snapshots).
