# How Pekit Builds

---

# Targets and Steps

_Pekit / How Pekit Builds_

> How pekit evaluates a target's GCSL code, turns calls of hermetic functions into steps, runs steps in parallel and shares them between targets, and handles a target that waits for a step's result.

A build has two kinds of work. A target's own code is GCSL that decides
what to build. A step is one piece of the actual building, such as running
a compiler, and pekit runs it in a sandbox and keeps its result. Knowing
which code is which explains what pekit reuses, what it runs in parallel,
and what a build can see.

## Definitions and targets

A build file declares definitions, each made with a definition type:

| Definition type | Declares | Run by |
|---|---|---|
| `build` | Something to build: a file, a directory, or a record of them. | `pekit build` |
| `test` | A check that passes or fails. | `pekit test` |
| `package` | A package's name, version, and files. | `pekit package` |
| `script` | A task you run by hand, which can change things outside the build. | `pekit run` |

A target is a definition you name on the command line. `pekit build hello`
builds the `build` definition called `hello`. Its body is GCSL code, and
whatever the body gives is what the target built.

## Steps

A step is a call of a function marked `#[hermetic]`:

```gcsl
#[hermetic]
fn compile(source: File) -> File {
    let compiled = exec(["cc", "-c", "-o", "out.o", source.path])
    = working_dir().file("out.o")
}
```

When a target's code calls `compile`, pekit doesn't run the call there.
It records the call as a step, with its arguments, and the target's code
carries on. pekit runs the step separately, in a sandbox holding only the
step's arguments, and keeps what it gives. Libraries such as the gcc
library are made of functions like this one, so a target that calls
`gcc.compile` and `gcc.link` makes two steps.

A step is identified by everything that can change what it gives: its
function's code, its arguments, the contents of the files it's given, and
the platform it runs on. A step with the same identity as one pekit has
already run is found in the store, and doesn't run again. [Reuse and the
Store](/pekit/concepts/reuse-and-the-store.md) describes how.

A call of a function without `#[hermetic]` is ordinary GCSL. It runs as
part of whatever code called it: in the target's code, or inside the step
that called it.

## A build is a graph

Because a target's code only records each step, pekit learns every step it
needs before running any of them. A step that takes another step's result
as an argument runs after that step. Steps that don't depend on each other
run at the same time, up to the number of programs `--jobs` allows, which
is by default the number of processors. Every build on the machine also
shares one budget of programs and memory. See [Sharing the
Machine](/pekit/concepts/sharing-the-machine.md).

```gcsl
import "github.com/gcslib/gcc"

def build app() {
    let objects = [gcc.compile(file("main.c")), gcc.compile(file("util.c"))]
    = gcc.link(objects, output = "app")
}
```

Here the two compiles run at once, and the link runs when both have
finished. The target's code ran once, start to finish, before any of them.

In a terminal, pekit shows a line with the steps running and how many have
finished while the build goes, and clears it when the build ends.

When its output goes to a file or a service's journal instead, pekit keeps
quiet for a build that ends within a minute. After a minute, it writes a
line every minute with how many targets have ended, how many steps ran or
were found, which steps are running, and how much memory pekit is using:

```text
[00:12:00] 23 of 30 targets ended; 812 steps run, 4410 found; running 2: compile/9927fb8abbee4a05, link/3f1c0a9e2b7d4c68; pekit uses 3.2 GiB
```

From then on it also writes a line as each target ends, `ended` or
`FAILED`. Set `PEKIT_PROGRESS_SECS` to change the minute, or to `0` for no
lines.

## Several targets are one build

`pekit build app tool` builds both targets as one build. A step that both
targets need, such as a library they both link, runs once. Their other
steps run at the same time as each other.

A step's identity doesn't depend on which target asked for it. Two targets
that make the same call share the step, and so does the next build that
makes it, in this workspace or any other on the machine.

If one target fails, the others carry on. pekit reports each target, and
exits with status 1 if any failed.

## Waiting for a step's result

A target's code can use what a step made to decide what to build next. In
this target, `generate` is a hermetic function that runs a generator,
`msggen`, which writes a directory of C files. The code lists those files
and compiles each:

```gcsl
def build app() {
    let out = generate(build msggen(), file("data/messages.txt"))
    let objects = for f in out.files() if f.path.ends_with(".c") {
        gcc.compile(f)
    }
    = gcc.link(objects, output = "app")
}
```

`out.files()` needs the generator's result. The target's code stops there,
pekit runs the generator's step, and the code carries on from where it
stopped, with the files. This is a dynamic dependency: the compile steps
aren't known until the generator has run.

Dynamic dependencies cost a pause, but nothing else. The steps before the
pause still run in parallel, and the code never runs twice. A build that must
know all its steps before anything runs, such as one in continuous
integration, can forbid them with `--no-dynamic`. It fails a target at the
point the target waits.

Waiting for a fetch, or for an archive to unpack, isn't a dynamic
dependency. pekit does those for the target's code itself, as part of
evaluating it.

## What a target's own code can do

A target's code runs outside any sandbox, on your machine. It can fetch
files, unpack archives, read the workspace and what steps made, and run
programs. It sees the workspace at `/w` and outputs at `/pekit-out`, as
steps do, but its effects aren't cached: they happen every time the code
runs.

So keep the work in steps. Code that runs a compiler in a target's own
body runs it on every build, however little changed. A strict build goes
further, and refuses a target's own code anything but fetching, unpacking,
reading, and asking for secrets. See [Hermetic and Strict
Builds](/pekit/concepts/hermetic-and-strict-builds.md).

## Calls inside a step

Only a call made by a target's own code becomes a step. Inside a step, a
call of another hermetic function runs as part of the step, in the same
sandbox, and isn't cached on its own. To cache two pieces of work
separately, call both from the target's code, and pass the first one's
result to the second.

---

# Step Sandboxes

_Pekit / How Pekit Builds_

> What a step can see and change while it runs, covering the paths of its inputs and outputs, its own directory, the host's tools, its environment, the network, devices, and the directories it composes.

pekit runs every step in a sandbox of its own, made with bubblewrap. The
sandbox holds only what the step was given, so the step can't depend on
anything pekit doesn't know about. That is what lets pekit reuse a step's
result safely: if none of the step's inputs changed, nothing it could see
changed either.

## The layout every step sees

Every step sees the same layout, on every machine and in every checkout:

| Path | Holds |
|---|---|
| `/w` | The workspace files the step was given, at their paths in the workspace. |
| `/pekit-out` | The results of earlier steps that the step was given. |
| `/pekit-out/.steps/<function>/<identity>` | The step's own directory, where it writes what it makes. |
| `/tmp` | An empty, writable directory of the step's own. |
| `/usr`, `/bin`, `/lib`, `/lib64`, `/sbin` | The host's own, read-only, unless the build is strict. |
| `/etc/passwd`, `/etc/group` | A fixed user database, the same in every step. |

A file the step wasn't given isn't there. If a step is given
`file("src/main.c")` from the directory `app`, it finds `/w/app/src/main.c`,
and no other file of the workspace. A path outside what the step was given
fails with "it is outside the step".

Because the layout never depends on where your checkout is, a path a step
records, such as a path a compiler writes into debugging information, is
the same on every machine.

## The step's own directory

`working_dir()` names the step's own directory. A program the step runs
starts there, and the step gives what it made from there:

```gcsl
#[hermetic]
fn archive(files: List<File>) -> File {
    let paths = for f in files { f.path }
    let packed = exec(["tar", "-cf", "files.tar", ...paths])
    = working_dir().file("files.tar")
}
```

The directory is named after the step's function and its identity, a
digest of what the step is. So the same call makes the same directory in
every build. [Where Results Go](/pekit/concepts/where-results-go.md) describes how its
files reach `pekit-out/`.

A relative path in GCSL code, such as `file("main.c")`, is never relative
to the step's directory. It's relative to the directory of the build file
it's written in, as it is everywhere else. Use `working_dir().file(name)`
for a file the step made.

## Inputs are read-only

A step can't change what it was given. Its programs see their inputs
read-only, and GCSL's file functions, such as `fs.write` and `fs.copy`,
refuse to change a path in one. They also refuse to change a directory the
step composed with `fs.compose`, once it's made.

To change files it was given, a step works on a copy in its own directory.
This step copies a directory and adds a file to the copy:

```gcsl
import fs

#[hermetic]
fn stamped(source: Dir) -> Dir {
    let copied = exec(["cp", "-r", source.path, "copy"])
    fs.write(working_dir().file("copy/STAMP").path, "built by pekit\n")
    = working_dir().dir("copy")
}
```

A large directory that `fs.compose` places whole, such as a toolchain of
thousands of files, is mounted from the store rather than copied. It's mounted
in any `Dir.sandbox` made of the composition too. In a sandbox, a program can
change files inside such a directory, but can't move or remove the directory
itself: it fails with "Device or resource busy".

## The host's tools

Outside a strict build, a step can run the host's own programs: it sees the
host's `/usr`, `/bin`, `/lib`, `/lib64`, and `/sbin`, read-only. It doesn't
see `/usr/local`. Its `/etc` holds only what those programs need to load
their libraries.

A build that uses the host's tools isn't hermetic, because what a step
gives depends on what's installed. pekit says so after the build, and keys
every such step by a fingerprint of the host's installed packages, so that
upgrading a compiler doesn't leave stale results in the store. [Hermetic
and Strict Builds](/pekit/concepts/hermetic-and-strict-builds.md) describes the fingerprint, and how
to build without the host's tools.

## Environment and isolation

A step's programs run with only the environment variables their `exec`
call sets, and `PATH` set to `/usr/bin:/bin:/usr/sbin:/sbin` if the call
doesn't set it. `LOGNAME` and `USER` are `pekit` unless the call sets
them. Nothing of the environment you ran pekit in reaches them.

A step has no network. It has its own processes, its own users, and a
`/dev` that holds only the usual few devices, such as `/dev/null` and
`/dev/urandom`. If pekit stops, its steps' programs are stopped too.

## The step's user

A step's programs run as the user `pekit`, number 1000, in the group
`pekit`, number 1000, whoever runs pekit. Every step has the same
`/etc/passwd` and `/etc/group`, holding `root`, `pekit` and `nobody`, as
Nix gives its builds. They don't come from the host, so a step behaves the
same on every machine. A program that looks up the current user's name
finds it, and a test that needs `/etc/passwd` to exist finds it.

`pekit` has no home directory. A program that tries to write to its home
fails, instead of leaving files that nothing keys. Give a step a `HOME`,
such as a directory under `/tmp`, if its programs need one.
[The Step Sandbox](/pekit/technical-reference/sandboxes/the-step-sandbox.md) lists the files' contents.

A step that runs a virtual machine can ask for KVM with
`#[device("kvm")]`. [Writing Steps](/pekit/building/writing-steps.md) shows how, and
the other attributes a step can take.

## Sandboxes inside a step

A step can make sandboxes of its own with `Dir.sandbox`, as a build library
does to run a pinned compiler on the compiler's own runtime. Each sandbox's
programs see the sandbox's directory as their `/`, and are cut off from the
network and the host as the step's own programs are. A sandbox is a copy:
nothing a program writes in it reaches the directory it was made of.

A sandbox's programs run as the step's user, and find the step's
`/etc/passwd` and `/etc/group` unless the sandbox's directory has its own.
A build environment that puts its own user database in the directory it
composes keeps it.

---

# Reuse and the Store

_Pekit / How Pekit Builds_

> How pekit decides that a step's result can be reused, what keys a step, how it tells a changed file, how it reuses the programs of a step that runs again, and how the store is shared and kept to its size limit.

pekit keeps the result of every step that succeeds in its store. When a build
needs a step that pekit has already run with the same inputs, pekit takes the
result from the store instead of running the step again. This page explains
what "the same" means, so you can predict what a change rebuilds.

## What keys a step

A step's key is everything that can change what it gives:

- **Its code.** The source files that declare its function and every
  function it calls, library files included. Any change to one of those
  files counts, even to a comment.
- **Its arguments.** Every value passed to it, and the contents of every
  file and directory among them.
- **Where it writes.** The step's own directory, which is named by what the
  step is.
- **Its platform.** The kind of machine it runs on.
- **The contexts it reads.** Only those it actually read as it ran.
- **The host's packages.** A fingerprint of what's installed, unless the
  build is strict. See [Hermetic and Strict Builds](/pekit/concepts/hermetic-and-strict-builds.md).

When every part of the key matches a step pekit recorded, the build reports
the step as found in the store:

```text
built app/hello: 0 steps run, 2 found in the store
```

Change a file a step reads, and that step runs again. So does every step
that takes what it gives, unless the step that ran again gave exactly the
same files as before. A comment changed in a C source, say, reruns its
compile, but if the object file comes out the same, the link is found in
the store.

## How pekit tells a changed file

pekit compares files by their contents, never by their modification times. To
avoid reading the whole workspace on every build, it remembers each file's
size, times, and inode from the last build. It reads again only a file where
one of those changed. A workspace where nothing changed builds without reading
any file.

Saving a file without changing it doesn't rebuild anything, and neither
does changing a file and changing it back.

## Contexts a step reads

GCSL contexts, such as `^platform`, pass settings through every call
without being arguments. A step is keyed only by the contexts it read as it
ran. Registering another toolchain, or binding a context the step never
reads, doesn't make it run again.

A step that read a context nothing bound, and so got the context's default,
is keyed apart from the same step with the context bound, even to the same
value. A step is given the files a context names only once it reads that
context, so a program it runs can't reach a file its key doesn't cover.

## Programs found in a step that runs

A step runs again when anything in its key changes, including its code.
Editing a comment in the file that declares a step, or in a library it
uses, makes it run. Most of the programs it runs then see exactly what they
saw before.

So pekit also records each program a step runs. A program's key is what it can
see: the files the step was given, the step's own directory and `/tmp` as they
are when the program starts, and everything the step did before it. When a
step runs again, a program that sees the same as before isn't run. pekit puts
back what it wrote, and the step goes on:

```text
built app/hello: 1 step run (2 programs found), 0 found in the store
```

The first program that sees something new runs, and so does each program
after it that sees what that program wrote.

pekit records no program of a step from the moment the step is given a
secret. Nor does it record a program once a sandbox of the step removes a
file of the directory the sandbox was made of, because the store can't hold
a removal.

## What's never reused

Some results are never taken from the store:

- A step whose result holds a secret. It runs on every build.
- A step that failed. Only a step that succeeds is recorded.
- Everything, in a build run with `--rebuild`, which runs every step and
  every program again and records each as it goes.

## One store for the machine

Every workspace on a machine shares one store. A step's key doesn't include
where the workspace is, so two checkouts of the same commit, or two
workspaces that build the same library, share their results.

The store is in pekit's cache directory: `$PEKIT_CACHE_DIR` if you set it,
otherwise `pekit` under `$XDG_CACHE_HOME`, otherwise `~/.cache/pekit`.

Files in the store are kept by their SHA-256 digests, so a file that
several steps give is stored once. That includes every file pekit fetches:
a pinned download already in the store is never downloaded again.

A remote cache shares steps between machines in the same way. A step
missing from the store is looked for there before it runs. See [Sharing a
Remote Cache](/pekit/building/sharing-a-remote-cache.md).

## Keeping the store to its size

The store has a size limit, 100 GiB unless you set `PEKIT_CACHE_LIMIT`.
When a build ends with the store over its limit, pekit evicts until the
store is under nine tenths of it. It removes first what is cheapest to make
again for the space it takes, and among those, what was used longest ago.
A large file that took a second to make goes before a small one that took a
minute.

Eviction removes files, not records. A step whose outputs were evicted
isn't found in the store: it runs again and puts them back. While another
pekit process is using the store, a build evicts nothing, and a later
build does it instead. [Managing the Store](/pekit/building/managing-the-store.md)
shows how to set the limit, and how to clear the store.

---

# Where Results Go

_Pekit / How Pekit Builds_

> How pekit lays out pekit-out, covering each step's own directory, the paths under each target's name, fetched and unpacked files, and when intermediate files appear on disk.

pekit puts what a build made in `pekit-out/`, at the root of the workspace. It
has two views of the same files. One is by what each step is, which never
changes from build to build. The other is by the name of each target you
built, and it's the one `pekit build` prints.

## Each target's files

After a build, each file a target gave is under `pekit-out/`, by the
target's name and the step that made it:

```text
built app/hello: 1 step run, 0 found in the store
  ../pekit-out/app/hello/link/hello
```

Here the target `app/hello` gave a file its `link` step made. If a target
gives files from two steps of the same function, the second is under `link.2`,
the third under `link.3`, and so on. They're numbered in the order the
target's value names them. The path pekit prints is relative to the directory
you ran it from.

These paths are symbolic links into each step's own directory. The file
they lead to is a copy of the step's output, and it's yours: you can change
it or delete it, and the next build puts it back. A copy that nobody has
changed since a build made it is left as it is, so a build with nothing to
run doesn't write its results out again.

## Each step's own directory

Every step has a directory of its own under `pekit-out/.steps/`. It's named by
the step's function and a digest of what the step is: its function, its
arguments, and the platform it runs on. For example,
`pekit-out/.steps/link/3fa9c2e17b04d6a8/` is the directory of one call of
`link`.

A file argument counts by its path, not its contents, so the directory
stays the same when you edit a source file. Changing the file runs the step
again, in the same directory. Two targets that make the same call share
the one step and its directory, whichever of them asked for it.

## Fetched and unpacked files

Files that the build fetched, unpacked, or took from a git repository are
named by their contents rather than by a step:

| Path | Holds |
|---|---|
| `pekit-out/.fetch/<sha256>/<name>` | A file `fetch` downloaded, by its digest and the last part of its URL. |
| `pekit-out/.unpack/<key>` | What `archive.unpack` unpacked, by a digest of the archive and how much of each path it strips. |
| `pekit-out/.git/<key>/<name>` | The files of one commit `fetch_git` took, by a digest of the repository and the commit. |

A target that gives one of these directly, rather than a step's output,
shows it at this path. It isn't linked under the target's name.

## When intermediate files appear

pekit keeps every output in its store, and gives steps their inputs from
there. Most intermediate files, such as object files, are never needed on
disk, so pekit doesn't write them to `pekit-out/` unless something outside
a step might read them there. That happens when:

- A target's own code runs a program, or reads a file of `pekit-out/` by a
  path it names as text.
- `pekit run` runs a program, which might read any of them.

What a target gives always appears. Files that appear this way are
read-only, and they're the store's own files: don't change them.

## Paths in GCSL values

In GCSL code, every output's path starts with `/pekit-out`, and every
workspace file's with `/w`. A target that gives `gcc.link(...)` gives a
`File` whose path is `/pekit-out/.steps/link/<identity>/hello`, the same on
every machine. `pekit build` shows it as a path on your machine instead.

`pekit-out/` isn't part of the workspace. A listing such as
`dir(".").files()` never includes it, and a step can't be given a file in it
by its path in the workspace. Name an output by its path under
`/pekit-out` instead, or better, pass the value the step gave.

---

# Platforms and Toolchains

_Pekit / How Pekit Builds_

> How pekit tells the machine steps run on from the platform a build is for, how a library asks for a compiler, how a workspace registers its toolchains, and how pinned toolchains keep the host out of a build.

A build involves two platforms. Steps run on one machine, and what they
build can be for another, as when you compile a program for a phone on a
laptop. pekit keeps the two apart, and libraries use them to choose the
right compiler for each step.

## Two platforms

GCSL has two contexts for platforms, each a record such as
`{arch = "x86_64"; os = "linux"}`:

- **`^host_platform`** is where steps run. pekit sets it to the machine
  it runs on, for every target it builds.
- **`^platform`** is what the build is for. It's the same as
  `^host_platform` unless something sets it.

`pekit build --platform aarch64-linux app` builds `app` for 64-bit Arm
Linux, as if the target were called with `with { platform = ... }`.
`--platform aarch64` keeps the machine's operating system. A target can
also set the platform for part of its work:

```gcsl
def build all() {
    x86_64 = build app() with { platform = {arch = "x86_64"; os = "linux"} }
    aarch64 = build app() with { platform = {arch = "aarch64"; os = "linux"} }
}
```

Every step is keyed by the machine it runs on, so a result made on one
kind of machine is never reused on another. [GCSL's context
page](/gcsl/language/context.md) explains contexts in general.

## Asking for a toolchain

A library doesn't name a compiler. It asks GCSL's `toolchain` module for
one of a kind, such as `toolchain.get(Toolchain::C)`, and gets the first
registered toolchain of that kind that runs on `^host_platform` and builds
for `^platform`.

Libraries ask in a parameter default:

```gcsl
#[hermetic]
def compile(src: File, cchain: toolchain.CToolchain = toolchain.get(Toolchain::C)) -> File {
    # ...
}
```

The default is worked out where the function is called, outside the step,
so the toolchain arrives as an ordinary argument. The step is keyed by the
toolchain's files, and changing the compiler reruns exactly the steps that
use it. [GCSL's toolchains page](/gcsl/language/toolchains.md) describes the module and
the kinds of toolchain.

## Registering toolchains

A workspace registers the toolchains it builds with in `pekitconf`, in
`workspace.gcsl`:

```gcsl
import Toolchain::* from "github.com/gcslib/gcc"
import Toolchain from toolchain

pekitconf = {toolchains = [
    Toolchain::C gcc_x86_64,
    Toolchain::C gcc_x86_64_to_aarch64,
]}
```

pekit sets the `toolchains` context from this list for every target it
builds. The list is in order of preference, and the first toolchain that
fits both platforms is used. So a workspace can register a native compiler
and a cross compiler, and each step gets the one its platforms need.

With nothing registered, the list holds one toolchain, `system_c`: the
host's own `cc`, which builds only for the host. Registering any toolchain
replaces it. If you still want the host's compiler, register `system_c`
yourself.

A registered toolchain's definition runs only when the build first asks
for its kind, and only once. A toolchain that has to be downloaded or
built costs nothing in a build that doesn't use it.

## Pinned toolchains

A pinned toolchain is fetched by its SHA-256 digest, such as the gcc
library's Bootlin compilers. Its tools run in a sandbox whose root is the
toolchain's own runtime, so they read none of the host's libraries or
headers. A build whose steps use only pinned toolchains gives the same
results on any machine of the same platform.

The host's own toolchains, such as `system_c`, run the host's programs, so
a build that uses them depends on what's installed.
[Hermetic and Strict Builds](/pekit/concepts/hermetic-and-strict-builds.md) describes how pekit
accounts for that, and how a strict build refuses it.

---

# Hermetic and Strict Builds

_Pekit / How Pekit Builds_

> What makes a pekit build hermetic, how pekit keys steps that use the host's tools by a fingerprint of its packages, what a strict build refuses, and how pekit checks that a build is reproducible.

A build is hermetic when its results depend only on its inputs: the
workspace, the libraries it pins, and the files it fetches by their
digests. A hermetic build gives the same results on any machine of the same
platform, which is what lets you trust a release, or share results between
machines.

Every step runs in a sandbox, but a sandbox alone doesn't make a build
hermetic. By default a step can still run the host's own programs, and
those differ from machine to machine.

## Builds that use the host's tools

Outside a strict build, every step can see the host's `/usr`, `/bin`,
`/lib`, `/lib64`, and `/sbin`. A step that runs `cc` from there depends on
which compiler is installed. pekit can't tell which steps used the host's
tools, so after any build that ran steps and wasn't strict, it says the
build isn't hermetic:

```text
note: steps ran with the host's own tools, so this build is not hermetic
```

So that upgrading a package doesn't leave stale results in the store,
pekit keys every such step by a fingerprint of the host. The fingerprint is
a digest of `/etc/os-release`, of the package manager's database, and of
the parts of `/etc` that choose programs, such as `/etc/alternatives`.
Installing, upgrading, or removing any package changes it, and the steps
run again.

pekit knows the package databases of dpkg, rpm, apk, and pacman. On a host
with none of them, it can't tell when the tools change, so it warns, and
doesn't reuse any step from the store:

```text
warning: the host's packages cannot be identified, so no step is reused from the store
```

Programs in `/usr/local` aren't managed by a package manager, so a change
to them would change no fingerprint. Steps don't see `/usr/local` at all.

## Strict builds

`--strict` builds as a release should: from what the workspace pins, and
nothing of the machine it runs on.

- **Steps see none of the host's tools.** A step has to run its programs
  from a pinned toolchain or build environment. The host's own toolchains,
  such as `system_c`, fail a strict build.
- **A target's own code can only fetch, unpack, read, and ask for
  secrets.** It can read the workspace and the build's outputs. It can't
  run a program, write a file, or read anything else of the host. Each of
  these fails where the target does it.
- **Every library has to be pinned.** The build fails unless its libraries
  are exactly those `pekit.lock` pins, and `$GCSL_LIBRARY_PATH` is unset.
  See [Pinning Libraries](/pekit/libraries/pinning-libraries.md).
- **Scratch directories start empty.** A step marked `#[scratch]` gets an
  empty directory every time, so nothing kept from an earlier run can reach
  what the build gives.

A strict build's steps aren't keyed by the host's fingerprint. Their keys
are the same on any machine of the platform, so a strict build's results
can be shared between machines.

## Requiring strict builds

A strict build and one that isn't are keyed apart, so a workspace that
mixes them builds everything twice. A workspace that should only ever be
built strictly, such as one that builds packages for a repository, can say
so in `workspace.gcsl`:

```gcsl
pekitconf = {
    packagers = [packager()]
    require_strict = true
}
```

Then `pekit build`, `pekit test`, `pekit package`, and `pekit publish`
refuse to run without `--strict`:

```text
error: this workspace requires `--strict`, as `pekitconf.require_strict` in `workspace.gcsl` says, so that every build is keyed and checked as a strict one: run `pekit build --strict`
```

The setting refuses rather than adding `--strict` for you. A command line
then means the same in every workspace, so a command in a script, a README,
or a CI job says whether it's strict. The cost is typing `--strict` each
time.

pekit reads `require_strict` before it builds, without running
`workspace.gcsl`. So write it as `true` or `false`, inside the `pekitconf`
record. `pekit run` and `pekit query` don't check it, but a build that
`pekit run` makes isn't strict unless you pass `--strict`. `pekit release`
is always strict.

## Reproducible builds

A step is reproducible if it gives the same outputs, byte for byte, every
time it runs with the same inputs. A hermetic build can still have a step
that isn't, such as one that writes the current time into its output.

`--check-reproducible` finds them. It builds, then runs every step again,
reusing nothing from the store, and compares what each gave the second
time with the first. A step that gave other outputs fails the command. See
[Checking That a Build Is
Reproducible](/pekit/building/checking-reproducibility.md).

`pekit release` builds strictly and checks that the build is reproducible
before it publishes anything. See [Releasing](/pekit/shipping/releasing.md).

---

# Sharing the Machine

_Pekit / How Pekit Builds_

> How every pekit build on a machine shares one budget of programs and memory, how pekit estimates what a program uses, how make and Cargo borrow from the budget, and how two builds that need the same step run it once.

Several pekit builds often run on one machine at once: a build in each
worktree of a repository, or one for each agent working on it. Each build
runs as many programs as `--jobs` allows, so without anything shared, twelve
builds would run twelve times as many compilers as the machine has
processors, and could run it out of memory. pekit shares one budget between
every build on the machine instead, and runs a step that two builds need at
the same time only once.

## The budget

The machine's budget has two limits:

- **Jobs:** how many programs can run at once, by default one for each
  processor.
- **Memory:** how many bytes those programs are expected to use at once, by
  default half the machine's memory, leaving the rest to editors, other
  builds, and everything else the machine runs.

Before a program of a step runs, pekit takes one job from the budget, and as
much memory as it expects the program to use. When the program ends, it
gives them back. A program that can't have both waits, holding neither,
while the build goes on with everything else it can do. A build's programs
wait in the order the build asked for them.

`--jobs` still limits one build: a build runs at most that many programs,
however much of the budget is free. The budget limits every build together.

A program expected to use more memory than the whole budget runs alone,
once every other program has given its memory back. A program that has
waited long for the budget stops every other program from starting until
it starts, so a stream of smaller programs can't keep it waiting forever.

The budget only changes when a program runs. It's never part of a step's
key, so a build with another budget finds the same steps in the store.

## What a program is expected to use

pekit measures the peak memory of every program a step runs, and keeps the
last few peaks of each program of each step. It expects a program to use a
quarter more than the most it used in those runs:

1. by the same program in the same step, if that was measured;
2. otherwise by the same program in other steps of the same function, such
   as `rustc` in another crate's compile;
3. otherwise 1 GiB, or what you set, and half as much again for `rustc`:
   one `rustc` compiling a large crate, such as a GUI application's, can
   use 0.7 to 1.4 GB.

The peak pekit measures is that of the program's largest process, not the
sum of its processes. A `make -j` that runs several compilers at once uses
more than its peak says. If such steps overrun the machine, lower the
budget's memory to leave room.

## Setting the budget

Set the budget for every build on the machine in `machine.conf`, in pekit's
configuration directory: `$XDG_CONFIG_HOME/pekit`, otherwise
`~/.config/pekit`.

```text
# This machine: 16 processors, 64 GiB, other work alongside.
jobs = 12
memory = 40GiB
unseen = 2GiB
```

`unseen` is what a program is expected to use when pekit has never measured
it. Each setting can also be given in the environment, which overrides the
file: `PEKIT_MACHINE_JOBS`, `PEKIT_MACHINE_MEMORY`, and
`PEKIT_MACHINE_UNSEEN`. Sizes are written as `PEKIT_CACHE_LIMIT`'s are,
such as `512MiB` or `24GiB`.

Each build reads the budget for itself. Builds that read different limits
share the larger, so set the budget in `machine.conf` rather than in one
build's environment.

`machine.conf` can also set three more things for every build on the
machine:

- `cache_limit`, how large the store can grow, as `PEKIT_CACHE_LIMIT` does.
- `evaluating`, how many targets a build evaluates at once, as
  `PEKIT_EVALUATING` does.
- `keep_free`, how much room builds keep free on the store's disk, as
  `PEKIT_KEEP_FREE` does (see [Managing the
  Store](/pekit/building/managing-the-store.md#keep-room-free-on-the-disk)).

The environment overrides each:

```text
cache_limit = 400GiB
evaluating = 8
keep_free = 30GiB
```

## Jobservers for `make` and Cargo

A program can use more than one processor. `make -j`, Cargo, `rustc`, and
the `cc` crate share processors through a GNU make *jobserver*: a pipe of
tokens, each a job they can run. pekit gives every program of a step a
jobserver, by setting `MAKEFLAGS` and `CARGO_MAKEFLAGS`. Every token in it
is a job of the machine's budget that pekit lends while it's free.

So a step's `make` runs its recipes one at a time on a busy machine, and as
many at once as there are free jobs on an idle one. Run `make` without `-j`
in a step: GNU make 4.4 or later takes its jobs from the jobserver. An
older make can't read this form of jobserver and can stop with an error,
so a step that runs make needs make 4.4 or later.

pekit takes lent jobs back as soon as another program waits for the
budget. A step that sets `MAKEFLAGS` or `CARGO_MAKEFLAGS` itself keeps its
own value. Neither variable is part of a step's key.

## Memory for evaluating targets

The budget covers the programs that steps run. pekit itself also uses
memory while it evaluates a target's code, before and between its steps.
The code of a large target, such as a Rust package with hundreds of crates,
can need a few hundred megabytes while it runs.

pekit evaluates at most a few targets at once, by default as many as `--jobs`
and at least 8, and starts the next as one finishes. A target stops counting
once its code has run to the end and it waits only for its steps, so its steps
still run alongside the next targets' code. A build of hundreds of targets
then needs the memory of a few at once rather than of all of them, and takes
about as long, since pekit evaluates code on one thread either way.

To change the limit, give `--evaluating` or set `PEKIT_EVALUATING`:

```sh
pekit package --evaluating 4 'app/**'
```

A lower number uses less memory. `0` evaluates every target named at once,
which suits a build of a few targets on a machine with memory to spare.

## A step two builds need at once

Two worktrees at the same commit need the same steps, and both would run
each one before either had recorded it. Instead, a build that doesn't find a
step in the store claims it, and holds the claim until the step is
recorded. Another build that needs the step meanwhile waits for the claim,
going on with its other steps, and then finds the step in the store:

```text
built app/hello: 0 steps run, 2 found in the store
```

If the build that held the claim fails the step, or stops, the waiting
build runs the step itself.
