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

Building

Single-page view · as markdown

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.

Peios Learn — documentation for Peios software.

Built with Trail.