# Memory model

URL: /docs/tour/memory
Markdown: /docs/tour/memory.md

> Value semantics, var rebinding, compiler-inserted reference counting with Perceus reuse, cycles through Graph, scope-bound resources, and backends in Sakura Lang.

In Sakura Lang every value behaves like its own copy. Changing one never changes another. You never manage memory yourself: there are no pointers, lifetimes, borrow annotations or `Rc`/`Arc` in user code.

```sakura
type User = { id: Int, name: String, handle: String }

fn rename(u: User, name: String) -> User {
  var v = u
  v.name = name          // sugar for v = User { ..v, name: name }
  v
}

test "updates never alias" {
  let a = User { id: 1, name: "Ada", handle: "ada" }
  let b = rename(a, "Ada L.")
  expect_eq(a.name, "Ada")
  expect_eq(b.name, "Ada L.")
}
```

- `rename` changes `v.name`, but the caller's `a` is untouched.
- `v.name = name` is shorthand for building a new `User` with one field changed and storing it back in `v`.
- The compiler may share memory behind the scenes, but your program can never tell.

The price of this model is a few rules: no shared mutable values, no cycles between values, and explicit scopes for files and connections. The rest of this page covers each one.

## Value semantics [#value-semantics]

Assigning, passing, capturing and returning a value never creates an alias, a second name for the same mutable thing. Records, variants, lists, maps and strings cannot be changed in place from the program's point of view.

- `let` binds a name that cannot be reassigned.
- `var` binds a name that can be **reassigned**. Reassigning changes the binding and nothing else.

## Growing a collection [#growing-a-collection]

Collections grow the same way: `xs = List.push(xs, 1)`. `List.push` returns a new list. If you call it and drop the result, that is error `V2040`, which catches a forgotten reassignment:

```sakura
fn evens(n: Int) -> List<Int> {
  var xs: List<Int> = []
  for i in 0..n {
    if i % 2 == 0 { xs = List.push(xs, i) }   // List.push(xs, i) alone would be V2040
  }
  xs
}
```

## Closures capture values [#closures-capture-values]

A closure copies the `var` bindings it uses when it is created:

```sakura
test "closures see the value at creation" {
  var greeting = "hello"
  let say = fn() { greeting }
  greeting = "bye"
  expect_eq(say(), "hello")
}
```

- A closure cannot assign to an outer `var` (`V2041`). Accumulate with a `var` in the same function body, or with `List.fold`.
- A `try` body follows the same rule, because it may stop at any failing call. Assign after the `try` instead: `let v = try { … } catch { … }`, then `total = total + v`.

## Shared state lives in handlers [#shared-state-lives-in-handlers]

The only places with changing state are handler `var` state and `Graph`, and both are confined. Shared mutable state, such as a counter or a cache, lives in a [handler](/docs/tour/handlers):

```sakura
effect Counter { fn next() -> Int }

fn counter() -> Handler<Counter> {
  handler Counter {
    var n = 0
    fn next() { n = n + 1; n }
  }
}
```

The state is private to the handler, starts fresh each time you install it with `with`, and is released when the `with` exits.

## Cycles: use Graph [#cycles-use-graph]

A value can only refer to values that existed before it, so values cannot form cycles. For cyclic data, such as a social graph, use `std/graph`. A `Graph<N>` owns a table of nodes, and edges are `NodeId` keys that the graph checks:

```sakura
import std/graph.{Graph, NodeId}

type Person = { name: String }

fn befriend(g: Graph<Person>, a: Person, b: Person) -> (Graph<Person>, NodeId, NodeId) {
  let (g1, ia) = Graph.insert(g, a)
  let (g2, ib) = Graph.insert(g1, b)
  (Graph.connect(Graph.connect(g2, ia, ib), ib, ia), ia, ib)
}
```

`ia` and `ib` point at each other through the graph, but no value points to itself. `Graph.get(g, id)` returns `Option<N>`, so a stale id gives `None`, not a dangling pointer. There are no weak pointers.

## Resources [#resources]

A **resource** is something the host owns that must be closed: a file, a socket, a database connection, an HTTP body, a running task. You never open one and forget it. Instead, a function lends it to a callback and closes it when the callback returns:

This excerpt is from the standard `Fs` declaration; the omitted types come from std. It is not a standalone program.

```sakura fragment
effect Fs {
  fn with_file<T, e>(path: Path, mode: Mode, body: fn(File) -> T ! e) -> T ! {Fail<FsError> | e}
}
```

- The callback's result may not contain the resource (`V6003`). Return the data you read instead.
- `Sql.transaction(fn() { … })` follows the same pattern.
- Resources are released on normal exit, `fail`, defect and cancellation, in reverse order of opening. A failed release is reported as a defect, never ignored.
- Resources cannot be compared, shown or serialized, and are used at most once as a whole.

## Streams are values [#streams-are-values]

A `std/stream` `Source` is a value you pull items from. `pull` returns `Done`, or `Next(item, rest)` with the source that continues after the item.

```sakura
import std/stream.{Source}

test "a pure source reads the same items every time" {
  let src: Source<Int, {}> = Source.from_list([1, 2, 3])
  expect_eq(src.fold(0, fn(a, x) { a + x }), 6)
  expect_eq(src.fold(0, fn(a, x) { a + x }), 6)
}
```

- A **pure source** (`Source.from_list`, `Blob.source`, and `map`, `filter`, `lines` or `chunks` over them) holds only values. Reading it twice reads the same items twice.
- A **view** reads a resource: `Http.body_source(body, chunk)` and `Fs.file_source(file, chunk)`. Two reads advance the same body or file. A view is scoped like its resource, so returning one from the `Http.stream` or `Fs.with_file` callback is `V6003`.

## No data races [#no-data-races]

There is no shared mutable memory, so tasks cannot race on data. Tasks communicate through their results (`Task.join`, `Task.all`, `Task.race`), through handler state (whose operations run one at a time), and through channels. Evaluation is strict and left to right, and `Map`/`Set` iterate in insertion order on every backend. See [Concurrency](/docs/tour/concurrency).

## Backends [#backends]

A **backend** is what the compiler turns your program into. All backends give the same results; they differ in how memory is freed.

| Backend | Status | Memory management |
| --- | --- | --- |
| JavaScript | the default; in every release | the JavaScript engine's garbage collector |
| WebAssembly | complete; in every release | reference counting inserted by the compiler |
| Native | experimental | reference counting inserted by the compiler |

```bash
sakura run                  # JavaScript, the default
sakura run --target wasm    # WebAssembly, run through Node
sakura build --target wasm
sakura test --target wasm
```

- WASM builds write `main.wasm` and the Node host files to `target/sakura/wasm`. `run` and `test` execute through Node 26, not a browser or WASI host.
- `Int` is a signed 64-bit integer on WASM. On JavaScript, an `Int` beyond ±(2^53−1) is defect `D003`; `String.parse_int` returns `None` for such a value instead.
- `--target native` builds an executable that runs directly. It is **experimental**: see [Native builds](/docs/native).

Every backend starts from the same internal form, so they agree:

> **Diagram:** The compiler pipeline on main (design §13). One Core feeds every backend; WASM and native share the LIR.
>
> 1. `source`: .sak files, parsed with error recovery.
> 2. `CST`: lossless; the formatter works here.
> 3. `HIR`: names resolved.
> 4. `Typed HIR`: types, effect rows, holes, obligations.
> 5. `Core`: explicit Perform, Handle, Fail, Check. Then `JavaScript` or `LIR`.
> 6. `JavaScript`: the default target; runs on Node. This path ends here.
> 7. `LIR`: from a Core snapshot; reference counts made explicit. Then `WebAssembly` or `native`.
> 8. `WebAssembly`: complete; runs on Node. This path ends here.
> 9. `native`: Cranelift; experimental, behind a feature.
>
> Select a backend with --target js (the default) or --target wasm. Native code is experimental: only a compiler built with the native Cargo feature accepts --target native, and no release includes it.

**Stability.** `--target js` and `--target wasm` are proposed as stable from v1.0.0-beta.1, and so is the WASM runtime ABI. Generated JavaScript, LIR and WASM bytes are internal and may change in any release. `--target native` is experimental. See [Stability](/docs/stability).

## Reference counting and reuse [#reference-counting-and-reuse]

Because values never form cycles, **reference counting** (each value counts who uses it and is freed at zero) frees everything without a separate cycle collector. The WASM backend uses it today, conservatively. The JavaScript backend uses the engine's garbage collector instead.

The native design adds in-place reuse, a technique called Perceus. It is experimental and planned after 1.0:

- **Same-shape reuse.** When nothing else holds a value, an update or a `match` that rebuilds a value of the same shape reuses its memory.
- **Copy-on-write buffers** for `List`, `Map` and `String`. A `var xs` whose last use is `List.push(xs, v)` appends in place, which gives fast appends without exposing anything in the language.
- **Counts per task.** Current native work is single-threaded; counts shared across threads are deferred.

```sakura
type Tree = Leaf | Node(Tree, Int, Tree)

fn increment(t: Tree) -> Tree {
  match t {
    Leaf => Leaf
    Node(l, v, r) => Node(increment(l), v + 1, increment(r))
  }
}
```

If the caller passes its last reference to `t`, native code can rebuild each `Node` in the memory it just took apart. If the tree is still used elsewhere, the update copies and the original stays intact. The result is the same either way.

When the compiler can prove an update copies because the old version is still used (read again later, captured by a live closure or handler, or stored in a live value), `sakura check` emits warning `W8001 copy_on_write`, pointing at that use. An update whose value only might be shared, such as a parameter, is not warned about.

## Costs and limits [#costs-and-limits]

- Reference counting costs something on every use. Reuse is what makes it competitive; how well it works is not yet measured.
- Sharing a large value and then updating it copies. `W8001` reports the copies the compiler can prove.
- Cyclic data needs `Graph` and `NodeId`s instead of direct references.
- In the native design, handler state uses a lock per handler. Whether that holds up under parallelism is an open question.
- There are no regions (request-scoped arenas). The `region` keyword is reserved.

## What the compiler checks [#what-the-compiler-checks]

- There is no syntax for mutating shared values or for pointer identity, so aliasing bugs cannot be written.
- A dropped non-`Unit` result is an error (`V2040`), which catches `List.push(xs, v)` without reassignment.
- Neither a lambda nor a `try` body can assign an outer `var` (`V2041`).
- A resource cannot escape its scope (`V6003`).
- Reference counting is inserted automatically and is never visible in source.

## Reference [#reference]

### Backend flags [#backend-flags]

- `--out-dir PATH` selects another output directory on `build`, `run` and `test`. `run` accepts one source path and passes arguments after `--` to the program; `build` and `test` accept several paths. With no path, they use `src/` when present, otherwise the current directory.
- `build --emit lir` writes `main.lir` to `target/sakura/lir`. LIR output supports `--layout tagged`; `--emit lir --layout niche` is rejected as not implemented. WASM always uses the tagged layout.
- There is no `build --release` flag. `build --manifest` writes the trust manifest for JS and WASM output, with `target` naming which; it is rejected with `--emit lir`. Like JS, a WASM build drops the checks `sakura verify --target wasm` proved; see [verification](/docs/agents/verify).
- See the [CLI reference](/docs/cli) for every flag.

### WebAssembly [#webassembly]

- HTTP sends and streams, `Sql.sqlite`, `Llm.stream`, `Serve.host()` and `Log.json()` work on WASM, including requests with `Secret` HTTP headers (`Http.bearer`, and `Llm.anthropic` over `Http.host()`). The header's value reaches the host's `fetch` and nothing else, and cassettes record it redacted, as on JS.
- `test --record` requires `--target js`; both backends read the cassette it writes. Ordinary tests and `test --contracts` run on both.
- User `@external(js, …)` bindings are rejected for WASM with `V8004`.
- To call a library's functions from Node, see [Embedding a library in Node](/docs/tour/embedding).
- CI compares JS and WASM outputs, exits, defects and traces on Ubuntu and macOS, with explicit expectations for the integer-range difference. WASM defect codes, messages and source spans match JS. Spans come from `sakura.debug`; `--strip` removes them. See [changes on main](/docs/changes#webassembly-backend-complete) for host fault handling.

### Native [#native]

The macOS arm64, Linux x64 and Linux arm64 release binaries (from v1.0.0-beta.4), the Intel macOS one (from v1.0.0-beta.5), and a compiler built from source with `cargo build --release -p sakura_cli --features native`, accept `--target native` on `build`, `run` and `test`. The native backend agrees with JavaScript on the semantics test corpus and runs every standard service, `WebSocket` from `v1.0.0-beta.6`. See [Native builds](/docs/native).

## Next [#next]

[Concurrency](/docs/tour/concurrency): running work at the same time with tasks, cancellation, timeouts and retries.

Details for contributors: [design §8.2, §10.2, §16](https://github.com/icantcodefyi/sakuralang/blob/main/docs/design.md).
