Peios Learn
Documentation

Peios

Peios Peios Kernel Universal Directory Project

Developer Tools

Trail Acta Provium clackatoo CAF GCSL Pekit

Applications

Framewright

Standards and Conventions

Standards and Conventions Peios Specifications
Pekit

Pekit

A build system whose build files are GCSL.

Single-page view · as markdown

Pekit

Pekit / Getting Started

pekit is a build system. You describe what to build in GCSL, a typed scripting language, and pekit works out which steps that needs, runs each one in a sandbox, and keeps every result. When you build again, pekit runs only the steps whose inputs changed.

If you have used Bazel, pekit will be familiar: a build is a graph of cached, sandboxed actions, and the same inputs always give the same outputs. The difference is the language. A pekit build file is an ordinary GCSL program, so a build can compute what to build, and can decide what to do next from what an earlier step made.

The parts of a build #

These are the parts a build is made of:

  • Workspace. A directory tree with a workspace.gcsl file at its root. Everything pekit builds comes from a workspace.
  • Build file. A .gcsl file in the workspace that declares what can be built.
  • Target. A definition in a build file that you can ask pekit to build, such as def build hello().
  • Step. One cached, sandboxed piece of work, such as compiling a file. A step is a call of a GCSL function marked #[hermetic].
  • Store. Where pekit keeps the result of every step, shared by every workspace on the machine.
  • Output directory. pekit-out/, at the workspace's root, where pekit puts what each target built.

A target's own code runs outside any sandbox and decides which steps to call. pekit runs the steps, as many at once as the machine allows, and gives their results back to the code that asked for them. Targets and Steps explains how the two fit together.

Why steps are sandboxed #

A step can see only what it's given: the files passed to it as arguments, and the results of the steps before it. pekit keys each step by exactly those inputs. So when none of them has changed, pekit knows the step would give the same result, and takes it from the store instead of running it. If a step could read anything else, a change to that file would go unnoticed, and pekit would reuse a stale result.

The same rule makes builds portable. A step sees the workspace at /w and earlier results at /pekit-out, wherever your checkout is, so two machines that build the same commit run the same steps.

What pekit does #

The pekit command builds targets, and also runs the other kinds of definition a workspace can hold:

CommandDoes
pekit buildBuilds targets.
pekit testRuns tests, and doesn't rerun a passing test whose inputs didn't change.
pekit runRuns a script, or a program a target built.
pekit queryLists what targets reach, or which targets a file change reaches, without building.
pekit lockPins the libraries a workspace imports.
pekit package and pekit publishPack packages, and publish them into a package store.
pekit releaseBuilds a package from a commit, checks that it's reproducible, publishes it, and tags the commit.
pekit cleanRemoves pekit-out/, and optionally the store.

pekit(1) documents every command and option.

Where to go next #

Start with Building a First Program, which builds a C program from an empty directory. Then read Workspaces and the How Pekit Builds topic. pekit's build files are GCSL, and the GCSL documentation covers the language itself.

Building a First Program

Pekit / Getting Started

This page builds a one-file C program from an empty directory. Along the way it shows the parts every pekit build has: a workspace, a build file, a target, and a step. It takes about five minutes.

Before you start #

You need:

  • pekit. To build it from its source, run cargo install --git https://github.com/peios/pekit pekit --locked, or cargo install --path crates/pekit --locked in a checkout. Building it needs a C compiler and make, for the compression libraries and the memory allocator it links.
  • bubblewrap, the bwrap program, which pekit runs every step in.
  • A C compiler from your distribution's packages, as /usr/bin/cc. A step can see the host's /usr, but not /usr/local.

Create the workspace #

  1. Make a directory for the workspace, and change into it:

    mkdir hello
    cd hello
    
  2. Create an empty workspace.gcsl. Its presence makes the directory a workspace; it can hold settings, but this one doesn't need any.

    touch workspace.gcsl
    
  3. Save this program as hello.c:

    #include <stdio.h>
    
    int main(void) {
        puts("Hello from pekit");
        return 0;
    }
    

Write the build file #

Save this as build.gcsl, beside hello.c:

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

def build hello() {
    = compile(file("hello.c"))
}

The file declares two things:

  • compile, a function that runs the compiler on one source file and gives the program it made. #[hermetic] makes each call of it a step: pekit runs the call in a sandbox that holds only source, and keeps what it gives. working_dir() is the step's own directory, where the compiler writes hello.
  • hello, a target. def build declares a definition you can name to pekit build. Its body calls compile with the file hello.c, found relative to the build file.

Build it #

  1. Build the target:

    pekit build hello
    

    pekit runs the one step, and shows what the target gave:

    built /hello: 1 step run, 0 found in the store
      pekit-out/hello/compile/hello
    note: steps ran with the host's own tools, so this build is not hermetic
    

    The note says that the step could use your machine's own tools, and this one did: it ran your cc. That's fine to start with. Hermetic and Strict Builds explains how to build without them.

  2. Run the program:

    ./pekit-out/hello/compile/hello
    

    It prints Hello from pekit.

  3. Build again:

    pekit build hello
    

    Nothing changed, so pekit takes the step's result from its store instead of running it:

    built /hello: 0 steps run, 1 found in the store
      pekit-out/hello/compile/hello
    

Change the program #

  1. In hello.c, change the message to Hello again.

  2. Build again. pekit sees that the step's input changed, and runs it:

    built /hello: 1 step run, 0 found in the store
      pekit-out/hello/compile/hello
    
  3. Change the message back to Hello from pekit, and build once more. pekit has run the step with that input before, so it finds the result in the store and runs nothing.

pekit tells a changed file by its contents, never by its modification time. Saving a file without changing it, or changing it and changing it back, rebuilds nothing.

Check the result #

pekit-out/hello/compile/hello is the program the last build made, and ./pekit-out/hello/compile/hello prints Hello from pekit. The path names the target, hello, then the step that made the file, compile. Where Results Go describes the rest of pekit-out/.

Next steps #

A real C build compiles and links many files, and uses a compiler pekit pins rather than the host's. The gcc library does both: see Building C. Targets and Steps explains what pekit did during each build.

Workspaces

Pekit / Getting Started

A workspace is the directory tree that pekit builds from. Its root holds a file called workspace.gcsl, and every directory below the root belongs to it. pekit finds the workspace from the directory you run it in, by looking upward for the nearest workspace.gcsl, so you can run pekit from any directory inside.

A pekit workspace is a GCSL workspace, so GCSL's rules for how files see each other apply unchanged. Workspaces in the GCSL documentation describes them.

Build files #

Any .gcsl file in the workspace can declare targets. A common layout puts a build.gcsl in each directory beside the sources it builds:

workspace.gcsl
pekit.lock
app/
  build.gcsl
  main.c
lib/
  build.gcsl
  greet.c
  greet.h

The files of one directory share their public declarations, and a directory sees the public declarations of the directories above it. So a helper declared in workspace.gcsl is available everywhere, and a target in app/build.gcsl can call another in app/package.gcsl without an import. To use a declaration from a sibling directory, import it by its path from the root, as import lib.

A definition's full name is its directory and its name: app/hello is the definition hello in app. Naming Targets explains how you name one on the command line.

A relative path in a build file, such as file("main.c"), is relative to the directory of the file it's written in. It's never relative to the directory you run pekit from.

What pekit leaves out #

pekit reads build files from every directory of the workspace, except:

  • A directory or file whose name starts with a dot, such as .git.
  • A directory below the root that has a workspace.gcsl of its own. A nested workspace is a separate workspace, built on its own.
  • A path that .gcslignore at the root names. Use it for .gcsl files that are data, such as test fixtures. Each line names one file or directory, relative to the root, and lines that start with # are comments.

These rules decide only which .gcsl files declare definitions. A build can read any file under the root, hidden or not. A directory listing such as dir(".").files() includes hidden files too, but it leaves out three kinds of directory, with everything in them:

  • pekit-out/, the output directory. No build reads it as part of the workspace.
  • .git at the root, the workspace's history.
  • A directory below the root that holds a .git of its own, file or directory: a nested checkout, a Git worktree, or a submodule. It's another repository, so a listing doesn't descend into it. A listing of that directory itself, such as dir("other").files(), still includes everything in it.

pekit still loads the .gcsl files of a nested checkout that isn't hidden and has no workspace.gcsl of its own. To keep pekit out of one, or out of a large output directory such as Cargo's target/, name it in .gcslignore.

A step can take the whole workspace, by being given dir(".") at the root. It receives everything under the root except .git and pekit-out/, so a commit doesn't rerun the step, but any other file there does, whether or not Git tracks it. Listing only what a step needs avoids those reruns.

workspace.gcsl and pekitconf #

workspace.gcsl is an ordinary GCSL file. It can be empty, and it can declare helpers for the whole workspace. pekit also reads one value from it, pekitconf, a record of the workspace's settings:

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

pekitconf = {
    toolchains = [Toolchain::C gcc_x86_64]
    keychain = [{profile = "dev"; name = "signing"; file = "keys/test.pem"}]
}

Each field is optional:

  • toolchains. The compilers and other tools the workspace builds with. See Platforms and Toolchains.
  • keychain. Where each secret the build uses is kept. See Using Secrets.
  • packagers. The package formats pekit package packs into. See Packaging.
  • contexts. Values for contexts that the workspace or its libraries declare, by name, as contexts = {greeting = "Good morning"}. pekit sets each one for every target it builds. See Setting a Context for the Whole Workspace.

toolchains, keychain, and packagers each need the module the setting belongs to: toolchain for toolchains, keychain for keychain, and packaging for packagers. A library's import of the module counts, so importing the gcc library is enough for toolchains. Each name in contexts must be a context that some file of the workspace declares.

pekit refuses a pekitconf it can't read whole, rather than build without part of it. It stops before building anything if pekitconf has a field not in this list, such as one that an older or newer pekit reads, or sets toolchains, keychain, or packagers without the module that declares it. The error names the field and the fields pekit reads.

Files pekit adds #

pekit adds these to a workspace:

PathHoldsIn version control
pekit-out/What each target built, and the files of every step that ran.Ignore it.
.gcsl/libraries/The libraries pekit lock pinned, exported from their repositories.Ignore it. Any build puts back a pinned library that's missing.
pekit.lockThe commit each library is pinned at.Commit it, so every checkout builds with the same libraries.

Add pekit-out/ and .gcsl/ to your .gitignore. Everything else pekit keeps, such as its store, is outside the workspace, in your cache directory. Reuse and the Store describes it.

Targets and Steps

Pekit / How Pekit Builds

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 typeDeclaresRun by
buildSomething to build: a file, a directory, or a record of them.pekit build
testA check that passes or fails.pekit test
packageA package's name, version, and files.pekit package
scriptA 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]:

#[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 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.

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:

[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:

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.

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

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:

PathHolds
/wThe workspace files the step was given, at their paths in the workspace.
/pekit-outThe 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.
/tmpAn empty, writable directory of the step's own.
/usr, /bin, /lib, /lib64, /sbinThe host's own, read-only, unless the build is strict.
/etc/passwd, /etc/groupA 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:

#[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 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:

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 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 lists the files' contents.

A step that runs a virtual machine can ask for KVM with #[device("kvm")]. Writing Steps 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

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.

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

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:

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.

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 shows how to set the limit, and how to clear the store.

Where Results Go

Pekit / How Pekit Builds

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:

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:

PathHolds
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

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:

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 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:

#[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 describes the module and the kinds of toolchain.

Registering toolchains #

A workspace registers the toolchains it builds with in pekitconf, in workspace.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 describes how pekit accounts for that, and how a strict build refuses it.

Hermetic and Strict Builds

Pekit / How Pekit Builds

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:

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:

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.
  • 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:

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

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

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 release builds strictly and checks that the build is reproducible before it publishes anything. See Releasing.

Sharing the Machine

Pekit / How Pekit Builds

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.

# 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).

The environment overrides each:

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:

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:

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.

Naming Targets

Pekit / Building

Every pekit command that builds takes targets: definitions in your workspace, named by their name. pekit build hello builds the build definition called hello, and pekit test greeting runs the test definition called greeting. The command decides the kind; the name decides which definition of that kind.

When a name is defined more than once #

Directories often reuse names: several can each have a build main. pekit picks one this way:

  1. If only one definition of the kind has the name, pekit uses it, from any directory.
  2. If several do, pekit uses the one in the directory you ran pekit from.
  3. Otherwise, pekit lists each one by its full name and asks you to name one.

A full name puts the definition's directory first, relative to the workspace's root: pekit build app/hello. A definition in the root directory is /hello. A full name always means the same definition, wherever you run pekit from.

If no definition has the name, pekit says so and suggests the closest names it has.

Several targets at once #

A command takes as many targets as you give it. A glob selects every definition of the command's kind that it matches, relative to the directory you run pekit from. A glob reads as a full name does: its last part is the name, and the parts before it are directories.

GlobSelects
app/*Every definition in app.
app/test_*Each definition in app whose name begins with test_.
* or .Every definition in this directory.
pkgs/*/*Every definition in each directory directly below pkgs.
pkgs/**Every definition in pkgs and every directory below it.
**Every definition in this directory and every directory below it.

In a part, * matches any run of characters, as in net.*. ** matches any number of directories, including none, and as the last part it matches every name in them. A glob that starts with / is relative to the workspace's root. A glob never selects a library's definitions, so pekit test doesn't run the tests of the libraries you import.

Quote a glob, so that your shell doesn't expand it first:

pekit build hello 'pkgs/**'

Several targets are one build. A step that two of them need runs once, and their steps run at the same time. A definition that several names or globs select is built once. A target that fails doesn't stop the others, and pekit exits with status 1 if any did. To stop at the first failure instead, give --fail-fast: pekit starts nothing more, lets what is running finish, and reports each target it didn't finish.

With several targets, pekit reports each one, then the steps for the whole build:

built /stamp
  pekit-out/stamp/stamped/copy
built /tarred
  pekit-out/tarred/archive/files.tar
2 steps run, 0 found in the store

Commands that default to everything #

pekit test and pekit package don't need a name. Given none, each takes every definition of its kind in the directory you run it from and every directory below, as ** would. pekit build always needs at least one target.

Writing Steps

Pekit / Building

A step is a GCSL function marked #[hermetic]. Libraries such as the gcc library provide steps for common work. Any build can also declare its own: to run a code generator, to call a tool no library wraps, or to arrange files in a directory. This page writes a small C build from scratch, then covers the rest of what a step can do.

Before you start #

You need a workspace with a src directory holding these three files. src/add.c:

int add(int a, int b) { return a + b; }

src/add.h:

int add(int a, int b);

src/main.c:

#include "add.h"
#include <stdio.h>

int main(void) {
    printf("%d\n", add(2, 3));
    return 0;
}

Write the steps #

  1. In a build.gcsl beside src, declare a step that compiles one source file:

    import path
    
    #[hermetic]
    fn compile(source: File, headers: List<File> = []) -> File {
        let object = path.basename(source.path).strip_suffix(".c") + ".o"
        let includes = for h in headers { "-I{path.dirname(h.path)}" }
        let compiled = exec(["cc", "-c", ...includes, "-o", object, source.path])
        = working_dir().file(object)
    }
    

    The step's sandbox holds only source and headers, at their paths under /w. A header the step isn't given doesn't exist there, so the compile fails rather than reading a file pekit doesn't know about.

  2. Declare a step that links objects into a program. A step can give a record of several files:

    #[hermetic]
    fn link(objects: List<File>, name: String) -> {program: File, map: File} {
        let paths = for o in objects { o.path }
        let linked = exec(["cc", "-o", name, "-Wl,-Map={name}.map", ...paths])
        program = working_dir().file(name)
        map = working_dir().file("{name}.map")
    }
    
  3. Declare a target that calls them:

    def build adder() {
        let headers = [file("src/add.h")]
        let objects = [compile(file("src/add.c")), compile(file("src/main.c"), headers = headers)]
        = link(objects, "adder")
    }
    
  4. Build it:

    pekit build adder
    

    pekit runs the two compiles at the same time, then the link:

    built /adder: 3 steps run, 0 found in the store
      pekit-out/adder/link/adder
      pekit-out/adder/link/adder.map
    

Check the result #

Run ./pekit-out/adder/link/adder, which prints 5. Then add a comment to src/add.c and build again. The compile of add.c runs, but it makes the same object file as before, so the link is found in the store:

built /adder: 1 step run, 2 found in the store

What a step takes and gives #

A step's arguments can be any GCSL values. pekit gives the step every File and Dir among them, at their paths, and keys the step by their contents. Other values, such as strings and numbers, key the step by their values.

What a step gives has to be files it made in its own directory, files or directories it was given, or values without files. working_dir() is the step's own directory, and working_dir().file(name) and working_dir().dir(name) name what's in it. A step that gives a path outside these fails.

A relative path such as file("data.txt") is relative to the build file it's written in, even inside a step. It never names a file the step made.

Compose a directory #

fs.compose builds a directory from files and directories, each at the path you give it. This step lays out a program and its documentation as an install tree:

import fs
import path

#[hermetic]
fn layout(program: File, readme: File) -> Dir {
    = fs.compose([
        {at = "bin/{path.basename(program.path)}"; place = program},
        {at = "share/doc/README"; place = readme},
    ])
}

pekit links the files rather than copying them, and mounts a large directory whole. Once it's made, nothing can change the composed directory. To change files in it, run programs in a Dir.sandbox of it, which is a copy of its own. GCSL's File and Process Effects page describes both.

Use a toolchain #

A step that runs a compiler should take the compiler as an argument, so that pekit keys the step by the compiler's files. Resolve the toolchain in a parameter default, which runs where the step is called:

import toolchain
import Toolchain from toolchain

#[hermetic]
fn compile(source: File, cchain: toolchain.CToolchain = toolchain.get(Toolchain::C)) -> File {
    let compiled = exec([cchain.cc.path, "-c", "-o", "out.o", source.path])
    = working_dir().file("out.o")
}

This step works with the host's own compiler, whose runtime is /. A pinned toolchain's programs need its own runtime as their root, so a step runs them in a Dir.sandbox of the runtime. The gcc library's rules.gcsl shows how. See Registering Toolchains.

Report errors at the call #

When a program a step runs fails, pekit reports the error at the exec in the step's code, with the program's standard output and standard error:

error: `/bin/sh` exited with status 4
  --> build.gcsl:17:15
   |
17 |     let ran = exec(["/bin/sh", "-c", "echo to stdout; echo to stderr >&2; exit 4"])
   |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: its standard output: to stdout
   = note: its standard error: to stderr

In a library, mark a step #[track_caller] too, and an error in its body is reported where your code called it. GCSL's Attributes page describes it.

Retry a step, or limit its time #

Two attributes change how pekit runs a step:

  • #[retry(n)] runs a step that failed up to n more times, each time from the start in a fresh sandbox. A step that passes only on a retry is flaky, and pekit warns about it:

    warning: step `fetch_index` passed only when it was run again: it is flaky
    
  • #[timeout(limit)] fails a step that runs longer than limit, such as 5m or 30s. The limit covers every attempt together, not each one. The time pekit spends placing the step's inputs doesn't count.

#[retry(2)]
#[timeout(5m)]
#[hermetic]
fn integration(server: File) -> File {
    let ran = exec([server.path, "--self-test"])
    = working_dir().file("report.txt")
}

A step that times out fails with the step timed out, at the program it was running.

Give a step a device #

A step sees no device but the usual few, such as /dev/null. A step that runs a virtual machine can ask for KVM, so the machine runs at full speed:

#[device("kvm")]
#[hermetic]
fn boots(iso: File) -> File {
    # Runs QEMU with -enable-kvm.
}

A device changes how fast a step runs, never what it gives, so it isn't part of the step's key. On a machine without KVM, the step runs anyway, and more slowly if its program falls back to emulation. kvm is the only device pekit gives; asking for another fails the step.

Keep state between runs #

Some tools do much less on a second run when they keep state: a compiler cache, Cargo's target directory, or a kernel's build tree. A step marked #[scratch] sees a directory of its own at /pekit-scratch that pekit keeps between its runs:

#[scratch]
#[hermetic]
fn kernel(source: Dir, config: File) -> File {
    # Runs make with its object directory under /pekit-scratch, then copies
    # the kernel image into the step's own directory.
}

The directory belongs to the step's own directory under pekit-out/ and to the platform it builds for. Changing the contents of the step's inputs keeps it, and it isn't part of the step's key. So a step has to give exactly what it would give with an empty directory. Use it only for state that saves time, never for anything that changes the result. pekit relies on this:

  • A strict build gives the step an empty directory every time.
  • When another build is running the same step at the same moment, this run gets an empty directory of its own rather than waiting.
  • A program found in the store leaves the directory as it is, as Programs found in a step that runs describes.

pekit clean --cache removes scratch directories, with the store.

Registering Toolchains

Pekit / Building

A workspace chooses the compilers and tools its steps use by registering toolchains in pekitconf. Register pinned toolchains to make a build independent of the machine it runs on, or define your own for a tool that no library provides.

Before you start #

  • A workspace that imports a library whose steps ask for a toolchain, such as the gcc library. See Libraries for how to make one available.

Register a library's toolchains #

  1. In workspace.gcsl, import the toolchains the library defines, and the Toolchain type:

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

    import Toolchain::* from a library brings in every toolchain it defines, and nothing else of it. To bring in one, name it, as import Toolchain::C gcc_x86_64 from "github.com/gcslib/gcc".

  2. List them in pekitconf.toolchains, in order of preference:

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

    Each entry names a toolchain's kind and its definition. For each step, pekit uses the first toolchain of the kind it asks for that runs on the machine and builds for the target platform.

  3. Build a target that uses the library:

    pekit build hello
    

Check the result #

The steps that ask for a C toolchain run with the one you registered. pekit build --platform aarch64 hello builds the same target with gcc_x86_64_to_aarch64, and file pekit-out/hello/link/hello reports an ARM aarch64 executable. A get that finds no toolchain fails with an error naming the kind and both platforms.

Keep the host's compiler #

Registering any toolchain replaces the default list, which holds only system_c, the host's own C compiler. To keep it as well, register it yourself. It's defined in the toolchain module:

import * from toolchain

pekitconf = {toolchains = [Toolchain::C system_c]}

A step that uses system_c runs the host's cc, so its result depends on what's installed. A strict build refuses it.

Define a toolchain of your own #

A toolchain can hold any tool, not only a compiler. This workspace keeps a tool called greet in tools/greeter/bin/, and defines a toolchain kind for it.

  1. In workspace.gcsl, declare the kind, with the layout of files and directories it provides:

    import * from toolchain
    
    enum Toolchain::Greeter<{root: Dir, greet: File}>
    

    A kind's layout is a record whose every field is a file or a directory, so that a toolchain can be passed to a step.

  2. Define a toolchain of that kind. Its host_platform and platform say where it runs and what it builds for; a field you leave out matches any platform:

    def Toolchain::Greeter workspace_greeter() {
        let tools = dir("tools/greeter")
        host_platform = {os = "linux"}
        platform = {}
        provides = {root = tools; greet = tools.file("bin/greet")}
    }
    

    A toolchain fetched from the internet would fetch and unpack its files here, as the gcc library's do.

  3. Register it, beside any others:

    pekitconf = {toolchains = [Toolchain::C system_c, Toolchain::Greeter workspace_greeter]}
    
  4. In a build file, ask for it in a step's parameter default:

    import toolchain
    import Toolchain from toolchain
    
    #[hermetic]
    fn greeting(name: String, greeter: {root: Dir, greet: File} = toolchain.get(Toolchain::Greeter)) -> File {
        let greeted = exec([greeter.greet.path, name, "greeting.txt"])
        = working_dir().file("greeting.txt")
    }
    
    def build hello() {
        = greeting("world")
    }
    

pekit build hello runs the tool in the step, and pekit-out/hello/greeting/greeting.txt holds Hello, world. Because the tool is an argument, changing it reruns every step that uses it.

Fetching Files

Pekit / Building

Fetching is the only part of a pekit build that uses the network. Every fetch is pinned: a file by its SHA-256 digest, and a git repository by a commit. So a fetch gives the same files on every machine and in every build, and pekit downloads each one only once.

Fetch a file #

  1. In a target, call fetch with the file's URL and no digest:

    def build zlib_source() {
        = fetch("https://zlib.net/fossils/zlib-1.3.1.tar.gz")
    }
    
  2. Build the target. pekit downloads the file, and fails with the digest it found, ready to paste in:

    error: `fetch` of `https://zlib.net/fossils/zlib-1.3.1.tar.gz` is not pinned: its sha256 is `9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23`
    

    Check the digest against one the file's publisher gives, if there is one. A digest pins whatever the server sent.

  3. Add the digest:

    def build zlib_source() {
        = fetch("https://zlib.net/fossils/zlib-1.3.1.tar.gz", sha256 = "9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23")
    }
    
  4. Build again. pekit downloads the file, checks it against the digest, and keeps it in the store.

Check the result #

pekit build zlib_source prints the file's path, under pekit-out/.fetch/<sha256>/. The next build finds the file in the store and doesn't use the network. So does any workspace on the machine that fetches a file with the same digest, from any URL.

A fetch whose download doesn't match its digest fails, and pekit keeps nothing of it.

Mark a tool #

pekit records what each package is built from, its corresponding source (see Recording Corresponding Source). Every fetch counts as source unless it's a tool the build runs, such as a compiler's release archive.

What a registered toolchain's definition fetches is a tool already, and so is everything fetched to make the toolchain, such as the source of a tool it compiles. Mark a tool fetched anywhere else with tool = true:

def libclang() -> Dir {
    let wheel = fetch(
        "https://files.pythonhosted.org/packages/1d/fc/716c1e62e512ef1c160e7984a73a5fc7df45166f2ff3f254e71c58076f7c/libclang-18.1.1-py2.py3-none-manylinux2010_x86_64.whl",
        sha256 = "c533091d8a3bbf7460a00cb6c1a71da93bffe148f172c7d03b1c31fbf8aa2a0b",
        tool = true,
    )
    = archive.unpack(wheel).dir("libclang-18.1.1.data/platlib/clang/native")
}

The file is fetched and kept the same either way. Mark only tools: an unmarked fetch is recorded as source, which costs some space if it wasn't, while a source marked as a tool goes missing from the record.

fetch_git takes tool = true too, for a git repository that is a tool's, such as the git crates of a tool the build compiles, and treats a repository fetched while a toolchain is made as a tool's already.

Unpack an archive #

archive.unpack unpacks a tar archive, compressed with gzip, xz, bzip2, or zstd or not compressed, or a zip archive such as a Python wheel. strip leaves off the first parts of each path, as tar --strip-components does:

import archive

def build zlib_source() {
    let tarball = fetch("https://zlib.net/fossils/zlib-1.3.1.tar.gz", sha256 = "9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23")
    = archive.unpack(tarball, strip = 1)
}

pekit unpacks archives itself, so it needs no tar, and keeps what it unpacked in the store, so each archive is unpacked only once. An entry whose path would leave the directory fails the unpacking, so an archive can never write outside it. Of each file's permissions, only whether it is executable is kept.

Fetch a git commit #

fetch_git gives the files of a git repository at one commit, without .git or submodules:

def build gcc_library() {
    = fetch_git("https://github.com/gcslib/gcc", "72dae8c75eabc34c63615380a9197e1021a39952")
}

The commit has to be named in full, by its 40 hexadecimal digits. A branch or a tag can move, so neither can pin a fetch. pekit keeps a clone of each repository in its cache, and fetches only commits it doesn't have.

pekit runs git without your or the system's git configuration, so a setting such as a line-ending conversion can't change the files a commit gives.

Fetch a private repository #

pekit fetches a private repository with the credentials your own git uses for its URL. Set up git so that git clone of the repository works, and fetch_git works too. For a GitHub repository, for example:

gh auth setup-git

pekit asks your git for credentials only; no other setting of yours reaches its git. It never stores or erases credentials, and it never prompts. Without credentials, the fetch fails:

error: `fetch_git` could not fetch `…` of `https://github.com/…`: fatal: could not read Username for 'https://github.com': terminal prompts disabled

A commit gives the same files whoever fetches it, so credentials don't change what pekit builds or what it keeps. A step never sees them.

Pass fetched files to a step #

A step has no network, so it can't fetch. A fetch in a step's code fails:

error: `fetch` runs outside hermetic steps: a step has no network; fetch in a parameter default, or in the caller, and pass the file in

Fetch in the code that calls the step, and pass what you fetched as an argument. A library usually fetches in a parameter default, which runs where the step is called:

import archive

#[hermetic]
fn header(source: Dir = archive.unpack(fetch("https://zlib.net/fossils/zlib-1.3.1.tar.gz", sha256 = "9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23"), strip = 1)) -> File {
    let copied = exec(["cp", source.file("zlib.h").path, "zlib.h"])
    = working_dir().file("zlib.h")
}

def build zlib_header() {
    = header()
}

archive.unpack works in a step too, on an archive the step was given.

Using Secrets

Pekit / Building

Some steps need a secret, such as a key to sign a package. pekit's keychain gives a step a secret without the secret entering the store, the build files, or a program's arguments. A workspace says where each secret is kept, and can keep different secrets for development and for releases.

Before you start #

  • The secret, in a file only you can read. This page uses a test key at keys/test.pem in the workspace. Keep a real key outside the workspace, and out of version control.

Give a step a secret #

  1. In workspace.gcsl, say where the secret is for the dev profile, the one builds use by default:

    import keychain
    
    pekitconf = {keychain = [
        {profile = "dev"; name = "signing"; file = "keys/test.pem"},
    ]}
    

    A relative file is relative to the workspace's root.

  2. In a build file, ask for the secret in a step's parameter default, so that the step is given it as an argument:

    import keychain
    
    #[hermetic]
    fn sign(message: File, key: Secret<File> = keychain.file("signing")) -> File {
        let signed = exec_secret(
            ["/bin/sh", "-c", "sha256sum \"$KEY\" {message.path} > signature.txt"],
            secrets = {KEY = key.reveal().path},
        )
        = working_dir().file("signature.txt")
    }
    
    def build signature() {
        = sign(file("message.txt"))
    }
    

    exec_secret gives the program the secret in an environment variable, never in its arguments, which any user of the machine can read. keychain.string(name) gives a secret string instead of a file.

  3. Build the target:

    pekit build signature
    

Check the result #

pekit-out/signature/sign/signature.txt names the key's path as /pekit-secrets/dev/signing: the step found the secret there, read-only. Every machine gives the step the same path, whatever the key's real location, so a program that records the path records the same one everywhere.

Keep release secrets apart #

Each keychain entry belongs to a profile. Add the release key under its own profile:

pekitconf = {keychain = [
    {profile = "dev"; name = "signing"; file = "keys/test.pem"},
    {profile = "release"; name = "signing"; file = "/run/secrets/signing.pem"},
]}

pekit build --profile release signature then uses the release key. pekit release always uses the release profile.

A secret with no entry for the profile comes from the environment, as in plain GCSL: $GCSL_SECRET_FILE_SIGNING names its file, and $GCSL_SECRET_SIGNING holds a secret string. Without either, the build fails at the call:

error: no secret `signing` for the profile `release`: configure it in the keychain, or set `$GCSL_SECRET_FILE_SIGNING`

How pekit protects secrets #

pekit handles a step given a secret differently from other steps:

  • Only that step sees it. No other step has the file, and pekit never copies a secret into the store. What the step makes with it, such as a signature, is kept like any output. - A step can't ask for a secret itself. A keychain call inside a step's code fails. Give the step its secrets as arguments instead. - Its key doesn't hold the secret. pekit identifies a secret by its profile, its name, and a hash of its contents keyed by a random key of this machine's. The hash tells nothing of the secret to anyone without the machine's key. Changing a secret's contents runs the steps given it again. - Its programs aren't recorded. From the moment a step is given a secret, pekit records none of the programs it runs. So a program's output that might reveal the secret never reaches the store.

The machine's key is in pekit's state directory: $PEKIT_STATE_DIR if you set it, otherwise pekit under $XDG_STATE_HOME, otherwise ~/.local/state/pekit. Two machines hash the same secret differently, so a step given a secret runs on each machine that builds it. A changed or lost key reuses nothing made with the old one. pekit clean never removes the state directory.

A step whose result holds a secret, such as one that gives a Secret<String>, is never recorded, and runs on every build.

Building for Another Platform

Pekit / Building

pekit can build a target for a platform other than the machine it runs on, such as 64-bit Arm Linux from an x86-64 laptop. The target's code doesn't change. Each library step asks for a toolchain that builds for the platform, and pekit picks a cross compiler.

Before you start #

  • A workspace that registers a toolchain building for the platform, as Registering Toolchains shows. The gcc library's gcc_x86_64_to_aarch64 runs on x86-64 Linux and builds for aarch64 Linux.

Build one target for another platform #

  1. Register a toolchain for each platform in workspace.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,
    ]}
    
  2. Build with --platform and the platform's name:

    pekit build --platform aarch64 hello
    

    A platform's name is its architecture and operating system, such as aarch64-linux. A name without an operating system, such as aarch64, keeps the machine's.

Check the result #

Check the program pekit printed:

file -L pekit-out/hello/link/hello

The output names the architecture:

pekit-out/hello/link/hello: ELF 64-bit LSB pie executable, ARM aarch64, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux-aarch64.so.1, for GNU/Linux 3.7.0, not stripped

Building again without --platform builds for the machine, with its own steps. Each platform's steps are keyed apart, so switching back and forth reuses both from the store.

Build for several platforms at once #

A target can build the same thing for several platforms by setting the platform context with with:

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

pekit build all builds both, as one build. Both programs come from a step of the gcc library's link, so the second is under link.2:

built /all: 0 steps run, 4 found in the store
  pekit-out/all/link/hello
  pekit-out/all/link.2/hello

Here every step was found in the store, from the two earlier builds.

Build tools that run during the build #

A program the build makes and then runs, such as a code generator, has to run on the machine the steps run on, whatever the build is for. Build it for ^host_platform:

let generator = build msggen() with { platform = ^host_platform }

Link such a tool statically, as with the gcc library's flags = ["-static"]. A step that runs it then needs nothing of the toolchain that built it.

Setting a Context for the Whole Workspace

Pekit / Building

A library can declare a GCSL context to let the workspace that imports it change how it builds, such as extra compiler flags. Set the context once in pekitconf.contexts, and pekit binds it around every target it builds. You don't need a with block in each build file.

Before you start #

  • A workspace that imports a library declaring a context. This example uses a library github.com/example/greeting that declares one, and reads it in a step:

    context greeting: String = "Hello"
    
    #[hermetic]
    def greet(name: String) -> File {
        let greeted = exec(["sh", "-c", "echo '{^greeting}, {name}' > greeting.txt"])
        = working_dir().file("greeting.txt")
    }
    

    See Libraries for how to make a library available.

Set the context #

  1. In workspace.gcsl, add the context to pekitconf.contexts, by its name:

    pekitconf = {
        contexts = {greeting = "Good morning"}
    }
    

    workspace.gcsl doesn't need to import the library, as long as some file of the workspace does. Each value can be any GCSL expression that workspace.gcsl can evaluate, such as a call of a function the workspace defines.

  2. Build a target that uses the library:

    pekit build hello
    

Check the result #

The step that reads ^greeting writes Good morning, world. A step that doesn't read the context keeps its key, so pekit finds it in the store rather than running it again. A step that reads it runs again whenever the value changes.

pekit checks each field before it builds anything:

  • A name that no file of the workspace or its libraries declares as a context fails the build, naming the field.
  • A value that isn't of the context's type fails with GCSL's type error, as a with block's value would.
  • pekit sets some contexts itself, such as host_platform and toolchains, and contexts can't set those. Use their own options and fields instead. Root Contexts lists them.

Override it for one target #

A with block in a build file binds the context for what it covers, as it would anywhere in GCSL. It overrides the workspace's value:

import "github.com/example/greeting"

def build hello() {
    = greeting.greet("world")
}

def build formal() {
    = greeting.greet("world") with { greeting = "Good day" }
}

pekit build formal writes Good day, world. pekit build hello still writes Good morning, world.

Evaluation #

Each value is evaluated as part of workspace.gcsl, before any target. That evaluation can't read the target's own contexts, such as ^platform. A value that has to depend on them belongs in a with block in the build files instead.

Checking That a Build Is Reproducible

Pekit / Building

A reproducible step gives the same outputs, byte for byte, every time it runs with the same inputs. pekit relies on this when it reuses results, and a release relies on it so that anyone can rebuild what you published and get the same bytes. --check-reproducible finds the steps that don't.

Check a build #

  1. Build with the check:

    pekit build --check-reproducible stamped
    

    pekit builds the targets, then runs every step again, reusing nothing from the store, and compares what each step gave the second time with what it gave the first.

  2. Read the report. A step that gave other outputs fails the command, named with each file that differs:

    error: a step is not reproducible: run again with the same inputs, it gave other outputs
      .steps/stamp/7367551baf538abf
        /pekit-out/.steps/stamp/7367551baf538abf/stamp.txt
    

    The first line under the error is the step's directory under pekit-out/, and the lines under it are its files that differed.

  3. Fix the step, and check again.

Check the result #

When every step is reproducible, the command reports the build as usual, and exits with status 0.

What the check compares #

pekit compares only steps given the same inputs both times. A step whose input differed because an earlier step wasn't reproducible isn't reported too, so each report points at the step where the difference started.

The second run doesn't change the store: each step's first record stays. --check-reproducible works with pekit build, pekit test, and pekit package. It doesn't work with pekit run or pekit publish, which change things outside the build and can't be done twice. Check what they build with pekit build --check-reproducible instead.

Common causes #

Most steps that aren't reproducible record something of the moment they ran:

  • Times. A timestamp written into an output, or an archive that records each file's modification time. Many tools honor SOURCE_DATE_EPOCH; set it in the step's exec. The gcc library's archive uses ar rcsD, which records no times.
  • Order. A list of files in the order a directory returned them. Sort it.
  • Randomness. A random identifier, or a hash table iterated in an order that changes between runs.
  • Parallel tools. A tool that writes its output in the order its own threads finish.

A step that uses the host's tools can also differ between machines, which this check doesn't see, because it runs both times on one machine. Build with --strict to keep the host out. See Hermetic and Strict Builds.

Profiling a Build

Pekit / Building

A slow build spends its time in one of two places: running steps, or evaluating GCSL code. pekit can record either. A trace shows each step and program on a timeline, and a GCSL profile shows which functions took the time.

See the steps on a timeline #

  1. Build with --trace and a file to write:

    pekit build --trace build-trace.json app
    
  2. Open build-trace.json in Perfetto, or in chrome://tracing in a Chromium-based browser.

The trace has these rows:

  • steps. One span for each attempt of each step, named by its function and identity, such as compile/9927fb8abbee4a05. A step found in the store is a mark rather than a span.
  • worker 1, worker 2, and so on. The work each of pekit's workers did. Each program a step ran is a span, such as exec cc. So is pekit's own work for a step: stage places the step's inputs in its sandbox before it runs, and keep stores the files of its result.
  • evaluation. One span for each time a target's or a step's code ran.

A command that builds more than once writes one trace of every build, on one timeline. pekit release builds, checks its sources and publishes, and --check-reproducible builds twice. pekit writes the file again as each build ends, so a command that stops part way still leaves the trace of the builds before it.

The trace names programs, but never shows their arguments, so it holds no secrets.

Look for long spans on the steps row, and for gaps where few workers are busy. A gap usually means that one step holds up the rest, and that splitting it would let more run at once.

See where the code spends its time #

When even a build where nothing changed is slow, the time is in evaluating code, not in running steps.

  1. Build with --gcsl-profile and a file to write:

    pekit build --gcsl-profile profile.txt app
    
  2. Read profile.txt. It starts by counting how many times the targets' code and the steps' code ran, and how long that took. A table follows, with a row for each function and built-in that ran, the most expensive first:

        own (ms)   total (ms)      calls      found  kind     function
           0.052        0.055          1          0  fn       link  build.gcsl:13
           0.037        0.028          3          0  fn       exec  <stdlib>/prelude.gcsl:57
           0.024        0.027          1          0  fn       adder  build.gcsl:28
    

Each row gives the time spent in the function's own body, its total time including the calls it made, and how many times it was called. For a memoized function, found is how many of those calls found an earlier result.

A target's code stops each time it waits for a step or an effect, and carries on when the result is ready. So a target that waits a hundred times runs about a hundred times, but never runs the same code twice. A function called thousands of times, once on each run of a target, is usually worth memoizing with ->>.

Timing every call slows the build, so a profiled build takes longer than an ordinary one. Compare the rows with each other, not with a build you timed without the profile.

Rebuild everything to measure it #

A build that finds its steps in the store measures nothing of them. To time every step, add --rebuild, which runs every step and every program again:

pekit build --rebuild --trace build-trace.json app

Managing the Store

Pekit / Building

pekit's store holds the result of every step it ran, shared by every workspace on the machine. pekit keeps it to a size limit by itself, so most machines need no management. This page covers the settings for when the defaults don't suit a machine.

Set the size limit #

The store can grow to 100 GiB unless you set PEKIT_CACHE_LIMIT. To set a limit of 20 GiB, set the variable in your shell's startup file:

export PEKIT_CACHE_LIMIT=20GiB

To set it for every build on the machine, whatever their environment, put cache_limit = 20GiB in machine.conf in pekit's configuration directory instead (see Sharing the Machine). The variable overrides the file.

A limit is a number of bytes, with a unit or none: KiB, MiB, GiB, and TiB count in powers of 1024, and KB, MB, GB, and TB in powers of 1000. 0 means no limit.

When a build ends with the store over its limit, pekit removes what is cheapest to make again until the store is under nine tenths of the limit. Reuse and the Store explains the order. An eviction waits until no other pekit process is using the store, so a build that runs while another is running leaves it to a later build. If the store is over its limit then, pekit warns that nothing was evicted.

Keep room free on the disk #

The store's limit counts the store, not what shares its disk: the directories builds write outputs and scratch files to, and other programs. To keep room free whatever fills the disk, set keep_free in machine.conf, or PEKIT_KEEP_FREE:

keep_free = 30GiB

Once less is free during a build, pekit starts no new step. Once none of its steps is running, it evicts what the build hasn't used, if no other pekit is using the store, and then goes on. It warns of what it evicted, or why it couldn't. As the build ends, it evicts again if less is free.

Whether or not keep_free is set, a step that fails because the disk is full runs once more, after pekit makes room for it. If it fails again, its error says how much is free.

See and evict the store #

pekit store stats shows where the store is, how large it was when it was last measured, its limit, when it was last evicted, and whether another pekit process is using it:

store: /home/me/.cache/pekit/store
size: 402.3 GiB, by its ledger, last walked 3 hours ago
limit: 400.0 GiB
last evicted: 2 days ago
in use: by another pekit

A build evicts only when it ends with no other pekit process using the store, so on a machine where builds overlap, the store can grow past its limit, and each build warns of it. pekit store evict evicts it now instead. It waits for the builds that are using the store to end, and a build that starts meanwhile waits for the eviction rather than holding it off:

pekit store evict

--limit evicts to another size than the store's limit, such as --limit 300GiB to make room ahead of a large build.

A build's outputs in pekit-out/.steps/, .unpack/, .git/, and .fetch/ are links to the store's files, so evicting a step from the store leaves its outputs there holding the same space. pekit store evict, and a build that evicts with the store to itself, remove those outputs too. No build can use them, and a build exposes what it needs again. The files your targets give are never removed. pekit store stats shows how much such outputs held when an eviction last looked:

held by outputs of evicted steps: 33.1 GiB in 2480 exposures, found 3 hours ago

Move the store #

The store is in pekit's cache directory. To keep it on another disk, set PEKIT_CACHE_DIR:

export PEKIT_CACHE_DIR=/srv/cache/pekit

Without it, the cache directory is pekit under $XDG_CACHE_HOME, or ~/.cache/pekit if that isn't set either. Moving the variable doesn't move the store: the next build starts with an empty store in the new place. Move the directory yourself to keep what's in it.

The cache directory also holds the git repositories pekit fetched from, and the directories steps are staged in. Keep it on a file system that supports hard links, as every local Linux file system does.

Keep each workspace's pekit-out/ on the same file system as the store. pekit links outputs to the store's files, and it can't link across file systems, so it copies every output instead, and copies it again on every build. A large build then writes far more to disk than it needs to. pekit warns when this happens. To fix it, make pekit-out a symbolic link to a directory on the store's file system.

Clear what builds made #

pekit clean removes the workspace's pekit-out/:

pekit clean

The store is untouched, so the next build finds its steps there and puts pekit-out/ back without running them.

pekit clean --cache also removes the store, the scratch directories of steps marked #[scratch], and the directories steps are staged in. The next build runs every step again:

pekit clean --cache

It removes nothing while another pekit process has the store open, since that process would lose the files it is using. Run it once no other build is running. The store's lock file stays, so a pekit that was waiting for the store finds it empty.

Neither removes pekit's state directory, which holds the key that identifies this machine's secrets. See Using Secrets.

To run every step again without losing the store, build with --rebuild instead. It runs every step and every program, and records each as it goes.

Check the result #

After pekit clean --cache, pekit build reports every step as run and none found in the store.

Don't change files in the store #

pekit hard-links the store's files into the directories it stages steps in, and into pekit-out/.steps/ when it writes an intermediate file there. A hard link is the same file, not a copy. Changing the permissions or contents of one changes the store's file too, and pekit would then give the changed file to later steps. Leave these files read-only.

The files each target gives are the exception: pekit copies them, so you can change them freely.

Verify the store #

If a store file might have been changed, for example by a chmod -R over pekit-out/, or after a disk fault, verify the store:

pekit store verify

It reads every file the store keeps and hashes it again, and lists each whose contents aren't those its name says, and each that isn't read-only. Builds can run meanwhile. On a large store this takes minutes, reading on up to eight threads, and it reports how far it is every few seconds.

To repair what it finds:

pekit store verify --repair

It makes each file that isn't read-only so again, and removes each whose contents are wrong, so that the next build fetches or builds again what needed it. Like pekit store evict, it waits for the builds that are using the store to end, and builds that start meanwhile wait for it.

Sharing a Remote Cache

Pekit / Building

pekit's store holds the steps one machine ran. A remote cache shares them between machines, so a developer's build finds what CI already built. pekit speaks Bazel's Remote Execution API (REAPI), so any server of it works, such as bazel-remote, Buildbarn, BuildBuddy, or NativeLink.

Read from a cache #

Name the cache with --remote-cache, or set PEKIT_REMOTE_CACHE in your shell's startup file:

export PEKIT_REMOTE_CACHE=grpcs://cache.example.org:443

A URL is grpc://HOST:PORT, or grpcs://HOST:PORT for TLS with the system's certificate authorities. A Buildbarn server also needs its instance name, given with --remote-instance or PEKIT_REMOTE_INSTANCE.

A step that isn't in the store is then looked for in the cache before it runs. One found there is downloaded with every file it gave, each checked against its digest, and put into the store. The build counts it as found in the store, and says how many came from the cache:

built app/hello: 0 steps run, 1 found in the store (1 from the remote cache)

Steps are looked for only where the store's results are reused. So --rebuild and the second build of --check-reproducible never use the cache.

Write to a cache #

A machine writes to the cache with --remote-upload, or with PEKIT_REMOTE_UPLOAD=1. Each step it records is then sent with every file it gave, but only the files the cache doesn't already have. The build waits for its uploads before it ends.

Let CI write and developers only read. A step's result is keyed by what the step is and everything it was given. A cache trusts the machines that write to it to give the results those inputs give. CI's machines are the ones to trust.

Give credentials #

Send credentials as headers, with --remote-header, which can be given more than once, or with PEKIT_REMOTE_HEADERS, one header to a line:

export PEKIT_REMOTE_HEADERS='Authorization: Bearer TOKEN'

Keep credentials in the environment or on the command line, never in the workspace's files, which everyone who clones the workspace reads.

Which machines share steps #

A step's receipt names the platform it ran on. A build that isn't strict also names the host's packages, since its steps use the host's tools. So those steps are shared only between machines with the same packages.

A strict build's steps use pinned toolchains and none of the host's tools. They're shared between every machine of the platform, which makes strict builds the ones a team gains most from sharing. See Hermetic and Strict Builds.

When the cache is down #

If a call to the cache fails, the build stops asking it and runs its steps itself. It warns once, at the end:

warning: the remote cache failed a call: Unavailable: ...; the build went on without the remote cache

A cache that gives a file that doesn't match its digest, or has lost one, isn't trusted for that step. The step runs, and the build warns in the same way.

pekit(1) documents each option and environment variable.

Building a Large Workspace

Pekit / Building

A workspace of hundreds of targets, such as a catalog of packages, can run for hours. It might run unattended under a service, often beside other builds. Four things keep such builds within the machine's memory and disk, and make them easy to follow.

Keep pekit's own memory in bounds #

pekit itself uses memory to evaluate a target's code, separately from the programs that steps run. The code of a large target can need a few hundred megabytes. pekit evaluates only a few targets at once, so a build of hundreds needs the memory of a few. By default it evaluates as many as --jobs, and at least 8.

On a machine that also runs other builds, set a lower number for every build in machine.conf, in pekit's configuration directory (~/.config/pekit):

evaluating = 4

A lower number costs little time, because pekit evaluates code on one thread whatever the number. --evaluating sets it for one build, and PEKIT_EVALUATING for a shell. A run with output going to a log shows how much memory pekit uses in each status line (see below).

Keep outputs on the store's file system #

pekit links each output in pekit-out/ to the file the store keeps. It can't link across file systems, so if pekit-out/ is on another file system than the store, pekit copies every output, on every build, and warns:

warning: `/srv/pkgs/pekit-out` is on another file system than the store, ...

With a store on another disk, make pekit-out a symbolic link to a directory on that disk:

mkdir -p /srv/cache/pekit-outputs/pkgs
ln -s /srv/cache/pekit-outputs/pkgs pekit-out

Set the store's limit for every build #

The store's limit holds for builds started from a service as much as from a shell only if it's set in machine.conf, not in one shell's environment:

cache_limit = 400GiB
keep_free = 30GiB

keep_free keeps that much free on the store's disk during every build, whatever else fills it, such as outputs or scratch files (see Managing the Store).

A build evicts only as it ends with no other pekit using the store, so while builds overlap, the store can grow past its limit, and each build warns that it did. Between runs, or before a large one, check it and evict it:

pekit store stats
pekit store evict

pekit store evict waits for the builds using the store to end. Builds that start while it waits wait for it in turn, so it is never kept from the store for long. Managing the Store covers the rest.

Follow a build from its log #

With standard error going to a file or a service's journal, pekit writes nothing for the first minute. After that it writes a status line each minute, and a line as each target ends:

[00:41:00] 212 of 1212 targets ended, 2 failed; 3104 steps run, 40211 found; running 6: compile/9927fb8abbee4a05, link/3f1c0a9e2b7d4c68, gate/71ab0c4e9d2f6a13 and 3 more; pekit uses 3.1 GiB
[00:41:12] ended dev.peios.authd/dev.peios.authd
[00:41:30] FAILED org.gnu.bash/org.gnu.bash-doc

PEKIT_PROGRESS_SECS changes the minute, or turns the lines off with 0. For a full timeline of a run, give it --trace: the file is written again as each of the command's builds ends, so a run that is stopped still leaves the builds before it.

A target that fails doesn't stop the others. pekit publish --strict publishes every recipe whose packages all packed, holds back the recipes that had a failure, and exits with an error. So after a long run, look for the FAILED lines, fix those recipes, and run again: the steps that already succeeded are found in the store.

Libraries

Pekit / Libraries

A library is GCSL code kept apart from any workspace, such as the gcc library, which compiles and links C. A build file imports a library by a path in quotes, and calls its functions, which are usually steps:

import "github.com/gcslib/gcc"

def build hello() {
    = gcc.link([gcc.compile(file("hello.c"))], output = "hello")
}

A library sees only its own files, the standard library, and the libraries it imports, never anything of the workspace that uses it. So it means the same in every workspace. GCSL's Workspaces page describes imports in full.

Where pekit finds a library #

pekit looks for a library's directory, by its import path, in two places, and uses the first it finds:

  1. Each directory of $GCSL_LIBRARY_PATH, in order.
  2. .gcsl/libraries/ at the workspace's root, where pekit lock puts the libraries it pins.

$GCSL_LIBRARY_PATH is for working on a library: point it at your checkout, and every workspace on your machine builds with your copy. For everything else, pin libraries with pekit lock, so that every checkout builds with the same ones. See Pinning Libraries.

Steps from a library are shared #

pekit places every library at /w/.gcsl/libraries/<path> in the layout steps see, wherever it found the library. A step a library makes is keyed by the library's path and contents, never by where it was on disk. So a library's steps give the same results from the store whether the library came from $GCSL_LIBRARY_PATH or from pekit lock, and in every workspace that imports the same version.

Libraries with files of their own #

A library can keep other files beside its .gcsl files: sources to build, templates, or tools to run. A relative path in a library's code names its own files, such as file("templates/greeting.txt"), wherever the library is used. The Peios SDK's library builds libpeios this way, from the sources in its own repository.

Because every library is at the same path in every workspace, a step that builds from a library's files is the same step everywhere, and its results are shared through the store.

What the lock tells a build #

A build's code can read what pekit.lock pins, through the GCSL standard library's libraries module: each pinned library's path, repository, directory, and commit. A library that takes something the same repository also gives another way can check that the two agree. The gcslib rust library uses it to check Cargo.lock. A build fails if Cargo.lock takes a git crate from a repository at another commit than the one pekit.lock pins a library of that repository at.

The gcslib libraries #

gcslib is a set of libraries for building common kinds of software with pekit:

LibraryBuilds
github.com/gcslib/gccC programs and static libraries, with Bootlin's pinned compilers. See Building C.
github.com/gcslib/buildenvSoftware with its own build system, such as ./configure and make, in a pinned environment. See Building Upstream Software.
github.com/gcslib/pythonPython programs, bundled into one archive. See Building Python.
github.com/gcslib/rustRust programs, one crate at a time or with Cargo. See Building Rust.
github.com/gcslib/goGo programs, one package at a time. See Building Go.
github.com/gcslib/clangA pinned libclang, for tools such as bindgen.
github.com/gcslib/modsigLinux kernel modules signed with a key of the keychain. See Signing Kernel Modules.
github.com/gcslib/pipsigFirmware, and other files that aren't ELF, signed for the Peios kernel with a key of the keychain. See Signing Firmware.
github.com/gcslib/ppkPeios packages. See Packaging.
github.com/gcslib/peisoBootable Peios images. See Building and Booting an Image.
github.com/gcslib/qemuPrograms and tests that boot an image in QEMU.

The first eight are in repositories of their own, which pekit lock finds by their paths. ppk, peiso and qemu are in pekit's own repository, under gcslib/. To pin them, give their paths a source in pekit.lock, as Pinning Libraries shows.

Pinning Libraries

Pekit / Libraries

pekit lock pins each library a workspace imports, and each library those import, at a commit of the git repository it comes from. It records the pins in pekit.lock, at the workspace's root. Commit that file, and every checkout builds with exactly the same libraries.

Before you start #

  • git, which pekit runs to fetch libraries.
  • A workspace whose build files import at least one library.

Pin the workspace's libraries #

  1. From anywhere in the workspace, run:

    pekit lock
    

    pekit finds every library the workspace imports, fetches each from its repository, and pins it at the commit the repository's HEAD names:

    pinned github.com/gcslib/gcc at 72dae8c75eabc34c63615380a9197e1021a39952
    

    It exports each library into .gcsl/libraries/<path>/, and records its commit and tree digest in .gcsl/pekit-exports.json, outside the exported tree.

  2. Commit pekit.lock. Don't commit .gcsl/: any command that builds puts back a pinned library that's missing, from the commit it's pinned at. It also refreshes an untouched recorded export when the lock moves.

Check the result #

pekit.lock lists each library under libraries, with its repository and commit. Run pekit build --strict on a target: a strict build fails unless every library it imports is pinned, so a successful one confirms the pins are complete.

Update the pins #

pekit lock pins only libraries that aren't pinned yet. To move every library to what its repository holds now, run:

pekit lock --update

pekit prints a line for each library it pins again. A library that nothing imports any more is dropped from the lock, and its directory with it:

dropped example.org/greeting, no longer imported

If the dropped library's directory is inside a library that's still pinned, the directory belongs to that library and stays.

Pin a library inside another #

A library's directory can be inside another library's, as github.com/peios/peios-sdk/tools is inside github.com/peios/peios-sdk. The outer library's export holds the inner one's directory, so pekit pins both at one commit of one repository. It refuses to pin them at two commits, because each export would overwrite the other's files.

The usual way to meet this is to import the inner library after the outer one is pinned and its repository has moved on. pekit lock would pin the inner library at the repository's new commit, so it refuses, naming both:

error: `github.com/peios/peios-sdk/tools`'s directory is in `github.com/peios/peios-sdk`'s, so both must be pinned at one commit, and are not:
  `github.com/peios/peios-sdk` is the root of `https://github.com/peios/peios-sdk` at 3f1c0a9e2b7d45c8a6e0f9b18d2c47e5a1b3c6d8
  `github.com/peios/peios-sdk/tools` is `tools` of `https://github.com/peios/peios-sdk` at 9b2e4d71c0a85f36e1d7c9a2b4f08e6d3c5a17b9
pin both at one commit: give their sources in `pekit.lock` one repository and revision, and run `pekit lock --update`

To pin both at one commit, run pekit lock --update. When both libraries come from one source, as they do by default, it pins them at the same commit. If you gave them sources of their own, make the sources name one repository and revision first.

pekit.lock is unchanged by the refusal, but the inner library might already be exported at the new commit. Until you run pekit lock --update, builds then warn that the outer library differs from its pin.

Every command that builds refuses a pekit.lock that pins two such libraries at two commits in the same way, before it exports either.

When a library differs from its pin #

After pulling a changed pekit.lock, the next command that builds refreshes an older export automatically, before checking strictness. This applies to non-strict builds too. pekit replaces it only if its tree still matches the digest it recorded when exporting it.

If a library under .gcsl/libraries/ differs from the commit it's pinned at, and you edited it there or it has no export record from pekit, it is left alone. A non-strict build warns, and a strict build fails:

warning: `.gcsl/libraries/github.com/gcslib/gcc` differs from the commit `pekit.lock` pins, 72dae8c75eabc34c63615380a9197e1021a39952; remove `.gcsl/libraries/github.com/gcslib/gcc` and pekit will restore it from the pin

Preserve any edits you need, then remove the named library directory. The next command that builds exports the pinned commit and records it. Exports made by an older pekit have no record. One that still matches its pin is recorded the next time pekit runs, and refreshes like any other from then on. One that already differs needs this one-time recovery.

To work on a library, use $GCSL_LIBRARY_PATH instead of editing the exported copy. See Writing a Library.

Take libraries from elsewhere #

By default, a library's repository follows the convention of Go's modules: the library github.com/gcslib/gcc is the repository https://github.com/gcslib/gcc, at its HEAD, with the library at the repository's root. pekit lock records this as a source in pekit.lock.

To take libraries from another repository, a mirror, a branch, or a directory inside a repository, edit the sources. Each source has a prefix of import paths, a git repository, the directory in it that holds the prefix's libraries, and the branch, tag, or commit to follow:

{
  "sources": [
    {"prefix": "github.com/gcslib/ppk", "git": "<pekit-repository>", "dir": "gcslib/github.com/gcslib/ppk", "rev": "main"}
  ]
}

Replace pekit-repository with the URL or path of pekit's repository, which holds the ppk library under gcslib/.

A library uses the first source whose prefix its path is under. Run pekit lock --update after changing a source, so that the libraries it covers are pinned from it. git can be any repository git can fetch, including a path on your machine.

Build offline #

pekit keeps a bare clone of each repository in its cache directory, and fetches only when it needs a commit it doesn't have. A workspace whose libraries are pinned and already fetched builds without the network.

Build strictly from the pins #

A strict build, --strict, fails unless its libraries are exactly those pekit.lock pins. That means:

  • Every library it imports is pinned.
  • No library differs from its pin.
  • $GCSL_LIBRARY_PATH is unset.
error: a strict build uses the libraries `pekit.lock` pins, and only them:
  the workspace has no `pekit.lock`: run `pekit lock`
  `$GCSL_LIBRARY_PATH` is set, which would find libraries elsewhere: unset it

pekit.lock(5) describes every field of pekit.lock.

Writing a Library

Pekit / Libraries

A library packages steps for other workspaces to use. It's a directory of GCSL files in a git repository, named by an import path. This page writes a small library that greets someone using a template file of its own, tries it from a workspace, and pins it there.

Before you start #

  • git.
  • A workspace to try the library from. This page uses one at uselib, with an empty workspace.gcsl.

Write the library #

  1. Make a directory for the library, and a git repository in it. This page names the library example.org/greeting, and keeps its checkout at libsrc/example.org/greeting:

    mkdir -p libsrc/example.org/greeting/templates
    cd libsrc/example.org/greeting
    git init -b main
    

    A library published at https://example.org/greeting is found there by default, as the Go modules convention has it.

  2. Save the template as templates/greeting.txt:

    Hello, NAME, from a library
    
  3. Save the library's code as greeting.gcsl:

    # Greets someone with the library's own template.
    
    #[track_caller]
    #[hermetic]
    def greet(name: String, template: File = file("templates/greeting.txt")) -> File {
        let made = exec(["/bin/sh", "-c", "sed 's/NAME/{name}/' {template.path} > greeting.txt"])
        = working_dir().file("greeting.txt")
    }
    

    A library's public names are its def functions, declared types, and fields; fn and let stay private to their file. #[track_caller] reports an error in the step at the caller's line, where the reader can act on it. The relative path in the default names the library's own file, wherever the library is used.

  4. Commit it:

    git add -A
    git commit -m "Add the greeting library"
    

Try it from a workspace #

  1. In uselib/build.gcsl, import the library and call it:

    import "example.org/greeting"
    
    def build hello() {
        = greeting.greet("world")
    }
    
  2. Build with $GCSL_LIBRARY_PATH naming the directory that holds example.org/:

    GCSL_LIBRARY_PATH=/path/to/libsrc pekit build hello
    

    pekit finds the library in your checkout. Edit it and build again, and pekit uses your edit.

Pin it #

  1. Tell pekit lock where the library's repository is. In uselib/pekit.lock, add a source:

    {"sources": [{"prefix": "example.org/greeting", "git": "/path/to/libsrc/example.org/greeting", "dir": "", "rev": "main"}]}
    

    A library published at the URL its path names needs no source.

  2. Pin it, without $GCSL_LIBRARY_PATH:

    pekit lock
    pekit build hello
    

Check the result #

pekit lock prints the commit it pinned:

pinned example.org/greeting at 1b4e27f7c836186a4bfab3f74521ef642b953632

The build after it reports the step found in the store, 0 steps run, 1 found in the store. The step is keyed by the library's path and contents, not by where pekit found it, so the result from your checkout is reused. pekit-out/hello/greet/greeting.txt holds Hello, world, from a library.

Ask for a tool #

A library that runs a compiler or another tool should ask for it as a toolchain, so that each workspace chooses which one. Use an existing kind, such as Toolchain::C, or declare a kind in the library, and resolve it in a step's parameter default. Registering Toolchains shows both sides.

Keep libraries apart from the workspace #

A library sees nothing of the workspace that imports it: not its declarations, and not its files. Take anything from the workspace as an argument. A library can import other libraries, which pekit lock pins along with it.

Writing and Running Tests

Pekit / Testing, Running, and Querying

A test is a definition made with test, beside your builds. pekit runs each test's body as a step, so a test that passed doesn't run again until something it tests changes. A failing test is a result, not a broken build: the other tests still run.

Before you start #

  • A workspace with a target to test. This page uses a C program, app, that prints a greeting, and a test program, greeting_test, built from the same library.

Write tests #

  1. In a build file, declare a test for each check. A test passes if its body succeeds, and fails if its body fails: an assert that doesn't hold, a program that exits with an error, or any other failure.

    def test greeting(prog: File = build greeting_test()) {
        let ran = exec([prog.path])
    }
    
    def test output(prog: File = build app(), expected: File = file("test/expected_output.txt")) {
        let ran = exec([prog.path])
        assert ran.stdout == expected.read()
    }
    

    Give a test what it tests through its parameters' defaults, as these do. pekit builds the defaults first, outside the test, and gives the test's step what they built. The step holds nothing else, so a test can't read a file it wasn't given.

  2. Run every test below the current directory:

    pekit test
    

Check the result #

pekit test reports each test as it ended, then a count:

passed           example/greeting
passed           example/output
2 passed, 0 failed

It exits with status 0 if every test passed, and 1 if any failed.

Read a failure #

A failing test shows its failure's message under its name:

passed (cached)  example/greeting
FAILED           example/output
    assertion failed: `ran.stdout == expected.read()`
1 passed, 1 failed

Each test is reported with one of four results:

ResultMeans
passedThe test ran and passed.
passed (cached)The test passed before with the same inputs, so it didn't run.
flakyThe test failed, then passed when run again.
FAILEDThe test failed, after any retries. The message follows.

A test whose program fails shows the program's exit status, then what it wrote to standard output and standard error, in full:

FAILED           example/greeting
    `/pekit-out/.steps/link/…/greeting_test` exited with status 1
    its standard error: greeting() returned "Hi", expected "Hello"

A test whose program fails to build fails too, with the build's error.

Run some tests #

Name tests to run only those, or select them with a glob, as for builds:

pekit test output 'lib/**'

Naming Targets describes names and globs.

When tests run again #

A test that passed isn't run again until something it was given changes. Change main.c, and output runs again with the rebuilt program, while greeting, which never saw main.c, is passed (cached). A change that rebuilds a program to the same bytes, such as a new comment, runs no test at all.

A test that failed runs again every time, in case it was flaky.

Retry flaky tests #

#[retry(3)] runs a failing test up to three more times, each time from the start in a fresh sandbox. A test that passes only on a retry is reported flaky:

#[retry(3)]
def test reconnects(prog: File = build client()) {
    let ran = exec([prog.path, "--self-test"])
}

#[timeout(5m)] fails a test that runs for longer than five minutes, all its attempts together.

Tests that can't be sandboxed #

A test that needs something a step can't have, such as the network, can say #[hermetic(false)]. It runs every time, outside a sandbox, and its result is never reused:

#[hermetic(false)]
def test mirror_answers() {
    let ran = exec(["curl", "--fail", "https://example.com/"])
}

Prefer a hermetic test wherever you can, so that a test that passed costs nothing on the next run.

Running Scripts and Programs

Pekit / Testing, Running, and Querying

Some tasks change things outside the build: deploying a site, booting an image in a virtual machine, or copying files to a device. Write each as a script, a definition made with script, beside your builds, and run it with pekit run. A script can build what it needs first, exactly as pekit build would.

Write and run a script #

  1. In a build file, declare the script:

    def script deploy() {
        let site = build site()
        let copied = exec(["rsync", "-a", site.path, "web:/srv/site"], interactive = true)
    }
    

    A script's commands run one after another, in the order the script gives them, with your terminal, environment, and network. They aren't shut away as a step is. Pass interactive = true to exec to give a program the terminal; otherwise pekit captures its output.

  2. Run it:

    pekit run deploy
    

Check the result #

The script's programs run, and pekit run exits with status 0 if the script succeeded. Whatever a script builds is built as pekit build builds it. The steps of build site() are those of pekit build site, and are found in the store if they've been built before.

Give a script arguments #

The words after a script's name are its ^script_session.args:

def script greet() {
    let said = exec(["echo", "hello {^script_session.args}"], interactive = true)
}

pekit run greet there prints hello ["there"]. pekit's own options, such as --jobs, come before the name. Everything after the name belongs to the script.

Run a program you built #

pekit run also runs the program a build gives, when the build gives one executable file:

pekit run app --verbose input.txt

pekit builds app, then runs the file it gives with the words after the name, in the directory you ran pekit from. It exits with the program's status. A build that gives anything else, such as a record of files, can't be run.

Name what to run #

Name a script or a build as you name any target: deploy, or site/deploy for the one in site. See Naming Targets.

A build and a script of one name in one directory are an error for every command, since pekit run couldn't tell which you meant. If two directories each have one, name the one you mean by its directory.

Scripts and builds stay apart #

A script can run another script, as script greet(). A build, a test, or a package can't call a script, through any number of functions. The check fails before anything runs:

error: context `script_session` has no value in this definition

So building never deploys or boots anything. Only pekit run runs a script.

Paths in scripts #

A script sees the workspace at /w and the build's outputs at /pekit-out, as steps do, so the paths a build gives work in the script's commands. The rest of the system is where it always is. pekit gives the script that view with bubblewrap, so a program that would gain privileges, such as sudo, can't do so from a script.

Before a script or a program runs, pekit writes every output of the build to pekit-out/, since the program might read any of them.

Querying What Targets Reach

Pekit / Testing, Running, and Querying

pekit query evaluates targets as a build does, but runs no step. It answers from the code alone, so it's quick, and it doesn't fill the store. Use it to see what a target depends on, or to find the targets a change affects.

List what a target reaches #

Run pekit query deps with the target's name:

pekit query deps app

pekit lists each step the target reaches, with the workspace files each reads, and the steps whose results each is given:

example/app
  code: example/build.gcsl
  step .steps/compile/57b56f08130b0576
    reads: example/lib/greet.c, example/lib/greet.h, example/lib/internal.h
  step .steps/archive/cbefc0a26b666e11
    after: .steps/compile/57b56f08130b0576
  step .steps/compile/225fcd6be0b8661d
    reads: example/lib/greet.h, example/main.c
  step .steps/link/7f71dca914d576d2
    after: .steps/archive/cbefc0a26b666e11, .steps/compile/225fcd6be0b8661d, .steps/compile/57b56f08130b0576

code lists the build files the target's code is in. Each step is named by its directory under pekit-out/.

Name targets as pekit build does. --kind test asks about tests instead of builds, and --kind package about packages.

When a query can't see further #

A target's own code still runs: its fetches, its unpacks, and its reads of the workspace, which it needs to say what it builds. A target that waits for a step's result, a dynamic dependency, can't go further without running that step. The query stops there, and says so:

  unknown: it waits at build.gcsl:22 for a step's result, so what it reaches after is known only once that step runs

List the targets a change reaches #

Run pekit query rdeps with a file's path, relative to the current directory:

pekit query rdeps example/main.c

pekit lists each target that reads the file, one to a line. It asks about every target below the current directory, or about those you name after the file.

A GCSL file is read by every target whose code is in its directory or below, since what it declares is visible there, whether or not anything uses it yet. workspace.gcsl is read by every target.

A target that waits for a step's result might read the file after the wait, so it's listed too, with a note on standard error:

note: `/app` waits at build.gcsl:22 for a step's result, so it might read `main.c` after: it is listed

An unknown is never taken to mean that the file isn't read.

Run only the tests a change reaches #

In continuous integration, you can pass the list to pekit test:

pekit test $(pekit query rdeps --kind test app/main.c)

If the list is empty, pekit test given no names runs every test. Check for an empty list first if you'd rather run none.

Every test waits for the result of its own step, so pekit query rdeps --kind test lists every test, with a note for each one it can't rule out. For tests, the list is complete, but it holds every test, so this runs them all.

Building C

Pekit / Languages

The gcc library builds C programs and static libraries. Each of its functions is one step, so pekit reruns only the compiles whose sources or headers changed. Import it as github.com/gcslib/gcc.

Before you start #

  • The gcc library. See Libraries for how pekit finds one.
  • Optional: Bootlin's pinned compilers registered in pekitconf. Without them, the library uses the host's cc.

Build a program #

  1. In a build file, compile each source and link the objects:

    import "github.com/gcslib/gcc"
    
    def build hello() {
        = gcc.link([gcc.compile(file("hello.c"))], output = "hello")
    }
    
  2. Build it:

    pekit build hello
    

Check the result #

pekit prints the program's path, pekit-out/hello/link/hello. Run it.

The library's functions #

The library has three steps:

FunctionMakes
compile(src, headers, output, flags)The object of one C source, by default its name with .o for .c.
archive(objs, output)A static library of objects, by ar rcsD, with no times or owners recorded.
link(objs, libraries, output, flags)A program of objects and static libraries.

flags go to the compiler as they are. output names the file the step makes.

Give each compile its headers #

A compile's sandbox holds its source and the headers you give it, and nothing else of the workspace. pekit passes each header's directory to the compiler with -I. Give a compile exactly the headers it includes:

  • A header it includes but isn't given fails the compile.
  • A header it's given but doesn't include reruns it for nothing when the header changes.

Build a library and a program that uses it #

A library target can give its archive and its public headers together, so that a program compiles against the public headers alone:

import "github.com/gcslib/gcc"

def build greet() {
    let obj = gcc.compile(file("lib/greet.c"), headers = [file("lib/greet.h"), file("lib/internal.h")])
    archive = gcc.archive([obj], output = "libgreet.a")
    headers = [file("lib/greet.h")]
}

def build app() {
    let g = build greet()
    let obj = gcc.compile(file("main.c"), headers = g.headers)
    = gcc.link([obj], libraries = [g.archive], output = "app")
}

Editing lib/internal.h reruns the library's compile, its archive, and the link, but never the program's compile, which wasn't given that header.

Build with pinned compilers #

The gcc library defines toolchains of Bootlin's compilers. Each is fetched by its SHA-256 digest and unpacked once, and its compiler runs in a sandbox whose root is the toolchain's own runtime. A build with them reads nothing of the host's compiler or libraries. Register them in workspace.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,
]}

The toolchains are:

ToolchainRuns onBuilds for
gcc_x86_64x86-64 Linuxx86-64 Linux, with glibc
gcc_x86_64_to_aarch64x86-64 Linuxaarch64 Linux, with glibc

gcc_x86_64_musl() gives a Bootlin toolchain that builds for x86-64 Linux with musl. It isn't registered, but a library can pass it to a step, as the rust library does for static musl programs.

With both registered, pekit build --platform aarch64 hello builds the program for aarch64. See Building for Another Platform.

Tools built during the build #

A program the build makes and then runs, such as a code generator, is a file like any other: pass it to the step that runs it. Build it for the machine steps run on, and link it statically, so that it runs in a step's sandbox with nothing of the toolchain that built it:

def build embed() {
    = gcc.link([gcc.compile(file("gen/embed.c"))], output = "embed", flags = ["-static"])
}

def build app() {
    let tool = build embed() with { platform = ^host_platform }
    # Runs the tool in a step, then compiles what it wrote.
}

Building Upstream Software

Pekit / Languages

Code from elsewhere usually comes with its own build system. The buildenv library runs one as a single step: configure_make runs ./configure, make, and make install on a source directory, and gives the directory the build installed into. Import it as github.com/gcslib/buildenv.

Before you start #

  • The buildenv and gcc libraries. See Libraries.
  • A C toolchain and a build environment registered in pekitconf. This page registers pinned ones.

Build zlib from source #

  1. Register a C toolchain and a build environment in workspace.gcsl:

    import Toolchain::* from "github.com/gcslib/gcc"
    import Toolchain::* from "github.com/gcslib/buildenv"
    import Toolchain from toolchain
    
    pekitconf = {toolchains = [Toolchain::C gcc_x86_64, Toolchain::BuildEnv busybox_x86_64]}
    

    busybox_x86_64 gives /bin/sh and the usual tools from a static busybox, and GNU make built from its pinned source, all fetched by their digests.

  2. In a build file, fetch and unpack the source, and build it:

    import unpack from archive
    import "github.com/gcslib/buildenv"
    
    def build zlib() {
        let src = unpack(fetch("https://zlib.net/fossils/zlib-1.3.1.tar.gz", sha256 = "9a93b2b7dfdac77ceba5a558a580e74667dd6fede4585b91eefb60f03b72df23"))
        let out = buildenv.configure_make(src.dir("zlib-1.3.1"), configure = ["--static"])
        headers = [out.file("include/zlib.h"), out.file("include/zconf.h")]
        archive = out.file("lib/libz.a")
    }
    

    configure words go to ./configure after --prefix, and make words go to make. Each word is one argument, as written.

  3. Build it:

    pekit build zlib
    

Check the result #

pekit prints the paths of the two headers and libz.a, in the directory the build installed into. The target gives them in the same shape as the gcc library's own libraries, so a program can compile against headers and link archive.

What the step does #

The build runs with the registered C toolchain, given to it as CC, AR, RANLIB, OBJCOPY, and LD, in the registered build environment. The step copies the source to a writable directory first, as a build system expects. Every path is the same on every run, so anything the build records, such as its install prefix, doesn't change from one run to the next. Each static archive it installs is made deterministic with objcopy -D, so the same source gives the same archive.

pekit can't see inside the step, so any change to the source rebuilds all of it.

Use the host's tools #

To build with the host's own compiler and tools instead, register host_tools from the buildenv library and system_c from the toolchain module:

import Toolchain::BuildEnv host_tools from "github.com/gcslib/buildenv"
import * from toolchain

pekitconf = {toolchains = [Toolchain::C system_c, Toolchain::BuildEnv host_tools]}

The step then runs in its own sandbox with the host's tools, and a strict build refuses it.

Building Python

Pekit / Languages

The python library builds a Python program into one file, an archive that python3 app.pyz runs. It checks that each source compiles, as a step of its own, so changing one file rechecks only that file. Import it as github.com/gcslib/python.

Before you start #

  • The python library. See Libraries.
  • A Python interpreter registered in pekitconf. This page registers the library's pinned CPython.

Build a program #

  1. Register an interpreter in workspace.gcsl:

    import Toolchain::Python python_3_14 from "github.com/gcslib/python"
    import Toolchain from toolchain
    
    pekitconf = {toolchains = [Toolchain::Python python_3_14]}
    
  2. In a build file, declare a library for each group of sources, and a binary for the program:

    import "github.com/gcslib/python"
    
    def build words() {
        = python.library([file("words/words.py")])
    }
    
    def build greet() {
        = python.library([file("greet/greet.py")], deps = [build words()])
    }
    
    def build app() {
        = python.binary(file("app/__main__.py"), deps = [build greet()], output = "app.pyz")
    }
    
  3. Build the program:

    pekit build app
    

Check the result #

Run the archive pekit printed with python3. It holds app/__main__.py as its __main__.py, and the sources of greet and words beside it.

Libraries and binaries #

python.library(srcs, deps) gives a python.Library: its own sources, and every source of its dependencies, all the way down. app depends on greet alone, and still gets words.

python.binary(main, deps, output) bundles main, as __main__.py, and every source of its dependencies into one archive, each at the top by its name. Two different sources with one name are an error. A library reached by two paths is bundled once.

The archive's entries are sorted and carry a fixed date, so the same sources always give the same bytes. A step that uses the archive reruns only when a source really changed.

Interpreters #

The library asks the toolchain module for a Toolchain::Python. It defines two:

ToolchainIs
python_3_14CPython 3.14 from python-build-standalone, pinned by its SHA-256, running in a sandbox whose root is the gcc library's Bootlin runtime. A build with it reads nothing of the host's Python.
system_pythonThe host's own python3, found on PATH.

Building Rust

Pekit / Languages

The rust library builds Rust programs from the crates your Cargo.lock pins, with no network and nothing of the host. It builds a Cargo workspace one crate at a time, as Bazel's Rust rules do, or whole, as Cargo does. Import it as github.com/gcslib/rust.

Before you start #

  • The rust, gcc, buildenv, and python libraries. See Libraries.
  • A Cargo workspace with a Cargo.lock.

Register the toolchain #

The library asks the toolchain module for a Toolchain::Rust. Its rust_1_98 is Rust 1.98.1 from static.rust-lang.org, each part pinned by its SHA-256, with the standard libraries for x86_64-unknown-linux-gnu and x86_64-unknown-linux-musl, and their source, rust-src. It runs on the gcc library's Bootlin sysroot and links with its compiler. Register both in workspace.gcsl:

import Toolchain::C gcc_x86_64 from "github.com/gcslib/gcc"
import Toolchain::Rust rust_1_98 from "github.com/gcslib/rust"
import Toolchain from toolchain

pekitconf = {toolchains = [Toolchain::C gcc_x86_64, Toolchain::Rust rust_1_98]}

rustc needs zlib, which the sysroot lacks. The toolchain builds zlib from its pinned source with the buildenv library's pinned environment, so a first build takes longer.

Build one crate at a time #

  1. Plan the workspace with rust.workspace, then build what you need of it:

    import "github.com/gcslib/rust"
    
    fn crates() -> rust.RustWorkspace {
        = rust.workspace(dir("."), rust.vendored(file("Cargo.lock")))
    }
    
    def build server() {
        = rust.bin(crates(), "server")
    }
    
    def build client_library() {
        = rust.library(crates(), "client")
    }
    
  2. Build a program:

    pekit build server
    

rust.bin(ws, package, name) gives a member's program, by default the one named after the member. rust.library(ws, package) gives its shared library, and rust.static_library(ws, package) its static library. Give each features to turn on the member's own features, as cargo build --features does.

Check the result #

pekit prints the program's path. Change one source file and build again: pekit compiles that file's crate, and the crates that depend on it, again, and finds every other crate in the store.

How planning works #

Cargo plans the build: what each member needs, unit by unit, as cargo build --unit-graph lists it. Each crate, with the features Cargo resolves for the member you build, is compiled as a step of its own, and so is each build script and each run of one. Two programs that use the same crate with the same features share the one step.

Planning reads the manifests, Cargo.lock, and which files exist, never what the sources say. Editing a source plans nothing again.

It leaves out files under a hidden directory, such as .git or .claude, but .cargo, and under the paths that workspace's ignore names, relative to the workspace: by default ["target", "pekit-out"]. Add any other directory a build writes, such as ignore = ["target", "pekit-out", "docs/dist"], so that what it writes there doesn't plan the workspace again. pekit never lists a nested checkout or a Git worktree inside the workspace, a directory that holds a .git of its own, so an agent's worktree under crates/ isn't taken for a member. Planning doesn't read .gitignore, and it still walks the directories that ignore names.

Features follow the member. A program built from a member that asks for a crate's feature gets it, and a program from a member that doesn't never does, even when you build both at once. Cargo unifies features across everything one cargo build names; pekit plans each member on its own. Give workspace whole = true to plan every member with the whole workspace's features instead, as cargo build --workspace and cargo test --workspace resolve them, so that a member's tests see what they see under Cargo.

Cargo's plans leave out some of what it takes from the manifests: the [lints] table, which targets have harness = false, and the --check-cfg flags it gives every crate. The library reads each member's manifest for them with the python library's pinned Python, and compiles the member's crates with them, as Cargo does. Link-time optimization follows Cargo too: the programs a profile's lto names are optimized whole, and the libraries they link carry what that needs. A profile's strip applies as Cargo applies it, so strip = "symbols" gives programs without symbols.

Profiles #

workspace plans for the Cargo profile profile, by default release:

fn crates() -> rust.RustWorkspace {
    = rust.workspace(dir("."), rust.vendored(file("Cargo.lock")), profile = "dev")
}

A profile is chosen as Cargo chooses it. dev builds as cargo build does, and tests take the test profile, as under cargo test. release builds as --release does. Any other profile, such as a quick profile that your Cargo.toml defines, builds as --profile quick does. Each crate is compiled with its profile's settings, debug = "line-tables-only" and per-package overrides included.

A build script is told PROFILE as Cargo tells it: release for a profile that inherits from release, and debug for one that inherits from dev. pekit reads the chain of inherits from the workspace's Cargo.toml. A profile that only .cargo/config.toml defines isn't supported.

To set a profile as an environment variable would, give profile_env:

rust.workspace(
    dir("."),
    rust.vendored(file("Cargo.lock")),
    profile = "dev",
    profile_env = [{key = "CARGO_PROFILE_DEV_DEBUG"; value = "line-tables-only"}],
)

Each key has to start with CARGO_PROFILE_. Cargo plans with them set, so they apply as they would to cargo build.

A profile's rustflags, which Cargo's unstable profile-rustflags feature allows, apply as Cargo applies them, after the workspace's own flags.

Control-flow protection #

A program built one crate at a time for an x86-64 glibc target, such as x86_64-unknown-linux-gnu, has Intel's control-flow protection (CET) compiled in: indirect-branch tracking (IBT) and shadow stacks (SHSTK).

The linker marks a program with IBT and SHSTK only if every object it links is marked. Upstream's prebuilt standard libraries aren't, so the rust library compiles them again from the toolchain's rust-src:

  • each crate is a step, as your own crates are, and every workspace that uses the same toolchain and target shares them;
  • they have the features upstream's have, but compiler_builtins' C intrinsics, whose source rust-src doesn't include;
  • they use the dist profile that upstream's use, so a crate compiled with link-time optimization still finds their bitcode;
  • their source paths are /rustc/COMMIT/library, as upstream's are, so no path of the step's is in them.

Every crate compiled for the target is then compiled against them with -Zcf-protection=full. C that a build script compiles through the cc crate gets -fcf-protection=full, in CFLAGS_<target> and CXXFLAGS_<target>. A package's env in crates can set those itself.

The first glibc build compiles the standard libraries, which takes a few minutes. After that the store has them.

Unstable flags on a stable Rust #

-Zcf-protection is unstable, and the pinned Rust is stable. Only rustc is told RUSTC_BOOTSTRAP=1, in the step that compiles a crate. Build scripts aren't told it or the flags, so a build script that probes the compiler, as autocfg does, finds the same stable compiler it would without them. Build scripts and procedural macros run on the build machine, and are compiled as before.

RUSTC_BOOTSTRAP isn't supported upstream, so a flag's behavior can change between Rust versions. After updating the toolchain, check a program with readelf -n.

What glibc must provide #

The program is marked only if the C library's own objects it links are marked too: its start files, Scrt1.o, crti.o and crtn.o, and libc_nonshared.a. The gcc library's Bootlin glibc isn't built with CET. A program linked with gcc_x86_64 is therefore not marked, even though every object Rust compiles for it is. To see what isn't marked, link with -Clink-arg=-Wl,-z,cet-report=error in rustflags, and the linker names each object.

Turning it off, and other targets #

To use upstream's standard libraries without the flags, give workspace cet = false.

A musl target never has control-flow protection: musl's assembly isn't marked, so no static musl program can be. CET is x86-64's, so a target for another architecture doesn't have it either. cet = true with any target but an x86-64 glibc one is an error. cargo_build, which builds with Cargo whole, doesn't give control-flow protection either.

Crates that read outside their directory #

Each step's sandbox holds the toolchain, the crate's own directory, and what it is given. A crate that reads a file outside its directory needs it named. Give workspace the settings of such packages in crates:

rust.workspace(
    dir("."),
    rust.vendored(file("Cargo.lock")),
    crates = [
        {package = "policy"; data = [{at = "registry.d"; place = dir("registry.d")}]},
        {
            package = "sdk-sys"
            env = [{key = "SDK_DIR"; value = "/opt/sdk"}]
            given = [{at = "/opt/sdk"; place = build sdk()}]
        },
    ],
)

Each setting does one thing:

  • data places files and directories under the workspace, where the crate's compiles and build script find them.
  • env sets variables for its build script and its compiles.
  • given places files and directories at absolute paths, for its build script and its compiles, and for every crate that depends on it. A native library that a build script links goes here, so that the programs that use the crate link it too.

Tests #

rust.tests(ws, package) gives a member's test programs, its unit tests and each integration test, as cargo test -p builds them. Give features too if the tests need them. rust.run_test(test) runs one as a step, in a sandbox of the toolchain's runtime with a writable /tmp. It runs from its package's directory, as Cargo does, and the sandbox holds that directory with the package's data and beside:

def test server_tests(tests: List<rust.RustTest> = rust.tests(crates(), "server")) {
    let ran = for each in tests { = rust.run_test(each) }
}

So a test reads its own files by relative paths or through CARGO_MANIFEST_DIR, as it does under Cargo. What a test writes there stays in its sandbox, so no change reaches your workspace.

Give run_test what else a test reads in given, such as another member's directory, its variables in env, and its arguments in args, such as a filter and --test-threads=1. A path in given that the package already places is placed once, from the package. A test reruns when its program or any file of its package changes.

A test target with harness = false in its manifest is compiled as a program of its own, as Cargo compiles it.

rust.tests builds the package's examples too, as cargo test does. A test program runs at /work/deps/<name>, with the examples beside it in /work/examples, as in Cargo's target directory. So a test that finds an example from its own path, at ../../examples/<name>, finds it.

rust.benches(ws, package) gives a member's benchmarks, as cargo test --benches builds them, and rust.run_test runs each. A benchmark with harness = false is a program of its own, which runs with no arguments.

Documentation, its tests, and Clippy #

rust.doctests(ws, package) tests a member's documentation, as cargo test --doc does: rustdoc compiles and runs each crate's examples as a step. It takes features, given, and env as run_test does, and gives no tests for a member with no library.

rust.clippy(ws, package) checks a member with Clippy, as cargo clippy --all-targets does: its library, programs, build script, tests, benchmarks, and examples, each crate a step. flags come after the member's lints, so flags = ["-Dwarnings"] denies every warning. A check fails when a lint it denies fires.

Clippy's cargo lints read cargo metadata, which a check of one crate can't run, so rust.clippy allows them. rust.cargo_lints(ws) checks them instead, as cargo clippy --workspace does, in one step for the whole workspace. The step holds what Cargo plans with: the manifests, the lock, the vendored crates, and Cargo's home, with the network off. The member's [lints] that name these lints apply, then flags, so flags = ["-Wclippy::cargo", "-Dwarnings"] denies them. It reads the workspace's Clippy configuration too, such as allowed-duplicate-crates.

rust.docs(ws, package) makes a member's library documentation, as cargo doc --no-deps does, as a step, and gives the directory rustdoc wrote. flags come after the member's lints, as they do for Clippy, so flags = ["-Dwarnings"] fails it when rustdoc warns, such as about a broken link.

All of these are steps that the rust library makes, so make them in a test's parameter defaults, where a test plans and builds what it needs:

def test clippy(checked: List<List<{}>> = rust.clippy(crates(), "server", flags = ["-Dwarnings"])) {}

def test doctests(ran: List<List<{}>> = rust.doctests(crates(), "server")) {}

def test docs(made: Dir = rust.docs(crates(), "server", flags = ["-Dwarnings"])) {}

def test cargo_lints(checked: {} = rust.cargo_lints(crates(), flags = ["-Wclippy::cargo", "-Dwarnings"])) {}

Build with Cargo, whole #

rust.cargo_build builds the workspace with Cargo, in one step:

import "github.com/gcslib/rust"

def build ppk() {
    = rust.cargo_build(dir("src"), rust.vendored(file("src/Cargo.lock")), bins = ["ppk"])
}

rust.cargo_build(src, vendor, bins) builds the Cargo workspace src with cargo build --release --frozen --offline, from the crates of vendor. It gives a directory of the binaries bins, each by its name. packages names the workspace's packages to build, as Cargo's -p does.

The whole of cargo build is one step, so changing one source file runs it again. Cargo's target directory is kept between runs in the step's scratch directory, so the crates of vendor aren't compiled again. The workspace's own crates, and crates it takes by their paths, are always compiled again. Cargo judges them by their files' modification times, which a file put back as it was can make look older than the last build.

Either way of building takes its crates from rust.vendored, so no crate is fetched again.

Where crates come from #

rust.vendored(lock) fetches every crate of crates.io that lock pins, each checked against the checksum Cargo.lock records for it, and lays them out as cargo vendor does. Each crate's fetch and unpacking is kept in the store.

A crate from a git repository is pinned by the commit Cargo.lock records for it. rust.vendored fetches the repository at that commit with fetch_git, once for every crate it holds. It gives each crate's directory as the repository has it, so a crate that takes another of the same repository by its path still finds it. A crate whose manifest takes values from its workspace's, such as version.workspace = true, or names a sibling crate's path, has its manifest written for it to build on its own.

A crate from anywhere else is an error, since nothing pins it.

Git crates of a pinned library #

If pekit.lock pins a library from the same repository as a git crate, Cargo.lock must pin the crate at the library's commit, because the library's settings for the crate and the crate must match. A crate at another commit is an error that names both commits, so update one lock to match the other.

A distribution that builds others' workspaces can set the context crates_at_pins instead. Each such crate is then built at the library's commit, not at the commit Cargo.lock records, so a fix to one crate of a repository reaches every workspace that pins its library without a change to each workspace's Cargo.lock:

let vendor = rust.vendored(file("Cargo.lock")) with { crates_at_pins = true }

rust.overrides_report(vendor) lists each crate built at another commit than its lock records, one line each, NAME URL LOCKED -> PINNED, for a packager to record.

Cargo takes the crate only while the lock still describes it. If the crate has another version at the library's commit, the build fails and says to update the lock with cargo update -p NAME. If its dependencies changed, Cargo's own check of the lock fails.

Targets and flags #

By default cargo_build builds for x86_64-unknown-linux-musl, as static, position-independent programs that need nothing of the system they run on. Give target = "x86_64-unknown-linux-gnu" for programs linked against glibc instead.

The flags follow the target: a glibc build takes none unless you give rustflags. The library's flags are Cargo's build.rustflags, so a project's own configuration of its target's flags, or of its linker, takes precedence over them, as Cargo intends.

C, libraries, and bindings #

C that a crate compiles through the cc crate, such as zstd-sys, is compiled for the target by target_c. By default that's the gcc library's Bootlin musl toolchain, gcc_x86_64_musl(), for a musl target, which a static musl program needs, and the registered C toolchain for any other.

cargo_build takes these as well:

  • libs names libraries a crate builds to give besides the binaries, such as a staticlib: libs = ["libpeios.a"].
  • beside places directories next to the source, at ../NAME, for a crate that takes another by a path outside its own tree.
  • env gives every build script variables of its own, each a {key; value}, as Cargo's [env] table does.
  • libclang is for a build script that runs bindgen: a list of one directory holding libclang.so, such as libclang = [clang.libclang_18()]. The clang library's libclang_18 is a pinned build from PyPI. The build is given LIBCLANG_PATH, and BINDGEN_EXTRA_CLANG_ARGS names the target C toolchain's own headers and sysroot, so bindgen parses as that toolchain's compiler would.

A build script finds the C compiler in CC_<target>, the C++ compiler beside it in CXX_<target>, such as x86_64-linux-g++ beside x86_64-linux-gcc, and the archiver in AR_<target>, so a crate that compiles C++ through cc builds. That holds both one crate at a time and with cargo_build.

No pkg-config is pinned, and a build script's sandbox holds only the toolchain, so a probe for a system library fails the same way on every machine. A crate that falls back without the library, or loads it at run time, such as wayland-sys with its dlopen feature, builds. For a crate that has to link a system library, give the library through given and tell its build script where it is through env.

Everything is pinned, so a strict build gives the same program, byte for byte, on any machine. See Hermetic and Strict Builds.

Building Go

Pekit / Languages

The go library builds Go programs from the modules your go.sum names, with no network and nothing of the host. It compiles a module one package at a time, as Bazel's Go rules do. Import it as github.com/gcslib/go.

Before you start #

  • The go, buildenv, and gcc libraries. See Libraries.
  • A Go module with a go.sum.
  • curl and sha256sum on the host, to pin the module files.

Register the toolchain #

The library asks the toolchain module for a Toolchain::Go. Its go_1_26 is Go 1.26.8 from go.dev, pinned by its SHA-256. It runs on the buildenv library's busybox environment. Register both in workspace.gcsl, with the gcc library's C toolchain for the race detector:

import Toolchain::* from "github.com/gcslib/buildenv"
import Toolchain::* from "github.com/gcslib/gcc"
import Toolchain::* from "github.com/gcslib/go"
import Toolchain from toolchain

pekitconf = {
    toolchains = [Toolchain::C gcc_x86_64, Toolchain::Go go_1_26, Toolchain::BuildEnv busybox_x86_64]
}

Pin the modules #

pekit fetches a file only by its SHA-256. go.sum records a different hash, of a module's contents, so a second file, go.pins, records the digest of each module file as the module proxy serves it.

  1. Add a script that writes it:

    import "github.com/gcslib/go"
    
    def script pin_modules() {
        let count = go.pin_modules(file("go.sum"), "{dir(".").path}/go.pins")
    }
    
  2. Run it, and commit go.pins beside go.sum:

    pekit run pin_modules
    

Run it again whenever go.sum changes, and review the change to go.pins as you would review go.sum. A build fails when go.pins lacks a file go.sum names, and says which.

The build fetches each file by its pin and lays them out as a module proxy for the go command. The go command checks each module against go.sum as it reads it, so the pins name the bytes and go.sum names what they must be.

Build a program #

  1. Plan the module with go.workspace, then build what you need of it:

    import "github.com/gcslib/go"
    
    fn module() -> go.GoWorkspace {
        = go.workspace(dir("."), file("go.sum"), file("go.pins"))
    }
    
    def build server() {
        = go.bin(module(), "./cmd/server")
    }
    
  2. Build it:

    pekit build server
    

go.bin(ws, package) gives the program of a main package, named after its last path element unless you give name. Give ldflags for the linker, such as ldflags = ["-B", "gobuildid"]. The program carries the build information go build -trimpath embeds, which go version -m prints.

go.workspace builds for Linux on x86-64, with cgo off. Give goos and goarch for another platform. Its build mode is exe unless you give buildmode, such as buildmode = "pie". Give tags for build tags.

Check the result #

pekit prints the program's path. Change one source file and build again: pekit compiles that file's package, and the packages that import it, again, and finds every other package in the store. A change that leaves a package's archive the same, such as a new comment, compiles nothing that imports it.

How planning works #

The go command plans the build: go list lists each package a program needs, with its files and imports. Each package is then a step of its own, compiled as the go command compiles it. compile compiles its Go files, asm its assembly, and pack adds the objects to its archive. A step holds only the package's own files and the archives of the packages it imports.

The go command reads the sources' imports to plan, so an edit plans again. Planning is quick, and a package whose files and imports didn't change is found in the store.

The standard library is built once for each configuration, by the go command, as one step.

Tests #

go.tests(ws, package) gives a package's test program, as go test -c builds it, or nothing for a package with no test files. go.run_test(test) runs one as a step, in the package's directory, as go test does:

def test store(tests: List<go.GoTest> = go.tests(module(), "./internal/store")) {
    let ran = for each in tests { = go.run_test(each) }
}

Give run_test what a test reads in given, its variables in env, and its arguments in args, such as -test.run=TestOpen. A test program is a static program, as go test links one, whatever the workspace's build mode.

Vet and the race detector #

go.vet(ws) runs go vet on every package, and go.race(ws) runs every package's tests with go test -race. Each is one step, which fails as the go command does. The race detector links with C, so race uses the registered C toolchain:

def test vet(checked: {} = go.vet(module())) {}

def test race(checked: {} = go.race(module())) {}

Give either patterns to check only some packages, such as patterns = ["./internal/..."].

Embedded files #

A package's //go:embed files are placed with it, and its compile is given the go command's own record of what each pattern matches. An edit to an embedded file compiles its package again.

What it doesn't build #

These are errors, which say so:

  • A package with cgo files.
  • A package of a module that go.mod replaces with a local directory.

Everything is pinned, so a strict build gives the same program, byte for byte, on any machine. See Hermetic and Strict Builds.

Packaging

Pekit / Packaging and Releasing

A package says what it contains, not how a format stores it. You write packages with the package definition type, beside the builds they ship. The workspace's packagers turn each into a file of their format, such as a Peios package, and publish it into a store.

Before you start #

  • The ppk library, and a ppk program to register as its tool. See Libraries.
  • A target that builds what you want to ship.

Describe a package #

In a build file beside the build it ships, such as package.gcsl next to build.gcsl, declare the package:

let version = "1.0-1"

def package dev.example.greet() {
    version = version
    files = {"bin/greet" = build app()}
}

def package dev.example.greet-dev() {
    let g = build greet()
    version = version
    files = {"include" = g.headers; "lib/libgreet.a" = g.archive}
}

The definition's path is the package's name. Each of its files is placed at its path under /usr: a file at its path, a list of files under it by their names, and a directory's tree under it. Files in one directory see each other's declarations, so build app() needs no import.

Give a package its metadata #

A package can carry more than its files. pekit keeps any other field of a package's body and never reads it, so each packager defines the fields it takes. The ppk packager reads a field named ppk, and records what it holds in the package's manifest:

def package dev.example.greet-dev() {
    let g = build greet()
    version = version
    files = {"include" = g.headers; "lib/libgreet.a" = g.archive}
    ppk = {
        description = "The greet library, for developers"
        license = "MIT"
        license_class = "free"
        homepage = "https://example.com/greet"
        dependencies = {"dev.example.greet" = "= {version}"}
    }
}

ppk has two kinds of field:

  • Single values, each a string: description, homepage, license, license_class, and source_license.
  • Tables, each a record of strings:
    • dependencies: the packages this one needs, each with a version constraint.
    • requires: the capabilities it needs, such as sh, each with a constraint.
    • provides: the capabilities it offers, each with a version.
    • claims: links it owns outside its files, each an absolute path and the link's target, such as "/usr/bin/sh" = "dash".
    • descriptors: files and directories of the package that get a security descriptor of their own, each a path as files gives it and the descriptor in hexadecimal.

An empty string means any version, or no version. ppk checks every value as ppk pack does, and finds an ELF program's libraries and their floors itself, so don't write those. A field ppk has no form for is an error naming it, so a misspelt field never goes missing quietly. A package without ppk is packed with no metadata, as before.

A signed file, such as firmware, takes its signature from a file beside it named with .peios.sig added. Place the signature in files like any other file, or in the directory you place. ppk pack records it in the signed file's entry and doesn't pack it as a file:

def package dev.example.firmware() {
    version = "1.0-1"
    files = {
        "lib/firmware/acme/fw.bin" = file("fw.bin")
        "lib/firmware/acme/fw.bin.peios.sig" = file("fw.bin.peios.sig")
    }
    ppk = {descriptors = {"lib/firmware/acme" = "0100048014000000..."}}
}

The descriptor is shortened here. What ppk requires of a descriptor or a signature is under SECURITY METADATA in ppk(1).

Register the packager #

  1. In workspace.gcsl, register the ppk tool as a toolchain, and the ppk packager in pekitconf.packagers:

    import * from "github.com/gcslib/ppk"
    import * from toolchain
    
    def Toolchain::Ppk workspace_ppk() {
        let tools = dir("tools")
        host_platform = ^host_platform
        platform = {}
        provides = {root = tools; runtime = dir("/"); ppk = tools.file("ppk")}
    }
    
    pekitconf = {
        toolchains = [Toolchain::C system_c, Toolchain::Ppk workspace_ppk]
        packagers = [packager()]
    }
    

    This keeps the ppk program at tools/ppk in the workspace. A relative path is relative to the file it's written in, so dir("tools") in workspace.gcsl is tools at the workspace's root.

  2. Pack every package below the current directory:

    pekit package
    

Check the result #

pekit packs each package with each packager, and prints where each went:

packed example/dev.example.greet with ppk
  pekit-out/example/dev.example.greet/pack/artifacts
packed example/dev.example.greet-dev with ppk
  pekit-out/example/dev.example.greet-dev/pack/artifacts
6 steps run, 0 found in the store

Name packages to pack only those, as pekit build names targets: pekit package dev.example.greet, or pekit package 'pkgs/**'.

What reruns #

Each packing is a step of its own, so a package whose files didn't change isn't packed again. Changing main.c repacks dev.example.greet and leaves dev.example.greet-dev alone. Changing the version alone repacks both and compiles nothing.

The ppk packager packs a package as ppk pack does, for the architecture of ^platform, into a new directory, so the same files and version always give the same package.

Pack in a build #

A build can pack packages itself, with the ppk library's pack:

import "github.com/gcslib/ppk"

def build packages() {
    greet = ppk.pack(package dev.example.greet())
    greet_dev = ppk.pack(package dev.example.greet-dev())
}

ppk.pack gives the artifact directory of one package.

Publish packages #

Copying a package into a store is publishing. It changes things outside the build, so it's never a step: it happens on each run, in order, after the packing it needs. pekit publish packs each package it's given, as pekit package does, then publishes it with each packager into the store --to names:

pekit publish dev.example.greet --to /srv/artifacts
published example/dev.example.greet with ppk
  pekit-out/example/dev.example.greet/pack/artifacts
0 steps run, 5 found in the store

Packing doesn't depend on the store, so publishing what you've packed, or the same package into a second store, packs nothing again. ppk publishes into an artifact directory with ppk fetch --no-deps, which copies only the named package and refuses a version whose contents changed: publish a new version instead. If one package fails to publish, the packages published before it stay published.

Publish strictly #

A strict build refuses a target's own effects, and publishing is one. To publish what a strict build packs, pass --strict to pekit publish:

pekit publish 'pkgs/**' --to /srv/artifacts --strict

pekit packs every package strictly, then publishes them, taking every pack from the store. If a package fails to pack strictly, pekit publishes none of its recipe's packages, so that a recipe is published whole or not at all. It publishes the other recipes, says which it held back, and fails:

error: a recipe is not published, since a package of it did not pack strictly: org.gnu.bash

Replace a published version #

ppk refuses to publish a version whose contents changed, because something might already have fetched the old contents. A repository that nothing has fetched from yet, such as one being bootstrapped, can need a version rebuilt and published again. For that, give the ppk packager replace = true in workspace.gcsl:

pekitconf = {
    packagers = [packager(replace = true)]
}

The packager then publishes with ppk fetch --no-deps --replace, and each line pekit prints names it:

published example/dev.example.greet with ppk --replace

Caution

A replaced version breaks anything that fetched the old one. Use replace = true only on a repository nothing has fetched from, and don't commit it.

Write a packager #

Each packager is a packaging.Packager, from GCSL's standard packaging module. It has a name, a pack function of a package to the directory it packed it into, and a publish function of a package, that directory, and a store. A library for another format gives a packager of its own, and a workspace lists it in pekitconf.packagers beside ppk's.

Signing Kernel Modules

Pekit / Packaging and Releasing

A kernel that enforces module signatures loads a module only if it carries a signature by a key the kernel trusts. The modsig library signs a tree of modules after they are built, in a step of its own. It's the only step given the key, so no build command sees it. Signing the same modules with the same key always gives the same bytes, so a package of signed modules stays reproducible.

Before you start #

  • The modsig library, which builds its signing program with the rust library. See Libraries.
  • The Rust and C toolchains registered in workspace.gcsl. See Building Rust.
  • A target that builds a directory of modules, each compressed with zstd and named .ko.zst.
  • A PEM file holding an ML-DSA-65 private key, with its seed, followed by its certificate, which the kernel trusts. Keep it outside the workspace, and out of version control.

Sign the modules #

  1. Tell pekit where the key is. Name a file in the environment, which keeps the path out of your workspace:

    export GCSL_SECRET_FILE_MODULE_SIGNING=~/.config/peios/keys/modsig.pem
    

    Or give it a keychain entry named module-signing. See Using Secrets.

  2. In the package, give modsig.sign the directory of modules:

    import "github.com/gcslib/modsig"
    
    def package dev.example.modules() {
        version = "1.0-1"
        files = {"lib/modules" = modsig.sign(build modules())}
    }
    
  3. Pack it:

    pekit package dev.example.modules
    

Check the result #

Decompress a module from the package, and modinfo shows who signed it:

zstd -d example.ko.zst
modinfo example.ko | grep -E '^(sig_id|signer)'
sig_id:         PKCS#7
signer:         example module signing key

What it changes #

modsig.sign gives a copy of the directory. In that copy, each .ko.zst is decompressed, signed, and compressed again at zstd's level 19. Everything else is copied unchanged, so run depmod before or after signing, as you prefer.

The step fails, and says why, if:

  • a module is a .ko, .ko.gz, or .ko.xz. The signature has to be inside the compression, and only zstd's is supported.
  • a module is signed already.
  • the directory holds no module.
  • the key file holds no seed, or the certificate isn't the private key's.

How a signature is made #

Each signature is deterministic pure ML-DSA-65 over the whole module, with an empty context string and no signed attributes, in a PKCS#7 message appended to the module. The kernel's sign-file can't produce this with OpenSSL 3, which adds a signing time and randomises each signature.

A signed module's bytes also depend on zstd. The library's Cargo.lock pins the version, so updating it changes every package that holds signed modules.

How the key and the store work together #

The signing step is an ordinary step given a secret, so Using Secrets describes how pekit protects the key. For signing, that means:

  • The directory you give modsig.sign, and every step that made it, stays unsigned in the store. Changing the key signs again without rebuilding them.
  • The signed copy is kept in the store, under the key's identity. It holds no secret.
  • Another machine signs for itself, because a secret's identity differs between machines. It packs for itself too, and gets the same package.
  • pekit release uses the release profile's key. Signing twice gives the same bytes, so the release's reproducibility check passes.

Signing Firmware

Pekit / Packaging and Releasing

The Peios kernel loads device firmware only if the file carries a signature by a key in the kernel's trusted computing base. A file that isn't ELF carries its signature in its security.peios.sig attribute, which a package can't hold. So the package carries the signature as a file beside the one it signs, <file>.peios.sig, and the package's consumer sets the attribute from it. The pipsig library makes those files after the build, in a step of its own. It's the only step given the key, so no build command sees it. Signing the same files with the same key always gives the same bytes, so the package stays reproducible.

For the format of the signature and what the kernel checks, see Signature Format and Files the Kernel Loads. For how a package carries one, see Payload Entries.

Before you start #

  • The pipsig library, which builds its signing program with the rust library. See Libraries.
  • The Rust and C toolchains registered in workspace.gcsl. See Building Rust.
  • A target that builds a directory holding the files to sign.
  • A PEM file holding an ML-DSA-65 private key with its seed, such as openssl genpkey -algorithm ML-DSA-65 writes, whose public key the kernel trusts. Keep it outside the workspace, and out of version control.

Sign the files #

  1. Tell pekit where the key is. Name a file in the environment, which keeps the path out of your workspace:

    export GCSL_SECRET_FILE_TCB_SIGNING=~/.config/peios/keys/tcb.pem
    

    Or give it a keychain entry named tcb-signing. See Using Secrets.

  2. In the package, give pipsig.sign the directory and the patterns of the files to sign:

    import "github.com/gcslib/pipsig"
    
    def package dev.example.firmware() {
        version = "1.0-1"
        files = {"." = pipsig.sign(build firmware(), take = ["usr/lib/firmware/**"])}
    }
    
  3. Pack it:

    pekit package dev.example.firmware
    

Check the result #

Each file the patterns take has its signature beside it, of 3310 bytes:

wc -c usr/lib/firmware/example.bin.zst.peios.sig
3310 usr/lib/firmware/example.bin.zst.peios.sig

What it changes #

pipsig.sign gives a copy of the directory. In that copy, each regular file the patterns take has a signature beside it, with mode 0644. Everything else, the files themselves included, is copied unchanged.

A pattern is matched against the whole of a path in the directory. ** matches any characters, * matches any characters but /, and every other character matches itself. So usr/lib/firmware/** takes every file under usr/lib/firmware, and */usr/lib/firmware/** takes those of each directory the tree holds.

A link that a pattern takes isn't signed. The kernel checks the file a link names, so that file's signature serves the link.

The step fails, and says why, if:

  • a file it takes is ELF. An ELF file carries its signature in a section instead.
  • a file it takes is a signature, or already has one beside it.
  • a pattern takes no file, or take is empty.
  • the tree holds something that is neither a file, a directory nor a link.
  • the key file holds no seed, or its expanded key isn't its seed's.

How a signature is made #

Each signature is a version byte, 1, followed by a deterministic pure ML-DSA-65 signature, with an empty context string, of the SHA-256 of the whole file as it is on disk. A compressed file is signed as it is compressed, since the kernel checks the file before it decompresses it.

How the key and the store work together #

The signing step is an ordinary step given a secret, so Using Secrets describes how pekit protects the key. For signing, that means:

  • The directory you give pipsig.sign, and every step that made it, stays unsigned in the store. Changing the key signs again without rebuilding them.
  • The signed copy is kept in the store, under the key's identity. It holds no secret.
  • Another machine signs for itself, because a secret's identity differs between machines. It packs for itself too, and gets the same package.
  • pekit release uses the release profile's key. Signing twice gives the same bytes, so the release's reproducibility check passes.

Recording Corresponding Source

Pekit / Packaging and Releasing

A package that ships a binary often has to come with its corresponding source: everything the binary was built from, as the GPL asks of anyone who distributes a GPL program, say. pekit works that out for you. It records what each recipe's packages are built from in pekit.sources, a file at the workspace's root, beside pekit.lock. A package of a recipe's source is then built from that record alone, so it's the same wherever it's built, and a change to a recipe's source shows in review.

What a recipe's source is #

A recipe is a directory of package definitions, such as org.gnu.bash. Its source is everything a build of all its packages used, except tools:

  • each file its build fetched, by URL and SHA-256;
  • each git commit its build fetched, by repository and commit;
  • each file and directory of the workspace that its code read, that its steps were given, or that its packages hold, by its path in the workspace. The GCSL code itself is among them, with workspace.gcsl and pekit.lock, which loading the workspace takes;
  • each library whose code it ran. A library that pekit.lock pins is recorded whole, by its import path and its directory, since a build restores a pinned library whole. One the lock doesn't pin is recorded by the files of its code alone.

A tool isn't source:

  • What a registered toolchain is made from: its definition's fetches, and everything fetched to make it, such as the source of a tool it compiles.
  • A fetch or a fetch_git marked tool = true (see Fetching Files).
  • A path that leads out of the workspace, such as a link to a repository of packages that build roots are taken from.

Packing isn't part of a recipe's source either: pekit builds a recipe's packages without packing them to record it, so a packager's own program isn't counted.

Nor is what the package of the source holds. A package whose own code reads pekit.sources is built from the record, so pekit counts its code but not what it reads, fetches or holds. Otherwise a file the record once named would stay recorded after the recipe stopped using it, or even after it was deleted, since the package of the source holds it.

Before you start #

  • A workspace whose packages build strictly, if the workspace requires --strict. See Hermetic and Strict Builds.
  • Every tool your builds fetch outside a toolchain marked tool = true.

Record the sources #

  1. Run pekit sources with the packages whose recipes to record, or none to record every recipe below this directory:

    pekit sources --strict 'org.gnu.bash/**'
    

    pekit builds each recipe's packages on their own, every package of the recipe whichever you named, and records what each build used, with the names of the recipe's packages:

    recorded org.gnu.bash: 21 fetched, 0 git, 15 files, 9 directories
    
  2. Review pekit.sources, and commit it with the change that made it.

A recipe's record replaces what was recorded of it. Recipes you didn't name keep theirs.

Keep it current #

Run pekit sources again whenever a recipe's source changes: a new version, a new patch, a build that reads another file, or a new package. A strict publish or a release checks the record of each recipe it publishes, and publishes nothing if one isn't what the recipe's build uses and the packages it has:

error: nothing is published, since `pekit.sources` does not record what org.gnu.bash is built from: run `pekit sources --strict` for it, and review the change

A workspace with no pekit.sources publishes without the check.

Check the result #

Each recipe in pekit.sources lists its packages, its fetched files, its git commits, the libraries whose code it ran, and the workspace's files and dirs it read, each sorted:

{
  "recipe": "org.gnu.bash",
  "packages": ["org.gnu.bash", "org.gnu.bash-doc"],
  "fetched": [
    {
      "url": "https://ftpmirror.gnu.org/bash/bash-5.3.tar.gz",
      "sha256": "0d5cd86965f869a26cf64f4b71be7b96f90a3ba8b3d74e27e8e9d9d5550f31ba"
    }
  ],
  "git": [],
  "libraries": ["github.com/gcslib/ppk"],
  "files": [
    "org.gnu.bash/build.gcsl",
    "pekit.lock",
    "recipe.gcsl",
    "workspace.gcsl"
  ],
  "dirs": [".gcsl/libraries/github.com/gcslib/ppk", "org.gnu.bash/patches"]
}

A directory stands for everything in it. A package of the source fetches each file again by its digest, which the store answers, and takes the commits and the workspace's files as they are.

A build from a package of the source restores every library that its pekit.lock pins, and fetches any that it lacks. So give the package a lock that pins only the recipe's libraries, beside their directories. It then builds with no network, from the store's tools and what the package holds.

Releasing

Pekit / Packaging and Releasing

pekit release makes a release of one package. It builds the package as a release should be built, publishes it, and tags the commit it was built from. Everything a release depends on is pinned, so anyone with the commit can build the same bytes.

Before you start #

  • A workspace in a git repository, with every change committed.
  • Every library pinned in pekit.lock. See Pinning Libraries.
  • Steps that use only pinned toolchains, since a release is a strict build.
  • The release profile's secrets in the keychain, if the package needs any. See Using Secrets.
  • A packager registered in pekitconf.packagers. See Packaging.

Release a package #

  1. Commit everything, and check that git status is clean.

  2. Release the package into its store:

    pekit release dev.example.greet --to /srv/artifacts
    

Check the result #

pekit reports what it published and the tag it added:

published dev.example.greet@1.0-1 with ppk into /srv/artifacts
tagged dev.example.greet@1.0-1 at 4834d15186dbf67463ca1410d67bc578faca1f4e

git tag lists the new tag. Push it to share the release.

What a release is built from #

A release is built from a commit, never from your working tree. The workspace must match the repository's HEAD: every file committed, and nothing changed or added, except the build's own pekit-out/ and .gcsl/. If any file differs, pekit names it and stops.

pekit then exports the workspace's tree at HEAD into a directory of its own, and builds there. So a file that git ignores never reaches a release.

How a release is built #

A release builds as pekit build --strict --check-reproducible would, with the keychain's release profile:

  • No host tools. Its steps run their programs from pinned toolchains, and a target's own code only fetches, unpacks, asks the keychain, and reads the workspace and the build's outputs. See Hermetic and Strict Builds.
  • Pinned libraries. Its libraries are exactly those pekit.lock pins.
  • Reproducible steps. Every step runs a second time, and a step that gives other outputs from the same inputs fails the release.
  • Release secrets. Secrets come from the release profile, so a release signs with its own keys.

Publishing and tagging #

Once the package is built and checked, pekit publishes it with each of the workspace's packagers into the store --to names. Then it tags HEAD as NAME@VERSION, the package's name and version: dev.example.greet@1.0-1. The tag is a lightweight tag, so it needs no git identity.

A version is released from one commit. If its tag is on another commit, pekit refuses before publishing anything: give the new release a version of its own. Releasing again from the commit that has the tag publishes the same package again, and adds no tag. pekit only ever adds tags. It never moves or deletes one.

Building and Booting an Image

Pekit / Packaging and Releasing

A bootable ISO is an ordinary build. The peiso library makes one from packages with the peiso tool, and the qemu library boots one in QEMU, in a test or for you to use.

Before you start #

  • The peiso, ppk, and qemu libraries. See Libraries.
  • The peiso, mkirf, and mkuki programs, and ppk, to register as toolchains.
  • On the host: mkfs.vfat, mtools, and xorriso, which peiso runs, and QEMU with OVMF's firmware for booting.

Register the tools #

The libraries ask the toolchain module for their tools. The qemu library's system_qemu is the host's qemu-system-x86_64 and OVMF's firmware. peiso, mkirf, and mkuki aren't published, so register the ones you have, as ppk is registered in Packaging:

def Toolchain::Peiso workspace_peiso() {
    let tools = dir("tools")
    host_platform = ^host_platform
    platform = {}
    provides = {
        root = tools
        runtime = dir("/")
        peiso = tools.file("peiso")
        mkirf = tools.file("mkirf")
        mkuki = tools.file("mkuki")
    }
}

Build the image #

  1. In a build file, call peiso.iso with the kernel the ISO boots and the packages it carries:

    import "github.com/gcslib/peiso"
    import "github.com/gcslib/ppk"
    
    def build iso() {
        = peiso.iso(
            kernel = {
                package = ppk.from_repository(dir("repository"), "dev.peios.kernel", "0.25.0-indev-1")
                cmdline = "console=ttyS0"
            },
            packages = [
                {package = ppk.from_repository(dir("repository"), "net.busybox.busybox", "1.37.0-1"); initramfs = true},
                {package = package dev.example.motd()},
            ],
        )
    }
    

    Each package is a package definition, which the library packs with ppk, or a package ppk has packed already, such as one from a repository.

  2. Build it:

    pekit build iso
    

Check the result #

pekit prints the ISO's path. The ISO is one step, given its packages, so changing the kernel's command line rebuilds the ISO and no package. Changing one package rebuilds that package and the ISO.

Choose where each package goes #

Each package says whether the live system holds it, liveboot, which it does unless you say otherwise, and whether the initramfs does, initramfs. The initramfs and liveboot arguments of peiso.iso replace what each holds outside /usr, as peiso's own specification does. Each holds symbolic links, each {at; to}, with a target starting : in usr, and empty directories.

Take packages from a repository #

ppk.from_repository(repo, name, version) takes a package that isn't built here from an artifact directory in the workspace, by its name and version, for the platform being built for. It's a step keyed by the repository's contents, so what it gives is exactly what the repository holds. The repository has to be a directory of the workspace; the ppk library doesn't fetch one over the network. It uses ppk fetch --no-deps to take only the named package. Callers that need its dependencies resolve the closure themselves.

Boot the image in a test #

qemu.boot(iso, until) boots an ISO under UEFI, with no network and its console on its first serial port, until a line holding until appears. It gives what the machine printed, with status 0 if the line appeared. In a test, ask for KVM so that the machine runs at speed:

import "github.com/gcslib/qemu"

#[device("kvm")]
#[timeout(5m)]
def test boots(iso: File = build iso()) {
    let run = qemu.boot(iso, until = "Please press Enter to activate this console.")
    assert run.status == 0, run.stdout
}

The test is a step given the ISO, so it boots again only when the ISO changes. Without KVM, QEMU emulates the machine, slowly but the same.

Boot the image yourself #

qemu.launcher(iso) builds a program that boots the ISO with your terminal, so that pekit run can run it:

def build boot() { = qemu.launcher(build iso()) }
pekit run boot

Commands

Pekit / Reference

The pekit command has a subcommand for each kind of work. This page says what each is for and where to read about it. pekit(1) is the authority for every command, option, exit status, environment variable, and file, and pekit <command> --help summarizes one command.

The commands #

These are the commands, in the order you're likely to meet them:

CommandDoesRead
pekit buildBuilds targets.Building a First Program
pekit testRuns tests, every test below this directory by default.Writing and Running Tests
pekit runRuns a script, or the program a build gives.Running Scripts and Programs
pekit query depsLists the steps and files targets reach.Querying What Targets Reach
pekit query rdepsLists the targets that read a file.Querying What Targets Reach
pekit lockPins the libraries the workspace imports.Pinning Libraries
pekit sourcesRecords what each recipe's packages are built from in pekit.sources.Recording Corresponding Source
pekit packagePacks packages with the workspace's packagers.Packaging
pekit publishPacks packages and publishes them into a store.Packaging
pekit releaseBuilds a package from HEAD strictly, publishes it, and tags it.Releasing
pekit cleanRemoves pekit-out/, and with --cache the store.Managing the Store
pekit store statsShows the store's size, its limit, and whether a build is using it.Managing the Store
pekit store evictEvicts the store to within its limit now.Managing the Store
pekit store verifyHashes every file of the store again, and with --repair repairs what is wrong.Managing the Store

Options the building commands share #

build, test, run, query, package, publish, and sources take the same options for how they build:

OptionDoesRead
--jobsLimits how many programs this build runs at once.Targets and Steps, Sharing the Machine
--evaluatingLimits how many targets this build evaluates at once.Sharing the Machine
--platformBuilds for another platform.Building for Another Platform
--profileChooses the keychain's profile.Using Secrets
--rebuildRuns every step, reusing nothing from the store.Reuse and the Store
--check-reproducibleRuns every step twice and compares the outputs.Checking That a Build Is Reproducible
--strictBuilds as a release does.Hermetic and Strict Builds
--fail-fastStops the build at the first target that fails.Naming Targets
--no-dynamicFails a target that waits for a step's result.Targets and Steps
--traceWrites a timeline of the build.Profiling a Build
--gcsl-profileWrites a profile of the build's GCSL code.Profiling a Build
--remote-cache, --remote-instance, --remote-headerLooks for steps in a remote cache.Sharing a Remote Cache
--remote-uploadWrites the steps a build records to the remote cache.Sharing a Remote Cache

Definition Types and Attributes

Pekit / Reference

GCSL's prelude declares the definition types and attributes that build files use. Plain GCSL runs them as ordinary calls; pekit gives them their meaning as a build system. This page lists what each means to pekit. GCSL's Attributes and Definition Types and Metadata pages describe them as language features.

Definition types #

Each definition type declares a kind of target, which one command acts on:

Definition typeDeclaresIts body givesCommand
buildSomething to build.Any value: a file, a directory, or a record or list of them.pekit build
testA check. Its body is a step, unless marked #[hermetic(false)].Nothing. The test passes if the body succeeds.pekit test
packageA package of any format.A version and the files it installs under /usr.pekit package, pekit publish, pekit release
scriptA task you run by hand. Only a script can call a script.Any value.pekit run
Toolchain::<kind>A toolchain of a kind, to register in pekitconf.Its platforms and the files it provides.None; libraries ask for it.

A definition can declare parameters with defaults, as def test runs(prog: File = build app()). The defaults are worked out where the definition is called, outside any step, so a test is given what it tests.

Attributes #

These attributes change how pekit runs a function. Put them on the lines before a fn or def:

AttributeMeans to pekit
#[hermetic]A call of the function from a target's code is a step: run in a sandbox, and its result kept in the store. #[hermetic(false)] turns this off, as for a test that needs the network.
#[retry(n)]A step that fails runs again from the start, up to n more times. One that passes only on a retry is reported as flaky.
#[timeout(limit)]A step that runs longer than limit, such as 5m, fails. The limit covers all its attempts together.
#[device("kvm")]The step's sandbox has /dev/kvm, where the machine has it. It doesn't key the step.
#[scratch]The step has a directory at /pekit-scratch that pekit keeps between its runs. It doesn't key the step.
#[track_caller]An error in the function's body is reported where it was called.

#[retry], #[timeout], and #[track_caller] mean the same in plain GCSL. #[hermetic], #[device], and #[scratch] mean nothing to plain GCSL, which runs such a call at once, as any call.

Paths in a Step

Pekit / Reference

A step's sandbox has the same layout on every machine and in every checkout. This table lists each path a step can have, in the order a step is likely to use them. Step Sandboxes explains why the layout is as it is.

PathHoldsWritableThere when
/w/<path>A workspace file or directory the step was given, at its path in the workspace.NoThe step was given it.
/w/.gcsl/libraries/<library>/A library's own files the step was given.NoThe step was given one.
/pekit-out/.steps/<function>/<identity>/The step's own directory, where its programs start and its outputs go.YesAlways.
/pekit-out/<path>Another step's output the step was given.NoThe step was given it.
/pekit-out/.fetch/<sha256>/<name>A fetched file the step was given.NoThe step was given it.
/pekit-out/.unpack/<key>/An unpacked archive the step was given.NoThe step was given it.
/pekit-out/.git/<key>/<name>/A git commit's files the step was given.NoThe step was given them.
/tmpAn empty directory of the step's own.YesAlways.
/pekit-scratchA directory pekit keeps between the step's runs.YesThe step is marked #[scratch].
/pekit-secrets/<profile>/<name>A secret file.NoThe step was given the secret.
/usr, /bin, /lib, /lib64, /sbinThe host's own programs and libraries.NoThe build isn't strict.
/etc/alternatives, /etc/ld.so.cacheWhat the host's programs need to start.NoThe build isn't strict.
/etc/passwd, /etc/groupA fixed user database of root, pekit and nobody, the same in every step.NoAlways.
/devnull, zero, full, random, urandom, tty, and the standard streams.Yes, as devices allowAlways.
/dev/kvmThe machine's KVM device.YesThe step is marked #[device("kvm")] and the machine has KVM.
/procThe step's own processes.NoAlways.

A program the step runs starts in the step's own directory, with PATH set to /usr/bin:/bin:/usr/sbin:/sbin unless its exec sets one. It runs as the user pekit, number 1000, with LOGNAME and USER set to pekit unless its exec sets them. pekit's home, /nonexistent, isn't there.

1.1 Overview

Pekit / Pekit TRM / Introduction

pekit is a build system that embeds GCSL. It loads a workspace of GCSL files, evaluates the definitions it is asked for in GCSL's graph mode, and runs each call of a function marked #[hermetic] as a step: a unit of work run in a bubblewrap sandbox holding only its inputs, keyed by those inputs, and recorded in a content-addressed store. It is one Rust crate, pekit, with the pekit command as its only executable.

1.1.1 What is unusual about it #

Three decisions shape the implementation more than any other.

The build language is a general programming language, evaluated incrementally. A target's code is not a declaration that pekit reads and then plans from. It is a GCSL program that pekit evaluates as a unit: the program runs until it needs a result pekit has not given it, stops, and runs again from where it stopped once the result is given. A call of a hermetic function does not run where it is made; GCSL records it as a node of an action graph, and the program carries on with a hole where the result will be. So a target's code learns every step it can reach before any runs, and still decides what to build next from what an earlier step made. One thread evaluates every unit; what runs in parallel is the programs steps run, on a pool of threads.

Every path is in one logical layout. The workspace is at /w and every output is under /pekit-out, in GCSL values, in keys, and in every sandbox, whatever the host's paths are. A step's output directory is named by a digest of what the step is, not by the target that reached it. So the same call is the same step, at the same paths, in every build, checkout, and machine of a platform, and two targets that make it share it.

Steps are keyed by what they read, and so are the programs inside them. A step's key holds the contents of every file it is given, and of the GCSL contexts only those it read as it ran. A step that runs again, because one input changed, runs its programs against keys of their own: each program a step runs is recorded by what it can see, and a program that sees what it saw before is not run, its writes put back from the store.

1.1.2 The rest of this manual #

Loading a Workspace describes how pekit reads and checks a workspace and its libraries. Evaluation describes how targets become steps, and Steps how steps are named, keyed, and recorded. Sandboxes and The Store describe where steps run and what is kept. Failure Modes collects what goes wrong.

1.2 What This Manual Covers

Pekit / Pekit TRM / Introduction

This manual describes the pekit crate in pekit's repository, and the behavior of the pekit command built from it. It covers the engine's state, its keys and on-disk formats, its concurrency, its limits, and its failure behavior, with the reasoning behind its design where the reasoning is the implementation's own.

A manual's authority comes from the software. Where this manual and the source disagree, the source is right and the manual is stale. Nothing here is a promise about a later version: the encodings of keys, records, and trees change whenever the implementation needs them to, and old records are then not found.

1.2.1 What is covered elsewhere #

These documents hold what this manual leaves out:

SubjectWhere
Using pekit: commands, workflows, and conceptsThe other topics of this product, starting at Pekit
Every command, option, exit status, environment variable, and filepekit(1)
The lock file's formatpekit.lock(5)
The GCSL language, its standard library, and graph modeThe GCSL documentation, gcsl(5), and gcsl-stdlib(3)
What a library such as gcc or rust doesThe library's own README and source
Design history, and decisions made and changedThe task records of the work that produced them

Where this manual names a function or type of the source, such as Store::put_tree, it does so to help a reader find the implementation. The names are not an interface.

1.3 Terminology

Pekit / Pekit TRM / Introduction

The terms in this manual have these meanings. GCSL's own terms, such as context, effect, and definition type, have the meanings GCSL's documentation gives them.

TermMeaning
BlobA file's contents in the store, named by their SHA-256 digest.
CompositionA directory a step makes with fs.compose or fs.compose_dir, sealed once made.
EffectA built-in call that touches the world, such as exec or fs.write, run as a job on the pool.
Execution platformThe machine steps run on: the machine pekit runs on, named as <arch>-<os>.
ExposureWriting an output into pekit-out/ on the host, once something that is not hermetic might read it there.
Host snapshotThe host's system directories that steps see outside a strict build, and the fingerprint that identifies them.
Host viewThe effect context of a target's own code: the host, with the logical layout mapped onto it.
IdentityA 64-bit digest of what a step is, apart from its inputs' contents, naming its output directory.
Logical layoutThe paths every GCSL value and sandbox uses: /w for the workspace, /pekit-out for outputs.
ManifestFor a step's base receipt, every set of contexts a run of it has read.
Materialized treeA store tree made once as a directory of links to its blobs, for steps to mount.
PoolThe threads, --jobs of them, that run effects and pekit's own work for steps.
Program recordThe record of one program a step ran, keyed by what the program could see.
ReceiptThe SHA-256 key of a step: everything that can change what it gives.
RecordWhat a step gave, kept in the store under its receipt.
Scratch directoryA directory kept between a step's runs for a step marked #[scratch].
Staging directoryThe directory on the host that a step's sandbox is made of.
StepA call of a hermetic function made by a target's code, run in a sandbox and recorded.
StoreThe content-addressed store under the cache directory, shared by every workspace and process on the machine.
TargetA definition named on the command line, evaluated as a unit.
TokenThe 16 random hexadecimal digits a process names its temporary files and directories with.
TreeA directory in the store, kept as a blob of its sorted entries in a canonical encoding.
UnitA GCSL evaluation that stops at each result it needs and runs again from there: a target's, or a step's body.

1.4 Compatibility

Pekit / Pekit TRM / Introduction

pekit runs on Linux. It needs:

  • bwrap, bubblewrap, on PATH, for every step and every program a target's code runs, and unprivileged user namespaces for it to make. pekit never nests one bubblewrap inside another, so a host that forbids that, such as Ubuntu, is supported.
  • git, on PATH, for pekit lock, for putting back pinned libraries, for fetch_git, and for pekit release.
  • A file system for the cache directory that supports hard links.
  • A kernel that lets bubblewrap mount an overlay in an unprivileged user namespace, for a Dir.sandbox of a composition, which pekit makes with bubblewrap's --overlay.

The execution platform is the machine pekit runs on, named as Rust names architectures and operating systems: x86_64-linux, aarch64-linux. Steps never run on another machine.

1.4.1 What is shared #

The store is shared by every workspace and every pekit process of the same user on a machine. Its records are found only by the receipts of the same encoding: a version of pekit that changes how receipts, identities, trees, or records are encoded finds none of the old ones, and runs the steps again. Nothing is migrated.

A step's receipt names the execution platform, and outside a strict build the host snapshot's fingerprint. So a store copied between machines reuses only what the machines agree on: a strict build's steps on any machine of the platform, and others only on a machine with the same installed packages.

A step given a secret is keyed by an identity hashed with the machine's own key, so it is reused only on the machine that recorded it.

2.1 Finding and Checking the Workspace

Pekit / Pekit TRM / Loading a Workspace

Every command but pekit clean starts by loading the workspace (load). Loading finds the root, reads the GCSL sources, and checks them. Nothing is evaluated until every source checks.

2.1.1 The root #

The workspace's root is the nearest directory, from the current directory upward, that holds a workspace.gcsl (gcsl_disk::find_root). With none, the command fails with an error that names the directory it searched from. The root is canonicalized, so a workspace reached through a symbolic link is the same workspace as one reached directly.

2.1.2 The sources #

The sources are read as the gcsl command reads them (gcsl_disk::read_workspace): every .gcsl file under the root, except under a hidden directory, a hidden file, and any directory below the root that holds its own workspace.gcsl. A nested workspace is never part of the outer one.

Each library the sources import is read too, with every library those import, from where Libraries and the Lock says. GCSL's standard modules are compiled into pekit and come first in the order of inputs, so that a diagnostic names its file by its input number correctly.

2.1.3 Checking #

The sources are checked with GCSL's standard library (gcsl::workspace::check_with_standard), rooted at /w, the workspace's place in the logical layout. So fileroot.workspace is /w, and fileroot.this in a directory app is /w/app. A diagnostic is shown against its file, named relative to the root, and the command fails with status 1 if any is an error.

Two rules are pekit's own, checked once GCSL's checking has passed:

  • A build and a script of the same name in the same directory are an error, since pekit run NAME could mean either.
  • A build, test, or package that can reach a call of a script fails to check. The prelude's script definition type reads the context ^script_session, which has no default and which only pekit run binds, so GCSL reports "context script_session has no value in this definition".

2.1.4 A workspace checked afresh #

A build leaves state in the checked workspace: each file's top level and each memoized call's result, which name what it fetched, unpacked, and built. A second build in the same process, --check-reproducible's second pass or a release's publishing pass, has to make those itself. So every build after the first checks the workspace again from the same sources (Loaded::ready), rather than reusing the evaluated one.

2.1.5 Which files changed #

pekit tells a workspace file by its contents. To avoid reading every file on every build, the store keeps, for each workspace root, the stamp of each file it read: its device and inode, size, mode, and modification and change times, with the digest of its contents and whether it is executable. They are in the store's seen/ directory, in a file named by the SHA-256 of the root's path. The file is binary, not JSON, because a large workspace has a hundred thousand stamps and every build reads them all. Stamps that an older pekit kept as JSON are read once and replaced.

A file whose stamp matches is taken to have the recorded digest, unread. A file whose stamp differs, or which is new, is read and hashed, and so is a file whose blob is gone from the store (see Blobs and Trees). A stamp taken in the same tick of the file system's clock as the build began, or later, isn't trusted: a file changed again within that tick would keep the same times. The next build reads such a file again. Stamps of files that are gone are dropped as the build ends. The file is written again only if its stamps changed.

The workspace's path is noted beside its stamps, in seen/<digest>.root. A build that ends with no other pekit using the store removes the stamps of each workspace whose directory is gone. Stamps from a pekit that noted no path are removed once they are 30 days unchanged.

2.1.6 Files that change as they are read #

A workspace file or directory that a step is given can be changing as pekit reads it, as a package repository is while a package is published into it. pekit reads a directory one entry at a time, so it could read part of it before a change and part after. It could fail on an entry that was listed and is gone, or read a ref without the manifest it names.

So pekit keeps what it saw: the names each directory listed, and the stamp of each file and link. Once it has read the directory, it looks again. If anything differs, or is gone, the directory changed as it was read. pekit discards what it read, even if the read failed because of the change, and reads it again after a pause. The pause starts at 50 milliseconds and doubles each time, up to 2 seconds. A file is read the same way, by its stamp. A read that fails while nothing changed fails the build.

A directory still changing after 30 seconds, and after at least five reads, fails the build with "PATH kept changing while it was read, HOST-PATH last: wait for whatever is writing there to finish, then build again". pekit never gives a step a mix of before and after.

A file changed in place within one tick of the file system's clock, to the same size, after pekit read it, keeps its stamp, so pekit cannot see that change. A writer that renames each file into place, as ppk does, is always seen.

2.2 Libraries and the Lock

Pekit / Pekit TRM / Loading a Workspace

A library is a directory of GCSL files named by an import path, such as github.com/gcslib/gcc. pekit finds, places, and pins libraries itself; GCSL only reads the sources it is given.

2.2.1 Where a library is found #

A library's directory is looked for in each directory of $GCSL_LIBRARY_PATH, in order, then in .gcsl/libraries/ at the workspace's root, and the first found is used. Its sources are the .gcsl files directly in that directory.

Wherever a library was found, its sources are given to GCSL at /w/.gcsl/libraries/<path>/ in the logical layout (gcsl::SourceFile::with_dir). A relative path in a library's code therefore names the same logical path in every workspace. To the rest of the engine, a library's files are workspace files under that path: they are hashed, put into the store, and staged as any are. Only where one is on the host differs, for a library found through $GCSL_LIBRARY_PATH (Libraries::host).

So a step a library makes has the same identity, the same receipt for the same library contents, and the same outputs in every workspace, whether the library came from a checkout or from the lock.

2.2.2 The lock #

pekit.lock is JSON at the workspace's root, described in pekit.lock(5): sources, each a prefix of import paths with a git repository, a directory in it, and a revision; and libraries, each pinned by its path, repository, directory, commit, and the digest of its exported tree.

A library's source is the first source whose prefix is its path or a part of its path ending before a /. A library no source covers is given one by the convention of Go's modules: the first three parts of its path, HOST/OWNER/REPO, are the prefix, https://HOST/OWNER/REPO the repository, its root the directory, and HEAD the revision. The source is added to the lock.

2.2.3 Pinning #

pekit lock reads the import paths of the workspace's sources, without checking them, and works through them and every library they import, transitively:

  1. A library the lock pins, without --update, is exported again at its pinned commit.
  2. Any other is fetched from its source: its repository's bare clone is made or fetched, the source's revision resolved to a commit with git rev-parse, and the library exported at that commit.
  3. Each exported library's tree is put into the store, and its digest recorded as the pin's tree.

Each pin that changed is reported. Each library the lock pinned that nothing imports any more is dropped, and its directory under .gcsl/libraries/ removed. A library's directory can be inside another library's, as example.org/sdk/tools is inside example.org/sdk. A dropped library's directory that is inside a library still pinned is that library's, so it stays. A library still pinned whose directory was inside the one removed is exported again. The lock is written with its libraries sorted by path.

Two libraries whose directories nest, one's directory inside the other's, are pinned at one commit or not at all (lock::nested). The outer library's export holds the inner one's directory, so the two agree only if both have one repository and commit, and the inner library's directory in the repository is the outer one's followed by the rest of its path. Otherwise each export replaces the other's files, and whichever is exported last wins. Before each library is exported, its pin is compared with every pin made so far. A pin that disagrees fails the command, naming both pins, and the lock is not written. Libraries exported before the failure stay as exported, so the next build can find the outer library differing from its pin.

A library is exported with git archive of the commit's directory, into .gcsl/libraries/<path>/, replacing what was there. Repositories are bare clones under the cache directory's git/, fetched only to resolve a revision or to get a pinned commit the clone lacks. Git runs as the git program found on PATH.

Each successful export records its commit and tree digest, by import path, in .gcsl/pekit-exports.json. This local JSON file is outside every library tree and is not committed. The export is unpacked and hashed in a temporary directory beside its destination before replacing it. The old directory is renamed aside, the complete new directory renamed into place, and the old one removed. Only then is the record written through a temporary file and renamed into place. An interrupted replacement cannot record a half-export as the new one.

2.2.4 Putting back and checking #

Before loading, build, test, run, query, package, and publish restore the lock's libraries (lock::restore):

  • Every pair of pins is compared, as pinning compares them, before anything is exported. Two nested libraries pinned at two commits fail the command.
  • A pinned library whose directory is missing is exported from its commit.
  • A pinned library whose directory is there is put into the store as a tree, and its digest compared with the pin's. If it matches but its record is missing or names another commit or tree, it is recorded: it is what an export would write, so it refreshes when the pin moves. If it differs but still matches pekit's export record, it is an untouched older export: it is replaced from the pinned commit and its record updated. Outer libraries are handled before libraries inside them; after an outer export, each pinned library inside it is exported and recorded at that commit too. Putting a library into the store reads only the files whose stamps changed, as with a workspace's files (see Finding the Workspace). The stamps of library files are kept apart, in seen/<digest>-libraries.stamps.
  • A differing library whose tree does not match its record, or has no record, is left alone and reported with a recovery hint: preserve any edits, remove .gcsl/libraries/<path>/, and pekit puts back the pin.

Outside a strict build, each difference is a warning, and the build goes on with the library as it is. Refreshing an untouched older export happens outside strict builds too. An export made by an older pekit has no record; if it matches the pin it is recorded then, and if it already differs it needs removing once.

A strict build fails, listing every problem, if any of these holds (lock::check_strict):

  • The workspace imports a library and has no pekit.lock.
  • A library it loaded isn't pinned.
  • A pinned library differs from its pin.
  • $GCSL_LIBRARY_PATH is set and not empty.

2.2.5 What the lock tells a build #

pekit sets the libraries module's pinned_libraries context, where the workspace declares it, to the lock's libraries, each with its path, repository, directory, and commit. A library can compare these with what it takes another way, as the gcslib rust library compares a git crate's commit in Cargo.lock with the commit a library of the same repository is pinned at.

2.3 Selecting Targets

Pekit / Pekit TRM / Loading a Workspace

A target is a definition made with a definition type: build hello is the definition hello of the definition type build. The command decides the definition type: build for pekit build, test for pekit test, package for pekit package, pekit publish, and pekit release, the --kind option's for pekit query, and script, or else build, for pekit run. Selection is target::select.

2.3.1 Names #

A name is a definition's path alone, hello, or qualified by its directory relative to the root, app/hello, with /hello for one in the root directory. A path alone resolves in order:

  1. The one definition of that path in the workspace, wherever pekit runs from.
  2. Of several, the one in the directory pekit runs from.
  3. Otherwise none. The command fails with "build hello is defined in several places", listing each by its qualified name.

A qualified name means the definition in that directory, or none. A name that matches nothing fails with "no build is named hello", with the closest names there are.

2.3.2 Globs #

A name with * in it is a glob. It selects every definition of the definition type that it matches, relative to the directory pekit runs from, or to the root if it starts with /. Its last part matches the definition's name, and the parts before it match directories:

  • * in a part matches any run of characters within the part.
  • ** matches any number of directories, including none. As the last part, it matches every name in them too.
  • . matches the directory itself, and every name in it.

So app/* is every definition of app, pkgs/*/* every definition of a directory directly below pkgs, and ** every definition at or below the current directory.

A glob matches the workspace's directories alone. A library's definitions are in no directory of the workspace, so no glob selects them, whatever their names. A library's tests therefore never run in pekit test of a workspace that imports it.

pekit test, pekit package, and pekit query rdeps select ** when given no names.

2.3.3 Several targets #

What several names and globs select is selected once, and the targets are sorted by their qualified names. They are evaluated as one build, against one action graph: each target is a unit of its own, and a step two units reach is one node, run once. Reports come in the sorted order.

For pekit run, a definition of one name in one directory is a script or a build, never both, by the check of Finding and Checking the Workspace. Of one name in two directories, pekit run asks for the directory, as any command does.

2.4 Root Contexts

Pekit / Pekit TRM / Loading a Workspace

pekit evaluates every target as if wrapped in a with block that binds some GCSL contexts (root_contexts and root_fields). It binds a context only where the workspace declares it: where some loaded module, the standard library's included, declares the context. A workspace that never imports keychain, for example, has no ^keychain_profile to bind.

ContextModuleValue
host_platformpreludeThe execution platform, as {arch; os}.
platformpreludeThe platform --platform names, if given. Otherwise unbound, and its default is ^host_platform.
toolchainstoolchainpekitconf.toolchains of workspace.gcsl, if it has the field.
keychain_keyskeychainpekitconf.keychain of workspace.gcsl, if it has the field.
keychain_profilekeychainThe --profile option's value, dev by default, or release in pekit release.
packagerspackagingpekitconf.packagers of workspace.gcsl, if it has the field.
pinned_librarieslibrariesThe libraries pekit.lock pins, each as {commit; dir; git; path}.
script_sessionpreludeFor pekit run of a script only: {args}, the words after the script's name.

The fields of pekitconf are evaluated as part of workspace.gcsl, in GCSL, so a mistake in one is a check error of that file. A pekitconf without one of these fields leaves the context at its default: the toolchain module's [Toolchain::C system_c], and an empty keychain and packager list.

toolchains, keychain, packagers, contexts, and require_strict are the only fields pekit reads. require_strict sets no context, and is read before the build, as Strict and Reproducible Builds describes. Before it prepares any target, pekit fails the build if:

  • pekitconf is not a record of named fields;
  • it has any other field, which a different pekit might read but this one would ignore; or
  • it has toolchains, keychain, or packagers but no loaded file declares the context the field sets, which import toolchain, import keychain, or import packaging would.

2.4.1 Contexts the workspace sets #

pekitconf.contexts sets any other context, each of its fields the context of its name, as Setting a Context for the Whole Workspace shows. pekit binds them in the same with as the fields above, so a target's own with binds over them. Before it prepares any target, pekit fails the build if:

  • contexts is not a record whose fields name contexts, such as a record type with a rest-field;
  • a field names a context that no loaded file declares; or
  • a field names one of the contexts in the table above, which pekit sets itself.

GCSL checks each value against its context's type, as it checks a with binding, so a value of another type is a check error. Each value is evaluated as part of workspace.gcsl, in the declared defaults of every context, so it can't depend on a target's ^platform.

2.4.2 Contexts and keys #

Binding a context changes no step that doesn't read it. A step is keyed by the contexts it read as it ran, as Receipts describes, so registering another toolchain reruns no step that didn't read ^toolchains. A library that resolves its toolchain in a parameter default reads ^toolchains outside the step, and gives the step the toolchain itself, which keys it as an argument. ^script_session has no default, so a step that could read it is one only a script can reach.

3.1 Units and the Action Graph

Pekit / Pekit TRM / Evaluation

pekit evaluates every target in GCSL's graph mode, against one action graph for the whole build. GCSL's Running Steps for a Host page describes graph mode; this article describes what pekit does with it.

3.1.1 Prepared calls #

Each selected target is a prepared call of its definition: build hello(), test greeting(), or script deploy(). Two commands wrap the call in a function of the standard packaging module, since pekit can't call a GCSL function value from outside GCSL:

  • pekit package prepares packaging.pack(package NAME()), which packs the package with each of ^packagers.
  • pekit publish and pekit release prepare packaging.publish(package NAME(), "STORE"). The store is an argument, not a context, so that publishing into a second store keys no step differently.

A prepared call binds its own definition as a reference's call does (GCSL's run_prepared), so the steps it makes are named under that definition. Each prepared call is evaluated as a unit of its own.

3.1.2 Steps and other calls #

In graph mode, a call of a function whose attributes defer it is not run where it is made. GCSL adds it to the graph as a node, and the calling code goes on with a hole where its result will be. pekit takes a deferred node as a step if one of its function's attributes is hermetic and not hermetic(false).

Inside a step's own unit, a deferred call is not a node: it runs inline, as part of the step. So only a call that a target's code makes, directly or through any number of ordinary functions, becomes a step.

Every effect, a built-in that touches the world, is a node too, carrying its position in program order. pekit runs a step's effects in the step's sandbox, in the step's program order, and a target's own effects on the host view, one at a time, in the target's program order. A target's effects whose order cannot matter run out of order, as Order describes.

3.1.3 Stopping and resuming #

A unit runs until it ends or until it needs a node's result that pekit hasn't given: a step's value it reads, an effect's result, or a memoized call another unit is computing. It then stops, and GCSL keeps its position as data. Once pekit gives the result, the unit resumes from where it stopped, without running any code twice.

A unit that ends with a value whose holes are steps not yet run is done evaluating: its value is complete once those steps give their results. A target is built when its value has no holes.

Within a unit, GCSL schedules its own branches, and runs everything it can before stopping. Where several branches fail, the failure reported is the one a sequential run would have reached first.

3.1.4 The build loop #

The engine repeats, until every target is done (build_all_observed):

  1. Run each unit that can progress: one whose results are given.
  2. For each step node a unit needs whose inputs are given, look its receipt up in the store. A hit gives the step's recorded result. A miss stages the step's sandbox on the pool, then runs the step's body as a unit of its own.
  3. Queue each ready effect of a step's unit on the pool, and run each target's next effect in program order.
  4. Take each finished piece of work from the pool, and give its result to the node that waited for it.

A memoized call or a lazy that two units need is computed by the first to reach it, and the other waits for it. Once another unit waits for it, the target's own effects inside it don't wait for the target's earlier work outside it, so they can reach the system out of the target's program order. They still run one at a time. GCSL's Running Steps for a Host page explains why. A target that --no-dynamic fails, or that a query stops, while its unit waits gives up the shared work it was computing, and a target waiting for that work computes it itself.

If no unit can progress and no work is running, the units wait for each other. When they wait in a circle through memoized calls or lazy values, some call needs its own result, and the build fails with "this call depends on its own result". Each call in the circle is labeled with the target or step that needs it and the one computing it. Any other such build fails with "the build's targets and steps wait for each other's shared results".

3.1.5 Naming steps under definitions #

A step is reported, and its outputs linked, under the target whose unit first met it, or under the target of the step that met it. Its identity and directory don't depend on that, as Identities describes. A step made inside a build called from another target, a test, or a script is made under the innermost definition around the call (GCSL's Workspace::step_definition), so build lib() called anywhere makes the steps pekit build lib makes.

3.2 The Pool

Pekit / Pekit TRM / Evaluation

GCSL's values are reference-counted for one thread, so one thread evaluates every unit of a build. What runs in parallel is work that needs no GCSL value: programs, file-system effects, and pekit's own handling of whole trees. That work runs on the pool (Pool): two fixed sets of threads, each taking work from a queue of its own.

3.2.1 Its size #

The pool has --jobs threads for effects, by default as many as the machine has processors. A running program holds its thread until it ends, so --jobs is the most programs a build runs at once. A step's program also waits on its thread for the machine's budget, which bounds every build's programs together (see The Machine's Budget). A step's own make or Cargo borrows the budget's free jobs through its jobserver.

The pool has as many threads again for the rest of its work, so that programs waiting for the budget hold up none of it.

3.2.2 Kinds of work #

Each piece of work (Work) is one of these:

  • An effect of a unit, with its effect context and its deadline: a step's effect in the step's sandbox, or a target's effect on the host view.
  • A fetch, answered from the store or downloaded.
  • A read of an output by a target's code, answered from the store's tree of it while the output isn't exposed.
  • Staging a step's sandbox before its body runs.
  • Keeping a step's result: putting every file and directory it names into the store, once it has given one.
  • A program a step runs whose result can be recorded, with the hashing and placing of trees that finding or recording it takes. See Program Records.

Staging and keeping place or hash whole trees, often of tens of thousands of files, so they run on the pool beside the programs, never on the thread that evaluates. A step's unit runs once its sandbox is staged, and the step is recorded once its files are kept.

Each piece of work reports what it came to, with the thread that ran it and when it started and ended, for the build's events, and the store's files it used, for eviction.

3.2.3 Order #

Effects of different steps run in any order and at the same time. A step's own effects run in its program order, one after another, since they share the step's sandbox. A target's own effects run one at a time in the target's program order, since they share the host.

The host view isolates some of the target's effects (HostView::isolates). GCSL makes an isolated effect as soon as the code reaches it and has its arguments, without waiting for earlier effects in program order (see Code that waits). The isolated effects are:

  • A fetch or an unpacking, which pekit answers by content.
  • file.read and dir.files. Each waits only for the File or Dir it reads. file and dir are not effects in graph mode, so outside a strict build such a read can run before a program or write of the target's that is earlier in program order, and find what was there before it.
  • In a strict build, fs.exists and fs.read. Each is given only a path, so outside a strict build it waits for the target's earlier programs and writes, which can change what is at that path.

A strict build refuses a target's programs and writes, so nothing the target does changes what any of these reads finds.

One more exception holds for effects that are not isolated: those inside a memoised call or lazy that another target or step is waiting for. GCSL then orders them only after earlier work inside that call, not after the target's other earlier work, still one at a time per target, so that two targets that need each other's shared calls don't wait for each other (see Code that waits). Such a call's effects already reach the host only once, in whichever target got to the call first, so the other targets never saw them in their own order anyway.

3.3 A Target's Own Effects

Pekit / Pekit TRM / Evaluation

A target's own code is not hermetic. Its effects run on the host view (HostView), one at a time in program order, every time the code runs. Fetches, unpacks and some reads are isolated and run out of order, as Order describes. None of them is cached.

3.3.1 The host view #

The host view maps the logical layout onto the host. GCSL's own file-system work, such as fs.read or dir.files(), maps /w to the workspace's root and /pekit-out to its output directory, and any other absolute path to itself. A relative path given to file or dir resolves against the directory of the file it is written in, never the working directory. The fs built-ins, such as fs.exists and fs.read, take only absolute paths: GCSL refuses a relative one.

A program a target runs runs under bubblewrap, with the host's own directories bound where they are and the workspace and outputs bound at /w and /pekit-out, so that it sees the paths GCSL code gave it. It has the network and the environment pekit was run with. Its working directory is the target's directory under /w. Because it runs under bubblewrap, a program can't gain privileges: sudo fails in one. Temporary directories GCSL makes for a target are under the cache directory, never /tmp.

3.3.2 Effects pekit answers itself #

pekit answers some effects itself rather than running them as plain GCSL would:

  • fetch. From the store by the pinned digest, or downloaded on the host and kept only if its digest matches. See Fetches, Unpacks, and Git Commits.
  • fetch_git. From the store, or fetched into a bare clone and checked out.
  • archive.unpack. Unpacked by pekit itself, without tar, and kept.
  • keychain.string and keychain.file. From the workspace's keychain configuration or the environment. See Secrets.
  • A read of an output. dir.files() and file.read() of a path inside a build's output are answered from the store's tree of it until a target's own effect has run a program or written. See Exposure.

fetch, fetch_git, and the keychain are refused inside a step, each with an error saying to resolve it in a parameter default or in the caller and pass the result in.

3.3.3 What a strict build refuses #

Under --strict, a target's own effect is refused unless it is one of these:

  • fetch, fetch_git, archive.unpack, keychain.string, or keychain.file
  • A read, fs.exists, fs.read, file, file.read, dir, or dir.files, of a path at or under /w or /pekit-out

pekit judges a path once each . is left out and each .. has taken the component before it, so /w/../etc is /etc. It follows no symbolic link, so a link in the workspace to a directory outside it, such as a package repository, can be read. A read elsewhere fails with "a strict build reads only the workspace and the build's outputs, and this reads PATH", PATH as judged. A relative path is left to GCSL, which refuses it. Any other effect fails with "a strict build refuses a target's own NAME: a release's targets run programs and write files only in steps". Each failure is reported where the target's code made the effect.

The host's toolchains, such as system_c, call which to find the host's tools, which a strict build refuses, so they fail a strict build where their definition runs.

3.3.4 Dynamic dependencies #

A target's unit that stops for a step's result has a dynamic dependency: what it builds after depends on what the step made. The step runs, its result is given, and the unit resumes.

Under --no-dynamic, a target whose unit stops for a step's result fails there instead. Only a stop for a step counts. A stop for an effect of the target's own, such as a fetch, is part of evaluating it.

3.4 The Machine's Budget

Pekit / Pekit TRM / Evaluation

Every pekit process on a machine shares one budget (Budget): at most jobs programs at once, expected to use at most memory bytes at once. Nothing runs to keep it. It's a directory of lock files, each held with flock by whatever uses it, so a process that ends, however it ends, lets go of everything it held.

3.4.1 Its limits #

Each limit is read, in order of precedence, from:

  1. the environment: PEKIT_MACHINE_JOBS, PEKIT_MACHINE_MEMORY, and PEKIT_MACHINE_UNSEEN;
  2. machine.conf in the configuration directory, $XDG_CONFIG_HOME/pekit or ~/.config/pekit, a line KEY = VALUE for each of jobs, memory, and unseen, with # starting a comment;
  3. the machine: a job for each processor, half of MemTotal in /proc/meminfo, and 1 GiB.

jobs is a count above 0. memory and unseen are sizes, written as PEKIT_CACHE_LIMIT's are, above 0. machine.conf can also set cache_limit, evaluating and keep_free, which are not limits of the budget but are read the same way, after PEKIT_CACHE_LIMIT, PEKIT_EVALUATING and PEKIT_KEEP_FREE. Anything else, or a line of machine.conf that sets nothing it knows, fails every command that builds.

3.4.2 Its files #

The budget's directory is pekit/budget under $XDG_RUNTIME_DIR, which the system empties when the user's last session ends, or budget in the cache directory where that's unset or can't be used. It holds:

FileHeld by
job-<n>, for n below jobsA running program, exclusively, or a job a program's jobserver lent.
memory-<n>, for n below memory / 256 MiBA running program, exclusively, a file for each 256 MiB it's expected to use.
waitingEvery process with a program waiting for the budget, shared.
gateA program that has waited 2 seconds, exclusively, until it starts; every other process, shared, while it tries to start one.
fifo-<pid>-<n>A program's jobserver, made by its meter and removed when it ends.

Each process uses the files numbered below its own limits. Processes that read different limits share the larger.

3.4.3 Waiting for the budget #

A program of a step takes its job and its memory on the pool's thread, before it runs (Budget::admit). These programs wait:

  • exec, exec_live, and exec_secret;
  • a sandbox's exec;

unless interactive. A program found in the store doesn't run, and takes nothing. A target's own effects, which run one at a time, don't wait.

A process's programs wait in the order they asked, and only the first of them tries the files. It tries to hold, without waiting, a job-<n> file and as many memory-<n> files as it needs, at least one and at most all of them. It holds all of them or none, so no two programs wait for each other. While it can't, it holds waiting, and tries again, at first after 2 ms and then less often, up to every 50 ms, or as soon as a program of its process ends.

Once it has waited 2 seconds, it holds gate exclusively, waiting for it. No program of another process starts while it does, since each holds gate shared while it tries, so the program starts as soon as running programs end, however many smaller programs would otherwise start first.

A budget whose files can't be opened lets the program run at once: the budget paces programs, and never fails one.

The time a program waits is added to its step's deadline and left out of its cost, as the time its staging took is. Programs wait on the pool's threads for effects, so they hold up none of the engine's own work. See The Pool.

3.4.4 Estimates #

A program of a step is expected to use a quarter more than the largest of its kept peaks, each in bytes (Budget::estimate):

  1. its own, kept under the step's name <function>/<identity> and the program's file name;
  2. otherwise its kind's, kept under the step's function and the program's file name, by every step of that function;
  3. otherwise unseen, or half as much again for a program named rustc (Budget::unseen).

Peaks are kept in the state directory under peaks/: a file for each, named by a SHA-256 of the names it's kept under, the kind's prefixed kind-, holding the last four peaks, oldest first, a decimal number of bytes on each line. Each file is replaced whole. Peaks key nothing.

3.4.5 Metering #

Each program of a step runs under pekit __meter, outside its sandbox, which runs the program's bubblewrap and waits for it. The meter:

  • dies with the pool's thread that started it, by PR_SET_PDEATHSIG, and exits at once if that has already ended;
  • is a subreaper, so that the process bubblewrap starts as the sandbox's init, which bubblewrap's own process doesn't wait for, is reparented to it and waited for. Its peak, the largest of the program's processes', then reaches the meter;
  • waits for what the program left, its init, for 5 seconds at most;
  • keeps ru_maxrss of getrusage(RUSAGE_CHILDREN) as the program's peak, for the step and its kind;
  • exits with the program's status, or 128 and the signal's number for a program a signal killed, which exec reports alike.

The meter is added after the program is keyed. Neither it nor anything it adds reaches a receipt or a record.

3.4.6 Jobservers #

Each metered program is offered a GNU make jobserver. The meter makes a FIFO, fifo-<pid>-<n> in the budget's directory, and bubblewrap binds it at /dev/pekit-jobserver. MAKEFLAGS and CARGO_MAKEFLAGS are set to --jobserver-auth=fifo:/dev/pekit-jobserver, each unless the program's exec sets it. Neither has -j. GNU make reads the FIFO form from 4.4; an older make doesn't, and by its source stops with "invalid --jobserver-auth string" (not tested).

The program holds one job, which the protocol leaves implicit. Every 10 ms, the meter:

  • reads back every token the FIFO holds: tokens unread, or given back;
  • writes one back, unless a program of any process waits for the budget, since waiting is held, or a token has sat unread for 250 ms; and gives back to the budget the job of every other token it read;
  • if the FIFO held nothing, so every token it lent is the program's, lends one more, taking a free job without waiting, if one is free, no program waits, gate isn't held, it has lent fewer than jobs less one, and it isn't backing off.

A token that sat unread for 250 ms makes the meter back off before it lends again: 250 ms, doubled each time up to 4 seconds, and reset once a token is read. So a program that never reads the jobserver holds a second job for at most 250 ms at a time, less and less often. When the program ends, the meter gives back every job it lent.

4.1 Identities

Pekit / Pekit TRM / Steps

A step's identity names its output directory, /pekit-out/.steps/<function>/<identity>, as 16 hexadecimal digits: the first 64 bits of a SHA-256 (receipt::identity). Every file a step makes is under that directory, so the identity is part of every path its outputs have, and of every key those paths reach.

4.1.1 What it covers #

The identity is a digest of what the step is, encoded after the tag pekit-identity-2:

  • Its callee. The name of its code's file, its function's number in that code, and the function's captures.
  • Its arguments, as plain data. Every file and directory counts by its path alone, not its contents. The result of a step not yet given counts by that step's own name, so that a step is named before the steps it waits for have run.
  • The platform it runs on.

The contexts it was made in don't name it, so binding a context moves only the steps that read it, as their receipts say.

4.1.2 Steps that only their contexts tell apart #

GCSL makes one call made in two contexts two steps, such as one compile made through with for two platforms. Both have one identity and share one name. Whether they are one step depends on whether the step reads a context they were made in differently, and only running it says which contexts it reads. So pekit settles it as they start:

  1. The first of them to start holds the name, and is found in the store or runs, as any step is.
  2. Each of the others waits until the first is done. Then it is keyed by the contexts the first was keyed by: those its run read, or those the record it was found by was keyed by.
  3. If its receipt is the same as the first step's, it is the same step. It takes the first step's result, and is neither run nor looked up.
  4. If its receipt differs, it is another step. It reads a context they were made in with different values, or it was given the result of a step that does. It is named <identity>-<receipt>, with the first 16 hexadecimal digits of that receipt, and is found or runs there. Others with that receipt share that name in the same way.

A step that doesn't read the contexts the steps differ in therefore has one name and runs once, in whatever order evaluation meets the steps. Steps that really differ never share a name or a result. Which of them keeps the plain name still depends on which starts first, so reordering a build can rename those steps, and the steps after them.

If the first step fails, the next of the others to start holds the name instead, since what the failed step read is not known.

4.1.3 The tag's version #

The tag's version changes when what every step's sandbox holds, beyond the step's inputs, changes in a way that can change what a step gives. A new version gives every step a new identity, so no step recorded under the old sandbox is found in the store, and every step runs again once.

VersionWhat changed
1The first.
2Every step runs as user and group 1000, pekit, with a fixed /etc/passwd and /etc/group, and LOGNAME and USER set, as The Step Sandbox describes. Before, a step ran as whoever ran pekit, with no user database.

4.1.4 Why not its contents #

An identity doesn't hold its inputs' contents, so editing a source keeps every step at the same paths: the step runs again in the same directory, and gives files at the same paths. A step after it that is given a rebuilt file with the same bytes at the same path has the same receipt, and is found in the store. This is early cutoff. Naming a step by its contents would move every later step whenever an earlier one ran again, even to the same bytes.

An identity doesn't hold the target that reached the step. Two targets that make the same call make one step, and a step's paths don't change with what else is built, or in what order. A target's view of its steps, under pekit-out/<target>/<function>[.N], is a link into the step's directory, made after the build.

4.1.5 Collisions #

Two different steps with the same function and identity would share a directory. An identity is 64 bits for each function's steps, which makes that chance negligible for any number of steps a store holds.

4.2 Receipts

Pekit / Pekit TRM / Steps

A step's receipt is the SHA-256 that its record is kept under: a digest of everything that can change what the step gives (receipt::receipt). A step whose receipt the store has a record for is not run.

4.2.1 What it covers #

The receipt is a canonical encoding, after the tag pekit-receipt-3, of:

  • Its code. The path and contents' digest of every source file that makes the step's code: the file of its function and of every function it can reach, library and standard files included, in order. Any change to one of these files, a comment included, changes the receipt.
  • Its arguments and its function's captures, as plain data. A record's fields are sorted by name, a float is encoded by its bits, every NaN as one, and -0.0 as 0.0.
  • Each file it is given, by its path and the digest of its contents, and each directory by its path and its tree's digest. The path stays in the key because it reaches command lines and names outputs. An input is keyed by its contents, never by the step that made it.
  • Each secret, by its identity and whether it is revealed, never by its value.
  • Each function value among its captures or contexts, such as a registered toolchain's definition, by the name and contents of its code's file, its number in that code, and its captures.
  • The contexts it read, each by its key, with its value or a tag saying that it was unbound.
  • Its own output directory, which names the files it makes.
  • The platform it runs on. Outside a strict build, this is the execution platform with the host snapshot's fingerprint. In a strict build, it is the execution platform marked as having no host tools.

#[retry], #[timeout], #[device], and #[scratch] are not in it: they change how a step runs, never what it gives.

4.2.2 Two levels: base and manifest #

A step can't know which contexts it reads before it runs. So a step is keyed in two levels:

  1. Its base is the receipt without any context.
  2. The store keeps, under a key made from the base (pekit-manifest-1), a manifest: every set of context keys a run of a step with that base has read.

To look a step up, pekit takes each set in its manifest in turn, and makes the full receipt of the base and, for each key of the set, the value the step's context gives it, or that it is unbound. A record under that receipt is the step's result.

A step that runs is recorded under the receipt of the set its run read, and that set is merged into the manifest. Merging never removes a set.

This is sound because a run is a function of what it reads. Two runs with one base, given the same values for the contexts the first read, read the same contexts in the same order, and give the same result.

4.2.3 When a context's files are staged #

A step's sandbox holds the files of its arguments and captures from its start. A context's value can name files too, such as the registered toolchains' trees. Those are staged into the sandbox only once the step reads the context, at the read itself (StepSandbox::context_read). So a program a step runs can't reach a file of a context its receipt doesn't hold.

The files of every context a step can read are hashed when the step starts, so that they can be staged on a read.

4.3 Records

Pekit / Pekit TRM / Steps

A step that succeeds is recorded: its receipt, its result, and how long it ran. A step found in the store gives its record's result without running.

4.3.1 Keeping a result's files #

When a step's unit ends with a value, every file and directory the value names is put into the store (record::keep_files), whether or not the result can be recorded, since later steps are given them. A file becomes a blob, and a directory a tree. A directory that holds a mount point is put into the store with the mounted tree's digest, unread.

A step fails unless every file and directory its result names is one of these:

  • A file or directory in the step's own output directory
  • A file or directory it was given, or a context's file that a read staged
  • A file of /pekit-out/.fetch/ or /pekit-out/.unpack/, which are named by their contents

Any other path fails the step: another step's file at that path could otherwise stand for it.

4.3.2 What a record holds #

A record (StepRecord) is JSON in the store's records/, under its receipt's digest. It holds:

  • receipt, the digest it is kept under.
  • result, the step's value as plain data (Stored): integers, floats, booleans, strings, durations, sizes, records with their fields in order, lists, enum variants, sandboxes, and every file and directory by its path and what the store keeps of it: a file's digest, size, and whether it is executable, and a directory's tree. A string longer than 64 KiB (INLINE_TEXT), such as a program's whole output, is kept as a blob, and the record names it by digest and length (Stored::Text). This matters because a record is read whole, by every eviction too, and JSON writes some bytes as six. A record whose string blob was evicted isn't live.
  • duration_ms, how long the step ran, from the end of its staging to the end of its last attempt. Eviction weighs a record's contents by it.

Records are never evicted. A record whose contents were evicted is not live: a step whose record isn't live runs again, as if it weren't found, and records again.

4.3.3 What is never recorded #

These results are not recorded, and the step runs on every build:

  • A result that holds a secret (StoreError::Secret). A secret is never stored. Its files are still kept, so later steps are given them.
  • A result that holds a function value, which is not data.

A step that fails isn't recorded either.

4.3.4 Giving a found record's result #

A found record's result is turned back into a GCSL value, its files and directories at their recorded paths. The steps after it are staged with those files from the store. The record's files are exposed under pekit-out/ only once something that is not hermetic might read them, as Exposure describes.

Before a record is used, pekit checks that the store has everything it names: every blob, and every tree with everything it names at any depth. A tree found complete is marked in the store's complete/, so that it is walked once rather than in every build. An eviction removes every mark before it removes a blob.

4.4 Retries and Timeouts

Pekit / Pekit TRM / Steps

GCSL applies #[retry] and #[timeout] to an ordinary call itself. For a step's own call, pekit applies them instead, since the step's body runs as a unit of its own on pekit's schedule.

4.4.1 Attempts #

A step's first attempt is attempt 0. When an attempt fails, by its code's own failure, and the step's #[retry(n)] allows another, the step runs again from its start, in a new sandbox staged afresh as step-<token>-<node>-<attempt> under the cache's scratch directory. Nothing of the failed attempt carries over: not its files, not its /tmp, and not its programs' writes.

A program that can't start because its file is open for writing isn't an attempt. GCSL starts it again for about a second, whatever the step's #[retry]. A newly written file can stay open for moments in a process forked meanwhile, and a program that didn't start did nothing.

A step that passes on an attempt after the first is flaky. It is recorded as any step that succeeds, and the build warns:

warning: step `NAME` passed only when it was run again: it is flaky

pekit test reports a test whose step was flaky as flaky.

4.4.2 Timeouts #

A step's #[timeout(limit)] is a deadline for all its attempts together, from the start of its first attempt. The time the pool spends staging each attempt's sandbox doesn't count: the deadline moves on by that time. When the deadline passes, the running program is stopped, and the step fails with "the step timed out", at the program it was running. A step that fails once its deadline has passed isn't retried, whatever its #[retry] allows.

4.4.3 What a failure reaches #

A step that fails after its attempts fails every step that needs its result, without running them, with the same failure. A target whose value needs the failed step fails with that failure, reported where the target's code, or the library code it called, made the step. Other targets of the same build carry on, and the command exits with status 1 once every target has finished or failed.

4.5 Secrets in Steps

Pekit / Pekit TRM / Steps

GCSL's keychain module asks the host for a secret by name. pekit answers (Keychain::answer) from the workspace's keychain configuration, pekitconf.keychain, for the build's profile, or else from the environment: $GCSL_SECRET_FILE_<NAME> for a file, or $GCSL_SECRET_<NAME> for a string. NAME is the secret's name in capitals, with _ for each character that is not a letter or a digit. A secret found nowhere fails the call. A string secret is the file's contents without one final newline.

4.5.1 Identity #

Each secret's identity is what receipts record of it: <profile>/<name>#<hash>, where the hash is the first 32 hexadecimal digits of HMAC-SHA-256 of the secret's contents under the machine's key.

The machine's key is 32 random bytes, in keychain-key in the state directory, readable only by its owner. pekit makes it the first time a build needs it, writing it beside its place and linking it into place, so that two builds starting at once use one key.

Consequences of the identity:

  • A changed secret has a new identity, and reruns the steps given it.
  • Nothing about the contents can be learned from the identity without the key, since a guess can't be tested.
  • Two machines give one secret two identities, so a step given a secret is found in the store only on the machine that recorded it.
  • A new key gives every secret a new identity, and nothing made with the old identities is reused.

4.5.2 A secret file in a step #

A step given a secret file has the file bound read-only at /pekit-secrets/<profile>/<name>, from where the keychain found it. The path is the same on every machine. No other step has the file, and it is never staged by copying or linking, and never put into the store.

A step can't ask the keychain itself: a keychain call in a step's code fails, since what a step reads has to be among its inputs. A library resolves a secret in a parameter default instead.

4.5.3 What never holds a secret #

  • The store. A result that holds a secret is never recorded. A program of a step that has been given a secret is never recorded either, from the moment it is given one, so a program's output that reveals a secret isn't kept.
  • Events and the trace. An event names a step by its name and an effect by its built-in and program, never the program's other arguments. A program named by a secret is shown as <secret>.
  • Errors. A program given a secret through exec_secret that fails reports neither its status nor its output.

5.1 Staging

Pekit / Pekit TRM / Sandboxes

A step's sandbox is made of a staging directory on the host, under the cache directory's scratch/, named step-<token>-<node>-<attempt>. The pool stages it before the step's body runs (Work::Stage).

5.1.1 What it holds #

The staging directory has four parts, which the sandbox binds at their logical paths:

On the hostIn the sandboxHolds
w//wThe workspace files and directories the step is given.
out//pekit-outThe outputs of other steps, fetches, and unpacks the step is given.
out/.steps/<function>/<identity>/The same path, writableThe step's own output directory, empty at the start.
tmp//tmpAn empty directory of the step's own.

Every input is staged from the store, never from the workspace, so the step sees exactly the contents its receipt holds, even if a workspace file changes while the build runs.

5.1.2 Files and trees #

Each input is staged by what the store keeps of it (StepSandbox::stage):

  • A file is a hard link to its blob, cas/<xx>/<digest>, or to <digest>.x if it is executable. A blob is read-only, so the step can't change it.
  • A directory of fewer than 64 files is made file by file, each a link to its blob.
  • A directory of 64 files or more is mounted: the store's materialized tree of it is bound read-only on an empty directory at the input's path. See Materialized Trees.

A tree that holds one content at several paths gives the first a link to the blob and each other a link to a numbered copy, <digest>.r1 and on, which the store keeps. So no two files of a staged tree are one file, and placing the tree copies nothing that was copied before.

Where linking fails, as across file systems, a file is copied.

5.1.3 Removing it #

When a step is done, its staging directory is renamed, which takes no time, and a thread of its own removes it while the build goes on (sweep::Sweeper). The build waits for that thread before it ends, and a directory that can't be removed fails the build at its end.

A process killed before it removed a staging directory leaves it behind. The next build that holds the store's lock alone removes it, as Concurrency and Sweeping describes.

5.2 The Step Sandbox

Pekit / Pekit TRM / Sandboxes

Each program a step runs is wrapped in its own bubblewrap command (StepSandbox::command). Every program of a step sees the same sandbox, since each binds the same staging directory.

5.2.1 Isolation #

The command unshares every namespace bubblewrap can: user, IPC, PID, network, UTS, and cgroup, with a new session, and dies with its parent. So a program has no network, its own processes and users, and stops if pekit stops. Its root is an empty tmpfs.

5.2.2 The step's user #

A program runs as user 1000 and group 1000, named pekit, whoever runs pekit (sandbox::STEP_UID). Without this, it would run as the number of the user who ran pekit, which differs between machines. Files the step is given, and files it makes, belong to that user. The host's other files, such as those under /usr, belong to nobody.

Every step has the same user database (sandbox::PASSWD and sandbox::GROUP), as Nix gives its builds. /etc/passwd holds:

root:x:0:0:root:/root:/bin/sh
pekit:x:1000:1000:pekit:/nonexistent:/bin/sh
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin

/etc/group holds:

root:x:0:
pekit:x:1000:
nogroup:x:65534:

Programs that look up users by name or number find them there, and tests that need a file every system has, such as /etc/passwd, find one. The step's user has no home directory, so a program that writes to one fails rather than leaving files nothing keys.

A program can be in more groups than pekit. A user namespace that pekit makes without privileges keeps the groups of the user who ran pekit, and shows each of them as 65534, nogroup. So the number of groups id -G lists depends on the machine.

5.2.3 Mounts #

The sandbox binds, in this order:

  1. The host snapshot's directories, read-only at their own paths, unless the build is strict. Each directory of the snapshot that is hidden, such as /usr/local, is an empty tmpfs.
  2. The user database, read-only at /etc/passwd and /etc/group, in every build, strict or not.
  3. The staging directory's w/ at /w, and out/ at /pekit-out, read-only.
  4. The step's own output directory at its path, writable.
  5. Each mounted tree and each sealed composition, read-only at its path.
  6. Each secret file given, read-only at /pekit-secrets/<profile>/<name>.
  7. The staging directory's tmp/ at /tmp, writable.
  8. The step's scratch directory at /pekit-scratch, writable, for a step marked #[scratch].
  9. /proc, and a minimal /dev: null, zero, full, random, urandom, tty, ptmx, pts, shm, and the standard streams.
  10. /dev/kvm, for a step marked #[device("kvm")] on a machine that has it.

A path outside these isn't there. A GCSL file function given such a path fails with "it is outside the step".

5.2.4 Working directory and environment #

A program starts in the step's own output directory, unless its exec gives cwd. Its environment is cleared, then set to the variables its exec gives. LOGNAME and USER are pekit unless the exec gives them, since some programs, such as DejaGnu's runtest, need them. If it gives no PATH, and the build isn't strict, PATH is /usr/bin:/bin:/usr/sbin:/sbin. In a strict build a program given no PATH has none.

5.2.5 What a program doesn't inherit from pekit #

How pekit was started isn't part of a step's key, so pekit keeps it from reaching a step's programs:

  • Standard input. A program's standard input is /dev/null, even when its exec is interactive. It can't read the terminal pekit runs in, or whatever else pekit's standard input is.
  • Signal dispositions. A program starts with every signal's default disposition. A shell's & starts pekit with SIGINT and SIGQUIT ignored, and a signal ignored stays ignored across exec, so without this every program of the step would ignore them, which test suites of signals, such as bash's, notice. pekit catches each signal it inherited as ignored with a handler that does nothing (default_dispositions): exec resets a caught signal to its default, and pekit itself still ignores the signal. SIGILL, SIGFPE and SIGSEGV can't be caught this way, so a pekit started with one of them ignored passes it on.
  • The file-creation mask. A program's umask is 022 (sandbox::UMASK), whatever pekit was started with. The modes a step gives its files are part of what it made, as an archive it makes records them. pekit can't set a child's mask alone, so it sets its own before a build runs anything (fixed_umask). GCSL's file work for a step, which runs in pekit's process, gets the same mask, and so does every other program pekit starts and every file it makes, a step's or not.

A program does inherit pekit's resource limits, such as ulimit -n, the number of files it can open. These can differ between a terminal and another launcher: an agent's shell can raise the open-file limit from 1,024 to 524,288. They aren't part of a step's key.

5.2.6 GCSL's own file work #

GCSL's file functions inside a step, such as fs.write, run in pekit's process, not in the sandbox, against the staging directory. pekit maps each logical path to the staging directory itself, and refuses two things:

  • A path outside what the step has. It fails with "it is outside the step".
  • A write to an input or a sealed composition. fs.write, fs.mkdir, fs.copy's destination, and fs.set_executable fail on a path in an input of the step or in a sealed composition. The error says that the path is an input of the step, or a finished composition.

Temporary directories GCSL makes for a step, a Dir.sandbox's copy among them, are .pekit-tmp-<n> in the step's own output directory, so that a file given from one has a path no other step's file has.

5.2.7 Sandboxes a step makes #

A Dir.sandbox's commands run in a bubblewrap of their own beside the step's, never inside it, since a host such as Ubuntu forbids one bubblewrap inside another. That bubblewrap has the sandbox's directory as its root, and the same isolation, user, LOGNAME and USER, devices, and scratch directory as the step's own. It has the step's user database unless its root has its own /etc/passwd or /etc/group. Compositions and Overlays describes how its root is made.

5.3 Compositions and Overlays

Pekit / Pekit TRM / Sandboxes

A step composes directories with fs.compose and fs.compose_dir, and runs programs in a Dir.sandbox of one, as a toolchain library does to run a pinned compiler on its own runtime. Plain GCSL copies for both. A step's sandbox answers both itself (Layers), without copying.

5.3.1 Compositions #

A composition places each entry under its key, as GCSL describes. pekit places each kind of entry this way (Layers::place_tree and Layers::place_file):

  • A directory of 64 files or more that is a store tree is mounted: an empty directory of its own, the mount point, is made at its place, and the materialized tree is bound read-only there for every program. GCSL finds what it holds there too.
  • A file nothing can change, one of a staged input, a materialized tree, or another sealed composition, is hard-linked.
  • Any other file is copied.

A content a composition places twice, as a toolchain's runtime is placed both alone and within the toolchain, is a link to the blob once and to a numbered copy each other time. A tree mounted in a composition that holds contents the composition already has is an instance of the tree whose files of those contents link later copies. So no two files of a composition are one, and nothing is copied anew.

Directories GCSL doesn't place whole, because an entry is placed inside them, are made entry by entry.

5.3.2 Sealing #

Once a composition is made it is sealed: its files are made read-only on the host, and it is bound read-only to every program of the step. No program can change it, and so none can change a blob through a link. GCSL's file functions refuse to write into it. Its directories keep their modes, since an overlay's merged directory shows its lower directory's mode, and a read-only one would refuse every write.

5.3.3 Sandboxes of a composition #

A Dir.sandbox of a directory that nothing can change, a sealed composition or a staged input, is an overlay (Layers::make_sandbox):

  • The directory is the lower layer, which no program changes.

  • A directory of the step's own outputs is the upper layer, where every write goes.

  • Each tree mounted in the directory is an overlay of its own, nested on its mount point, with an upper layer of its own, .pekit-upper-<n> in the step's output directory.

  • The step's user database, the directory holding its etc/passwd and etc/group, is a layer below the directory. So a composition that has its own /etc/passwd or /etc/group shows its own, and one with none shows the step's.

So a program in the sandbox can write anywhere, and nothing it writes reaches the composition. It can't move or remove a nested overlay's mount point, which fails with EBUSY, "Device or resource busy". GCSL's own reads of the sandbox don't see the user database layer, only programs do.

A Dir.sandbox of any other directory is copied, as plain GCSL does. Before a program runs in a copy, pekit writes the step's etc/passwd and etc/group into it, each unless the copy already has it. If the copy's etc is a symbolic link or a file, pekit leaves it alone. The Step Sandbox lists their contents.

5.3.4 Reading an overlay #

GCSL reads a path of an overlay sandbox as the overlay shows it (Layers::resolve):

  • What the upper layer has, unless it is a whiteout, a character device of number 0, which hides what the lower has.
  • Otherwise what the lower has, unless a directory of the upper layer on the way is opaque, marked user.overlay.opaque, which hides all the lower has below it.
  • A directory both layers have is merged into a new tree of hard links, a snapshot of it as it is at the time.
  • A path in a nested overlay is read from that overlay's layers.

GCSL writes to an overlay sandbox's path in the upper layer of the overlay the path is in (Layers::write_target). A step's result can name a file or directory of an overlay sandbox; it is kept from the merged view.

5.4 The Host Snapshot

Pekit / Pekit TRM / Sandboxes

Outside a strict build, every step sees the host's system directories, so that it can run the host's programs: the host snapshot (HostSnapshot). A strict build gives steps none of it.

5.4.1 What it binds #

Each of these that exists is bound read-only at its own path:

  • /usr, /bin, /lib, /lib64, and /sbin.
  • /etc/alternatives, where Debian's cc and similar names lead.
  • /etc/ld.so.cache, the dynamic linker's cache.

/usr/local is hidden by an empty tmpfs, since no package manager manages it, and so its changes would change no fingerprint. Nothing else of /etc is there.

5.4.2 The fingerprint #

The snapshot is an input of every step, and too large to hash on every build. It is identified instead by a fingerprint, a digest of these:

  • /etc/os-release
  • The package manager's database, which changes whenever a package is installed, upgraded, or removed
  • What the bound parts of /etc say, which an administrator can change without a package: each alternative's target, and the linker's cache

The databases pekit knows are dpkg's /var/lib/dpkg/status, rpm's rpmdb.sqlite in /var/lib/rpm/ or /usr/lib/sysimage/rpm/, apk's /lib/apk/db/installed, and pacman's /var/lib/pacman/local/, whose entries name each package and version.

The fingerprint is part of the platform every receipt names. A step recorded before a compiler was upgraded is not found after it.

5.4.3 A host it can't identify #

On a host with none of those databases, the snapshot has no fingerprint. Its steps are recorded, but never found in the store, since nothing would say when its tools changed. Every command that builds warns:

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

A strict build doesn't use the snapshot, so it reuses steps on any host.

5.4.4 The note after a build #

After a build that ran at least one step and wasn't strict, pekit notes that steps ran with the host's own tools, so the build isn't hermetic. Every step of such a build could see the snapshot, whether or not it used it.

5.5 Scratch Directories

Pekit / Pekit TRM / Sandboxes

A step marked #[scratch] has a directory at /pekit-scratch, kept between its runs, for a tool that does less on a second run: a build system's object directory, Cargo's target directory, or a compiler cache (Scratch).

5.5.1 Whose it is #

A scratch directory belongs to a step's output directory under /pekit-out, which its identity names, and to the platform it builds for. So it is kept when the contents of the step's inputs change, and a different call of the same function, or the same call for another platform, has its own.

It keys nothing. A step has to give exactly what it would give with an empty directory, and pekit relies on that.

5.5.2 Where it is #

Scratch directories are in the store's directory, under scratch/, each named by a digest of whose it is. Beside each is a lock file, which a run holds while it uses the directory, and whose modification time is when it was last held, and a size file, which eviction reads. While a run has the directory, a .dirty file is beside it too, removed as the run lets the directory go.

5.5.3 When a run gets an empty one #

A run gets an empty directory of its own, removed when it ends, when:

  • The build is strict, so that what a release gives depends on nothing a scratch directory kept.
  • Another run, of this process or another, holds the step's directory, so that no run waits for one.

A run is also given the step's directory empty when a .dirty file is beside it: the run that last had it was killed before it let it go, and might have left it half written, a truncated object file newer than its source say, which a tool would take as up to date.

A program of the step found in the store leaves the directory as it is.

5.5.4 Removing them #

An eviction removes scratch directories whole, ordered as other contents are, as costing nothing to make again, and never one a run holds. pekit clean --cache removes them with the store.

6.1 Store Layout

Pekit / Pekit TRM / The Store

The store is the directory store/ under the cache directory, shared by every workspace and every pekit process on the machine (Store). It holds:

PathHolds
cas/<xx>/Blobs by their SHA-256 digests, in directories named by a digest's first two hexadecimal digits, with their executable and numbered copies.
records/<xx>/Step records, program records, manifests, and the records of fetches, unpacks, and git commits, by their keys.
trees/Materialized trees, made once as directories of links to blobs.
complete/A mark for each tree found to have everything it names, at any depth.
seen/For each workspace root, the stamps of the files a build read, and the root's path.
git/Bare clones of the repositories fetch_git fetched from.
scratch/The scratch directories of steps marked #[scratch], with their lock and size files.
claims/A lock file for each step a build claimed. See Claims.
usage/One journal for each build of what it used, for eviction.
eviction.jsonEach record's eviction priority, and what eviction removed.
orphanedWhat workspaces' output directories held of evicted steps, when an eviction last looked.
size, size.lockThe blobs' total size as last measured and added to, and its lock.
tmp/What is being written.
lockThe store's lock.

6.1.1 Writing #

A blob, a tree, or a record is written in full into tmp/, under a name holding the writing process's token, then renamed into place. A rename is atomic, so a reader, or another process, sees a file whole or not at all. A process that loses a race to write the same blob finds it there, and drops its own.

A file put into the store is hashed as it is copied into tmp/, flushed to the disk unless PEKIT_NO_SYNC is set, and renamed to its digest's name (Store::put_file). A blob is read-only. A blob under its digest's name is therefore whole even after a power loss, and is trusted as it's found.

A file that is pekit's own to discard is adopted instead (Store::adopting): a step's results, which its staging directory holds until it is removed, an unpacked archive, and a checked-out commit. Such a file with one link is hashed where it is. If the store holds its contents, nothing is written. Otherwise the file is linked into tmp/, flushed, and renamed into place, so it becomes the blob without being copied. A workspace's files are never adopted, since someone might change them later.

A tree is put at once (Store::put_tree_mounted, Store::put_tree_seen_at). Each new blob it holds, and each of its trees' encodings, is written whole into tmp/ as the tree is walked. Then 16 threads flush them all together, so that one commit of the file system's journal serves many files. Only then is each renamed into place, in the order it was written, so a tree's entries come before the tree. Flushing files one by one cost a journal commit each: storing 20,000 small files took 43 seconds, and takes 7 at once. A put that fails removes everything it wrote.

6.1.2 The lock #

Every process holds lock shared, with flock, while it has the store open, and an eviction or a sweep of stale files takes it exclusively, without waiting. So an eviction or a sweep runs only while no other process has the store, and a process that opens the store waits for one that is running.

6.2 Blobs and Trees

Pekit / Pekit TRM / The Store

The store keeps a file's contents once, as a blob, and a directory as a tree of its entries. Both are named by SHA-256 digests, so the same contents are kept once, whichever step, fetch, or workspace they came from.

6.2.1 Blobs #

A blob is cas/<xx>/<digest>, where <xx> is the digest's first two hexadecimal digits. It is read-only.

Whether a file is executable is not part of its contents, but a file's mode is shared by every hard link to it. So an executable file's blob is a copy beside the plain one, <digest>.x, made the first time it is needed.

A tree or a composition that holds one content at several paths needs a separate file for each, so that no two of its files are one. The store keeps numbered copies for this, <digest>.r1, <digest>.r2, and on, and <digest>.x.r1 and on for an executable one, each made the first time it is needed and kept (Store::link_copy). The first path is a link to the blob, and each other path a link to the next copy. No record names a copy, so an eviction removes copies first, as costing nothing to make again.

A blob is taken out of the store by a hard link (Store::materialise_file), or by a copy where a link can't be made, as across file systems.

6.2.2 Trees #

A tree is a directory's entries, sorted by name. Each entry is one of:

  • A file, by its contents' digest and whether it is executable
  • A directory, by its own tree's digest
  • A symbolic link, by its target, kept as it is

A tree is encoded canonically as JSON and stored as a blob itself, so a tree's digest covers its whole contents at any depth, as the directories of the Remote Execution API's content store do. Names have to be UTF-8; a directory holding another name can't be put into the store.

A tree found to have every blob and tree it names, at any depth, is marked in complete/ by its digest (Store::holds_tree), so that it is walked for that once, not in every build that finds a record naming it.

6.2.3 Putting a tree it has seen #

A tree put into the store again and again, as a step's writable directories are around each of its programs, is mostly what it was. Store::put_tree_seen keeps each file's stamp, its device, inode, size, mode, and times, from when it was last put, and reads again only a file whose stamp differs, or whose blob is gone.

A file changed since it was stamped has another change time, unless it changed in the same tick of the file system's clock as it was stamped. So a stamp taken in the tick a put begins in, or later, by the clock of the tree's own file system, isn't trusted, as git treats its index.

For each file taken by its stamp, the store checks for its blob once the walk is over, unless the tree is already marked complete. A gone blob is put back from its file. When every blob is found, the tree is marked complete, so walking the same tree again checks for none. These marks accumulate until an eviction removes them all.

Before a walk, the tree is read ahead, one level at a time: each directory of the level is listed, then each entry of the level is stamped, on up to eight threads where there are enough entries. The walk then takes each listing and stamp as it was read ahead.

A file that is a hard link to a blob this process linked, by its device and inode, is that blob, and isn't read. A file that is read is hashed before it is copied, and isn't copied if its blob is there. A directory known not to change, such as a sealed composition, is walked once. A mount point's directory takes the mounted tree's digest, unread.

6.3 Materialized Trees

Pekit / Pekit TRM / The Store

A step is given, and composes, whole trees, such as a toolchain of tens of thousands of files. Linking each file into each step's staging directory would cost as much as the step. Instead the store makes a tree's directory once, in trees/, of hard links to its blobs and their copies, and every step that needs the tree mounts that directory read-only (store::trees). Nothing changes it, so every step of every build shares it.

6.3.1 When a tree is mounted #

A tree is mounted rather than linked file by file when it holds 64 files and symbolic links or more, at any depth (MOUNT_FILES). That applies to a directory a step is given, and to one a composition places whole.

6.3.2 Instances #

A tree is materialized as an instance: its digest, and for some of its contents a base, the number of the copy its first file of that content and mode links. The instance with no bases is named by the tree's digest, trees/<digest>. Any other is named by the digest and the first 16 hexadecimal digits of a digest of its bases, trees/<digest>-<bases>.

A composition that mounts a tree whose contents it already holds elsewhere mounts an instance whose files of those contents link copies the composition doesn't use yet. So no two of the composition's files are one.

6.3.3 Making one #

An instance is made in tmp/ and renamed into trees/ whole, so an instance there is complete. Within a process, each instance has its own lock, so two threads never make one twice. A process that loses a race with another finds the other's instance there, and drops its own.

pekit learns what is in an instance from the tree, not by walking its directory: the digest of a directory inside it, and which blob or copy each of its files links.

6.3.4 Removal #

An instance holds links to blobs, so an eviction removes every materialized tree before it removes any blob (Store::forget_materialised). The next step that needs a tree materializes it again.

6.4 Fetches, Unpacks, and Git Commits

Pekit / Pekit TRM / The Store

pekit answers GCSL's fetch, archive.unpack, and fetch_git itself, never running the programs plain GCSL runs. Each result is named by its contents, so it has the same path in every build, and is kept in the store so that it is fetched or unpacked once on a machine.

6.4.1 Fetches #

fetch(url, sha256) is the only part of a build that touches the network (fetch). With a pin:

  1. A blob of the pinned digest in the store is the file, and the network is not used.
  2. Otherwise the file is downloaded on the host, hashed as it is streamed into the store, and kept only if its digest is the pin. A download that goes 60 seconds without a byte fails.

The file's path is /pekit-out/.fetch/<sha256>/<name>, where <name> is the URL's last part as GCSL names it. Without a pin, the file is downloaded only to report its digest, and the call fails with that digest. A pin that is no digest, or a file that doesn't match, fails the call too.

How long a download took is recorded, for eviction to weigh.

6.4.2 Unpacks #

archive.unpack(archive, strip) is answered by pekit's own unpacker (unpack), since the build environment that would give a step tar is itself an archive.

  • Formats. An archive is read as zip by its first bytes, as a wheel or a jar is; otherwise as gzip, xz, bzip2, or zstd, or a plain tar.
  • Paths. Each entry's path has its first strip components left off, and an entry with no more is left out. An entry whose path would leave the directory, by being absolute, holding .., or passing through a symbolic link the archive made, fails the unpacking. Nothing is ever written outside it.
  • Kinds of entry. A symbolic link is kept as it is, and a sandbox resolves it inside itself. A hard link becomes a copy. A device or a pipe is left out. Of each file's mode, only whether it is executable is kept.

An unpacking is keyed by the archive's digest and strip, and recorded as the tree it made. Its path is /pekit-out/.unpack/<key>. It runs in a directory unpack-<token>-<n> under the cache's scratch directory, then is put into the store.

6.4.3 Git commits #

fetch_git(url, commit) gives the files of the repository at the commit, whose whole name pins its files as a digest does (git_fetch):

  1. A record for the URL and commit names the tree of its files, which the store holds whole.
  2. Otherwise the commit is fetched into a bare clone of the URL in the store's git/: the commit alone, shallowly, or, if the server won't give a commit by its name, with every branch and tag. It is checked out into git-<token>-<n> under the cache's scratch directory, without .git or submodules, put into the store, and recorded with how long it took.

Fetches of one repository take turns, since a build fetches several crates of one repository at once into one clone. One that waited finds the record the other made.

Git runs with no configuration but the repository's own: the user's and the system's are left out, so that nothing of the machine, such as a line-ending conversion or a filter, changes the files a commit gives. GIT_CONFIG_PARAMETERS and GIT_CONFIG_COUNT are removed from its environment for the same reason. The path is /pekit-out/.git/<key>/<name>, where the key is a digest of the URL and the commit.

Credentials are the exception. Git's one credential helper runs git credential fill with the user's configuration environment restored: GIT_CONFIG_GLOBAL, GIT_CONFIG_NOSYSTEM, GIT_CONFIG_PARAMETERS and GIT_CONFIG_COUNT, each as the user had it, or unset. Credentials therefore come from wherever the user's git gets them. The helper answers get only; store and erase do nothing, so a fetch never changes the user's credential store. GIT_TERMINAL_PROMPT is 0 throughout, so nothing prompts. Credentials are part of neither the key nor any step.

6.4.4 In a step #

A step has no network, so fetch and fetch_git in a step's code fail. archive.unpack works in a step, on an archive the step was given, and is answered and kept the same way.

6.5 Program Records

Pekit / Pekit TRM / The Store

A step runs again whenever anything in its receipt changes, including any byte of its code's files. Most of the programs it runs then see what they saw before. So pekit also records each program a step runs, by what the program can see, and replays a program it finds instead of running it (programs and engine::programs).

6.5.1 Which programs #

Each exec, exec_live, and Sandbox.exec of a step is a program. The first time a step is given a secret, at its start or when a read binds one, its programs are neither found nor recorded from then on. With --rebuild, programs are run and recorded but not found. In --check-reproducible's second build, they are neither found nor recorded.

6.5.2 A program's key #

A program's key covers:

  • The platform, as the step's receipt names it, with the host snapshot's fingerprint.
  • The program itself: the built-in, its words, its working directory, its environment, and exec's options. Its words name files by path alone; their contents are the next part's.
  • What it can see: every input the step has staged, by path and contents' digest, and the digests of the trees it can write, the step's own output directory and its /tmp, as they are before it runs.
  • The step's view: a chain that starts from the step's platform and own output directory, and folds in each effect the step had run before the program. An effect that only reads, fs.exists, fs.read, File.read, Dir.files, or which, isn't folded in. Any other folds in its built-in, its arguments by path, and what it staged, by contents.

A device and a scratch directory key nothing, and a scratch directory is neither captured nor put back.

6.5.3 Recording #

A program that runs is recorded with its status, its output and error, and the digests of the two writable trees after it, whose contents go into the store. A tree's digest leaves out modification times and modes other than the executable bit, so the record also keeps a blob of them: each file's, directory's and symbolic link's modification time, and each file's and directory's permission bits, by path. A sealed composition and a mount point are left out of it. Hashing the trees again after each program is cheap: the step's sandbox keeps a stamp of each file, as Blobs and Trees describes, and reads again only a file whose stamp changed.

6.5.4 Replaying #

A program found is not run. Each writable tree whose digest differs from the record's is placed again from the store, whole, so the step's world is exactly as the recorded run left it, and the record's result is given to the step. A record whose contents aren't all in the store is not found, and neither is a record without the blob of times and modes, such as one made before pekit kept them.

A replay puts back what the store keeps of a tree: contents, symbolic links, and whether a file is executable. Then it gives every entry of both trees, placed again or not, the modification time and mode the recorded run left, what a directory holds before the directory. So a make after a replay sees which files are newer than others as it would have after the run, and a chmod a found program ran is kept. A replay doesn't put back which files were hard links of one another, and leaves alone a file with more than one link. A sealed composition put back is sealed again.

6.5.5 What stops recording #

An entry the store can't hold stops a step's programs being found or recorded from then on:

  • An entry that is neither a file, a directory, nor a symbolic link, such as an overlay's whiteout
  • A directory an overlay's attributes mark, such as an opaque one

So a step whose sandbox removes a file of the directory it was made of, which leaves a whiteout, runs its later programs every time. Overlay attributes that only say where an entry came from, or which layer it is, are dropped from a copy and don't stop recording.

6.5.6 Where the work is done #

The engine keeps each step's view, and the writable trees' digests while it knows them. A program is sent to the pool, and the thread that takes it hashes the trees if needed, makes the key, and finds and replays the record or runs the program, hashes again, and records. No tree is hashed or placed on the thread that evaluates.

A build reports how many programs its steps found:

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

6.6 The Remote Cache

Pekit / Pekit TRM / The Store

A remote cache holds records and their contents for many machines. pekit uses a server's content-addressable store and action cache, never its execution service (remote). The server is any of the Remote Execution API, version 2, spoken over gRPC.

6.6.1 Records as action results #

  • Contents. A pekit blob is named by the SHA-256 digest of its contents, as a REAPI blob is, so a file is the same blob in both.
  • Keys. A record is kept as an action result. Its action cache key is the digest and size of an action blob: pekit-action-1, a zero byte, and the record's key in hex. The action blob is uploaded too, so a server that checks an action exists finds it.
  • Outputs. The result's output files are the record's own encoding, at record, and each file the record names, at blobs/<digest>. Its output directories are each tree the record names, at trees/<digest>, each as a REAPI Tree message.
  • What a record names. Every 64-digit hex string in the record's encoding that names a blob in the store, a tree if the blob is a tree's encoding, as eviction finds them.

A Tree message holds a root Directory and every directory under it, each once. A Directory lists its files, with digest, size, and whether each is executable, its directories by digest, and its symbolic links by target. pekit's trees name the same entries, so a tree is made again from its Tree message and has the same digest.

6.6.2 Finding a step #

A step whose receipt has no usable record in the store is looked for in the cache, as work on the pool, never on the thread that evaluates (engine::looked_remotely):

  1. Its manifest is asked for by its key and merged into the store's: each set of contexts either holds is kept, the store's first.
  2. A receipt is made for each set of the merged manifest, from the values the step's contexts give now. Each is asked for in turn, until one is found.
  3. The step is looked up in the store again. Found, it is counted as found in the store and as found remotely. Missed, it runs.

A record found is put into the store only once everything it names is there:

  • Every file blob the result and its trees name that the store lacks is downloaded and checked against its digest.
  • Each tree is made again from its Tree message and checked against the digest its path names.
  • The record is written last.

A blob that is missing, or not its digest's contents, fails the lookup. The record is not written, so the step runs. Blobs already downloaded stay in the store, each its digest's.

Steps are looked for only where records are reused. A build with --rebuild, the second build of --check-reproducible, and a build on a host whose packages cannot be identified ask the cache nothing.

6.6.3 Writing a step #

A build that uploads writes each step it records, after the record and the manifest are in the store, as work on the pool:

  1. The cache's manifest for the step's base is merged into the store's.
  2. For the step's record and then the manifest, the cache is asked which of their blobs it lacks.
  3. Those blobs are sent, batches of small ones by BatchUpdateBlobs and each large one by ByteStream.
  4. The action result is written.

The build waits for its uploads before it ends, and before the store is evicted. A failed upload fails no build.

6.6.4 Transfers #

  • Batches. A batch is kept within the cache's max_batch_total_size_bytes, and within 4 MiB, gRPC's default message limit, counting 256 bytes for each blob besides its contents. A blob too large for a batch is read or written by ByteStream, in parts of 1 MiB, and a read blob is hashed as it is written to the store.
  • Empty blobs. The empty blob is never transferred, since every cache has it.
  • Capabilities. The cache's capabilities are asked for once, before its first transfer. A cache that names its digest functions without SHA-256 is not used.

6.6.5 Configuration and failure #

The cache's URL, instance name, headers, and whether to upload come from pekit's options and environment, never from the workspace's files. pekit(1) documents them. One runtime of two threads per process runs every call, and the pool's threads wait on it.

Connecting has 10 seconds. Once a call fails, because the cache cannot be reached or refuses it, the process asks the cache nothing more and builds as if it had none. A lookup that fails for a missing or wrong blob affects that step only. The build's first failure of either kind is reported as a warning when it ends.

6.7 Claims

Pekit / Pekit TRM / The Store

A build that misses a step in the store claims it before it looks in the remote cache or runs it (try_claim). The claim is the lock file claims/<base> in the store, by the step's base receipt, the receipt without its contexts (see Receipts), held exclusively with flock. The build holds it until the step is recorded, or has failed every attempt, or the process ends.

A build that finds the step claimed waits for the claim on a thread of its own (Pool::claim), not one of the pool's, holding nothing of the machine's budget, and goes on with every other step meanwhile. Once it holds the claim, it looks in the store again, as it looked first:

  • the step's record is there, with everything it names: the step is found in the store, and its claim let go of;
  • otherwise the build that held it failed the step or ended first: this build looks further, and runs the step, holding the claim.

A step's base receipt is the same whatever contexts it reads, so a build can wait for a step that read a context bound otherwise, miss, and run its own. That costs a wait, never a wrong result.

Claims are taken only where steps are taken from the store, not by --rebuild or --check-reproducible. A claim that can't be opened or locked isn't taken, and the step runs as it would have.

An eviction, which runs only while no other process has the store, removes claims/. Nothing else removes a claim's file.

7.1 Exposure

Pekit / Pekit TRM / Outputs

Every output of a build, a step's, a fetch's, or an unpacking's, is kept in the store by its logical path under /pekit-out. Steps are staged from the store, so only what is not hermetic reads outputs from pekit-out/ on the disk: a target's own code, the programs it runs, and pekit run. An output is exposed there, as read-only hard links to the store's files, only once something might read it from the disk (exposure). A build that changed nothing writes nothing there for outputs no one reads.

7.1.1 When an output is exposed #

  • Each exposure waits. A kept output is noted, and a later note of the same path replaces an earlier one.
  • A target's reads are answered from the store. A target's dir.files() or file.read() of a path inside an output of the build is answered from the store's tree of it, which is what the disk would show once it's exposed. That holds until a target's own effect runs a program or writes, which might have changed the output directory; from then on, reads go to the disk, as a read of a path in no output does.
  • Every waiting exposure is made before a target's own effect that might read the output directory: a read that isn't answered from the store and whose path is, or leads into, the output directory; a read of a path that GCSL code names as a string; a keychain's file; and any effect that runs a program or writes.
  • pekit run makes every waiting exposure before the program or script runs, since it might read any of them.

Any other build leaves an exposure no one needed unmade, so pekit-out/.steps/ and pekit-out/.unpack/ hold only what was.

7.1.2 What a target gives #

As a build ends, each file and directory a target's value names under /pekit-out is copied out to pekit-out/ on the host. Each exposure above one of its paths is made first, and those at or below its paths are dropped, the copy taking their place. The copy is the user's: writable, and a file of its own, not a link to the store.

Each of a target's results under .steps/<function>/<identity>/ is then linked under the target's name (target_view), as pekit-out/<target>/<function>/<rest>, a symbolic link to the step's copy. The second step of one function a target's value names is under <function>.2, and so on, numbered in the order the value names them.

A step found in the store has its outputs placed the same way, so a target's results are there after pekit clean, or in a release's fresh tree, without running anything.

7.1.3 What the output directory isn't #

pekit-out/ is not part of the workspace. GCSL's directory listings of the workspace leave it out, and a step can't be given a file of it by its workspace path; outputs are named by their /pekit-out paths. The listings leave out the root's .git too, and any directory below the root that holds a .git of its own (HostView::hides), without descending into it.

8.1 Eviction

Pekit / Pekit TRM / Maintenance

The store can grow to the size PEKIT_CACHE_LIMIT gives: 100 GiB by default, or no limit for 0 (evict::limit_of). As a build ends, pekit journals what the build used and, if the store is larger than its limit, evicts until it is below nine tenths of the limit (evict).

8.1.1 What is evicted #

An eviction removes a record's contents together: every blob and tree a record names, whether a step's, a program's, an unpacking's, or a download's. The record stays, but isn't live: a later build that finds it runs what made it again. A blob is removed once no live record names it at any depth.

An eviction never lists a record's contents whole. Each blob counts what names it: each live record that names it directly, and each tree a live record reaches that holds it as an entry. Evicting a record lets go of what it names. A blob that nothing names any more is removed, and a removed tree lets go of its entries in turn. Trees share their subtrees. So the memory an eviction needs depends on how many blobs the store holds, together with how many entries its trees have. It doesn't depend on how much each record names. A store of 37 GiB in 128,000 records evicts in about 200 MiB.

Before it removes any blob, an eviction removes every materialized tree and every completeness mark, since both depend on blobs being there. In order, it then removes:

  1. Blobs no record names, and numbered and executable copies, which cost nothing to make again.
  2. Records' contents, and scratch directories, by priority, lowest first.

A scratch directory is evicted whole, as costing nothing to make again, and never while a run holds it.

8.1.2 The order #

The order is GreedyDual-Size. Each record's priority is L + cost / size, set when the record was last used, where:

  • cost is the time it took to make, in milliseconds.
  • size is the size of its contents, in bytes. A file that two of its directories hold counts for each.
  • L is the priority of the last record evicted.

So what is cheapest to make again for the space it takes goes first, and among records alike in that, what was used longest ago, since L grows as evictions go on. A large file that took a second to make goes before a small one that took a minute.

8.1.3 What was used #

Each build writes a journal of the records and scratch directories it used into the store's usage/, one file per build. An eviction reads every journal, and keeps each record's priority, with L, in eviction.json, with which records it evicted.

8.1.4 The store's size #

The store's size is its blobs' and its scratch directories'. Walking every blob on every build would cost too much, so the blobs' size is kept in size, a ledger: what an eviction last measured, walking every blob, plus the bytes of the blobs each build has written since, added under size.lock as each of its steps is recorded and as it ends.

The blobs are walked again only when the ledger is above the limit, is a day old or older, or isn't there. A build killed part way has added what it wrote up to its last recorded step, so the ledger falls short by little more than one step's output, which the next walk sets right.

8.1.5 When it runs #

An eviction takes the store's lock exclusively without waiting. If another process has the store open, the build evicts nothing, and a later build does. A store that can't be kept within its limit is a warning, not a failure:

warning: the store could not be kept within `PEKIT_CACHE_LIMIT`: MESSAGE

If another process has the store open and the ledger says the store is over its limit, the build says so in the same warning, with the store's size and its limit, rather than evicting nothing silently. A command shows each warning once, however many builds it runs.

8.1.6 Room during a build #

With keep_free set, a build evicts during the run as well (evict::make_room), when less than that much is free on the file system of the store or the scratch directory. It starts no new step until none of its own steps, effects, or jobs is running. It then evicts until the floor, and a tenth more, is free. Whatever it costs, it keeps:

  • every blob the build has used: put, looked up, or taken by its stamp;
  • every record it found or wrote;
  • every scratch directory it held.

A step that fails for want of room is held, unstaged, and run once more after room is made for it: at least the floor, and at least 10 GiB. A step counts as failing for want of room if its error says "No space left on device", "Disk quota exceeded", or tar's "Wrote only", or if less than the floor, or 1 GiB, is free once it has failed. If it fails so again, or no room could be made, its error ends with a note:

= note: not enough space: the file system of the store and the scratch directory has FREE free, and the build could make no more room

As with eviction at the end, room is made beside other processes only as Eviction beside other builds describes. Otherwise the build warns that nothing was evicted, and why, and goes on. It warns too if it could go on only by starting a step it holds, and it then starts that step.

8.1.7 Outputs of evicted steps #

A build exposes outputs under its output directory as hard links to the store's blobs (see Exposure). An eviction removes a blob's name in the store, but an exposure's link keeps its contents on the disk, though the store's size leaves them out. No build can use them, because a build exposes what it needs again from the store.

Each build notes its workspace's output directory beside its stamps, in seen/<digest>.outputs. An eviction that evicted something with the store to itself, and every pekit store evict, then removes each exposure under .steps/, .unpack/, .git/, or .fetch/ of a noted output directory that holds a file of the store's file system that no name in cas/ links. It never touches the files a target gives, nor anything on another file system, which is a copy rather than a link. What it found is kept in orphaned, which pekit store stats shows.

8.1.8 Eviction beside other builds #

While other processes have the store open, a build evicts beside them, if every process that holds the store publishes what it uses. Each process keeps a file of its own in using/, <pid>-<token>, locked for as long as it lives. Before it relies on anything of the store, it appends it there, once: each record before it reads it, each blob before it looks for it or links it, and each tree it takes as complete. The kernel's /proc/locks says which processes hold the store. One that publishes nothing, an older pekit say, keeps the build from evicting beside it, and the build warns as it always did. So does a process that could not write its file, the disk full say: it removes the file, and publishes no more.

One such eviction runs at a time, holding the evicting lock. It also holds the store's gate for its whole length, so that no process opens the store meanwhile; if either is held, the eviction does not run:

  1. It evicts as an eviction alone does, keeping everything any live process has published, but it moves each blob it evicts into tmp/evicting-<token>/ rather than deleting it.
  2. It reads what each live process has published again, and moves back each blob published meanwhile, directly or through a record or a tree. If a process has meanwhile put a blob of the same name, of the same contents, the one moved aside is dropped instead.
  3. It deletes what is still aside.

A process that published a blob before step 2 has it moved back. One that published it after finds it gone, and puts or builds it again. So no process relies on what is deleted. Such an eviction removes every mark that a tree is complete, but it leaves the materialized trees, which a running step might have mounted, and the outputs of what it evicted, for an eviction with the store to itself. pekit store stats shows how many materialized trees there are. A process removes its file in using/ as it exits. A file there whose lock no process holds is a dead process's, and the next such eviction, or sweep with the store to itself, removes it. What a dead evictor moved aside is moved back by the next eviction or sweep, unless a blob of the same name is there again, and the rest is deleted.

An eviction as a build ends keeps everything that build used, not only what other processes use: it still holds the store as it evicts. A store that only such evictions trim keeps each running build's working set, and is trimmed further by pekit store evict or by an eviction with the store to itself.

8.2 Concurrency and Sweeping

Pekit / Pekit TRM / Maintenance

Any number of pekit processes can use one store at once, from one workspace or several. Each writes only through names of its own and atomic renames, and nothing they share is changed in place.

8.2.1 The store's lock #

Every process holds the store's lock file shared while it has the store open. An eviction, and a sweep of what killed processes left, take it exclusively without waiting, and do nothing if they can't. So neither runs while another process has the store open, and a process opening the store waits for one that is running.

8.2.2 Names of its own #

Every process names what it makes in a directory others share, the store's tmp/ and the cache's scratch/, with its token: 16 hexadecimal digits read once from /dev/urandom (sweep::token). A process's number isn't used, since another process sharing the store, in another PID namespace, can have the same one.

8.2.3 Races #

Two processes that make the same blob, tree, record, or materialized tree each write their own in tmp/ and rename it into place. The rename that loses finds the other's there, and drops its own, which is as good, since both are of the same contents. Within a process, a lock for each materialized tree, and for each repository fetch_git fetches into, keeps two threads from doing the same work.

Two runs of one step marked #[scratch] don't share its scratch directory: the first holds it by a lock, and the other gets an empty one of its own.

8.2.4 Sweeping as a build goes #

A step's staging directory often holds tens of thousands of links, and removing it takes as long as staging it. So a build renames a finished step's staging directory, which takes no time, and a thread of its own, the sweeper, removes it while the build goes on. The build waits for the sweeper before it ends, and fails if a directory couldn't be removed.

8.2.5 Sweeping what a killed process left #

A process killed before it removed what it made leaves it behind. Once the sweeper is done, a build tries the store's lock exclusively. If it gets it, no other process has the store open, so everything in the shared directories is some dead process's or its own, and it removes (sweep::sweep_stale):

  • Every entry of the store's tmp/ that isn't its own
  • Every staging directory, swept directory, empty scratch directory, unpacking, and checkout in the cache's scratch/: the entries whose names start with step-, swept-, kept-, unpack-, or git-

If another process has the store, nothing is swept, and a later build does it.

9.1 Queries

Pekit / Pekit TRM / Commands

pekit query deps and pekit query rdeps evaluate targets as a build does, in a query mode of the engine (engine::query_all), but start no step.

9.1.1 What a query runs #

A target's own effects run, since evaluation needs them: its fetches, unpacks, and reads of the workspace. No step starts, and no step's record is looked up. What a target reaches is the steps its value needs, or the steps the result it stopped for needs, each with the steps it is given.

A step's outputs are known only once it runs. A target that stops for a step's result is done there: what it reached so far is reported, and where it waits (TargetDeps::waits). The query never builds to find out more.

9.1.2 What a target reads #

A target reads a workspace file if any of these holds:

  • Its prepared call's code needs the file, as a GCSL source.
  • A step it reaches has code in the file.
  • One of its own effects reads the file.
  • A step it reaches is given the file as an argument, capture, or context value, or is given a directory that holds it.

A GCSL file is also read by every target whose code is in its directory or below, since its declarations are visible there. A change to it can change what a name there means, whether or not anything names it yet. workspace.gcsl is read by every target.

9.1.3 Reverse dependencies #

pekit query rdeps FILE lists, of the targets it selects, those that read the file (TargetDeps::reads_file). A target that waits for a step's result might read the file after the wait, so it is listed too, with a note on standard error: an unknown is never taken for no.

The prelude's test definition type awaits its definition's step inside a recover, so every test's unit waits for its own step's result. So pekit query rdeps --kind test lists every test, those it can't rule out with a note.

9.2 Strict and Reproducible Builds

Pekit / Pekit TRM / Commands

9.2.1 Strict builds #

--strict changes four things:

  • Libraries. Loading fails unless the workspace's libraries are exactly those pekit.lock pins, as Libraries and the Lock describes.
  • Sandboxes. Steps are given no host snapshot: no /usr, /bin, /lib, /lib64, /sbin, or /etc, and no default PATH. A step runs its programs from what it is given.
  • Keys. Every receipt's platform is the execution platform marked as having no host tools, <platform> no-host-tools, without the host's fingerprint. So a strict build's records are the same on every machine of the platform, and apart from a build's that borrowed host tools.
  • Effects. A target's own effects are limited to fetches, unpacks, the keychain, and reads under /w and /pekit-out, as A Target's Own Effects describes. Since a target then cannot write, its fs.exists and fs.read run out of order, as Order describes. Steps marked #[scratch] get an empty directory.

9.2.2 Requiring strict builds #

A workspace whose pekitconf has require_strict = true fails build, test, package, and publish without --strict, after loading and before selecting targets (strict_as_required). run, query, lock, and clean don't check it, and release is always strict.

pekit needs the value before it builds, to choose the build's settings, and running workspace.gcsl early would evaluate it outside the build. So requires_strict reads the field from the parsed file, running nothing:

  • pekitconf = {require_strict = true} or false, a Bool literal in the record written at the top level, is read as written.
  • A dotted pekitconf.require_strict = ... fails the command. pekit reads no dotted field of pekitconf, and ignoring this one would build what it forbids.
  • Any other expression, or a pekitconf whose type has the field but whose record isn't written at the top level, fails the command.
  • No such field requires nothing.

9.2.3 Checking reproducibility #

--check-reproducible builds twice (Settings::compare):

  1. The first build is an ordinary one, finding and recording steps as ever.
  2. The workspace is checked afresh, and every step whose receipt has a record from the first build is run again, its programs neither found nor recorded. Its result and outputs are compared, byte for byte, with the record's. A directory is compared through its trees, so each file that differs is named.

Only steps given the same inputs both times are compared, so a step whose input differed because an earlier step wasn't reproducible isn't reported too. The second build records nothing, so a step's first record stays.

A step that differs fails the command:

error: a step is not reproducible: run again with the same inputs, it gave other outputs
  .steps/stamp/7367551baf538abf
    /pekit-out/.steps/stamp/7367551baf538abf/stamp.txt

pekit run and pekit publish refuse --check-reproducible, since their effects change the world and would be done twice.

A --gcsl-profile of a checked build covers both builds.

9.3 Packing, Publishing, and Releasing

Pekit / Pekit TRM / Commands

9.3.1 Packing #

The workspace's packagers are the packaging module's ^packagers, set from pekitconf.packagers. Each is a packaging.Packager: a name, a pack function of a package to the directory it packed it into, and a publish function of a package, that directory, and a store.

pekit package evaluates packaging.pack(package NAME()) for each package selected. The module's pack calls each packager's pack, which is normally a hermetic step. A workspace with no packager fails with an error saying to list one in pekitconf.packagers.

9.3.2 Publishing #

pekit publish evaluates packaging.publish(package NAME(), "STORE") for each package. The module packs the package with each packager, then calls each packager's publish with the packed directory and the store, as the target's own effects, in program order, outside any step. The store is an argument rather than a context, so packing doesn't depend on it, and publishing into a second store packs nothing again.

A package that fails to publish fails alone, as any target does, and the packages published before it stay published.

9.3.3 Publishing strictly #

A packager's publish is a target's own effect, which a strict build refuses. So pekit publish --strict builds in two passes, as a release does (published_strictly):

  1. Pack strictly. Every package selected is packed, as pekit package --strict packs it.
  2. Gate. A recipe any of whose packages failed to pack is held back: none of its packages is published, each fails, and so does the command. A packager such as ppk never publishes a version twice with other contents, so a recipe's family of packages is published whole or not at all. The other recipes go on to be published.
  3. Publish. The packages are published with the strict pass's settings: no host tools, and the same platform key. The target's own effects are allowed, and every step is taken from the store, even with --rebuild. This pass writes no trace or GCSL profile.

The steps counted are those of the strict pass, and any the publishing ran.

9.3.4 Releasing #

pekit release PACKAGE --to STORE works in these stages (release):

  1. Check the tree. The workspace has to be in a git repository and match its HEAD: every file committed, nothing changed or untracked, except pekit-out/ and .gcsl/. Otherwise the command fails, naming each file that differs.
  2. Export. The workspace's tree at HEAD is exported with git archive into a directory of its own under the cache, so no file the repository ignores, or doesn't hold, reaches the build.
  3. Build strictly. The package is packed there with --strict, --check-reproducible, and the release profile. Its value gives the package's name and version.
  4. Check the tag. The tag is NAME@VERSION. If a tag of that name is on another commit, the release fails, before anything is published.
  5. Publish. The package is published with each packager into the store. Publishing is a target's own effect, which a strict build refuses, so this pass keeps the strict build's step settings, no host tools and the same platform key, so that its steps are found in the store, and allows the target's effects, which the strict pass checked.
  6. Tag. HEAD is tagged NAME@VERSION with a lightweight tag, which needs no git identity. If the tag is already on HEAD, the package is published again and no tag is added.

A tag is only ever added, never moved or deleted.

10.1 Failures of a Build

Pekit / Pekit TRM / Failure Modes

pekit reports every failure on standard error, prefixed error:, and exits with status 1. A failure in GCSL code is shown at the line that made it, with a library's line shown beneath as "failed here, in library code" where a library raised it. This chapter lists failures by where they happen.

10.1.1 Before anything is evaluated #

FailureWhat it looks likeCause and recovery
No workspaceAn error naming the directory searched from.No workspace.gcsl at or above the current directory. Run pekit inside a workspace.
A check errorGCSL diagnostics, with the file and line.A source doesn't check. Nothing runs until every source checks.
A build and a script of one nameAn error naming both.One directory declares build NAME and script NAME. Rename one.
An ambiguous name"build hello is defined in several places", with each candidate.Several directories define the name. Give its qualified name.
An unknown name"no build is named hello", with the closest names.A typo, or a definition of another kind.
A bad cache limit"PEKIT_CACHE_LIMIT is X, which is no size".Set it to a number with a unit, or 0.
A strict build's libraries"a strict build uses the libraries pekit.lock pins, and only them", with each problem.Run pekit lock, remove a changed library's directory, or unset $GCSL_LIBRARY_PATH.
A library can't be put backA git error naming what was run.The repository or commit is unreachable. Check the network and the lock's git field.

10.1.2 While evaluating #

FailureWhat it looks likeCause and recovery
An unpinned fetch"fetch of URL is not pinned: its sha256 is DIGEST".Add the digest the error gives, after checking it.
A fetch that doesn't matchAn error naming the pin and the digest found.The server's file changed, or the pin is wrong. Nothing is kept.
A fetch in a step"fetch runs outside hermetic steps".Fetch in a parameter default or the caller. The same holds for fetch_git and the keychain.
A strict refusal"a strict build refuses a target's own NAME", or "reads only the workspace and the build's outputs".Move the effect into a step, or out of the release.
A dynamic dependency under --no-dynamicAn error where the target waits for a step's result.Remove --no-dynamic, or restructure the target.
Shared calls that need their own results"this call depends on its own result", each call in the circle labeled with the target or step that needs it and the one computing it.Memoized calls or lazy values that targets share call each other in a circle. A run of either target alone would fail the same way. Break the circle.
Units waiting for each other"the build's targets and steps wait for each other's shared results".Two units each need a result the other is computing, through a step's result. Restructure the shared code.
No toolchainAn error naming the kind and both platforms, and saying that registering replaces the default.Register a toolchain of the kind for the platforms.

10.1.3 While running a step #

FailureWhat it looks likeCause and recovery
A program fails"PROGRAM exited with status N", at the exec, with its standard output and standard error.The step's own failure. Its retries run first, if it has any.
A timeout"the step timed out", at the program it was running.The step's attempts together ran past its #[timeout].
A path outside the step"it is outside the step".The step uses a file it wasn't given. Pass it as an argument.
A write to an inputAn error that the path is an input of the step, or a finished composition.Work on a copy, or in a Dir.sandbox.
A mount point movedA program fails with "Device or resource busy".A program tried to move or remove a directory a composition mounts. Copy it first.
A result outside the stepAn error naming the file the result names.A step gave a path it neither made nor was given.
No bubblewrap"pekit runs programs under bubblewrap (bwrap), which is not installed".Install bubblewrap.
An unknown device"pekit gives a step no device NAME: the one it knows is kvm".Use #[device("kvm")] only.
A flaky stepA warning: "step NAME passed only when it was run again: it is flaky".Not a failure. Find what makes it vary.

A step that fails fails every step that needs its result, unrun, with the same failure, and every target that needs it. Other targets carry on.

10.1.4 At the end of a build #

FailureWhat it looks likeCause and recovery
Not reproducible"a step is not reproducible", with the step and its files.The step's outputs vary. See the common causes on Checking That a Build Is Reproducible.
A staging directory not removedAn error from the sweeper.Something under the cache's scratch/ can't be removed. Check its permissions.
The store over its limitA warning that it "could not be kept within PEKIT_CACHE_LIMIT".Not a failure. Another process might hold the store; a later build evicts.
The host unidentifiedA warning that no step is reused from the store.The host has no package database pekit knows. Build strictly to reuse steps.

10.1.5 Getting back to a known state #

These restore a known state, from least to most drastic:

  1. Remove a changed library. Remove its directory under .gcsl/libraries/, preserving any edits first; the next build puts back the pinned one. Untouched exports with pekit's record refresh automatically when the lock moves. An export made by an older pekit that already differs has no record and needs this one-time removal too.
  2. pekit clean. Removes pekit-out/. The next build puts every target's results back from the store, running nothing.
  3. --rebuild. Runs every step and program again, and records each. It doesn't repair a changed blob: a blob already in the store isn't written again.
  4. pekit clean --cache. Removes the store, its scratch directories, and the cache's staging directories. The next build runs everything. The state directory, and with it the machine's keychain key, stays.

10.1.6 A store whose blobs were changed #

A blob is shared by hard links with every staging directory, materialized tree, and exposed output that holds it. Changing one of those files, its contents or its permissions, changes the blob, and pekit doesn't detect it: later steps are given the changed file, and their records are wrong. A blob's name is its contents' SHA-256, so a blob can be checked by hashing it and comparing the digest with its name, ignoring a .x or .rN suffix. A plain blob's mode is 0444, and an executable one's 0555. After such a change, pekit clean --cache is the safe recovery.

10.1.7 A killed build #

A build killed part way leaves files in the store's tmp/ and staging directories in the cache's scratch/. Nothing it left is seen as complete, since everything is renamed into place only once whole. The next build that finds no other process using the store sweeps them, as Concurrency and Sweeping describes.

Appendix A On-Disk Layout

Pekit / Pekit TRM

This appendix collects every path pekit uses. CACHE is the cache directory, $PEKIT_CACHE_DIR, $XDG_CACHE_HOME/pekit, or ~/.cache/pekit. STATE is the state directory, $PEKIT_STATE_DIR, $XDG_STATE_HOME/pekit, or ~/.local/state/pekit. CONFIG is the configuration directory: $XDG_CONFIG_HOME/pekit, else ~/.config/pekit. BUDGET is the machine's budget's directory: $XDG_RUNTIME_DIR/pekit/budget, else CACHE/budget.

A.1 In the workspace #

PathHoldsWritten by
workspace.gcslThe root file, and pekitconf.The user.
pekit.lockThe pinned libraries and their sources, as JSON.pekit lock.
pekit.sourcesWhat each recipe's packages are built from, as JSON.pekit sources.
.gcsl/libraries/<path>/Each pinned library, exported.pekit lock, and restoring before a build.
pekit-out/<target>/<function>[.N]/Symbolic links to each target's results.Each build.
pekit-out/.steps/<function>/<identity>/A step's outputs: copies of what targets gave, and read-only links for exposed outputs.Each build.
pekit-out/.fetch/<sha256>/<name>An exposed fetched file.Each build.
pekit-out/.unpack/<key>/An exposed unpacked archive.Each build.
pekit-out/.git/<key>/<name>/An exposed git commit's files.Each build.
pekit-out/.pekit-copiesWhat each copy a build made holds, and its files' stamps as made, so a later build leaves an unchanged copy.Each build that copies.

A.2 In the cache directory #

PathHolds
CACHE/git/Bare clones of the repositories libraries are pinned from.
CACHE/scratch/step-<token>-<node>-<attempt>/A step attempt's staging directory: w/, out/, and tmp/.
CACHE/scratch/swept-<token>/Staging directories renamed for the sweeper to remove.
CACHE/scratch/kept-<token>-<node>/An empty scratch directory for one run of a step marked #[scratch].
CACHE/scratch/unpack-<token>-<n>/An archive being unpacked.
CACHE/scratch/git-<token>-<n>/A git commit being checked out.
CACHE/store/The store, below.

A.3 In the store #

PathHolds
lockThe store's lock, held shared by every process with the store open.
cas/<xx>/<digest>A blob, read-only.
cas/<xx>/<digest>.xThe executable copy of a blob.
cas/<xx>/<digest>.rN, <digest>.x.rNNumbered copies of a blob.
records/<xx>/<key>A record, as JSON: a step's, a program's, a manifest, a fetch's, an unpacking's, or a git commit's.
trees/<digest>, trees/<digest>-<bases>A materialized tree's instance.
complete/<digest>A mark that a tree has everything it names.
seen/<digest>.stampsThe stamps of a workspace's files, by a digest of its root's path, in a binary form.
seen/<digest>-libraries.stampsThe stamps of the files of a workspace's locked libraries.
seen/<digest>.rootThe path of the workspace whose stamps these are.
seen/<digest>.outputsThe path of that workspace's output directory.
git/Bare clones of the repositories fetch_git fetched from, each with a .lock beside it that a fetch into it holds.
scratch/<digest>A step's scratch directory, with <digest>.lock, <digest>.size, and <digest>.dirty while a run has it.
claims/<base>The lock file of the claim on a step, by its base receipt.
usage/A journal of what each build used.
eviction.jsonEach record's eviction priority, and what was evicted.
using/<pid>-<token>What each process that has the store open uses of it, published, held locked by the process, and removed as it exits.
evictingThe lock of an eviction beside other processes.
tmp/evicting-<token>/What such an eviction has moved aside, until it puts back or deletes it.
orphanedWhat output directories held of evicted steps when an eviction last looked: bytes, exposures, and when.
size, size.lockThe ledger of the blobs' size, and its lock.
tmp/Files and directories being written, each named with a process's token.

A.4 In the state directory #

PathHolds
STATE/keychain-keyThe machine's 32-byte key that secrets' identities are hashed with, mode 0600.
STATE/peaks/<digest>, STATE/peaks/kind-<digest>The last peaks of a step's program, and of its kind's.

A.5 The machine's budget #

PathHolds
CONFIG/machine.confThe budget's limits, jobs, memory, and unseen, and the machine's cache_limit and evaluating. Written by the user.
BUDGET/job-<n>, BUDGET/memory-<n>The lock files of the budget's jobs and units of memory.
BUDGET/waiting, BUDGET/gateThe lock files a waiting program holds.
BUDGET/fifo-<pid>-<n>A running program's jobserver.

The Machine's Budget says what each is.

A.6 In a step's sandbox #

Paths in a Step lists the paths a step sees.

Checking Pekit

Pekit / Developing Pekit

tools/check is the check a change to pekit must pass. It checks style, runs Clippy with every warning denied, and runs every test of the workspace and of the modsig library's tool:

tools/check

Some tests take several minutes, such as the one that boots an ISO, and are ignored unless asked for. tools/check --all runs them too.

The style check uses pinned PSC tools. Prepare them once, outside the repository, and point the check at them:

python3 tools/prepare-style-tools.py ~/.cache/peios/pekit-style
export PEIOS_STYLE_BIN=~/.cache/peios/pekit-style/bin

What the tests need #

Many tests build something real, and need what that build needs on the machine. They read every file they would fetch from disk, so that no test downloads anything.

  • Host tools. A static busybox at /usr/bin/busybox, git, cc, ppk on PATH, and /dev/kvm. The ISO test also needs QEMU, OVMF, xorriso, mkfs.vfat and mtools.
  • Room for temporary files. The examples unpack toolchains into temporary directories, several gigabytes at once. If /tmp is a small or shared memory-backed filesystem, set TMPDIR to a directory on disk.
  • A user who can't read every file. One test checks what happens when a file can't be read, which it can't arrange as root.
  • The Peios workspace. The examples take the gcslib libraries from their clones in gcslib/, the files their builds fetch from local/pekit2-data/, and the sources of ppk, peiso, peiosutils and prelude from the repositories of those names. Each is found in the directory pekit's repository is in.

Skipped is not passed #

Cargo can't mark a test as skipped once it has started, so a test that finds something missing returns early, and Cargo reports it as passed. To keep that from passing unnoticed, such a test writes a line that Cargo shows even for a passing test:

SKIPPED, NOT PASSED: example_4_builds_zlib_with_its_own_build_system_and_the_host_s_tools: zlib's source is not on this machine; set $PEKIT_TEST_NO_SKIP to fail instead

With PEKIT_TEST_NO_SKIP set to any value, the same test fails instead, naming what is missing. tools/check sets it, so a passing check means that every test it runs ran. A plain cargo test doesn't, so it can still skip, and says so.

Check from a worktree #

A worktree outside the Peios workspace has no gcslib, ppk or local beside it. Point the tests at the workspace with PEKIT_TEST_WORKSPACE:

PEKIT_TEST_WORKSPACE=~/projects/peios tools/check

Two variables override a single location within it:

VariableDefault
PEKIT_TEST_GCSLIBgcslib in the workspace
PEKIT_TEST_DOWNLOADSlocal/pekit2-data in the workspace

Check the documentation #

tools/check-docs lints this documentation, builds it with Trail, and checks the man pages:

tools/check-docs

Links to another product resolve only in the combined Learn site, so build that as well when a change adds one.

Peios Learn — documentation for Peios software.

Built with Trail.